Agent Planning and Retrieval-Augmented Generation: A Practical Guide
This guide explains how to build agents that fetch fresh facts instead of relying on stale model memory. It covers a five-layer architecture, when-to-retrieve decisions, structured query constraints, evidence governance, citation enforcement, evaluation, and common anti-patterns. The goal is a system that reasons well and cites verifiable evidence.
1. The Problem: Knowledge Has Boundaries, Tasks Do Not
A large model’s knowledge comes from its training corpus, so it inevitably has a knowledge cutoff. Real business tasks, however, do not stop at that point: version numbers change, prices change, policies and announcements change, and incidents and public sentiment are generated every minute. When you put an agent directly into production, the most common failure mode is not “it cannot reason” but “it reasons fluently while the facts are outdated.”
There are usually two ways to address this. The first is to keep scaling pretraining and increasing update frequency, which is expensive, slow, and cannot cover private-domain or long-tail facts. The second is retrieval-augmented generation (RAG) combined with tool-based web search: the agent actively fetches facts at the moment it needs them rather than depending on parametric memory. The second approach is generally preferred in engineering because it turns “knowledge updating” from a model training problem into an operable data and retrieval problem.
It is worth stressing that web retrieval is not as simple as adding “please search the web” to the prompt. Three things actually determine the outcome: when to retrieve, what to retrieve, and whom to trust. These three things fall squarely within the responsibility of the agent’s planning layer.
2. Overall Architecture: Treat Retrieval as a First-Class Citizen in Planning
A practical architecture typically has five layers:
- Planning layer: breaks the user goal into subtasks and tags each subtask with a “fact dependency type” (no facts needed / stable facts needed / time-sensitive facts needed).
- Retrieval intent layer: translates each subtask into a retrieval request, including the query, time range, source preferences, result count, and other constraints.
- Retrieval execution layer: invokes search capabilities to perform recall, deduplication, page fetching, segmentation, and indexing.
- Evidence layer: performs relevance judgment, source credibility grading, and conflict detection on candidate snippets, and outputs structured evidence.
- Generation and verification layer: answers based on evidence, enforces citations, and blocks cases that assert claims without evidence.
The key design principle is: the planning layer only produces a “retrieval requirement description” and does not care about the specific retrieval implementation. This way the retrieval backend can be swapped, canary-released, or fused from multiple recall paths without polluting the task planning logic.
3. Three Decisions in Planning: Whether Retrieval Is Needed
Letting the agent “search all the time” adds latency and noise, so an upfront decision is needed. In practice, a hybrid of rules and model judgment works well:
- Time-sensitivity trigger words are hit (latest, today, this year, current version, just released, price, policy effective date);
- A verifiable entity appears (product model, organization name, regulation number, place name, timestamp);
- The user explicitly asks for sources or links;
- The model’s self-assessed confidence is below a threshold, or an internal knowledge conflict is detected.
An illustrative planning output (pseudocode, structure only):
plan = {"subtasks": [{"id": "s1", "goal": "Confirm the current stable version of a component","fact_type": "time_sensitive", "search": True},{"id": "s2", "goal": "Explain the semantics of a config option introduced in that version","fact_type": "stable", "search": False},{"id": "s3", "goal": "Verify the deprecation date in the official announcement","fact_type": "time_sensitive", "search": True,"constraints": {"freshness": "90d", "source_tier": ["official"]}}]}
The fact_type field is the most valuable one: it turns “whether to go online” from an on-the-spot feeling into an auditable configuration.
4. Structuring Retrieval Requests: Make Constraints Transferable
The capabilities mentioned in the source material can be abstracted into four general retrieval constraints, which should be expressed explicitly in the request structure rather than scattered across natural language:
- Authoritative source filtering: set an admission whitelist or weights by source tier (official docs, standards bodies, mainstream media, community Q&A);
- Time range filtering: restrict recall to content published or updated within a given period, for version, price, and policy questions;
- Automatic query rewriting: split colloquial, referential, multi-intent questions into several high-quality queries;
- Multi-path recall and fusion: issue multiple queries in parallel for the same subtask, then deduplicate and rank them together.
def build_query(subtask):return {"q": subtask["goal"],"freshness": subtask.get("constraints", {}).get("freshness"),"source_tier": subtask.get("constraints", {}).get("source_tier", []),"rewrite": {"split_multi_intent": True, "expand_synonyms": True},"top_k": 8}
Query rewriting deserves a separate note. User input often contains contextual references (“does it support that”, “when is this deprecated”), and retrieving directly loses the subject. The engineering approach is to first complete entities using the conversation history, then apply three kinds of rewriting: subject completion, terminology normalization (mapping colloquial names to standard terms), and intent splitting (breaking one question into multiple independently retrievable sub-questions). Both the rewritten and original queries are kept for traceability and evaluation.
5. Evidence Governance: From “Found It” to “Dare to Use It”
Recall is only the beginning; evidence quality determines answer quality. Three layers of governance are recommended:
Layer one, relevance filtering. Use a reranking model or rules to score titles, summaries, and body paragraphs, and remove results that only match keywords but are semantically off.
Layer two, source grading and authority first. Build tier labels and weights for sources; when conflicts arise, prefer evidence from a higher tier and a more recent update time; downweight community content and require secondary corroboration.
Layer three, conflict detection and uncertainty expression. When two high-weight pieces of evidence reach opposite conclusions, do not “smooth it over” at generation time; instead surface the conflict explicitly: present both claims with their sources and dates, and flag that human confirmation is needed.
Evidence should be unified into a structured object for downstream citation and auditing:
{"claim": "This config option is off by default in the latest stable release","evidence": [{"snippet": "...", "source_tier": "official","published_at": "2026-05-12", "score": 0.91}],"conflict": false,"confidence": 0.86}
6. Generation and Citation: Make Verifiability a Hard Constraint
To make answers traceable, the generation stage should follow a few hard rules:
- Every factual conclusion must be bound to at least one evidence snippet and output an inline citation number;
- When evidence is insufficient, output “no reliable source found” rather than generating freely;
- Numbers, dates, and version numbers must match the evidence verbatim; no rounding or inference is allowed;
- For time-sensitive conclusions, annotate the evidence date to signal that it may have changed.
Illustrative constraint (pseudocode):
SYSTEM = """Answer using only the given evidence; tag [i] after each fact.If evidence is insufficient, answer "no reliable source found" and suggest a retrieval direction.Do not rewrite numbers, dates, or version numbers from the evidence."""
7. Evaluation and Operations: Make Results Measurable
Once the retrieval capability is live, you must continuously run regression tests with an offline evaluation set. It is recommended to cover four sample types: time-sensitive (answers change over time), authoritative (distracting low-quality sources with the same name exist), multi-hop (requires chaining two or more pieces of evidence), and no-answer (should refuse). Core metrics include evidence hit rate, citation accuracy, time-sensitive accuracy, refusal accuracy, and end-to-end latency.
On the operations side, make the retrieval pipeline observable: log each subtask’s query rewriting result, the source tier distribution of recalled items, the evidence score distribution, and the final citations, and use logging services and monitoring alerts for trend analysis. If you use general cloud capabilities, you can store raw documents and fetched page content in object storage, use a message queue to smooth out traffic spikes, use a container platform to host fetching and reranking tasks, and use logging and monitoring systems to track quality metrics.
8. Common Anti-Patterns
- Treating retrieval as a fallback: searching only when the model cannot answer, leaving many “confident errors” unblocked;
- Hiding constraints in the prompt: time ranges and source preferences are not auditable and cannot be regression-tested;
- Recall without reranking: low-quality content mixed into top-k misleads the generation stage;
- No conflict handling: randomly trusting one source when sources contradict, producing unstable answers;
- No refusal mechanism: fabricating rather than saying “I don’t know”, which carries the highest risk.
9. Conclusion
Giving an agent web and retrieval capabilities is essentially moving “fact acquisition” out of the model and into a governable engineering pipeline. The planning layer decides when facts are needed, the retrieval layer translates needs into constraint-bearing queries, the evidence layer handles credibility and conflicts, and the generation layer handles citations and refusals. Baidu AI Cloud continues to provide general capability support in retrieval augmentation and agent engineering; developers can build agent systems that both reason well and argue from evidence based on the layered design above.
