Claude Web Search Tool: Real-Time Data in Your AI App

Every AI model has a training cutoff. Claude Sonnet 4.6 was trained on data up to a certain point in time, which means it cannot tell you the current share price of a stock, the outcome of a match played last night, or the contents of an article published yesterday. For a significant category of questions — anything involving recent events, live data, or current news — Claude without web access will either refuse to answer or produce outdated information.
The web search tool solves this. By enabling web search as a tool in your Claude API requests, you give Claude the ability to request live web searches during a conversation, incorporate the results into its context, and produce answers grounded in current, verifiable information.
This post covers the complete web search integration — enabling it, controlling it, and building applications that make effective use of real-time data.
How Claude's Web Search Works
When web search is enabled, Claude follows a modified version of the standard tool use loop:
- The user asks a question that Claude determines requires current information
- Claude generates a tool_use block requesting a web search with a specific query string
- Anthropic's infrastructure (or your own integration) executes the search and retrieves results
- The search results are returned to Claude as tool_result blocks containing page titles, URLs, and content snippets
- Claude synthesises the search results into a coherent, sourced answer
In the managed version (using Anthropic's built-in web search), steps 3 and 4 happen automatically — you do not write the search execution code. In a custom integration, you handle those steps yourself.
Enabling the Built-In Web Search Tool
Anthropic provides a managed web_search tool that you can include in your API request without writing any search infrastructure. This is the recommended starting point.
1import anthropic
2
3client = anthropic.Anthropic()
4
5response = client.messages.create(
6 model="claude-sonnet-4-6",
7 max_tokens=4096,
8 tools=[
9 {
10 "type": "web_search_20250305",
11 "name": "web_search"
12 }
13 ],
14 messages=[{
15 "role": "user",
16 "content": "What were the main announcements from Anthropic in the last 30 days?"
17 }]
18)
19
20# The response will include source citations
21print(response.content[-1].text)When you include the managed web_search tool, Anthropic handles the actual search execution. You receive a complete text response with citations woven into the answer.
Web Search is Available on Select Models
The managed web search tool is available for Claude Sonnet 4.6 and Claude Opus 4.6. It is not available on Haiku models at the time of writing. Check the Anthropic documentation for the current list of models that support web search, as availability expands with new releases.
Controlling Search Behaviour
You can customise how Claude uses web search to match your application's needs.
Limiting Search to Specific Domains
To restrict Claude to trusted sources — useful for enterprise applications where you want results only from authoritative industry publications or your own documentation:
1response = client.messages.create(
2 model="claude-sonnet-4-6",
3 max_tokens=4096,
4 tools=[
5 {
6 "type": "web_search_20250305",
7 "name": "web_search",
8 "allowed_domains": ["bbc.co.uk", "reuters.com", "apnews.com"]
9 }
10 ],
11 messages=[{"role": "user", "content": "What is the current situation in..."}]
12)Blocking Specific Domains
If certain domains consistently produce poor quality or irrelevant results:
1tools=[
2 {
3 "type": "web_search_20250305",
4 "name": "web_search",
5 "blocked_domains": ["pinterest.com", "quora.com"]
6 }
7]Controlling Max Searches Per Turn
By default, Claude can perform multiple searches in a single turn to gather comprehensive information. You can cap this to control latency and cost:
1tools=[
2 {
3 "type": "web_search_20250305",
4 "name": "web_search",
5 "max_uses": 3
6 }
7]Handling Search Citations in Your Application
When Claude uses web search and returns a response, it includes source citations. The response content includes web_search_result blocks alongside text blocks.
For consumer-facing applications, you should surface these citations so users can verify the information:
1for block in response.content:
2 if block.type == "text":
3 print("Response:", block.text)
4 elif hasattr(block, 'type') and block.type == "tool_result":
5 # Search results are embedded in the response flow
6 passClaude's text response will typically include inline source references like "According to Reuters (reuters.com)..." which appear naturally in the output.
Always Surface Sources to Users
For any application that surfaces search-grounded answers to users — whether a chatbot, a research assistant, or a news summariser — always display the cited sources in your UI. Users need to know where information came from, especially for factual claims. Including source links also builds trust and lets users verify answers independently.
Building a Real-Time Research Assistant
Here is a practical pattern for a research assistant that automatically searches when it needs current information but answers from its own knowledge when it does not:
1import anthropic
2
3client = anthropic.Anthropic()
4
5system_prompt = """You are a research assistant specialising in technology, business, and AI news.
6
7Answer questions using your existing knowledge when possible.
8Use web search when:
9- The user asks about events from the past 6 months
10- The user asks for current prices, statistics, or market data
11- The user explicitly asks for "latest" or "recent" information
12
13When you use web search, always cite your sources in your response.
14"""
15
16def research_assistant(user_question: str) -> str:
17 response = client.messages.create(
18 model="claude-sonnet-4-6",
19 max_tokens=4096,
20 system=system_prompt,
21 tools=[
22 {
23 "type": "web_search_20250305",
24 "name": "web_search",
25 "max_uses": 5
26 }
27 ],
28 messages=[{"role": "user", "content": user_question}]
29 )
30
31 # Extract the final text response
32 for block in response.content:
33 if block.type == "text":
34 return block.text
35
36 return "I was unable to generate a response."
37
38# Example usage
39answer = research_assistant("What are the latest token pricing changes from Anthropic?")
40print(answer)Custom Web Search Integration
If you need to use your own search provider — Brave, Serper, SerpAPI, or a private enterprise search index — you implement web search using the standard tool use pattern from the previous post.
1import anthropic
2import requests
3import json
4
5client = anthropic.Anthropic()
6
7# Define a custom search tool pointing to your provider
8custom_search_tool = {
9 "name": "search_web",
10 "description": "Search the internet for current information on a topic. Returns titles, URLs, and snippets from top results.",
11 "input_schema": {
12 "type": "object",
13 "properties": {
14 "query": {
15 "type": "string",
16 "description": "The search query to look up"
17 }
18 },
19 "required": ["query"]
20 }
21}
22
23def execute_search(query: str) -> str:
24 """Call your preferred search API here"""
25 # Example using Brave Search API
26 headers = {"X-Subscription-Token": "YOUR_BRAVE_API_KEY"}
27 params = {"q": query, "count": 5}
28 response = requests.get(
29 "https://api.search.brave.com/res/v1/web/search",
30 headers=headers,
31 params=params
32 )
33 results = response.json()
34
35 # Format results for Claude
36 formatted = []
37 for item in results.get("web", {}).get("results", []):
38 formatted.append(f"Title: {item['title']}\nURL: {item['url']}\nSnippet: {item['description']}")
39
40 return "\n\n---\n\n".join(formatted)The full tool use loop then follows the same pattern as the previous post — handle tool_use blocks, execute your search function, return results as tool_result blocks.
Pricing Considerations
Using the managed web search tool incurs costs on top of standard API token usage. Each individual search query has a per-search cost in addition to the tokens consumed by the search results being added to Claude's context.
- Every web search call adds the retrieved content to Claude's context, increasing your input token count for that turn
- Multiple searches per turn multiply both the per-search cost and the token overhead
- Use max_uses to prevent runaway search costs on open-ended queries
- Consider whether questions genuinely need real-time data before enabling search — many queries are better answered from Claude's training knowledge
Disable Web Search for Static Content Tasks
If your application summarises documents, generates code, analyses data files, or performs tasks that do not require real-time information, do not include the web search tool in those API calls. Including tools you do not need slightly increases the prompt size and may lead Claude to attempt unnecessary searches. Only include tools that are relevant to the task at hand.
Summary
Web search transforms Claude from a static knowledge base into a dynamic research tool capable of working with current information. The managed web_search tool makes integration straightforward for most use cases, while the custom tool use pattern gives you full control over your search infrastructure.
Key decisions when implementing web search:
- Use the managed web_search tool for rapid integration and Anthropic-handled infrastructure
- Use a custom search tool for private indexes, specific providers, or compliance requirements
- Control costs with max_uses and domain restrictions
- Always cite sources in consumer-facing applications
Next in Module 4: Claude Vision: Analyse Images, PDFs, and Documents.
This post is part of the Anthropic AI Tutorial Series. Previous post: Claude Tool Use Explained: Give Claude the Ability to Act.
