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

「Tool use」（工具使用），也稱為「function calling」（函式呼叫），讓 Claude 能夠呼叫您定義的函式或 Anthropic 提供的函式。Claude 會根據使用者的請求和工具的描述，決定何時呼叫工具。接著，它會回傳一個結構化的呼叫，由您的應用程式執行（「client tools」，用戶端工具），或由 Anthropic 執行（「server tools」，伺服器工具）。

以下是一個使用伺服器工具的最簡範例。此範例使用[網頁搜尋工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool)，由 Anthropic 為您執行：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 1024,
      "tools": [{"type": "web_search_20260209", "name": "web_search"}],
      "messages": [{"role": "user", "content": "What'\''s the latest on the Mars rover?"}]
    }'
  ```

  ```bash CLI
  ant messages create --transform content --format yaml \
    --model claude-opus-5-5 \
    --max-tokens 1024 \
    --tool '{type: web_search_20260209, name: web_search}' \
    --message '{role: user, content: "What is the latest on the Mars rover?"}'
  ```

  ```python Python
  client = anthropic.Anthropic()
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=[{"type": "web_search_20260209", "name": "web_search"}],
      messages=[{"role": "user", "content": "What's the latest on the Mars rover?"}],
  )
  print(response.content)
  ```

  ```typescript TypeScript
  const client = new Anthropic();
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [{ type: "web_search_20260209", name: "web_search" }],
    messages: [{ role: "user", content: "What's the latest on the Mars rover?" }]
  });
  console.log(response.content);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = [new ToolUnion(new WebSearchTool20260209())],
      Messages = [new() { Role = Role.User, Content = "What's the latest on the Mars rover?" }]
  };

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

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

  response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
  	Model:     anthropic.ModelClaudeOpus5_5,
  	MaxTokens: 1024,
  	Tools: []anthropic.ToolUnionParam{
  		{OfWebSearchTool20260209: &anthropic.WebSearchTool20260209Param{}},
  	},
  	Messages: []anthropic.MessageParam{
  		anthropic.NewUserMessage(anthropic.NewTextBlock("What's the latest on the Mars rover?")),
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response.Content)
  ```

  ```java Java
  import com.anthropic.models.messages.WebSearchTool20260209;

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

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(WebSearchTool20260209.builder().build())
          .addUserMessage("What's the latest on the Mars rover?")
          .build();

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

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

  $message = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      tools: [
          ['type' => 'web_search_20260209', 'name' => 'web_search'],
      ],
      messages: [
          ['role' => 'user', 'content' => "What's the latest on the Mars rover?"],
      ],
  );

  echo $message;
  ```

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

  message = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: [{ type: "web_search_20260209", name: "web_search" }],
    messages: [{ role: "user", content: "What's the latest on the Mars rover?" }]
  )
  puts message.content
  ```
</CodeGroup>

Claude 會在 Anthropic 的基礎架構上執行搜尋，並在同一個回應中回傳附有引用來源的結果。若要讓 Claude 呼叫您定義的函式，請傳入帶有 `input_schema` 的工具，然後在 Claude 回傳 `tool_use` 區塊時執行該呼叫。[工具使用的運作方式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/overview#how-tool-use-works)完整展示了這個往返流程。進一步了解如何[定義工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools)和[處理工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls)。

## 工具使用的運作方式

工具之間的主要差異在於程式碼的執行位置。**用戶端工具**（包括使用者定義的工具，以及採用 Anthropic 定義之「schema」（結構描述）的工具，例如 `bash` 和 `text_editor`）在您的應用程式中執行。Claude 會以 `stop_reason: "tool_use"` 以及一個或多個 `tool_use` 區塊回應。您的程式碼會執行該操作，並傳回 `tool_result`。**伺服器工具**（例如 `web_search`、`web_fetch`、`code_execution` 和 `tool_search`）在 Anthropic 的基礎架構上執行：您可以直接看到結果，無需自行處理執行，除非 Claude 在同一組平行工具呼叫中，同時呼叫了該工具與您的某個用戶端工具（請參閱[停止原因與後備處理](https://platform.claude.com/docs/zh-TW/build-with-claude/handling-stop-reasons#tool-use)）。

以下是用戶端工具的完整往返流程。第一個請求定義了 `get_weather` 工具，Claude 透過呼叫該工具來回答問題：回應中包含一個 `tool_use` 區塊，您的程式碼執行查詢，然後第二個請求以 `tool_result` 區塊將結果傳回，讓 Claude 能夠回覆答案。

<CodeGroup>
  ```bash cURL
  # Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
  TOOLS='[
    {
      "name": "get_weather",
      "description": "Get the current weather for a given location.",
      "input_schema": {
        "type": "object",
        "properties": {
          "location": {"type": "string", "description": "City and state, e.g. San Francisco, CA"}
        },
        "required": ["location"]
      }
    }
  ]'
  USER_MSG="What's the weather in San Francisco?"
  RESPONSE=$(curl -s https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d "$(jq -n --argjson tools "$TOOLS" --arg msg "$USER_MSG" '{
      model: "claude-opus-5-5",
      max_tokens: 1024,
      tools: $tools,
      # 每個回合最多只要求一次工具呼叫。
      tool_choice: {type: "auto", disable_parallel_tool_use: true},
      messages: [{role: "user", content: $msg}]
    }')")
  TOOL_USE=$(echo "$RESPONSE" | jq '.content[] | select(.type == "tool_use")')
  echo "Claude called $(echo "$TOOL_USE" | jq -r '.name') with $(echo "$TOOL_USE" | jq -c '.input')"

  # 執行工具，然後將結果放在 tool_result 區塊中傳回。
  # Claude 會使用該結果來回答原始問題。
  WEATHER="15 degrees Celsius, partly cloudy"
  curl -s https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2023-06-01" \
    -H "content-type: application/json" \
    -d "$(jq -n \
      --argjson tools "$TOOLS" \
      --arg msg "$USER_MSG" \
      --argjson assistant "$(echo "$RESPONSE" | jq '.content')" \
      --arg tool_use_id "$(echo "$TOOL_USE" | jq -r '.id')" \
      --arg weather "$WEATHER" \
      '{
        model: "claude-opus-5-5",
        max_tokens: 1024,
        tools: $tools,
        tool_choice: {type: "auto", disable_parallel_tool_use: true},
        messages: [
          {role: "user", content: $msg},
          {role: "assistant", content: $assistant},
          {role: "user", content: [
            {type: "tool_result", tool_use_id: $tool_use_id, content: $weather}
          ]}
        ]
      }')"
  ```

  ```bash CLI
  # ant 從 stdin 以 YAML 讀取請求主體；jq 將對話
  # 狀態帶入第二個請求。
  USER_MSG="What's the weather in San Francisco?"
  MESSAGES=$(jq -n --arg msg "$USER_MSG" '[{role: "user", content: $msg}]')
  call_api() {
    {
      cat <<'YAML'
  model: claude-opus-5-5
  max_tokens: 1024
  # 要求每個回合最多只進行一次工具呼叫。
  tool_choice: {type: auto, disable_parallel_tool_use: true}
  tools:
    - name: get_weather
      description: Get the current weather for a given location.
      input_schema:
        type: object
        properties:
          location: {type: string, description: "City and state, e.g. San Francisco, CA"}
        required: [location]
  YAML
      printf 'messages: %s\n' "$MESSAGES"
    } | ant messages create --format json
  }

  # Claude 會回覆一個 tool_use 區塊，指明工具名稱及其引數。
  RESPONSE=$(call_api)
  TOOL_USE=$(jq '.content[] | select(.type == "tool_use")' <<<"$RESPONSE")
  echo "Claude called $(jq -r '.name' <<<"$TOOL_USE") with $(jq -c '.input' <<<"$TOOL_USE")"

  # 執行工具，然後在 tool_result 區塊中傳回結果。
  WEATHER="15 degrees Celsius, partly cloudy"
  MESSAGES=$(jq \
    --argjson assistant "$(jq '.content' <<<"$RESPONSE")" \
    --arg tool_use_id "$(jq -r '.id' <<<"$TOOL_USE")" \
    --arg weather "$WEATHER" \
    '. + [
      {role: "assistant", content: $assistant},
      {role: "user", content: [
        {type: "tool_result", tool_use_id: $tool_use_id, content: $weather}
      ]}
    ]' <<<"$MESSAGES")

  # Claude 會使用該結果回答原本的問題。
  call_api
  ```

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

  tools = [
      {
          "name": "get_weather",
          "description": "Get the current weather for a given location.",
          "input_schema": {
              "type": "object",
              "properties": {
                  "location": {
                      "type": "string",
                      "description": "City and state, e.g. San Francisco, CA",
                  }
              },
              "required": ["location"],
          },
      }
  ]
  messages = [{"role": "user", "content": "What's the weather in San Francisco?"}]

  # Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=tools,
      # 每個回合最多只要求一次工具呼叫。
      tool_choice={"type": "auto", "disable_parallel_tool_use": True},
      messages=messages,
  )
  tool_use = next(block for block in response.content if block.type == "tool_use")
  print(f"Claude called {tool_use.name} with {json.dumps(tool_use.input)}")

  # 執行工具，然後以 tool_result 區塊將結果傳回。
  weather = "15 degrees Celsius, partly cloudy"  # your weather lookup goes here
  messages += [
      {"role": "assistant", "content": response.content},
      {
          "role": "user",
          "content": [
              {"type": "tool_result", "tool_use_id": tool_use.id, "content": weather}
          ],
      },
  ]
  followup = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=1024,
      tools=tools,
      tool_choice={"type": "auto", "disable_parallel_tool_use": True},
      messages=messages,
  )

  # Claude 會使用該結果來回答原本的問題。
  final_text = next(block for block in followup.content if block.type == "text")
  print(final_text.text)
  ```

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

  const tools: Anthropic.Tool[] = [
    {
      name: "get_weather",
      description: "Get the current weather for a given location.",
      input_schema: {
        type: "object",
        properties: {
          location: { type: "string", description: "City and state, e.g. San Francisco, CA" }
        },
        required: ["location"]
      }
    }
  ];
  const messages: Anthropic.MessageParam[] = [
    { role: "user", content: "What's the weather in San Francisco?" }
  ];

  // Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
  const response = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools,
    // 每個回合最多只要求一次工具呼叫。
    tool_choice: { type: "auto", disable_parallel_tool_use: true },
    messages
  });
  const toolUse = response.content.find(
    (block): block is Anthropic.ToolUseBlock => block.type === "tool_use"
  )!;
  console.log(`Claude called ${toolUse.name} with ${JSON.stringify(toolUse.input)}`);

  // 執行工具，然後將結果放在 tool_result 區塊中傳回。
  const weather = "15 degrees Celsius, partly cloudy"; // your weather lookup goes here
  messages.push(
    { role: "assistant", content: response.content },
    {
      role: "user",
      content: [{ type: "tool_result", tool_use_id: toolUse.id, content: weather }]
    }
  );
  const followup = await client.messages.create({
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools,
    tool_choice: { type: "auto", disable_parallel_tool_use: true },
    messages
  });

  // Claude 會使用該結果來回答原本的問題。
  const finalText = followup.content.find(
    (block): block is Anthropic.TextBlock => block.type === "text"
  )!;
  console.log(finalText.text);
  ```

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

  List<ToolUnion> tools =
  [
      new ToolUnion(new Tool()
      {
          Name = "get_weather",
          Description = "Get the current weather for a given location.",
          InputSchema = new InputSchema()
          {
              Properties = new Dictionary<string, JsonElement>
              {
                  ["location"] = JsonSerializer.SerializeToElement(new
                  {
                      type = "string",
                      description = "City and state, e.g. San Francisco, CA",
                  }),
              },
              Required = ["location"],
          },
      }),
  ];

  // 每個回合最多只要求一次工具呼叫。
  var toolChoice = new ToolChoice(new ToolChoiceAuto { DisableParallelToolUse = true });

  const string userPrompt = "What's the weather in San Francisco?";

  // Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
  var response = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = tools,
      ToolChoice = toolChoice,
      Messages = [new() { Role = Role.User, Content = userPrompt }],
  });
  ToolUseBlock? toolUse = null;
  foreach (var block in response.Content)
  {
      if (block.TryPickToolUse(out var picked))
      {
          toolUse = picked;
          break;
      }
  }
  Console.WriteLine($"Claude called {toolUse!.Name} with {JsonSerializer.Serialize(toolUse.Input)}");

  // 執行該工具，然後將結果放在 tool_result 區塊中傳回。
  var weather = "15 degrees Celsius, partly cloudy";
  List<ContentBlockParam> toolResults =
  [
      new ContentBlockParam(new ToolResultBlockParam()
      {
          ToolUseID = toolUse.ID,
          Content = weather,
      }),
  ];
  var followup = await client.Messages.Create(new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 1024,
      Tools = tools,
      ToolChoice = toolChoice,
      Messages =
      [
          new() { Role = Role.User, Content = userPrompt },
          new() { Role = Role.Assistant, Content = response.Content.Select(block => new ContentBlockParam(block.Json)).ToList() },
          new() { Role = Role.User, Content = new MessageParamContent(toolResults) },
      ],
  });

  // Claude 會使用該結果來回答原本的問題。
  foreach (var block in followup.Content)
  {
      if (block.TryPickText(out var text))
      {
          Console.WriteLine(text.Text);
      }
  }
  ```

  ```go Go
  client := anthropic.NewClient()
  ctx := context.Background()

  tools := []anthropic.ToolUnionParam{
  	{OfTool: &anthropic.ToolParam{
  		Name:        "get_weather",
  		Description: anthropic.String("Get the current weather for a given location."),
  		InputSchema: anthropic.ToolInputSchemaParam{
  			Properties: map[string]any{
  				"location": map[string]any{
  					"type":        "string",
  					"description": "City and state, e.g. San Francisco, CA",
  				},
  			},
  			Required: []string{"location"},
  		},
  	}},
  }
  // 每個回合最多只要求一次工具呼叫。
  toolChoice := anthropic.ToolChoiceUnionParam{
  	OfAuto: &anthropic.ToolChoiceAutoParam{DisableParallelToolUse: anthropic.Bool(true)},
  }
  messages := []anthropic.MessageParam{
  	anthropic.NewUserMessage(anthropic.NewTextBlock("What's the weather in San Francisco?")),
  }

  // Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
  response, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:      anthropic.ModelClaudeOpus5_5,
  	MaxTokens:  1024,
  	Tools:      tools,
  	ToolChoice: toolChoice,
  	Messages:   messages,
  })
  if err != nil {
  	log.Fatal(err)
  }
  var toolUse anthropic.ContentBlockUnion
  for _, block := range response.Content {
  	if block.Type == "tool_use" {
  		toolUse = block
  		break
  	}
  }
  fmt.Printf("Claude called %s with %s\n", toolUse.Name, string(toolUse.Input))

  // 執行該工具，然後將結果放在 tool_result 區塊中傳回。
  weather := "15 degrees Celsius, partly cloudy"
  var assistantContent []anthropic.ContentBlockParamUnion
  for _, block := range response.Content {
  	assistantContent = append(assistantContent, block.ToParam())
  }
  messages = append(messages,
  	anthropic.NewAssistantMessage(assistantContent...),
  	anthropic.NewUserMessage(anthropic.NewToolResultBlock(toolUse.ID, weather, false)),
  )
  followup, err := client.Messages.New(ctx, anthropic.MessageNewParams{
  	Model:      anthropic.ModelClaudeOpus5_5,
  	MaxTokens:  1024,
  	Tools:      tools,
  	ToolChoice: toolChoice,
  	Messages:   messages,
  })
  if err != nil {
  	log.Fatal(err)
  }

  // Claude 會使用該結果來回答原本的問題。
  for _, block := range followup.Content {
  	if block.Type == "text" {
  		fmt.Println(block.Text)
  	}
  }
  ```

  ```java Java
  import com.anthropic.core.JsonValue;
  import com.anthropic.models.messages.ContentBlockParam;
  // ...
  import com.anthropic.models.messages.Tool;
  import com.anthropic.models.messages.Tool.InputSchema;
  import com.anthropic.models.messages.ToolChoiceAuto;
  import com.anthropic.models.messages.ToolResultBlockParam;
  import com.anthropic.models.messages.ToolUseBlock;
  // ...

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

      Tool weatherTool = Tool.builder()
          .name("get_weather")
          .description("Get the current weather for a given location.")
          .inputSchema(InputSchema.builder()
              .properties(JsonValue.from(Map.of(
                  "location", Map.of(
                      "type", "string",
                      "description", "City and state, e.g. San Francisco, CA"
                  )
              )))
              .required(List.of("location"))
              .build())
          .build();

      // 每個回合最多只要求一次工具呼叫。
      ToolChoiceAuto toolChoice = ToolChoiceAuto.builder()
          .disableParallelToolUse(true)
          .build();

      String userPrompt = "What's the weather in San Francisco?";

      // Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
      Message response = client.messages().create(MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(weatherTool)
          .toolChoice(toolChoice)
          .addUserMessage(userPrompt)
          .build());
      ToolUseBlock toolUse = response.content().stream()
          .flatMap(block -> block.toolUse().stream())
          .findFirst()
          .orElseThrow();
      IO.println("Claude called " + toolUse.name() + " with " + toolUse._input());

      // 執行該工具，然後將結果放在 tool_result 區塊中傳回。
      String weather = "15 degrees Celsius, partly cloudy";
      Message followup = client.messages().create(MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(1024L)
          .addTool(weatherTool)
          .toolChoice(toolChoice)
          .addUserMessage(userPrompt)
          .addMessage(response)
          .addUserMessageOfBlockParams(List.of(ContentBlockParam.ofToolResult(
              ToolResultBlockParam.builder()
                  .toolUseId(toolUse.id())
                  .content(weather)
                  .build())))
          .build());

      // Claude 會使用該結果來回答原本的問題。
      followup.content().stream()
          .flatMap(block -> block.text().stream())
          .forEach(textBlock -> IO.println(textBlock.text()));
  }
  ```

  ```php PHP
  use Anthropic\Messages\ToolChoiceAuto;

  $client = new Client();

  $tools = [
      [
          'name' => 'get_weather',
          'description' => 'Get the current weather for a given location.',
          'input_schema' => [
              'type' => 'object',
              'properties' => [
                  'location' => [
                      'type' => 'string',
                      'description' => 'City and state, e.g. San Francisco, CA',
                  ],
              ],
              'required' => ['location'],
          ],
      ],
  ];
  $userMessage = ['role' => 'user', 'content' => "What's the weather in San Francisco?"];

  // 每個回合最多只要求一次工具呼叫。
  $toolChoice = ToolChoiceAuto::with(disableParallelToolUse: true);

  // Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
  $response = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      tools: $tools,
      toolChoice: $toolChoice,
      messages: [$userMessage],
  );
  $toolUse = null;
  foreach ($response->content as $block) {
      if ($block->type === 'tool_use') {
          $toolUse = $block;
          break;
      }
  }
  printf("Claude called %s with %s\n", $toolUse->name, json_encode($toolUse->input));

  // 執行該工具，然後將結果放在 tool_result 區塊中傳回。
  $weather = '15 degrees Celsius, partly cloudy';
  $followup = $client->messages->create(
      model: 'claude-opus-5-5',
      maxTokens: 1024,
      tools: $tools,
      toolChoice: $toolChoice,
      messages: [
          $userMessage,
          ['role' => 'assistant', 'content' => $response->content],
          [
              'role' => 'user',
              'content' => [
                  [
                      'type' => 'tool_result',
                      'tool_use_id' => $toolUse->id,
                      'content' => $weather,
                  ],
              ],
          ],
      ],
  );

  // Claude 會使用該結果來回答原本的問題。
  foreach ($followup->content as $block) {
      if ($block->type === 'text') {
          echo $block->text, "\n";
      }
  }
  ```

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

  tools = [
    {
      name: "get_weather",
      description: "Get the current weather for a given location.",
      input_schema: {
        type: "object",
        properties: {
          location: {type: "string", description: "City and state, e.g. San Francisco, CA"}
        },
        required: ["location"]
      }
    }
  ]
  messages = [{role: "user", content: "What's the weather in San Francisco?"}]

  # Claude 會回覆一個 tool_use 區塊，其中指明工具名稱及其引數。
  response = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: tools,
    # 每個回合最多只要求一次工具呼叫。
    tool_choice: {type: "auto", disable_parallel_tool_use: true},
    messages: messages
  )
  tool_use = response.content.find { |block| block.type == :tool_use }
  puts "Claude called #{tool_use.name} with #{JSON.generate(tool_use.input)}"

  # 執行工具，然後以 tool_result 區塊將結果傳回。
  weather = "15 degrees Celsius, partly cloudy"
  messages += [
    {role: "assistant", content: response.content},
    {
      role: "user",
      content: [
        {type: "tool_result", tool_use_id: tool_use.id, content: weather}
      ]
    }
  ]
  followup = client.messages.create(
    model: "claude-opus-5-5",
    max_tokens: 1024,
    tools: tools,
    tool_choice: {type: "auto", disable_parallel_tool_use: true},
    messages: messages
  )

  # Claude 會使用該結果來回答原本的問題。
  final_text = followup.content.find { |block| block.type == :text }
  puts final_text.text
  ```
</CodeGroup>

```text Output wrap
Claude called get_weather with {"location": "San Francisco, CA"}
The current weather in San Francisco is 15 degrees Celsius with partly cloudy skies.
```

[處理工具呼叫](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls)詳細說明了每個步驟，包括結果格式化和錯誤通報；[平行工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/parallel-tool-use)說明了一次呼叫多個工具的回應。若要省去自行撰寫此往返流程，請使用 [Tool Runner](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-runner)：SDK 會執行您的工具並自動將結果傳回。

如需完整的概念模型，包括「agentic loop」（代理迴圈）以及何時選擇各種方法，請參閱[工具使用的運作方式](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/how-tool-use-works)。

若要連接到「Model Context Protocol」（即 MCP）伺服器，請參閱 [MCP 連接器](https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector)。若要建置您自己的 MCP 用戶端，請參閱 Model Context Protocol 指南中的[建置 MCP 用戶端](https://modelcontextprotocol.io/docs/develop/build-client)。

## Claude 何時使用工具

在預設的 `tool_choice` 為 `{"type": "auto"}` 時，Claude 會在每一輪判斷要呼叫工具還是直接回應。當請求對應到該工具所描述的能力，且答案尚未存在於上下文中時，它會呼叫工具。對於穩定的知識、創意任務與對話性的輪次，它會直接回應。

這個界線可以透過您的系統提示加以引導。如果 Claude 沒有在您預期的時候呼叫工具，一個輕量的指示，例如 `"Use the tools to investigate before responding."`，可以增加工具使用。更強烈的形式，例如 `"Always call a tool first before responding."`，則會進一步推動。相反地，`"Use your judgment about whether to call a tool or respond directly."` 會讓觸發行為保持保守。

若要強制要求工具呼叫而非依賴提示，請設定 [`tool_choice`](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools#forcing-tool-use)。

<Tip>
  **透過嚴格工具使用保證符合 schema**

  在您的自訂工具定義中加入 `strict: true`，以確保 Claude 的工具呼叫始終與您的 schema 完全相符。請參閱[嚴格工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/strict-tool-use)。
</Tip>

每個伺服器工具的頁面都更詳細地描述了其自身的觸發界線。

<Accordion title="當缺少必要參數時">
  如果使用者的提示未包含足夠的資訊來填入工具的所有必要參數，Claude Opus 更有可能辨識出缺少某個參數並詢問該參數。Claude Sonnet 可能會詢問，尤其是在被提示於輸出工具請求前先思考時。但它也可能推斷出一個合理的值。

  例如，給定一個需要 `location` 參數的 `get_weather` 工具，如果您詢問 Claude「What's the weather?」而未指定地點，Claude（尤其是 Claude Sonnet）可能會猜測您未提供的值：

  ```json JSON
  {
    "type": "tool_use",
    "id": "toolu_01A09q90qw90lq917835lq9",
    "name": "get_weather",
    "input": { "location": "New York, NY", "unit": "fahrenheit" }
  }
  ```

  此行為並不保證，尤其是對於較模糊的提示以及能力較弱的模型。
</Accordion>

## 選擇工具

如需 `type` 字串、版本與 beta 標頭，請參閱[工具參考](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference)。

### 您自己的工具

對於您定義的工具，由您撰寫 schema，並由您的應用程式執行每次呼叫。

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

  <Card title="處理工具呼叫" icon="arrows-left-right" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/handle-tool-calls">
    解析 `tool_use` 區塊、格式化 `tool_result` 回應，並處理錯誤。
  </Card>
</CardGroup>

### Anthropic schema 用戶端工具

Anthropic 發布 schema 並以此訓練 Claude。您的應用程式仍需執行每次呼叫並回傳 `tool_result`。

<CardGroup cols={2}>
  <Card title="Memory 工具" icon="brain" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/memory-tool">
    在您控制的檔案中跨對話儲存與擷取資訊。
  </Card>

  <Card title="Bash 工具" icon="terminal" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/bash-tool">
    在維持狀態的持久工作階段中執行 shell 指令。
  </Card>

  <Card title="文字編輯器工具" icon="edit" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/text-editor-tool">
    檢視與修改文字檔案，以除錯、修正並改進程式碼。
  </Card>

  <Card title="電腦使用工具" icon="computer" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/computer-use-tool">
    在桌面環境中擷取螢幕截圖並控制滑鼠與鍵盤。
  </Card>

  <Card title="瀏覽器使用工具" icon="browser" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/browser-use-tool">
    在您自己的瀏覽器環境中導覽、閱讀並與網頁互動。
  </Card>
</CardGroup>

### 伺服器工具

伺服器工具在 Anthropic 的基礎設施上執行，您的應用程式中無需處理程式碼。請參閱[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools)以了解它們共通的運作機制。

<CardGroup cols={2}>
  <Card title="Web search 工具" icon="magnifying-glass" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool">
    在網路上搜尋超出知識截止日期的資訊，並附上引用來源。
  </Card>

  <Card title="Web fetch 工具" icon="download" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool">
    擷取指定網頁與 PDF 文件的完整內容。
  </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="Advisor 工具" icon="lightbulb" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/advisor-tool">
    讓較快速的執行者模型在生成過程中諮詢智慧更高的顧問模型。
  </Card>

  <Card title="工具搜尋工具" icon="library" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-search-tool">
    透過按需探索與載入工具，處理數以千計的工具。
  </Card>

  <Card title="MCP 連接器" icon="link" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/mcp-connector">
    從 Messages API 連接到遠端 MCP 伺服器，無需獨立的 MCP 用戶端。
  </Card>
</CardGroup>

<Note>
  [Claude Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview) 提供一組內建工具集，Claude 會在工作階段中自主使用。如需該工具集以及 Managed Agents 新增自訂工具的方式，請參閱其[工具](https://platform.claude.com/docs/zh-TW/managed-agents/tools)頁面。
</Note>

## 定價

工具使用（tool use）請求的計價依據如下：

1. 傳送至模型的輸入 token 總數（包括 `tools` 參數中的內容）
2. 產生的輸出 token 數量
3. 對於伺服器端工具，另有依使用量計算的額外費用（例如，網頁搜尋依每次執行的搜尋計費）

用戶端工具的計價方式與任何其他 Claude API 請求相同，但伺服器端工具可能會依其特定使用情況產生額外費用。

工具使用所產生的額外 token 來自：

* API 請求中的 `tools` 參數（工具名稱、描述與結構描述）
* API 請求與回應中的 `tool_use` 內容區塊
* API 請求中的 `tool_result` 內容區塊

當您使用 `tools` 時，API 也會自動為模型加入一段特殊的系統提示（system prompt），以啟用工具使用功能。下表列出了每個模型所需的工具使用 token 數量（不包括前述的額外 token）。請注意，此表假設至少提供了 1 個工具。若未提供任何 `tools`，則工具選擇為 `none` 時會使用 0 個額外的系統提示 token。

| Model                                                                                                                                   | Tool use system prompt tokens: auto, none | Tool use system prompt tokens: any, tool |
| :-------------------------------------------------------------------------------------------------------------------------------------- | :---------------------------------------- | :--------------------------------------- |
| Claude Opus 5.5                                                                                                                         | 286 tokens                                |                                          |
| Claude Opus 5                                                                                                                           | 286 tokens                                | 406 tokens                               |
| Claude Opus 4.8                                                                                                                         | 290 tokens                                | 410 tokens                               |
| Claude Opus 4.7                                                                                                                         | 675 tokens                                | 804 tokens                               |
| Claude Opus 4.6                                                                                                                         | 497 tokens                                | 589 tokens                               |
| Claude Opus 4.5                                                                                                                         | 496 tokens                                | 588 tokens                               |
| Claude Opus 4.1 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations)) | 313 tokens                                | 315 tokens                               |
| Claude Opus 4 ([retired, except on Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations))               | 313 tokens                                | 315 tokens                               |
| Claude Sonnet 5.5                                                                                                                       | 286 tokens                                |                                          |
| Claude Sonnet 5                                                                                                                         | 354 tokens                                | 474 tokens                               |
| Claude Sonnet 4.6                                                                                                                       | 497 tokens                                | 589 tokens                               |
| Claude Sonnet 4.5                                                                                                                       | 496 tokens                                | 588 tokens                               |
| Claude Sonnet 4 ([retired, except on Bedrock and Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations)) | 313 tokens                                | 315 tokens                               |
| Claude Haiku 5.5                                                                                                                        | 286 tokens                                | 406 tokens                               |
| Claude Haiku 4.5                                                                                                                        | 496 tokens                                | 588 tokens                               |
| Claude Haiku 3.5 ([retired, except on Google Cloud](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations))            | 264 tokens                                | 355 tokens                               |

* **auto, none:** The count when tool\_choice is auto or none.
* **any, tool:** The count when tool\_choice is any or tool.
* **Retired:** May still be available on other cloud platforms. See [Model deprecations](https://platform.claude.com/docs/zh-TW/about-claude/model-deprecations) for more.

這些 token 數量會加到您一般的輸入與輸出 token 中，以計算請求的總費用。

請參閱[模型概覽](https://platform.claude.com/docs/zh-TW/models/overview#latest-models-comparison)表格以了解目前各模型的價格。

當您傳送工具使用提示時，與任何其他 API 請求一樣，回應會在回報的 `usage` 指標中同時包含輸入與輸出 token 數量。

部分伺服器工具會在 token 之外加收依用量計費的費用：請參閱 [Web search 工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#usage-and-pricing)與[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool#usage-and-pricing)以了解其費率。

## 後續步驟

<CardGroup cols={3}>
  <Card href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/how-tool-use-works" title="工具使用的運作方式" icon="compass">
    了解工具使用迴圈、工具在何處執行，以及何時應使用工具而非散文式回應。
  </Card>

  <Card href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/build-a-tool-using-agent" title="教學：建構使用工具的代理" icon="graduation-cap">
    從單一工具呼叫到可用於正式環境的代理迴圈的引導式逐步教學。
  </Card>

  <Card href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference" title="工具參考" icon="book">
    Anthropic 提供之工具的目錄，以及選用工具定義屬性的參考。
  </Card>
</CardGroup>
