Agent Planning and Retrieval Augmentation: A Practical Guide
This guide explains how to make retrieval a first-class capability inside an AI agent's planning loop. It covers a three-layer architecture (planner, retriever, and evidence layer), how to turn task descriptions into executable queries, how to treat time ranges and source credibility as structured constraints, how to rewrite failing queries into a converging process, and how to backfill cited evidence and resolve conflicts. It also lists termination conditions, cost controls, observability practices, common anti-patterns, and a deployment checklist.
Agent Planning and Retrieval Augmentation: A Practical Guide
1. Background: Knowledge Has a Cutoff, Tasks Do Not
A large language model’s parametric knowledge ends at a fixed training cutoff, while real business tasks often demand information that is true right now: a specification released this week, a process that just changed, this week’s market data, a defect fixed hours ago. This mismatch — knowledge with an expiration date, tasks without one — is the most underestimated risk when agents go into production.
The second risk is the fluent hallucination. Lacking factual support, the model still fills in details with a highly confident tone, citing clauses that do not exist or inventing interfaces that were never defined. For an agent, the cost of such errors is amplified by the actions that follow: a wrong query leads to a wrong tool call, and a wrong conclusion leads to a wrong write operation.
The fix is to promote retrieval from a one-off question-answering step to a first-class capability inside the planning chain. During planning, the agent decides whether a given step needs external facts; when it does, it initiates retrieval proactively, verifies sources, applies time constraints and credibility filtering, and finally backfills traceable evidence into the reasoning context.
2. Overall Architecture: A Three-Way Split Between Planner, Retriever, and Evidence Layer
Split the capability into three layers instead of piling all the logic into a single prompt.
- Planning layer: task decomposition, state tracking, and deciding when to retrieve, what to retrieve, and when enough has been retrieved.
- Retrieval layer: query construction and rewriting, time-range and source-type constraints, result ranking and deduplication.
- Evidence layer: snippet extraction, citation registration, credibility labeling, conflict detection, and context backfill.
Keep the interfaces between the three layers stable. A sketch follows (pseudocode that expresses the contract only and does not point to any specific product API):
def plan_step(state) -> Step:# Output: action type (retrieve / compute / call tool / finish), retrieval intent, acceptance criteria...def search(intent, *, time_range=None, source_policy=None) -> list[Evidence]:# Output: list of evidence with source, timestamp, and credibility label...def backfill(state, evidence) -> State:# Write evidence and citation IDs into the context, trigger conflict detection...
The key design principle is acceptance criteria up front. When the planner initiates retrieval, it must state what evidence counts as completing this step — for example, “at least two independent sources, both published within the last 30 days.” This constraint is reused repeatedly in the termination check, and it guards against both extremes: endless retrieval and shallow, stop-too-early retrieval.
3. Generating Retrieval Intent: From Task Description to Executable Query
The most common mistake an agent makes is using the user’s exact words as the query. High-quality retrieval requires one round of intent translation:
- Element extraction: subject, time, region, version, scenario constraints.
- Term normalization: map colloquial phrasing to standard domain terminology and common abbreviations.
- Query set expansion: generate 2–4 complementary queries (one for broad recall, one for exact match, one for counter-evidence verification).
- Budget control: set a maximum number of queries and a maximum number of returned items per step, so noise does not flood the context.
Example:
def build_queries(task):return [{"q": task.canonical, "mode": "broad"}, # broad recall{"q": f'"{task.term}" {task.version}', "mode": "exact"}, # exact match{"q": f"{task.term} change notes errata", "mode": "verify"} # counter-evidence / change verification]
4. Time-Range Filtering: Making Freshness a Computable Constraint
Time constraints should not be vague adjectives; they should be structured parameters. In practice, distinguish three semantics:
- Event time: when the fact occurred. Fits “latest progress” or “data for this month.”
- Publish time: when the document went live. Fits specifications, announcements, and release notes.
- Update time: when the page was last revised. Fits explanatory content that is still evolving.
Record the time window explicitly in the planning state and re-validate it in the evidence layer, so loose matching on the retrieval side cannot let stale content flow back in:
@dataclassclass TimeWindow:field: str # publish | update | eventstart: str | None # ISO8601end: str | Nonedef accept(ev: Evidence, tw: TimeWindow) -> bool:t = ev.meta.get(tw.field)return bool(t) and (tw.start is None or t >= tw.start) and (tw.end is None or t <= tw.end)
Engineering-wise, you also need a fallback for missing timestamps: when a piece of evidence has no time field, downgrade it to low credibility and require cross-confirmation from another piece of evidence that does carry a timestamp; otherwise it must not enter the conclusion.
5. Source Credibility and Authority Filtering
Authority filtering should be implemented as a configurable policy, not a hardcoded allowlist. Prefer multi-dimensional scoring over a single whitelist:
- Source tier: first-party publisher > organization with a clearly accountable owner > general reposts.
- Consistency: do multiple sources corroborate each other, or is there “fake multi-source” caused by copies of the same origin?
- Verifiability: are traceable elements such as an ID, a date, and an applicable scope provided?
- Conflict of interest: does the content show an obvious promotional bias?
def score(ev: Evidence, policy) -> float:s = policy.level.get(ev.source_type, 0.0)s += 0.3 * ev.cross_confirmeds += 0.2 * ev.has_traceable_ids -= 0.4 * ev.promotionalreturn max(0.0, min(1.0, s))
When the highest-scoring evidence falls below the threshold, the correct behavior is to admit uncertainty: output the items awaiting confirmation and the additional information needed, rather than forcing a conclusion.
6. Automatic Query Rewriting: Turning Failed Retrieval into a Converging Process
Rewriting is not simple synonym substitution; it is a feedback-driven loop:
- Too few results: widen the time window, drop overly narrow qualifiers, switch to a broader term.
- Too many noisy results: add qualifiers, enable exact match, raise the source-tier threshold.
- Conflicting results: generate targeted verification queries to locate whether the difference comes from version, region, or applicable scope.
- Two consecutive rounds with no gain: switch retrieval dimension (from “conclusion retrieval” to “definition/standard retrieval”).
def rewrite(q, feedback):if feedback.hit == 0:return q.drop("version").widen_time()if feedback.noise > 0.6:return q.add("exact").raise_source_level()if feedback.conflict:return q.focus("version difference applicable scope")return q.shift_dimension("definition")
Set a maximum number of rewrite rounds (usually 2–3) and keep each round’s query and a summary of its results, which makes post-hoc review and effect attribution easier.
7. Evidence Backfill and Conflict Handling
The goal of backfill is to make conclusions traceable. Assign a citation ID to each piece of evidence, and when writing it into the context, keep the source label, timestamp, and credibility score alongside it. Require every sentence in the conclusion paragraph to carry a citation; mark sentences without one as speculation.
Conflict handling follows this priority: the more recent and more authoritative source wins; at the same tier, the one whose applicable scope matches better prevails; if it still cannot be decided, present the differences side by side and state where they diverge.
[Conclusion] In the latest specification, the target interface has been changed to return asynchronously.[Citations] E1 (first-party release, event time 2 days ago, 0.92) / E2 (organization doc, updated 1 month ago, 0.71)[Divergence] E3 still describes a synchronous return; its applicable scope is the older version, so it has been down-weighted.
8. Termination Conditions, Cost Control, and Observability
- Termination conditions: preset acceptance criteria are met, the maximum number of rounds is reached, or marginal information gain drops below the threshold.
- Cost control: three layers of limits — query budget, context budget, and a cap on the number of evidence items; for long documents, extract at the snippet level before putting them into the context.
- Observability: log each step’s query, the reason for each rewrite, which filters matched and why items were dropped, and the citation chain, forming a replayable trace.
- Caching strategy: cache “stable facts” and “high-frequency queries” with timestamps, and define expiration and invalidation conditions.
9. Common Anti-Patterns
- Answer first, retrieve later: generating a conclusion before retrieving leaves a back door for hallucination.
- Single-source conclusions: concluding from one source without cross-validation.
- Mixing time and freshness: treating update time as event time and reaching a wrong chronological judgment.
- Endless rewriting: no round limit and no gain check, so cost runs out of control.
- Decorative citations: citations attached only at the end of a paragraph, with no way to locate the specific sentence.
10. Deployment Checklist
- Require the planner output to always include two fields: “does this step need external facts” and “acceptance criteria.”
- Unify time-window and source-policy parameters in the retrieval layer, and re-validate in the evidence layer.
- Before launch, run regression tests with three case types: stale-information lures, conflicting information, and pages without timestamps.
- Continuously track citation coverage, factual accuracy, average retrieval rounds per task, and cost per task as core metrics.
Embedding web retrieval into the planning loop is, in essence, constraining the generation process with traceable external evidence. Once an agent learns to retrieve at the right moment, filter with structured conditions, and backfill conclusions with citations, the knowledge cutoff is no longer the boundary of task completion. If you need to manage both retrieval artifacts and runtime logs in the same environment, general-purpose capabilities from Baidu AI Cloud (such as object storage, log service, and monitoring and alerting) can handle archiving and observability.
