
Combine web search and code execution on the Grok API
Combine web search and code execution on the Grok API
Put both tools in the same tools array. The model gathers live data with web search, then runs Python via code execution for averages, charts, and other analysis. Official guide: Advanced Usage → Tool Combinations.
| Goal | Tools |
|---|---|
| Research and analyze data | Web Search + Code Execution |
| News plus social | Web Search + X Search |
| Multi-source insights | Web Search + X Search + Code Execution |
Advanced multi-tool patterns need the xAI SDK or OpenAI-compatible Responses API. The Vercel AI SDK does not support these patterns yet.
xAI SDK
import os
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import web_search, code_execution
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
model="grok-4.6",
tools=[
web_search(),
code_execution(),
],
include=["verbose_streaming"],
)
chat.append(
user(
"What is the average market cap of the companies with the "
"top 5 market cap in the US stock market today?"
)
)
for response, chunk in chat.stream():
if chunk.content:
print(chunk.content, end="", flush=True)
print(response.server_side_tool_usage)
print(response.citations)
Responses API
In Responses API payloads, code execution is "type": "code_interpreter" and web search is "type": "web_search".
curl https://api.x.ai/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $XAI_API_KEY" \
-d '{
"model": "grok-4.6",
"input": [
{
"role": "user",
"content": "What is the average market cap of the companies with the top 5 market cap in the US stock market today?"
}
],
"tools": [
{"type": "web_search"},
{"type": "code_interpreter"}
]
}'
xAI runs both server-side tools. You do not execute them locally. For custom functions mixed with these tools, see Mix client and server-side tools.
Pitfalls
- Use a reasoning model that supports agentic tools (docs examples use
grok-4.6). - Naming differs by surface: xAI SDK
code_execution()vs Responses"code_interpreter". - Each server-side tool call bills under its own usage category — check
server_side_tool_usageon the response.