Web Search for AI Agents: A Practical Guide to Real-Time Information Retrieval
Learn how to connect AI agents to current, verifiable information through query rewriting, time filters, source ranking, and citation verification. This guide covers the retrieval workflow, a modular architecture, illustrative Python code, and engineering considerations for reliable implementation.
1. Why AI Agents Need External Information
A large language model’s parameters remain fixed after training. Its answers therefore rely on statistical knowledge within the scope of its training data. User tasks, however, often concern the present: whether a policy has changed, whether the latest release of an open-source library introduces breaking changes, or what a company announced today.
An agent that relies entirely on parametric memory may give an outdated answer with the same confidence as a correct one, making the problem difficult for users to detect.
Retrieval connects a model’s internal knowledge with external information. It does not replace reasoning; it supplies current, verifiable material for that reasoning.
2. The Core Retrieval Workflow
A practical web-enabled agent typically follows six steps:
- Decide whether external information is needed. Determine whether to answer directly or initiate a search based on the question.
- Generate search queries. Convert the natural-language question into keywords or phrases suitable for retrieval.
- Apply constraints. Specify the time range, source types, languages, and geographic scope.
- Retrieve and clean results. Extract page content and remove advertisements and duplicates.
- Verify sources and preserve citations. Assess source credibility, retain provenance, and determine whether the evidence is sufficient.
- Generate the answer. Cite supporting sources and identify what remains uncertain.
Every step can fail. An incorrect decision at the first stage can trigger unnecessary searches, increasing latency and cost. Poor query rewriting can retrieve irrelevant material. Without constraints, cleaning, and verification, the model may reason over noise and produce conclusions that appear well supported but are not reliable.
3. Four Essential Capabilities
3.1 Query Rewriting
User questions are often conversational and omit context. A question such as “Does it still support that?” contains references that must be resolved before it becomes a useful search query.
The query-rewriting module should use the conversation history to resolve those references and split the question into subqueries where necessary. A common approach is to have the model generate several candidate queries, then remove candidates that cover substantially the same topic.
Rewriting also needs boundaries. Expanding too broadly introduces noise; narrowing too aggressively can exclude important results. One practical safeguard is to retain the original question as a candidate, search it alongside the rewritten queries, and rank the combined results.
3.2 Time-Range Filtering
Freshness is a central reason to use web retrieval. For questions about news, policies, or software releases, apply time constraints during retrieval rather than relying solely on manual filtering afterward.
The task may provide enough information to derive a time window. Expressions such as “the past week,” “this year,” or “the previous major release” should be translated into specific start and end dates. If the intended range cannot be inferred, ask the user instead of silently applying a default.
A page’s publication date may differ from its last update date. For pages that change over time, record the retrieval timestamp as well as the publication date to support later review.
3.3 Authoritative Source Filtering
Search results are not equally trustworthy. Sources can be grouped into tiers, such as official documentation, standards organizations, academic publications, established news outlets, forums, and personal blogs.
The aim is not simply to exclude lower-tier sources. Higher-tier sources should take priority when establishing facts, while other sources can provide leads or supplementary context.
Domain allowlists and blocklists are straightforward to implement but can be costly to maintain. A more robust approach combines domain rules with content signals, such as whether the page identifies its author and date or cites primary sources.
3.4 Citation Verification
Verification should establish that each factual claim in the answer is supported by its sources.
One implementation approach is to break the answer into individual claims and check whether each claim is semantically consistent with the cited passage. Unsupported claims should be removed or explicitly labeled as speculation.
The output should retain source titles, links, and access timestamps so users can review the evidence themselves.
4. System Architecture
User question|v[Intent assessment] ── No retrieval needed ──> Generate answer directly|| Retrieval neededv[Query rewriting + constraint generation](Time range / source tier / language)|v[Search execution] → Multiple result sets|v[Deduplication · Content extraction · Source classification]|v[Relevance ranking · Passage selection]|v[Answer generation + claim verification]|vFinal answer with citations
These modules can be deployed and replaced independently. The retrieval layer and model layer should exchange structured data rather than placing entire raw web pages into the prompt.
5. Implementation Example
The following illustrative code shows how data moves between modules. The search interface is hypothetical and should be replaced with the client for the search service used in the actual project.
from dataclasses import dataclassfrom datetime import date, timedelta@dataclassclass SearchConstraint:start: date | None = Noneend: date | None = Nonemin_source_level: int = 2 # Lower values indicate greater authority; 1 means an official primary sourcelanguages: tuple[str, ...] = ("zh", "en")def rewrite_queries(question: str, history: list[str], llm) -> list[str]:"""Resolve references using conversation history and generate candidate queries."""prompt = ("Use the conversation history to resolve references in the question. ""Output 3 complementary search queries, one per line.\n"f"History: {history}\nQuestion: {question}")candidates = llm.generate(prompt).splitlines()# Keep the original question to reduce drift from the user's intentreturn list(dict.fromkeys([question, *candidates]))[:4]def search_with_constraints(queries, constraint, search_client):results = []for q in queries:results += search_client.search(query=q,date_from=constraint.start,date_to=constraint.end,languages=constraint.languages,)return resultsdef filter_and_dedupe(results, constraint):seen, kept = set(), []# Sort by source tier so the highest-rated result for each URL is retainedfor r in sorted(results, key=lambda x: x["source_level"]):if r["source_level"] > constraint.min_source_level:continueif r["url"] in seen:continueseen.add(r["url"])kept.append(r)return keptdef last_week() -> SearchConstraint:today = date.today()return SearchConstraint(start=today - timedelta(days=7), end=today)
Several design choices are worth noting.
First, retaining the original question is a low-cost safeguard against query rewriting that misinterprets the user’s intent.
Second, the filtering function sorts results by source tier before deduplication. If multiple records share a URL, the record with the highest credibility rating is retained. Although the field is named min_source_level, the comparison treats it as the largest permitted numeric tier: with a value of 2, tiers 1 and 2 pass.
Third, a separate function generates the time window, making it easier to unit-test and to log the constraints actually used for each search.
Claim verification can follow a similar pattern: split the answer into sentences, retrieve supporting passages for each claim, and send sentences without support to a revision queue.
6. Engineering Considerations
Set Retrieval Budgets
Limit the number of searches, results per search, and amount of extracted text allowed for each task. Without these limits, an agent can fall into repeated searching.
Balance Caching and Freshness
Stable reference material can be cached, while news content needs a shorter cache lifetime. Store the retrieval timestamp in each cache record.
Extract Content Conservatively
Navigation menus, comments, and promotional material can interfere with model judgment. Preserve paragraph boundaries after extraction so supporting passages remain easy to locate and cite.
Treat Web Content as Untrusted Data
Retrieved pages may contain text designed to change the model’s behavior. Place retrieved content in clearly marked data sections and specify that it may be used as factual material, not executed as instructions.
Record the Retrieval Trace
Log the original and rewritten queries, applied constraints, retrieved sources, and final citations. These records are essential for diagnosing incorrect answers.
