Claude 可以直接在 API 對話中分析資料、建立視覺化圖表、執行複雜計算、執行系統命令、建立和編輯檔案,以及處理上傳的檔案。程式碼執行工具讓 Claude 能夠在安全的沙箱環境中執行 Bash 命令並操作檔案,包括撰寫程式碼。
當與網頁搜尋或網頁擷取(web_search_20260209、web_fetch_20260209 或更新版本)一起使用時,程式碼執行是免費的。 當您的請求中包含其中一個工具時,該請求中的程式碼執行除了標準 token 費用外不會產生額外費用。這涵蓋了動態過濾背後的程式碼執行以及 Claude 直接執行的任何程式碼。當未包含這些工具時,則適用標準的程式碼執行定價。
程式碼執行也為網頁搜尋和網頁擷取工具中的動態過濾提供支援:Claude 會在程式碼執行環境中過濾結果,然後才將其送入上下文視窗。當動態過濾執行時,API 會自動為該請求配置所需的程式碼執行,因此您不需要為此在請求中加入程式碼執行工具。
請透過意見回饋表單分享您對此功能的意見回饋。
關於「zero data retention」(零資料保留),即 ZDR 如何適用於此功能,請參閱 API 與資料保留。
程式碼執行工具可在以下模型上使用:
| 模型 | 工具版本 |
|---|---|
| Claude Opus 5 (claude-opus-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Fable 5 (claude-fable-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Mythos 5 (claude-mythos-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 5 (claude-sonnet-5) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.8 (claude-opus-4-8) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.7 (claude-opus-4-7) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.6 (claude-opus-4-6) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.6 (claude-sonnet-4-6) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.5 (claude-opus-4-5-20251101) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Sonnet 4.5 (claude-sonnet-4-5-20250929) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Haiku 4.5 (claude-haiku-4-5-20251001) | code_execution_20250825、code_execution_20260120、code_execution_20260521 |
| Claude Opus 4.1 (claude-opus-4-1-20250805)(已棄用,請參閱模型棄用) | code_execution_20250825 |
每個工具版本都建立在前一個版本的基礎上:
code_execution_20250825 支援 Bash 命令和檔案操作,並且可在表格中的每個模型上使用。code_execution_20260120 新增了 REPL 狀態持久化以及從沙箱內進行程式化工具呼叫的功能。Claude Haiku 4.5 接受 code_execution_20260120 和 code_execution_20260521 工具類型,但程式化工具呼叫以及依賴它的 REPL 狀態持久化在該模型上不可用,因此較新的版本在該模型上的行為與 code_execution_20250825 相同。code_execution_20260521 與 code_execution_20260120 是相同的執行環境。差異在於工具描述會告知 Claude 程式化工具呼叫中每個 Python 儲存格有 90 秒的實際時間(wall-clock)限制,因此 Claude 可以為長時間執行的儲存格做好規劃。超過限制的儲存格會回傳正常的程式碼執行結果,其中包含非零的 return_code 以及輸出中的 detection_timeout 狀態訊息。這與 execution_time_exceeded 錯誤代碼不同,後者是當整個工具呼叫超過最大執行時間時由 API 回傳的。這三個工具版本均已正式推出,不需要 anthropic-beta 標頭。舊版的程式碼執行 beta 標頭仍然是有效的選用項目。
本頁的範例使用 code_execution_20250825,因為表格中的每個模型都支援它。目前的網頁搜尋和網頁擷取工具(web_search_20260209、web_fetch_20260209 及更新版本)需要 code_execution_20260120 或更新版本作為其程式碼執行版本。
如果您仍在使用舊版的 code_execution_20250522(僅限 Python),請參閱升級至最新工具版本以從中遷移。
較舊的工具版本不保證與較新的模型向後相容。請務必使用與您的模型版本相對應的工具版本。
程式碼執行可在以下平台使用:
程式碼執行目前無法在 Amazon Bedrock 或 Google Cloud 上使用。
對於 Claude Mythos Preview,程式碼執行僅在 Claude API 和 Microsoft Foundry 上受支援。Mythos Preview 在 Amazon Bedrock、Claude Platform on AWS 或 Google Cloud 上無法使用此功能。
以下是一個要求 Claude 執行計算的範例:
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=4096,
messages=[
{
"role": "user",
"content": "Use the code execution tool to 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"}],
)
print(response.to_json())回應會將 server_tool_use 區塊(Claude 執行的命令)與其工具結果區塊交錯排列,後面接著 Claude 的文字。頂層還包含一個 container 物件,您可以在多個請求之間重複使用其 id。請參閱回應格式以了解區塊的結構。
當您將程式碼執行工具加入 API 請求時:
tool_result 區塊。一個例外是當 Claude 在程式碼執行的同時呼叫您的其中一個用戶端工具時:API 會回傳程式碼執行呼叫但不含其結果。結果會在您回傳用戶端工具的 tool_result 區塊之後,在後續的回應中送達容器已預先安裝 Python。Claude 使用檔案操作子工具撰寫 Python,並使用 Bash 命令執行它。使用 code_execution_20260120 或更新版本以及程式化工具呼叫時,Python 直譯器狀態(例如變數繫結)也會在重複使用容器的請求之間持續存在。
當請求能從計算或檔案處理中受益時,Claude 會執行程式碼:
對於以下情況,Claude 會直接回答而不執行程式碼:
如果您希望 Claude 為邊界情況的請求執行程式碼,請明確要求(例如「執行程式碼來驗證這一點」)。
若要分析您自己的資料檔案(例如 CSV、Excel 或圖片),請透過 Files API 上傳它們並在您的請求中引用:
將 Files API 與程式碼執行一起使用需要 Files API beta 標頭:"anthropic-beta": "files-api-2025-04-14"
Python 環境可以處理透過 Files API 上傳的各種檔案類型,包括:
container_upload 內容區塊引用該檔案client = anthropic.Anthropic()
# 上傳檔案
file_object = client.beta.files.upload(file=Path("data.csv"))
# 將 file_id 與程式碼執行搭配使用
response = client.beta.messages.create(
model="claude-opus-5",
betas=["files-api-2025-04-14"],
max_tokens=4096,
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this CSV data"},
{"type": "container_upload", "file_id": file_object.id},
],
}
],
tools=[{"type": "code_execution_20250825", "name": "code_execution"}],
)
print(response.to_json())當 Claude 在程式碼執行期間建立檔案時,每個建立的檔案 ID 都會出現在程式碼執行工具結果中,您可以使用 Files API 下載它:
client = Anthropic()
# 請求執行會建立檔案的程式碼
response = client.beta.messages.create(
model="claude-opus-5",
betas=["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: BetaMessage) -> list[str]:
file_ids: list[str] = []
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 output_block in content_item.content:
file_ids.append(output_block.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}")程式碼執行工具不需要額外的參數:
{
"type": "code_execution_20250825",
"name": "code_execution"
}這兩個欄位都是固定的:type 選擇工具版本,而 name 必須是 code_execution。
當您提供此工具時,Claude 會自動獲得兩個子工具的存取權限:
bash_code_execution:執行 shell 命令text_editor_code_execution:檢視、建立和編輯檔案,包括撰寫程式碼當 Claude 執行程式碼時,回應還會包含一個頂層的 container 物件,其中包含容器的 id 和 expires_at 時間戳記。將該 ID 傳回頂層的 container 請求參數中,即可繼續使用同一個容器。請參閱容器重複使用。
程式碼執行工具可以根據操作回傳兩種類型的結果:
{
"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,
"content": []
}
}檢視檔案:
{
"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_view_result",
"file_type": "text",
"content": "{\n \"setting\": \"value\",\n \"debug\": true\n}",
"num_lines": 4,
"start_line": 1,
"total_lines": 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_create_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_str_replace_result",
"old_start": 3,
"old_lines": 1,
"new_start": 3,
"new_lines": 1,
"lines": ["- \"debug\": true", "+ \"debug\": false"]
}
}Bash 命令結果(bash_code_execution_result)包含:
stdout:成功執行的輸出stderr:執行失敗時的錯誤訊息return_code:0 表示成功,非零表示失敗content:一個清單,其中每個項目對應命令建立的一個檔案。每個項目都帶有 file_id,可用於透過 Files API 擷取檔案檔案操作結果有其自己的欄位:
text_editor_code_execution_view_result):file_type、content、num_lines、start_line、total_linestext_editor_code_execution_create_result):is_file_update(檔案是否已存在)text_editor_code_execution_str_replace_result):old_start、old_lines、new_start、new_lines、lines(diff 格式)每種工具類型都可能回傳特定的錯誤:
常見錯誤(所有工具):
{
"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 | 工具呼叫超過最大執行時間 |
| 所有工具 | invalid_tool_input | 提供給工具的參數無效 |
| 所有工具 | too_many_requests | 工具使用超過速率限制 |
| bash | output_file_too_large | 命令輸出超過最大大小 |
| text_editor | file_not_found | 檔案不存在(針對檢視/編輯操作) |
已過期的容器無法重複使用:引用它的請求會回傳錯誤,而不是還原它。請在不帶 container 參數的情況下再次發送請求以取得新容器。
pause_turn 停止原因回應可能包含 pause_turn 停止原因,這表示 API 暫停了一個長時間執行的回合。您可以在後續請求中原樣提供該回應,讓 Claude 繼續其回合,或者如果您想中斷對話,也可以修改內容。
程式碼執行工具在專為程式碼執行設計的安全容器化環境中執行,並更著重於 Python。
execution_time_exceeded 錯誤。使用程式化工具呼叫時,每個 REPL 儲存格也有 90 秒的實際時間限制沙箱 Python 環境包含以下常用函式庫:
容器還包含命令列工具,例如 unzip、unrar、7zip、bc、rg(ripgrep)、fd 和 sqlite。
容器沒有網際網路存取權限,因此 Claude 無法在執行時下載或安裝額外的套件:只有預先安裝的函式庫可用。
您可以透過提供先前回應中的容器 ID,在多個 API 請求之間重複使用現有的容器。這讓您可以在請求之間保留已建立的檔案。使用 code_execution_20260120 或更新版本以及程式化工具呼叫時,Python 直譯器狀態也會持續存在。
容器在建立後 30 天過期。在大約 5 分鐘的閒置後,容器會被建立檢查點(checkpoint),在 30 天期限內發送帶有其 ID 的請求會將其還原。回應的 container 物件中的 expires_at 時間戳記是一個較短的滾動值,並不代表 30 天的限制。已過期的容器無法重複使用。請在不帶 container 參數的情況下再次發送請求以取得新容器。
client = anthropic.Anthropic()
# 第一個請求:在新容器中建立一個包含隨機數字的檔案
response1 = client.messages.create(
model="claude-opus-5",
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,讓 Claude 重複使用同一個容器
response2 = client.messages.create(
container=response1.container.id,
model="claude-opus-5",
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"}],
)
print(response2.to_json())當您將程式碼執行與同樣會執行程式碼的用戶端提供工具(例如 Bash 工具或自訂 REPL)一起提供時,Claude 是在多電腦環境中運作。程式碼執行工具在 Anthropic 的沙箱容器中執行,而您的用戶端提供工具則在您控制的獨立環境中執行。Claude 有時會混淆這些環境,嘗試使用錯誤的工具或假設它們之間共享狀態。
為了避免這種情況,請在您的系統提示中加入說明以釐清兩者的區別:
When multiple code execution environments are available, be aware that:
- Variables, files, and state do NOT persist between different execution environments
- Use the code_execution tool for general-purpose computation in Anthropic's sandboxed environment
- Use client-provided execution tools (e.g., bash) when you need access to the user's local system, files, or data
- If you need to pass results between environments, explicitly include outputs in subsequent tool calls rather than assuming shared state當將程式碼執行與網頁搜尋或網頁擷取結合使用時,這一點尤其重要,因為它們會自動啟用程式碼執行。如果您的應用程式已經提供了用戶端 shell 工具,自動的程式碼執行會建立第二個執行環境,Claude 需要區分這兩者。
當 Claude 在程式碼執行的同時呼叫您的其中一個用戶端工具時,API 會回傳程式碼執行呼叫但不含其結果。結果會在您回傳用戶端工具的 tool_result 區塊之後,在後續的回應中送達。
啟用串流("stream": true)後,您將在程式碼執行事件發生時收到它們。子工具輸入會以 input_json_delta 事件串流,而每個結果區塊會在單一 content_block_start 事件中完整送達:
event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "bash_code_execution"}}
// Tool input streamed as partial JSON
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"command\": \"python analyze.py\"}"}}
// Pause while the command runs
// Execution result delivered as a complete block
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "bash_code_execution_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": {"type": "bash_code_execution_result", "stdout": " A B C\n0 1 2 3\n1 4 5 6", "stderr": "", "return_code": 0, "content": []}}}您可以在 Messages Batches API 中包含程式碼執行工具。透過 Messages Batches API 進行的程式碼執行工具呼叫,其定價與一般 Messages API 請求中的相同。
程式碼執行在與網路搜尋或網路擷取一起使用時是免費的。 當您的 API 請求中包含 web_search_20260209(或更新版本)或 web_fetch_20260209(或更新版本)時,除了標準的輸入和輸出 token 費用外,程式碼執行工具呼叫不會產生額外費用。
在不使用這些工具的情況下,程式碼執行會依執行時間計費,與 token 使用量分開追蹤:
程式碼執行使用量會在回應中追蹤:
{
"usage": {
"input_tokens": 105,
"output_tokens": 239,
"server_tool_use": {
"code_execution_requests": 1
}
}
}最新的工具版本是 code_execution_20260521。若要在三個目前的版本之間切換,請更新請求中的 type 字串:這三個版本都會回傳回應格式中記載的回應區塊。請參閱模型相容性以了解每個版本新增的功能以及哪些模型支援它。
本節的其餘部分涵蓋從舊版僅限 Python 的 code_execution_20250522 遷移到目前工具版本的方法。
| 元件 | 舊版 | 目前版本 |
|---|---|---|
| Beta 標頭 | code-execution-2025-05-22 | 不需要 |
| 工具類型 | code_execution_20250522 | code_execution_20250825 或更新版本 |
| 功能 | 僅限 Python | Bash 命令、檔案操作 |
| 回應類型 | code_execution_result | bash_code_execution_result、text_editor_code_execution_*_result |
若要升級,請更新 API 請求中的工具類型:
- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"檢閱回應處理(如果以程式化方式解析回應):
程式碼執行在伺服器端沙箱容器中執行。容器資料(包括執行產物、上傳的檔案和輸出)最多保留 30 天。此保留政策適用於容器環境中處理的所有資料。程式碼執行在 Files API 中建立的檔案(可透過 client.beta.files.download() 擷取)會持續存在,直到被明確刪除。
有關所有功能的 ZDR 資格,請參閱 API 與資料保留。
將速度較快的執行者模型與智慧程度較高的顧問模型配對,後者可在生成過程中提供策略性指導。
從在程式碼執行容器內執行的程式碼中呼叫您自己的工具。
上傳檔案進行分析,並下載程式碼執行建立的檔案。
了解如何使用 Agent Skills 透過 API 擴展 Claude 的功能。
Was this page helpful?