
Run code execution on the Grok API
Run code execution on the Grok API
The code execution tool lets Grok write and run Python in a sandbox for exact math, stats, and data work. xAI SDK name: code_execution. Responses / OpenAI-compatible name: code_interpreter. Vercel AI SDK: xai.tools.codeExecution(). The sandbox includes common libraries (NumPy, Pandas, Matplotlib, SciPy), has time and memory limits, and has no external network or durable filesystem between requests.
Enable the tool
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": "Calculate the compound interest for $10,000 at 5% annually for 10 years"}
],
"tools": [{"type": "code_interpreter"}]
}'
import os
from xai_sdk import Client
from xai_sdk.chat import user
from xai_sdk.tools import code_execution
client = Client(api_key=os.getenv("XAI_API_KEY"))
chat = client.chat.create(
model="grok-4.6",
tools=[code_execution()],
include=["verbose_streaming"],
)
chat.append(user("Calculate the compound interest for $10,000 at 5% annually for 10 years"))
for response, chunk in chat.stream():
for tool_call in chunk.tool_calls:
print(f"Calling {tool_call.function.name}: {tool_call.function.arguments}")
if chunk.content:
print(chunk.content, end="")
Analyze an attached file
Attach a CSV (or other data file) with input_file / file_url and keep code_interpreter in tools. The model loads the file, runs analysis code in the sandbox, and returns the numbers. See Chat with files on the Grok API.
from xai_sdk.chat import user, file
from xai_sdk.tools import code_execution
chat = client.chat.create(model="grok-4.6", tools=[code_execution()])
chat.append(user(
"Total revenue by product, average units by region, and the top product-region pair.",
file(url="https://docs.x.ai/assets/api-examples/documents/sales-data.csv"),
))
print(chat.sample().content)
When it helps
- Exact numerical results instead of approximate prose
- Multi-step calculations that need intermediate values
- Prompt-supplied datasets you want summarized or plotted in code
- Checking a math result before you trust it
Prefer grok-4.6 for code generation. Keep temperature low (about 0.0–0.3) for arithmetic.
Pitfalls
- Expecting packages outside the sandbox set, or outbound HTTP from the runner.
- Assuming files written in one request still exist on the next request — context is temporary.
- Vague prompts ("analyze this") — name the metrics, formats, and success criteria.