Rana Maninder Singh
Lesson 5 of 12Advanced AI Engineering & LLMOps

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

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

PrerequisiteWhy it matters
Enterprise RAG ArchitecturePipeline stages, metadata, authority and access rules that evaluation will test.
Evaluation & Safety basicsIntroduces test sets and simple checks.
RAG basicsChunk, embed and retrieve.
Evaluation & Testing (agent course)Evaluation pyramid and regression testing.
Statistics basicsAverages, proportions and why small samples mislead.
Monitoring and drift for MLMonitoring 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?

Generation metrics ask: given the evidence, was the answer good?

Special question types need their own tests:

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:

CategoryTypical causeTypical fix
Ingestion/parse errorTable columns merged, text missingParser fix, parse validation
Chunking problemAnswer split across chunks, no heading contextStructure-aware chunking, add context prefix
Retrieval missRight document never retrievedHybrid search, query handling, metadata
Ranking problemRight chunk retrieved but lowReranking, authority ordering
Stale or wrong-version sourceSuperseded document returnedStatus filters, supersession process
Access errorRestricted chunk retrieved, or allowed chunk missingACL logic and sync
Context assemblyEvidence truncated or buriedBudget, ordering, de-duplication
Ungrounded generationClaims not in evidencePrompt, validator, refusal rule
Wrong citationCited passage does not support claimCitation validation
False refusalEvidence existed but system refusedThreshold tuning
Answered unanswerableSystem invented an answerRefusal threshold, relevance gate
Incomplete answerKey point missingContext 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.

  1. Business owner. The Service Desk Manager owns quality targets; the knowledge-base owner owns article accuracy.
  2. Approved users. Employees via SSO. Evaluation runs use test accounts that mirror different permission groups.
  3. 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.
  4. Permissions. Include test questions that require restricted content from accounts that lack it, to confirm neutral refusal.
  5. 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.
  6. Validation of the dataset. Two reviewers label a subset; disagreements are resolved by the owner. A labelling guide defines "relevant," "supported" and "complete."
  7. 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).
  8. Classify failures. Tag every failed case with one taxonomy category and look at counts by category and by slice.
  9. Human review. The owner reviews the top failing categories and a random sample of passing cases to check the scorer is not wrong.
  10. Plan fixes. Rank categories by frequency and business impact; assign one experiment per fix with a success threshold.
  11. Escalation. Any case showing restricted content in an answer is escalated to security immediately, regardless of overall scores.
  12. 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.
  13. 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:

  1. What kind of test case catches stale citations?
  2. Which metric flags the problem, and which taxonomy category applies?
  3. What are two candidate fixes at different pipeline stages?
  4. How do you check the fix did not break other slices?
  5. What is the stop condition for release?

Complete solution:

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

Common mistakes

  1. Scoring only the final answer, so retrieval problems hide behind fluent text.
  2. Evaluating on a handful of friendly questions chosen by the builder.
  3. Reporting recall without labels, or claiming "high recall" because the system returned results.
  4. Ignoring unanswerable, conflicting, stale and permission-limited questions.
  5. Using synthetic questions only; they are usually easier and more literal than real ones.
  6. Copying test questions into prompts or fine-tuning data so the test measures memory, not quality.
  7. Changing several variables at once and attributing the result to one of them.
  8. Looking only at averages and missing a failing slice.
  9. Treating a model-based judge as truth without checking it against human labels.
  10. Replacing the model when the failure lies in chunking, retrieval or sources.
  11. Declaring victory on a difference of one or two cases in a small dataset.

Quick check

  1. Why can answers be fluent and grounded yet irrelevant?
  2. What labels are needed to compute recall at k?
  3. Name two question types, besides normal answerable questions, that an evaluation set should contain.
  4. Why compare variants per case rather than only by average?
  5. What does a failure taxonomy let a team do?

Answers:

  1. 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.
  2. For each test question, the documents or chunks that contain the answer must be marked as relevant (gold labels).
  3. Any two of: unanswerable, conflicting sources, stale or superseded sources, permission-limited questions.
  4. Paired comparison shows which cases improved or regressed and exposes slice regressions that an average can hide.
  5. 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

Northline Consumer Goods, article identifiers, case counts and scores are illustrative teaching data, not benchmark results.