網頁搜尋工具讓 Claude 能夠直接存取即時網頁內容,使其能夠使用超出其知識截止日期的最新資訊來回答問題。Claude 會在回答中自動引用搜尋結果中的來源。

請透過我們的意見回饋表單分享您使用網頁搜尋工具的體驗。

支援的模型

網頁搜尋可用於:

  • Claude Opus 4 (claude-opus-4-20250514)
  • Claude Sonnet 4 (claude-sonnet-4-20250514)
  • Claude Sonnet 3.7 (claude-3-7-sonnet-20250219)
  • Claude Sonnet 3.5 (新版) (claude-3-5-sonnet-latest)
  • Claude Haiku 3.5 (claude-3-5-haiku-latest)

網頁搜尋的運作方式

當您在 API 請求中添加網頁搜尋工具時:

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

如何使用網頁搜尋

您組織的管理員必須在 Console 中啟用網頁搜尋。

在您的 API 請求中提供網頁搜尋工具:

curl https://api.anthropic.com/v1/messages \
    --header "x-api-key: $ANTHROPIC_API_KEY" \
    --header "anthropic-version: 2023-06-01" \
    --header "content-type: application/json" \
    --data '{
        "model": "claude-opus-4-20250514",
        "max_tokens": 1024,
        "messages": [
            {
                "role": "user",
                "content": "How do I update a web app to TypeScript 5.5?"
            }
        ],
        "tools": [{
            "type": "web_search_20250305",
            "name": "web_search",
            "max_uses": 5
        }]
    }'

工具定義

網頁搜尋工具支援以下參數:

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

  // 選填:限制每個請求的搜尋次數
  "max_uses": 5,

  // 選填:僅包含來自這些網域的結果
  "allowed_domains": ["example.com", "trusteddomain.org"],

  // 選填:永不包含來自這些網域的結果
  "blocked_domains": ["untrustedsource.com"],

  // 選填:本地化搜尋結果
  "user_location": {
    "type": "approximate",
    "city": "San Francisco",
    "region": "California",
    "country": "US",
    "timezone": "America/Los_Angeles"
  }
}

最大使用次數

max_uses 參數限制執行的搜尋次數。如果 Claude 嘗試進行的搜尋超過允許的次數,web_search_tool_result 將返回一個帶有 max_uses_exceeded 錯誤代碼的錯誤。

網域過濾

使用網域過濾器時:

  • 網域不應包含 HTTP/HTTPS 協議(使用 example.com 而非 https://example.com
  • 子網域會自動包含(example.com 涵蓋 docs.example.com
  • 支援子路徑(example.com/blog
  • 您可以使用 allowed_domainsblocked_domains,但不能在同一請求中同時使用兩者。

本地化

user_location 參數允許您根據用戶的位置本地化搜尋結果。

  • type:位置類型(必須為 approximate
  • city:城市名稱
  • region:地區或州
  • country:國家
  • timezoneIANA 時區 ID

回應

以下是回應結構的範例:

{
  "role": "assistant",
  "content": [
    // 1. Claude 決定搜尋
    {
      "type": "text",
      "text": "I'll search for when Claude Shannon was born."
    },
    // 2. 使用的搜尋查詢
    {
      "type": "server_tool_use",
      "id": "srvtoolu_01WYG3ziw53XMcoyKL4XcZmE",
      "name": "web_search",
      "input": {
        "query": "claude shannon birth date"
      }
    },
    // 3. 搜尋結果
    {
      "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 的回應及引用
    {
      "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"
}

搜尋結果

搜尋結果包括:

  • url:來源頁面的 URL
  • title:來源頁面的標題
  • page_age:網站最後更新的時間
  • encrypted_content:加密內容,必須在多回合對話中傳回以供引用

引用

網頁搜尋始終啟用引用功能,每個 web_search_result_location 包括:

  • url:被引用來源的 URL
  • title:被引用來源的標題
  • encrypted_index:必須在多回合對話中傳回的參考。
  • cited_text:最多 150 個字符的引用內容

網頁搜尋引用字段 cited_texttitleurl 不計入輸入或輸出令牌使用量。

向最終用戶顯示網頁結果或網頁結果中包含的信息時,必須在您的用戶界面中清晰顯示並使內嵌引用可點擊。

錯誤

如果在網頁搜尋期間發生錯誤,您將收到以下形式的回應:

{
  "type": "web_search_tool_result",
  "tool_use_id": "servertoolu_a93jad",
  "content": {
    "type": "web_search_tool_result_error",
    "error_code": "max_uses_exceeded"
  }
}

以下是可能的錯誤代碼:

  • too_many_requests:超出速率限制
  • invalid_input:無效的搜尋查詢參數
  • max_uses_exceeded:超出最大網頁搜尋工具使用次數
  • query_too_long:查詢超出最大長度
  • unavailable:發生內部錯誤

pause_turn 停止原因

回應可能包含 pause_turn 停止原因,這表示 API 暫停了一個長時間運行的回合。您可以在後續請求中按原樣提供回應,讓 Claude 繼續其回合,或者如果您希望中斷對話,可以修改內容。

提示快取

網頁搜尋與提示快取兼容。要啟用提示快取,請在您的請求中添加至少一個 cache_control 斷點。系統將自動快取直到執行工具時的最後一個 web_search_tool_result 區塊。

對於多回合對話,請在最後一個 web_search_tool_result 區塊上或之後設置 cache_control 斷點,以重用快取內容。

例如,要在多回合對話中將提示快取與網頁搜尋一起使用:

import anthropic

client = anthropic.Anthropic()

# 第一個帶有網頁搜尋和快取斷點的請求
messages = [
    {
        "role": "user",
        "content": "What's the current weather in San Francisco today?"
    }
]

response1 = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    messages=messages,
    tools=[{
        "type": "web_search_20250305",
        "name": "web_search",
        "user_location": {
            "type": "approximate",
            "city": "San Francisco",
            "region": "California",
            "country": "US",
            "timezone": "America/Los_Angeles"
        }
    }]
)

# 將 Claude 的回應添加到對話中
messages.append({
    "role": "assistant",
    "content": response1.content
})

# 第二個請求,在搜尋結果之後設置快取斷點
messages.append({
    "role": "user",
    "content": "Should I expect rain later this week?",
    "cache_control": {"type": "ephemeral"}  # 快取到此點
})

response2 = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=1024,
    messages=messages,
    tools=[{
        "type": "web_search_20250305",
        "name": "web_search",
        "user_location": {
            "type": "approximate",
            "city": "San Francisco",
            "region": "California",
            "country": "US",
            "timezone": "America/Los_Angeles"
        }
    }]
)
# 第二個回應將受益於快取的搜尋結果
# 同時仍能在需要時執行新的搜尋
print(f"Cache read tokens: {response2.usage.get('cache_read_input_tokens', 0)}")

串流

啟用串流後,您將收到作為串流一部分的搜尋事件。在搜尋執行期間會有一個暫停:

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 決定搜尋

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

// 搜尋查詢串流
event: content_block_delta
data: {"type": "content_block_delta", "index": 1, "delta": {"type": "input_json_delta", "partial_json": "{\"query\":\"latest quantum computing breakthroughs 2025\"}"}}

// 搜尋執行期間暫停

// 搜尋結果串流
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 的回應及引用(本例中省略)

批次請求

您可以在 Messages Batches API 中包含網頁搜尋工具。通過 Messages Batches API 進行的網頁搜尋工具調用的價格與常規 Messages API 請求中的相同。

使用量和定價

網頁搜尋使用量除了令牌使用量外還需額外收費:

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

網頁搜尋在 Anthropic API 上的價格為每 1,000 次搜尋 $10,外加搜尋生成內容的標準令牌費用。在對話過程中檢索的網頁搜尋結果計為輸入令牌,包括在單次回合中執行的搜尋迭代和後續對話回合中的搜尋。

每次網頁搜尋計為一次使用,無論返回的結果數量如何。如果在網頁搜尋期間發生錯誤,則不會對該網頁搜尋收費。