Anthropic 平台文档(英文全量)
To learn how zero data retention (ZDR) applies to this feature, see API and data retention.
The web search tool gives Claude direct access to real-time web content, allowing it to answer questions with up-to-date information beyond its knowledge cutoff. The response includes citations for sources drawn from search results.
With web_search_20260209 and later versions, Claude can write and run code that filters the search results before they reach the context window (dynamic filtering), keeping only relevant information. Dynamic filtering is available with Claude 4.6 and later models and Claude Mythos Preview.
Three versions of the web search tool are available:
web_search_20250305: basic web searchweb_search_20260209: adds dynamic filteringweb_search_20260318: adds response inclusion control for agentic workflows
The examples on this page use web_search_20250305 for basic search and web_search_20260318 for dynamic filtering.
For Claude Mythos Preview, web search is supported on the Claude API, Google Cloud, and Microsoft Foundry. Web search is not available for Mythos Preview on Amazon Bedrock or Claude Platform on AWS.
For web search's Zero Data Retention eligibility and the related allowed_callers configuration, see Server tools.
For model support, see the Tool reference.
How web search works
When you add the web search tool to your API request:
- Claude determines when to search based on the prompt.
- The API runs the searches and provides Claude with the results. This process can repeat multiple times throughout a single request.
- At the end of its turn, Claude provides a final response with cited sources.
When Claude searches
Claude searches when the request depends on information that is current, changing, or outside its training data:
- Recent events, news, or announcements
- Current prices, rates, scores, or statistics
- Information about specific organizations, people, or products that might have changed
- Explicit requests to search or look something up
Claude answers directly without searching when the request draws on stable knowledge:
- Established facts, math, science fundamentals, or coding concepts
- Creative writing or brainstorming
- Analysis of content already provided in the conversation
- Conversational turns and greetings
Triggering is steerable through your system prompt: you can encourage Claude to search more readily or to prefer answering directly. For a hard constraint, use max_uses to cap the number of searches for each request.
Dynamic filtering
With basic web search, every search result is loaded into Claude's context window, and much of that content can be irrelevant to the request. With web_search_20260209 or later, Claude instead writes and runs code that filters the results first, so only relevant content reaches the context window. This reduces token use on search-heavy requests.
Dynamic filtering runs web search from inside code execution: on web_search_20260209 and later, the tool's allowed_callers field defaults to ["code_execution_20260120"], and when dynamic filtering runs, the API provisions the code execution it needs for the request automatically. You don't need to add the code execution tool to tools yourself. There are no additional charges for code execution calls made this way beyond the standard token costs.
To call web search directly, without dynamic filtering, set allowed_callers: ["direct"]. Models that don't support programmatic tool calling require this setting. Without it, the API returns a 400 error that tells you to set it.
The web search tool (with and without dynamic filtering) is available on the Claude API, Claude Platform on AWS, and Microsoft Foundry. On Microsoft Foundry, deployments hosted on Azure support only the basic web search tool (web_search_20250305, without dynamic filtering). Deployments hosted on Anthropic support all versions. On Google Cloud, only the basic web search tool (without dynamic filtering) is available. Web search is not available on Amazon Bedrock.
The following examples use web_search_20260318:
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",
"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"
}]
}'ant messages create <<'YAML'
model: claude-opus-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
YAMLclient = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-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)const client = new Anthropic();
const response = await client.messages.create({
model: "claude-opus-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);AnthropicClient client = new();
var parameters = new MessageCreateParams
{
Model = Model.ClaudeOpus5,
MaxTokens = 4096,
Messages = [new() { Role = Role.User, 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);client := anthropic.NewClient()
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
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)import com.anthropic.models.messages.WebSearchTool20260318;
void main() {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_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);
}$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: 'claude-opus-5',
tools: [
[
'type' => 'web_search_20260318',
'name' => 'web_search',
],
],
);
echo $message;client = Anthropic::Client.new
message = client.messages.create(
model: "claude-opus-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 messageHow to use web search
Web search is enabled for your organization unless an administrator has disabled it in the Claude Console, where they can also restrict which domains it searches. If it's disabled, a request that includes the tool fails with a 400 invalid_request_error that says web search is not enabled, rather than an error code inside a search result.
These organization-level settings in the Claude Console apply to Messages API requests only. Claude Managed Agents sessions use only the per-tool allowed_domains and blocked_domains lists on the agent toolset; see Restrict web search and web fetch domains.
Provide the web search tool in your API request:
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",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "What is the weather in NYC?"
}
],
"tools": [{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 5
}]
}'ant messages create \
--model claude-opus-5 \
--max-tokens 1024 \
--message '{role: user, content: What is the weather in NYC?}' \
--tool '{type: web_search_20250305, name: web_search, max_uses: 5}'client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": "What's the weather in NYC?"}],
tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}],
)
print(response)const client = new Anthropic();
const response = await client.messages.create({
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: "What's the weather in NYC?"
}
],
tools: [
{
type: "web_search_20250305",
name: "web_search",
max_uses: 5
}
]
});
console.log(response);AnthropicClient client = new();
var parameters = new MessageCreateParams
{
Model = Model.ClaudeOpus5,
MaxTokens = 1024,
Messages = [new() { Role = Role.User, Content = "What's the weather in NYC?" }],
Tools = [new ToolUnion(new WebSearchTool20250305() { MaxUses = 5 })]
};
var message = await client.Messages.Create(parameters);
Console.WriteLine(message);client := anthropic.NewClient()
response, err := client.Messages.New(context.TODO(), anthropic.MessageNewParams{
Model: anthropic.ModelClaudeOpus5,
MaxTokens: 1024,
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)import com.anthropic.models.messages.WebSearchTool20250305;
void main() {
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model(Model.CLAUDE_OPUS_5)
.maxTokens(1024L)
.addUserMessage("What's the weather in NYC?")
.addTool(WebSearchTool20250305.builder()
.maxUses(5L)
.build())
.build();
Message response = client.messages().create(params);
IO.println(response);
}$client = new Client();
$message = $client->messages->create(
maxTokens: 1024,
messages: [
['role' => 'user', 'content' => "What's the weather in NYC?"],
],
model: 'claude-opus-5',
tools: [
[
'type' => 'web_search_20250305',
'name' => 'web_search',
'max_uses' => 5,
],
],
);
echo $message;client = Anthropic::Client.new
message = client.messages.create(
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{ role: "user", content: "What's the weather in NYC?" }
],
tools: [{
type: "web_search_20250305",
name: "web_search",
max_uses: 5
}]
)
puts messageTool definition
The web search tool supports the following parameters:
{
"type": "web_search_20250305",
"name": "web_search",
// Optional: Limit the number of searches per request
"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"
}
}All web search tool versions accept allowed_callers, which controls whether Claude calls web search directly or from code execution through dynamic filtering. On web_search_20260209 and later it defaults to ["code_execution_20260120"] instead of ["direct"]. See Server tools for how to configure it. web_search_20260318 and later also accept response_inclusion.
Max uses
The max_uses parameter limits the number of searches performed. If Claude attempts more searches than allowed, the web_search_tool_result is an error with the max_uses_exceeded error code.
Simple factual queries typically use 1–3 searches; comparative or multientity research can use 10 or more. For guidance on choosing a value, see Server tools.
Domain filtering
Provide allowed_domains or blocked_domains, not both. If a request includes both, the API returns a 400 error. Entries are bare domains with an optional path, for example example.com or example.com/blog, without a scheme.
For the full domain filtering rules, see Domain filtering in the Server tools guide.
On Claude Managed Agents, set these fields on the web_search entry of the agent toolset; see Restrict web search and web fetch domains.
Localization
The user_location parameter allows you to localize search results based on a user's location. Provide at least one of city, region, country, or timezone.
type: The type of location (must beapproximate)city: The city nameregion: The region or statecountry: The two-letter ISO 3166-1 alpha-2 country code. The API rejects unsupported country codes with a 400 error.timezone: The IANA timezone ID.
On Claude Managed Agents, the web_search entry of the agent toolset accepts a user_location object with the same fields. The API rejects an unsupported country code with a 400 error when you create or update the agent, or when you create or update a session that supplies the setting. See Restrict web search and web fetch domains.
Response inclusion
Requires web_search_20260318 or later.
The response_inclusion parameter controls how search result blocks appear in the API response when the result was consumed by a completed code execution call in the same turn. Set "response_inclusion": "excluded" to drop those nested server_tool_use and result block pairs entirely from the response, reducing output token costs for agentic workflows that don't need to echo raw search content back to the client. The default is "full". Results from direct calls, or from code execution calls that paused before completing, are always returned in full so they can be sent back on the next turn.
{
"tools": [
{
"type": "web_search_20260318",
"name": "web_search",
"response_inclusion": "excluded"
}
]
}Response
Here's an example response structure:
{
"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"
}This example shows a direct search. When a search runs through dynamic filtering, the response also contains the code execution tool's result blocks, and each nested server_tool_use and web_search_tool_result pair carries a caller field identifying the code execution call that made it.
Search results
Search results include:
url: The URL of the source pagetitle: The title of the source pagepage_age: When the site was last updatedencrypted_content: Encrypted content that you must pass back in multi-turn conversations
To continue a conversation that contains search results, send the assistant's content blocks back exactly as you received them, including each result's encrypted_content. The API decrypts that content on later turns to restore the search results in Claude's context. If encrypted_content is missing or modified, the request fails with a 400 validation error.