Loading...
    • 開發者指南
    • API 參考
    • MCP
    • 資源
    • 發行說明
    Search...
    ⌘K
    入門
    Claude 簡介快速開始
    模型與定價
    模型概覽選擇模型Claude 4.6 新功能遷移指南模型棄用定價
    使用 Claude 構建
    功能概覽使用 Messages API處理停止原因提示最佳實踐
    模型能力
    延伸思考自適應思考思考力度快速模式(研究預覽)結構化輸出引用串流訊息批次處理PDF 支援搜尋結果多語言支援嵌入視覺
    工具
    概覽如何實作工具使用網頁搜尋工具網頁擷取工具程式碼執行工具記憶工具Bash 工具電腦使用工具文字編輯器工具
    工具基礎設施
    工具搜尋程式化工具呼叫細粒度工具串流
    上下文管理
    上下文視窗壓縮上下文編輯提示快取Token 計數
    檔案與資源
    Files API
    Agent 技能
    概覽快速開始最佳實踐企業技能透過 API 使用技能
    Agent SDK
    概覽快速開始TypeScript SDKTypeScript V2(預覽)Python SDK遷移指南
    API 中的 MCP
    MCP 連接器遠端 MCP 伺服器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示工程
    概覽提示產生器使用提示範本提示改進器清晰直接使用範例(多範例提示)讓 Claude 思考(CoT)使用 XML 標籤賦予 Claude 角色(系統提示)串連複雜提示長上下文技巧延伸思考技巧
    測試與評估
    定義成功標準開發測試案例使用評估工具降低延遲
    強化防護機制
    減少幻覺提高輸出一致性防範越獄攻擊串流拒絕減少提示洩漏讓 Claude 保持角色
    管理與監控
    Admin API 概覽資料駐留工作區用量與成本 APIClaude Code Analytics API零資料保留
    Console
    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
    • Catalog
    • 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
    • Catalog
    • 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
    工具基礎設施

    程式化工具呼叫

    了解如何讓 Claude 在程式碼執行容器中以程式化方式呼叫您的工具,減少延遲和 token 消耗。

    程式化工具呼叫允許 Claude 在程式碼執行容器中撰寫程式碼來以程式化方式呼叫您的工具,而不需要每次工具呼叫都透過模型進行來回通訊。這減少了多工具工作流程的延遲,並透過允許 Claude 在資料到達模型的上下文視窗之前進行過濾或處理,來降低 token 消耗。

    此功能需要啟用程式碼執行工具。

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

    模型相容性

    程式化工具呼叫可在以下模型上使用:

    模型工具版本
    Claude Opus 4.6 (claude-opus-4-6)code_execution_20250825
    Claude Sonnet 4.6 (claude-sonnet-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 API 和 Microsoft Foundry 使用。

    快速開始

    以下是一個簡單的範例,Claude 以程式化方式多次查詢資料庫並彙總結果:

    curl https://api.anthropic.com/v1/messages \
        --header "x-api-key: $ANTHROPIC_API_KEY" \
        --header "anthropic-version: 2023-06-01" \
        --header "content-type: application/json" \
        --data '{
            "model": "claude-opus-4-6",
            "max_tokens": 4096,
            "messages": [
                {
                    "role": "user",
                    "content": "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
                }
            ],
            "tools": [
                {
                    "type": "code_execution_20250825",
                    "name": "code_execution"
                },
                {
                    "name": "query_database",
                    "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
                    "input_schema": {
                        "type": "object",
                        "properties": {
                            "sql": {
                                "type": "string",
                                "description": "SQL query to execute"
                            }
                        },
                        "required": ["sql"]
                    },
                    "allowed_callers": ["code_execution_20250825"]
                }
            ]
        }'

    程式化工具呼叫的運作方式

    當您將工具設定為可從程式碼執行中呼叫,且 Claude 決定使用該工具時:

    1. Claude 撰寫 Python 程式碼來呼叫工具函式,可能包含多個工具呼叫和前/後處理邏輯
    2. Claude 透過程式碼執行在沙箱容器中執行此程式碼
    3. 當工具函式被呼叫時,程式碼執行暫停,API 回傳一個 tool_use 區塊
    4. 您提供工具結果,程式碼執行繼續(中間結果不會載入 Claude 的上下文視窗)
    5. 所有程式碼執行完成後,Claude 接收最終輸出並繼續處理任務

    此方法特別適用於:

    • 大型資料處理:在工具結果到達 Claude 的上下文之前進行過濾或彙總
    • 多步驟工作流程:透過連續或循環呼叫工具來節省 token 和延遲,無需在工具呼叫之間對 Claude 進行取樣
    • 條件邏輯:根據中間工具結果做出決策

    自訂工具會被轉換為非同步 Python 函式以支援平行工具呼叫。當 Claude 撰寫呼叫您工具的程式碼時,它會使用 await(例如 result = await query_database("<sql>"))並自動包含適當的非同步包裝函式。

    為了清晰起見,本文件的程式碼範例中省略了非同步包裝。

    核心概念

    allowed_callers 欄位

    allowed_callers 欄位指定哪些上下文可以呼叫工具:

    {
      "name": "query_database",
      "description": "Execute a SQL query against the database",
      "input_schema": {...},
      "allowed_callers": ["code_execution_20250825"]
    }

    可能的值:

    • ["direct"] - 只有 Claude 可以直接呼叫此工具(省略時的預設值)
    • ["code_execution_20250825"] - 只能從程式碼執行中呼叫
    • ["direct", "code_execution_20250825"] - 可直接呼叫也可從程式碼執行中呼叫

    我們建議為每個工具選擇 ["direct"] 或 ["code_execution_20250825"] 其中之一,而不是同時啟用兩者,因為這能為 Claude 提供更清晰的指引,讓它知道如何最佳地使用該工具。

    回應中的 caller 欄位

    每個工具使用區塊都包含一個 caller 欄位,指示它是如何被呼叫的:

    直接呼叫(傳統工具使用):

    {
      "type": "tool_use",
      "id": "toolu_abc123",
      "name": "query_database",
      "input": {"sql": "<sql>"},
      "caller": {"type": "direct"}
    }

    程式化呼叫:

    {
      "type": "tool_use",
      "id": "toolu_xyz789",
      "name": "query_database",
      "input": {"sql": "<sql>"},
      "caller": {
        "type": "code_execution_20250825",
        "tool_id": "srvtoolu_abc123"
      }
    }

    tool_id 參照進行程式化呼叫的程式碼執行工具。

    容器生命週期

    程式化工具呼叫使用與程式碼執行相同的容器:

    • 容器建立:除非您重複使用現有容器,否則每個工作階段都會建立新容器
    • 過期:容器在大約 4.5 分鐘不活動後過期(可能會變更)
    • 容器 ID:透過 container 欄位在回應中回傳
    • 重複使用:傳遞容器 ID 以在請求之間維持狀態

    當工具被程式化呼叫且容器正在等待您的工具結果時,您必須在容器過期之前回應。請監控 expires_at 欄位。如果容器過期,Claude 可能會將工具呼叫視為逾時並重試。

    範例工作流程

    以下是完整的程式化工具呼叫流程:

    步驟 1:初始請求

    發送包含程式碼執行和允許程式化呼叫的工具的請求。要啟用程式化呼叫,請在您的工具定義中新增 allowed_callers 欄位。

    在工具描述中提供工具輸出格式的詳細說明。如果您指定工具回傳 JSON,Claude 將嘗試在程式碼中反序列化和處理結果。您提供的輸出結構描述越詳細,Claude 就能越好地以程式化方式處理回應。

    response = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=4096,
        messages=[
            {
                "role": "user",
                "content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue",
            }
        ],
        tools=[
            {"type": "code_execution_20250825", "name": "code_execution"},
            {
                "name": "query_database",
                "description": "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
                "input_schema": {...},
                "allowed_callers": ["code_execution_20250825"],
            },
        ],
    )

    步驟 2:API 回應包含工具呼叫

    Claude 撰寫呼叫您工具的程式碼。API 暫停並回傳:

    {
      "role": "assistant",
      "content": [
        {
          "type": "text",
          "text": "I'll query the purchase history and analyze the results."
        },
        {
          "type": "server_tool_use",
          "id": "srvtoolu_abc123",
          "name": "code_execution",
          "input": {
            "code": "results = await query_database('<sql>')\ntop_customers = sorted(results, key=lambda x: x['revenue'], reverse=True)[:5]\nprint(f'Top 5 customers: {top_customers}')"
          }
        },
        {
          "type": "tool_use",
          "id": "toolu_def456",
          "name": "query_database",
          "input": {"sql": "<sql>"},
          "caller": {
            "type": "code_execution_20250825",
            "tool_id": "srvtoolu_abc123"
          }
        }
      ],
      "container": {
        "id": "container_xyz789",
        "expires_at": "2025-01-15T14:30:00Z"
      },
      "stop_reason": "tool_use"
    }

    步驟 3:提供工具結果

    包含完整的對話歷史記錄加上您的工具結果:

    response = client.messages.create(
        model="claude-opus-4-6",
        max_tokens=4096,
        container="container_xyz789",  # Reuse the container
        messages=[
            {
                "role": "user",
                "content": "Query customer purchase history from the last quarter and identify our top 5 customers by revenue",
            },
            {
                "role": "assistant",
                "content": [
                    {
                        "type": "text",
                        "text": "I'll query the purchase history and analyze the results.",
                    },
                    {
                        "type": "server_tool_use",
                        "id": "srvtoolu_abc123",
                        "name": "code_execution",
                        "input": {"code": "..."},
                    },
                    {
                        "type": "tool_use",
                        "id": "toolu_def456",
                        "name": "query_database",
                        "input": {"sql": "<sql>"},
                        "caller": {
                            "type": "code_execution_20250825",
                            "tool_id": "srvtoolu_abc123",
                        },
                    },
                ],
            },
            {
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": "toolu_def456",
                        "content": '[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]',
                    }
                ],
            },
        ],
        tools=[...],
    )

    步驟 4:下一個工具呼叫或完成

    程式碼執行繼續並處理結果。如果需要額外的工具呼叫,重複步驟 3 直到所有工具呼叫都被滿足。

    步驟 5:最終回應

    程式碼執行完成後,Claude 提供最終回應:

    {
      "content": [
        {
          "type": "code_execution_tool_result",
          "tool_use_id": "srvtoolu_abc123",
          "content": {
            "type": "code_execution_result",
            "stdout": "Top 5 customers by revenue:\n1. Customer C1: $45,000\n2. Customer C2: $38,000\n3. Customer C5: $32,000\n4. Customer C8: $28,500\n5. Customer C3: $24,000",
            "stderr": "",
            "return_code": 0,
            "content": []
          }
        },
        {
          "type": "text",
          "text": "I've analyzed the purchase history from last quarter. Your top 5 customers generated $167,500 in total revenue, with Customer C1 leading at $45,000."
        }
      ],
      "stop_reason": "end_turn"
    }

    進階模式

    使用迴圈進行批次處理

    Claude 可以撰寫高效處理多個項目的程式碼:

    # async wrapper omitted for clarity
    regions = ["West", "East", "Central", "North", "South"]
    results = {}
    for region in regions:
        data = await query_database(f"<sql for {region}>")
        results[region] = sum(row["revenue"] for row in data)
    
    # Process results programmatically
    top_region = max(results.items(), key=lambda x: x[1])
    print(f"Top region: {top_region[0]} with ${top_region[1]:,} in revenue")

    此模式:

    • 將模型來回次數從 N(每個區域一次)減少到 1
    • 在回傳給 Claude 之前以程式化方式處理大型結果集
    • 透過只回傳彙總結論而非原始資料來節省 token

    提前終止

    Claude 可以在滿足成功條件後立即停止處理:

    # async wrapper omitted for clarity
    endpoints = ["us-east", "eu-west", "apac"]
    for endpoint in endpoints:
        status = await check_health(endpoint)
        if status == "healthy":
            print(f"Found healthy endpoint: {endpoint}")
            break  # Stop early, don't check remaining

    條件式工具選擇

    # async wrapper omitted for clarity
    file_info = await get_file_info(path)
    if file_info["size"] < 10000:
        content = await read_full_file(path)
    else:
        content = await read_file_summary(path)
    print(content)

    資料過濾

    # async wrapper omitted for clarity
    logs = await fetch_logs(server_id)
    errors = [log for log in logs if "ERROR" in log]
    print(f"Found {len(errors)} errors")
    for error in errors[-10:]:  # Only return last 10 errors
        print(error)

    回應格式

    程式化工具呼叫

    當程式碼執行呼叫工具時:

    {
      "type": "tool_use",
      "id": "toolu_abc123",
      "name": "query_database",
      "input": {"sql": "<sql>"},
      "caller": {
        "type": "code_execution_20250825",
        "tool_id": "srvtoolu_xyz789"
      }
    }

    工具結果處理

    您的工具結果會傳回給正在執行的程式碼:

    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_abc123",
          "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000, \"orders\": 23}, {\"customer_id\": \"C2\", \"revenue\": 38000, \"orders\": 18}, ...]"
        }
      ]
    }

    程式碼執行完成

    當所有工具呼叫都被滿足且程式碼完成時:

    {
      "type": "code_execution_tool_result",
      "tool_use_id": "srvtoolu_xyz789",
      "content": {
        "type": "code_execution_result",
        "stdout": "Analysis complete. Top 5 customers identified from 847 total records.",
        "stderr": "",
        "return_code": 0,
        "content": []
      }
    }

    錯誤處理

    常見錯誤

    錯誤描述解決方案
    invalid_tool_input工具輸入不符合結構描述驗證您工具的 input_schema
    tool_not_allowed工具不允許請求的呼叫者類型檢查 allowed_callers 是否包含正確的上下文
    missing_beta_header未提供必要的 beta 標頭在您的請求中新增必要的 beta 標頭

    工具呼叫期間容器過期

    如果您的工具回應時間太長,程式碼執行將收到 TimeoutError。Claude 在 stderr 中看到此錯誤,通常會重試:

    {
      "type": "code_execution_tool_result",
      "tool_use_id": "srvtoolu_abc123",
      "content": {
        "type": "code_execution_result",
        "stdout": "",
        "stderr": "TimeoutError: Calling tool ['query_database'] timed out.",
        "return_code": 0,
        "content": []
      }
    }

    防止逾時的方法:

    • 監控回應中的 expires_at 欄位
    • 為您的工具執行實作逾時機制
    • 考慮將長時間操作分解為較小的區塊

    工具執行錯誤

    如果您的工具回傳錯誤:

    # Provide error information in the tool result
    {
        "type": "tool_result",
        "tool_use_id": "toolu_abc123",
        "content": "Error: Query timeout - table lock exceeded 30 seconds",
    }

    Claude 的程式碼將接收此錯誤並可以適當地處理它。

    限制與約束

    功能不相容性

    • 結構化輸出:具有 strict: true 的工具不支援程式化呼叫
    • 工具選擇:您無法透過 tool_choice 強制程式化呼叫特定工具
    • 平行工具使用:disable_parallel_tool_use: true 不支援程式化呼叫

    工具限制

    以下工具目前無法以程式化方式呼叫,但未來版本可能會新增支援:

    • 網路搜尋
    • 網頁擷取
    • 由 MCP 連接器提供的工具

    訊息格式限制

    回應程式化工具呼叫時,有嚴格的格式要求:

    僅包含工具結果的回應:如果有待處理的程式化工具呼叫等待結果,您的回應訊息必須僅包含 tool_result 區塊。您不能包含任何文字內容,即使在工具結果之後也不行。

    // ❌ INVALID - Cannot include text when responding to programmatic tool calls
    {
      "role": "user",
      "content": [
        {"type": "tool_result", "tool_use_id": "toolu_01", "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"},
        {"type": "text", "text": "What should I do next?"}  // This will cause an error
      ]
    }
    
    // ✅ VALID - Only tool results when responding to programmatic tool calls
    {
      "role": "user",
      "content": [
        {"type": "tool_result", "tool_use_id": "toolu_01", "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"}
      ]
    }

    此限制僅適用於回應程式化(程式碼執行)工具呼叫時。對於一般的客戶端工具呼叫,您可以在工具結果之後包含文字內容。

    速率限制

    程式化工具呼叫受到與一般工具呼叫相同的速率限制。來自程式碼執行的每個工具呼叫都算作一次單獨的呼叫。

    使用前驗證工具結果

    實作將被程式化呼叫的自訂工具時:

    • 工具結果以字串形式回傳:它們可以包含任何內容,包括可能被執行環境處理的程式碼片段或可執行命令。
    • 驗證外部工具結果:如果您的工具回傳來自外部來源的資料或接受使用者輸入,請注意如果輸出將被解釋或作為程式碼執行,可能存在程式碼注入風險。

    Token 效率

    程式化工具呼叫可以顯著減少 token 消耗:

    • 程式化呼叫的工具結果不會新增到 Claude 的上下文中 - 只有最終的程式碼輸出會
    • 中間處理在程式碼中進行 - 過濾、彙總等不會消耗模型 token
    • 在一次程式碼執行中進行多個工具呼叫 - 與分開的模型輪次相比減少了開銷

    例如,直接呼叫 10 個工具使用的 token 大約是以程式化方式呼叫它們並回傳摘要的 10 倍。

    使用量與定價

    程式化工具呼叫使用與程式碼執行相同的定價。詳情請參閱程式碼執行定價。

    程式化工具呼叫的 token 計算:來自程式化呼叫的工具結果不計入您的輸入/輸出 token 使用量。只有最終的程式碼執行結果和 Claude 的回應才會計算。

    最佳實踐

    工具設計

    • 提供詳細的輸出描述:由於 Claude 在程式碼中反序列化工具結果,請清楚記錄格式(JSON 結構、欄位類型等)
    • 回傳結構化資料:JSON 或其他易於解析的格式最適合程式化處理
    • 保持回應簡潔:只回傳必要的資料以最小化處理開銷

    何時使用程式化呼叫

    適合的使用案例:

    • 處理大型資料集,您只需要彙總或摘要
    • 具有 3 個以上相依工具呼叫的多步驟工作流程
    • 需要對工具結果進行過濾、排序或轉換的操作
    • 中間資料不應影響 Claude 推理的任務
    • 跨多個項目的平行操作(例如,檢查 50 個端點)

    較不理想的使用案例:

    • 具有簡單回應的單一工具呼叫
    • 需要即時使用者回饋的工具
    • 非常快速的操作,程式碼執行開銷會超過收益

    效能最佳化

    • 進行多個相關請求時重複使用容器以維持狀態
    • 盡可能在單次程式碼執行中批次處理類似操作

    疑難排解

    常見問題

    「Tool not allowed」錯誤

    • 驗證您的工具定義包含 "allowed_callers": ["code_execution_20250825"]

    容器過期

    • 確保您在容器的生命週期內(約 4.5 分鐘)回應工具呼叫
    • 監控回應中的 expires_at 欄位
    • 考慮實作更快的工具執行

    工具結果未正確解析

    • 確保您的工具回傳 Claude 可以反序列化的字串資料
    • 在您的工具描述中提供清晰的輸出格式文件

    除錯技巧

    1. 記錄所有工具呼叫和結果以追蹤流程
    2. 檢查 caller 欄位以確認程式化呼叫
    3. 監控容器 ID 以確保正確重複使用
    4. 獨立測試工具後再啟用程式化呼叫

    為什麼程式化工具呼叫有效

    Claude 的訓練包含大量的程式碼接觸,使其能有效地推理和串連函式呼叫。當工具在程式碼執行環境中作為可呼叫函式呈現時,Claude 可以利用這一優勢來:

    • 自然地推理工具組合:像撰寫任何 Python 程式碼一樣自然地串連操作和處理相依性
    • 高效處理大型結果:過濾大型工具輸出、僅提取相關資料,或在將摘要回傳到上下文視窗之前將中間結果寫入檔案
    • 顯著減少延遲:消除多步驟工作流程中每次工具呼叫之間重新對 Claude 取樣的開銷

    此方法使傳統工具使用不切實際的工作流程成為可能——例如處理超過 1M token 的檔案——透過允許 Claude 以程式化方式處理資料,而不是將所有內容載入對話上下文。

    替代實作

    程式化工具呼叫是一種可通用的模式,可以在 Anthropic 的託管程式碼執行之外實作。以下是各種方法的概述:

    客戶端直接執行

    為 Claude 提供程式碼執行工具,並描述該環境中可用的函式。當 Claude 使用程式碼呼叫工具時,您的應用程式在定義了這些函式的本地環境中執行它。

    優點:

    • 實作簡單,最少的重新架構
    • 完全控制環境和指令

    缺點:

    • 在沙箱外執行不受信任的程式碼
    • 工具呼叫可能成為程式碼注入的攻擊向量

    適用時機: 您的應用程式可以安全地執行任意程式碼,您想要簡單的解決方案,且 Anthropic 的託管方案不符合您的需求。

    自行管理的沙箱執行

    從 Claude 的角度來看方法相同,但程式碼在具有安全限制的沙箱容器中執行(例如,無網路出口)。如果您的工具需要外部資源,您需要一個在沙箱外執行工具呼叫的協議。

    優點:

    • 在您自己的基礎設施上安全的程式化工具呼叫
    • 完全控制執行環境

    缺點:

    • 建置和維護複雜
    • 需要管理基礎設施和行程間通訊

    適用時機: 安全性至關重要且 Anthropic 的託管解決方案不符合您的需求。

    Anthropic 託管執行

    Anthropic 的程式化工具呼叫是沙箱執行的託管版本,具有為 Claude 調校的固定 Python 環境。Anthropic 處理容器管理、程式碼執行和安全的工具呼叫通訊。

    優點:

    • 預設安全且可靠
    • 以最少的設定即可輕鬆啟用
    • 環境和指令針對 Claude 進行最佳化

    如果您使用 Claude API,我們建議使用 Anthropic 的託管解決方案。

    相關功能

    程式碼執行工具

    了解驅動程式化工具呼叫的底層程式碼執行功能。

    工具使用概述

    了解 Claude 工具使用的基礎知識。

    實作工具使用

    實作工具的逐步指南。

    Was this page helpful?

    • allowed_callers 欄位
    • 回應中的 caller 欄位
    • 步驟 1:初始請求
    • 步驟 2:API 回應包含工具呼叫
    • 步驟 3:提供工具結果
    • 步驟 4:下一個工具呼叫或完成
    • 步驟 5:最終回應
    • Token 效率
    • Anthropic 託管執行