代码执行工具允许Claude在安全的沙盒环境中执行Python代码。 Claude可以分析数据、创建可视化图表、执行复杂计算,以及在API对话中直接处理上传的 文件。

此功能需要测试版标头"anthropic-beta": "code-execution-2025-05-22"

支持的模型

代码执行工具可用于:

  • 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-05-22" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-20250514",
        "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_20250522",
            "name": "code_execution"
        }]
    }'

代码执行的工作原理

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

  1. Claude评估代码执行是否有助于回答您的问题
  2. Claude在安全的沙盒环境中编写并执行Python代码
  3. 在单个请求中可能会多次执行代码
  4. Claude提供结果,包括任何生成的图表、计算或分析

工具定义

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

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

响应格式

以下是带有代码执行的示例响应:

{
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "I'll calculate the mean and standard deviation for you."
    },
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2",
      "name": "code_execution",
      "input": {
        "code": "import numpy as np\ndata = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\nmean = np.mean(data)\nstd = np.std(data)\nprint(f\"Mean: {mean}\")\nprint(f\"Standard deviation: {std}\")"
      }
    },
    {
      "type": "code_execution_tool_result",
      "tool_use_id": "srvtoolu_01A2B3C4D5E6F7G8H9I0J1K2",
      "content": {
        "type": "code_execution_result",
        "stdout": "Mean: 5.5\nStandard deviation: 2.8722813232690143\n",
        "stderr": "",
        "return_code": 0
      }
    },
    {
      "type": "text",
      "text": "The mean of the dataset is 5.5 and the standard deviation is approximately 2.87."
    }
  ],
  "id": "msg_01BqK2v4FnRs4xTjgL8EuZxz",
  "model": "claude-opus-4-20250514",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 45,
    "output_tokens": 187,
    "server_tool_use": {
      "execution_time_seconds": 1.5
    }
  }
}

结果

代码执行结果包括:

  • stdout:来自打印语句和成功执行的输出
  • stderr:如果代码执行失败的错误消息
  • return_code(0表示成功,非零表示失败)
{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_01ABC123",
  "content": {
    "type": "code_execution_result",
    "stdout": "",
    "stderr": "NameError: name 'undefined_variable' is not defined",
    "return_code": 1
  }
}

错误

如果使用工具时出现错误,将会有一个code_execution_tool_result_error

{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_01VfmxgZ46TiHbmXgy928hQR",
  "content": {
    "type": "code_execution_tool_result_error",
    "error_code": "unavailable"
  }
}

可能的错误包括

  • unavailable:代码执行工具不可用
  • code_execution_exceeded:执行时间超过了允许的最大值
  • container_expired:容器已过期且不可用

pause_turn 停止原因

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

容器

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

运行环境

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

资源限制

  • 内存:1GiB RAM
  • 磁盘空间:5GiB工作空间存储
  • CPU:1个CPU
  • 执行超时:执行时间在消息请求中有限制,可以通过max_execution_duration参数控制
  • 容器过期:在1小时不活动后,容器将无法再次访问

网络和安全

  • 互联网访问:出于安全考虑完全禁用
  • 外部连接:不允许向外发出网络请求
  • 沙盒隔离:与主机系统和其他容器完全隔离
  • 文件访问:仅限于工作空间目录

预安装库

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

  • 数据科学:pandas, numpy, scipy, scikit-learn, statsmodels
  • 可视化:matplotlib, seaborn
  • 文件处理:pyarrow, openpyxl, xlrd, pillow
  • 数学与计算:sympy, mpmath
  • 实用工具:tqdm, python-dateutil, pytz, joblib

在代码执行中使用文件

代码执行可以分析通过Files API上传的文件,如CSV文件、Excel文件和其他数据格式。 这允许Claude读取、处理并从您的数据中生成见解。

将Files API与代码执行一起使用需要两个测试版标头:"anthropic-beta": "code-execution-2025-05-22,files-api-2025-04-14"

支持的文件类型

Python环境能够处理但不限于以下文件类型

  • 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-05-22,files-api-2025-04-14" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-20250514",
        "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_20250522",
            "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请求中的相同。

使用和定价

代码执行工具的使用与令牌使用分开跟踪。执行时间最少为5分钟。 如果请求中包含文件,即使由于文件被预加载到容器上而未使用该工具,也会计费执行时间。

定价:每会话小时$0.05。