工具
Code Execution Tool
Code execution tool 使 Grok 能够实时编写并执行 Python 代码,显著扩展文本生成之外的能力。借助该功能,Grok 可以进行精确计算、复杂数据分析、统计计算,并解决仅通过文本无法处理的数学问题。
主要能力
数学计算:求解复杂方程、执行统计分析并精确处理数值计算
数据分析:处理 dataset,并从 prompt 中提取洞察
金融建模:构建金融 model、计算风险指标并执行量化分析
科学计算:处理科学计算、simulation 和数据转换
代码生成与测试:实时编写、测试和调试 Python code snippet
何时使用 Code Execution
Code execution tool 特别适用于:
数值问题:需要精确计算而非近似值时
数据处理:分析 prompt 中的复杂数据
复杂逻辑:需要中间结果的多步计算
验证:复核数学结果或验证假设
SDK 支持
Code execution tool 可通过多个 SDK 和 API 使用,其命名约定有所不同:
| SDK/API | Tool 名称 | 说明 |
|---|---|---|
| xAI SDK | code_execution | xAI SDK native implementation |
| OpenAI Responses API | code_interpreter | 兼容 OpenAI API 格式 |
| Vercel AI SDK | xai.tools.codeExecution() | Vercel AI SDK 集成 |
所有与 Responses API 兼容的 SDK 也支持该 tool。
实现示例
以下完整示例展示如何在不同平台和使用场景中集成 code execution tool。
基础计算
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)数据分析
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)最佳实践
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.5等 reasoning model,以获得更好的代码生成效果
常见使用场景
金融分析
# 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"限制与注意事项
执行环境:代码在预装常用 library 的 sandboxed Python environment 中运行
时间限制:复杂计算可能受执行时间限制
内存使用:大型 dataset 可能达到内存限制
Package 可用性:支持大多数主流 Python package(NumPy、Pandas、Matplotlib、SciPy)
File I/O:出于安全原因,file system 访问受限
安全说明
代码在安全、隔离的环境中执行
无法访问外部网络或 file system
临时 execution context,不会在请求之间持久保存
所有计算均为 stateless 且安全