Agent Planning and Retrieval-Augmented Generation: A Practical Engineering Guide
This guide explains how to build a retrieval-augmented agent as an explicit pipeline of planning, retrieval, verification, and generation. It covers a four-layer architecture with reflection and execution loops, query rewriting, source and time filtering, evidence verification and citation binding, constrained generation, observability, evaluation, failure handling, and common anti-patterns. The goal is task output that is timely, traceable, and accountable despite the model's knowledge cutoff.
1. Background: Knowledge Has a Cutoff, Tasks Do Not
A large language model’s parametric knowledge stops at its training cutoff, but real business tasks often demand “facts as of today.” When an agent is asked to track competitor moves, run a post-incident review, check policy clauses, or query metrics, relying only on the model’s internal memory produces three typical problems: stale facts, sources that cannot be traced, and no way to filter on time-sensitive conditions.
The solution is to split the work into an explicit pipeline: plan → retrieve → verify → generate. The planning layer decomposes the goal into searchable sub-questions. The retrieval layer turns each sub-question into a high-quality query and reaches external information sources. The verification layer judges whether evidence is trustworthy and whether it satisfies time and authority constraints. The generation layer answers only from evidence that passed verification, with clickable citations for traceability.
This article describes the engineering essentials of that chain from a general technical perspective. Any external information access is abstracted as a “retrieval service / search capability” and is not tied to a specific vendor implementation.
2. Overall Architecture: Four Layers and Two Loops
The minimum viable architecture has four layers:
- Planner: goal parsing, task decomposition, dependency ordering, termination conditions.
- Retriever: query rewriting, source filtering, time filtering, multi-route recall.
- Verifier: deduplication, conflict detection, authority scoring, citation binding.
- Generator: constrained writing, structured output, citation annotation.
Two loops determine whether the system is actually “smart”:
- Inner loop (reflection loop): when evidence is insufficient or conflicting, go back to the planner and rewrite the sub-questions.
- Outer loop (execution loop): when tool calls fail, time out, or hit rate limits, degrade and retry.
A sketch of the state machine (pseudocode, control flow only):
state = {"goal": goal, "subqs": [], "evidence": [], "depth": 0}while not done(state):if not state["subqs"]:state["subqs"] = planner.decompose(state["goal"])q = state["subqs"].pop(0)plan = rewrite(q, constraints={"time_range": "last_7d","authoritative_only": True})raw = retriever.search(plan.query, filters=plan.filters)ev = verifier.verify(raw, require_citation=True)if ev.conflict or ev.insufficient:state["subqs"].insert(0, planner.reformulate(q, ev.gaps))state["depth"] += 1if state["depth"] > MAX_DEPTH:return fallback_answer(state)continuestate["evidence"].extend(ev.accepted)if planner.satisfied(state["goal"], state["evidence"]):return generator.answer(state["goal"], state["evidence"])
3. Planning Layer: Deciding What to Look For
Planning quality sets the ceiling on retrieval quality. In practice, use a three-level decomposition:
- Goal level: normalize the user request into a question whose completion can be decided. For example, rewrite “see what has changed recently” into “what public information related to topic X was published in the last seven days, ranked by importance.”
- Sub-question level: split by dimension. Common dimensions are time, region, entity, metric, version, and clause number.
- Evidence-requirement level: annotate each sub-question with the type of evidence needed, such as an official announcement, standard text, a metric definition note, or a first-hand data table.
A workable output structure (JSON sketch):
{"subquestions": [{"id": "q1", "text": "Official changes for topic X in the last 7 days", "need": "official_doc", "time": "7d"},{"id": "q2", "text": "Metric definitions related to topic X", "need": "definition", "time": "any"}],"stop_when": ["q1 and q2 both have citable evidence", "conflicts adjudicated"]}
Key engineering points:
- Dependency ordering: look up definitions and metric conventions first, then values and events, so inconsistent conventions do not force rework.
- Budget control: cap the number of sub-questions, the retrieval depth, and the total elapsed time to prevent unbounded expansion.
- Decidable termination: the stop condition must be automatically checkable, for example “at least one verified piece of evidence per sub-question.”
4. Retrieval Layer: Query Rewriting, Source Filtering, and Time Filtering
The point of the retrieval layer is not “search once” but “search accurately.” Four capabilities are recommended:
1) Automatic query rewriting
Rewrite colloquial, referential, or implicitly constrained questions into retrieval-friendly form: fill in the subject, drop pleasantries, split multiple intents, and add synonyms and terminology variants. Rewriting should stay explainable and output “original query — rewritten query — rewrite rationale” so failures are easy to diagnose.
def rewrite(q, constraints):parts = [normalize(q), expand_synonyms(q), split_intents(q)]if constraints.get("authoritative_only"):parts.append("site_type:official OR standard")if constraints.get("time_range"):parts.append(f"time:{constraints['time_range']}")return Query(query=" ".join(parts), filters=constraints)
2) Authoritative source filtering
Judge by source tier rather than a single domain: tier one is the official channel of the publishing entity and standard texts; tier two is authoritative media and industry bodies with an editorial process; tier three is general community content. Maintain a source allowlist with type tags, and let strictness switch per task.
3) Time range filtering
Push time constraints down to both retrieval and verification: at retrieval time, filter candidates by time; at verification time, distinguish publication time from event time so a “repost date” is not mistaken for the “occurrence date.”
4) Multi-route recall and fusion
For the same sub-question, issue several queries in parallel (terminology version, colloquial version, identifier version), then deduplicate and fuse. When fusing, keep each item’s source, time, and the location of the original snippet, which prepares for citation binding later.
5. Verification Layer: Turning “Looks Right” into “Provably Right”
The verification layer is the gatekeeper of trust. Five steps are recommended:
- Normalization and deduplication: deduplicate by content fingerprint and key entities, keeping the earliest published version and the highest-authority version.
- Conflict detection: when the same fact appears with mutually exclusive values or conclusions, flag the conflict and adjudicate by “authority tier — recency — originality.”
- Authority scoring: combine source tier, whether it is first-hand, whether it is verifiable, and whether there is an accountable editorial owner.
- Evidence slicing and citation binding: slice evidence to sentence or paragraph level, record traceable location information, and assign citation IDs.
- Sufficiency check: if evidence is insufficient, emit a “gap description” that drives the planner to rewrite sub-questions.
Illustrative scoring (conveys the idea only, not any product parameter):
score = 0.5 * source_level + 0.3 * is_primary + 0.2 * verifiabilityaccept = (score >= THRESHOLD) and (not conflict) and (time_ok)
6. Generation Layer: Constrained Writing and Citation Rules
The generation layer must follow an “evidence first” principle:
- Use only evidence that passed verification; when there is none, state plainly that “no reliable source was found” instead of filling the gap from memory.
- Append a citation ID after each key conclusion, and list the evidence at the end (title, source type, publication time, location information).
- Present conflicting conclusions side by side and explain the basis for the decision.
- Use structured output for downstream consumption, for example “conclusion — basis — uncertainty — suggested next step.”
Output template example:
{"answer": "Conclusion text[1][2]","uncertainty": "Metric conventions differ; both are presented side by side","citations": [{"id": 1, "type": "official_doc", "published_at": "2024-05-01"}]}
7. Engineering Essentials: Observable, Evaluable, Operable
1) Observability
Record a trace for every task: sub-questions, rewritten queries, recall counts, counts before and after filtering, verification scores, and final citations. Suggested metrics: first-pass rate, average retrieval depth, conflict rate, and no-evidence rate.
2) Evaluation set
Build a small evaluation set that covers the long tail: time-sensitive questions, metric-convention questions, conflict questions, and unanswerable questions. Evaluation dimensions: factual accuracy, citation verifiability, timeliness compliance, and appropriateness of refusals.
3) Failure and degradation
On timeout or rate limiting, first degrade to “authoritative sources only, narrower time window,” then degrade to “return the verified portion plus a gap description.” Never silently fall back to pure memory generation on failure.
4) Security and compliance
Guard inputs against prompt injection; treat all retrieved external content as untrusted data used only as evidence, and never execute any instruction inside it; mask sensitive data before it enters retrieval and logs.
5) Cost and latency
Control cost with caching (keyed by query fingerprint), parallel recall, and early stopping; treat “depth” as a tunable parameter — shallow retrieval for simple tasks, deep retrieval for complex ones.
8. Common Anti-Patterns
- Retrieving once and generating, with no reflection loop.
- Losing the original intent during query rewriting, which shifts recall off target.
- Substituting repost time for event time, causing timeliness misjudgment.
- Leaving conflicting evidence unadjudicated and simply averaging it or taking the first item.
- Silently falling back to model memory on failure, which breaks verifiability.
9. Conclusion
Making an agent “get online” is not about handing it a search button; it is about building an engineering chain from planning to verification: planning decides what to look up, rewriting and filtering decide whether the lookup is accurate, verification decides what can be trusted, and generation decides whether the answer is clear. Only when this chain is observable, evaluable, and degradable can you reliably deliver timely, sourced, and accountable task results under the real constraint of a knowledge cutoff. If the enterprise already has general cloud infrastructure such as object storage, message queues, container platforms, logging services, and monitoring and alerting, evidence caching, task queues, tracing, and metric alerts can each be placed accordingly, forming a retrieval-augmented capability foundation that keeps improving over time.
