Claude 可以直接在 API 对话中分析数据、创建可视化、执行复杂计算、运行系统命令、创建和编辑文件以及处理上传的文件。代码执行工具允许 Claude 在安全的沙盒环境中运行 Bash 命令和操作文件,包括编写代码。
当与网络搜索或网络获取(web_search_20260209、web_fetch_20260209 或更高版本)一起使用时,代码执行是免费的。 当您的请求中包含其中一个工具时,除了标准令牌成本外,该请求中的代码执行不会产生额外费用。这涵盖了动态过滤背后的代码执行以及 Claude 直接运行的任何代码。当不包含这些工具时,适用标准代码执行定价。
代码执行还为网络搜索和网络获取工具中的动态过滤提供支持:Claude 在结果到达上下文窗口之前,在代码执行环境中对其进行过滤。当动态过滤运行时,API 会自动为请求配置所需的代码执行,因此您无需为此在请求中添加代码执行工具。
请通过反馈表单分享您对此功能的反馈。
此功能不符合零数据保留(ZDR)的条件。数据将根据该功能的标准保留策略进行保留。
代码执行工具可在以下模型上使用:
| 模型 | 工具版本 |
|---|---|
| Claude Fable 5 (claude-fable-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Mythos 5 (claude-mythos-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 5 (claude-sonnet-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.8 (claude-opus-4-8) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.7 (claude-opus-4-7) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.1 (claude-opus-4-1-20250805)(已弃用) | code_execution_20250825 |
每个工具版本都建立在前一个版本的基础上:
code_execution_20250825 支持 Bash 命令和文件操作,并且在表中的每个模型上都可用。code_execution_20260120 增加了 REPL 状态持久化以及从沙盒内部进行的程序化工具调用。Claude Haiku 4.5 接受 code_execution_20260120 和 code_execution_20260521 工具类型,但程序化工具调用以及依赖于它的 REPL 状态持久化在该模型上不可用,因此较新的版本在该模型上的行为与 code_execution_20250825 相同。code_execution_20260521 与 code_execution_20260120 是相同的运行时。区别在于工具描述会告知 Claude 程序化工具调用中每个 Python 单元格的 90 秒实际时间(wall-clock)限制,以便 Claude 可以为长时间运行的单元格做预算。超过限制的单元格会返回一个正常的代码执行结果,其中包含非零的 return_code 和输出中的 detection_timeout 状态消息。这与 execution_time_exceeded 错误代码不同,后者是在整个工具调用超过最大执行时间时由 API 返回的。所有三个工具版本均已正式发布,不需要 anthropic-beta 标头。旧版代码执行 beta 标头仍然是有效的选择加入方式。
本页面上的示例使用 code_execution_20250825,因为表中的每个模型都支持它。当前的网络搜索和网络获取工具(web_search_20260209、web_fetch_20260209 及更高版本)要求使用 code_execution_20260120 或更高版本作为其代码执行版本。
如果您仍在使用旧版 code_execution_20250522(仅限 Python),请参阅升级到最新工具版本以从中迁移。
不保证较旧的工具版本与较新的模型向后兼容。请始终使用与您的模型版本对应的工具版本。
代码执行可在以下平台上使用:
代码执行目前在 Amazon Bedrock 或 Google Cloud 上不可用。
对于 Claude Mythos Preview,代码执行仅在 Claude API 和 Microsoft Foundry 上受支持。Mythos Preview 在 Amazon Bedrock、Google Cloud 或 Claude Platform on AWS 上不支持代码执行。
以下是一个简单的示例,要求 Claude 执行计算:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Use the code execution tool to 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.to_json())响应将 server_tool_use 块(Claude 运行的命令)与其工具结果块交错排列,后面跟着 Claude 的文本。顶层还包含一个 container 对象,您可以在多个请求之间重用其 id。有关块的结构,请参阅响应格式。
当您将代码执行工具添加到 API 请求时:
tool_result 块。一个例外是当 Claude 在代码执行的同时调用您的某个客户端工具时:API 会返回代码执行调用但不包含其结果。结果会在您发回客户端工具的 tool_result 块之后,在后续响应中到达容器预装了 Python。Claude 使用文件操作子工具编写 Python,并使用 Bash 命令运行它。使用 code_execution_20260120 或更高版本以及程序化工具调用时,Python 解释器状态(例如变量绑定)也会在重用容器的请求之间持久保留。
当请求能从计算或文件处理中受益时,Claude 会运行代码:
对于以下情况,Claude 会直接回答而不运行代码:
如果您希望 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=Path("data.csv"))
# 将 file_id 与代码执行一起使用
response = client.beta.messages.create(
model="claude-opus-4-8",
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.to_json())当 Claude 在代码执行期间创建文件时,每个创建的文件的 ID 都会出现在代码执行工具结果中,您可以使用 Files API 下载它:
client = Anthropic()
# 请求创建文件的代码执行
response = client.beta.messages.create(
model="claude-opus-4-8",
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: BetaMessage) -> list[str]:
file_ids: list[str] = []
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":
for output_block in content_item.content:
file_ids.append(output_block.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"
}这两个字段都是固定的:type 选择工具版本,name 必须是 code_execution。
提供此工具后,Claude 会自动获得对两个子工具的访问权限:
bash_code_execution:运行 shell 命令text_editor_code_execution:查看、创建和编辑文件,包括编写代码当 Claude 运行代码时,响应还包含一个顶层 container 对象,其中包含容器的 id 和 expires_at 时间戳。在顶层 container 请求参数中传回该 ID 以继续使用同一容器。请参阅容器重用。
根据操作的不同,代码执行工具可以返回两种类型的结果:
{
"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,
"content": []
}
}查看文件:
{
"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_view_result",
"file_type": "text",
"content": "{\n \"setting\": \"value\",\n \"debug\": true\n}",
"num_lines": 4,
"start_line": 1,
"total_lines": 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_create_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_str_replace_result",
"old_start": 3,
"old_lines": 1,
"new_start": 3,
"new_lines": 1,
"lines": ["- \"debug\": true", "+ \"debug\": false"]
}
}Bash 命令结果(bash_code_execution_result)包括:
stdout:成功执行的输出stderr:执行失败时的错误消息return_code:0 表示成功,非零表示失败content:一个列表,其中每个条目对应命令创建的一个文件。每个条目都带有 file_id,可用于通过 Files API 检索文件文件操作结果有自己的字段:
text_editor_code_execution_view_result):file_type、content、num_lines、start_line、total_linestext_editor_code_execution_create_result):is_file_update(文件是否已存在)text_editor_code_execution_str_replace_result):old_start、old_lines、new_start、new_lines、lines(diff 格式)每种工具类型都可能返回特定的错误:
常见错误(所有工具):
{
"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 | 工具调用超过了最大执行时间 |
| 所有工具 | invalid_tool_input | 提供给工具的参数无效 |
| 所有工具 | too_many_requests | 工具使用超过了速率限制 |
| bash | output_file_too_large | 命令输出超过了最大大小 |
| text_editor | file_not_found | 文件不存在(针对查看/编辑操作) |
已过期的容器无法重用:引用它的请求会返回错误,而不是恢复它。请在不带 container 参数的情况下再次发送请求以获取新容器。
pause_turn 停止原因响应可能包含 pause_turn 停止原因,这表示 API 暂停了一个长时间运行的轮次。您可以在后续请求中按原样提供该响应,让 Claude 继续其轮次;如果您想中断对话,也可以修改内容。
代码执行工具在专为代码执行设计的安全容器化环境中运行,并更侧重于 Python。
execution_time_exceeded 错误。使用程序化工具调用时,每个 REPL 单元格还有 90 秒的实际时间限制沙盒 Python 环境包含以下常用库:
容器还包含命令行工具,例如 unzip、unrar、7zip、bc、rg(ripgrep)、fd 和 sqlite。
容器没有互联网访问权限,因此 Claude 无法在运行时下载或安装其他软件包:只有预装库可用。
您可以通过提供先前响应中的容器 ID,在多个 API 请求之间重用现有容器。这使您可以在请求之间保留已创建的文件。使用 code_execution_20260120 或更高版本以及程序化工具调用时,Python 解释器状态也会持久保留。
容器在创建后 30 天过期。在大约五分钟的不活动后,容器会被设置检查点(checkpoint),在 30 天窗口内发送带有其 ID 的请求会恢复它。响应的 container 对象中的 expires_at 时间戳是一个较短的滚动值,并不反映 30 天的限制。已过期的容器无法重用。请在不带 container 参数的情况下再次发送请求以获取新容器。
client = anthropic.Anthropic()
# 第一个请求:在新容器中创建一个包含随机数的文件
response1 = client.messages.create(
model="claude-opus-4-8",
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,以便 Claude 复用同一个容器
response2 = client.messages.create(
container=response1.container.id,
model="claude-opus-4-8",
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.to_json())当您将代码执行与同样运行代码的客户端提供的工具(例如 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 需要对其加以区分。
当 Claude 在代码执行的同时调用您的某个客户端工具时,API 会返回代码执行调用但不包含其结果。结果会在您发回客户端工具的 tool_result 块之后,在后续响应中到达。
启用流式传输("stream": true)后,您将在代码执行事件发生时收到它们。子工具输入以 input_json_delta 事件的形式流式传输,每个结果块在单个 content_block_start 事件中完整到达:
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "bash_code_execution"}}
// Tool input streamed as partial JSON
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"python analyze.py\"}"}}
// Pause while the command runs
// Execution result delivered as a complete block
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "bash_code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "bash_code_execution_result", "stdout": " A B C\n0 1 2 3\n1 4 5 6", "stderr": "", "return_code": 0, "content": []}}}您可以在 Messages Batches API 中包含代码执行工具。通过 Messages Batches API 进行的代码执行工具调用的定价与常规 Messages API 请求中的定价相同。
与网络搜索或网络抓取一起使用时,代码执行是免费的。 当您的 API 请求中包含 web_search_20260209(或更高版本)或 web_fetch_20260209(或更高版本)时,除了标准的输入和输出令牌费用外,代码执行工具调用不会产生额外费用。
在不与这些工具一起使用时,代码执行按执行时间计费,与令牌使用量分开计算:
代码执行使用量会在响应中进行跟踪:
{
"usage": {
"input_tokens": 105,
"output_tokens": 239,
"server_tool_use": {
"code_execution_requests": 1
}
}
}最新的工具版本是 code_execution_20260521。要在三个当前版本之间切换,请更新请求中的 type 字符串:所有三个版本都返回响应格式中记录的响应块。有关每个版本新增的功能以及哪些模型支持它,请参阅模型兼容性。
本节的其余部分介绍如何从旧版仅限 Python 的 code_execution_20250522 迁移到当前工具版本。
| 组件 | 旧版 | 当前版本 |
|---|---|---|
| Beta 标头 | code-execution-2025-05-22 | 不需要 |
| 工具类型 | 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 和数据保留。
将速度更快的执行器模型与智能程度更高的顾问模型配对,后者在生成过程中提供战略性指导。
从在代码执行容器内运行的代码中调用您自己的工具。
上传文件进行分析,并下载代码执行创建的文件。
了解如何使用 Agent Skills 通过 API 扩展 Claude 的能力。
Was this page helpful?