程式碼執行工具允許 Claude 在安全、沙盒化的環境中執行 Python 程式碼。 Claude 可以分析資料、建立視覺化圖表、執行複雜計算,以及直接在 API 對話中處理上傳的 檔案。

此功能需要 beta 標頭: "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:來自 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 繼續其回合,或者修改內容如果您 希望中斷對話。

容器

程式碼執行工具在專為 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

在程式碼執行中使用檔案

程式碼執行可以分析通過檔案 API 上傳的檔案,例如 CSV 檔案、Excel 檔案和其他資料格式。 這允許 Claude 讀取、處理並從您的資料中生成洞見。

在程式碼執行中使用檔案 API 需要兩個 beta 標頭:"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. 上傳您的檔案 使用 檔案 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": ""}}}

批次請求

您可以在 訊息批次 API 中包含程式碼執行工具。通過訊息批次 API 的程式碼執行工具調用的價格與常規訊息 API 請求中的相同。

使用和定價

程式碼執行工具的使用與 token 使用分開追蹤。執行時間最少為 5 分鐘。 如果請求中包含檔案,即使由於檔案被預先載入到容器中而未使用該工具,也會計費執行時間。

定價:每個會話小時 $0.05。