Claude 可以直接在 API 对话中分析数据、创建可视化图表、执行复杂计算、运行系统命令、创建和编辑文件,以及处理上传的文件。代码执行工具允许 Claude 在安全的沙盒环境中运行 Bash 命令并操作文件(包括编写代码)。
当与网络搜索或网络获取(web_search_20260209、web_fetch_20260209 或更高版本)一起使用时,代码执行是免费的。 当您的请求中包含其中一个工具时,该请求中的代码执行除标准令牌费用外不会产生额外费用。这涵盖了动态过滤背后的代码执行以及 Claude 直接运行的任何代码。当未包含这些工具时,将适用标准代码执行定价。
代码执行还为网络搜索和网络获取工具中的动态过滤提供支持:Claude 在结果进入上下文窗口之前,在代码执行环境内对其进行过滤。当动态过滤运行时,API 会自动为请求配置所需的代码执行,因此您无需为此在请求中添加代码执行工具。
代码执行工具在以下模型上可用:
| 模型 | 工具版本 |
|---|---|
| Claude Opus 5 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Fable 5 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Mythos 5 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 5 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.8 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.7 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.6 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.6 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.5 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.5 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Haiku 4.5 () | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
每个工具版本都在前一个版本的基础上构建:
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 秒的挂钟时间限制,以便 Claude 为长时间运行的单元格分配时间预算。超过该限制的单元格会返回一个正常的代码执行结果,其中包含非零的 return_code 以及输出中的 detection_timeout 状态消息。这与 execution_time_exceeded 错误代码不同,后者是当整个工具调用超过最大执行时间时 API 返回的错误。这三个工具版本均已正式发布,不需要 anthropic-beta 标头。旧版代码执行 beta 标头仍然是有效的选择加入方式。
本页面的示例使用 code_execution_20250825,它涵盖了示例中演示的 Bash 和文件操作,并且在表格中的每个模型上行为一致;当您需要编程式工具调用或 REPL 状态持久化时,请使用 code_execution_20260120 或更高版本。当前的网络搜索和网络获取工具(web_search_20260209、web_fetch_20260209 及更高版本)要求使用 code_execution_20260120 或更高版本作为其代码执行版本。
代码执行在以下平台上可用:
代码执行目前在 Amazon Bedrock 或 Google Cloud 上不可用。
以下示例要求 Claude 执行一个计算:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
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 上传它们并在请求中引用:
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-5",
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-5",
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 时间戳。将该 ID 传回顶层 container 请求参数中,以继续使用同一容器。请参阅容器重用。
代码执行工具可以根据操作返回两种类型的结果:
{
"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 天过期。在大约 5 分钟不活动后,容器会被设置检查点,在 30 天窗口内使用其 ID 发送请求会恢复该容器。响应的 container 对象中的 expires_at 时间戳是一个较短的滚动值,不反映 30 天的限制。已过期的容器无法重用。请在不带 container 参数的情况下再次发送请求以获取新容器。
client = anthropic.Anthropic()
# 第一个请求:在新容器中创建一个包含随机数的文件
response1 = client.messages.create(
model="claude-opus-5",
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-5",
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 和数据保留。
将速度更快的执行器模型与智能更高的顾问模型配对,后者在生成过程中提供战略指导。
从代码执行容器内运行的代码中调用您自己的工具。
上传文件进行分析,并下载代码执行创建的文件。
了解如何通过 API 使用 Agent Skills 来扩展 Claude 的能力。
Was this page helpful?