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

代码执行工具目前处于公开测试阶段。

要使用此功能,请在您的API请求中添加"code-execution-2025-08-25" 测试版头部

我们最近升级了代码执行工具以支持Bash命令和直接文件操作。有关升级到最新工具版本的说明,请参阅升级到最新工具版本

支持的模型

代码执行工具可用于:

  • Claude Opus 4.1 (claude-opus-4-1-20250805)
  • Claude Opus 4 (claude-opus-4-20250514)
  • Claude Sonnet 4 (claude-sonnet-4-20250514)
  • Claude Sonnet 3.7 (claude-3-7-sonnet-20250219)
  • Claude Haiku 3.5 (claude-3-5-haiku-latest)

快速开始

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

curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: code-execution-2025-08-25" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-1-20250805",
        "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"
        }]
    }'

代码执行的工作原理

当您将代码执行工具添加到API请求中时:

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

如何使用该工具

执行Bash命令

要求Claude检查系统信息并安装包:

curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: code-execution-2025-08-25" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": "Check the Python version and list installed packages"
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

直接创建和编辑文件

Claude可以使用文件操作功能直接在沙盒中创建、查看和编辑文件:

curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: code-execution-2025-08-25" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": "Create a config.yaml file with database settings, then update the port from 5432 to 3306"
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

上传和分析您自己的文件

要分析您自己的数据文件(CSV、Excel、图像等),请通过Files API上传它们并在您的请求中引用它们:

将Files API与代码执行一起使用需要两个测试版头部:"anthropic-beta": "code-execution-2025-08-25,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请求中包含代码执行工具
# 首先,上传一个文件
curl https://api.anthropic.com/v1/files \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: files-api-2025-04-14" \
    --form 'file=@"data.csv"' \

# 然后将file_id与代码执行一起使用
curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: code-execution-2025-08-25,files-api-2025-04-14" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": [
                {"type": "text", "text": "Analyze this CSV data"},
                {"type": "container_upload", "file_id": "file_abc123"}
            ]
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

检索生成的文件

当Claude在代码执行期间创建文件时,您可以使用Files API检索这些文件:

from anthropic import Anthropic

# 初始化客户端
client = Anthropic()

# 请求创建文件的代码执行
response = client.beta.messages.create(
    model="claude-opus-4-1-20250805",
    betas=["code-execution-2025-08-25", "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.get('type') == 'code_execution_result':
                for file in content_item.get('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}")

组合操作

使用所有功能的复杂工作流程:

# 首先,上传一个文件
curl https://api.anthropic.com/v1/files \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: files-api-2025-04-14" \
    --form 'file=@"data.csv"' \
    > file_response.json

# 提取file_id(使用jq)
FILE_ID=$(jq -r '.id' file_response.json)

# 然后将其与代码执行一起使用
curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "anthropic-beta: code-execution-2025-08-25,files-api-2025-04-14" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-1-20250805",
        "max_tokens": 4096,
        "messages": [{
            "role": "user",
            "content": [
                {
                    "type": "text", 
                    "text": "Analyze this CSV data: create a summary report, save visualizations, and create a README with the findings"
                },
                {
                    "type": "container_upload", 
                    "file_id": "'$FILE_ID'"
                }
            ]
        }],
        "tools": [{
            "type": "code_execution_20250825",
            "name": "code_execution"
        }]
    }'

工具定义

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

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

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

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

响应格式

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

Bash命令响应

{
  "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_typecontentnumLinesstartLinetotalLines
  • 创建is_file_update(文件是否已存在)
  • 编辑oldStartoldLinesnewStartnewLineslines(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执行超过最大时间限制
所有工具container_expired容器已过期且不再可用
所有工具invalid_tool_input提供给工具的参数无效
所有工具too_many_requests工具使用的速率限制已超过
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)

资源限制

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

网络和安全

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

预安装库

沙盒Python环境包括这些常用库:

  • 数据科学:pandas、numpy、scipy、scikit-learn、statsmodels
  • 可视化:matplotlib、seaborn
  • 文件处理:pyarrow、openpyxl、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请求中重用现有容器。这允许您在请求之间维护创建的文件。

示例

import os
from anthropic import Anthropic

# 初始化客户端
client = Anthropic(
    api_key=os.getenv("ANTHROPIC_API_KEY")
)

# 第一个请求:创建一个包含随机数的文件
response1 = client.beta.messages.create(
    model="claude-opus-4-1-20250805",
    betas=["code-execution-2025-08-25"],
    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.beta.messages.create(
    container=container_id,  # 重用相同的容器
    model="claude-opus-4-1-20250805",
    betas=["code-execution-2025-08-25"],
    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"
    }]
)

流式传输

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

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

使用和定价

The code execution tool usage is tracked separately from token usage. Execution time is a minimum of 5 minutes. If files are included in the request, execution time is billed even if the tool is not used due to files being preloaded onto the container.

Pricing: $0.05 per session-hour.

升级到最新工具版本

通过升级到code-execution-2025-08-25,您可以访问文件操作和Bash功能,包括多种语言的代码。价格没有差异。

变化内容

组件旧版当前
测试版头部code-execution-2025-05-22code-execution-2025-08-25
工具类型code_execution_20250522code_execution_20250825
功能仅PythonBash命令、文件操作
响应类型code_execution_resultbash_code_execution_resulttext_editor_code_execution_result

向后兼容性

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

升级步骤

要升级,您需要在API请求中进行以下更改:

  1. 更新测试版头部

    - "anthropic-beta": "code-execution-2025-05-22"
    + "anthropic-beta": "code-execution-2025-08-25"
    
  2. 更新工具类型

    - "type": "code_execution_20250522"
    + "type": "code_execution_20250825"
    
  3. 检查响应处理(如果以编程方式解析响应):

    • 将不再发送之前的Python执行响应块
    • 相反,将发送Bash和文件操作的新响应类型(请参阅响应格式部分)