Lecture 26
Corrective RAG (CRAG)
Grading retrieved documents and falling back to web search when retrieval isn't good enough.
Based on the original video (~75 min) · lesson written for this course
Why plain RAG needs correcting
A quick recap of the RAG pipeline
Retrieval-augmented generation (RAG) answers questions from your own documents instead of from whatever the model happened to learn in training. It has three steps:
- Retrieval. The user's question is turned into a vector by an embedding model (a network that maps text to a list of numbers so that similar meanings land close together). That vector is compared against the vectors of your document chunks in a vector store, and the closest few chunks come back.
- Augmentation. Those chunks are pasted into a prompt next to the question: "Answer this question using this context."
- Generation. The LLM writes an answer from the context.
If your vector store holds three machine-learning textbooks and someone asks "what is the bias–variance trade-off?", retrieval returns four passages that discuss exactly that, and the answer is excellent. When it works, RAG is simple and very effective.
Blind trust in retrieval
The weak point is step one. A vector store always returns something. Similarity search ranks every chunk by distance to the query and hands back the top k, whether or not any of them is actually about the question. There is no "nothing found" in plain nearest-neighbour search.
So when the question falls outside what the documents cover, retrieval quietly returns the least-unrelated chunks. Ask the ML-textbook bot "what is a large language model?" and you might get passages about random forests or XGBoost, because they share words like "model" and "training".
The generation step then trusts that context blindly. The prompt says "answer from the context", so the model either:
- builds a wrong answer out of irrelevant text, or
- ignores the context and answers from its own parametric knowledge (what it absorbed in training), which may be right, outdated or invented, and in any case isn't what your system promised.
Now picture the same thing in a company. An employee asks the HR bot about the leave policy for a situation the handbook doesn't cover. Retrieval returns some loosely related paragraphs, the model produces a confident answer, and the employee acts on it. The failure is silent, which is what makes it dangerous.
Seeing the failure in a real pipeline
Three questions against the textbook bot show the three behaviours:
| Question | What retrieval returns | What the model does |
|---|---|---|
| "What is the bias–variance trade-off?" | Four chunks that discuss it directly | A correct, grounded answer |
| "What were the top AI stories last month?" | Unrelated chunks (the books are years old) | Says it doesn't know, because the prompt allows that |
| "What is a transformer in deep learning?" | Chunks about MLPs, CNNs, regularisation and an index page | A fluent, correct-sounding answer about self-attention |
The third row is the alarming one. None of the four chunks mention transformers, yet the answer looks fine. It came entirely from parametric knowledge. Here the model happened to know the topic. Ask about something it doesn't know (an internal policy, a product launched last month) and the same mechanism produces a hallucination wearing the costume of a grounded RAG answer.
How corrective RAG works
Corrective RAG (CRAG), proposed in a 2024 paper, adds one idea to the pipeline: don't trust retrieval, check it. Between retrieval and generation sits a retrieval evaluator that looks at the question and each retrieved document and judges how useful the document is for answering it. What happens next depends on that judgement.
The retrieval evaluator
The evaluator gives each document a relevance score between 0 and 1. A score near 1 means "this chunk alone is enough to answer the question"; a score near 0 means "irrelevant". Two thresholds turn the scores into an overall verdict for the retrieval as a whole.
Three verdicts and three actions
| Verdict | Condition | Action | Knowledge used for the answer |
|---|---|---|---|
| Correct | At least one document scores above the upper threshold | Refine the good documents, then generate | Internal only |
| Incorrect | No document scores above the lower threshold | Throw retrieval away, search the web, refine the results, then generate | External only |
| Ambiguous | Anything in between | Keep the decent documents and search the web, refine both together, then generate | Internal plus external |
Each verdict is a reasonable response to a different situation. When retrieval clearly worked, use it. When it clearly failed, don't feed garbage to the generator; go get better information. When the evidence is weak but not worthless (part of the question is covered, part isn't), keep what you have and top it up.
The overall shape is:
question ─▶ retrieve ─▶ evaluate ─┬─ Correct ───────────────────────────────▶ refine ─▶ generate
├─ Ambiguous ─▶ rewrite query ─▶ web search ─▶ refine (good + web) ─▶ generate
└─ Incorrect ─▶ rewrite query ─▶ web search ─▶ refine (web only) ─▶ generate
Every path goes through knowledge refinement before generation. That is the second idea in CRAG: even relevant documents carry noise, so strip them down to the sentences that actually help.
What the paper used
The paper's evaluator is not a general chat model. It is T5-large (about 770 million parameters), fine-tuned specifically to score query–document relevance, and the authors report it judged relevance better than a much larger general-purpose LLM while being far cheaper to run. They used a similar fine-tuned model to filter sentences during refinement.
The fine-tuned weights aren't something you can just download and drop in, so the implementation below uses a general chat model with a tight prompt and structured output for both jobs. The architecture is identical; only the judge differs. If you run CRAG at scale, training a small dedicated grader on your own labelled query–chunk pairs is the natural upgrade: it is faster, cheaper and more consistent than prompting a big model for every chunk.
Correction versus better retrieval
CRAG doesn't make retrieval better; it notices when retrieval was bad and reacts. That distinction matters when you decide where to spend effort. Several techniques improve retrieval itself:
- Better chunking. Splitting on headings and paragraphs instead of fixed character counts keeps topics together, which reduces the noise that refinement has to remove.
- Hybrid search. Combining vector similarity with keyword search (BM25) catches exact terms, like product names and error codes, that embeddings blur.
- Reranking. Retrieving 20 candidates and letting a cross-encoder reorder them puts the best few at the top before anything is graded.
- Metadata filters. Restricting a policy question to the policy documents removes whole classes of wrong answers.
These all raise the share of questions that come back Correct. None of them can fix a question your corpus simply doesn't answer, and none tells you when it failed. That's CRAG's job: a final check that turns silent failures into explicit decisions. In practice you want both. Better retrieval makes the evaluator say Correct more often; the evaluator catches what's left. If your logs show a high rate of Ambiguous verdicts on questions your documents do cover, the fix is usually upstream in retrieval, not in the thresholds.
A baseline RAG graph
Everything is built step by step on top of a plain RAG graph, so start there. The corpus is three classic ML/DL textbooks as PDFs.
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_openai import OpenAIEmbeddings
from langchain_core.vectorstores import InMemoryVectorStore
pages = []
for path in ["books/hands_on_ml.pdf", "books/deep_learning.pdf", "books/pattern_recognition.pdf"]:
pages.extend(PyPDFLoader(path).load()) # one Document per page
splitter = RecursiveCharacterTextSplitter(chunk_size=900, chunk_overlap=150)
chunks = splitter.split_documents(pages)
for c in chunks: # PDFs often contain broken unicode
c.page_content = c.page_content.encode("utf-8", "ignore").decode("utf-8")
store = InMemoryVectorStore.from_documents(chunks, OpenAIEmbeddings(model="text-embedding-3-small"))
retriever = store.as_retriever(search_kwargs={"k": 4})
A few thousand pages become several thousand chunks of about 900 characters, with 150 characters of overlap so a sentence cut at a boundary still appears whole in one of the two neighbours. The retriever returns the top four chunks for any query. The unicode clean-up line exists because PDF text extraction regularly produces invalid characters that later crash encoders.
from typing_extensions import TypedDict
from langchain_core.documents import Document
from langchain.chat_models import init_chat_model
from langgraph.graph import StateGraph, START, END
llm = init_chat_model("openai:gpt-4.1-mini", temperature=0)
class State(TypedDict):
question: str
docs: list[Document]
answer: str
def retrieve(state: State) -> dict:
return {"docs": retriever.invoke(state["question"])}
def generate(state: State) -> dict:
context = "\n\n".join(d.page_content for d in state["docs"])
msg = llm.invoke([
("system", "Answer only from the context. If the answer is not in the context, say you don't know."),
("human", f"Question: {state['question']}\n\nContext:\n{context}"),
])
return {"answer": msg.content}
builder = StateGraph(State)
builder.add_node("retrieve", retrieve)
builder.add_node("generate", generate)
builder.add_edge(START, "retrieve")
builder.add_edge("retrieve", "generate")
builder.add_edge("generate", END)
rag = builder.compile()
This is the pipeline that produced the "transformer" answer from unrelated chunks. Even with "say you don't know" in the prompt, the model sometimes answers anyway when it knows the topic well. Prompt instructions alone don't make retrieval trustworthy, which is why CRAG adds structure instead.
Iteration one, knowledge refinement
Start with the step every path shares. Retrieved chunks are cut by character count, not by meaning. A 900-character window often contains the end of one topic and the start of the next. Ask "what is gradient descent?" and a perfectly relevant chunk might read:
Gradient descent is an optimisation algorithm used to minimise a loss function. It iteratively updates parameters in the direction of the negative gradient. Neural networks are composed of layers of neurons with non-linear activations. Convolutional networks are particularly effective for image tasks.
The first two sentences answer the question. The last two belong to the next section of the book and are just noise. Noise costs tokens, and worse, it gives the generator material to wander into.
Decompose, filter, recompose
Knowledge refinement has three steps:
- Decompose. Split each document into small strips: roughly one or two sentences each.
- Filter. Score each strip against the question and keep only the ones that help answer it.
- Recompose. Join the kept strips back into one compact context.
The generator then sees two sentences about gradient descent instead of four sentences across three topics.
Try it · Knowledge refinement
Question: "What is gradient descent?" One retrieved chunk is split into strips and each strip is filtered. Tap a strip to override the filter.
1. decompose → 2. filter
3. recompose → refined_context
Gradient descent is an optimisation algorithm used to minimise a loss function. The step size is controlled by the learning rate.
The widget shows the main risk of this step. Sentence-level filtering judges each strip out of context. "It iteratively updates parameters…" doesn't say what "it" is, so a strict filter can drop it even though it's the most useful sentence. Two mitigations: strips of two sentences instead of one, and a filter prompt that says "keep a sentence if it helps answer the question, even if it relies on the previous sentence for its subject".
The refine node
import re
from pydantic import BaseModel
from langchain_core.prompts import ChatPromptTemplate
def decompose_to_sentences(text: str) -> list[str]:
text = re.sub(r"\s+", " ", text).strip()
return [s for s in re.split(r"(?<=[.!?])\s+", text) if len(s) > 20]
class KeepStrip(BaseModel):
keep: bool
filter_prompt = ChatPromptTemplate.from_messages([
("system", "You are a strict relevance filter. Return keep=true only if the sentence "
"directly helps answer the question. Judge the sentence only."),
("human", "Question: {question}\n\nSentence: {sentence}"),
])
filter_chain = filter_prompt | llm.with_structured_output(KeepStrip)
The splitter collapses whitespace, splits after sentence-ending punctuation, and drops tiny fragments (page numbers, stray headings). The filter is a prompt piped into a structured-output model, so each call returns a validated KeepStrip.
class State(TypedDict):
question: str
docs: list[Document]
strips: list[str]
kept_strips: list[str]
refined_context: str
answer: str
def refine(state: State) -> dict:
context = "\n\n".join(d.page_content for d in state["docs"])
strips = decompose_to_sentences(context)
verdicts = filter_chain.batch([{"question": state["question"], "sentence": s} for s in strips])
kept = [s for s, v in zip(strips, verdicts) if v.keep]
return {"strips": strips, "kept_strips": kept, "refined_context": "\n".join(kept)}
batch sends the filter calls concurrently instead of one after another, which matters: four chunks of 900 characters are easily 30 sentences, and 30 sequential model calls would make every question slow. generate now reads refined_context instead of joining raw documents, and the graph becomes retrieve → refine → generate.
The state keeps strips and kept_strips even though only refined_context is needed for the answer. They cost nothing and make debugging easy: you can see exactly which sentences were thrown away when an answer comes out thin.
Iteration two, the retrieval evaluator
Refinement makes good retrieval better. It does nothing about bad retrieval: filtering random-forest sentences against a transformer question just yields an empty context. The evaluator decides whether to trust retrieval at all.
Why two thresholds instead of one
A single cutoff would give you only two outcomes: trust retrieval or replace it. The middle band exists because relevance scores near the boundary are exactly where a grader is least reliable, and where a question is most often half covered. With two thresholds, a document scoring 0.5 is neither trusted as sufficient nor thrown away: it's kept as partial evidence while the system looks for more. The width of the band is a dial. Widen it (lower LOWER, raise UPPER) and more questions land in Ambiguous, which costs a web search each but rarely discards useful context. Narrow it and the system commits to one source more often, which is cheaper and riskier.
Scoring each document
class DocScore(BaseModel):
score: float
reason: str
grade_prompt = ChatPromptTemplate.from_messages([
("system",
"You are a strict retrieval evaluator for RAG. Given a question and ONE retrieved chunk, "
"return a relevance score from 0.0 to 1.0. 1.0 means the chunk alone is sufficient to "
"answer fully; 0.0 means it is irrelevant. Be conservative with high scores. "
"Also give a short reason."),
("human", "Question: {question}\n\nChunk:\n{chunk}"),
])
grader = grade_prompt | llm.with_structured_output(DocScore)
Grading one chunk at a time matters. If you show the grader all four chunks together, it judges the set, and you lose the per-document scores you need both for the verdict and for deciding which chunks survive. The reason field is for you: when the verdict looks wrong, the reasons tell you whether the grader or the threshold is at fault.
"Be conservative with high scores" is doing real work. General chat models are generous graders; without that line they hand out 0.8 to anything on the right topic, and everything becomes "Correct".
Turning scores into a verdict
UPPER, LOWER = 0.7, 0.3
def evaluate(state: State) -> dict:
results = grader.batch([{"question": state["question"], "chunk": d.page_content}
for d in state["docs"]])
scores = [r.score for r in results]
good = [d for d, s in zip(state["docs"], scores) if s > LOWER]
if any(s > UPPER for s in scores):
return {"good_docs": good, "verdict": "CORRECT", "reason": f"best score {max(scores):.2f} > {UPPER}"}
if not good:
return {"good_docs": [], "verdict": "INCORRECT", "reason": f"no chunk scored above {LOWER}"}
return {"good_docs": good, "verdict": "AMBIGUOUS", "reason": "mixed signals, no chunk above the upper threshold"}
Work through three cases with UPPER = 0.7 and LOWER = 0.3:
| Scores | Verdict | Why |
|---|---|---|
| 0.8, 0.5 | Correct | One chunk clears 0.7 |
| 0.1, 0.2 | Incorrect | Nothing clears 0.3 |
| 0.55, 0.45, 0.2 | Ambiguous | Something clears 0.3, nothing clears 0.7 |
The paper doesn't publish the threshold values it used, so 0.7 and 0.3 are starting points. Tune them on real questions from your users (more on that at the end).
Notice the edge case for free: if retrieval returns no documents at all, scores is empty, any(...) is false, good is empty, and the verdict is Incorrect. That's the right call.
Which documents survive
A Correct verdict doesn't mean "use all retrieved documents". Only documents scoring above the lower threshold go forward. With scores 0.8, 0.4 and 0.2, the verdict is Correct because of the first document; the first two go to refinement (both beat 0.3) and the third is dropped. This is why evaluate stores good_docs separately from docs, and why refine must now build its context from good_docs.
Why keep the 0.4 document at all, instead of only the one that cleared the upper bar? Because a single chunk rarely holds the whole answer. The top document might define the trade-off while the second one carries the worked example or the formula. Documents between the thresholds are "useful but not sufficient alone", and refinement will strip whatever parts of them don't help. Dropping everything except the best chunk throws away supporting detail; keeping everything, including the 0.2 chunk, invites the noise CRAG exists to remove. The lower threshold is the line between those two.
Try it · CRAG retrieval evaluator
Pick a question, then drag document scores or the thresholds. Watch the verdict, which documents survive, and the path through the graph.
Question: Explain the bias–variance trade-off
- D1 · ch.4: bias, variance and model complexity0.90 kept
- D2 · ch.5: generalisation error decomposition0.75 kept
- D3 · ch.2: overfitting and underfitting0.50 kept
- D4 · index page: B–C0.15 dropped
Verdict: CORRECT
D1 scored above 0.70. Retrieval worked.
refine uses: good_docs (3 internal)
Routing on the verdict
from typing import Literal
def route_after_eval(state: State) -> Literal["refine", "web_search", "ambiguous"]:
return {"CORRECT": "refine", "INCORRECT": "web_search", "AMBIGUOUS": "ambiguous"}[state["verdict"]]
builder.add_conditional_edges("evaluate", route_after_eval)
In this iteration only the Correct branch is real: it refines and generates. The other two are placeholder nodes that set an answer like "retrieval was not good enough" and end. Wiring placeholders first is a good habit: you can test the evaluator and the routing on real questions before you write the expensive branches.
Running the three test questions now gives:
- "Explain the bias–variance trade-off": Correct (one chunk scored above 0.7), refined and answered.
- "AI news from last week": Incorrect, nothing above 0.3.
- "What are attention mechanisms, and why are they central to current models?": Ambiguous. The books touch on attention in older models but not on the modern part of the question, so scores land in the middle.
The transformer question that fooled plain RAG now lands in Incorrect or Ambiguous instead of being answered from nowhere. That alone is a big safety win.
Iteration three, web search for incorrect retrieval
An Incorrect verdict shouldn't leave the user empty-handed. CRAG's answer is to go outside: search the web and answer from what comes back.
from langchain_tavily import TavilySearch
tavily = TavilySearch(max_results=5)
def web_search(state: State) -> dict:
res = tavily.invoke({"query": state["question"]})
web_docs = [
Document(page_content=f"{r['title']}\n{r['content']}", metadata={"url": r["url"]})
for r in res["results"]
]
return {"web_docs": web_docs}
Search results are converted into Document objects, the same type the retriever returns, so everything downstream can treat internal and external knowledge alike. The URL goes in metadata so the generator can cite it.
Web results are no cleaner than retrieved chunks. A results page mixes the useful hit with SEO filler and tangents. So in CRAG, web documents also go through knowledge refinement before generation. You don't need a second refine node for that; make the existing one choose its source based on the verdict:
def refine(state: State) -> dict:
if state["verdict"] == "CORRECT":
source = state["good_docs"]
else: # INCORRECT
source = state["web_docs"]
context = "\n\n".join(d.page_content for d in source)
strips = decompose_to_sentences(context)
verdicts = filter_chain.batch([{"question": state["question"], "sentence": s} for s in strips])
kept = [s for s, v in zip(strips, verdicts) if v.keep]
return {"strips": strips, "kept_strips": kept, "refined_context": "\n".join(kept)}
The graph gains web_search → refine, reusing both refine and generate. State gains a web_docs: list[Document] key. Ask "AI news from last month" now and, instead of "I don't know", you get a summary of real recent stories drawn from search results.
Iteration four, query rewriting
Users don't type search-engine queries. They type things like "llm and recent developments" or "who wrote that batman movie where he dies". Sent verbatim, those get mediocre results. The paper therefore rewrites the question into a search query before searching. Its example turns "Who was the screenwriter for Death of a Batman?" into a keyword query like "Death of a Batman screenwriter Wikipedia".
class WebQuery(BaseModel):
query: str
rewrite_prompt = ChatPromptTemplate.from_messages([
("system",
"Rewrite the user's question into one web search query. Keep it short and keyword-rich, "
"keep names and entities exact. If the question implies recency, add a constraint such as "
"'last 30 days'. Do not answer the question."),
("human", "{question}"),
])
rewriter = rewrite_prompt | llm.with_structured_output(WebQuery)
def rewrite_query(state: State) -> dict:
return {"web_query": rewriter.invoke({"question": state["question"]}).query}
web_search now searches state["web_query"] instead of the raw question, and the graph becomes evaluate → rewrite_query → web_search → refine → generate on the Incorrect branch.
"Recent AI news" might become "AI news last 30 days". The rewrite added a time window the user only implied, which is exactly the kind of fix that improves search results. Honest caveat: with a capable search API, the gain is often modest, because the API already does some query understanding. It's cheap insurance, and it's also the natural place to strip private details before a query leaves your system.
Keep the original question for everything else. Grading, refinement and generation should all judge relevance against what the user asked, not against the search-engine phrasing.
Iteration five, the ambiguous case
The last missing branch is Ambiguous: retrieval found something useful, but not enough. The paper's action is to keep the good internal documents, search the web as well, and refine the combination.
Merging two branches with state
You could build a third branch with its own rewrite, search and refine nodes. There's a neater way, and it shows why shared state is so useful. The Ambiguous path needs exactly the same steps as Incorrect (rewrite, search, refine, generate). The only difference is what refine uses as its source. And refine can see the verdict in state.
So route both non-Correct verdicts down one path, and let refine decide:
def refine(state: State) -> dict:
if state["verdict"] == "CORRECT":
source = state["good_docs"] # internal only
elif state["verdict"] == "INCORRECT":
source = state["web_docs"] # external only
else:
source = state["good_docs"] + state["web_docs"] # AMBIGUOUS: both
... # decompose, filter, recompose as before
def route_after_eval(state: State) -> Literal["refine", "rewrite_query"]:
return "refine" if state["verdict"] == "CORRECT" else "rewrite_query"
The good_docs from the evaluator are still sitting in state when the web results arrive two nodes later, so refine can merge them. Three behaviours, two paths, no duplicated nodes. The verdict travels with the data and the shared node adapts.
Test it with "batch normalisation vs layer normalisation". The textbooks cover batch norm but not layer norm, so no chunk scores above 0.7, but several beat 0.3: Ambiguous. The answer draws batch-norm details from the books and layer-norm details from the web, refined together into one context.
The complete graph
from typing import Literal
class State(TypedDict):
question: str
docs: list[Document]
good_docs: list[Document]
verdict: str
reason: str
web_query: str
web_docs: list[Document]
strips: list[str]
kept_strips: list[str]
refined_context: str
answer: str
builder = StateGraph(State)
for name, fn in [("retrieve", retrieve), ("evaluate", evaluate), ("rewrite_query", rewrite_query),
("web_search", web_search), ("refine", refine), ("generate", generate)]:
builder.add_node(name, fn)
builder.add_edge(START, "retrieve")
builder.add_edge("retrieve", "evaluate")
builder.add_conditional_edges("evaluate", route_after_eval)
builder.add_edge("rewrite_query", "web_search")
builder.add_edge("web_search", "refine")
builder.add_edge("refine", "generate")
builder.add_edge("generate", END)
crag = builder.compile()
out = crag.invoke({"question": "Batch normalization vs layer normalization?"})
print(out["verdict"], "|", out["reason"])
print(out["answer"])
The final generate reads refined_context and is told to cite URLs when the context came from the web. Map it back to the paper's diagram:
| Paper | This graph |
|---|---|
| Retrieval evaluator | evaluate with two thresholds |
| Correct → knowledge refinement → internal knowledge | refine over good_docs |
| Incorrect → query rewrite → web search → external knowledge | rewrite_query → web_search → refine over web_docs |
| Ambiguous → both | Same path, refine over good_docs + web_docs |
| Generator | generate over refined_context |
Note there are no loops: every question passes through at most six nodes once. CRAG corrects retrieval with a single decision, not by retrying. That makes it predictable in cost and latency, which is a real advantage over looping designs like Self-RAG in the next lecture.
Tracing a run
CRAG makes several decisions per question, and when an answer is wrong you need to know which one failed. Streaming node updates shows each decision as it happens:
for update in crag.stream({"question": "Batch normalization vs layer normalization?"},
stream_mode="updates"):
for node, delta in update.items():
if node == "evaluate":
print("verdict:", delta["verdict"], "-", delta["reason"])
elif node == "rewrite_query":
print("web query:", delta["web_query"])
elif node == "refine":
print(f"kept {len(delta['kept_strips'])} of {len(delta['strips'])} strips")
else:
print("done:", node)
For the normalisation question a typical trace reads like this:
- retrieve returns four chunks: two on batch normalisation, one on training deep networks, one on feature scaling.
- evaluate scores them roughly 0.6, 0.45, 0.35 and 0.2. Nothing clears 0.7, three clear 0.3: Ambiguous, with three good documents.
- rewrite_query produces something like "batch normalization vs layer normalization differences transformers".
- web_search returns five results, most explaining layer normalisation.
- refine decomposes the three book chunks plus the five web results into sentences, keeps perhaps a dozen, and drops the feature-scaling material and the web pages' filler.
- generate writes the comparison, citing the web URLs for the layer-norm claims.
Each line points at one component. A wrong verdict means the grader or the thresholds; a bad web query means the rewrite prompt; a thin answer with many dropped strips means the filter. With LangSmith tracing enabled (LANGSMITH_TRACING=true plus an API key), the same information appears per node in the trace view, including every grader call and its reason.
Failure modes and tuning
| Problem | What you see | What to do |
|---|---|---|
| Generous grader | Almost everything is Correct; irrelevant chunks still reach the generator | "Be conservative" in the prompt, few-shot examples of low scores, or raise UPPER |
| Harsh grader | Constant web searches for questions your docs answer | Lower thresholds; check grader reasons on known-good questions |
| Threshold guesswork | Verdicts feel random | Label 50–100 real questions as answerable or not, sweep UPPER/LOWER, pick the best split |
| Over-filtering | Answers come out thin or miss the key sentence | Two-sentence strips; lenient filter prompt; log kept_strips |
| Cost and latency | One grading call per chunk plus one per sentence | batch, grade strips per document, or a small fine-tuned grader |
| Data leakage | Internal questions sent to a public search API | Disable web fallback or sanitise in the rewrite |
| Untrusted web text | A result page says "ignore previous instructions…" | Treat web content as data; keep instructions in the system prompt; refine before use |
| Stale or wrong web info | Confident answers from low-quality pages | Prefer authoritative domains (include_domains), cite URLs so users can check |
Measure before and after. Keep a small test set of questions with known answers in three buckets: questions your documents fully cover, questions they don't cover at all, and questions they half cover. Run plain RAG and CRAG on the same set and compare:
| Metric | What it tells you |
|---|---|
| Answer correctness (graded by hand or by an LLM judge against reference answers) | Whether the extra machinery actually helps |
| Verdict accuracy per bucket | Whether covered questions get Correct, uncovered get Incorrect, half-covered get Ambiguous |
| Correct refusals | How often the system declines when it truly can't answer |
| Web-search rate | How often you pay for, and leak to, the fallback |
| Cost and latency per question | The price of the reliability |
The verdict-accuracy row is the one that drives tuning. If covered questions often come out Ambiguous, UPPER is too high or the grader too harsh; if uncovered questions come out Correct, the grader is too generous. CRAG trades extra model calls for reliability; the test set tells you whether the trade is worth it for your data.
Cheat sheet
- Plain RAG always retrieves top-k and trusts it; off-topic questions get answered from noise or parametric memory.
- CRAG inserts a retrieval evaluator that scores each document from 0 to 1 against the question.
- Correct: some score above UPPER. Incorrect: none above LOWER. Ambiguous: everything else.
- Only documents above LOWER are used for generation, even when the verdict is Correct.
- Knowledge refinement: decompose into sentence strips, filter by relevance, recompose.
- Incorrect: rewrite the query, search the web, refine the web results, generate from external knowledge only.
- Ambiguous: keep the good internal docs, add web results, refine both together.
- Route Incorrect and Ambiguous down one path; let
refinepick its source from the verdict in state. - Grade one chunk per call and use
batchfor concurrency. - The paper's evaluator was a fine-tuned T5-large; a prompted chat model is a workable stand-in.
- CRAG has no loops: one decision, predictable cost.
- Watch for generous graders, over-filtering, and leaking private questions to web search.
Scenario quiz
Real situations, engineer-style answers. 80% to pass.
Your CRAG evaluator uses UPPER = 0.7 and LOWER = 0.3. Classify each retrieval by its per-document scores.