Claude 可以分析数据、创建可视化、执行复杂计算、运行系统命令、创建和编辑文件,以及直接在 API 对话中处理上传的文件。代码执行工具允许 Claude 在安全的沙箱环境中运行 Bash 命令和操作文件,包括编写代码。
与网络搜索或网络获取一起使用时,代码执行是免费的。 当您的请求中包含 web_search_20260209 或 web_fetch_20260209 时,代码执行工具调用不会产生额外费用,仅需支付标准的输入和输出令牌成本。当不包含这些工具时,标准代码执行费用适用。
代码执行是构建高性能代理的核心原语。它在网络搜索和网络获取工具中启用动态过滤,允许 Claude 在结果到达上下文窗口之前处理它们,提高准确性同时降低令牌消耗。
通过反馈表分享您对此功能的反馈。
This feature is not eligible for Zero Data Retention (ZDR). Data is retained according to the feature's standard retention policy.
代码执行工具在以下模型上可用:
| 模型 | 工具版本 |
|---|---|
Claude Opus 4.7 (claude-opus-4-7) | code_execution_20250825, code_execution_20260120 |
Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825, code_execution_20260120 |
Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825, code_execution_20260120 |
Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825, code_execution_20260120 |
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825, code_execution_20260120 |
Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825 |
Claude Opus 4.1 (claude-opus-4-1-20250805) | code_execution_20250825 |
Claude Opus 4 (claude-opus-4-20250514) (已弃用) | code_execution_20250825 |
Claude Sonnet 4 (claude-sonnet-4-20250514) (已弃用) | code_execution_20250825 |
Claude Sonnet 3.7 (claude-3-7-sonnet-20250219) (已弃用) | code_execution_20250825 |
Claude Haiku 3.5 (claude-3-5-haiku-latest) (已弃用) | code_execution_20250825 |
较旧的工具版本不保证与较新的模型向后兼容。始终使用与您的模型版本相对应的工具版本。
代码执行在以下平台上可用:
代码执行目前在 Amazon Bedrock 或 Google Vertex AI 上不可用。
对于 Claude Mythos Preview,代码执行仅在 Claude API 和 Microsoft Foundry 上受支持。在 Amazon Bedrock 或 Google Vertex AI 上不适用于 Mythos Preview。
这是一个简单的示例,要求 Claude 执行计算:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response)当您将代码执行工具添加到您的 API 请求时:
当您提供代码执行以及也运行代码的客户端提供的工具(例如 bash 工具或自定义 REPL)时,Claude 在多计算机环境中运行。代码执行工具在 Anthropic 的沙箱容器中运行,而您的客户端提供的工具在您控制的单独环境中运行。Claude 有时可能会混淆这些环境,尝试使用错误的工具或假设状态在它们之间共享。
为了避免这种情况,请在您的系统提示中添加说明,以澄清区别:
When multiple code execution environments are available, be aware that:
- Variables, files, and state DO NOT persist between different execution environments
- Use the code_execution tool for general-purpose computation in Anthropic's sandboxed environment
- Use client-provided execution tools (e.g., bash) when you need access to the user's local system, files, or data
- If you need to pass results between environments, explicitly include outputs in subsequent tool calls rather than assuming shared state这在将代码执行与网络搜索或网络获取结合时尤其重要,这会自动启用代码执行。如果您的应用程序已经提供了客户端 shell 工具,自动代码执行会创建第二个执行环境,Claude 需要在它们之间进行区分。
要分析您自己的数据文件(CSV、Excel、图像等),请通过 Files API 上传它们,并在您的请求中引用它们:
使用 Files API 与代码执行需要 Files API beta 标头:"anthropic-beta": "files-api-2025-04-14"
Python 环境可以处理通过 Files API 上传的各种文件类型,包括:
container_upload 内容块引用该文件client = anthropic.Anthropic()
# 上传一个文件
file_object = client.beta.files.upload(
file=open("data.csv", "rb"),
)
# 使用 file_id 进行代码执行
response = client.beta.messages.create(
model="claude-opus-4-7",
betas=["files-api-2025-04-14"],
max_tokens=4096,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this CSV data"},
{"type": "container_upload", "file_id": file_object.id},
],
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response)当 Claude 在代码执行期间创建文件时,您可以使用 Files API 检索这些文件:
# 初始化客户端
client = Anthropic()
# 请求代码执行以创建文件
response = client.beta.messages.create(
model="claude-opus-4-7",
betas=["files-api-2025-04-14"],
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Create a matplotlib visualization and save it as output.png",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
# 从响应中提取文件 ID
def extract_file_ids(response):
file_ids = []
for item in response.content:
if item.type == "bash_code_execution_tool_result":
content_item = item.content
if content_item.type == "bash_code_execution_result":
# concrete-typed list: List[BashCodeExecutionOutputBlock]
for file in content_item.content:
file_ids.append(file.file_id)
return file_ids
# 下载创建的文件
for file_id in extract_file_ids(response):
file_metadata = client.beta.files.retrieve_metadata(file_id)
file_content = client.beta.files.download(file_id)
file_content.write_to_file(file_metadata.filename)
print(f"Downloaded: {file_metadata.filename}")代码执行工具不需要额外的参数:
{
"type": "code_execution_20250825",
"name": "code_execution"
}提供此工具后,Claude 会自动获得对两个子工具的访问权限:
bash_code_execution:运行 shell 命令text_editor_code_execution:查看、创建和编辑文件,包括编写代码代码执行工具可以根据操作返回两种类型的结果:
{
"type": "server_tool_use",
"id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
"name": "bash_code_execution",
"input": {
"command": "ls -la | head -5"
}
},
{
"type": "bash_code_execution_tool_result",
"tool_use_id": "srvtoolu_01B3C4D5E6F7G8H9I0J1K2L3",
"content": {
"type": "bash_code_execution_result",
"stdout": "total 24\ndrwxr-xr-x 2 user user 4096 Jan 1 12:00 .\ndrwxr-xr-x 3 user user 4096 Jan 1 11:00 ..\n-rw-r--r-- 1 user user 220 Jan 1 12:00 data.csv\n-rw-r--r-- 1 user user 180 Jan 1 12:00 config.json",
"stderr": "",
"return_code": 0
}
}查看文件:
{
"type": "server_tool_use",
"id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
"name": "text_editor_code_execution",
"input": {
"command": "view",
"path": "config.json"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01C4D5E6F7G8H9I0J1K2L3M4",
"content": {
"type": "text_editor_code_execution_result",
"file_type": "text",
"content": "{\n \"setting\": \"value\",\n \"debug\": true\n}",
"numLines": 4,
"startLine": 1,
"totalLines": 4
}
}创建文件:
{
"type": "server_tool_use",
"id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
"name": "text_editor_code_execution",
"input": {
"command": "create",
"path": "new_file.txt",
"file_text": "Hello, World!"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01D5E6F7G8H9I0J1K2L3M4N5",
"content": {
"type": "text_editor_code_execution_result",
"is_file_update": false
}
}编辑文件 (str_replace):
{
"type": "server_tool_use",
"id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
"name": "text_editor_code_execution",
"input": {
"command": "str_replace",
"path": "config.json",
"old_str": "\"debug\": true",
"new_str": "\"debug\": false"
}
},
{
"type": "text_editor_code_execution_tool_result",
"tool_use_id": "srvtoolu_01E6F7G8H9I0J1K2L3M4N5O6",
"content": {
"type": "text_editor_code_execution_result",
"oldStart": 3,
"oldLines": 1,
"newStart": 3,
"newLines": 1,
"lines": ["- \"debug\": true", "+ \"debug\": false"]
}
}所有执行结果包括:
stdout:成功执行的输出stderr:执行失败时的错误消息return_code:成功时为 0,失败时为非零值文件操作的其他字段:
file_type、content、numLines、startLine、totalLinesis_file_update(文件是否已存在)oldStart、oldLines、newStart、newLines、lines(差异格式)每种工具类型都可以返回特定的错误:
常见错误(所有工具):
{
"type": "bash_code_execution_tool_result",
"tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
"content": {
"type": "bash_code_execution_tool_result_error",
"error_code": "unavailable"
}
}按工具类型的错误代码:
| 工具 | 错误代码 | 描述 |
|---|---|---|
| 所有工具 | unavailable | 该工具暂时不可用 |
| 所有工具 | execution_time_exceeded | 执行超过最大时间限制 |
| 所有工具 | container_expired | 容器已过期且不再可用 |
| 所有工具 | invalid_tool_input | 提供给工具的参数无效 |
| 所有工具 | too_many_requests | 超过工具使用速率限制 |
| bash | output_file_too_large | 命令输出超过最大大小 |
| text_editor | file_not_found | 文件不存在(用于查看/编辑操作) |
| text_editor | string_not_found | 在文件中找不到 old_str(用于 str_replace) |
pause_turn 停止原因响应可能包括 pause_turn 停止原因,这表示 API 暂停了长时间运行的轮次。您可以在后续请求中按原样提供响应以让 Claude 继续其轮次,或者如果您想中断对话,可以修改内容。
代码执行工具在专为代码执行设计的安全容器化环境中运行,特别关注 Python。
沙箱 Python 环境包括这些常用库:
您可以通过提供来自先前响应的容器 ID,在多个 API 请求中重用现有容器。这允许您在请求之间维护创建的文件。
# 第一个请求:创建一个包含随机数的文件
response1 = client.messages.create(
model="claude-opus-4-7",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Write a file with a random number and save it to '/tmp/number.txt'",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
# 从第一个响应中提取容器 ID
container_id = response1.container.id
# 第二个请求:重用容器来读取文件
response2 = client.messages.create(
container=container_id, # 重用同一个容器
model="claude-opus-4-7",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Read the number from '/tmp/number.txt' and calculate its square",
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response2)启用流式传输后,您将在代码执行事件发生时接收它们:
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}}
// 代码执行流式传输
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"code\":\"import pandas as pd\\ndf = pd.read_csv('data.csv')\\nprint(df.head())\"}"}}
// 暂停以执行代码
// 执行结果流式传输
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"stdout": " A B C\n0 1 2 3\n1 4 5 6", "stderr": ""}}}您可以在 Messages Batches API 中包含代码执行工具。通过 Messages Batches API 进行的代码执行工具调用的定价与常规 Messages API 请求中的定价相同。
Code execution is free when used with web search or web fetch. When web_search_20260209 or web_fetch_20260209 is included in your API request, there are no additional charges for code execution tool calls beyond the standard input and output token costs.
When used without these tools, code execution is billed by execution time, tracked separately from token usage:
Code execution usage is tracked in the response:
"usage": {
"input_tokens": 105,
"output_tokens": 239,
"server_tool_use": {
"code_execution_requests": 1
}
}通过升级到 code-execution-2025-08-25,您可以访问文件操作和 Bash 功能,包括多种语言的代码。没有价格差异。
| 组件 | 旧版本 | 当前版本 |
|---|---|---|
| Beta 标头 | code-execution-2025-05-22 | code-execution-2025-08-25 |
| 工具类型 | code_execution_20250522 | code_execution_20250825 |
| 功能 | 仅 Python | Bash 命令、文件操作 |
| 响应类型 | code_execution_result | bash_code_execution_result、text_editor_code_execution_result |
要升级,请更新 API 请求中的工具类型:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"审查响应处理(如果以编程方式解析响应):
有关在代码执行容器内运行工具的信息,请参阅 程序化工具调用。
代码执行在服务器端沙箱容器中运行。容器数据(包括执行工件、上传的文件和输出)最多保留 30 天。此保留适用于在容器环境中处理的所有数据。代码执行在 Files API 中创建的文件(可通过 client.beta.files.download() 检索)会一直保留到明确删除。
有关所有功能的 ZDR 资格,请参阅 API 和数据保留。
代码执行工具使 Claude 能够使用 Agent Skills。Skills 是模块化功能,由说明、脚本和资源组成,可扩展 Claude 的功能。
在 Agent Skills 文档 和 Agent Skills API 指南 中了解更多信息。
Was this page helpful?