Agentic RAG in Practice: Building Self-Correcting Retrieval with a State Machine

    This article explains why traditional RAG pipelines confidently produce wrong answers when retrieval quality is never evaluated, and how Agentic RAG fixes this by turning the linear flow into a feedback-driven state machine. It covers a six-node architecture (route, retrieve, grade, rewrite, generate, end), how to define the grading criteria that set the system's ceiling, rewrite strategies and hard termination conditions, and common pitfalls with tuning advice for observability and deployment. Readers will learn a framework-agnostic engineering pattern they can roll out gradually, starting with threshold calibration on a small corpus.

    1. Where the Problem Starts: Why Traditional RAG Answers Wrong with Confidence

    In most enterprise knowledge base scenarios, Retrieval-Augmented Generation (RAG) has become the default approach: documents are chunked, vectorized, and written into a vector index; at query time a similarity recall runs first, and the retrieved fragments are stitched into the prompt for the LLM to generate an answer. This pipeline performs well when “the question and the document are phrased almost identically,” but it has a structural flaw: retrieval quality is never evaluated explicitly, so the generation stage has no choice but to trust the context unconditionally.

    Take a typical example. The knowledge base contains a document about parameter-efficient training methods, and the user asks “what gives the best results when fine-tuning a large model?” There is indeed some similarity between the question and the document in the semantic space, but it is not strong enough to rank first, so the recall results end up mixed with a lot of “tangentially related but off-topic” content about model architecture and operator implementations. The generation model has no way of knowing the context is wrong: it treats the irrelevant fragments as factual grounding and outputs an answer that is dense with terminology, neatly formatted, and actually off target. This kind of error is more dangerous than “no answer at all,” because it is deceptive to the user.

    Traditional RAG has almost no means against this failure mode, for three reasons:

    • One-way feed-forward: recall, concatenation, and generation form a straight line, with no channel back to the retrieval stage.
    • No quality gate: context enters the prompt regardless of its quality, and the model has no option to refuse to answer.
    • Fixed query phrasing: the user’s colloquial question is used as-is for vector retrieval and is never rewritten just because “retrieval failed.”

    The core idea of Agentic RAG is to reshape this straight line into a state machine with a feedback loop: give the system the ability to judge whether “the retrieval results are good enough,” and when they are not, let it autonomously decide to rewrite the query and retrieve again, or to terminate and state that information is insufficient.

    2. Overall Architecture: A Directed State Graph of Six Modules

    In engineering terms there is no need to depend on a specific framework; any graph orchestration capability that supports “nodes, edges, shared state” can achieve the same effect. What matters is separating responsibilities so each node does one thing only, and making decisions explicit.

    1. Route node: decide whether this question needs retrieval at all. Greetings, pure computation, and small talk go straight to the generation branch, avoiding the latency and noise of pointless recall.
    2. Retrieve node: run vector recall plus any necessary sparse recall, and write candidate fragments into the shared state.
    3. Grade node (Grade Edge): judge the relevance of the recalled results. This is the quality gate of the whole system.
    4. Rewrite node: for cases of “unclear phrasing” or “recall drift,” rewrite the query and then return to the retrieve node.
    5. Generate node: runs only after grading passes, producing an answer grounded in qualified context.
    6. End / fallback node: when repeated rewrites still fall short, return an honest “insufficient material” response instead of fabricating one.

    The shared state can be abstracted into the following illustrative structure (pseudocode that only expresses the data flow and involves no specific API):

    1. state = {
    2. "question": "what gives the best results when fine-tuning an LLM",
    3. "route": "retrieve", # retrieve | direct
    4. "documents": [], # recalled fragments
    5. "grade": None, # pass | fail
    6. "attempt": 0, # rewrite count
    7. "answer": ""
    8. }

    Edges carry the control flow: the route node is followed by a conditional edge that splits the paths; the grade node is followed by a conditional edge deciding “go to generate” or “go to rewrite”; the rewrite node is followed by a loop-back edge returning to the retrieve node. The loop-back edge must come with a counting constraint, otherwise an infinite loop will occur.

    3. Key Design 1: The Grading Criteria Set the System’s Ceiling

    The grade node is where the value of the whole mechanism lies, but its difficulty is not in the implementation, it is in defining what “qualified” means. A dual-signal fusion is recommended to avoid the misjudgments of a single criterion:

    • Semantic relevance: the relevance strength between the question and each fragment, which can be scored with vector similarity or a cross-encoder, taking a weighted aggregate of the Top-K rather than the single maximum value, so that “one high-scoring fragment cannot mask the remaining noise.”
    • Coverage: whether the qualified fragments cover the key elements of the question. For example, a fine-tuning question should cover at least four dimensions: data preparation, method selection, hyperparameters, and evaluation; missing any one counts as insufficient coverage.

    The decision logic can be written as:

    1. def grade(state):
    2. scores = relevance(state["question"], state["documents"])
    3. strong = [s for s in scores if s.score >= TAU]
    4. coverage = key_points_covered(state["question"], strong)
    5. ok = len(strong) >= MIN_DOCS and coverage >= MIN_COVER
    6. return "pass" if ok else "fail"

    The threshold TAU, the minimum number of fragments MIN_DOCS, and the coverage floor MIN_COVER need to be calibrated offline on your own corpus: use a batch of labeled question-answer pairs, observe the “false pass rate” and the “excessive rewrite rate” under different thresholds, and take the balance point. Never copy someone else’s empirical values directly, because thresholds depend heavily on chunking granularity and corpus style.

    4. Key Design 2: Rewrite Strategy and Termination Conditions

    When grading fails, the system enters the rewrite node. Rewriting is not simple synonym substitution; it should take different actions for different failure causes:

    • Recall drift: rewrite the colloquial question into a term-dense domain phrasing, for example expanding “best results” into “comparison of parameter-efficient fine-tuning methods and their applicable scenarios.”
    • Missing elements: perform query decomposition, splitting a compound question into multiple sub-queries to retrieve separately, then merging the candidate sets.
    • Granularity too coarse: attach constraints (time range, document type, version number) to narrow the retrieval space.

    Termination conditions must be set as hard limits. A combination strategy is common in engineering: a maximum rewrite count (such as 2 to 3), an upper bound on cumulative elapsed time, and an early-stop check for “no grading improvement twice in a row.” Once the limit is reached, the flow moves to the fallback node, which outputs “the current knowledge base did not retrieve sufficient grounding” and attaches the most relevant material found so far for the user’s reference. An honest failure is always better than a fabricated success, and this is the most substantive improvement of Agentic RAG over traditional RAG.

    5. Common Pitfalls and Tuning Advice

    • Pitfall 1: letting the generation model grade as a side task. Mixing grading and generation in one prompt introduces verbose output and unstable judgments; splitting them into separate nodes makes the system easier to observe and tune.
    • Pitfall 2: no budget on the loop. Without count and timeout constraints, tail latency spikes in production, so the count must be tracked explicitly in the state.
    • Pitfall 3: leaving the chunking strategy untouched and only tuning thresholds. If chunking splits “method, applicable scenario, parameters” across different chunks, no threshold can rescue coverage; fix the data first.
    • Observability: record an input summary, the grading score, the branch taken, and the elapsed time for every node, and ship them to a logging service with monitoring alerts, so you can tell whether the problem is in retrieval or in the decision.
    • Deployment shape: the index and the state store can live separately in object storage, a vector retrieval service, and a container platform, while the orchestration logic stays stateless so it can scale horizontally.

    6. Summary

    The point of Agentic RAG is not to introduce a more complex model, but to make “whether retrieval succeeded” a first-class concern of the system: use routing to cut wasted recall, use grading to establish a quality gate, use rewriting and the loop to provide a self-repair channel, and use termination conditions to hold the line on facts. When deploying on platforms such as Baidu AI Cloud, treat it as a general engineering pattern independent of any specific product, roll it out gradually with your own logging, monitoring, and containerization capabilities, calibrate thresholds on a small corpus first, and then extend to the full knowledge base.