网络搜索工具使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": "如何将网络应用更新到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的回答带有引用(本例中省略)

批量请求

您可以在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美元,外加搜索生成内容的标准令牌费用。在整个对话中检索的网络搜索结果计为输入令牌,包括在单个回合中执行的搜索迭代和后续对话回合中的搜索。

每次网络搜索计为一次使用,无论返回的结果数量如何。如果在网络搜索期间发生错误,则不会对该网络搜索收费。