---
title: 網頁搜尋工具
url: https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool
description: 讓 Claude 存取最新的網路內容並附上引用來源，支援選用的動態篩選與網域控制。
featureMetadata:
  status: stable
  zdr:
    eligibility: eligible
    note: Excludes [Covered Models](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention#model-specific-data-retention-requirements). 即時網頁搜尋結果會在 API 回應中傳回。網頁搜尋的動態篩選不符合 ZDR 或 HIPAA 的適用資格。
  supportedModels:
    - claude-fable-5-1
    - claude-mythos-5-1
    - claude-fable-5
    - claude-mythos-5
    - claude-mythos-preview
    - claude-opus-5-5
    - claude-opus-5
    - claude-sonnet-5-5
    - claude-sonnet-5
    - claude-haiku-5-5
    - claude-haiku-4-5-20251001
    - claude-opus-4-8
    - claude-opus-4-7
    - claude-opus-4-6
    - claude-sonnet-4-6
    - claude-opus-4-5-20251101
    - claude-sonnet-4-5-20250929
  supportedPlatforms:
    Claude API: stable
    Claude Platform on AWS: stable
    Claude Models on Google Cloud (Anthropic managed): stable
    Claude Models on Google Cloud (Google managed):
      availability: stable
      note: 僅支援基本網頁搜尋工具（`web_search_20250305`），不含動態篩選。
    Microsoft Foundry:
      availability: stable
      note: 僅支援基本網頁搜尋工具（`web_search_20250305`），不含動態篩選。
---

**API 支援**：用法因產品而異。

* **Messages API**：在請求的 `tools` 中加入 `web_search` 工具。`max_uses`、網域清單與 `user_location` 等設定皆放在該工具上。
* **Managed Agents**：在代理工具集中預設開啟，不提供 `max_uses`、`citations` 或 `cache_control`。

網路搜尋工具讓 Claude 能直接存取即時網路內容，使其能以超出知識截止日期的最新資訊回答問題。回應中包含從搜尋結果取得之來源的引用。

使用 `web_search_20260209` 及更新版本時，Claude 可以撰寫並執行程式碼，在搜尋結果進入「context window」（上下文視窗）之前先進行篩選（**dynamic filtering**，動態篩選），只保留相關資訊。動態篩選適用於 Claude 4.6 及更新的模型，以及 [Claude Mythos Preview](https://anthropic.com/glasswing)。

網路搜尋工具有三個版本可用：

* `web_search_20250305`：基本網路搜尋
* `web_search_20260209`：新增[動態篩選](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#dynamic-filtering)
* `web_search_20260318`：新增適用於代理式工作流程的[回應納入](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#response-inclusion)控制

本頁範例使用 `web_search_20250305` 進行基本搜尋，並使用 `web_search_20260318` 進行動態篩選。

<Note>
  對於 [Claude Mythos Preview](https://anthropic.com/glasswing)，網路搜尋支援 Claude API、Claude Models on Google Cloud (Google managed) 以及 Microsoft Foundry。
</Note>

關於網路搜尋的零資料保留（Zero Data Retention）資格及相關的 `allowed_callers` 設定，請參閱[伺服器工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#zdr-and-allowed-callers)。

關於模型支援，請參閱[工具參考](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-reference)。

若要在傳送請求之前檢查模型是否接受網路搜尋，請從 Models API 讀取其 `capabilities.server_tools.web_search.supported` 值。[使用 Models API](https://platform.claude.com/docs/zh-TW/models/overview#using-the-models-api) 說明了此欄位。

## 網路搜尋的運作方式

當您將網路搜尋工具加入 API 請求時：

1. Claude 根據提示決定何時進行搜尋。
2. API 執行搜尋並將結果提供給 Claude。此過程可能在單一請求中重複多次。
3. 在其回合結束時，Claude 提供附有引用來源的最終回應。

### Claude 何時進行搜尋

當請求依賴於最新、會變動或超出其訓練資料範圍的資訊時，Claude 會進行搜尋：

* 近期事件、新聞或公告
* 目前的價格、費率、比分或統計數據
* 可能已變更的特定組織、人物或產品的資訊
* 明確要求搜尋或查詢某些內容

當請求涉及穩定的知識時，Claude 會直接回答而不進行搜尋：

* 既定事實、數學、科學基礎知識或程式設計概念
* 創意寫作或腦力激盪
* 分析對話中已提供的內容
* 對話回合與問候

觸發行為可透過您的系統提示來引導：您可以鼓勵 Claude 更積極地搜尋，或偏好直接回答。若需強制限制，請使用 [`max_uses`](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#max-uses) 來限制一個回合中的搜尋次數。

### 動態篩選

使用基本網路搜尋時，每個搜尋結果都會載入 Claude 的上下文視窗，而其中許多內容可能與請求無關。使用 `web_search_20260209` 或更新版本時，Claude 會改為撰寫並執行程式碼先篩選結果，因此只有相關內容會進入上下文視窗。這可減少大量搜尋請求的 token 使用量。

動態篩選是從[程式碼執行](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)內部執行網路搜尋：在 `web_search_20260209` 及更新版本中，工具的 `allowed_callers` 欄位預設為 `["code_execution_20260120"]`，且當動態篩選執行時，API 會自動為該請求佈建所需的程式碼執行環境。您不需要自行將程式碼執行工具加入 `tools`。以此方式進行的程式碼執行呼叫，除了標準 token 費用外，不會產生額外費用。

若要直接呼叫網路搜尋而不使用動態篩選，請設定 `allowed_callers: ["direct"]`。不支援程式化工具呼叫的模型需要此設定。若未設定，API 會回傳 400 錯誤，提示您進行設定。

<Note>
  網路搜尋工具（無論是否使用動態篩選）可在 Claude API、[Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws)、[Claude Models on Google Cloud (Anthropic managed)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-models-on-google-cloud/anthropic-managed) 以及 [Microsoft Foundry](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) 上使用。在 Microsoft Foundry 上，[託管於 Azure](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry#additional-features-not-supported-when-hosted-on-azure) 的部署僅支援基本網路搜尋工具（`web_search_20250305`，不含動態篩選）。託管於 Anthropic 的部署支援所有版本。在 Claude Models on Google Cloud (Google managed) 上，僅提供基本網路搜尋工具（不含動態篩選）。
</Note>

以下範例使用 `web_search_20260318`：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio."
        }
      ],
      "tools": [{
        "type": "web_search_20260318",
        "name": "web_search"
      }]
    }'
  ```

  ```bash CLI
  ant messages create <<'YAML'
  model: claude-opus-5-5
  max_tokens: 4096
  messages:
    - role: user
      content: >-
        Search for the current prices of AAPL and GOOGL, then calculate
        which has a better P/E ratio.
  tools:
    - type: web_search_20260318
      name: web_search
  YAML
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[
          {
              "role": "user",
              "content": "Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio.",
          }
      ],
      tools=[{"type": "web_search_20260318", "name": "web_search"}],
  )
  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:
          "Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio."
      }
    ],
    tools: [{ type: "web_search_20260318", name: "web_search" }]
  });

  console.log(response);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new UserMessageParam { Content = "Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio." }],
      Tools = [new ToolUnion(new WebSearchTool20260318())]
  };

  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("Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio.")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfWebSearchTool20260318: &anthropic.WebSearchTool20260318Param{}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

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

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

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio.")
          .addTool(WebSearchTool20260318.builder().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' => 'Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio.'],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [
          [
              'type' => 'web_search_20260318',
              'name' => 'web_search',
          ],
      ],
  );

  echo $message;
  ```

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

  message = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      { role: "user", content: "Search for the current prices of AAPL and GOOGL, then calculate which has a better P/E ratio." }
    ],
    tools: [{
      type: "web_search_20260318",
      name: "web_search"
    }]
  )
  puts message
  ```
</CodeGroup>

## 如何使用網路搜尋

<Note>
  網路搜尋預設為您的組織啟用，除非管理員已在 [Claude Console](https://platform.claude.com/settings/capabilities) 中將其停用；管理員也可以在該處限制其搜尋的網域。若已停用，包含此工具的 Messages API 請求會失敗並回傳 400 `invalid_request_error`，表示網路搜尋未啟用，而非在搜尋結果中回傳[錯誤代碼](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#errors)。
</Note>

關於您組織的網路搜尋設定如何套用於 Claude Managed Agents 工作階段，請參閱[限制網路搜尋與網頁擷取網域](https://platform.claude.com/docs/zh-TW/managed-agents/tools-web-restrictions)。

在您的 API 請求中提供網路搜尋工具：

<CodeGroup>
  ```bash cURL
  curl https://api.anthropic.com/v1/messages \
    -H "x-api-key: $ANTHROPIC_API_KEY" \
    -H "anthropic-version: 2026-10-21" \
    -H "content-type: application/json" \
    -d '{
      "model": "claude-opus-5-5",
      "max_tokens": 4096,
      "messages": [
        {
          "role": "user",
          "content": "What is the weather in NYC?"
        }
      ],
      "tools": [{
        "type": "web_search_20250305",
        "name": "web_search",
        "max_uses": 5
      }]
    }'
  ```

  ```bash CLI
  ant messages create \
    --model claude-opus-5-5 \
    --max-tokens 4096 \
    --message '{role: user, content: What is the weather in NYC?}' \
    --tool '{type: web_search_20250305, name: web_search, max_uses: 5}'
  ```

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

  response = client.messages.create(
      model="claude-opus-5-5",
      max_tokens=4096,
      messages=[{"role": "user", "content": "What's the weather in NYC?"}],
      tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}],
  )
  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: "What's the weather in NYC?"
      }
    ],
    tools: [
      {
        type: "web_search_20250305",
        name: "web_search",
        max_uses: 5
      }
    ]
  });

  console.log(response);
  ```

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

  var parameters = new MessageCreateParams
  {
      Model = Model.ClaudeOpus5_5,
      MaxTokens = 4096,
      Messages = [new UserMessageParam { Content = "What's the weather in NYC?" }],
      Tools = [new ToolUnion(new WebSearchTool20250305() { MaxUses = 5 })]
  };

  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("What's the weather in NYC?")),
  	},
  	Tools: []anthropic.ToolUnionParam{
  		{OfWebSearchTool20250305: &anthropic.WebSearchTool20250305Param{
  			MaxUses: anthropic.Int(5),
  		}},
  	},
  })
  if err != nil {
  	log.Fatal(err)
  }
  fmt.Println(response)
  ```

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

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

      MessageCreateParams params = MessageCreateParams.builder()
          .model(Model.CLAUDE_OPUS_5_5)
          .maxTokens(4096L)
          .addUserMessage("What's the weather in NYC?")
          .addTool(WebSearchTool20250305.builder()
              .maxUses(5L)
              .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' => "What's the weather in NYC?"],
      ],
      model: Model::CLAUDE_OPUS_5_5,
      tools: [
          [
              'type' => 'web_search_20250305',
              'name' => 'web_search',
              'max_uses' => 5,
          ],
      ],
  );

  echo $message;
  ```

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

  message = client.messages.create(
    model: Anthropic::Model::CLAUDE_OPUS_5_5,
    max_tokens: 4096,
    messages: [
      { role: "user", content: "What's the weather in NYC?" }
    ],
    tools: [{
      type: "web_search_20250305",
      name: "web_search",
      max_uses: 5
    }]
  )
  puts message
  ```
</CodeGroup>

## 工具定義

網路搜尋工具支援以下參數：

```json JSON
{
  "type": "web_search_20250305",
  "name": "web_search",

  // Optional: Limit the number of searches
  "max_uses": 5,

  // Optional: Only include results from these domains.
  // Use allowed_domains or blocked_domains, not both.
  "allowed_domains": ["example.com", "trusteddomain.org"],

  // Optional: Never include results from these domains
  "blocked_domains": ["untrustedsource.com"],

  // Optional: Localize search results
  "user_location": {
    "type": "approximate",
    "city": "San Francisco",
    "region": "California",
    "country": "US",
    "timezone": "America/Los_Angeles"
  }
}
```

所有網路搜尋工具版本都接受 `allowed_callers`，它控制 Claude 是直接呼叫網路搜尋，還是透過[動態篩選](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#dynamic-filtering)從程式碼執行中呼叫。在 `web_search_20260209` 及更新版本中，其預設值為 `["code_execution_20260120"]` 而非 `["direct"]`。關於如何設定，請參閱 [ZDR 與 allowed\_callers](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#zdr-and-allowed-callers)。`web_search_20260318` 及更新版本也接受 [`response_inclusion`](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#response-inclusion)。

### 最大使用次數

`max_uses` 參數限制單一回合中的搜尋次數。單一事實查詢通常使用 1–3 次搜尋；比較性或多實體的研究可能使用 10 次以上。

失敗的搜尋也會計入限制。如果 Claude 直接呼叫網路搜尋的次數超過允許值，`web_search_tool_result` 會是帶有 `max_uses_exceeded` 錯誤代碼的錯誤。如果 Claude 從程式碼執行中呼叫網路搜尋的次數超過允許值，該程式碼執行會以錯誤結束。

一個回合可以跨越多個請求。當請求是在 [`pause_turn`](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#the-server-side-loop-and-pause-turn) 之後恢復，或其最後一則訊息僅包含 `tool_result` 區塊時，該請求即延續同一回合。該回合中先前請求的搜尋會計入限制，除非 Claude 是透過[動態篩選](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#dynamic-filtering)從程式碼執行中執行這些搜尋。

### 網域篩選

請提供 `allowed_domains` 或 `blocked_domains`，不可同時提供兩者。若請求同時包含兩者，API 會回傳 400 錯誤。項目為不含 scheme 的純網域，可選擇性加上路徑，例如 `example.com` 或 `example.com/blog`。

完整的網域篩選規則，請參閱伺服器工具指南中的[網域篩選](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#domain-filtering)。

在 [Claude Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview) 上，請在代理工具集的 `web_search` 項目中設定這些欄位；請參閱[限制網路搜尋與網頁擷取網域](https://platform.claude.com/docs/zh-TW/managed-agents/tools-web-restrictions)。

### 在地化

`user_location` 參數可讓您根據使用者的位置將搜尋結果在地化。請至少提供 `city`、`region`、`country` 或 `timezone` 其中之一。

* `type`：位置類型（必須為 `approximate`）
* `city`：城市名稱
* `region`：地區或州
* `country`：兩個字母的 [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) 國家代碼（API 會以 400 錯誤拒絕不支援的代碼）
* `timezone`：[IANA 時區 ID](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)

在 Claude Managed Agents 上，代理工具集的 `web_search` 項目也接受 `user_location`；請參閱[網路工具設定](https://platform.claude.com/docs/zh-TW/managed-agents/tools-web-restrictions#settings)。

### 回應納入

<Note>
  需要 `web_search_20260318` 或更新版本。
</Note>

`response_inclusion` 參數控制當搜尋結果已被同一回應中已完成的[程式碼執行](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)呼叫使用時，搜尋結果區塊如何出現在 API 回應中。設定 `"response_inclusion": "excluded"` 可將這些巢狀的 `server_tool_use` 與結果區塊配對從回應中完全移除，適用於不需要原始搜尋內容的代理式工作流程。Token 用量不受影響，因為 Claude 讀取的是程式碼的輸出，而非這些區塊。預設值為 `"full"`。API 一律會完整回傳來自直接呼叫的結果，或來自在完成前暫停的程式碼執行呼叫的結果，以便您在下一個請求中傳回。

```json JSON
{
  "tools": [
    {
      "type": "web_search_20260318",
      "name": "web_search",
      "response_inclusion": "excluded"
    }
  ]
}
```

## 回應

以下是回應結構範例：

```json Output
{
  "role": "assistant",
  "content": [
    // 1. Claude's decision to search
    {
      "type": "text",
      "text": "I'll search for when Claude Shannon was born."
    },
    // 2. The search query used
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01WYG3ziw53XMcoyKL4XcZmE",
      "name": "web_search",
      "input": {
        "query": "claude shannon birth date"
      }
    },
    // 3. Search results
    {
      "type": "web_search_tool_result",
      "tool_use_id": "srvtoolu_01WYG3ziw53XMcoyKL4XcZmE",
      "content": [
        {
          "type": "web_search_result",
          "url": "https://en.wikipedia.org/wiki/Claude_Shannon",
          "title": "Claude Shannon - Wikipedia",
          "encrypted_content": "EqgfCioIARgBIiQ3YTAwMjY1Mi1mZjM5LTQ1NGUtODgxNC1kNjNjNTk1ZWI3Y...",
          "page_age": "April 30, 2025"
        }
      ]
    },
    {
      "text": "Based on the search results, ",
      "type": "text"
    },
    // 4. Claude's response with citations
    {
      "text": "Claude Shannon was born on April 30, 1916, in Petoskey, Michigan",
      "type": "text",
      "citations": [
        {
          "type": "web_search_result_location",
          "url": "https://en.wikipedia.org/wiki/Claude_Shannon",
          "title": "Claude Shannon - Wikipedia",
          "encrypted_index": "Eo8BCioIAhgBIiQyYjQ0OWJmZi1lNm..",
          "cited_text": "Claude Elwood Shannon (April 30, 1916 – February 24, 2001) was an American mathematician, electrical engineer, computer scientist, cryptographer and i..."
        }
      ]
    }
  ],
  "id": "msg_a930390d3a",
  "usage": {
    "input_tokens": 6039,
    "output_tokens": 931,
    "server_tool_use": {
      "web_search_requests": 1
    }
  },
  "stop_reason": "end_turn"
}
```

此範例顯示的是直接搜尋。當搜尋透過[動態篩選](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-search-tool#dynamic-filtering)執行時，回應還會包含[程式碼執行工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/code-execution-tool)的結果區塊，且每個巢狀的 `server_tool_use` 與 `web_search_tool_result` 配對都帶有 `caller` 欄位，用以識別發出該呼叫的程式碼執行呼叫。

### 搜尋結果

搜尋結果包含：

* `url`：來源頁面的 URL
* `title`：來源頁面的標題
* `page_age`：網站最後更新的時間
* `encrypted_content`：您在多輪對話中必須傳回的加密內容

若要繼續包含搜尋結果的對話，請將助理的內容區塊完全依照收到的原樣傳回，包括每個結果的 `encrypted_content`。API 會在後續請求中解密該內容，以在 Claude 的上下文中還原搜尋結果。若 `encrypted_content` 遺失或遭修改，請求會失敗並回傳 400 驗證錯誤。

### 引用

網路搜尋一律啟用引用，每個 `web_search_result_location` 包含：

* `url`：被引用來源的 URL
* `title`：被引用來源的標題
* `encrypted_index`：多輪對話中必須傳回的參照
* `cited_text`：最多 150 個字元的引用內容

網路搜尋引用欄位 `cited_text`、`title` 和 `url` 不計入輸入或輸出 token 使用量。

<Note>
  將 API 輸出直接顯示給終端使用者時，必須包含指向原始來源的引用。如果您要修改 API 輸出，包括在顯示給終端使用者之前重新處理或將其與您自己的資料結合，請根據與您法務團隊的諮詢結果適當地顯示引用。
</Note>

### 錯誤

當網路搜尋工具遇到錯誤（例如達到速率限制）時，Claude API 仍會回傳 200（成功）回應。錯誤會以下列結構呈現在回應主體中：

```json Output
{
  "type": "web_search_tool_result",
  "tool_use_id": "srvtoolu_a93jad",
  "content": {
    "type": "web_search_tool_result_error",
    "error_code": "max_uses_exceeded"
  }
}
```

發生錯誤時，`content` 是單一錯誤物件，而非結果區塊清單。搜尋成功但沒有符合的結果時，會回傳空的 `content` 清單，而非錯誤。

可能的錯誤代碼如下：

* `too_many_requests`：超過速率限制
* `invalid_tool_input`：無效的搜尋查詢參數
* `max_uses_exceeded`：超過網路搜尋工具的最大使用次數
* `query_too_long`：查詢超過最大長度
* `request_too_large`：搜尋請求過大，通常是因為網域篩選清單過長
* `unavailable`：發生內部錯誤

### `pause_turn` 停止原因

API 可能會暫停長時間執行的搜尋回合，並回傳 `stop_reason: "pause_turn"`。若要繼續，請在新的請求中將暫停的助理訊息原封不動地傳回。

如果 Claude 在同一組平行工具呼叫中同時呼叫網路搜尋和您的某個用戶端工具，API 會改為回傳 `stop_reason: "tool_use"`，且暫不執行搜尋。若要繼續，請回傳用戶端工具結果，API 會在下一個請求中執行搜尋。請參閱[在單一回合中混合使用伺服器工具與用戶端工具](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#mixing-server-tools-and-client-tools-in-one-turn)。

關於伺服器端迴圈與 `pause_turn` 的處理，請參閱伺服器工具指南中的[伺服器端迴圈與 pause\_turn](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools#the-server-side-loop-and-pause-turn)。

## 提示快取

若要跨回合快取工具定義，請參閱[搭配提示快取的工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/tool-use-with-prompt-caching)。

## 串流

啟用串流後，您會在串流中收到搜尋事件。搜尋執行期間會有暫停：

```sse Output
event: message_start
data: {"type": "message_start", "message": {"id": "msg_abc123", "type": "message"}}

event: content_block_start
data: {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}

// Claude's decision to search

event: content_block_start
data: {"type": "content_block_start", "index": 1, "content_block": {"type": "server_tool_use", "id": "srvtoolu_xyz789", "name": "web_search"}}

// Search query streamed
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"query\":\"latest quantum computing breakthroughs 2025\"}"}}

// Pause while search runs

// Search results streamed
event: content_block_start
data: {"type": "content_block_start", "index": 2, "content_block": {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_xyz789", "content": [{"type": "web_search_result", "title": "Quantum Computing Breakthroughs in 2025", "url": "https://example.com"}]}}

// Claude's response with citations (omitted in this example)
```

## 批次請求

您可以在 [Message Batches API](https://platform.claude.com/docs/zh-TW/build-with-claude/batch-processing) 中包含網路搜尋工具。透過 Message Batches API 進行的網路搜尋工具呼叫，其定價與一般 Messages API 請求相同。

為了保護共享容量，Batches API 會針對每個組織節流網路搜尋請求，因此包含大量搜尋的大型批次可能需要較長時間才能完成。您可以在 Claude Console 的[速率限制](https://platform.claude.com/usage/limits)頁面查看您組織的網路搜尋速率限制。若要申請更高的限制，請從該頁面聯絡業務團隊。

## 用量與定價

除了 token 用量之外，網頁搜尋的使用也會另外計費：

```json
{
  "usage": {
    "input_tokens": 105,
    "output_tokens": 6039,
    "cache_read_input_tokens": 7123,
    "cache_creation_input_tokens": 7345,
    "server_tool_use": {
      "web_search_requests": 1
    }
  }
}
```

網頁搜尋可在 Claude API 上使用，費用為**每 1,000 次搜尋 $10 美元**，另加搜尋所產生內容的標準 token 費用。在整個對話過程中擷取的網頁搜尋結果，無論是在單一回合內執行的搜尋迭代中，還是在後續的對話回合中，都會計為輸入 token。

每次網頁搜尋計為一次使用，無論回傳的結果數量多寡。發生錯誤而失敗的網頁搜尋不會計費。

## 後續步驟

<CardGroup cols={3}>
  <Card title="網頁擷取工具" icon="link" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/web-fetch-tool">
    從特定 URL 擷取並讀取內容，以即時網路內容擴充 Claude 的上下文。
  </Card>

  <Card title="伺服器工具" icon="tool" href="https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/server-tools">
    使用由 Anthropic 執行的工具：`server_tool_use` 區塊、`pause_turn` 接續，以及網域篩選。
  </Card>

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

## 可用性

網頁搜尋工具在所有模型上可供使用，且具備零資料保留和HIPAA 就緒資格。

### API 支援

#### [Messages API](https://platform.claude.com/docs/zh-TW/build-with-claude/working-with-messages)

* 可用性：可用
* 用法：在請求的 `tools` 中加入 `web_search` 工具。`max_uses`、網域清單與 `user_location` 等設定皆放在該工具上。

| 狀態             | 雲端平台                                                                                                                                                                                                                                                                                                                                                                                                                  |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 可用             | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws), [Claude Models on Google Cloud (Anthropic managed)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-models-on-google-cloud/anthropic-managed), [Microsoft Foundry (hosted on Anthropic)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry) |
| 可用<sup>1</sup> | [Claude Models on Google Cloud (Google managed)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-models-on-google-cloud/google-managed), [Microsoft Foundry (hosted on Azure)](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-in-microsoft-foundry)                                                                                                                                  |

1. 僅支援基本網頁搜尋工具（`web_search_20250305`），不含動態篩選。

#### [Managed Agents](https://platform.claude.com/docs/zh-TW/managed-agents/overview)

* 可用性：可用
* 用法：屬於代理工具集的一部分，加入工具集後即預設開啟。網域清單與 `user_location` 放在工具集的 `web_search` 項目上；不提供 `max_uses`、`citations` 與 `cache_control`。

| 狀態 | 雲端平台                                                                                                                  |
| -- | --------------------------------------------------------------------------------------------------------------------- |
| 可用 | Claude API, [Claude Platform on AWS](https://platform.claude.com/docs/zh-TW/build-with-claude/claude-platform-on-aws) |

### 資料處理

[資料處理概覽](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention#feature-eligibility)

| 項目   | 零資料保留                                                                                                                                    | HIPAA                           |
| ---- | ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| 狀態   | 符合資格（不含 [涵蓋的模型](https://platform.claude.com/docs/zh-TW/manage-claude/api-and-data-retention#model-specific-data-retention-requirements)） | 符合資格                            |
| 詳細資訊 | 即時網頁搜尋結果會在 API 回應中傳回。網頁搜尋的動態篩選不符合 ZDR 或 HIPAA 的適用資格。                                                                                     | 網頁搜尋的動態篩選不符合 ZDR 或 HIPAA 的適用資格。 |

適用端點：

* `/v1/messages` 搭配 `web_search` 工具
