网络搜索工具让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提供带有引用来源的最终响应。

如何使用网络搜索

您组织的管理员必须在控制台中启用网络搜索。

在您的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": "如何将Web应用程序更新到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": "我将搜索Claude Shannon的出生时间。"
    },
    // 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": "根据搜索结果,",
      "type": "text"
    },
    // 4. Claude带引用的响应
    {
      "text": "Claude Shannon于1916年4月30日出生在密歇根州的Petoskey",
      "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": "今天旧金山的当前天气如何?"
    }
]

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": "我应该预期本周晚些时候会下雨吗?",
    "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"缓存读取令牌: {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带引用的响应(在此示例中省略)

批量请求

您可以在消息批处理API中包含网络搜索工具。通过消息批处理API的网络搜索工具调用与常规消息API请求中的定价相同。

使用和定价

Web search usage is charged in addition to token usage:

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

Web search is available on the Anthropic API for $10 per 1,000 searches, plus standard token costs for search-generated content. Web search results retrieved throughout a conversation are counted as input tokens, in search iterations executed during a single turn and in subsequent conversation turns.

Each web search counts as one use, regardless of the number of results returned. If an error occurs during web search, the web search will not be billed.