RAG Evaluation & Improvement
Lesson opener
In one line: Measure retrieval and generation separately, classify every failure, then change one thing at a time and prove the change helped on a fixed dataset.
Why it matters: A RAG system can sound confident, cite a document and still be irrelevant, unsupported or out of date. Reading a few good-looking answers tells you nothing about how often it fails or where. Without a failure taxonomy and a repeatable test set, teams "improve" retrieval by trial and error and often make other cases worse.
Before this lesson: Enterprise RAG Architecture. Evaluation basics are assumed from Evaluation & Safety basics and Evaluation & Testing for agents.
Northline Consumer Goods (illustrative) launched an internal support assistant over IT and ERP knowledge-base articles. After two weeks, the service desk reports that answers are fluent but often irrelevant: a question about resetting a locked ERP account returned a polished explanation of password policy that never mentioned the reset step. Satisfaction scores are falling, but the team cannot say whether the cause is retrieval, chunking, an out-of-date article, the prompt or the model. They need an evaluation suite and an improvement plan.
What you will be able to do
- Separate retrieval metrics (relevance, context precision, recall) from generation metrics (groundedness, citation correctness, completeness).
- Explain why recall needs labelled ground truth and what "recall awareness" means when you cannot label everything.
- Build evaluation datasets that include answerable, unanswerable, conflicting and stale-source questions.
- Create a failure taxonomy that tells you which pipeline stage to fix.
- Run controlled experiments with paired comparisons and per-slice results.
- Turn findings into a prioritised improvement plan with acceptance thresholds.
Deliverable: a RAG evaluation suite (dataset design, metric definitions, scoring method, thresholds) plus an improvement plan (ranked fixes, one experiment per fix, success criteria, stop conditions).
Prerequisites
| Prerequisite | Why it matters |
|---|---|
| Enterprise RAG Architecture | Pipeline stages, metadata, authority and access rules that evaluation will test. |
| Evaluation & Safety basics | Introduces test sets and simple checks. |
| RAG basics | Chunk, embed and retrieve. |
| Evaluation & Testing (agent course) | Evaluation pyramid and regression testing. |
| Statistics basics | Averages, proportions and why small samples mislead. |
| Monitoring and drift for ML | Monitoring ideas carried into production sampling. |
Plain English
RAG has two halves, and each needs its own measurement. If you only score the final answer you cannot tell which half failed.
Retrieval metrics ask: did the system bring back the right evidence?
- Context relevance / context precision at k: of the top k retrieved chunks, what share are actually relevant? Low precision means the prompt is padded with noise, which can distract the model.
- Recall at k: of the relevant chunks that exist, what share appears in the top k? Low recall means the answer cannot be right because the evidence never arrived. Recall requires a labelled set: for each test question, someone has marked which documents or chunks contain the answer. You cannot compute true recall over a whole corpus without labels. Recall awareness means being honest about this: you estimate recall on a labelled sample, you add questions whose answers are known to exist, and you treat "no result" as a signal rather than proof of absence.
Generation metrics ask: given the evidence, was the answer good?
- Groundedness (faithfulness): is every claim in the answer supported by the retrieved passages? A fluent answer can be ungrounded.
- Citation correctness: do the citations point to passages that actually support the claim, and are they approved, current documents?
- Completeness: did the answer include the key points a good answer must contain? An answer can be grounded yet leave out the essential step.
- Answer relevance: does the answer address the question asked?
Special question types need their own tests:
- Unanswerable: nothing in the approved sources answers it. The right behaviour is a refusal and a route to an owner.
- Conflicting sources: two sources disagree. The right behaviour follows your authority rule, or surfaces both.
- Stale: the answer exists only in a superseded document, or a newer one exists. The right behaviour is to use the current one and never cite the old.
- Permission-limited: the answer exists but the user may not read it. The right behaviour is neutral refusal.
Datasets. A useful evaluation set mixes: (1) a golden set written and labelled by subject-matter experts, small but trusted; (2) real questions sampled from production logs (with privacy handling), labelled later; (3) synthetic questions generated from documents with a model to widen coverage, always spot-checked by a human because generated questions tend to be easier and more literal than real ones; (4) adversarial and trap questions for unanswerable, conflicting, stale and permission cases. Keep the golden set separate from anything used to tune the system, and do not copy test questions into prompts or examples, otherwise scores overstate real quality (leakage).
Failure taxonomy. Classify each failure by the earliest stage that broke, so the fix goes to the right place:
| Category | Typical cause | Typical fix |
|---|---|---|
| Ingestion/parse error | Table columns merged, text missing | Parser fix, parse validation |
| Chunking problem | Answer split across chunks, no heading context | Structure-aware chunking, add context prefix |
| Retrieval miss | Right document never retrieved | Hybrid search, query handling, metadata |
| Ranking problem | Right chunk retrieved but low | Reranking, authority ordering |
| Stale or wrong-version source | Superseded document returned | Status filters, supersession process |
| Access error | Restricted chunk retrieved, or allowed chunk missing | ACL logic and sync |
| Context assembly | Evidence truncated or buried | Budget, ordering, de-duplication |
| Ungrounded generation | Claims not in evidence | Prompt, validator, refusal rule |
| Wrong citation | Cited passage does not support claim | Citation validation |
| False refusal | Evidence existed but system refused | Threshold tuning |
| Answered unanswerable | System invented an answer | Refusal threshold, relevance gate |
| Incomplete answer | Key point missing | Context size, prompt, retrieval of second chunk |
Experiments. Change one variable at a time (chunk size, reranker, prompt version, retrieval depth), run on the same dataset, compare per case (paired), and look at slices such as question type, source and department, because an average can improve while an important slice gets worse. Small datasets give noisy results; avoid declaring victory on a difference of one or two cases, and increase sample size or repeat runs when decisions are costly.
Teacher walkthrough
Evaluate the support assistant step by step.
- Business owner. The Service Desk Manager owns quality targets; the knowledge-base owner owns article accuracy.
- Approved users. Employees via SSO. Evaluation runs use test accounts that mirror different permission groups.
- Sources. Only approved IT and ERP articles at the time of the test snapshot. Record the snapshot date and the index version with every evaluation run so results are reproducible.
- Permissions. Include test questions that require restricted content from accounts that lack it, to confirm neutral refusal.
- Build the dataset. Start with 120 cases: 60 answerable golden questions with labelled gold articles and key points, 15 unanswerable, 15 conflict or version traps, 15 stale traps, 15 permission traps. Add 100 sampled production questions labelled by the service desk over time.
- Validation of the dataset. Two reviewers label a subset; disagreements are resolved by the owner. A labelling guide defines "relevant," "supported" and "complete."
- Run and score. Compute retrieval metrics from labels automatically. Score generation using deterministic checks (citations exist, quoted values match) plus reviewer or model-based judgement for groundedness and completeness. Model-based judging must be calibrated against human labels on a sample (see the next lesson).
- Classify failures. Tag every failed case with one taxonomy category and look at counts by category and by slice.
- Human review. The owner reviews the top failing categories and a random sample of passing cases to check the scorer is not wrong.
- Plan fixes. Rank categories by frequency and business impact; assign one experiment per fix with a success threshold.
- Escalation. Any case showing restricted content in an answer is escalated to security immediately, regardless of overall scores.
- Monitoring and fallback. After release, sample production answers weekly, track refusal rate, thumbs-down, stale citations and retrieval-empty rate. If the new variant regresses a protected slice, revert to the previous index or prompt version.
- Stop condition. Do not release a variant if any permission-trap case fails, if stale citations are above the threshold, or if any slice drops by more than the agreed tolerance.
Worked example
The script below scores a tiny, hand-labelled run with standard-library Python only. Each case records which chunks are gold, what was retrieved in rank order, which were cited, whether each claim was supported, how many key points were required and covered, and whether the system refused. It computes the metrics, classifies failures with a simple first-match rule, and compares two retrieval variants per case.
from collections import Counter
STALE = {"KB-OLD"}
CASES = [
{"id": "c1", "type": "answerable", "gold": {"KB-1"}, "retrieved": ["KB-1", "KB-7", "KB-3"],
"cited": ["KB-1"], "claims": [True, True], "points": 2, "covered": 2, "refused": False},
{"id": "c2", "type": "answerable", "gold": {"KB-2", "KB-5"}, "retrieved": ["KB-9", "KB-2", "KB-8"],
"cited": ["KB-9"], "claims": [True, False], "points": 3, "covered": 1, "refused": False},
{"id": "c3", "type": "answerable", "gold": {"KB-4"}, "retrieved": ["KB-6", "KB-8", "KB-9"],
"cited": ["KB-6"], "claims": [False], "points": 1, "covered": 0, "refused": False},
{"id": "c4", "type": "unanswerable", "gold": set(), "retrieved": ["KB-7", "KB-1"],
"cited": ["KB-7"], "claims": [False], "points": 0, "covered": 0, "refused": False},
{"id": "c5", "type": "answerable", "gold": {"KB-3"}, "retrieved": ["KB-OLD", "KB-3"],
"cited": ["KB-OLD"], "claims": [True], "points": 1, "covered": 1, "refused": False},
{"id": "c6", "type": "answerable", "gold": {"KB-1"}, "retrieved": ["KB-1"],
"cited": [], "claims": [], "points": 1, "covered": 0, "refused": True},
{"id": "c7", "type": "unanswerable", "gold": set(), "retrieved": [],
"cited": [], "claims": [], "points": 0, "covered": 0, "refused": True},
]
def precision_at_k(case, k):
top = case["retrieved"][:k]
return len([d for d in top if d in case["gold"]]) / len(top) if top else 0.0
def recall_at_k(case, k):
return len(case["gold"] & set(case["retrieved"][:k])) / len(case["gold"])
def classify(case, k=3):
if case["type"] == "unanswerable":
return None if case["refused"] else "answered_unanswerable"
if case["refused"]:
return "false_refusal"
if set(case["cited"]) & STALE:
return "stale_source_cited"
if recall_at_k(case, k) == 0:
return "retrieval_miss"
if case["claims"] and not all(case["claims"]):
return "ungrounded_claim"
if not set(case["cited"]) <= case["gold"]:
return "wrong_citation"
if case["covered"] < case["points"]:
return "incomplete"
return None
def report(cases, k=3):
ans = [c for c in cases if c["type"] == "answerable"]
unans = [c for c in cases if c["type"] == "unanswerable"]
answered = [c for c in ans if not c["refused"]]
claims = [x for c in answered for x in c["claims"]]
cited_ok = sum(1 for c in answered for d in c["cited"] if d in c["gold"])
cited_all = sum(len(c["cited"]) for c in answered)
print(f"context precision@{k}: {sum(precision_at_k(c, k) for c in ans) / len(ans):.2f}")
print(f"recall@{k}: {sum(recall_at_k(c, k) for c in ans) / len(ans):.2f}")
print(f"groundedness: {sum(claims) / len(claims):.2f}")
print(f"citation correctness: {cited_ok / cited_all:.2f}")
print(f"completeness: {sum(c['covered'] for c in ans) / sum(c['points'] for c in ans):.2f}")
print(f"unanswerable handled: {sum(c['refused'] for c in unans)}/{len(unans)}")
print("failure taxonomy:", dict(Counter(filter(None, (classify(c, k) for c in cases)))))
def compare_recall(cases, variant, k=3):
wins = losses = ties = 0
for c in cases:
if c["type"] != "answerable" or c["id"] not in variant:
continue
new = dict(c, retrieved=variant[c["id"]])
delta = recall_at_k(new, k) - recall_at_k(c, k)
wins += delta > 0
losses += delta < 0
ties += delta == 0
print(f"paired recall@{k}: wins={wins} losses={losses} ties={ties}")
VARIANT_RETRIEVAL = {"c1": ["KB-1", "KB-7", "KB-3"], "c2": ["KB-2", "KB-5", "KB-9"],
"c3": ["KB-4", "KB-6", "KB-8"], "c5": ["KB-3", "KB-1"], "c6": ["KB-1"]}
report(CASES)
compare_recall(CASES, VARIANT_RETRIEVAL)The baseline output reports context precision@3 of 0.43, recall@3 of 0.70, groundedness 0.67, citation correctness 0.25, completeness 0.50, one of two unanswerable questions handled, and one failure in each of five categories: ungrounded_claim, retrieval_miss, answered_unanswerable, stale_source_cited and false_refusal. The paired comparison shows the variant wins on two cases, loses none and ties on three, which points to a retrieval change worth trying; it does not by itself fix the stale citation, the false refusal or the unanswerable case, because those live in other stages. The table of numbers is only a teaching sample of seven cases; a real suite needs far more, and the thresholds must come from your owners.
A second workplace case
Northline's Logistics team uses a RAG assistant over carrier contracts. Scores look healthy at 92% groundedness, yet planners keep escalating wrong answers about penalty clauses. Analysis by slice shows contracts with clause tables score 61% completeness while plain-text contracts score 97%. The average hid the table slice. The taxonomy puts the failures in ingestion (table rows separated from their headers). The fix is parser and chunking work for tables, tested against a table-only slice of 40 labelled questions, with a gate that no slice may fall below its threshold.
Failure example
Symptom: Support answers about unlocking an ERP account are fluent but irrelevant: they describe password policy rules and never mention the unlock step. Users rate them poorly. The team's first reaction is to switch to a larger model, which makes the answers more eloquent and equally wrong.
Diagnosis: The team had no retrieval-level measurement. Running recall@5 on 40 labelled account questions shows 38%: the unlock procedure was split across two chunks, one of which began mid-list with no heading, and the vector search preferred the password-policy article that shared more vocabulary with the question. Generation was grounded in the wrong evidence, so groundedness looked acceptable while relevance failed.
Correction: Re-chunk procedures by step list with the article title and heading attached to each chunk; add keyword search for the exact transaction and field names; rerank the top 20; record results per slice. Do not change the model.
Validation: Re-run the same 40-case slice and the full suite. Recall@5 on the account slice reaches the target (set by the owner), no other slice drops beyond tolerance, and the unanswerable and stale traps still pass.
Prevention: Keep retrieval metrics in the release gate, require a failure-taxonomy label on every failed case, run the suite on every change to chunking, embeddings, retrieval settings, prompt or model, and refuse changes that fix one slice by breaking another.
Guided practice
Scenario: Northline's HR assistant answers leave questions. A new policy version changes carry-over from 5 to 3 days. After the update, some answers still cite the old policy. Design the evaluation additions and the first experiment.
Hints:
- What kind of test case catches stale citations?
- Which metric flags the problem, and which taxonomy category applies?
- What are two candidate fixes at different pipeline stages?
- How do you check the fix did not break other slices?
- What is the stop condition for release?
Complete solution:
- Test cases: 20 stale-trap questions whose correct answer exists only in the new policy and whose old version is also in the corpus snapshot before the fix; include the question types "how many days can I carry over" in several phrasings.
- Metric and category: citation correctness plus a stale-citation count; taxonomy
stale_source_cited(stale or wrong-version source). - Candidate fixes: (a) status filter and supersession flag at retrieval so superseded documents are excluded; (b) ingestion process that marks old versions superseded when a new version is approved. Fix (b) addresses the cause; fix (a) enforces it at query time.
- Experiment: deploy (a) in staging, re-index, run the stale-trap set plus the full suite; compare paired results to baseline.
- Regression checks: unanswerable, conflict and permission slices unchanged; overall recall within tolerance.
- Stop condition: release only if stale citations are zero on the stale-trap set and no slice falls below threshold; otherwise keep the previous index.
Independent practice
Create an evaluation suite and improvement plan for a RAG assistant in a domain you know (for example warehouse safety procedures or supplier onboarding).
Acceptance criteria
- Defines each metric (context precision, recall at k, groundedness, citation correctness, completeness) and how it is scored, including what labels are needed.
- Explains recall awareness: how recall is estimated from a labelled sample and what you will not claim.
- Includes a dataset plan with golden, production-sampled, synthetic (with human spot-check) and trap questions for unanswerable, conflicting, stale and permission cases.
- Keeps test data separate from tuning data and states how leakage is avoided.
- Provides a failure taxonomy and assigns a stage-specific fix to each category.
- Describes at least two controlled experiments with one variable each, paired comparison and slice analysis.
- Sets thresholds as proposals for the owner, not as universal values.
- Includes a human-review step for the scorer itself and a stop condition for release.
Common mistakes
- Scoring only the final answer, so retrieval problems hide behind fluent text.
- Evaluating on a handful of friendly questions chosen by the builder.
- Reporting recall without labels, or claiming "high recall" because the system returned results.
- Ignoring unanswerable, conflicting, stale and permission-limited questions.
- Using synthetic questions only; they are usually easier and more literal than real ones.
- Copying test questions into prompts or fine-tuning data so the test measures memory, not quality.
- Changing several variables at once and attributing the result to one of them.
- Looking only at averages and missing a failing slice.
- Treating a model-based judge as truth without checking it against human labels.
- Replacing the model when the failure lies in chunking, retrieval or sources.
- Declaring victory on a difference of one or two cases in a small dataset.
Quick check
- Why can answers be fluent and grounded yet irrelevant?
- What labels are needed to compute recall at k?
- Name two question types, besides normal answerable questions, that an evaluation set should contain.
- Why compare variants per case rather than only by average?
- What does a failure taxonomy let a team do?
Answers:
- If retrieval brings back the wrong evidence, the model can faithfully summarise irrelevant passages; groundedness is measured against what was retrieved, not against what should have been.
- For each test question, the documents or chunks that contain the answer must be marked as relevant (gold labels).
- Any two of: unanswerable, conflicting sources, stale or superseded sources, permission-limited questions.
- Paired comparison shows which cases improved or regressed and exposes slice regressions that an average can hide.
- It identifies the earliest pipeline stage that failed, so each failure gets the correct fix instead of a generic change like a bigger model.
Quiz alignment
The quiz (QUIZ_LLMOPS5) covers retrieval vs generation metrics, recall awareness, groundedness vs relevance, citation correctness, completeness, unanswerable and stale cases, dataset design and leakage, failure taxonomy, controlled experiments and slice analysis, using the support-assistant scenario.
Lesson summary
Evaluate retrieval and generation separately. Use labelled data for recall, deterministic checks for citations, and calibrated judgement for groundedness and completeness. Include unanswerable, conflict, stale and permission traps. Tag each failure with a pipeline stage, change one variable per experiment, compare per case and per slice, and gate releases on thresholds your owners set.
Bridge to the next lesson
RAG is one workload. The final lesson widens the view to evaluating LLM applications and agents as a whole: offline and online evaluation, golden sets, task success, tool-call accuracy, deterministic assertions, model-based evaluation concepts, human review, red-teaming and regression gates for controlled release.
Sources
- Es et al., RAGAS: Automated Evaluation of Retrieval Augmented Generation (2023): https://arxiv.org/abs/2309.15217
- Ragas documentation (one open-source toolkit; metric names and APIs change between versions, so check the docs for your pinned version): https://docs.ragas.io/
- Thakur et al., BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models (2021): https://arxiv.org/abs/2104.08663
- Zheng et al., Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (2023): https://arxiv.org/abs/2306.05685
- Manning, Raghavan and Schütze, Introduction to Information Retrieval, chapter on evaluation (precision, recall): https://nlp.stanford.edu/IR-book/
- Python 3 standard library
collections: https://docs.python.org/3/library/collections.html (example tested with Python 3.11+, standard library only)
Northline Consumer Goods, article identifiers, case counts and scores are illustrative teaching data, not benchmark results.