Sub topic 17
Self-RAG and Corrective RAG in context
This chapter places two named patterns, Self-RAG and Corrective RAG (CRAG), against the agent loop you built earlier. It assumes you have read the earlier chapters: you can write a tool-calling loop with a step budget, you know what result grading is, and you have a retriever behind a search_docs style function. Both patterns come from research papers, so the chapter ends with how to borrow their ideas without adopting their full machinery.
Why these patterns matter
Earlier chapters gave the model control over retrieval through tools and a loop. Two research papers reached similar ideas from different directions.
- Self-RAG (Asai et al., 2023) trains a language model to decide, while it writes, whether to retrieve and whether its own output is supported.
- Corrective RAG (Yan et al., 2024) keeps a normal retrieve-then-generate pipeline but adds an evaluator that scores the retrieved documents and triggers a corrective action when they look wrong.
Neither is a library you install. They are designs, and their names show up in framework docs and job descriptions. Knowing what each one actually does lets you tell which ideas you already have in your agent loop and which would be new work.
Self-RAG: reflection built into the model
Self-RAG fine-tunes a model to emit special reflection tokens inline with its normal text. Each token is a small classification made by the generator itself.
| Token | Question it answers | Typical values |
|---|---|---|
| Retrieve | Should I fetch passages now? | yes, no, continue |
| IsRel | Is this passage relevant to the question? | relevant, irrelevant |
| IsSup | Does the passage support what I just wrote? | fully, partially, no support |
| IsUse | Is this answer useful overall? | a score from 1 to 5 |
At inference time the model works one segment at a time. When it predicts Retrieve, it fetches several passages and generates a candidate continuation for each. It then scores each candidate using the IsRel, IsSup and IsUse tokens, with weights you can tune, and keeps the best. Setting the weights changes behavior without retraining. For example, a high IsSup weight favors cautious, well-supported text.
The training data for those tokens comes from a separate critic model, so the cost is paid once, offline. The result is a single model that has your retrieval decision, relevance grading and support checking compiled into its weights.
Corrective RAG: an evaluator in front of the generator
CRAG leaves the generator alone. After the usual retrieval, a lightweight retrieval evaluator (in the paper, a fine-tuned T5-based model) scores each document against the question. The scores map to one of three actions.
- Correct: at least one document scores high. The pipeline refines the documents and generates.
- Incorrect: all documents score low. The pipeline discards them and falls back to another source, such as web search, using a rewritten query.
- Ambiguous: the scores are in between. The pipeline uses both the refined documents and the fallback results.
The refinement step is called decompose-then-recompose. It splits each document into small strips, scores each strip, drops the low-scoring ones and joins the rest. This removes noise inside an otherwise relevant document.
How both map onto the agent loop
You already built most of these behaviors with prompts and tools. The patterns differ mainly in where the logic lives.
| Idea | Agent loop from earlier chapters | Self-RAG | CRAG |
|---|---|---|---|
| Decide whether to retrieve | The model chooses to call the tool or not | Retrieve token | Not done. Retrieval always runs |
| Grade results | Prompted grading step, or the model's own judgment | IsRel token | Trained evaluator |
| Try again | Model re-queries within the step budget | Not a loop. Several candidates are scored | One fixed fallback action |
| Check support | Citation and grounding checks | IsSup token | Not done |
| Where the logic lives | Prompts and your code | Model weights | A separate evaluator plus fixed routing |
Two differences deserve attention. First, CRAG is a fixed pipeline with a branch, not an open-ended loop. It has predictable cost and latency, because there is at most one correction. Second, Self-RAG needs a model trained for it. You cannot get its behavior by prompting a general model with the same token names, because the tokens have no learned meaning there.
A CRAG-style step you can write today
You can reproduce CRAG's control flow with any general model as the grader. The code below takes the grader, rewriter, and both search functions as arguments, so you can plug in your own.
def corrective_retrieve(question, search, grade, rewrite, fallback_search,
high=0.7, low=0.3, k=4):
# grade(question, text) -> float in [0, 1]; you supply it (LLM call or reranker score).
# Each chunk is {"id": str, "text": str}.
chunks = search(question, k)
scored = [(grade(question, c["text"]), c) for c in chunks]
best = max((s for s, _ in scored), default=0.0)
kept = [c for s, c in scored if s >= low]
if best >= high:
return {"verdict": "correct", "chunks": kept}
fallback = fallback_search(rewrite(question), k)
if best < low:
return {"verdict": "incorrect", "chunks": fallback}
return {"verdict": "ambiguous", "chunks": kept + fallback}
if __name__ == "__main__":
docs = [{"id": "d1", "text": "Rate limit is 100 requests per minute."},
{"id": "d2", "text": "Our office dog is called Biscuit."}]
result = corrective_retrieve(
"What is the API rate limit?",
search=lambda q, k: docs[:k],
grade=lambda q, t: 0.9 if "Rate limit" in t else 0.1,
rewrite=lambda q: q + " requests per minute",
fallback_search=lambda q, k: [],
)
print(result["verdict"], [c["id"] for c in result["chunks"]])This prints correct ['d1']. Dropping d2 is the strip-level filtering idea applied at chunk level. The returned verdict is worth logging, because it gives you a per-question signal for the evaluation work from the previous chapter.
Gotchas and failure modes
- Threshold drift. The
highandlowvalues depend on the grader's score distribution. Changing the grader or its prompt shifts the scores, so re-tune thresholds on a labeled set each time. - Fallback sources are untrusted. CRAG's web fallback pulls in the least controlled text you have. Everything from the security chapter applies, and applies more strongly here.
- Evaluator blind spots. A grader that checks relevance to the question cannot tell you whether a document is current or correct. A relevant but outdated page scores as "correct".
- No support check in CRAG. A correct verdict on the documents does not guarantee the generator stayed faithful to them. Pair it with the grounding checks from earlier.
- Self-RAG deployment cost. You host a fine-tuned model, which usually means falling behind newer general models and giving up their tool-calling features.
- Naming confusion. Frameworks sometimes label any grade-and-retry graph "Self-RAG" or "CRAG". Read what the graph does before assuming it matches the paper.
Choosing among them
Use these criteria in order.
- If you already run a tool-calling agent with a step budget, you have the open-loop version of both ideas. Add a grading step and a cheap verdict log before considering anything else.
- If your latency budget is tight and failures are mostly "retrieval returned the wrong documents", a CRAG-style fixed branch is the cheapest fix. It adds one grading pass and at most one extra search.
- If you control model training and need support checking built into generation, Self-RAG is the one to study. Most teams do not meet that condition.
- If you can't measure the retrieval failure rate yet, adopt neither. Build the evaluation set first, then see whether a corrective step improves it.
Exercise
Your support bot uses classic RAG. Roughly 15% of failures are cases where the top-4 chunks are all off-topic, and the answer is invented from them. You have a latency budget that allows one extra search at most, and you use a general hosted model with no fine-tuning option. Which pattern fits, and which signals would you log to check it works?
Show answer
A CRAG-style fixed branch fits. Self-RAG needs a fine-tuned model, which you can't use, and an open agent loop may exceed the latency budget. Grade the retrieved chunks, and when the best score falls below the low threshold, rewrite the query and run one fallback search. Log the verdict (correct, ambiguous, incorrect) for every question, the best grader score, and whether the final answer was judged grounded. Compare the off-topic failure rate before and after on a labeled question set, and re-tune thresholds if the grader changes.