工具
代码执行工具
代码执行工具使 Grok 能够实时编写和执行 Python 代码,极大地扩展了其超越文本生成的能力。这一强大功能允许 Grok 执行精确计算、复杂数据分析、统计计算以及解决仅通过文本无法解决的数学问题。
主要功能
- 数学计算:精确解决复杂方程式、执行统计分析并处理数值计算
- 数据分析:处理数据集,从提示中提取洞察
- 金融建模:构建金融模型、计算风险指标并执行量化分析
- 科学计算:处理科学计算、模拟和数据转换
- 代码生成与测试:实时编写、测试和调试 Python 代码片段
何时使用代码执行
代码执行工具在以下场景中特别有价值:
- 数值问题:当您需要精确计算而非近似值时
- 数据处理:分析来自提示的复杂数据
- 复杂逻辑:需要中间结果的多步计算
- 验证:双重检查数学结果或验证假设
SDK 支持
代码执行工具在多个 SDK 和 API 中可用,但命名约定不同:
| SDK/API | 工具名称 | 描述 |
|---|---|---|
| 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。
实现示例
以下是全面的示例,展示如何在不同平台和用例中集成代码执行工具。
基础计算
python
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.5", # reasoning model
tools=[code_execution()],
include=["verbose_streaming"],
)
# Ask for a mathematical calculation
chat.append(user("Calculate the compound interest for $10,000 at 5% annually for 10 years"))
is_thinking = True
for response, chunk in chat.stream():
# View the server-side tool calls as they are being made in real-time
for tool_call in chunk.tool_calls:
print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")
if response.usage.reasoning_tokens and is_thinking:
print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)
if chunk.content and is_thinking:
print("\\n\\nFinal Response:")
is_thinking = False
if chunk.content and not is_thinking:
print(chunk.content, end="", flush=True)
print("\\n\\nCitations:")
print(response.citations)
print("\\n\\nUsage:")
print(response.usage)
print(response.server_side_tool_usage)
print("\\n\\nServer Side Tool Calls:")
print(response.tool_calls)python
import os
from openai import OpenAI
api_key = os.getenv("XAI_API_KEY")
client = OpenAI(
api_key=api_key,
base_url="https://api.x.ai/v1",
)
response = client.responses.create(
model="grok-4.5",
input=[
{
"role": "user",
"content": "Calculate the compound interest for $10,000 at 5% annually for 10 years",
},
],
tools=[
{
"type": "code_interpreter",
},
],
)
print(response)python
import os
import requests
url = "https://api.x.ai/v1/responses"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"
}
payload = {
"model": "grok-4.5",
"input": [
{
"role": "user",
"content": "Calculate the compound interest for $10,000 at 5% annually for 10 years"
}
],
"tools": [
{
"type": "code_interpreter",
}
]
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())bash
curl https://api.x.ai/v1/responses \\
-H "Content-Type: application/json" \\
-H "Authorization: Bearer $XAI_API_KEY" \\
-d '{
"model": "grok-4.5",
"input": [
{
"role": "user",
"content": "Calculate the compound interest for $10,000 at 5% annually for 10 years"
}
],
"tools": [
{
"type": "code_interpreter"
}
]
}'javascript
import { xai } from '@ai-sdk/xai';
import { generateText } from 'ai';
const { text } = await generateText({
model: xai.responses('grok-4.5'),
prompt: 'Calculate the compound interest for $10,000 at 5% annually for 10 years',
tools: {
code_execution: xai.tools.codeExecution(),
},
});
console.log(text);数据分析
python
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"))
# Multi-turn conversation with data analysis
chat = client.chat.create(
model="grok-4.5", # reasoning model
tools=[code_execution()],
include=["verbose_streaming"],
)
# Step 1: Load and analyze data
chat.append(user("""
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
"""))
print("##### Step 1: Data Analysis #####\\n")
is_thinking = True
for response, chunk in chat.stream():
# View the server-side tool calls as they are being made in real-time
for tool_call in chunk.tool_calls:
print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")
if response.usage.reasoning_tokens and is_thinking:
print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)
if chunk.content and is_thinking:
print("\\n\\nAnalysis Results:")
is_thinking = False
if chunk.content and not is_thinking:
print(chunk.content, end="", flush=True)
print("\\n\\nCitations:")
print(response.citations)
print("\\n\\nUsage:")
print(response.usage)
print(response.server_side_tool_usage)
chat.append(response)
# Step 2: Follow-up analysis
chat.append(user("Now predict Q1 next year using linear regression"))
print("\\n\\n##### Step 2: Prediction Analysis #####\\n")
is_thinking = True
for response, chunk in chat.stream():
# View the server-side tool calls as they are being made in real-time
for tool_call in chunk.tool_calls:
print(f"\\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}")
if response.usage.reasoning_tokens and is_thinking:
print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)
if chunk.content and is_thinking:
print("\\n\\nPrediction Results:")
is_thinking = False
if chunk.content and not is_thinking:
print(chunk.content, end="", flush=True)
print("\\n\\nCitations:")
print(response.citations)
print("\\n\\nUsage:")
print(response.usage)
print(response.server_side_tool_usage)
print("\\n\\nServer Side Tool Calls:")
print(response.tool_calls)javascript
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.5'),
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.5'),
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. 请求要具体
提供清晰、详细的指令,说明您希望代码完成什么任务:
python
# Good: Specific and clear
"Calculate the correlation matrix for these variables and highlight correlations above 0.7"
# Avoid: Vague requests
"Analyze this data"2. 提供上下文和数据格式
始终指定数据格式和任何数据约束,并提供尽可能多的上下文:
python
# 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. 使用适当的模型设置
- Temperature:对于数学计算,使用较低值(0.0-0.3)
- Model:使用推理模型如
grok-4.5以获得更好的代码生成效果
常见用例
金融分析
python
# 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"统计分析
python
# 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]"科学计算
python
# Simulations, numerical methods, equation solving
"Solve this differential equation using numerical methods: dy/dx = x^2 + y, with initial condition y(0) = 1"限制与注意事项
- 执行环境:代码在沙盒 Python 环境中运行,预装了常用库
- 时间限制:复杂计算可能有执行时间限制
- 内存使用:大数据集可能会遇到内存限制
- 包可用性:大多数流行的 Python 包(NumPy、Pandas、Matplotlib、SciPy)都可用
- 文件 I/O:出于安全原因,文件系统访问有限
安全说明
- 代码执行在安全、隔离的环境中发生
- 无外部网络或文件系统访问权限
- 临时执行上下文,不会在请求之间持久化
- 所有计算都是无状态且安全的