Execute code with the Grok API
Execute code with the Grok API
Pass code_interpreter on POST https://api.x.ai/v1/responses. xAI runs Python in a sandbox and returns the result. You need a key and credits at console.x.ai.
Minimal call
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" }
]
}'
Python with the official SDK uses code_execution():
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()])
chat.append(user("Calculate the compound interest for $10,000 at 5% annually for 10 years"))
for response, chunk in chat.stream():
if chunk.content:
print(chunk.content, end="", flush=True)
print("\nUsage:", response.server_side_tool_usage)
Vercel AI SDK: xai.tools.codeExecution(). OpenAI Responses clients send { "type": "code_interpreter" }.
What the sandbox has
NumPy, Pandas, Matplotlib, and SciPy are available. The run is isolated: no outbound network, limited filesystem, time and memory caps. Each request starts a fresh context.
Keep the ask specific. Give the numbers and the formula you want, then let Grok write and run the Python. Mix it with web_search or file_search on the same request when the numbers live in a page or a collection.
Pitfalls
- xAI SDK name is
code_execution. Responses API type iscode_interpreter. Same tool. - Usage shows up as
SERVER_SIDE_TOOL_CODE_EXECUTION. Output items on Responses API arecode_interpreter_call. - Large datasets and long loops can hit memory or time limits.
- Console API credits are a separate bill from SuperGrok's weekly pool on grok.com.