RAG Evaluation, Grounding and Debugging
Know whether your system found the right evidence, used it faithfully and cited it correctly, and where to look when it did not.
Evaluate retrieval and generation separately. For retrieval, label which passages answer each question and compute recall, precision, MRR and NDCG. For answers, check correctness, faithfulness to the retrieved text, completeness, citation accuracy and the ability to say "not found". When something fails, walk the pipeline from source document to final sentence and fix the first broken stage.
What you will learn: test set design, retrieval metrics, grounded generation and citations, groundedness and faithfulness measures, failure analysis and evaluation of agentic retrieval.
Prerequisites: RAG Explained and Agentic RAG. Agent Testing: Unit to End-to-End covers testing agents in general.
Two systems in one
A retrieval-augmented system first searches, then writes. A wrong answer can come from either part, and the fixes are completely different. If the right passage never arrived, no prompt change will help. If it arrived and was ignored, a better index will not help.
Building the test set
Good evaluation is mostly good test data. Start with real questions, with permission, and include:
| Category | Tests |
|---|---|
| Common lookups | Everyday quality |
| Exact codes and names | Keyword matching |
| Paraphrases | Meaning matching |
| Multi-part and multi-hop | Coverage of all evidence |
| Unanswerable | Honest refusal |
| Outdated versus current | Freshness handling |
| Restricted content | Permissions |
| Conflicting sources | Authority and disclosure |
For each, record the expected answer points and the passages that support them, with a grade of how useful each is. Label against document sections and not only chunk identifiers, so that labels survive a change of chunking. Models can draft questions from documents, but such questions often echo the source wording and are too easy; review them and mix in real ones. Keep part of the set unseen while tuning.
Recall, precision, MRR and NDCG
| Metric | Question it answers | Notes |
|---|---|---|
| Recall at k | What share of relevant passages is in the top k? | Usually the first thing to fix |
| Precision at k | What share of the top k is relevant? | Low values waste context |
| Hit rate at k | Did at least one relevant passage appear? | Coarse but intuitive |
| MRR | How high is the first relevant result? | One divided by its rank, averaged |
| NDCG at k | Are the most useful passages near the top? | Uses graded relevance; one is ideal order |
"""Recall, precision, MRR and NDCG for a small retrieval test set."""
import math
# query: (ranked results, {relevant id: grade 1-3})
RUNS = {
"keyword": {"q1": (["a", "x", "b", "y", "z"], {"a": 3, "b": 2}),
"q2": (["x", "y", "z", "c", "w"], {"c": 3}),
"q3": (["d", "e", "x", "y", "z"], {"d": 1, "e": 3})},
"hybrid": {"q1": (["a", "b", "x", "y", "z"], {"a": 3, "b": 2}),
"q2": (["x", "c", "y", "z", "w"], {"c": 3}),
"q3": (["e", "d", "x", "y", "z"], {"d": 1, "e": 3})},
}
def recall(ranked, rel, k):
return len(set(ranked[:k]) & set(rel)) / len(rel)
def precision(ranked, rel, k):
return len(set(ranked[:k]) & set(rel)) / k
def reciprocal_rank(ranked, rel):
return next((1 / i for i, d in enumerate(ranked, 1) if d in rel), 0.0)
def ndcg(ranked, rel, k):
def dcg(grades):
return sum((2 ** g - 1) / math.log2(i + 1) for i, g in enumerate(grades, 1))
ideal = dcg(sorted(rel.values(), reverse=True)[:k])
return dcg([rel.get(d, 0) for d in ranked[:k]]) / ideal
def mean(values):
return sum(values) / len(values)
print("run recall@3 prec@3 MRR NDCG@3")
for name, queries in RUNS.items():
rows = queries.values()
print(f"{name:8} {mean([recall(r, g, 3) for r, g in rows]):8.2f} "
f"{mean([precision(r, g, 3) for r, g in rows]):6.2f} "
f"{mean([reciprocal_rank(r, g) for r, g in rows]):5.2f} "
f"{mean([ndcg(r, g, 3) for r, g in rows]):7.2f}")
Output:
run recall@3 prec@3 MRR NDCG@3
keyword 0.67 0.44 0.75 0.56
hybrid 1.00 0.56 0.83 0.88
The hybrid run finds everything within three results and orders it better. Note that precision cannot reach one here, because some questions have fewer than three relevant passages; read it against the maximum possible. NDCG formulas differ between tools in how they weight grades, so compare numbers only from one implementation. With few questions, small differences are noise: look at individual changed cases and, for larger sets, estimate uncertainty by resampling.
Recall at 50 tells you whether the reranker has a chance. Recall at the number of passages sent to the model tells you whether the answer has a chance. Track both.
Grounded generation, citations and attribution
Grounding means the answer rests on supplied evidence. Encourage it in the request and verify it afterward.
- Give each passage a short identifier, title and date.
- Instruct the model to answer only from the passages, to cite the identifier after each claim and to say what is not covered.
- Ask it to report disagreements between sources instead of silently choosing.
- Resolve identifiers to links in code, so that the model cannot invent a web address.
- Let users open the exact passage.
Some APIs provide citations directly. The Claude API's citations feature, for example, chunks supplied documents and returns references to the cited text, which guarantees that a citation points to real supplied content. It does not by itself guarantee that your sources are right or that every conclusion follows from them.
Groundedness, faithfulness and citation accuracy
| Measure | Definition | Example failure |
|---|---|---|
| Correctness | Matches the truth | Source was outdated |
| Faithfulness (groundedness) | Each claim is supported by retrieved text | Adds a figure from model memory |
| Completeness | All required points covered | Omits an exception |
| Citation validity | Cited identifier was retrieved | Invented reference |
| Citation support | Cited passage supports that claim | Right topic, wrong fact |
| Citation coverage | Claims that need a citation have one | Unsupported sentence slips in |
| Abstention | Declines when evidence is missing | Confident guess |
Faithful and correct are different. An answer can repeat an outdated policy with perfect faithfulness. Research benchmarks such as ALCE evaluate citation quality alongside correctness, and tools such as Ragas implement model-based versions of several of these measures.
Cheap checks first
"""Cheap citation checks to run before any model-based judge."""
import re
SOURCES = { # only what was actually retrieved
"s1": "The nightly hotel limit is 150. In capital cities the limit is 220.",
"s2": "Rail is required for journeys under four hours.",
}
ANSWER = ("The hotel limit is 150 per night [s1]. "
"In capital cities it rises to 250 [s1]. "
"Take the train for short journeys [s2]. "
"Taxis are always covered. "
"Flights need approval [s9].")
def words(t):
return {w for w in re.findall(r"[a-z]{4,}", t.lower())}
def check(sentence):
cited = re.findall(r"\[(\w+)\]", sentence)
if not cited:
return "no citation"
if any(c not in SOURCES for c in cited):
return "cites a source that was not retrieved"
text = " ".join(SOURCES[c] for c in cited)
claim = re.sub(r"\[\w+\]", "", sentence)
missing = set(re.findall(r"\d+", claim)) - set(re.findall(r"\d+", text))
if missing:
return f"number {sorted(missing)} not in source"
if len(words(claim) & words(text)) < 2:
return "weak support: send to judge"
return "passes cheap checks"
for sentence in re.split(r"(?<=\.)\s+", ANSWER):
print(f"{check(sentence):38} | {sentence}")
Output:
passes cheap checks | The hotel limit is 150 per night [s1].
number ['250'] not in source | In capital cities it rises to 250 [s1].
weak support: send to judge | Take the train for short journeys [s2].
no citation | Taxis are always covered.
cites a source that was not retrieved | Flights need approval [s9].
Deterministic checks catch an unretrieved citation, a missing citation and a number absent from the source. The third sentence is probably fine but shares too few words, so it goes to a stronger judge. These rules are rough: a right number can still be attached to the wrong thing. Use them as a filter, not as proof.
Model judges
A judge model can split an answer into claims and check each against the passages. Give it a clear rubric with examples, ask for the supporting quotation, and compare its verdicts with human labels on a sample before trusting it. Recheck when you change the judge model. See LLM Judges, Human Review and Ratings.
Retrieval failure analysis and debugging
| Stage | Check | Typical fix |
|---|---|---|
| Source | Does the fact exist in an approved document? | Add or correct content |
| Ingestion | Was it parsed and indexed, and is it current? | Parser, sync, deletion |
| Chunk | Is it intact and understandable alone? | Chunking, heading path |
| Permission | May this user see it, and did the filter agree? | Access mapping |
| Query | Does the searched text express the need? | Rewrite or decompose |
| Candidates | Is it in the first, wide result list? | Hybrid search, embedding model |
| Ranking | Did it make the final set? | Fusion, reranker, k |
| Context | Was it truncated or buried? | Assembly order and budget |
| Generation | Was it used correctly? | Instructions, model |
| Presentation | Are citations and caveats shown? | Application code |
Go top to bottom and stop at the first failure. Tally causes across many failed questions; the largest group is your next piece of work. Context Assembly, Retrieval, Compression and Caching covers the context stage.
Users report invented limits. Tracing twenty cases shows that in most of them the current policy was never retrieved: an older version outranked it. The team marks superseded documents, filters them out and adds ten such cases to the test set. Only the few remaining cases involve the model adding facts.
Evaluating RAG inside agents
An agent decides whether to search, what to search, how often and when to stop. Evaluate the path as well as the answer.
| Measure | Meaning |
|---|---|
| Search decision accuracy | Searched when needed, not when pointless |
| Query quality | Did queries retrieve new relevant evidence? |
| Cumulative recall | Evidence found across all searches |
| Redundancy | Repeated queries and passages |
| Stopping | Stopped with enough evidence, or admitted the gap |
| Cost per solved question | Tokens, searches and time |
Several paths can be valid, so judge outcomes and rules instead of requiring one exact sequence. Run each case more than once, since behavior varies, and record the whole trace.
Reading a set of results
Numbers become useful when they point to a decision. Consider the pattern first, then the single cases behind it.
| Pattern | Likely meaning | Look at next |
|---|---|---|
| Low recall, high faithfulness | The model is honest about thin evidence | Ingestion, queries, candidates |
| High recall, low correctness | Evidence arrives but is misused or outdated | Context order, instructions, source dates |
| High correctness, low faithfulness | Model answers from its own memory | Whether retrieval is helping at all |
| Good averages, bad multi-part cases | One part crowds out the other | Decomposition and result diversity |
| High abstention | Threshold too strict or coverage poor | Refused cases that had evidence |
| Valid citations, weak support | Identifiers attached loosely | Passage length and citation instructions |
Comparing two versions
Run both on the same cases and list the ones that changed in either direction. Ten gains and nine losses is not an improvement worth shipping, even if the average rose slightly. Read the losses. They often share a cause, such as a new chunker splitting one kind of table, that the average would never reveal.
Cost of evaluation
Judges and repeated runs cost money. Run the cheap deterministic checks and retrieval metrics on every change, the model-judged answer measures on candidate releases and human review on a sample. Cache judge results keyed by case, answer, passages and judge version so that unchanged items are not scored again.
After release
- Run the offline set on every change to content pipeline, index, prompt or model, and block releases on agreed regressions.
- Monitor empty results, low reranker scores, abstention rate, citation check failures and user corrections.
- Sample live answers for human review under privacy rules.
- Turn confirmed failures into new test cases.
- Refresh labels when documents change, or old answers will look "wrong" or "right" for the wrong reason.
Reporting results honestly
State the test set size and mix, the labeling method, the k used, runs per case and variation. Report by category: an overall score can rise while restricted-content or unanswerable cases get worse. Safety checks such as permission leakage are pass or fail.
Keeping the set alive
Give the test set an owner and a version. When a policy changes, update the expected answer on the same day. Remove duplicates, retire cases about content that no longer exists and record why, so that scores from different months remain explainable.
Common mistakes
- Judging only final answers.
- Testing questions generated from the documents and never reviewed.
- No unanswerable cases, so confident guessing goes unnoticed.
- Trusting a model judge without checking it.
- Tuning on the same set used to report quality.
Checklist
- Test cases cover codes, paraphrases, multi-part, unanswerable, stale and restricted.
- Passages are labeled with grades.
- Retrieval and answer metrics are tracked separately.
- Citations are checked in code and by judge or person.
- Failures are classified by pipeline stage.
- Agent search behavior is measured.
- Releases are gated and live failures feed the set.
Frequently asked questions
What score is good enough?
It depends on the cost of a wrong answer and on what people achieve today without the system. Set thresholds per category with the owners of the task.
How many questions do I need?
A few dozen reveal major problems. Grow toward hundreds as you need to detect smaller differences and cover more categories.
Can I evaluate without labeled passages?
Model judges can estimate relevance and faithfulness. Label at least a sample by hand so that you know how far to trust them.
Does adding citations prevent hallucination?
It makes errors easier to see and check. A citation can still point to text that does not support the claim, which is why support must be verified.
References and further reading
- Gao et al.: Generating text with citations (ALCE)
- Es et al.: Ragas, automated evaluation of retrieval-augmented generation
- Ragas documentation
- Saad-Falcon et al.: ARES evaluation framework
- Claude documentation: Citations
Next steps
RAG Security, Freshness and Cost
Keep a good system safe, current and affordable.
Build a RAG Knowledge Assistant
Apply these measures to a full build.
Agent Evaluation Framework
Fit retrieval tests into a wider evaluation program.