Loading...
  • 建構
  • 管理
  • 模型與定價
  • 客戶端 SDK
  • API 參考
Search...
⌘K
Log in
程式碼執行工具
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
建構/工具

程式碼執行工具

在沙箱容器中執行 Python 和 bash 程式碼,以分析資料、產生檔案並反覆改進解決方案。

Claude 可以分析資料、建立視覺化、執行複雜計算、執行系統命令、建立和編輯檔案,以及直接在 API 對話中處理上傳的檔案。程式碼執行工具允許 Claude 在安全的沙箱環境中執行 Bash 命令和操作檔案,包括編寫程式碼。

當與網路搜尋或網路擷取搭配使用時,程式碼執行是免費的。 當您的請求中包含 web_search_20260209 或 web_fetch_20260209 時,程式碼執行工具呼叫不會產生額外費用,超過標準的輸入和輸出代幣成本。當不包含這些工具時,標準程式碼執行費用適用。

程式碼執行是建立高效能代理的核心基元。它在網路搜尋和網路擷取工具中啟用動態篩選,允許 Claude 在結果到達上下文視窗之前處理結果,提高準確性同時降低代幣消耗。

透過意見回饋表單分享您對此功能的意見回饋。

This feature is not eligible for Zero Data Retention (ZDR). Data is retained according to the feature's standard retention policy.

模型相容性

程式碼執行工具在以下模型上可用:

模型工具版本
Claude Opus 4.7 (claude-opus-4-7)code_execution_20250825, code_execution_20260120
Claude Opus 4.6 (claude-opus-4-6)code_execution_20250825, code_execution_20260120
Claude Sonnet 4.6 (claude-sonnet-4-6)code_execution_20250825, code_execution_20260120
Claude Opus 4.5 (claude-opus-4-5-20251101)code_execution_20250825, code_execution_20260120
Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)code_execution_20250825, code_execution_20260120
Claude Haiku 4.5 (claude-haiku-4-5-20251001)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 3.5 (claude-3-5-haiku-latest) (已棄用)code_execution_20250825

code_execution_20250825 支援 Bash 命令和檔案操作,在上面列出的每個模型上都可用。code_execution_20260120 新增 REPL 狀態持久性和程式化工具呼叫(來自沙箱內),僅在 Opus 4.5+ 和 Sonnet 4.5+ 上可用。舊版本 code_execution_20250522(僅限 Python)也在與 code_execution_20250825 相同的模型上可用;請參閱升級到最新工具版本以從其遷移。

舊版工具版本不保證與較新模型向後相容。始終使用與您的模型版本相對應的工具版本。

平台可用性

程式碼執行在以下平台上可用:

  • Claude API(Anthropic)
  • Microsoft Azure AI Foundry

程式碼執行目前在 Amazon Bedrock 或 Google Vertex AI 上不可用。

對於 Claude Mythos Preview,程式碼執行在 Claude API 和 Microsoft Foundry 上受支援。它在 Amazon Bedrock 或 Google Vertex AI 上的 Mythos Preview 上不可用。

快速開始

以下是一個簡單的範例,要求 Claude 執行計算:

程式碼執行的運作方式

當您將程式碼執行工具新增到您的 API 請求時:

  1. Claude 評估程式碼執行是否有助於回答您的問題
  2. 該工具自動為 Claude 提供以下功能:
    • Bash 命令:執行 shell 命令以進行系統操作和套件管理
    • 檔案操作:直接建立、檢視和編輯檔案,包括編寫程式碼
  3. Claude 可以在單一請求中使用這些功能的任何組合
  4. 所有操作都在安全的沙箱環境中執行
  5. Claude 提供結果以及任何產生的圖表、計算或分析

將程式碼執行與其他執行工具搭配使用

當您提供程式碼執行以及也執行程式碼的用戶端提供工具(例如 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 需要在其中進行區分。

如何使用該工具

上傳並分析您自己的文件

要分析您自己的數據文件(CSV、Excel、圖像等),請通過 Files API 上傳它們,並在您的請求中引用它們:

使用 Files API 與代碼執行需要 Files API 測試版標頭:"anthropic-beta": "files-api-2025-04-14"

Python 環境可以處理通過 Files API 上傳的各種文件類型,包括:

  • CSV
  • Excel (.xlsx, .xls)
  • JSON
  • XML
  • 圖像 (JPEG, PNG, GIF, WebP)
  • 文本文件 (.txt, .md, .py 等)

上傳並分析文件

  1. 使用 Files API 上傳您的文件
  2. 在您的消息中使用 container_upload 內容塊引用該文件
  3. 在您的 API 請求中包含代碼執行工具

檢索生成的文件

當 Claude 在代碼執行期間創建文件時,您可以使用 Files API 檢索這些文件:

工具定義

代碼執行工具不需要任何額外參數:

JSON
{
  "type": "code_execution_20250825",
  "name": "code_execution"
}

提供此工具時,Claude 會自動獲得對兩個子工具的訪問權限:

  • bash_code_execution:運行 shell 命令
  • text_editor_code_execution:查看、創建和編輯文件,包括編寫代碼

響應格式

代碼執行工具可以根據操作返回兩種類型的結果:

Bash 命令響應

Output
{
  "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
  }
}

文件操作響應

查看文件:

Output
{
  "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
  }
}

創建文件:

Output
{
  "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):

Output
{
  "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(差異格式)

錯誤

每種工具類型都可以返回特定的錯誤:

常見錯誤(所有工具):

Output
{
  "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工具使用超過速率限制
bashoutput_file_too_large命令輸出超過最大大小
text_editor

pause_turn 停止原因

響應可能包括 pause_turn 停止原因,表示 API 暫停了長時間運行的輪次。您可以在後續請求中按原樣提供響應以讓 Claude 繼續其輪次,或者如果您想中斷對話,可以修改內容。

容器

代碼執行工具在專為代碼執行設計的安全容器化環境中運行,特別關注 Python。

運行時環境

  • Python 版本:3.11.12
  • 操作系統:基於 Linux 的容器
  • 架構:x86_64 (AMD64)

資源限制

  • 內存:5GiB RAM
  • 磁盤空間:5GiB 工作區存儲
  • CPU:1 個 CPU

網絡和安全

  • 互聯網訪問:出於安全考慮完全禁用
  • 外部連接:不允許出站網絡請求
  • 沙箱隔離:與主機系統和其他容器完全隔離
  • 文件訪問:僅限於工作區目錄
  • 工作區範圍:與 Files 一樣,容器的範圍限定於 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 請求中重用現有容器。這允許您在請求之間維護創建的文件。

範例

串流

啟用串流後,您將在程式碼執行事件發生時接收它們:

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": ""}}}

批次請求

您可以在 Messages Batches API 中包含程式碼執行工具。透過 Messages Batches API 的程式碼執行工具呼叫的定價與常規 Messages API 請求中的相同。

使用量和定價

Code execution is free when used with web search or web fetch. When web_search_20260209 or web_fetch_20260209 is included in your API request, there are no additional charges for code execution tool calls beyond the standard input and output token costs.

When used without these tools, code execution is billed by execution time, tracked separately from token usage:

  • Execution time has a minimum of 5 minutes
  • Each organization receives 1,550 free hours of usage per month
  • Additional usage beyond 1,550 hours is billed at $0.05 per hour, per container
  • If files are included in the request, execution time is billed even if the tool is not invoked, due to files being preloaded onto the container

Code execution usage is tracked in the response:

"usage": {
  "input_tokens": 105,
  "output_tokens": 239,
  "server_tool_use": {
    "code_execution_requests": 1
  }
}

升級到最新工具版本

透過升級到 code-execution-2025-08-25,您可以存取檔案操作和 Bash 功能,包括多種語言的程式碼。沒有價格差異。

變更內容

元件舊版目前版本
Beta 標頭code-execution-2025-05-22code-execution-2025-08-25
工具類型code_execution_20250522code_execution_20250825
功能僅 PythonBash 命令、檔案操作
回應類型code_execution_resultbash_code_execution_result、text_editor_code_execution_result

向後相容性

  • 所有現有的 Python 程式碼執行繼續完全按照之前的方式工作
  • 現有的僅 Python 工作流程無需任何變更

升級步驟

若要升級,請更新 API 請求中的工具類型:

- "type": "code_execution_20250522"
+ "type": "code_execution_20250825"

檢查回應處理(如果以程式設計方式解析回應):

  • 不再傳送 Python 執行回應的先前區塊
  • 改為傳送 Bash 和檔案操作的新回應類型(請參閱回應格式部分)

程式設計工具呼叫

若要在程式碼執行容器內執行工具,請參閱 程式設計工具呼叫。

資料保留

程式碼執行在伺服器端沙箱容器中執行。容器資料(包括執行成品、上傳的檔案和輸出)保留最多 30 天。此保留適用於在容器環境中處理的所有資料。程式碼執行在 Files API 中建立的檔案(可透過 client.beta.files.download() 檢索)會持續存在,直到明確刪除。

如需跨所有功能的 ZDR 資格,請參閱 API 和資料保留。

將程式碼執行與 Agent Skills 搭配使用

程式碼執行工具使 Claude 能夠使用 Agent Skills。Skills 是模組化功能,由指令、指令碼和資源組成,可擴展 Claude 的功能。

在 Agent Skills 文件 和 Agent Skills API 指南 中瞭解更多資訊。

Was this page helpful?

  • Bash 命令響應
  • 將程式碼執行與 Agent Skills 搭配使用
client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-7",
    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"}],
)

print(response)
client = anthropic.Anthropic()

# 上傳一個文件
file_object = client.beta.files.upload(
    file=open("data.csv", "rb"),
)

# 使用 file_id 進行代碼執行
response = client.beta.messages.create(
    model="claude-opus-4-7",
    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)
# 初始化客戶端
client = Anthropic()

# 請求代碼執行以創建文件
response = client.beta.messages.create(
    model="claude-opus-4-7",
    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):
    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":
                # concrete-typed list: List[BashCodeExecutionOutputBlock]
                for file in content_item.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"Downloaded: {file_metadata.filename}")
file_not_found
文件不存在(用於查看/編輯操作)
text_editorstring_not_found在文件中找不到 old_str(用於 str_replace)
# 第一個請求:建立一個包含隨機數字的檔案
response1 = client.messages.create(
    model="claude-opus-4-7",
    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.messages.create(
    container=container_id,  # 重新使用相同的容器
    model="claude-opus-4-7",
    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)