Sub topic 5
Web search: grounding answers in current information
This chapter assumes you can call a responses or messages API with an API key, read JSON response bodies, and write basic Python. You should also know what tool calling is, and how function tools differ from built-in tools (covered in earlier chapters).
Why a model needs web search
A language model learns from a fixed snapshot of text. Anything that happened after its training cutoff is unknown to it, and it may answer confidently anyway. Software release numbers, prices, news, and documentation changes all go stale.
Web search fixes this by grounding the answer. Grounding means the answer is based on retrieved sources instead of only on what the model memorized. With a built-in web search tool, the provider runs the search for you. The model decides whether to search, writes a query, reads the results, and then writes a final answer. You make one API request and get one response back.
The working model
The provider runs a loop on its servers. Your code does not see each step as a separate round trip.
The model may search more than once. It may also skip searching if it judges the question answerable without it. That decision is made per request, so the same tool declaration can lead to zero, one, or several searches.
Enabling web search with the Responses API
Add a tool of type web_search to the tools list.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "web_search"}],
input="What are the most recent stable releases of Python?",
)
print(response.output_text)output_text is a convenience property. It joins the text of the final message items. It hides everything else the response contains, including the search calls and the sources.
Reading the search calls and citations
The output field is a list of items. For a web search request it normally holds at least one web_search_call item and one message item. The message holds the answer text and its annotations. An annotation is a structured note attached to a span of the text. For web search, the useful kind is url_citation.
for item in response.output:
if item.type == "web_search_call":
print("search call:", item.status)
elif item.type == "message":
for part in item.content:
for ann in getattr(part, "annotations", []) or []:
if ann.type == "url_citation":
print(ann.title, ann.url)This loop is a debugging and auditing tool. It answers two questions:
- Did the model search at all? If there is no
web_search_callitem, the answer came from model memory. - Which pages support the answer? Each
url_citationgives a title and a URL.
A url_citation annotation also carries character offsets (start_index and end_index) that mark which part of the answer text the source supports. You can use these to render footnotes or inline links.
The table below summarizes the items you will see.
| Item type | What it tells you | Typical use |
|---|---|---|
| `web_search_call` | A search was performed, with a status such as `completed` | Confirm the tool ran, log usage |
| `message` | The final answer, split into content parts | Display text |
| `url_citation` annotation | A source page tied to a span of text | Show sources, verify claims |
Exact field names can change between SDK versions, so print response.output once during development and check what your version returns.
Showing sources to users
Citations are only useful if the user can see them. Provider terms for search tools commonly expect you to display the sources clearly and keep links clickable. Check the current terms for your provider. A simple approach is to list unique sources under the answer.
def collect_sources(response):
seen = {}
for item in response.output:
if item.type != "message":
continue
for part in item.content:
for ann in getattr(part, "annotations", []) or []:
if ann.type == "url_citation":
seen[ann.url] = ann.title
return seen
for url, title in collect_sources(response).items():
print(f"- {title}: {url}")Using a dictionary keyed by URL removes duplicates, since one page is often cited several times.
Web search on Anthropic
Anthropic exposes web search as a versioned server tool. The tool has a type that includes a date, a name, and an optional max_uses that caps the number of searches in one request.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=[
{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 3,
}
],
messages=[
{"role": "user", "content": "What are the latest developments in solid-state batteries?"}
],
)
for block in message.content:
if block.type == "text":
print(block.text)The shape of the response differs from the OpenAI one. Here message.content is a list of blocks. Besides text blocks, you will see blocks that record the search query and its results. Text blocks can carry their own citation objects. The idea is the same: the answer, the search activity, and the sources all come back in one response. Printing only text blocks, as above, shows the prose but drops the citations and the search trace.
Note the version string in the tool type. When the provider releases a newer version, the old one keeps working for a time, but it may lack newer features. Pin the version deliberately and review it when you upgrade your SDK.
Common errors
- Assuming the model always searches. The model chooses. If freshness matters, say so in the instructions, for example "Search the web before answering questions about current events." The tool-choice chapter covers forcing a call.
- Reading only
output_text. You lose the citations and cannot tell whether a search happened. - Treating citations as proof. A citation shows where the model got text. It does not guarantee the model summarized the page correctly. For high-stakes claims, open the source.
- Trusting page content. Search results come from the open web. A page can contain text written to manipulate the model. Treat results as data, never as instructions. The security chapter returns to this.
- Hard-coding field names without checking. Print the raw response and verify attribute names against your installed SDK.
- Ignoring cost. Each search is billed, and the retrieved text adds input tokens. Use limits such as
max_useswhere the provider supports them.
A quick checklist
- Declare the tool in
tools. - Add an instruction when the question needs fresh data.
- Inspect
outputfor search call items. - Extract and display the
url_citationsources. - Cap searches where possible and monitor cost.
Exercise
A teammate's code prints only response.output_text from a web search request. A user reports an answer that looks outdated. Name two things you would check in response.output, and explain what each result would tell you.
Show answer
First, check for a web_search_call item. If none exists, the model answered from memory and did not search, so you should tighten the instructions or force the tool. Second, check the url_citation annotations on the message. If they exist, read the cited pages and their dates. An outdated answer with citations suggests the search returned old pages or the model summarized them badly, which points to the query or the sources rather than a missing search.
Exercise
Why does the collect_sources function store results in a dictionary keyed by URL instead of appending to a list?
Show answer
One source page is often cited for several different spans of the answer. Keying by URL keeps one entry per page, so the user sees a clean list of unique sources instead of repeated links.