Claude 可以分析資料、建立視覺化圖表、執行複雜計算、執行系統指令、建立和編輯檔案,並直接在 API 對話中處理上傳的檔案。
程式碼執行工具允許 Claude 在安全的沙盒環境中執行 Bash 指令和操作檔案,包括編寫程式碼。
程式碼執行工具目前處於公開測試階段。
要使用此功能,請在您的 API 請求中加入 "code-execution-2025-08-25"
測試版標頭 。
我們最近升級了程式碼執行工具,以支援 Bash 指令和直接檔案操作。有關升級到最新工具版本的說明,請參閱升級到最新工具版本 。
支援的模型
程式碼執行工具可用於:
Claude Opus 4.1 (claude-opus-4-1-20250805
)
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-08-25" \
--header "content-type: application/json" \
--data '{
"model" : "claude-opus-4-1-20250805" ,
"max_tokens" : 4096 ,
"messages" : [
{
"role" : "user" ,
"content" : "計算 [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-opus-4-1-20250805" ,
"max_tokens" : 4096 ,
"messages" : [ {
"role" : "user" ,
"content" : "檢查 Python 版本並列出已安裝的套件"
} ] ,
"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-opus-4-1-20250805" ,
"max_tokens" : 4096 ,
"messages" : [ {
"role" : "user" ,
"content" : "建立一個包含資料庫設定的 config.yaml 檔案,然後將連接埠從 5432 更新為 3306"
} ] ,
"tools" : [ {
"type" : "code_execution_20250825" ,
"name" : "code_execution"
} ]
} '
上傳並分析您自己的檔案
要分析您自己的資料檔案(CSV、Excel、圖片等),請透過 Files API 上傳它們並在您的請求中引用它們:
將 Files API 與程式碼執行一起使用需要兩個測試版標頭:"anthropic-beta": "code-execution-2025-08-25,files-api-2025-04-14"
Python 環境可以處理透過 Files API 上傳的各種檔案類型,包括:
CSV
Excel (.xlsx, .xls)
JSON
XML
圖片 (JPEG, PNG, GIF, WebP)
文字檔案 (.txt, .md, .py, 等)
上傳並分析檔案
使用 Files 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"' \
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-1-20250805" ,
"max_tokens" : 4096 ,
"messages" : [ {
"role" : "user" ,
"content" : [
{ "type" : "text" , "text" : "分析這個 CSV 資料" } ,
{ "type" : "container_upload" , "file_id" : "file_abc123" }
]
} ] ,
"tools" : [ {
"type" : "code_execution_20250825" ,
"name" : "code_execution"
} ]
} '
取得產生的檔案
當 Claude 在程式碼執行期間建立檔案時,您可以使用 Files API 取得這些檔案:
from anthropic import Anthropic
client = Anthropic( )
response = client. beta. messages. create(
model= "claude-opus-4-1-20250805" ,
betas= [ "code-execution-2025-08-25" , "files-api-2025-04-14" ] ,
max_tokens= 4096 ,
messages= [ {
"role" : "user" ,
"content" : "建立一個 matplotlib 視覺化圖表並儲存為 output.png"
} ] ,
tools= [ {
"type" : "code_execution_20250825" ,
"name" : "code_execution"
} ]
)
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. 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"已下載: { 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
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-opus-4-1-20250805" ,
"max_tokens" : 4096 ,
"messages" : [ {
"role" : "user" ,
"content" : [
{
"type" : "text" ,
"text" : "分析這個 CSV 資料:建立摘要報告、儲存視覺化圖表,並建立包含發現的 README"
} ,
{
"type" : "container_upload" ,
"file_id" : "'$FILE_ID '"
}
]
} ] ,
"tools" : [ {
"type" : "code_execution_20250825" ,
"name" : "code_execution"
} ]
} '
工具定義
程式碼執行工具不需要額外的參數:
當提供此工具時,Claude 自動獲得兩個子工具的存取權限:
bash_code_execution
:執行 shell 指令
text_editor_code_execution
:檢視、建立和編輯檔案,包括編寫程式碼
回應格式
程式碼執行工具可以根據操作返回兩種類型的結果:
Bash 指令回應
檔案操作回應
檢視檔案:
建立檔案:
編輯檔案(str_replace):
所有執行結果包括:
stdout
:成功執行的輸出
stderr
:執行失敗時的錯誤訊息
return_code
:成功時為 0,失敗時為非零值
檔案操作的額外欄位:
檢視 :file_type
、content
、numLines
、startLine
、totalLines
建立 :is_file_update
(檔案是否已存在)
編輯 :oldStart
、oldLines
、newStart
、newLines
、lines
(差異格式)
每種工具類型都可以返回特定錯誤:
常見錯誤(所有工具):
按工具類型的錯誤代碼:
工具 錯誤代碼 描述 所有工具 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)
資源限制
記憶體 :1GiB RAM
磁碟空間 :5GiB 工作區儲存空間
CPU :1 CPU
網路和安全性
網際網路存取 :為了安全完全停用
外部連線 :不允許出站網路請求
沙盒隔離 :與主機系統和其他容器完全隔離
檔案存取 :僅限於工作區目錄
工作區範圍 :如同 Files ,容器的範圍限定於 API 金鑰的工作區
過期 :容器在建立後 1 小時過期
預安裝程式庫
沙盒 Python 環境包含這些常用程式庫:
資料科學 :pandas、numpy、scipy、scikit-learn、statsmodels
視覺化 :matplotlib、seaborn
檔案處理 :pyarrow、openpyxl、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-opus-4-1-20250805" ,
betas= [ "code-execution-2025-08-25" ] ,
max_tokens= 4096 ,
messages= [ {
"role" : "user" ,
"content" : "寫一個包含隨機數字的檔案並儲存到 '/tmp/number.txt'"
} ] ,
tools= [ {
"type" : "code_execution_20250825" ,
"name" : "code_execution"
} ]
)
container_id = response1. container. id
response2 = client. beta. messages. create(
container= container_id,
model= "claude-opus-4-1-20250805" ,
betas= [ "code-execution-2025-08-25" ] ,
max_tokens= 4096 ,
messages= [ {
"role" : "user" ,
"content" : "從 '/tmp/number.txt' 讀取數字並計算其平方"
} ] ,
tools= [ {
"type" : "code_execution_20250825" ,
"name" : "code_execution"
} ]
)
啟用串流後,您將在程式碼執行事件發生時收到它們:
批次請求
您可以在 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.
升級到最新工具版本
透過升級到 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 請求中進行以下變更:
更新測試版標頭 :
更新工具類型 :
檢視回應處理 (如果以程式方式解析回應):
不再發送先前的 Python 執行回應區塊
相反,將發送 Bash 和檔案操作的新回應類型(請參閱回應格式部分)