---
title: 程式化工具呼叫
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling
description: 讓 Claude 在程式碼執行容器中透過程式碼呼叫您的工具，減少多工具工作流程中的模型往返次數與 token 使用量。
featureMetadata:
  status: ga
  zdr: not-eligible
  supportedModels:
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-opus-5-5
    - claude-opus-5
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-sonnet-4-6
    - claude-sonnet-4-5-20250929
    - claude-haiku-5-5
  supportedPlatforms:
    Claude API: ga
    Claude Platform on AWS: ga
    Microsoft Foundry:
      availability: ga
      note: 在 [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) 上，程式化工具呼叫需要 [Hosted on Anthropic 部署](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure)。
  details:
    - 程式化工具呼叫需要使用 `code_execution_20260120` 或更新[工具版本](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#tool-versions)的程式碼執行工具。
    - Claude Haiku 4.5 接受 `code_execution_20260120` 及更新的工具版本，但不支援程式化工具呼叫。
---

「Programmatic tool calling」（程式化工具呼叫）讓 Claude 能夠撰寫程式碼，在[程式碼執行](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)容器中以程式化方式呼叫您的工具，而不需要每次工具呼叫都經過模型往返。這能降低多工具工作流程的「latency」（延遲），並讓 Claude 在資料進入模型的「context window」（上下文視窗）之前先行篩選或處理，從而減少 token 消耗。在 [BrowseComp](https://arxiv.org/abs/2504.12516) 和 [DeepSearchQA](https://github.com/google-deepmind/deepsearchqa) 等測試多步驟網路研究與複雜資訊檢索的代理式搜尋基準測試中，在基本搜尋工具之上加入程式化工具呼叫，平均提升了 11% 的效能，同時減少了 24% 的輸入 token（請參閱[透過動態篩選改善網路搜尋](https://claude.com/blog/improved-web-search-with-dynamic-filtering)）。

以檢查 20 位員工的預算合規情況為例：傳統做法需要 20 次獨立的模型往返，過程中會將數千筆費用明細拉進上下文。使用程式化工具呼叫時，單一腳本即可執行全部 20 次查詢、篩選結果，並只回傳超出額度的員工，將 Claude 需要推理的內容從數百 KB 縮減到寥寥數行。

<Tip>
  若想更深入了解程式化工具呼叫所解決的推論與上下文成本問題，請參閱[進階工具使用](https://www.anthropic.com/engineering/advanced-tool-use)。
</Tip>

程式化工具呼叫需要使用工具版本為 `code_execution_20260120` 或更新版本的[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)。若要在傳送請求前確認模型是否支援程式化工具呼叫，請從 Models API 讀取其 `capabilities.code_execution.supported` 值。[使用 Models API](https://platform.claude.com/docs/zh-TW/models/overview#using-the-models-api) 說明了此欄位。

## 快速開始

以下範例中，Claude 以程式化方式多次查詢資料庫並彙總結果。在工具定義中加入 `allowed_callers: ["code_execution_20260120"]`，即可讓該工具能夠從程式碼執行中被呼叫（請參閱 [`allowed_callers` 欄位](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling#the-allowed-callers-field)）：

<CodeGroup>
  ```bash cURL
  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-5-5",
          "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_20260120",
                  "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_20260120"]
              }
          ]
      }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  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_20260120
      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_20260120
  YAML
  ```

  ```python Python
  client = anthropic.Anthropic()

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

  print(response)
  ```

  ```typescript TypeScript
  const client = new Anthropic();

  const response = await client.messages.create({
    model: "claude-opus-5-5",
    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_20260120",
        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" as const,
          properties: {
            sql: {
              type: "string",
              description: "SQL query to execute"
            }
          },
          required: ["sql"]
        },
        allowed_callers: ["code_execution_20260120"]
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [
          new() {
              Role = Role.User,
              Content = "Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue"
          }
      ],
      Tools = [
          new CodeExecutionTool20260120(),
          new ToolUnion(new Tool()
          {
              Name = "query_database",
              Description = "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["sql"] = JsonSerializer.SerializeToElement(new { type = "string", description = "SQL query to execute" }),
                  },
                  Required = ["sql"],
              },
              AllowedCallers = ["code_execution_20260120"]
          }),
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
  		{OfTool: &anthropic.ToolParam{
  			Name:        "query_database",
  			Description: anthropic.String("Execute a SQL query against the sales database. Returns a list of rows as JSON objects."),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"sql": map[string]any{
  						"type":        "string",
  						"description": "SQL query to execute",
  					},
  				},
  				Required: []string{"sql"},
  			},
  			AllowedCallers: []string{"code_execution_20260120"},
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.CodeExecutionTool20260120;
  // ...

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue")
          .addTool(CodeExecutionTool20260120.builder().build())
          .addTool(Tool.builder()
              .name("query_database")
              .description("Execute a SQL query against the sales database. Returns a list of rows as JSON objects.")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "sql", Map.of(
                          "type", "string",
                          "description", "SQL query to execute"
                      )
                  )))
                  .putAdditionalProperty("required", JsonValue.from(List.of("sql")))
                  .build())
              .allowedCallers(List.of(Tool.AllowedCaller.of("code_execution_20260120")))
              .build())
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 4096,
      messages: [
          ['role' => 'user', 'content' => 'Query sales data for the West, East, and Central regions, then tell me which region had the highest revenue'],
      ],
      model: 'claude-opus-5-5',
      tools: [
          [
              'type' => 'code_execution_20260120',
              '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_20260120'],
          ],
      ],
  );

  echo $message;
  ```

  ```ruby Ruby
  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    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_20260120",
        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_20260120"]
      }
    ]
  )

  puts message
  ```
</CodeGroup>

回應會以 `stop_reason: "tool_use"` 停止，並帶有一個 `container` ID，以及一個 `query_database` 的 `tool_use` 區塊，其 `caller` 欄位標示了呼叫它的程式碼執行作業。請依照[範例工作流程的步驟 3](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling#step-3-provide-tool-result) 所示回傳結果，讓程式碼得以完成執行。

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

當您將某個工具設定為可從程式碼執行中呼叫，且 Claude 判斷需要該工具時：

1. Claude 撰寫 Python 程式碼，將該工具當作函式呼叫，其中可能包含多次工具呼叫以及前置／後置處理邏輯
2. Claude 透過程式碼執行在沙箱容器中執行這段程式碼
3. 當工具函式被呼叫時，程式碼執行會暫停，API 回傳一個 `tool_use` 區塊
4. 您提供工具結果，程式碼執行繼續進行（中間結果不會載入 Claude 的上下文視窗）
5. 所有程式碼執行完成後，Claude 收到最終輸出並繼續處理任務

這種做法特別適用於：

* **大量資料處理：**&#x5728;工具結果進入 Claude 的上下文之前先行篩選或彙總
* **多步驟工作流程：**&#x4EE5;序列或迴圈方式呼叫工具，而不需在工具呼叫之間對 Claude 進行取樣，從而節省 token 與延遲
* **條件邏輯：**&#x6839;據中間工具結果做出決策

<Note>
  允許程式碼執行呼叫者的工具會以非同步 Python 函式的形式提供給 Claude 的程式碼，因此 Claude 可以使用 `asyncio.gather` 平行執行它們。每個函式接受單一的引數 dict 並回傳一個字串：也就是您回傳的 `tool_result` 文字。Claude 的程式碼會以頂層 `await` 等待這些函式，並將所需的結果解析為結構化資料，例如 `rows = json.loads(await query_database({"sql": "<sql>"}))`。
</Note>

## 核心概念

### `allowed_callers` 欄位

`allowed_callers` 欄位指定哪些情境可以呼叫某個工具：

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

**可能的值：**

* `["direct"]` - 引導 Claude 直接呼叫此工具（省略時的預設值）
* `["code_execution_20260120"]` - 引導 Claude 僅從程式碼執行中呼叫此工具
* `["direct", "code_execution_20260120"]` - Claude 可以直接呼叫此工具，也可以從程式碼執行中呼叫

`"code_execution_20260120"` 與 `"code_execution_20260521"` 在 `allowed_callers` 中皆可接受且可互換：使用任一程式碼執行工具版本的請求，都能滿足列出任一呼叫者的工具。無論請求宣告的是哪個版本，回應區塊一律將呼叫者標記為 `code_execution_20260120`。

<Tip>
  請為每個工具選擇 `["direct"]` 或 `["code_execution_20260120"]` 其中之一，而非同時啟用兩者，這樣能為 Claude 提供更明確的指引，讓它知道如何最佳地使用該工具。
</Tip>

<Note>
  `allowed_callers` 控制工具呈現給 Claude 的方式，並會與 `tool_choice` 進行驗證，但它並非 API 層級對直接呼叫的硬性封鎖。Claude 會受到強烈引導去遵守它，但您的用戶端仍應準備好處理其所定義之任何工具的直接 `tool_use`。請勿將 `allowed_callers` 當作安全邊界。
</Note>

### 回應中的 `caller` 欄位

每個工具使用區塊都包含一個 `caller` 欄位，標示其被呼叫的方式：

**直接呼叫（傳統工具使用）：**

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

**程式化呼叫：**

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

`tool_id` 是發出該呼叫的程式碼執行 `server_tool_use` 區塊的 `id`，因此您可以將每個程式化 `tool_use` 對應到產生它的程式碼執行作業。

### 容器生命週期

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

* **容器建立：**&#x9664;非您重複使用現有容器，否則每個請求都會建立一個新容器
* **容器 ID：**&#x5728;回應的 `container` 欄位中回傳，並附帶 `expires_at` 時間戳記
* **重複使用：**&#x5728;下一個請求中傳回容器 ID 以保留狀態。當程式化工具呼叫正在等待您的結果時，該請求必須提供容器 ID，而非選填：若未提供，API 會拒絕該請求。
* **到期：**`expires_at` 告訴您容器還剩多少時間。閒置容器目前約在 5 分鐘後被回收，且任何容器在建立超過 30 天後都無法再重複使用。

<Warning>
  當 Claude 的程式碼正在等待程式化工具結果時，待處理的呼叫約在 4 分鐘後逾時，並在程式碼內引發 `TimeoutError`。請在暫停回應的 `expires_at` 時間戳記之前儘早回傳每個工具結果。請參閱[工具呼叫期間容器到期](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling#container-expiration-during-tool-call)。
</Warning>

## 範例工作流程

以下是完整程式化工具呼叫流程的運作方式：

### 步驟 1：初始請求

傳送一個包含程式碼執行以及允許程式化呼叫之工具的請求。若要啟用程式化呼叫，請在工具定義中加入 `allowed_callers` 欄位。

<Note>
  請在工具描述中詳細說明工具的輸出格式。如果您指定工具回傳 JSON，Claude 會嘗試在程式碼中反序列化並處理結果。您提供的輸出結構描述越詳細，Claude 就越能以程式化方式妥善處理回應。
</Note>

請求的形式與[快速開始](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling#quick-start)範例相同：在工具清單中加入 `code_execution`，為任何您希望 Claude 從程式碼中呼叫的工具加上 `allowed_callers: ["code_execution_20260120"]`，然後傳送您的使用者訊息。本工作流程的其餘步驟使用的使用者訊息為 `"Query customer purchase history from the last quarter and identify our top 5 customers by revenue"`。

### 步驟 2：帶有工具呼叫的 API 回應

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

```json Output
{
  "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": "import json\n\nrows = json.loads(await query_database({'sql': '<sql>'}))\ntop_customers = sorted(rows, 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_20260120",
        "tool_id": "srvtoolu_abc123"
      }
    }
  ],
  "container": {
    "id": "container_xyz789",
    "expires_at": "2026-01-20T14:30:00Z"
  },
  "stop_reason": "tool_use"
}
```

### 步驟 3：提供工具結果

傳送完整的對話歷史以及您的工具結果。此請求有三個細節需要注意：

* 承載您結果的使用者訊息只能包含 `tool_result` 區塊。請參閱[訊息格式限制](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling#message-formatting-restrictions)。
* 傳入暫停回應中的 `container` ID。若接續請求有待處理的程式化工具呼叫卻沒有容器 ID，API 會拒絕該請求。
* 傳送與原始請求相同的 `tools` 陣列。程式碼執行工具必須仍然存在，暫停的程式碼才能恢復執行，而您在此請求中傳送的工具，就是 Claude 與執行中的程式碼在本輪其餘部分可使用的定義。

<CodeGroup>
  ```bash cURL
  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-5-5",
          "max_tokens": 4096,
          "container": "container_xyz789",
          "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_20260120",
                              "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": [
              {
                  "type": "code_execution_20260120",
                  "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_20260120"]
              }
          ]
      }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  container: container_xyz789
  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_20260120
            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 陣列
  tools:
    - type: code_execution_20260120
      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_20260120
  YAML
  ```

  ```python Python
  response = client.messages.create(
      model="claude-opus-5-5",
      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_20260120",
                          "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 陣列
      tools=[
          {"type": "code_execution_20260120", "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_20260120"],
          },
      ],
  )

  print(response)
  ```

  ```typescript TypeScript
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    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_20260120",
              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 陣列
    tools: [
      {
        type: "code_execution_20260120",
        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" as const,
          properties: {
            sql: {
              type: "string",
              description: "SQL query to execute"
            }
          },
          required: ["sql"]
        },
        allowed_callers: ["code_execution_20260120"]
      }
    ]
  });

  console.log(response);
  ```

  ```csharp C#
  AnthropicClient client = new();

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Container = "container_xyz789",
      Messages =
      [
          new()
          {
              Role = Role.User,
              Content = "Query customer purchase history from the last quarter and identify our top 5 customers by revenue"
          },
          new()
          {
              Role = Role.Assistant,
              Content = new ContentBlock[]
              {
                  new TextBlock { Text = "I'll query the purchase history and analyze the results." },
                  new ServerToolUseBlock
                  {
                      Id = "srvtoolu_abc123",
                      Name = "code_execution",
                      Input = new { code = "..." }
                  },
                  new ToolUseBlock
                  {
                      Id = "toolu_def456",
                      Name = "query_database",
                      Input = new { sql = "<sql>" },
                      Caller = new ToolCaller
                      {
                          Type = "code_execution_20260120",
                          ToolId = "srvtoolu_abc123"
                      }
                  }
              }
          },
          new()
          {
              Role = Role.User,
              Content = new ContentBlockParam[]
              {
                  new ToolResultBlockParam
                  {
                      ToolUseID = "toolu_def456",
                      Content = "[{\"customer_id\": \"C1\", \"revenue\": 45000}, {\"customer_id\": \"C2\", \"revenue\": 38000}, ...]"
                  }
              }
          }
      ],
      // 與原始請求相同的 tools 陣列
      Tools = [
          new CodeExecutionTool20260120(),
          new ToolUnion(new Tool()
          {
              Name = "query_database",
              Description = "Execute a SQL query against the sales database. Returns a list of rows as JSON objects.",
              InputSchema = new InputSchema()
              {
                  Properties = new Dictionary<string, JsonElement>
                  {
                      ["sql"] = JsonSerializer.SerializeToElement(new { type = "string", description = "SQL query to execute" }),
                  },
                  Required = ["sql"],
              },
              AllowedCallers = ["code_execution_20260120"]
          }),
      ]
  };

  var message = await client.Messages.Create(parameters);
  Console.WriteLine(message);
  ```

  ```go Go
  client := anthropic.NewClient()

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 4096,
  	Container: anthropic.MessageCreateParamsContainerUnion{
  		OfString: anthropic.String("container_xyz789"),
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("Query customer purchase history from the last quarter and identify our top 5 customers by revenue")),
  		{
  			Role: anthropic.MessageParamRoleAssistant,
  			Content: []anthropic.ContentBlockParamUnion{
  				anthropic.NewTextBlock("I'll query the purchase history and analyze the results."),
  				{OfServerToolUse: &anthropic.ServerToolUseBlockParam{
  					ID:    "srvtoolu_abc123",
  					Name:  anthropic.ServerToolUseBlockParamNameCodeExecution,
  					Input: map[string]any{"code": "..."},
  				}},
  				{OfToolUse: &anthropic.ToolUseBlockParam{
  					ID:    "toolu_def456",
  					Name:  "query_database",
  					Input: map[string]any{"sql": "<sql>"},
  					Caller: anthropic.ServerToolUseBlockParamCallerUnion{
  						OfCodeExecution20260120: &anthropic.ServerToolCaller20260120Param{
  							ToolID: "srvtoolu_abc123",
  						},
  					},
  				}},
  			},
  		},
  		{
  			Role: anthropic.MessageParamRoleUser,
  			Content: []anthropic.ContentBlockParamUnion{
  				{OfToolResult: &anthropic.ToolResultBlockParam{
  					ToolUseID: "toolu_def456",
  					Content: []anthropic.ToolResultBlockParamContentUnion{
  						{OfText: &anthropic.TextBlockParam{
  							Text: `[{"customer_id": "C1", "revenue": 45000}, {"customer_id": "C2", "revenue": 38000}, ...]`,
  						}},
  					},
  				}},
  			},
  		},
  	},
  	// 與原始請求相同的 tools 陣列
  	Tools: []anthropic.ToolUnionParam{
  		{OfCodeExecutionTool20260120: &anthropic.CodeExecutionTool20260120Param{}},
  		{OfTool: &anthropic.ToolParam{
  			Name:        "query_database",
  			Description: anthropic.String("Execute a SQL query against the sales database. Returns a list of rows as JSON objects."),
  			InputSchema: anthropic.ToolInputSchemaParam{
  				Properties: map[string]any{
  					"sql": map[string]any{
  						"type":        "string",
  						"description": "SQL query to execute",
  					},
  				},
  				Required: []string{"sql"},
  			},
  			AllowedCallers: []string{"code_execution_20260120"},
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.RawJSON())
  ```

  ```java Java
  import com.anthropic.models.messages.CodeExecutionTool20260120;
  // ...

  void main() {
      AnthropicClient client = AnthropicOkHttpClient.fromEnv();

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .container("container_xyz789")
          .addUserMessage("Query customer purchase history from the last quarter and identify our top 5 customers by revenue")
          .addAssistantMessageOfBlockParams(List.of(
              ContentBlockParam.ofText(
                  TextBlockParam.builder()
                      .text("I'll query the purchase history and analyze the results.")
                      .build()),
              ContentBlockParam.ofServerToolUse(
                  ServerToolUseBlockParam.builder()
                      .id("srvtoolu_abc123")
                      .name("code_execution")
                      .input(JsonValue.from(Map.of("code", "...")))
                      .build()),
              ContentBlockParam.ofToolUse(
                  ToolUseBlockParam.builder()
                      .id("toolu_def456")
                      .name("query_database")
                      .input(JsonValue.from(Map.of("sql", "<sql>")))
                      .codeExecution20260120Caller("srvtoolu_abc123")
                      .build())
          ))
          .addUserMessageOfBlockParams(List.of(
              ContentBlockParam.ofToolResult(
                  ToolResultBlockParam.builder()
                      .toolUseId("toolu_def456")
                      .content("[{\"customer_id\": \"C1\", \"revenue\": 45000}, {\"customer_id\": \"C2\", \"revenue\": 38000}, ...]")
                      .build())
          ))
          // 與原始請求相同的 tools 陣列
          .addTool(CodeExecutionTool20260120.builder().build())
          .addTool(Tool.builder()
              .name("query_database")
              .description("Execute a SQL query against the sales database. Returns a list of rows as JSON objects.")
              .inputSchema(InputSchema.builder()
                  .properties(JsonValue.from(Map.of(
                      "sql", Map.of(
                          "type", "string",
                          "description", "SQL query to execute"
                      )
                  )))
                  .putAdditionalProperty("required", JsonValue.from(List.of("sql")))
                  .build())
              .allowedCallers(List.of(Tool.AllowedCaller.of("code_execution_20260120")))
              .build())
          .build();

      Message response = client.messages().create(params);
      IO.println(response);
  }
  ```

  ```php PHP
  $client = new Client();

  $message = $client->messages->create(
      maxTokens: 4096,
      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_20260120',
                          '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}, ...]',
                  ],
              ],
          ],
      ],
      model: 'claude-opus-5-5',
      container: 'container_xyz789',
      // 與原始請求相同的 tools 陣列
      tools: [
          [
              'type' => 'code_execution_20260120',
              '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_20260120'],
          ],
      ],
  );

  echo $message;
  ```

  ```ruby Ruby
  require "anthropic"

  client = Anthropic::Client.new

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 4096,
    container: "container_xyz789",
    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_20260120",
              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 陣列
    tools: [
      {
        type: "code_execution_20260120",
        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_20260120"]
      }
    ]
  )

  puts message
  ```
</CodeGroup>

### 步驟 4：下一次工具呼叫或完成

程式碼從暫停處繼續執行並處理您的結果。每個接續回應要麼再次暫停並帶有更多程式化 `tool_use` 區塊，要麼完成程式碼執行並讓 Claude 繼續本輪（步驟 5）。請檢查 `stop_reason` 以及每個 `tool_use` 區塊的 `caller` 來區分兩者：為您暫停的回應會有 `stop_reason: "tool_use"`，以及一個 `caller` 標示程式碼執行版本的 `tool_use` 區塊，此時您需重複步驟 3，在單一使用者訊息中為每個待處理的程式化呼叫提供一個 `tool_result`。

### 步驟 5：最終回應

程式碼執行完成後，Claude 提供最終回應：

```json Output
{
  "content": [
    {
      "type": "code_execution_tool_result",
      "tool_use_id": "srvtoolu_abc123",
      "content": {
        "type": "code_execution_result",
        "stdout": "Top 5 customers: [{'customer_id': 'C1', 'revenue': 45000}, {'customer_id': 'C2', 'revenue': 38000}, {'customer_id': 'C5', 'revenue': 32000}, {'customer_id': 'C8', 'revenue': 28500}, {'customer_id': 'C3', 'revenue': 24000}]",
        "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 可以撰寫能有效率地處理多個項目的程式碼：

```python
regions = ["West", "East", "Central", "North", "South"]
results = {}
for region in regions:
    rows = json.loads(await query_database({"sql": f"<sql for {region}>"}))
    results[region] = sum(row["revenue"] for row in rows)

# 以程式化方式處理結果
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 可以在達成成功條件後立即停止處理：

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

### 條件式工具選擇

```python
path = "/tmp/example.txt"
file_info = json.loads(await get_file_info({"path": path}))
if file_info["size"] < 10000:
    content = await read_full_file({"path": path})
else:
    content = await read_file_summary({"path": path})
print(content)
```

### 資料篩選

```python
server_id = "srv-01"
log_text = await fetch_logs({"server_id": server_id})
errors = [line for line in log_text.splitlines() if "ERROR" in line]
print(f"Found {len(errors)} errors")
for error in errors[-10:]:  # Only return last 10 errors
    print(error)
```

## 回應格式

### 程式化工具呼叫

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

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

### 工具結果處理

您的工具結果會傳回給執行中的程式碼：

```json
{
  "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}, ...]"
    }
  ]
}
```

### 程式碼執行完成

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

```json
{
  "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`                     | 回應中 `code_execution_tool_result` 錯誤區塊的 `error_code` | 傳遞給程式碼執行工具的參數無效                                          | 請參閱[程式碼執行工具錯誤](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#errors) |
| `invalid_request_error`（於 `tool_choice`） | HTTP 400 錯誤回應                                       | `tool_choice` 指定了一個 `allowed_callers` 不包含 `"direct"` 的工具 | 在該工具的 `allowed_callers` 中加入 `"direct"`，或將該工具從 `tool_choice` 中移除，讓 Claude 從程式碼中呼叫它                           |

### 工具呼叫期間容器到期

如果您的工具結果未在約 4 分鐘內送達，待處理的呼叫會在 Claude 執行中的程式碼內引發 `TimeoutError`。Claude 會在 `stderr` 中看到該錯誤，通常會重試該呼叫：

```json
{
  "type": "code_execution_tool_result",
  "tool_use_id": "srvtoolu_abc123",
  "content": {
    "type": "code_execution_result",
    "stdout": "",
    "stderr": "TimeoutError: Calling tool ['query_database'] timed out (no response after 270s).",
    "return_code": 0,
    "content": []
  }
}
```

為避免逾時：

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

### 工具執行錯誤

如果您的工具回傳錯誤：

```json
{
  "type": "tool_result",
  "tool_use_id": "toolu_abc123",
  "content": "Error: Query timeout - table lock exceeded 30 seconds"
}
```

Claude 的程式碼會收到此錯誤並可適當處理。

## 限制與約束

### 功能不相容

* **結構化輸出：**&#x5E36;有 `strict: true` 的工具不支援程式化呼叫
* **工具選擇：**&#x60A8;無法透過 `tool_choice` 強制對特定工具進行程式化呼叫
* **平行工具使用：**`disable_parallel_tool_use: true` 不支援程式化呼叫

### 輸入結構描述限制

若自訂工具的 `input_schema` 包含遞迴 `$ref`（參照循環，例如參照自身的結構描述），則無法啟用程式化呼叫。在此類工具的 `allowed_callers` 中加入程式碼執行工具版本，會導致請求失敗並回傳 `400 invalid_request_error`，其訊息包含 `Circular $ref detected`。相同的結構描述在直接工具呼叫時則可被接受。

若要解決此問題，請採取下列其中一種做法：

* 省略 `allowed_callers`（或將其設為 `["direct"]`），讓該工具維持僅限直接呼叫。同一請求中的其他工具仍可使用程式化呼叫。
* 從結構描述中移除循環。例如，將遞迴展開至固定深度，並在最內層的 `description` 中描述任何更深的巢狀結構；或將遞迴屬性替換為一個單純的 `{"type": "object"}`，並在其 `description` 中說明預期的形式。

### 工具限制

下列工具無法以程式化方式呼叫：

* 由 [MCP 連接器](https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector)提供的工具
* [電腦使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/computer-use-tool)與[瀏覽器使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/browser-use-tool)工具集（`computer_toolset_20260801` 與 `browser_toolset_20260801`），其 `allowed_callers` 欄位僅接受 `"direct"`

### 訊息格式限制

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

**僅含工具結果的回應：**&#x5982;果有待處理的程式化工具呼叫正在等待結果，您的回應訊息必須**僅**包含 `tool_result` 區塊。您不能包含任何文字內容，即使放在工具結果之後也不行。

無效 - 回應程式化工具呼叫時不能包含文字：

```json
{
  "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?" }
  ]
}
```

有效 - 回應程式化工具呼叫時僅包含工具結果：

```json
{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01",
      "content": "[{\"customer_id\": \"C1\", \"revenue\": 45000}]"
    }
  ]
}
```

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

**僅限文字的工具結果內容：**&#x56DE;應程式化呼叫的每個 `tool_result` 的 `content` 必須是字串或 `text` 區塊。圖片、文件及其他內容區塊類型會被拒絕。

### 速率限制

程式化工具呼叫與一般工具呼叫受相同的速率限制約束。來自程式碼執行的每次工具呼叫都計為一次獨立的呼叫。

### 使用前驗證工具結果

在實作將以程式化方式呼叫的使用者定義工具時：

* **工具結果以字串形式回傳：**&#x5B83;們可以包含任何內容，包括可能被執行環境處理的程式碼片段或可執行指令。
* **驗證外部工具結果：**&#x5982;果您的工具回傳來自外部來源的資料或接受使用者輸入，且輸出將被解譯或當作程式碼執行，請留意程式碼注入風險。

## Token 效率

程式化工具呼叫透過三種方式減少 token 消耗：

* **程式化呼叫的工具結果不會加入 Claude 的上下文** - 只有最終的程式碼輸出會加入
* **中間處理在程式碼中進行** - 篩選、彙總及其他轉換不會消耗模型 token
* **單次程式碼執行中進行多次工具呼叫** - 相較於分開的模型輪次，可減少額外負擔

例如，直接呼叫 10 個工具所使用的 token，約為以程式化方式呼叫並回傳摘要的 10 倍。

在 Anthropic 針對正式環境 Claude 模型的內部評估中：

* 在一個包含 75 個工具的專案管理代理基準測試中，啟用程式化工具呼叫使計費輸入 token 減少約 38%，且任務準確度沒有變化。
* 在 [τ²-bench](https://arxiv.org/abs/2506.07982)（航空、零售與電信領域）中，每輪進行一到兩次序列工具呼叫，程式化工具呼叫的分數維持不變，成本則增加約 8%。序列式單次呼叫工作流程無法從中受益。
* 在正式環境 API 流量中，`tools` 陣列包含 10 到 49 個工具定義的請求，啟用程式化工具呼叫後通常可節省 20% 到 40% 的 token。

實際節省幅度因工作負載形態而異。請參閱[何時使用程式化呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/programmatic-tool-calling#when-to-use-programmatic-calling)。

## 用量與定價

程式化工具呼叫採用與程式碼執行相同的定價。詳情請參閱[程式碼執行定價](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing)。

<Note>
  程式化工具呼叫的 token 計算：程式化呼叫的工具結果不計入您的輸入／輸出 token 用量。只有最終的程式碼執行結果與 Claude 的回應會計入。
</Note>

## 最佳實務

### 工具設計

* **提供詳細的輸出說明：**&#x7531;於 Claude 會在程式碼中反序列化工具結果，請記錄其格式（JSON 結構與欄位型別）
* **回傳結構化資料：**&#x4A;SON 或其他機器可讀格式最適合程式化處理
* **保持回應簡潔：**&#x53EA;回傳必要的資料，以將處理負擔降到最低

### 何時使用程式化呼叫

程式化工具呼叫以少量固定的額外負擔（容器啟動、腳本產生）換取工具結果 token 與模型往返次數的大幅節省。這項取捨是否划算取決於工作負載形態。

**非常適合：**

* 跨多個項目的扇出或平行作業（例如檢查 50 個端點或查詢 20 筆記錄）
* 可在進入 Claude 上下文之前先行篩選、彙總或摘要的大型工具結果
* 代理式搜尋與檢索，其工作流程以反覆查詢與結果篩選為主

**不太適合：**

* 嚴格序列式的工作流程，其中每次呼叫都依賴 Claude 對前一個結果的推理，因為在這種情況下腳本無法省略模型往返
* 少量工具呼叫且回應很小，尤其是在對話的第一輪，此時容器與腳本的額外負擔可能超過節省的量
* 需要在呼叫之間立即取得使用者回饋的工具

如果您不確定，請在廣泛啟用之前，先以具代表性的流量樣本測量有無 `allowed_callers` 時的計費輸入 token。

### 效能最佳化

* 在發出多個相關請求時**重複使用容器**以保留狀態
* 盡可能在單次程式碼執行中**批次處理類似作業**

## 疑難排解

### 常見問題

**設定 `tool_choice` 時出現 `invalid_request_error`**

* `tool_choice` 不能指定 `allowed_callers` 省略了 `"direct"` 的工具。請在該工具的 `allowed_callers` 中加入 `"direct"`，或將該工具從 `tool_choice` 中移除，讓 Claude 從程式碼中呼叫它。

**容器到期**

* 請在暫停回應的 `expires_at` 時間戳記之前儘早回應每個程式化工具呼叫。Claude 的程式碼約在 4 分鐘後停止等待結果，而閒置容器目前約在 5 分鐘後被回收。
* 考慮實作更快速的工具執行

**工具結果未正確解析**

* 確保您的工具回傳 Claude 可以反序列化的字串資料
* 在工具描述中提供清楚的輸出格式說明

### 除錯技巧

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

## 程式化工具呼叫為何有效

Claude 以大量程式碼進行訓練，因此將工具呈現為可呼叫的 Python 函式能讓它發揮這項優勢：

* **工具組合：**&#x93C8;式呼叫、迴圈與條件判斷都是一般的 Python 控制流程，而非一連串的模型往返
* **結果處理：**&#x43;laude 的程式碼會篩選並彙總大型工具輸出，或將其寫入檔案，只有最終輸出會進入上下文視窗
* **延遲：**&#x5728;單次程式碼執行內的工具呼叫之間，模型不會被重新取樣

## 替代實作方式

程式化工具呼叫是一種可通用的模式，也可以在您自己的基礎設施上實作。以下是各種做法的比較：

### 用戶端直接執行

為 Claude 提供一個程式碼執行工具，並描述該環境中有哪些可用函式。當 Claude 以程式碼呼叫該工具時，您的應用程式會在定義這些函式的本機環境中執行它。

**優點：**

* 對應用程式的架構改動最小
* 完全掌控環境與指令

**缺點：**

* 在沙箱之外執行不受信任的程式碼
* 工具呼叫可能成為程式碼注入的途徑

**適用時機：**&#x60A8;的應用程式可以安全地執行任意程式碼、您想要最精簡的實作，且 Anthropic 的託管方案不符合您的需求。

### 自行管理的沙箱執行

從 Claude 的角度來看做法相同，但程式碼在具有安全限制（例如無網路對外連線）的沙箱容器中執行。如果您的工具需要外部資源，您需要一套在沙箱外執行工具呼叫的協定。

**優點：**

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

**缺點：**

* 建置與維護複雜
* 需要同時管理基礎設施與行程間通訊

**適用時機：**&#x5B89;全性至關重要，且 Anthropic 的託管解決方案不符合您的需求。

### Anthropic 託管執行

Anthropic 的程式化工具呼叫是沙箱執行的託管版本，具備為 Claude 調校、帶有既定設計取向的 Python 環境。Anthropic 負責處理容器管理、程式碼執行以及安全的工具呼叫通訊。

**優點：**

* 預設即安全可靠
* 透過工具定義即可啟用，無需運行任何基礎設施
* 環境與指令已針對 Claude 最佳化

如果您使用 Claude API、[Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws) 或 [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry)，請考慮使用 Anthropic 的託管解決方案。在 Microsoft Foundry 上，程式化工具呼叫需要 [Hosted on Anthropic 部署](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure)。

## 資料保留

程式化工具呼叫建構於程式碼執行基礎設施之上，並使用相同的沙箱容器。容器資料（包括執行產物與輸出）最多保留 30 天。

關於所有功能的 ZDR 資格，請參閱 [API 與資料保留](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention)。

## 後續步驟

<CardGroup cols={2}>
  <Card title="細粒度工具串流" icon="bolt" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/fine-grained-tool-streaming">
    為對延遲敏感的應用程式串流工具輸入，無需伺服器端 JSON 緩衝。
  </Card>

  <Card title="程式碼執行工具" icon="code" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool">
    在沙箱容器中執行 Python 與 bash 程式碼，以分析資料、產生檔案並反覆改進解決方案。
  </Card>

  <Card title="使用 Claude 進行工具使用" icon="wrench" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/overview">
    將 Claude 連接到外部工具與 API。了解工具在何處執行、Claude 何時呼叫它們，以及哪種工具適合您的任務。
  </Card>

  <Card title="定義工具" icon="hammer" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools">
    指定工具結構描述、撰寫有效的描述，並控制 Claude 何時呼叫您的工具。
  </Card>
</CardGroup>
