OpenClaw code_execution 工具完全指南:基于 xAI 沙箱的远程 Python 分析与配置
code_execution 是 OpenClaw 中由内置 xai 插件提供的一项工具能力,它把计算、统计、制表与图表式分析任务委托给 xAI 服务器上的沙箱 Python 环境远程执行,不需要本地 Shell、仓库或配对设备参与。本文以 docs/tools/code-execution.md 为主线,结合 xai 插件源码 与其测试用例,完整讲解该工具的定位、启用配置、使用方式、错误处理与计费注意事项,读完即可在 Gateway 中正确启用并组合使用 x_search、web_search 与 code_execution 完成数据分析链路。
工具定位:远程沙箱分析,而非本地执行
code_execution 运行在 xAI 的 Responses API 上(端点 https://api.x.ai/v1/responses,与 x_search 使用的端点相同),由内置的 xai 插件在 tools 契约下注册。在 extensions/xai/code-execution-tool-shared.ts 中可以看到它的工具定义:
{
label: "Code Execution",
name: "code_execution",
description:
"Run sandboxed Python analysis with xAI. Use for calculations, tabulation, summaries, and chart-style analysis without local machine access.",
parameters: Type.Object({
task: Type.String({
description:
"The full analysis task for xAI's remote Python sandbox. Include any data to analyze directly in the task.",
}),
}),
}
工具只接受一个 task 字符串参数,要求把完整的分析请求和内联数据一次性放入该参数中。
核心特性一览
| Property | Value |
|---|---|
| Tool name | code_execution |
| Provider plugin | xai(内置插件,enabledByDefault: true) |
| Auth | xAI auth profile、XAI_API_KEY 环境变量,或 plugins.entries.xai.config.webSearch.apiKey |
| Default model | grok-4.6 |
| Default timeout | 30 秒 |
Default maxTurns |
未设置(由 xAI 自行应用其内部限制) |
其中默认模型 grok-4.6 在 extensions/xai/model-definitions.ts 中定义:export const XAI_DEFAULT_MODEL_ID = "grok-4.6",且 extensions/xai/openclaw.plugin.json 中声明插件 enabledByDefault: true。已有安装如果省略了工具模型设置,同样使用 Grok 4.6;一旦显式配置了模型,则以显式配置为准。
使用边界:能做什么,不能做什么
按官方文档的明确表述,code_execution 适合:
- 计算(calculations)
- 制表(tabulation)
- 快速统计(quick statistics)
- 图表式分析(chart-style analysis)
- 对
x_search或web_search返回的数据进行二次加工
而它没有以下任何能力:
- 不访问本地文件
- 不接触你的 Shell
- 不读取你的仓库
- 不涉及配对设备
- 调用之间不持久化状态,每次调用都是临时性分析,而非 Notebook 会话
因此需要将每次调用视为"一次性分析"。若要分析新鲜的 X 平台数据,应先运行 x_search 并把结果传入;若需要在本地执行命令,则应改用 exec 工具。这个边界在 docs/providers/xai.md 中同样被强调:"code_execution is remote xAI sandbox execution, not local"。
底层原理:它是如何把请求发给 xAI 的
在 extensions/xai/src/code-execution-shared.ts 中可以看到请求构建的关键逻辑:
const XAI_CODE_EXECUTION_ENDPOINT = XAI_RESPONSES_ENDPOINT; // https://api.x.ai/v1/responses
export async function requestXaiCodeExecution(params: {...}) {
return await requestXaiResponsesTool(
{
...params,
endpoint: XAI_CODE_EXECUTION_ENDPOINT,
inputText: params.task,
tools: [{ type: "code_interpreter" }],
reasoningEffort: resolveXaiToolDefaultReasoningEffort(params.model, "low"),
errorLabel: "xAI code execution failed",
},
...
);
}
即 OpenClaw 以 code_interpreter 工具类型调用 xAI Responses API,并在 extensions/xai/src/responses-tool-shared.ts 中组装请求体:
model:解析后的模型 ID(默认grok-4.6,可被配置覆盖)input:以单条 user 消息发送tasktools: [{ type: "code_interpreter" }]store: false:不存储请求reasoning:当模型为grok-4.3或grok-4.6时默认取effort: "low"(见resolveXaiToolDefaultReasoningEffort,仅这两个模型返回默认值,其他模型不附加该字段)max_turns:仅当配置了正整数maxTurns时才附加
响应解析后,工具返回结构化的结果负载(details),包含以下字段:
task:原始请求任务provider: "xai"model:实际使用的模型tookMs:本次调用的耗时(毫秒)content:合并后的文本答案(多个output_text块按顺序拼接)citations:去重后的引用 URL 列表usedCodeExecution:布尔值,表示输出中是否确实包含code_interpreter_calloutputTypes:响应输出块类型的去重集合
引用的规范化处理
在 extensions/xai/src/responses-tool-shared.ts 中,引用 URL 经过了严格校验:仅接受 http:/https: 协议、长度不超过 2048 字符,最多收集 20 条引用且最多扫描 1000 条注解。无效或不安全的 URL 会被静默丢弃。
测试用例印证
extensions/xai/code-execution.test.ts 对上述行为做了完整验证:
- 请求 URL 包含
api.x.ai/v1/responses,请求体包含model: "grok-4.6"、store: false、reasoning: { effort: "low" }、tools: [{ type: "code_interpreter" }] - 配置
maxTurns: 2时请求体携带max_turns: 2 - 多块输出
"Mean: "+"42"+". Verified."被合并为"Mean: 42. Verified.",引用去重后为["https://example.com/input.csv", "https://example.com/result.csv"] - 自定义模型(如
grok-build-0.1)时请求体不携带reasoning与max_turns - 缺失凭据时返回结构化错误而不是抛出异常
启用与配置
第一步:提供 xAI 凭据
有三种方式,任选其一即可(它们同时也会为 x_search 和 Grok web_search 提供鉴权):
方式一:OAuth 登录。需要符合条件的 SuperGrok 或 X Premium 订阅。采用设备码验证,因此可以在没有 localhost 回调的远程主机上使用:
openclaw models auth login --provider xai --method oauth
新安装时,也可以在引导流程中直接选择同一方案:
openclaw onboard --install-daemon --auth-choice xai-oauth
方式二:API Key:
openclaw models auth login --provider xai --method api-key
export XAI_API_KEY=xai-...
方式三:配置文件:
{
plugins: {
entries: {
xai: {
config: {
webSearch: {
apiKey: "xai-...",
},
},
},
},
},
}
从源码角度看,凭据解析实现在 extensions/xai/src/tool-auth-shared.ts:resolveXaiToolApiKeyWithAuth 按"配置的 API Key(运行时配置 → 源配置)→ xAI auth profile → XAI_API_KEY 环境变量"的优先级顺序解析,其中 XAI_API_KEY 是固定环境变量名(XAI_API_KEY_ENV_VAR = "XAI_API_KEY")。测试 extensions/xai/code-execution.test.ts 验证了从 auth profile 解析出的 Bearer xai-profile-key 以及从 webSearch.apiKey 配置解析出的 Bearer xai-plugin-key 均会正确写入请求头。
第二步:启用并调优 code_execution
enabled 参数的语义需要特别注意:
- 省略
enabled:仅当当前激活模型的 provider 是xai且 xAI 凭据可解析时,code_execution才会暴露; - 激活模型是已知的非 xAI provider:需将
plugins.entries.xai.config.codeExecution.enabled设为true,以显式同意跨 provider 使用; - 激活模型 provider 缺失或无法解析:工具保持隐藏(fail closed);
- 设为
false:对所有 provider 禁用该工具。
无论如何,xAI 凭据都是必需的。这一逻辑在 extensions/xai/src/code-execution-config.ts 与 extensions/xai/src/tool-auth-shared.ts 的 isXaiToolEnabled 中实现:enabled === false 直接返回 false,否则取决于配置的 API Key、auth profile 或环境变量是否存在。
在同一配置块中可以覆盖模型、限制内部工具轮次(cap)与超时:
{
plugins: {
entries: {
xai: {
config: {
codeExecution: {
enabled: true, // 已知的非 xAI 模型 provider 下必须显式开启
model: "grok-4.3", // 覆盖默认的 xAI code-execution 模型
maxTurns: 2, // 可选:限制 xAI 内部工具轮次上限
timeoutSeconds: 30, // 请求超时(默认 30)
},
},
},
},
},
}
各配置项的官方帮助文本同样登记在 extensions/xai/openclaw.plugin.json 的配置项清单中:
| 配置项 | 含义 | 默认值 |
|---|---|---|
codeExecution.enabled |
是否暴露 code_execution |
依 provider 而定(见上文语义) |
codeExecution.model |
执行分析所用 xAI 模型 | grok-4.6 |
codeExecution.maxTurns |
xAI 单次请求可用的内部工具轮次上限 | 未设置 |
codeExecution.timeoutSeconds |
请求超时(秒) | 30 |
从实现看(extensions/xai/code-execution.ts):
model会经过normalizeXaiModelId规范化(extensions/xai/src/tool-config-shared.ts),空字符串等无效值回退到默认模型;maxTurns仅接受正整数(Number.isFinite校验后取整且必须大于 0),非法值按未设置处理;timeoutSeconds必须是有限数字,否则回退到30。
第三步:重启 Gateway
openclaw gateway restart
一旦 xAI 插件重新注册,且上述 provider、enablement、auth 检查全部通过,code_execution 就会出现在 Agent 的工具列表中。
使用方法:把分析意图说清楚
由于工具只接收单个 task 参数,请把完整请求和需要分析的内联数据一次性放进提示词中,让分析意图显式化。官方文档给出的三类典型用法:
Use code_execution to calculate the 7-day moving average for these numbers: ...
Use x_search to find posts mentioning OpenClaw this week, then use code_execution to count them by day.
Use web_search to gather the latest AI benchmark numbers, then use code_execution to compare percent changes.
后两个示例演示了标准的数据获取→分析流水线:先用 x_search 或 web_search 获取数据,再把结果交给 code_execution 做统计与对比。注意 code_execution 本身不联网取数,它只处理你在 task 中给它的数据。
错误处理:结构化 JSON 而非异常
缺少凭据时,工具不会抛出异常,而是返回结构化 JSON 错误,便于 Agent 自行纠错并重试:
{
"error": "missing_xai_api_key",
"message": "code_execution needs xAI credentials. Run `openclaw onboard --auth-choice xai-oauth` to sign in with Grok, run `openclaw onboard --auth-choice xai-api-key`, set `XAI_API_KEY` in the Gateway environment, or configure `plugins.entries.xai.config.webSearch.apiKey`.",
"docs": "docs/tools/code-execution"
}
这段错误负载由 extensions/xai/code-execution-tool-shared.ts 的 buildMissingCodeExecutionApiKeyPayload 构建(原文中 docs 字段指向官方文档站,此处以仓库内对应文档路径表示),并通过 jsonResult 包装返回。
测试同样覆盖了异常路径:在 extensions/xai/code-execution.test.ts 中,"malformed code_execution JSON" 被报告为 provider 错误,而"缺少答案文本"则会被明确归类为服务端问题而非 JSON 解码错误(对应 requireXaiResponseTextAndCitations 中"no answer text returned; try a simpler request"的提示逻辑),这有助于 Agent 采取正确的修复策略而不是盲目重试。
成本与注意事项
使用 code_execution 前务必了解计费:
code_execution运行在 xAI 服务器上。xAI 按每 1,000 次工具调用收取 $5,外加模型的输入与输出 token 费用。
也就是说,每次调用除了 $5/1,000 次的工具使用费,还会产生模型 token 消耗,成本受所选模型(默认 grok-4.6)与任务复杂度的直接影响。由于工具无状态且每次调用独立计费,建议在提示词中一次性给出完整数据与任务,避免多次往返。
此外注意响应内容存在长度保护:文本会被 UTF-16 安全截断(truncateUtf16Safe 与 truncateSanitizedExternalContent),引用的数量与 URL 长度也有限制(最多 20 条、最长 2048 字符),超长或畸形的引用会被丢弃。
与其他工具的关系
code_execution 在 OpenClaw 工具体系中与以下能力互补:
exec:在本地机器或配对节点上执行 Shell 命令,适合需要本地资源、文件系统或设备能力的场景;exec-approvals:为本地 Shell 执行提供允许/拒绝策略;web:web_search、x_search、web_fetch,负责数据获取,是code_execution分析前的常用数据源;- xai provider 文档:Grok 模型、Web/X 搜索与代码执行的完整配置说明。
在 docs/providers/xai.md 的能力矩阵中,code_execution 被列为"Server-side code execution"并明确标记为远程沙箱执行;官方文档也建议对需要本地执行的场景优先选择 exec。合理划分"远程沙箱分析"与"本地执行"两类职责,是高效使用 OpenClaw 数据分析能力的关键。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0631
MiniCPM5-2BMiniCPM5-2B 是一款面向端侧、本地部署和资源受限场景的 2B 稠密 Transformer,能够达到同尺寸开源模型 SOTA 水平。Markdown00
video-shotcraftAI宣传片skill,使用 Remotion 制作电影级产品视频:提供106 张镜头配方卡和可复用的视频魔板。适用于 Claude Code 与 Codex以及所有其他智能体Markdown00
HivisionIDPhotos⚡️HivisionIDPhotos: a lightweight and efficient AI ID photos tools. 一个轻量级的AI证件照制作算法。Python09
DragonOSDragonOS is an operating system developed from scratch using Rust, with Linux compatibility. It is designed for **Serverless** scenarios. 使用Rust从0自研内核,具有Linux兼容性的操作系统,面向云计算Serverless场景而设计。Rust00
Spark-X2.5-1.7BSpark-X2.5-1.7B 旨在让强大的 AI 更加实用、高效且易于获取。这些模型在广泛的日常任务中表现出色,涵盖对话、写作、翻译、推理、编程、工具调用和智能体工作流,并在同等规模的开源模型中取得领先结果。Spark-X2.5 将面向效率的架构与最高 1M tokens 的原生上下文窗口相结合,并支持 200 多种语言。Python00