程式碼執行工具允許 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",
  "container": {
    "id": "container_011CPR5CNjB747bTd36fQLFk",
    "expires_at": "2025-05-23T21:13:31.749448Z"
  },
  "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,
  }
}

結果

程式碼執行結果包括:

  • stdout:來自 print 語句和成功執行的輸出
  • 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 繼續其回合,或者如果您 希望中斷對話,可以修改內容。

在程式碼執行中使用檔案

程式碼執行可以分析透過 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"
        }]
    }'

檢索由程式碼執行建立的檔案

當 Claude 在程式碼執行期間建立檔案時(例如,儲存 matplotlib 圖表、生成 CSV),您可以使用 Files API 檢索這些檔案:

from anthropic import Anthropic

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

# 請求建立檔案的程式碼執行
response = client.beta.messages.create(
    model="claude-opus-4-20250514",
    betas=["code-execution-2025-05-22", "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_20250522",
        "name": "code_execution"
    }]
)

# 從回應中提取檔案 ID
def extract_file_ids(response):
    file_ids = []
    for item in response.content:
        if item.type == '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}")

容器

程式碼執行工具在專為 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
  • 檔案處理:pyarrow、openpyxl、xlrd、pillow
  • 數學與計算:sympy、mpmath
  • 工具程式:tqdm、python-dateutil、pytz、joblib

容器重複使用

您可以透過提供先前回應中的容器 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-20250514",
    betas=["code-execution-2025-05-22"],
    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_20250522",
        "name": "code_execution"
    }]
)

# 從第一個回應中提取容器 ID
container_id = response1.container.id

# 第二個請求:重複使用容器來讀取檔案
response2 = client.beta.messages.create(
    container=container_id,  # 重複使用相同的容器
    model="claude-opus-4-20250514",
    betas=["code-execution-2025-05-22"],
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": "Read the number from '/tmp/number.txt' and calculate its square"
    }],
    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 請求中的定價相同。

使用方式和定價

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.