Applied AI SystemsVol. 14B · Part XIV
0 / 0

Shelves / Applied AI Systems

AS·162

RAG Evaluation

Measuring a RAG system part by part so you know what to fix: why end-to-end impressions mislead, building a golden dataset (real queries, reference answers, relevant-source labels, synthetic question generation and its pitfalls), retrieval metrics (recall@k, precision@k, hit rate, MRR, NDCG, context relevance) computed from labelled ids, generation metrics (faithfulness and groundedness via claim decomposition, answer relevance, completeness against key facts, correctness, citation precision and recall), LLM-as-judge design with rubrics, calibration against humans and bias controls, deterministic checks, abstention quality, latency and cost, component ablations, regression testing in CI, online signals and A/B tests, and tools such as Ragas, DeepEval, TruLens, promptfoo and Phoenix, with a complete evaluation harness.

24 topics · ~16 min read · 29-question quiz
Updated Suggest a correction

Start here: how do you know your RAG system is good?

Trying ten questions and liking the answers isn't evidence. A RAG system has separate parts that fail separately, so you test each part against a fixed list of questions with known answers: a golden set.

Test the parts, then the whole

Part Question you ask Typical metric
retrieval did the right passage come back in the top k? recall@k, MRR
generation does the answer stick to the passages it was given? faithfulness
the whole is the answer correct and useful? correctness against a reference, human rating
refusal does it say "I don't know" when the answer isn't there? correct-refusal rate, false-refusal rate

If the right passage never comes back, no model can answer correctly: fix retrieval first.

A worked example of the two most common metrics

Three questions; the rank at which the correct passage appeared was 1, 3 and "not in top 5":

Text
recall@5 = 2 found / 3 questions           = 0.67
MRR      = (1/1 + 1/3 + 0) / 3             = 0.44

Recall@k asks "was it there at all?"; MRR (mean reciprocal rank) also rewards putting it near the top.

Two traps the lab measured

  • Small golden sets wobble. With only 30 questions, the same system scored anywhere from 0.63 to 0.90 depending on which 30 were chosen. With 300 the range was 0.73–0.81. Report a confidence interval.
  • Questions copied from the documents are too easy. Sentences lifted from the passages scored recall@5 of 0.985; real-style questions scored 0.77. Synthetic questions must be rephrased the way users actually ask.

How deep to go in RAG evaluation

Volume 17 defines six mastery levels; for RAG evaluation they look like this:

Level You can…
L1 explain golden sets, recall@k, MRR and faithfulness
L2 build a golden set and compute retrieval metrics for a RAG app
L3 explain NDCG, LLM-as-judge methods and their biases, and confidence intervals
L4 diagnose failures with component ablations and per-question error analysis
L5 design an evaluation programme: offline sets, CI gates, online signals, human review
L6 run evaluation as a platform across teams, with versioned datasets and dashboards

Evaluate the parts, not just the whole

A RAG answer can fail because the right document was never retrieved, because it was retrieved but ranked too low to make the context, or because the model ignored or misused good context. One end-to-end "looks good / looks bad" judgment can't tell these apart. The roadmap's rule: evaluate retrieval and generation separately, then end to end.

question retriever context generator answer retrieval: recall@k · precision@kMRR · NDCG · vs gold ids faithfulness · groundedness · citations answer relevance · completeness · correctness (vs question + reference) latency · costabstention
Where RAG evaluation looks. Retrieval metrics compare retrieved chunk ids against labelled relevant ids. Generation metrics compare the answer against the retrieved context (faithfulness, citations) and against the question and a reference answer (relevance, completeness, correctness). End-to-end metrics and operational metrics such as latency and cost sit on top.

The golden dataset

Everything starts with a labelled evaluation set. Each item:

Field Purpose
question Realistic user phrasing, including vague, multi-part and follow-up questions
reference_answer What a good answer says (or key facts it must contain)
relevant_ids Document/chunk ids that contain the needed evidence (graded relevance optional)
metadata Category, difficulty, user role/tenant, language, whether answerable

How to build it:

  1. Mine real queries from logs, support tickets, search analytics, interviews with users. Real phrasing beats invented phrasing.
  2. Expert labelling: subject-matter experts write reference answers and mark sources.
  3. Synthetic generation to broaden coverage: an LLM reads a chunk and writes questions it answers (then a reference answer). Cheap and scalable, but synthetic questions tend to reuse the chunk's exact words (making retrieval look too easy) and miss real user intent. Filter, paraphrase, and mix with real queries; have humans review a sample.
  4. Include unanswerable questions (the corpus lacks the answer) to test abstention, and adversarial ones (prompt injection in documents, misleading premises).
  5. Size: 50–100 well-chosen items catch major regressions; a few hundred give tighter confidence intervals (chapter 147); stratify by category.
  6. Version it with the corpus snapshot; when documents change, relevant ids and answers can change too.

Retrieval metrics

With labelled relevant ids (chapter 149's ranking metrics):

Metric Question it answers
Recall@k Did the top k contain the needed evidence? The single most important retrieval metric for RAG: missing evidence can't be recovered downstream
Precision@k How much of the top k is relevant? Low precision wastes context and distracts the model
Hit rate@k Was at least one relevant chunk in the top k?
MRR How high is the first relevant result?
NDCG@k Ranking quality with graded relevance and position discount
Context relevance (judge-based) When ids aren't labelled, does an LLM judge rate each retrieved chunk relevant to the question?

Measure at the k you actually pass to the generator (after reranking), and also at the larger candidate pool (before reranking) to see whether the reranker or the first-stage retriever is the bottleneck.

Generation metrics

Metric Definition How to measure
Faithfulness / groundedness Every claim in the answer is supported by the retrieved context Decompose the answer into atomic claims; check each against the context (NLI model or LLM judge); score = supported / total
Answer relevance The answer addresses the question asked Judge rating; or generate questions from the answer and compare to the original
Completeness The answer covers the key facts needed Check each key fact from the reference answer is present
Correctness The answer agrees with the reference Judge comparison with the reference; exact match for short factual answers
Citation precision Cited sources actually support the sentences citing them Check each (sentence, cited chunk) pair
Citation recall Claims that need support carry citations Fraction of claims with a supporting citation
Abstention quality Says "I don't know" when evidence is missing; doesn't refuse when it's present Measure on unanswerable vs answerable subsets

Faithfulness ≠ correctness: an answer can faithfully repeat an outdated document (faithful, wrong), or be correct from the model's prior knowledge but unsupported by context (correct, unfaithful: risky, because the next unsupported answer may be wrong). For grounded assistants, require both.

answer: "API keys must be rotated every 90 days and are created in theDeveloper Portal. Revoked keys stop working immediately." rotated every 90 days✓ supported by S1 created in Dev Portal✓ supported by S1 stop "immediately"✗ S1: within 5 minutes faithfulness = 2 / 3 = 0.67
Claim-level faithfulness checking. The answer is split into atomic claims, and each claim is checked against the retrieved context as supported, contradicted or not found. The faithfulness score is the fraction supported; unsupported claims pinpoint hallucinations.

LLM-as-judge

Many generation metrics need judgment. LLM judges scale this, if designed carefully:

  • One criterion per judge call, with a clear rubric and definitions (what counts as "supported"?).
  • Prefer binary or small ordinal scales with anchored descriptions over 1–10 scores.
  • Ask for evidence first, verdict last (quote the supporting text, then decide), in structured output (chapter 167).
  • Pairwise comparison (A vs B) is more reliable than absolute scoring for comparing systems; swap positions and average to cancel position bias.
  • Known biases: position, verbosity (longer seems better), self-preference (judging its own family's outputs favourably), sensitivity to formatting. Use a different, strong model as judge when possible.
  • Calibrate against humans: have experts label 50–100 items; measure judge–human agreement (accuracy, Cohen's kappa, chapter 150); iterate on the rubric until agreement is acceptable; re-check when you change judge models.
  • Record judge model, prompt version and temperature (0) with every score.
Python
FAITHFULNESS_JUDGE = """You check whether a claim is supported by source passages.

<sources>
{sources}
</sources>

<claim>{claim}</claim>

Definitions:
- SUPPORTED: the sources state or directly imply the claim.
- CONTRADICTED: the sources state something incompatible with the claim.
- NOT_FOUND: the sources neither support nor contradict it.

First quote the most relevant source sentence (or "none"), then give the verdict.
Respond as JSON: {{"evidence": "...", "verdict": "SUPPORTED" | "CONTRADICTED" | "NOT_FOUND"}}"""

Deterministic checks

Not everything needs a judge. Cheap, reliable checks:

  • Citation format and validity: every cited id exists in the provided context; no citations to sources that weren't given.
  • Key-fact presence: regex or normalised string match for required facts (numbers, names, dates).
  • Format: valid JSON/schema, length limits, required sections, language.
  • Refusal detection for unanswerable items (phrases or a small classifier).
  • Forbidden content: no leaked system prompt, no PII, no raw document dumps.

An evaluation harness

Python
import json, re, statistics
from dataclasses import dataclass, field

@dataclass
class EvalItem:
    question: str
    relevant_ids: set
    key_facts: list = field(default_factory=list)       # normalised strings that must appear
    answerable: bool = True

def recall_at_k(retrieved, relevant, k): return len(set(retrieved[:k]) & relevant) / max(len(relevant), 1)
def precision_at_k(retrieved, relevant, k): return len(set(retrieved[:k]) & relevant) / k
def reciprocal_rank(retrieved, relevant):
    return next((1 / r for r, d in enumerate(retrieved, 1) if d in relevant), 0.0)

def citations_valid(answer, provided_ids):
    cited = set(re.findall(r"\[S(\d+)\]", answer))
    return all(1 <= int(c) <= len(provided_ids) for c in cited), cited

def fact_coverage(answer, facts):
    norm = lambda s: re.sub(r"\s+", " ", s.lower())
    return sum(norm(f) in norm(answer) for f in facts) / max(len(facts), 1)

REFUSAL = re.compile(r"\b(don't know|do not know|not (?:in|covered by) the sources|cannot find)\b", re.I)

def evaluate(items, rag, judge_claims=None, k=3):
    rows = []
    for it in items:
        retrieved_ids, answer = rag(it.question)              # system under test
        valid, cited = citations_valid(answer, retrieved_ids[:k])
        row = {"q": it.question,
               "recall@k": recall_at_k(retrieved_ids, it.relevant_ids, k) if it.answerable else None,
               "precision@k": precision_at_k(retrieved_ids, it.relevant_ids, k) if it.answerable else None,
               "rr": reciprocal_rank(retrieved_ids, it.relevant_ids) if it.answerable else None,
               "citations_valid": valid,
               "fact_coverage": fact_coverage(answer, it.key_facts) if it.answerable else None,
               "abstained": bool(REFUSAL.search(answer)),
               "should_abstain": not it.answerable}
        if judge_claims:                                       # optional LLM-judge faithfulness
            row["faithfulness"] = judge_claims(answer, retrieved_ids[:k])
        rows.append(row)
    mean = lambda key: statistics.mean(r[key] for r in rows if r[key] is not None)
    answerable = [r for r in rows if not r["should_abstain"]]; unanswerable = [r for r in rows if r["should_abstain"]]
    summary = {"recall@k": mean("recall@k"), "precision@k": mean("precision@k"), "MRR": mean("rr"),
               "fact_coverage": mean("fact_coverage"),
               "citations_valid": statistics.mean(r["citations_valid"] for r in rows),
               "false_refusals": statistics.mean(r["abstained"] for r in answerable) if answerable else 0,
               "correct_abstentions": statistics.mean(r["abstained"] for r in unanswerable) if unanswerable else None}
    return summary, rows

# A stub system: in practice `rag` calls your retriever and LLM
def fake_rag(q):
    if "rotate" in q: return ["security-policy#1", "expenses#1", "security-policy#0"], "API keys must be rotated every 90 days [S1]."
    if "locked" in q: return ["it-support#0", "security-policy#0"], "Your account unlocks after 15 minutes [S1]."
    return ["expenses#0", "security-policy#0"], "I don't know: the sources don't cover parking."

items = [EvalItem("How often must I rotate API keys?", {"security-policy#1"}, ["90 days"]),
         EvalItem("I'm locked out, how long until I can retry?", {"it-support#0"}, ["15 minutes"]),
         EvalItem("Where do employees park?", set(), answerable=False)]
summary, rows = evaluate(items, fake_rag)
summary     # {'recall@k': 1.0, 'precision@k': 0.33, 'MRR': 1.0, 'fact_coverage': 1.0, 'citations_valid': 1.0, ...}

Component ablations and diagnosis

Use the per-stage metrics to localise problems and test changes one at a time:

Experiment Hold fixed Vary Watch
Chunk size / overlap Everything else 256 / 512 / 1024 tokens Recall@k, faithfulness, cost
Embedding model Chunks Model A vs B (re-embed) Recall@k, NDCG
Hybrid vs dense Model + BM25 + RRF Recall on identifier-heavy questions
Reranker Retrieval pool none / cross-encoder / LLM Precision@k, faithfulness, latency
k passed to LLM Ranking 3 / 5 / 10 Completeness vs faithfulness and cost
Prompt Context Instruction variants Faithfulness, citation validity, abstention
Generator model Prompt and context Model A vs B Correctness, cost, latency

Oracle tests isolate generation: give the generator the gold relevant chunks directly. If answers are still poor, the problem is the prompt or model; if they're good, the problem is retrieval.

Report results with confidence intervals (bootstrap over questions) and paired comparisons between variants on the same questions (chapter 147).

Regression testing and CI

  • Run the evaluation suite on every change to prompts, chunking, models, retrieval parameters or ingestion code, like unit tests (chapter 175).
  • Set thresholds (e.g. recall@5 ≥ 0.9, faithfulness ≥ 0.95, false refusals ≤ 5%) and fail builds on significant regressions.
  • Keep a hard-case set of past failures; every fixed bug becomes a test.
  • Cache LLM calls for unchanged inputs to keep CI fast and cheap; sample-based judge evaluations nightly.

Online evaluation

Offline sets never cover everything. In production, collect:

  • Explicit feedback: thumbs up/down, "was this helpful", corrections; biased toward extremes but valuable.
  • Implicit signals: follow-up rephrasing (the answer didn't help), copying the answer, clicking citations, escalation to human support, session abandonment.
  • Sampled judge evaluations on live traffic (faithfulness, relevance) with dashboards and alerts (chapter 177).
  • A/B tests for significant changes, with guardrail metrics (latency, cost, refusal rate).
  • Drift monitoring: new topics in queries without good retrieval results signal corpus gaps.

Feed failures back into the golden set: the evaluation set should grow with the product.

Tools

Tool Notes
Ragas RAG metrics (faithfulness, answer relevancy, context precision/recall), synthetic test-set generation
DeepEval Pytest-style LLM evaluation with many metrics, CI integration
TruLens "RAG triad" (context relevance, groundedness, answer relevance) with tracing
promptfoo Config-driven prompt/model comparisons and assertions, red-teaming, CI
Arize Phoenix, Langfuse, LangSmith, Braintrust, MLflow GenAI eval Tracing + datasets + experiments + judges
BEIR / MTEB retrieval tasks Public retrieval benchmarks for model selection

Tools speed things up, but the core asset is your labelled dataset and rubric; metric names differ across tools, so read their definitions.

Lab: evaluating retrieval honestly

Setup. The corpus and golden set from chapters 159 and 161: 4,251 heading-aware chunks of Volumes 1–14 and 879 glossary definitions as questions, each labelled with the chapter it belongs to. Metrics are computed at chapter level over the top 10 distinct chapters; confidence intervals come from 2,000 bootstrap resamples of the questions. There's no generator, so this lab covers retrieval and answerability, which is where most RAG failures start; the harness in this chapter shows how to add generation metrics.

Experiment 1: three retrievers, with error bars

System R@1 R@5 MRR nDCG@10
BM25 0.463 [0.430, 0.496] 0.771 [0.744, 0.799] 0.595 [0.569, 0.619] 0.660 [0.635, 0.684]
LSA 256-d 0.378 [0.347, 0.408] 0.737 [0.709, 0.767] 0.527 [0.501, 0.555] 0.603 [0.579, 0.627]
hybrid (RRF) 0.448 [0.416, 0.480] 0.797 [0.769, 0.823] 0.590 [0.563, 0.616] 0.657 [0.633, 0.679]

The intervals for hybrid and BM25 overlap, which might suggest "no difference". The right test is paired: on the same questions, compare the two systems' results question by question.

Paired R@5 difference Mean [95% CI] Questions won / lost
hybrid − BM25 +0.026 [+0.005, +0.047] 59 / 36
BM25 − LSA +0.034 [+0.005, +0.061] 95 / 65

Both differences are real but small; and the hybrid's gain at rank 5 came with a slight loss at rank 1, so which is "better" depends on how many chunks your prompt uses. The per-question wins and losses are where to look next: read the 36 questions the hybrid lost.

Experiment 2: how big must the golden set be?

BM25 recall@5 over 500 random subsets of the 879 questions (middle 95% of results):

Questions Range
30 0.633 – 0.900
100 0.695 – 0.840
300 0.733 – 0.810

With 30 questions you can't distinguish a system at 0.70 from one at 0.85, let alone detect the 0.026 improvement above. A few hundred well-chosen questions is the practical minimum for retrieval decisions, more for subgroups (per language, per document type).

Experiment 3: the synthetic-question trap

274 "questions" made by copying a sentence from a random chunk scored BM25 recall@5 of 0.985, versus 0.771 for the glossary definitions, which are written in different words from the text. LLM-generated golden sets have a milder form of the same bias: generated questions borrow the passage's vocabulary. Ask the generator to paraphrase, to write as a user without access to the document, and mix in real user queries as soon as you have them.

Experiment 4: can retrieval scores tell you when to say "I don't know"?

The index was rebuilt without the security volume, so its 43 glossary questions became unanswerable; the other 836 stayed answerable. The signal was BM25's top score divided by the number of distinct query words:

Threshold Unanswerable correctly refused Answerable wrongly refused
2.00 0.26 0.09
2.41 0.47 0.29
2.81 0.60 0.49

Mean scores were 3.04 (answerable) vs 2.71 (unanswerable); AUC 0.615, barely better than chance. Security terms (TLS, hashing, tokens) appear throughout the other volumes, so "unanswerable" questions still found plausible passages. Retrieval scores alone are a weak refusal signal; production systems add a check by the generator ("do these sources answer the question?"), measured on a labelled set exactly like this one.

Try it yourself

  1. Read 20 questions the hybrid lost to BM25 and classify the cause (identifier, rare term, chunking, label error).
  2. Add a generator and score faithfulness with an LLM judge on 100 questions; check the judge against your own labels on 30.
  3. Build a CI job that fails if R@5 drops by more than the lower bound of a paired interval.
  4. Replace the answerability signal with a reranker score and remeasure the table in Experiment 4.

Revision sheet: RAG evaluation

Key ideas

  • Evaluate retrieval, generation and end-to-end separately, plus refusal behaviour.
  • Golden set: real queries where possible, reference answers, relevant-source labels, unanswerable cases, coverage of important slices; version it.
  • Retrieval metrics: recall@k, precision@k, hit rate, MRR, nDCG (graded relevance).
  • Generation metrics: faithfulness/groundedness, answer relevance, correctness vs reference, citation accuracy.
  • LLM-as-judge: scalable but biased (position, verbosity, self-preference); use rubrics, pairwise comparisons with swapped order, and calibrate against human labels.
  • Deterministic checks first: citations exist and point to retrieved chunks, format, forbidden content, refusals.
  • Compare systems with paired differences and confidence intervals; inspect per-question wins and losses.
  • Online: thumbs up/down, follow-up rate, escalations, citation clicks; feed failures back into the golden set.

Numbers to remember

  • Lab: hybrid − BM25 R@5 = +0.026 [+0.005, +0.047], paired.
  • Lab: 30-question sets ranged 0.63–0.90; 300-question sets 0.73–0.81.
  • Lab: copied-sentence queries 0.985 vs real-style 0.771.
  • Lab: retrieval score as refusal signal AUC 0.615.

Pitfalls

  • Too few questions, no confidence intervals.
  • Synthetic questions that copy document wording.
  • Trusting an LLM judge without checking it against humans.
  • Only measuring end-to-end, so failures can't be located.
  • Never testing unanswerable or permission-restricted questions.

Glossary

  • Golden set: versioned evaluation questions with labels.
  • MRR: mean of 1/rank of the first relevant result.
  • nDCG: discounted cumulative gain normalised by the ideal ranking.
  • Faithfulness: support of each claim by the provided context.
  • Paired bootstrap: resampling questions to get an interval on a difference between systems.