Enable Code Execution in the API
On this page
Run Python code via the Grok API
Code Execution lets the model write and run Python code in real time within a secure sandboxed environment. Instead of simply generating code for you to run yourself, the model executes the code directly and returns the results. It’s a powerful tool for calculations, data analysis, and code validation.
Tool identifiers by SDK
The tool identifier varies depending on the SDK you use:
| SDK | Identifier |
|---|---|
| xAI SDK | code_execution |
| OpenAI Responses API | code_interpreter |
| Vercel AI SDK | xai.tools.codeExecution() |
This naming difference matters. Use the identifier that matches your SDK to avoid errors.
Basic activation
cURL / Direct JSON
{
"model": "grok-4.20-0309-reasoning",
"input": "Calculate the sum of the first 1,000 prime numbers",
"tools": [
{"type": "code_interpreter"}
]
}
xAI SDK (Python)
response = client.responses.create(
model="grok-4.20-0309-reasoning",
input="Calculate the sum of the first 1,000 prime numbers",
tools=[client.tools.code_execution()]
)
print(response.output_text)
OpenAI SDK (Python)
response = client.responses.create(
model="grok-4.20-0309-reasoning",
input="Calculate the sum of the first 1,000 prime numbers",
tools=[{"type": "code_interpreter"}]
)
Vercel AI SDK (JavaScript)
const response = await generateText({
model: xai("grok-4.20-0309-reasoning"),
prompt: "Calculate the sum of the first 1,000 prime numbers",
tools: [xai.tools.codeExecution()]
});
How the model uses Code Execution
When Code Execution is enabled, the process works as follows:
- The model analyzes the request and determines that a calculation or data analysis is needed
- It writes Python code suited to the problem
- The code runs in xAI’s Python sandbox
- The model receives the execution results (standard output, any errors)
- It formulates its response incorporating the results
If the code produces an error, the model can automatically correct and re-execute it—which may generate multiple invocations for a single request.
Temperature recommendation
For mathematical calculations and data analysis, xAI recommends using low temperature values (0.0 to 0.3). A low temperature reduces variability in code generation and produces more reproducible results.
response = client.responses.create(
model="grok-4.20-0309-reasoning",
input="Calculate the Sharpe ratio for this portfolio...",
tools=[client.tools.code_execution()],
temperature=0.1
)
Key takeaways
- Code Execution enables real-time Python execution in a secure sandbox
- The identifier varies by SDK:
code_execution(xAI),code_interpreter(OpenAI) - The model writes, executes, and interprets the code automatically
- Use
grok-4.20-0309-reasoningand a low temperature for calculations - The cost is $0.005 per execution, with multiple invocations possible