Claude 可以分析數據、創建可視化、執行複雜計算、運行系統命令、創建和編輯文件,以及直接在 API 對話中處理上傳的文件。
代碼執行工具允許 Claude 在安全的沙箱環境中運行 Bash 命令和操作文件,包括編寫代碼。
代碼執行工具目前處於公開測試版。要使用此功能,請在您的 API 請求中添加 "code-execution-2025-08-25" 測試版標頭。
模型兼容性
代碼執行工具在以下模型上可用:
| 模型 | 工具版本 |
|---|
Claude Opus 4.1 (claude-opus-4-1-20250805) | code_execution_20250825 |
Claude Opus 4 (claude-opus-4-20250514) | code_execution_20250825 |
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825 |
Claude Sonnet 4 (claude-sonnet-4-20250514) | code_execution_20250825 |
Claude Sonnet 3.7 (claude-3-7-sonnet-20250219) (已棄用) | code_execution_20250825 |
Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825 |
Claude Haiku 3.5 (claude-3-5-haiku-latest) | code_execution_20250825 |
當前版本 code_execution_20250825 支持 Bash 命令和文件操作。還提供了舊版本 code_execution_20250522(僅限 Python)。有關遷移詳情,請參閱升級到最新工具版本。
舊版工具版本不保證與較新模型向後兼容。始終使用與您的模型版本相對應的工具版本。
快速開始
以下是一個簡單的示例,要求 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-sonnet-4-5",
"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 請求中添加代碼執行工具時:
- Claude 評估代碼執行是否有助於回答您的問題
- 該工具自動為 Claude 提供以下功能:
- Bash 命令:執行 shell 命令以進行系統操作和包管理
- 文件操作:直接創建、查看和編輯文件,包括編寫代碼
- Claude 可以在單個請求中使用這些功能的任何組合
- 所有操作都在安全的沙箱環境中運行
- 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-sonnet-4-5",
"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-sonnet-4-5",
"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、圖像等),請通過文件 API 上傳它們,並在您的請求中引用它們:
使用文件 API 與代碼執行需要兩個測試版標頭:"anthropic-beta": "code-execution-2025-08-25,files-api-2025-04-14"
Python 環境可以處理通過文件 API 上傳的各種文件類型,包括:
- CSV
- Excel (.xlsx, .xls)
- JSON
- XML
- 圖像 (JPEG, PNG, GIF, WebP)
- 文本文件 (.txt, .md, .py 等)
上傳和分析文件
- 使用文件 API 上傳您的文件
- 在您的消息中使用
container_upload 內容塊引用該文件
- 在您的 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"' \
# 然後使用文件 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-sonnet-4-5",
"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 在代碼執行期間創建文件時,您可以使用文件 API 檢索這些文件:
from anthropic import Anthropic
# 初始化客戶端
client = Anthropic()
# 請求創建文件的代碼執行
response = client.beta.messages.create(
model="claude-sonnet-4-5",
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.type == 'bash_code_execution_result':
for file in content_item.content:
if hasattr(file, 'file_id'):
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
# 提取文件 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-sonnet-4-5",
"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"
}]
}'
工具定義
代碼執行工具不需要額外參數:
{
"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_type、content、numLines、startLine、totalLines
- 創建:
is_file_update(文件是否已存在)
- 編輯:
oldStart、oldLines、newStart、newLines、lines(差異格式)
每種工具類型都可以返回特定的錯誤:
常見錯誤(所有工具):
{
"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_editor | file_not_found | 文件不存在(用於查看/編輯操作) |
| text_editor | string_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
網絡和安全
- 互聯網訪問:出於安全考慮完全禁用
- 外部連接:不允許出站網絡請求
- 沙箱隔離:與主機系統和其他容器完全隔離
- 文件訪問:僅限於工作區目錄
- 工作區範圍:與文件一樣,容器的範圍限於 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 請求中重用現有容器。
這允許您在請求之間維護創建的文件。
import os
from anthropic import Anthropic
# 初始化客戶端
client = Anthropic(
api_key=os.getenv("ANTHROPIC_API_KEY")
)
# 第一個請求:創建一個包含隨機數的文件
response1 = client.beta.messages.create(
model="claude-sonnet-4-5",
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-sonnet-4-5",
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": ""}}}
批量請求
您可以在消息批處理 API 中包含代碼執行工具。通過消息批處理 API 進行的代碼執行工具調用的定價與常規消息 API 請求中的定價相同。
使用情況和定價
Code execution tool usage is tracked separately from token usage. Execution time has 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.
Each organization receives 50 free hours of usage with the code execution tool per day. Additional usage beyond the first 50 hours is billed at $0.05 per hour, per container.
升級到最新工具版本
通過升級到 code-execution-2025-08-25,您可以訪問文件操作和 Bash 功能,包括多種語言的代碼。沒有價格差異。
變更內容
| 組件 | 舊版 | 當前 |
|---|
| 測試版標頭 | code-execution-2025-05-22 | code-execution-2025-08-25 |
| 工具類型 | code_execution_20250522 | code_execution_20250825 |
| 功能 | 僅限 Python | Bash 命令、文件操作 |
| 響應類型 | code_execution_result | bash_code_execution_result、text_editor_code_execution_result |
向後兼容性
- 所有現有 Python 代碼執行繼續完全按照之前的方式工作
- 現有的僅限 Python 的工作流無需更改
升級步驟
要升級,您需要在 API 請求中進行以下更改:
-
更新測試版標頭:
- "anthropic-beta": "code-execution-2025-05-22"
+ "anthropic-beta": "code-execution-2025-08-25"
-
更新工具類型:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"
-
檢查響應處理(如果以編程方式解析響應):
- 不再發送 Python 執行響應的先前塊
- 相反,將發送 Bash 和文件操作的新響應類型(請參閱響應格式部分)
將代碼執行與代理技能一起使用
代碼執行工具使 Claude 能夠使用代理技能。技能是由說明、腳本和資源組成的模塊化功能,可擴展 Claude 的功能。
在代理技能文檔和代理技能 API 指南中了解更多信息。