Agent Planning and Retrieval-Augmented Generation: A Practical Guide

    This guide explains how to build retrieval-augmented AI agents that combine planning, external search, and verification to answer time-sensitive questions reliably. It covers a four-layer architecture, query compilation, authoritative source filtering, time-range constraints, query rewriting, citation backfilling, prompt organization, evaluation, cost control, and common failure modes. Engineers will find practical code examples and design principles for balancing freshness, trustworthiness, and cost.

    1. Background: Model Knowledge Has Limits, User Tasks Do Not

    The parametric knowledge of large language models stops at a training data cutoff, but real business tasks often demand answers that are true right now: whether a policy has been updated, the latest stable version of a component, the final score of a match, or the official wording of an organization’s announcement. Handing these questions to a model in a closed-book setting produces two typical defects. First, timeliness errors occur when the model answers a new question with old facts. Second, the output is not verifiable because it has no sources, leaving users unable to judge credibility.

    For this reason, an AI agent cannot rely on internal knowledge alone. It needs the ability to actively acquire external information. The common industry approach combines Retrieval-Augmented Generation (RAG) with tool or function calling: the model handles planning and reasoning, while external retrieval services supply facts and sources. This article discusses the engineering implementation of this general technical approach from a neutral perspective, focusing on the closed loop of planning, retrieval, verification, and backfilling.

    2. Overall Architecture: Where Retrieval Fits in the Planning Stack

    A networked agent typically has four layers:

    1. Intent understanding layer: determines whether the user’s question needs external information, distinguishing between what can be answered closed-book and what must go online.
    2. Task planning layer: breaks a complex question into sub-questions and forms an execution plan with dependencies.
    3. Retrieval execution layer: builds queries for each sub-question, calls retrieval capabilities, and obtains candidate passages with metadata.
    4. Generation and verification layer: generates answers based on evidence, annotates sources, and performs a second retrieval when necessary.

    The key design principle is on-demand retrieval with layered filtering. Not every sub-question needs to go online, and for those that do, not every returned result should enter the context. Treating retrieval as an external dependency with cost and noise to be governed is the prerequisite for stability.

    3. Retrieval Intent Generation: From Natural Language Questions to Executable Queries

    The sub-questions produced by the planning layer are often natural language descriptions, while retrieval services work better with structured query conditions. A query compilation step is needed in between:

    1. def compile_query(sub_task: dict) -> dict:
    2. return {
    3. "query": sub_task["text"], # Core search terms
    4. "time_range": sub_task.get("freshness"),# e.g. "past_week" or custom start/end
    5. "site_scope": sub_task.get("authoritative_domains", []),
    6. "rewrite": sub_task.get("need_rewrite", False),
    7. "top_k": sub_task.get("top_k", 5),
    8. }

    In practice, it is better to make “whether the latest information is needed” an explicit field at the planning stage rather than have the execution layer guess. For example, if a user asks about a currently effective industry standard, the planner should output freshness=recent and a whitelist of authoritative sources. If a user asks for the definition of an algorithm, no time constraint is needed.

    4. Engineering Meaning of Four Core Capabilities

    1. Authoritative source filtering. Retrieval results usually carry source identifiers. The execution layer can maintain a configurable whitelist of authoritative domains or organizations and apply hard filtering or weighted ranking to candidates. Hard filtering guarantees that only trusted sources are used, while weighted ranking preserves a fallback when recall is insufficient.

    2. Time-range filtering. Time-sensitive questions must carry a time window. The window can be relative (past day, past week, past month) or an absolute start and end date. Note that the prompt should explicitly state that dates in the retrieval results take precedence, preventing the model from overriding evidence with internal memory.

    3. Automatic query rewriting. A user’s original wording is often colloquial and contains references. The rewriting module is responsible for resolving references, splitting multiple intents, expanding synonyms, and removing modifiers with no informational value. Rewriting can be done by a model or combined with rule templates, outputting multiple candidate queries that are searched in parallel and then merged and deduplicated.

    4. Result backfilling and citation. Each evidence passage should carry a title, source, time, body summary, and unique identifier. When backfilling, inject it into the context in structured form and require the final answer to annotate citation numbers item by item.

    5. Example: A Filtered Retrieval Call

    1. def search_with_filters(compiled: dict) -> list[dict]:
    2. results = external_search_service.search(
    3. query=compiled["query"],
    4. freshness=compiled.get("time_range"),
    5. top_k=compiled["top_k"],
    6. )
    7. allow = set(compiled.get("site_scope") or [])
    8. if allow:
    9. results = [r for r in results if r["domain"] in allow]
    10. return [
    11. {"id": i, "title": r["title"], "domain": r["domain"],
    12. "date": r.get("date"), "snippet": r["snippet"]}
    13. for i, r in enumerate(results)
    14. ]

    6. Prompt and Context Organization

    The backfilled prompt should be organized into sections: a system constraint section (requiring answers based only on evidence, with an explicit statement when evidence is absent), an evidence section (numbered list), and a task section (sub-question and output format). Requiring the model to output a conclusion plus citation numbers plus uncertain items can significantly reduce hallucination and overconfidence.

    7. Evaluation and Operations

    • Offline evaluation: build a set of time-sensitive questions with metrics including evidence hit rate, citation accuracy, time accuracy, and appropriate refusal rate.
    • Online monitoring: record the empty retrieval result rate, the rate of insufficient candidates after filtering, and the recall difference before and after rewriting, and feed them into logging services and monitoring alerts.
    • Cost control: cache high-frequency query results, set a maximum number of retrieval rounds and timeouts, and avoid infinite loops in the planning layer.

    8. Common Pitfalls

    The first is stuffing all retrieval results into the context indiscriminately, letting noise drown out key evidence. The second is missing time fields, which leads to answering new questions with old news. The third is over-rewriting that drifts from the original intent. The fourth is the absence of a fallback path, letting the model improvise when retrieval fails. Address these four points respectively with ranking and truncation, mandatory time fields, rewrite rollback validation, and refusing to answer on failure.

    9. Conclusion

    Making an agent go online essentially moves knowledge acquisition from the training stage to the runtime stage. The planning layer decides what to retrieve, the execution layer decides what to trust, and the verification layer decides how to express it. Only when the three work together can a balance be struck among timeliness, trustworthiness, and cost. For a managed implementation, you can combine general cloud capabilities for retrieval, object storage, logging, and monitoring to build an observable and scalable retrieval-augmented pipeline.