SPB Git

Repository Public

code-execution.md 10.7 KB 355 lines markdown

1<!-- source: https://docs.x.ai/developers/tools/code-execution (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Tools34# Code Execution Tool56The code execution tool enables Grok to write and execute Python code in real-time, dramatically expanding its capabilities beyond text generation. This powerful feature allows Grok to perform precise calculations, complex data analysis, statistical computations, and solve mathematical problems that would be impossible through text alone.78## Key Capabilities910* **Mathematical Computations**: Solve complex equations, perform statistical analysis, and handle numerical calculations with precision11* **Data Analysis**: Process datasets, and extract insights from the prompt12* **Financial Modeling**: Build financial models, calculate risk metrics, and perform quantitative analysis13* **Scientific Computing**: Handle scientific calculations, simulations, and data transformations14* **Code Generation & Testing**: Write, test, and debug Python code snippets in real-time1516## When to Use Code Execution1718The code execution tool is particularly valuable for:1920* **Numerical Problems**: When you need exact calculations rather than approximations21* **Data Processing**: Analyzing complex data from the prompt22* **Complex Logic**: Multi-step calculations that require intermediate results23* **Verification**: Double-checking mathematical results or validating assumptions2425## SDK Support2627The code execution tool is available across multiple SDKs and APIs with different naming conventions:2829| SDK/API | Tool Name | Description |30|---------|-----------|-------------|31| xAI SDK | `code_execution` | Native xAI SDK implementation |32| OpenAI Responses API | `code_interpreter` | Compatible with OpenAI's API format |33| Vercel AI SDK | `xai.tools.codeExecution()` | Vercel AI SDK integration |3435This tool is also supported in all Responses API compatible SDKs.3637## Implementation Example3839Below are comprehensive examples showing how to integrate the code execution tool across different platforms and use cases.4041### Basic Calculations4243```pythonXAI44import os4546from xai_sdk import Client47from xai_sdk.chat import user48from xai_sdk.tools import code_execution4950client = Client(api_key=os.getenv("XAI_API_KEY"))51chat = client.chat.create(52    model="grok-4.6",  # reasoning model53    tools=[code_execution()],54    include=["verbose_streaming"],55)5657# Ask for a mathematical calculation58chat.append(user("Calculate the compound interest for $10,000 at 5% annually for 10 years"))5960is_thinking = True61for response, chunk in chat.stream():62    # View the server-side tool calls as they are being made in real-time63    for tool_call in chunk.tool_calls:64        print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")65    if response.usage.reasoning_tokens and is_thinking:66        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)67    if chunk.content and is_thinking:68        print("\\n\\nFinal Response:")69        is_thinking = False70    if chunk.content and not is_thinking:71        print(chunk.content, end="", flush=True)7273print("\\n\\nCitations:")74print(response.citations)75print("\\n\\nUsage:")76print(response.usage)77print(response.server_side_tool_usage)78print("\\n\\nServer Side Tool Calls:")79print(response.tool_calls)80```8182```pythonOpenAISDK83import os84from openai import OpenAI8586api_key = os.getenv("XAI_API_KEY")87client = OpenAI(88    api_key=api_key,89    base_url="https://api.x.ai/v1",90)9192response = client.responses.create(93    model="grok-4.6",94    input=[95        {96            "role": "user",97            "content": "Calculate the compound interest for $10,000 at 5% annually for 10 years",98        },99    ],100    tools=[101        {102            "type": "code_interpreter",103        },104    ],105)106107print(response)108```109110```pythonRequests111import os112import requests113114url = "https://api.x.ai/v1/responses"115headers = {116    "Content-Type": "application/json",117    "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"118}119payload = {120    "model": "grok-4.6",121    "input": [122        {123            "role": "user",124            "content": "Calculate the compound interest for $10,000 at 5% annually for 10 years"125        }126    ],127    "tools": [128        {129            "type": "code_interpreter",130        }131    ]132}133response = requests.post(url, headers=headers, json=payload)134print(response.json())135```136137```bash138curl https://api.x.ai/v1/responses \\139  -H "Content-Type: application/json" \\140  -H "Authorization: Bearer $XAI_API_KEY" \\141  -d '{142  "model": "grok-4.6",143  "input": [144    {145      "role": "user",146      "content": "Calculate the compound interest for $10,000 at 5% annually for 10 years"147    }148  ],149  "tools": [150    {151      "type": "code_interpreter"152    }153  ]154}'155```156157```javascriptAISDK158import { xai } from '@ai-sdk/xai';159import { generateText } from 'ai';160161const { text } = await generateText({162  model: xai.responses('grok-4.6'),163  prompt: 'Calculate the compound interest for $10,000 at 5% annually for 10 years',164  tools: {165    code_execution: xai.tools.codeExecution(),166  },167});168169console.log(text);170```171172### Data Analysis173174```pythonXAI175import os176from xai_sdk import Client177from xai_sdk.chat import user178from xai_sdk.tools import code_execution179180client = Client(api_key=os.getenv("XAI_API_KEY"))181182# Multi-turn conversation with data analysis183chat = client.chat.create(184    model="grok-4.6",  # reasoning model185    tools=[code_execution()],186    include=["verbose_streaming"],187)188189# Step 1: Load and analyze data190chat.append(user("""191I have sales data for Q1-Q4: [120000, 135000, 98000, 156000].192Please analyze this data and create a visualization showing:1931. Quarterly trends1942. Growth rates1953. Statistical summary196"""))197198print("##### Step 1: Data Analysis #####\\n")199200is_thinking = True201for response, chunk in chat.stream():202    # View the server-side tool calls as they are being made in real-time203    for tool_call in chunk.tool_calls:204        print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")205    if response.usage.reasoning_tokens and is_thinking:206        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)207    if chunk.content and is_thinking:208        print("\\n\\nAnalysis Results:")209        is_thinking = False210    if chunk.content and not is_thinking:211        print(chunk.content, end="", flush=True)212213print("\\n\\nCitations:")214print(response.citations)215print("\\n\\nUsage:")216print(response.usage)217print(response.server_side_tool_usage)218219chat.append(response)220221# Step 2: Follow-up analysis222chat.append(user("Now predict Q1 next year using linear regression"))223224print("\\n\\n##### Step 2: Prediction Analysis #####\\n")225226is_thinking = True227for response, chunk in chat.stream():228    # View the server-side tool calls as they are being made in real-time229    for tool_call in chunk.tool_calls:230        print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")231    if response.usage.reasoning_tokens and is_thinking:232        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)233    if chunk.content and is_thinking:234        print("\\n\\nPrediction Results:")235        is_thinking = False236    if chunk.content and not is_thinking:237        print(chunk.content, end="", flush=True)238239print("\\n\\nCitations:")240print(response.citations)241print("\\n\\nUsage:")242print(response.usage)243print(response.server_side_tool_usage)244print("\\n\\nServer Side Tool Calls:")245print(response.tool_calls)246```247248```javascriptAISDK249import { xai } from '@ai-sdk/xai';250import { generateText } from 'ai';251252// Step 1: Load and analyze data253const step1 = await generateText({254  model: xai.responses('grok-4.6'),255  prompt: \`I have sales data for Q1-Q4: [120000, 135000, 98000, 156000].256Please analyze this data and create a visualization showing:2571. Quarterly trends2582. Growth rates2593. Statistical summary\`,260  tools: {261    code_execution: xai.tools.codeExecution(),262  },263});264265console.log('##### Step 1: Data Analysis #####');266console.log(step1.text);267268// Step 2: Follow-up analysis using previousResponseId269const step2 = await generateText({270  model: xai.responses('grok-4.6'),271  prompt: 'Now predict Q1 next year using linear regression',272  tools: {273    code_execution: xai.tools.codeExecution(),274  },275  providerOptions: {276    xai: {277      previousResponseId: step1.response.id,278    },279  },280});281282console.log('##### Step 2: Prediction Analysis #####');283console.log(step2.text);284```285286## Best Practices287288### 1. **Be Specific in Requests**289290Provide clear, detailed instructions about what you want the code to accomplish:291292```pythonWithoutSDK293# Good: Specific and clear294"Calculate the correlation matrix for these variables and highlight correlations above 0.7"295296# Avoid: Vague requests  297"Analyze this data"298```299300### 2. **Provide Context and Data Format**301302Always specify the data format and any constraints on the data, and provide as much context as possible:303304```pythonWithoutSDK305# Good: Includes data format and requirements306"""307Here's my CSV data with columns: date, revenue, costs308Please calculate monthly profit margins and identify the best-performing month.309Data: [['2024-01', 50000, 35000], ['2024-02', 55000, 38000], ...]310"""311```312313### 3. **Use Appropriate Model Settings**314315* **Temperature**: Use lower values (0.0-0.3) for mathematical calculations316* **Model**: Use reasoning models like `grok-4.6` for better code generation317318## Common Use Cases319320### Financial Analysis321322```pythonWithoutSDK323# Portfolio optimization, risk calculations, option pricing324"Calculate the Sharpe ratio for a portfolio with returns [0.12, 0.08, -0.03, 0.15] and risk-free rate 0.02"325```326327### Statistical Analysis328329```pythonWithoutSDK330# Hypothesis testing, regression analysis, probability distributions331"Perform a t-test to compare these two groups and interpret the p-value: Group A: [23, 25, 28, 30], Group B: [20, 22, 24, 26]"332```333334### Scientific Computing335336```pythonWithoutSDK337# Simulations, numerical methods, equation solving338"Solve this differential equation using numerical methods: dy/dx = x^2 + y, with initial condition y(0) = 1"339```340341## Limitations and Considerations342343* **Execution Environment**: Code runs in a sandboxed Python environment with common libraries pre-installed344* **Time Limits**: Complex computations may have execution time constraints345* **Memory Usage**: Large datasets might hit memory limitations346* **Package Availability**: Most popular Python packages (NumPy, Pandas, Matplotlib, SciPy) are available347* **File I/O**: Limited file system access for security reasons348349## Security Notes350351* Code execution happens in a secure, isolated environment352* No access to external networks or file systems353* Temporary execution context that doesn't persist between requests354* All computations are stateless and secure355
Files main
Menu

Theme