Was this page helpful?
Claude 可以直接在 API 對話中分析資料、建立視覺化圖表、執行複雜計算、執行系統命令、建立和編輯檔案,以及處理上傳的檔案。 程式碼執行工具允許 Claude 在安全的沙箱環境中執行 Bash 命令和操作檔案,包括撰寫程式碼。
程式碼執行工具可在以下模型上使用:
| 模型 | 工具版本 |
|---|---|
Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825 |
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825 |
Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825 |
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 (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 執行計算的簡單範例:
當您將程式碼執行工具加入 API 請求時:
要求 Claude 檢查系統資訊並安裝套件:
Claude 可以使用檔案操作功能直接在沙箱中建立、檢視和編輯檔案:
要分析您自己的資料檔案(CSV、Excel、圖片等),請透過 Files API 上傳它們,並在您的請求中引用:
將 Files API 與程式碼執行搭配使用需要兩個 beta 標頭:"anthropic-beta": "code-execution-2025-08-25,files-api-2025-04-14"
Python 環境可以處理透過 Files API 上傳的各種檔案類型,包括:
container_upload 內容區塊引用該檔案當 Claude 在程式碼執行期間建立檔案時,您可以使用 Files API 擷取這些檔案:
使用所有功能的複雜工作流程:
程式碼執行工具不需要額外參數:
{
"type": "code_execution_20250825",
"name": "code_execution"
}當提供此工具時,Claude 會自動獲得兩個子工具的存取權限:
bash_code_execution:執行 shell 命令text_editor_code_execution:檢視、建立和編輯檔案,包括撰寫程式碼程式碼執行工具可以根據操作返回兩種類型的結果:
{
"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、totalLinesis_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 |
pause_turn 停止原因回應可能包含 pause_turn 停止原因,這表示 API 暫停了一個長時間執行的回合。您可以將回應原樣提供在後續請求中,讓 Claude 繼續其回合,或者如果您希望中斷對話,可以修改內容。
程式碼執行工具在專為程式碼執行設計的安全容器化環境中運行,特別著重於 Python。
沙箱化的 Python 環境包含這些常用函式庫:
您可以透過提供先前回應中的容器 ID,在多個 API 請求之間重複使用現有容器。這允許您在請求之間維護已建立的檔案。
啟用串流後,您將在程式碼執行事件發生時即時接收:
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "code_execution"}}
// Code execution streamed
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())\"}"}}
// Pause while code executes
// Execution results streamed
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 請求中的相同。
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 1,550 free hours of usage with the code execution tool per month. Additional usage beyond the first 1,550 hours is billed at $0.05 per hour, per container.
透過升級至 code-execution-2025-08-25,您可以獲得檔案操作和 Bash 功能的存取權限,包括多種語言的程式碼。價格沒有差異。
| 元件 | 舊版 | 目前版本 |
|---|---|---|
| Beta 標頭 | 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 |
要升級,您需要在 API 請求中進行以下變更:
更新 beta 標頭:
- "anthropic-beta": "code-execution-2025-05-22"
+ "anthropic-beta": "code-execution-2025-08-25"更新工具類型:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"檢查回應處理(如果以程式方式解析回應):
程式碼執行工具支援程式化工具呼叫,允許 Claude 在執行容器中撰寫程式碼來以程式方式呼叫您的自訂工具。這使得高效的多工具工作流程、在到達 Claude 上下文之前進行資料過濾,以及複雜的條件邏輯成為可能。
# Enable programmatic calling for your tools
response = client.beta.messages.create(
model="claude-opus-4-6",
betas=["advanced-tool-use-2025-11-20"],
max_tokens=4096,
messages=[{
"role": "user",
"content": "Get weather for 5 cities and find the warmest"
}],
tools=[
{
"type": "code_execution_20250825",
"name": "code_execution"
},
{
"name": "get_weather",
"description": "Get weather for a city",
"input_schema": {...},
"allowed_callers": ["code_execution_20250825"] # Enable programmatic calling
}
]
)在程式化工具呼叫文件中了解更多。
程式碼執行工具使 Claude 能夠使用 Agent Skills。Skills 是由指令、腳本和資源組成的模組化功能,可擴展 Claude 的能力。
在 Agent Skills 文件和 Agent Skills API 指南中了解更多。
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-6",
"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"
}]
}'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-6",
"max_tokens": 4096,
"messages": [{
"role": "user",
"content": "Check the Python version and list installed packages"
}],
"tools": [{
"type": "code_execution_20250825",
"name": "code_execution"
}]
}'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-6",
"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"
}]
}'# First, upload a file
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"' \
# Then use the file_id with code execution
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-6",
"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"
}]
}'from anthropic import Anthropic
# Initialize the client
client = Anthropic()
# Request code execution that creates files
response = client.beta.messages.create(
model="claude-opus-4-6",
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"
}]
)
# Extract file IDs from the response
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
# Download the created files
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}")# First, upload a file
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
# Extract file_id (using jq)
FILE_ID=$(jq -r '.id' file_response.json)
# Then use it with code execution
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-6",
"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"
}]
}'string_not_found |
在檔案中找不到 old_str(用於 str_replace) |
import os
from anthropic import Anthropic
# Initialize the client
client = Anthropic(
api_key=os.getenv("ANTHROPIC_API_KEY")
)
# First request: Create a file with a random number
response1 = client.beta.messages.create(
model="claude-opus-4-6",
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"
}]
)
# Extract the container ID from the first response
container_id = response1.container.id
# Second request: Reuse the container to read the file
response2 = client.beta.messages.create(
container=container_id, # Reuse the same container
model="claude-opus-4-6",
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"
}]
)