Tools
Code Execution Tool
The 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.
Key Capabilities
Mathematical Computations: Solve complex equations, perform statistical analysis, and handle numerical calculations with precision
Data Analysis: Process datasets, and extract insights from the prompt
Financial Modeling: Build financial models, calculate risk metrics, and perform quantitative analysis
Scientific Computing: Handle scientific calculations, simulations, and data transformations
Code Generation & Testing: Write, test, and debug Python code snippets in real-time
When to Use Code Execution
The code execution tool is particularly valuable for:
Numerical Problems: When you need exact calculations rather than approximations
Data Processing: Analyzing complex data from the prompt
Complex Logic: Multi-step calculations that require intermediate results
Verification: Double-checking mathematical results or validating assumptions
SDK Support
The code execution tool is available across multiple SDKs and APIs with different naming conventions:
| SDK/API | Tool Name | Description |
|---|---|---|
| xAI SDK | code_execution | Native xAI SDK implementation |
| OpenAI Responses API | code_interpreter | Compatible with OpenAI's API format |
| Vercel AI SDK | xai.tools.codeExecution() | Vercel AI SDK integration |
This tool is also supported in all Responses API compatible SDKs.
Implementation Example
Below are comprehensive examples showing how to integrate the code execution tool across different platforms and use cases.
Basic Calculations
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text } = await generateText({
model: xai.responses('grok-4.7'),
prompt: 'Calculate the compound interest for $10,000 at 5% annually for 10 years',
tools: {
code_execution: xai.tools.codeExecution(),
},
});
console.log(text);Data Analysis
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
// Step 1: Load and analyze data
const step1 = await generateText({
model: xai.responses('grok-4.7'),
prompt: \`I have sales data for Q1-Q4: [120000, 135000, 98000, 156000].
Please analyze this data and create a visualization showing:
1. Quarterly trends
2. Growth rates
3. Statistical summary\`,
tools: {
code_execution: xai.tools.codeExecution(),
},
});
console.log('##### Step 1: Data Analysis #####');
console.log(step1.text);
// Step 2: Follow-up analysis using previousResponseId
const step2 = await generateText({
model: xai.responses('grok-4.7'),
prompt: 'Now predict Q1 next year using linear regression',
tools: {
code_execution: xai.tools.codeExecution(),
},
providerOptions: {
xai: {
previousResponseId: step1.response.id,
},
},
});
console.log('##### Step 2: Prediction Analysis #####');
console.log(step2.text);Best Practices
1. Be Specific in Requests
Provide clear, detailed instructions about what you want the code to accomplish:
# Good: Specific and clear
"Calculate the correlation matrix for these variables and highlight correlations above 0.7"
# Avoid: Vague requests
"Analyze this data"2. Provide Context and Data Format
Always specify the data format and any constraints on the data, and provide as much context as possible:
# Good: Includes data format and requirements
"""
Here's my CSV data with columns: date, revenue, costs
Please calculate monthly profit margins and identify the best-performing month.
Data: [['2024-01', 50000, 35000], ['2024-02', 55000, 38000], ...]
"""3. Use Appropriate Model Settings
Temperature: Use lower values (0.0-0.3) for mathematical calculations
Model: Use reasoning models like
grok-4.7for better code generation
Common Use Cases
Financial Analysis
# Portfolio optimization, risk calculations, option pricing
"Calculate the Sharpe ratio for a portfolio with returns [0.12, 0.08, -0.03, 0.15] and risk-free rate 0.02"Statistical Analysis
# Hypothesis testing, regression analysis, probability distributions
"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]"Scientific Computing
# Simulations, numerical methods, equation solving
"Solve this differential equation using numerical methods: dy/dx = x^2 + y, with initial condition y(0) = 1"Limitations and Considerations
Execution Environment: Code runs in a sandboxed Python environment with common libraries pre-installed
Time Limits: Complex computations may have execution time constraints
Memory Usage: Large datasets might hit memory limitations
Package Availability: Most popular Python packages (NumPy, Pandas, Matplotlib, SciPy) are available
File I/O: Limited file system access for security reasons
Security Notes
Code execution happens in a secure, isolated environment
No access to external networks or file systems
Temporary execution context that doesn't persist between requests
All computations are stateless and secure
Last updated:February 5, 2026