工具
代码执行工具
Code Execution 工具让 Grok 能够实时编写和执行 Python 代码,显著扩展其文本生成之外的能力。借助该功能,Grok 可进行精确计算、复杂数据分析和统计计算,并解决仅靠文本无法处理的数学问题。
主要能力
数学计算:求解复杂方程、执行统计分析并精确处理数值计算
数据分析:处理数据集,并从提示中提取洞察
金融建模:构建金融模型、计算风险指标并执行量化分析
科学计算:处理科学计算、模拟和数据转换
代码生成与测试:实时编写、测试和调试 Python 代码片段
何时使用代码执行
代码执行工具特别适用于:
数值问题:需要精确计算而非近似值时
数据处理:分析 prompt 中的复杂数据
复杂逻辑:需要中间结果的多步计算
验证:复核数学结果或验证假设
SDK 支持
Code execution tool 可通过多个 SDK 和 API 使用,其命名约定有所不同:
| SDK/API | Tool 名称 | 说明 |
|---|---|---|
| xAI SDK | code_execution | 原生 xAI SDK 实现 |
| OpenAI Responses API | code_interpreter | 兼容 OpenAI API 格式 |
| Vercel AI SDK | xai.tools.codeExecution() | Vercel AI SDK 集成 |
所有与 Responses API 兼容的 SDK 也支持该工具。
实现示例
以下完整示例展示如何在不同平台和使用场景中集成代码执行工具。
基础计算
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);数据分析
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);最佳实践
1. 在请求中明确说明
清晰、详细地说明希望代码完成的操作:
# Good: Specific and clear
"Calculate the correlation matrix for these variables and highlight correlations above 0.7"
# Avoid: Vague requests
"Analyze this data"2. 提供 Context 和数据格式
始终指定数据格式和所有数据约束,并尽可能提供充分的 context:
# 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. 使用合适的 Model 设置
Temperature:数学计算请使用较低值(0.0-0.3)
Model:使用
grok-4.7等推理模型,以获得更好的代码生成效果
常见使用场景
金融分析
# 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"统计分析
# 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]"科学计算
# Simulations, numerical methods, equation solving
"Solve this differential equation using numerical methods: dy/dx = x^2 + y, with initial condition y(0) = 1"限制与注意事项
执行环境:代码在预装常用库的沙箱 Python 环境中运行
时间限制:复杂计算可能受执行时间限制
内存使用:大型 dataset 可能达到内存限制
Package 可用性:支持大多数主流 Python package(NumPy、Pandas、Matplotlib、SciPy)
File I/O:出于安全原因,file system 访问受限
安全说明
代码在安全、隔离的环境中执行
无法访问外部网络或文件系统
临时 execution context,不会在请求之间持久保存
所有计算均为 stateless 且安全
最后更新:2026 年 2 月 5 日