Claude Platform Docs
  • 消息
  • 托管智能体
  • 管理

Search...
⌘K
第一步
Claude 简介快速入门
使用 Claude 构建
功能概览使用 Messages API停止原因与回退拒绝与回退回退额度
模型能力
扩展思考自适应思考努力程度任务预算(测试版)快速模式(研究预览)结构化输出引用流式传输消息批量处理搜索结果流式传输拒绝多语言支持嵌入
工具
概览工具使用的工作原理教程:构建使用工具的智能体定义工具处理工具调用并行工具使用工具运行器(SDK)严格工具使用工具使用与提示缓存服务器工具故障排除网页搜索工具网页抓取工具代码执行工具顾问工具记忆工具Bash 工具计算机使用工具文本编辑器工具
工具基础设施
工具参考管理工具上下文工具组合工具搜索编程式工具调用细粒度工具流式传输
上下文管理
上下文窗口压缩上下文编辑提示缓存对话中系统消息构建编排模式缓存诊断(测试版)令牌计数
处理文件
Files APIPDF 支持图像与视觉
技能
概览快速入门最佳实践企业技能API 中的技能
MCP
远程 MCP 服务器MCP 连接器
云平台上的 Claude
Amazon BedrockAmazon Bedrock(旧版)AWS 上的 Claude PlatformMicrosoft FoundryVertex AI

Log in
代码执行工具
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Claude Platform Docs

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Claude on AWS
  • Claude on Google Cloud

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
消息/工具

代码执行工具

在沙盒容器中运行 Python 和 bash 代码,以分析数据、生成文件并迭代解决方案。

Claude 可以直接在 API 对话中分析数据、创建可视化图表、执行复杂计算、运行系统命令、创建和编辑文件,以及处理上传的文件。代码执行工具允许 Claude 在安全的沙盒环境中运行 Bash 命令和操作文件(包括编写代码)。

当与网络搜索或网络获取一起使用时,代码执行是免费的。 当您的请求中包含 web_search_20260209(或更高版本)或 web_fetch_20260209(或更高版本)时,除了标准的输入和输出令牌费用外,代码执行工具调用不会产生额外费用。当不包含这些工具时,将按标准代码执行费用收费。

代码执行是构建高性能智能体的核心基础能力。它支持在网络搜索和网络获取工具中进行动态过滤,使 Claude 能够在结果进入上下文窗口之前对其进行处理,从而提高准确性并减少令牌消耗。



请通过反馈表单分享您对此功能的反馈。



此功能不符合零数据保留(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 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
Claude Opus 4.1 (claude-opus-4-1-20250805)(已弃用)code_execution_20250825


code_execution_20250825 支持 Bash 命令和文件操作,可在表格中的所有模型上使用。code_execution_20260120 增加了 REPL 状态持久化以及在沙盒内进行编程式工具调用的功能,仅在 Claude Fable 5、Claude Mythos 5、Opus 4.5+ 和 Sonnet 4.5+ 上可用。code_execution_20260521 与 _20260120 的运行时相同,但在工具描述中公开了每个单元格的执行时间限制,以便 Claude 可以相应地规划长时间运行的单元格。每个单元格的挂钟时间限制为 90 秒;超过此限制的代码将返回 detection_timeout 结果。如果您仍在使用旧版 code_execution_20250522(仅支持 Python),请参阅升级到最新工具版本以进行迁移。



旧版工具不保证与新版模型向后兼容。请始终使用与您的模型版本对应的工具版本。

平台可用性

代码执行可在以下平台上使用:

  • Claude API(Anthropic)
  • Claude Platform on AWS
  • Microsoft Foundry

代码执行目前在 Amazon Bedrock 或 Vertex AI 上不可用。



对于 Claude Mythos Preview,代码执行仅在 Claude API 和 Microsoft Foundry 上受支持。在 Amazon Bedrock、Vertex AI 或 Claude Platform on AWS 上,Mythos Preview 不支持代码执行。

快速开始

以下是一个要求 Claude 执行计算的简单示例:

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-8",
    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 请求中时:

  1. Claude 会评估代码执行是否有助于回答您的问题
  2. 该工具会自动为 Claude 提供以下能力:
    • Bash 命令:执行 shell 命令以进行系统操作和包管理
    • 文件操作:直接创建、查看和编辑文件,包括编写代码
  3. Claude 可以在单个请求中使用这些能力的任意组合
  4. 所有操作都在安全的沙盒环境中运行
  5. Claude 会提供结果以及生成的任何图表、计算或分析

Claude 何时运行代码

当请求能够从计算或文件处理中受益时,Claude 会运行代码:

  • 非简单数学运算(大数字、多步骤、对精度敏感的结果)
  • 数据分析、文件解析或可视化
  • 算法执行或模拟
  • 明确要求"运行"、"计算"或"执行"的请求

对于以下情况,Claude 会直接回答而不运行代码:

  • 简单算术和众所周知的数学事实
  • 事实性、对话性或创意性请求
  • 简单的单位换算或翻译

如果您希望 Claude 为边界情况的请求运行代码,请明确提出要求(例如,"运行代码来验证这一点")。

将代码执行与其他执行工具一起使用

当您在提供代码执行的同时还提供了同样运行代码的客户端工具(例如 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 上传的各种文件类型,包括:

  • CSV
  • Excel(.xlsx、.xls)
  • JSON
  • XML
  • 图像(JPEG、PNG、GIF、WebP)
  • 文本文件(.txt、.md、.py 等)

上传并分析文件

  1. 使用 Files API 上传您的文件
  2. 使用 container_upload 内容块在消息中引用该文件
  3. 在 API 请求中包含代码执行工具
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-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)

检索生成的文件

当 Claude 在代码执行期间创建文件时,您可以使用 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):
    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":
                # 具体类型的列表: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}")

工具定义

代码执行工具不需要额外的参数:

JSON
{
  "type": "code_execution_20250825",
  "name": "code_execution"
}

提供此工具后,Claude 会自动获得两个子工具的访问权限:

  • bash_code_execution:运行 shell 命令
  • text_editor_code_execution:查看、创建和编辑文件,包括编写代码

响应格式

代码执行工具可以根据操作返回两种类型的结果:

Bash 命令响应

Output
{
  "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
  }
}

文件操作响应

查看文件:

Output
{
  "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
  }
}

创建文件:

Output
{
  "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):

Output
{
  "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、totalLines
  • 创建:is_file_update(文件是否已存在)
  • 编辑:oldStart、oldLines、newStart、newLines、lines(diff 格式)

错误

每种工具类型都可能返回特定的错误:

通用错误(所有工具):

Output
{
  "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超出工具使用的速率限制
bashoutput_file_too_large命令输出超过最大大小
text_editorfile_not_found文件不存在(用于查看/编辑操作)
text_editorstring_not_found在文件中未找到 old_str(用于 str_replace)

pause_turn 停止原因

响应可能包含 pause_turn 停止原因,这表示 API 暂停了一个长时间运行的轮次。您可以在后续请求中按原样提供该响应,让 Claude 继续其轮次;如果您希望中断对话,也可以修改内容。

容器

代码执行工具在专为代码执行设计的安全容器化环境中运行,重点支持 Python。

运行时环境

  • Python 版本:3.11.12
  • 操作系统:基于 Linux 的容器
  • 架构:x86_64(AMD64)

资源限制

  • 内存:5GiB RAM
  • 磁盘空间:5GiB 工作区存储
  • CPU:1 个 CPU

网络和安全

  • 互联网访问:出于安全考虑完全禁用
  • 外部连接:不允许出站网络请求
  • 沙盒隔离:与主机系统和其他容器完全隔离
  • 文件访问:仅限于工作区目录
  • 工作区范围:与 Files 类似,容器的范围限定于 API 密钥的工作区
  • 过期时间:容器在创建后 30 天过期

预装库

沙盒 Python 环境包含以下常用库:

  • 数据科学:pandas、numpy、scipy、scikit-learn、statsmodels
  • 可视化:matplotlib、seaborn
  • 文件处理:pyarrow、openpyxl、xlsxwriter、xlrd、pillow、python-pptx、python-docx、pypdf、pdfplumber、pypdfium2、pdf2image、pdfkit、tabula-py、reportlab[pycairo]、Img2pdf
  • 数学与计算:sympy、mpmath
  • 实用工具:tqdm、python-dateutil、pytz、joblib、unzip、unrar、7zip、bc、rg(ripgrep)、fd、sqlite

容器复用

您可以通过提供先前响应中的容器 ID,在多个 API 请求中复用现有容器。这使您能够在请求之间保留已创建的文件。

示例

# 第一个请求:创建一个包含随机数的文件
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
container_id = response1.container.id

# 第二个请求:复用该容器以读取文件
response2 = client.messages.create(
    container=container_id,  # Reuse the same container
    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)

流式传输

启用流式传输后,您将在代码执行事件发生时接收到它们:

event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}}

// Code execution streamed
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())\"}"}}

// Pause while code executes

// Execution results streamed
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 请求中的定价相同。

使用量和定价

与网络搜索或网络抓取一起使用时,代码执行是免费的。 当您的 API 请求中包含 web_search_20260209(或更高版本)或 web_fetch_20260209(或更高版本)时,除了标准的输入和输出令牌费用外,代码执行工具调用不会产生额外费用。

在不与这些工具一起使用时,代码执行按执行时间计费,与令牌使用量分开计算:

  • 执行时间最低按 5 分钟计算
  • 每个组织每月可获得 1,550 小时免费使用时长
  • 超出 1,550 小时的额外使用量按每个容器每小时 $0.05 计费
  • 如果请求中包含文件,即使未调用该工具,也会按执行时间计费,因为文件会被预加载到容器中

代码执行使用量会在响应中进行跟踪:

{
  "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-22code-execution-2025-08-25
工具类型code_execution_20250522code_execution_20250825
功能仅 PythonBash 命令、文件操作
响应类型code_execution_resultbash_code_execution_result、text_editor_code_execution_result

向后兼容性

  • 所有现有的 Python 代码执行继续完全按照以前的方式工作
  • 现有的仅 Python 工作流无需任何更改

升级步骤

要升级,请更新 API 请求中的工具类型:

- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"

检查响应处理(如果以编程方式解析响应):

  • 之前用于 Python 执行响应的块将不再发送
  • 取而代之的是,将发送用于 Bash 和文件操作的新响应类型(请参阅"响应格式"部分)

编程式工具调用

有关在代码执行容器内运行工具的信息,请参阅编程式工具调用。

数据保留

代码执行在服务器端沙盒容器中运行。容器数据(包括执行产物、上传的文件和输出)最多保留 30 天。此保留策略适用于容器环境中处理的所有数据。代码执行在 Files API 中创建的文件(可通过 client.beta.files.download() 检索)会持续存在,直到被明确删除。

有关所有功能的 ZDR 资格,请参阅 API 和数据保留。

将代码执行与 Agent Skills 一起使用

代码执行工具使 Claude 能够使用 Agent Skills。Skills 是由指令、脚本和资源组成的模块化能力,可扩展 Claude 的功能。

在 Agent Skills 和通过 API 使用 Agent Skills 中了解更多信息。

Was this page helpful?

  • 模型兼容性
  • 平台可用性
  • 快速开始
  • 代码执行的工作原理
  • Claude 何时运行代码
  • 将代码执行与其他执行工具一起使用
  • 如何使用该工具
  • 上传并分析您自己的文件
  • 检索生成的文件
  • 工具定义
  • 响应格式
  • Bash 命令响应
  • 文件操作响应
  • 结果
  • 错误
  • 容器
  • 运行时环境
  • 资源限制
  • 网络和安全
  • 预装库
  • 容器复用
  • 示例
  • 流式传输
  • 批量请求
  • 使用量和定价
  • 升级到最新工具版本
  • 变更内容
  • 向后兼容性
  • 升级步骤
  • 编程式工具调用
  • 数据保留
  • 将代码执行与 Agent Skills 一起使用