07.9 Evaluating RAG
A RAG system has two places to be wrong: it can retrieve the wrong chunks, or it can read the right chunks and still write a bad answer. Module 06 taught you to measure the first half with a labelled query set and rank metrics; this lesson measures the second half — and, crucially, the interaction between them, because a perfect retriever feeding a sloppy generator produces confident nonsense, and a mediocre retriever feeding a careful one produces honest "I don't know"s. You will learn the metric families that define "good RAG" (context relevance, faithfulness, answer relevance, answer correctness, citation accuracy, abstention), how to build an evaluation set that survives contact with production, how LLM-as-judge works and where it lies to you, which off-the-shelf tools exist as of November 2026 (and which have been sunset), how to design ablation experiments honestly, and how to turn production failures back into test cases.
What you'll learn
- The two-stage view of RAG evaluation: retrieval metrics (owned by 06.10) versus generation metrics, and why you must measure both
- A short definition of every generation-side metric family: context precision/recall, faithfulness/groundedness, answer relevance, answer correctness, citation precision/recall, abstention accuracy, safety, latency and cost. The full treatment of each is 10A.6, Part 3
- The RAG eval case schema the harness loads, with short summaries of how to build a RAG eval set (reference answers and gold chunks, unanswerable and adversarial cases, versioning and the dev/test discipline); the full treatment is 10A.6, Part 4 and 10A.2
- LLM-as-judge for RAG: what each judge must see, the answer relevance and correctness prompts, two-stage claim checking, calibrating a judge with Cohen's kappa, and keeping judge costs sane; the general methodology is 10A.4 and 10A.5
- The tools landscape as of November 2026 in brief (the full treatment is 10A.6, Part 7 and 10A.10), including that OpenAI's Evals platform has been shut down, and the public benchmarks/taxonomies worth knowing (RGB, CRUD-RAG, RAGChecker, plus RAGTruth, ARES and the TREC RAG track)
- A complete from-scratch
docs_qa/eval/harness: dataset schema, runner, judges and report — stdlib-only core you can run today, model calls behind an injectable seam - Experiment design: ablations, CI regression gates and cost-aware evaluation in full; paired comparison with confidence intervals and evaluating ingestion changes in summary (10A.8 and 10A.6, Part 8 for more)
- Error analysis: a short version of the failure taxonomy and the "read 50 traces" routine, with the failure→fix mapping into 07.10; the full loop is 10A.6, Part 9
- Online evaluation: a summary of the RAG-specific signals, shadow traffic and drift; owned by 10A.9 and Module 11A
What you don't need
- API keys. The harness's core — dataset loading, deterministic metrics, the runner, the report — is pure Python standard library and runs on fixtures you write by hand. The judge and pipeline calls sit behind injectable functions with deterministic fakes; lesson 03.1, Part 12 covers a free local stand-in if you want real model calls.
- Retrieval metrics from scratch. 06.10 owns recall@k, MRR, nDCG, the qrels format and the retrieval harness; this lesson links to it constantly and extends the same machinery one level up.
- Judge design in depth. Module 10A owns general LLM-as-judge methodology, rubric design and statistical testing; this lesson teaches what a RAG judge must measure and the failure modes specific to judging grounded answers.
- Tracing/observability platforms. Module 11A owns those; we use the
Tracerecord from 07.1 as the unit of inspection.
Setup
The runnable parts of this lesson need only Python 3.11+ — no packages, no keys, no services. If you are building the module's docs_qa package across lessons, it lives in the same project folder the earlier module-07 lessons use; if you haven't created it yet:
uv init docs-qa --bare --python 3.13 && cd docs-qa
uv add pydantic openai anthropic google-genai python-dotenv
# or, without uv: pip install pydantic openai anthropic google-genai python-dotenvThese commands install the newest release of each package. The samples were checked against pydantic 2.x and the provider SDK majors named in 07.1's Setup as of November 2026; a newer major version may change names, so check the library's changelog if a call does not match.
The .env file (only needed for the optional real-model judge calls in Part 4):
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...What you must be able to do after this lesson#
- Evaluate retrieval and generation separately, and run the oracle-context test
- Choose the RAG metric that catches a given failure, such as faithfulness or context recall
- Write eval cases in the
docs_qa/evalschema, including unanswerable ones - Run the
docs_qa/evalharness and read its report - Use an LLM as judge and check the judge against human labels
- Run an ablation and read the result with a confidence interval
- Place a failing case in the failure taxonomy using set differences
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Our RAG answers sound great in demos but users complain." | Part 1 — demos test the happy path; evals test the distribution |
| "Is the retriever or the generator at fault?" | Part 1, Part 7 |
| "What's our faithfulness score?" | 2.2 Faithfulness and groundedness |
| "The judge gave it a 0.9 but the answer was wrong." | 4.5 Judge bias, variance and limits |
| "Do we need reference answers for every question?" | 3.2 Reference answers and gold chunks |
| "Ragas vs DeepEval vs LangSmith — which one?" | Part 5 |
| "OpenAI has an evals product, right?" | 5.3 What the providers offer (it was shut down on 30 November 2026) |
| "The eval said +2% but is that real?" | 6.2 Paired comparison and confidence intervals |
| "Every time we re-chunk, the eval breaks." | 3.4 Versioning and the dev/test discipline |
| "Users thumbs-down 3% of answers — is that good?" | Part 8 |
Part 1: The two-stage view#
1.1 One pipeline, two failure domains#
A single-turn RAG request crosses two quality boundaries:
flowchart LR
Q["user question"] --> RQ["query understanding<br/>(07.3)"]
RQ --> RET["retrieval + rerank<br/>(07.2, Module 06)"]
RET --> CA["context assembly<br/>(07.4)"]
CA --> GEN["grounded generation<br/>(07.4)"]
GEN --> CITE["citations<br/>(07.5)"]
CITE --> ANS["answer"]
subgraph stage1 ["Stage 1 — retrieval quality"]
RET
CA
end
subgraph stage2 ["Stage 2 — generation quality"]
GEN
CITE
ANS
end- Stage 1 (retrieval) decides what the model gets to see. Its metrics — recall@k, MRR, nDCG — are deterministic, cheap and need no judge when labelled qrels exist; the claims-scored context precision/recall of 2.9 are the judged exception. 06.10 owns the deterministic family completely; its harness scores
Retriever.search()outputs against qrels. - Stage 2 (generation) decides what the model does with what it sees. Its metrics — faithfulness, answer relevance, correctness, citation accuracy, abstention — almost always need an LLM judge or human labels, because "is this answer good?" has no closed-form computation.
The crucial engineering fact: stage 2 can only be as good as stage 1 allows. If the chunk containing the answer never reaches the context window, no prompt and no judge will save the answer. Conversely, perfect retrieval cannot fix a generator that ignores instructions or cites wrongly. This is why evaluation is staged: measure retrieval alone (cheap, every commit), measure generation on top of fixed retrieved contexts (so generator changes are isolated), and measure end-to-end only for the headline numbers.
1.2 The three levels of RAG evaluation#
06.10, 1.2 drew the same picture for retrieval alone. RAG adds the generation stage, giving four practical levels. (10A.6, 1.4 re-bases these labels as L0–L4, so check which scheme a section uses before quoting a level number.)
| Level | What you vary | What you measure | Cost per case | When to run |
|---|---|---|---|---|
| L0 — retrieval only | retriever config, k, filters, reranker | recall@k, MRR, nDCG on qrels | ~free (no LLM) | Every commit, every sweep |
| L1 — retrieval + fixed context | context assembly, grounding prompt, generator model | faithfulness, answer relevance on frozen retrieved contexts | one generation call (+ judges) | Prompt/model changes |
| L2 — end-to-end | the whole pipeline: query rewrite, retrieval, assembly, generation, citations | all metrics, per-type breakdowns | retrieval + generation + judges | Milestones, releases, regression gates |
| L3 — online | live traffic | thumbs, implicit signals, A/B metrics | production cost | Continuously (Part 8) |
L1 deserves emphasis because it is the cheapest way to isolate the generator: freeze the retrieved contexts (save the exact Context object from 07.1 per case), then swap prompts and models against identical inputs. Any metric movement is attributable to generation alone. This is the RAG analogue of the "replay the exact request" technique in 03.10, Part 5.
1.3 The oracle test: is retrieval even the problem?#
The full treatment, with oracle query, oracle retrieval and oracle assembly run as experiments over the whole eval set, is 10A.6, Part 2.
Before building any generation eval, run the oracle-context test from 07.1: for each eval case, bypass retrieval entirely and hand the generator the gold chunk(s) — the ones your labels say contain the answer. Then measure generation metrics on those answers.
- If oracle-context answers are still bad, the bottleneck is generation (prompt, model, abstention logic) — don't burn effort tuning the retriever.
- If oracle-context answers are good but end-to-end answers are bad, retrieval (or context assembly) is the bottleneck — the eval set's retrieval metrics will show where.
This single experiment prevents the most common RAG eval mistake: tuning the retriever when the generator was the problem, or rewriting prompts when the right chunk never arrived. Run it once per major change, not per commit.
Part 2: The metric families#
This part gives each generation-side metric a short definition, enough to read the harness and its report in 5.4. The full treatment of each metric (the procedures, the implementation choices, the pitfalls) is 10A.6, Part 3, which you will meet later in the path, in Module 10A. Retrieval-side metrics (recall@k and friends) are in 06.10, Part 3: link there rather than re-deriving them.
2.1 The RAG triad and its neighbours#
The term RAG triad comes from TruLens's evals documentation: three judge-scored dimensions — context relevance (did we retrieve the right stuff), groundedness/faithfulness (is the answer supported by it), and answer relevance (does it address the question). Ragas's four canonical metrics (Es et al., 2023) map onto the same idea. The full family used in this lesson:
| Metric family | Question it answers | Needs | Deterministic? | Catches |
|---|---|---|---|---|
| Context precision / recall (2.9) | Was the right context retrieved and kept, and ranked well? | qrels, reference answer or response | Id/qrels variants deterministic; claims-scored variants need a judge | retrieval miss, ranking quality, context-assembly loss |
| Faithfulness / groundedness | Is every claim in the answer supported by the context? | retrieved contexts | No — judge or NLI model | hallucination, parametric leakage, mis-synthesis |
| Answer relevance | Does the answer address what was asked? | question + answer | No — judge or embedding procedure | dodging the question, over-answering, wrong specificity |
| Answer correctness | Is the answer right? | reference answer or expected facts | Partly (exact match); usually judge | factual errors the context can't reveal |
| Citation precision / recall | Are citations present, correct and sufficient? | answer + citations + context | String checks yes; entailment needs judge | invented ids, unsupported claims, citation drift |
| Abstention accuracy | Did it refuse exactly when it should? | expect_abstain labels |
Yes — pure logic | over-answering unanswerables, over-abstaining answerables |
| Safety / refusal | Did it handle adversarial input safely? | adversarial cases | Judge + rules | injection compliance, harmful compliance (Module 12) |
| Latency / cost | Is it fast and cheap enough? | traces | Yes | p95 regressions, token bloat |
Two framing rules before the details:
- Faithfulness ≠ correctness. A perfectly faithful answer can be wrong (the retrieved chunk itself was wrong or outdated), and a correct answer can be unfaithful (right fact, unsupported citation path). Measure both; never substitute one for the other. This mirrors the glossary's factuality vs faithfulness distinction (02.10).
- Relevance ≠ correctness. An answer can be fluent, on-topic, well-cited and still factually wrong. "Answer relevance" metrics measure addressing the question; only correctness metrics (or humans) measure being right.
The same family, laid out by pipeline component (which stage each metric can see), is the evaluation matrix in 10A.6, 1.2.
2.2 Faithfulness and groundedness#
Definition. Faithfulness (Ragas's name; TruLens calls it groundedness) is the fraction of the answer's claims that are supported by the retrieved context:
faithfulness = (# claims in the answer supported by the retrieved context)
/ (# claims in the answer)The procedure has two steps. Claim extraction breaks the answer into atomic, verifiable statements ("employees accrue 1.5 vacation days per month, capped at 18 days yearly, and sick leave is separate at 10 days" is three claims, not one). Claim verification decides, for each claim, whether the retrieved context entails it: the context asserts it or it follows necessarily, which is stricter than "consistent with" or "true in the real world". Claim-level scoring gives an audit trail (the failing claims are your debugging gold; 07.10 uses them directly) and a score that degrades gracefully (3/4 supported = 0.75, not "unfaithful"). The harness scores it with a judge: the prompts are in 4.2 and the two-stage option is in 4.3.
You will meet the full treatment in 10A.6, 3.1: the granularity and verifier choices (string match, NLI model, LLM judge), the three-verdict vocabulary, a production-shaped judge prompt, and why the judge must see the post-assembly context. Three pitfalls to carry with you now:
- Numbers and dates are where judges fail. "18 days" vs "8 days" is a one-token difference that flips entailment; always include numeric claims in your human calibration sample (4.4).
- Hedged answers game the metric. "It might be the case that perhaps the policy could possibly allow..." contains few checkable claims, so claim extraction yields little and the score looks fine. Pair faithfulness with answer relevance (2.3) so vagueness is penalised elsewhere.
- Multi-turn answers. For conversational RAG (07.6), "the context" is the union of chunks retrieved this turn, not last turn's. Decide and document which, per case.
2.3 Answer relevance#
Definition. Answer relevance asks: does the response address the user's question? It is independent of truth. There are two procedures. The reference-free embedding procedure (Ragas AnswerRelevancy) generates N artificial questions the answer could be replying to (default N=3), embeds them and the real question, and scores the mean cosine similarity; the intuition is that the question should be recoverable from the answer. A judge rubric (1–5, the prompt in 4.2) is simpler and lets you define what "address" means for your product. The harness uses the judge rubric. The full treatment is 10A.6, 3.2.
The pitfalls (verbosity bias, ignoring truth, the embedder's blind spots in weaker languages) are in the home section: in short, penalise padding in the rubric, and always read relevance next to faithfulness and correctness, because a fluent, on-topic, fabricated answer scores high. Evaluate per language, as 06.10, Part 9 advises for retrieval.
2.4 Answer correctness#
Definition. Correctness asks the hardest question: is the answer right? There are three practical procedures, in increasing order of cost and coverage: an exact or contains match for short canonical answers ("What is the per diem?" → expected contains "$75"), an expected-facts checklist for answers with enumerable facts (expected_facts = ["net-30", "12 months of fees"], checked by code or a judge), and a reference-answer judge for prose answers with one good reference, graded on equivalence of content, not similarity. The harness uses token-F1 and the expected-facts judge. The full treatment, including semantic-equivalence prompts, nugget recall, completeness and conciseness, is 10A.6, 3.3.
Three points to keep in mind:
- There is rarely one right answer. Grade properties ("states the rate is $75/day AND mentions receipts over $25"), not similarity to a reference; 4.2 shows the pattern.
- The self-grading loop. If the reference answers were themselves generated by an LLM (10A.2) and graded by an LLM judge, the generator's blind spots become the rubric. Human-review a sample of references before trusting correctness scores (10A.2, 11.6).
- Unanswerable cases have no correct answer. Score abstention separately (2.6) and exclude these cases from correctness averages, the same convention 06.10 uses for empty-expected queries. Tag cases with the corpus version they were labelled against, because freshness changes correctness over time (3.4).
2.5 Citation precision and recall#
Citations are covered in depth by 07.5, which owns the verification machinery (does the cited span exist, does it contain the quote, does it entail the claim?). The eval-level treatment is 10A.6, 3.4. At the metric level, the definitions you need here:
- Citation precision — of the claims that carry a citation, what fraction have a citation that actually supports them? Catches invented ids, cite-the-wrong-chunk, and decoration citations.
- Citation recall — of the claims that should be cited (factual claims drawn from context), what fraction have one? Catches uncited facts and claims smuggled in without attribution.
- Citation correctness (a third, stricter cut) — the cited span must entail the claim, checked by string match for verbatim quotes or an entailment judge for paraphrases.
The deterministic layer (does the cited id exist in the retrieved set, does the quoted text appear in that chunk) is cheap string and set work, and 07.5 has the code, so run it on every case. The entailment layer needs a judge: treat it as a sampled audit, not a per-commit gate. Pitfall specific to evals: citation metrics are meaningless if the answer is not machine-readable. Score citations on the structured Answer object from 07.1, never on rendered prose with [1] markers, or parsing bugs become fake citation failures.
2.6 Abstention accuracy#
Definition. Abstention accuracy measures whether the system refuses exactly when it should. The scoring convention matters enough to state precisely — this is the convention run_eval in Part 5 implements:
a case is abstention-scored iff abstention was in play:
expect_abstain=True OR the system abstained
abstention accuracy = correct abstain decisions / abstention-scored cases
where, within scored cases, "correct" means abstained == expected:
- expect_abstain=True and the system abstained -> correct_abstention
- expect_abstain=True and the system answered -> answered_unanswerable
- expect_abstain=False and the system abstained -> abstained_answerable
- expect_abstain=False and the system answered -> NOT SCOREDThe last row is the deliberate choice: an answerable case the system answers is scored by the correctness metrics (token-F1, judges), not by abstention — this metric measures the refuse/answer boundary, not answer quality. The convention's edge cases are worth stating: a set with no unanswerable cases and a system that never abstains produces no scored cases at all (the metric is undefined — the report shows —), while an always-answering system scores 0 on every unanswerable case, which is the damning result you want. If your tooling uses a different convention — e.g. scoring all cases — the two numbers are not comparable; fix the convention in one place, record it in the run's run_meta, and keep the Terms entry and the code comment saying the same thing.
A single accuracy number hides the trade-off that matters. Report the full 2×2 of outcome counts and the abstention curve: answer accuracy on answerable cases against abstention rate on unanswerable cases, as the abstention threshold (or the sufficiency-check strictness from 07.4) is swept. A system that rarely abstains on unanswerables hallucinates confidently on gaps, which is the dangerous failure; one that often abstains on answerables loses coverage. The full treatment, including the partial-answer third state and the insufficient-context probe, is 10A.6, 3.5, which you will meet later in the path.
Two pitfalls that bear on the harness:
- "I don't know" is not always abstention. A system that answers "Based on the handbook, X" when X isn't in the handbook has not abstained, even if it sounds cautious. Abstention must be a detectable output state (a flag, a refusal template, an empty answer), another reason to keep
Answer.abstainedstructured. A partial answer ("the handbook covers parental leave but not the contractor variant") is a third state: labelpartial_okper case (3.1). - Pipeline errors are not abstention decisions. A crashed case produced no answer to grade —
run_evalrecords it asabstention="pipeline_error"withabstention_correct=Nonerather than scoring it as a wrong answer or a wrong abstention, and it is never sent to the judge.
2.7 Safety and refusal#
For adversarial cases (prompt injection embedded in retrieved documents, false-premise questions such as "given that the per diem is $200, what's the total?", harmful requests) the metric is appropriate refusal or compliance. At eval level you need adversarial cases in the set, a pass/fail grader per case and a separate reporting line, so a safety regression can't hide inside an average faithfulness score. The measurement is covered in 10A.6, 3.5 (refusal appropriateness) and 10A.6, 4.5. Injection-through-retrieval is previewed in 07.4 and 07.8; the defences are Module 12's.
2.8 Latency, cost and tokens#
Non-negotiable companions to every quality number (full treatment: 10A.6, 3.7):
- Latency: p50/p95/p99 per case, split by stage if your
Tracerecords stage timings. 06.10, 3.9 makes the same argument for retrieval; generation adds decode time, which scales with answer length. - Cost per answer: query embedding + retrieval (+ rerank) + prompt tokens + completion tokens + judge tokens if judges run in the loop. Prices are parameters: look them up via 03.7, never hard-code them. The context-assembly lesson (07.4) is where token bloat usually enters.
- Token counts: record
usagefrom every call (02.2 owns token counting); they are the audit trail for cost surprises.
A quality gain that doubles cost per answer may be a bad trade — 6.4 formalises the comparison.
2.9 Context precision and recall#
The triad's first member — context relevance — splits into two directional metrics, and the naming is treacherous because "precision" and "recall" mean something subtly different here than in 06.10's rank metrics:
- Context precision asks: of the chunks that reached the context, which ones actually mattered, and were the important ones ranked first? Ragas's
ContextPrecisionhas an LLM judge each retrieved context against the reference and weights the verdicts by rank, which is exactly what a reranker is supposed to buy. The ID-based variant is essentially 06.10's qrels precision applied to the in-context set rather than the rawsearch()output. - Context recall asks the reverse question: of the information the reference answer depends on, how much actually reached the context? Ragas's
ContextRecalldecomposes the reference answer into claims and checks each for attribution to the retrieved contexts:context recall = claims attributable to context / total claims in reference. A case can have perfect precision and terrible recall (the one chunk carrying the answer never arrived): the signature of a too-small k or an over-aggressive assembly budget, and invisible to generation metrics because the generator faithfully reports the little it saw.
The exact Ragas class names, which API each one lives in (collections or legacy) and the dated version notes are in 10A.6, 3.6 and 10A.6, 7.2.
Two usage rules:
- Score the in-context set, not the retrieved set. Pass
context_chunk_ids(what entered the prompt), notretrieved_chunk_ids— a chunk retrieved-then-trimmed is an assembly failure, and scoring raw retrieval output would hide it. This is the same retrieved-vs-in-context distinction as 1.1 and the reasonCaseResultrecords both. - These are judged metrics unless you use the ID/non-LLM variants. Claims-based precision/recall inherit every judge failure mode in Part 4 — calibrate them like any other judge metric, and prefer the deterministic ID-based variant for per-commit CI gates.
2.10 Which metric catches which failure#
The lookup table you will actually use during error analysis (Part 7):
| Symptom in production | Metric that detects it | Stage at fault |
|---|---|---|
| Answer misses information the corpus has | context recall (claims-in-reference check) | retrieval or context assembly |
| Right facts, buried under junk chunks | context precision | retrieval ranking / assembly |
| Fluent answer with invented details | faithfulness | generation |
| Correct facts, doesn't answer the question | answer relevance | generation (prompt/model) |
| Right answer, wrong or missing citations | citation precision/recall | citation layer (07.5) |
| Confident answer to an unanswerable question | abstention accuracy (false-answer rate) | sufficiency check / abstention logic (07.4) |
| "I don't know" when the corpus answers | abstention accuracy (false-abstain rate) + context recall | threshold tuning |
| Follows injected instructions from a document | safety pass/fail | generation defences (Module 12) |
| Great offline scores, bad live reviews | online signals (Part 8) | eval-set coverage gap |
Part 3: Building the eval set#
A RAG eval set is a retrieval eval set (06.10, Part 2) plus the generation-side labels: a reference answer (or expected facts), a gold-chunk set, an abstention expectation, and sometimes a whole conversation. Most of the retrieval-side advice carries over unchanged — sources, leakage, sizing, stratification, versioning — so this part covers only what is new for generation, and flags the two places the requirements conflict. The full treatment of the RAG eval dataset is 10A.6, Part 4, with dataset mechanics in 10A.2, which you will meet later in the path. This part keeps the case schema the harness loads and short summaries of the rest.
3.1 The eval case schema#
The extended schema (nuggets, qtype) is 10A.6, 4.1; the field guide below is the one the harness loads.
One JSONL line per case — the format docs_qa/eval/dataset.py loads (Part 5):
{"case_id": "e01", "question": "How much paid vacation do full-time employees accrue?",
"split": "dev", "type": "factoid",
"reference_answer": "Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.",
"expected_facts": ["1.5 days per month", "18 days per year"],
"gold_chunk_ids": ["handbook-001"], "expect_abstain": false, "partial_ok": false,
"filters": {"tenant": "acme"}, "tags": ["policy"], "source": "hand-written", "notes": ""}Field-by-field:
| Field | Purpose | Notes |
|---|---|---|
case_id |
stable identity across versions | never reuse an id for a different question |
question |
the user input | for multi-turn cases see turns below |
split |
dev / test / calibration |
discipline in 3.4 |
type |
query-type stratum | factoid, howto, diagnostic, multi-hop, comparison, unanswerable, adversarial, multi-turn, freshness |
reference_answer |
one correct answer, for judge scoring | optional; its absence selects reference-free metrics |
expected_facts |
enumerable facts the answer must contain | cheaper and more robust than a full reference for factoid cases |
gold_chunk_ids |
chunks that should reach the context | drives context-recall scoring and retrieval diagnosis |
expect_abstain |
correct behaviour is refusal/"I don't know" | unanswerable cases |
partial_ok |
a partial answer is acceptable | ambiguous cases where the corpus is incomplete — informational today: the harness records the flag but does not score these cases differently; reserved for lenient correctness scoring |
filters |
ACL/tenant filters applied at retrieval | leak-check cases like 06.10's q16 |
turns |
prior conversation for multi-turn cases | list of {role, content} before question (07.6) |
source, notes, corpus_version |
provenance | where the case came from, known quirks, which corpus version the labels assume |
gold_chunk_ids vs 06.10's qrels relevant map: keep both if you can. relevant (graded 1/2) serves retrieval metrics; gold_chunk_ids serves the stricter question "did the answer-bearing chunk reach the prompt". Where they diverge — helpful-but-not-sufficient context, like ticket-77 in 06.10's q05 — the divergence is exactly the diagnostic signal you want.
3.2 Reference answers and gold chunks#
Reference answers are the single most expensive and most abused artefact in a RAG eval set. The rules, in short (the full version is 10A.6, 4.4):
- Write them from the corpus, not from memory. The reference must be derivable from the gold chunks, or "correctness" penalises the system for faithfully reporting only what was retrieved.
- Prefer
expected_factsover prose references where you can. "Must contain: net-30, liability cap = 12 months of fees" is robust to paraphrase; use prose references for procedure and comparison questions. - One reference is a sample, not the answer key. Where answers legitimately vary ("list three causes"), label
expected_factsas any-of sets or mark the casepartial_ok.partial_okis currently informational only: it records that a partial answer is acceptable but does not yet change how the harness scores the case. - Gold chunks are span labels, not chunk ids. 06.10, 2.7 owns this: label where in the source document the answer lives, then map to whatever chunks exist at eval time.
Unanswerable cases need the opposite discipline: the question must be plausibly answerable ("what's the Wi-Fi password for the Berlin office?") but have gold_chunk_ids: [] and expect_abstain: true. A trivially out-of-domain question ("who won the 1998 World Cup?") makes the system abstain for the wrong reason and teaches you nothing about corpus-gap detection (10A.6, 4.2).
3.3 Unanswerable, adversarial and edge cases#
Stratify the set by type. The types this lesson's examples and harness use are unanswerable (corpus-gap abstention), adversarial (injection in retrieved text, false premises), multi-hop (synthesis across chunks), comparison (two-document reasoning), freshness (superseded or stale information), multi-turn (context carry-over, 07.6), filtered (ACL correctness: another tenant's data is the only match, so the correct output is empty or abstain; 06.6) and multilingual (per-language scoring, as in 06.10, Part 9). The full 15-type taxonomy is 10A.6, 4.2, and the injection, ACL and false-premise cases are 10A.6, 4.5.
The freshness type deserves a warning: labels rot. A case labelled against handbook-2025-Q3 becomes wrong when handbook-2026-Q1 ships, not because the system regressed but because the world changed. Tag every case with corpus_version and re-validate freshness cases on each ingestion run (10A.6, 4.6; 07.11 owns update pipelines).
3.4 Versioning and the dev/test discipline#
Same discipline as 06.10, 2.8, extended for generation (the general rules are 10A.2, Part 6 and 10A.6, 4.1):
- Three splits, three purposes:
dev(iterate prompts and thresholds freely),calibration(the ~50–100 cases humans label to calibrate judges, 4.4) andtest(untouched until release verification). Never tune ontest. - Version the dataset and the pipeline.
load_casesreturns the dataset's content sha, andrun_eval(..., run_meta={...})in 5.4 writes it, plus whatever else you supply (prompt version, model id, retriever config, chunker version, embedding model), to a<run>.meta.jsonsidecar next to the results JSONL; the smoke test shows the wiring. An eval number without provenance is a rumour. - Grow the set from production. Mine thumbs-down, reformulations and escalations into new cases (06.10, 8.5 owns the loop). For RAG, also capture the answer and the trace so generation-side failures are reproducible.
3.5 Sizing, stratification and the synthetic-data caveats#
06.10, 2.3–2.4 sized the retrieval set, and generation eval inherits the math with one twist: judge-scored metrics are noisier than rank metrics, so either grow n or accept wider confidence intervals (6.2). Start with ~30–100 cases, stratified by type in proportion to expected production share, and judge a sample on routine runs (4.6).
Synthetic generation (10A.2, and 10A.6, 4.3 for the RAG-specific requirements) scales the set fast, with three RAG-specific caveats on top of the lexical-leakage one: (a) questions generated from the gold chunk have answers trivially contained in context, which is fine for retrieval eval but too easy for generation eval, so generate some questions whose answers need synthesis across chunks and some unanswerable ones by design; (b) synthetic reference answers graded by an LLM judge share the generator's blind spots, the self-grading loop from 2.4; (c) difficulty skews easy, because synthetic questions rarely produce the weird phrasings real users do. Keep a human-written core set as the anchor.
Part 4: LLM-as-judge for RAG#
Almost every generation-side metric needs a judge: faithfulness, answer relevance, correctness against prose references, citation entailment, safety grading. This part is about using judges honestly — the prompts, the failure modes, the calibration, the cost. Module 10A owns general judge methodology (10A.4 for judge design and 10A.5 for validation); what follows is the RAG-specific slice, with links to the home sections for the rest.
4.1 What a RAG judge sees#
The single most common judge bug is showing the judge the wrong inputs. For each metric, the judge needs a different evidence bundle:
| Metric | Judge inputs | Deliberately excluded |
|---|---|---|
| Faithfulness | question, answer, retrieved contexts | the reference answer (it would leak the "right" answer into a grounding check) |
| Answer relevance | question, answer | contexts, reference (the question is whether the answer addresses the question) |
| Correctness | question, answer, reference or expected facts | — (the reference is the point) |
| Citation entailment | claim, cited span text | everything else |
| Abstention (if judged) | question, answer, expect_abstain label |
— |
Build the judge call so the evidence bundle is explicit per metric — a single "grade this RAG answer" mega-prompt conflates the signals and produces scores you can't decompose when they disagree. The general principle (the evidence bundle is the metric) is 10A.4, 3.1.
4.2 The judge prompts#
The harness's three prompts live as constants in judges.py (5.4). Below are the answer relevance and correctness prompts in full, ready to adapt; they follow the module's PromptSpec conventions (04.10), so version them like code. The faithfulness prompt is not repeated here: its full production-shaped version, with the three-verdict vocabulary and the numeric rule, is in 10A.6, 3.1, and FAITHFULNESS_PROMPT in judges.py is its compressed form. Prompt-writing methodology (anatomy, anchoring, the cannot-determine contract, versioning) is 10A.4, Part 3.
Answer relevance judge:
You are grading whether an answer addresses the user's question.
QUESTION: {question}
ANSWER TO GRADE:
{answer}
Rate the answer 1-5 on these criteria:
5 = directly and completely answers the question asked
4 = answers the question with minor gaps or padding
3 = partially addresses the question, or answers a neighbouring question
2 = mostly off-topic or refuses without cause
1 = completely unrelated, or answers a different question
Judge ONLY whether the answer addresses THIS question — do not judge
factual accuracy or writing quality.
Reply with JSON only:
{"score": <1-5>, "reason": "<one sentence>"}Correctness judge (expected-facts variant — robust to paraphrase):
You are checking whether an answer contains specific required facts.
QUESTION: {question}
REQUIRED FACTS (each must appear, possibly paraphrased):
{expected_facts}
ANSWER TO GRADE:
{answer}
For each required fact, decide: present (the answer states it, even in
different words), missing (absent), or contradicted (the answer asserts
the opposite).
Reply with JSON only:
{"facts": [{"fact": "...", "status": "present" | "missing" | "contradicted"}],
"score": <0.0-1.0 = fraction present, contradicted counts as 0>}4.3 Claim decomposition and NLI-style checks#
The one-call faithfulness prompt (10A.6, 3.1, and FAITHFULNESS_PROMPT in judges.py) does extraction and verification together. The alternative, and what Ragas's Faithfulness and TruLens's groundedness feedback actually implement, is two stages: LLM call 1 breaks the answer into claims (a JSON list), and call 2 (or an NLI model, or Vectara's open-source HHEM-2.1-Open classifier) judges each claim against the contexts: "does the context entail this statement? yes/no". Ragas's legacy API offers the HHEM route as FaithfulnesswithHHEM; in the v0.4.3 source the collections API exports Faithfulness but no HHEM class (checked 12 November 2026; see the Ragas docs).
The trade-off in short: one call is cheaper (1 call per answer against 1 + N, which you can batch per 03.9). The two-stage version makes claims a first-class artefact you can feed to 07.10, lets extraction and verification fail independently (a malformed JSON in the one-call version loses everything), and opens the NLI option.
NLI-style means treating verification as natural language inference: premise = retrieved context(s), hypothesis = the claim, label ∈ {entailment, neutral, contradiction}. Small open NLI models do this locally and cheaply, but they were trained on clean single-premise pairs, so long multi-chunk contexts and numeric claims degrade them. That is why the LLM-judge verify step remains the default, with NLI or HHEM as the cost-saving option at scale. The full comparison (granularity by verifier, a concrete NLI model and its licence caveat) is 10A.6, 3.1, and claim-level judging in general is 10A.4, 2.5.
4.4 Calibrating a judge against humans#
A judge you haven't calibrated is a random number generator with good PR. The RAG procedure, in short: take the calibration split (~50–100 cases, stratified by type), have a human label each case on the metric (for faithfulness, label each claim supported or unsupported, or just the case-level verdict if that is what you report), run the judge on the same cases, and measure agreement. Report raw percent agreement and Cohen's kappa, which corrects for the agreement you would get by chance. For a 3-way verdict (supported, unsupported, contradicted) chance agreement is high, so raw percentages flatter: always report κ. The kappa bands, TPR/TNR, intervals and bias correction are in 10A.5, starting at 3.3 and 3.11.
Pure-local kappa, runnable now (stdlib only — real output):
# kappa.py — Cohen's kappa between two raters' labels. Stdlib only.
from collections import Counter
def cohens_kappa(labels_a: list[str], labels_b: list[str]) -> float:
"""labels_a, labels_b: same-length lists of category labels."""
n = len(labels_a)
assert n == len(labels_b) and n > 0
po = sum(a == b for a, b in zip(labels_a, labels_b)) / n # observed agreement
ca, cb = Counter(labels_a), Counter(labels_b)
pe = sum((ca[k] / n) * (cb[k] / n) for k in set(ca) | set(cb)) # chance agreement
return (po - pe) / (1 - pe) if pe < 1 else 1.0
# judge vs human on 12 faithfulness verdicts (S=supported, U=unsupported, C=contradicted)
human = ["S", "S", "U", "S", "C", "S", "U", "S", "S", "U", "S", "S"]
judge = ["S", "U", "U", "S", "C", "S", "U", "S", "S", "U", "C", "S"]
po = sum(h == j for h, j in zip(human, judge)) / len(human)
print(f"raw agreement: {po:.2f}")
print(f"cohen's kappa: {cohens_kappa(human, judge):.2f}")Output:
raw agreement: 0.83
cohen's kappa: 0.71κ = 0.71 — moderate-to-good; good enough to trend metrics, not good enough to auto-fail releases on a 0.02 delta. When κ is low, don't reach for a bigger judge first: read the disagreements. They're almost always one of: ambiguous claims (fix the claim-extraction prompt), borderline entailment (tighten the verdict definitions), or genuinely hard cases (accept the noise, widen your CIs).
Recalibrate whenever the judge model, the judge prompt, or the answer distribution changes — a new generator model produces different error patterns, and yesterday's calibration doesn't transfer (10A.5, 6.4 lists the triggers).
4.5 Judge bias, variance and limits#
Judges fail in characteristic ways: self-preference (a judge grades answers from its own model family higher), verbosity bias (longer answers score higher), position bias (in pairwise judging the first-seen answer wins), reference bias (the judge defers to the reference even when it is wrong), sycophancy to confident tone, run-to-run variance, context-window truncation (a long context cut off in the judge prompt gives false "unsupported" verdicts) and circularity (judge and generator share blind spots). The full table of biases and defences is 10A.4, Part 4, and the checklist for when not to trust a judge is 10A.5, Part 9. The RAG-specific defences:
- Use a different model family as judge than as generator, plus a human calibration sample; that is the only real defence against circularity (10A.2, 11.4 says the same for data generation).
- Prefer expected-facts rubrics over prose references, and have humans spot-check the references, to limit reference bias. For RAG prefer pointwise rubrics over pairwise ones.
- Judge per claim against the relevant context spans (or use a larger-context judge) when the context is long.
- For borderline cases, judge at temperature 0 where supported, run k=3 and take the median, and report score variance in the run record.
Two hard limits to state plainly. A faithfulness judge can only verify claims against the context you show it: it cannot tell you the context itself was wrong, which is what correctness-vs-reference and human review are for. And judges are LLMs that hallucinate, especially on numeric entailment and long contexts, so treat judge scores as estimates with error bars, which is why 6.2 insists on confidence intervals even for judge metrics. In high-stakes or regulated domains the judge is a screening tool, not a verdict.
4.6 Keeping judge costs sane#
Judge calls multiply eval cost fast: cases × metrics × (1 + claims) calls, each carrying the full context. The general cost engineering (the cost model, sampling, tiered judging, batch runs, caching) is 10A.4, Part 7, 5.4 and 5.5. The controls that matter most for RAG, in order of leverage:
- Judge a sample, not everything, on routine runs. Deterministic metrics (abstention, citation string checks, token-F1 vs reference for short answers) run free on every case every time; reserve judges for the dev-set milestones and a rotating ~10–20% sample otherwise (10A.4, 7.3).
- Use the Batch API for offline eval runs: evals are the canonical batch workload (50% cost on supported endpoints; 03.9, Part 6 covers the lifecycle and
custom_idjoin-back). - Downsize the judge. A
gpt-6-luna/claude-haiku-5-5/gemini-3.8-flash-class model judges faithfulness fine for most corpora: verify on your calibration set before assuming, and keep a frontier judge for the audit sample. - Cache judgements. Key = (case_id, pipeline_version, judge_version, metric) — in practice, everything the judge sees: case id, question, expected facts, answer text, context ids, abstained flag, judge version.
CachedJudgeinjudges.py(Part 5) implements exactly that and can persist the cache to disk viapath=, so re-running an eval after an unrelated change doesn't re-pay for identical judge calls. - Two-stage for faithfulness (4.3): extract claims once, verify in batches, or use a local NLI/HHEM model for the verify step on high-volume corpora.
Part 5: The tools landscape as of November 2026#
Reference
This Part is a short orientation. The full treatment is 10A.6, Part 7 (minimal usage of each tool and the metric-definition differences) and 10A.10, Part 2 (versions, licences and pricing). What stays here in full are the public benchmarks (5.6) and the from-scratch harness (5.4).
5.1 The open-source libraries#
The libraries worth knowing for RAG evaluation, in one line each:
- Ragas is the RAG metric canon (
Faithfulness,AnswerRelevancy,ContextPrecision,ContextRecallin the collections API; the legacySingleTurnSampleAPI was deprecated in 0.4 and is removed in 1.0). Paper: arXiv:2309.15217. - DeepEval is pytest-style (
GEval, hallucination, answer relevancy and RAG metrics as tests). - TruLens is OTel-native and the origin of the RAG triad naming (context relevance, groundedness, answer relevance).
- promptfoo is a CLI with YAML assertions, including model-graded ones and red-teaming. OpenAI announced on 9 March 2026 that it is acquiring the company, and the project stays open source.
- LlamaIndex evaluators (llama-index 0.14.25, MIT) are
FaithfulnessEvaluator,AnswerRelevancyEvaluator,ContextRelevancyEvaluator,CorrectnessEvaluatorand others underllama_index.core.evaluation: judge prompts you can read and adapt even if you don't use the framework. - openevals / agentevals (LangChain) provide ready-made judge factories such as
create_llm_as_judge. - Inspect AI is a general eval framework (task = dataset + solver + scorer), the strongest option if you outgrow bespoke harnesses.
- MLflow offers
mlflow.genai.evaluate()with built-in judges (Correctness,RetrievalGroundednessand others), a natural fit if you already track experiments there.
Versions, licences and "best for" are in 10A.10, 2.2, and minimal usage for each is 10A.6, 7.1. Langfuse and Opik also have eval features that overlap TruLens and Phoenix. The category is crowded and moves fast: re-verify versions before relying on any of it.
5.2 The platforms#
LangSmith (datasets, evaluate(), online evals on production traces), Braintrust (Eval(), judge scorers, human review queues, CI gates) and Arize Phoenix (OTel tracing and evals on the same spans, annotation queues) add hosted or self-hosted datasets, experiments and dashboards on top of the libraries. Their versions, licences and pricing are in 10A.10, 2.2 and 2.2b, and what each category does differently is 10A.10, 2.3.
The pattern across platforms: tracing and evals converge. A trace captured in production is a candidate eval case; an eval failure is a trace you can inspect. That's why Module 11A's observability work and this lesson's eval work are two views of the same data — the Trace record from 07.1 is deliberately shaped to serve both.
5.3 What the providers offer#
Provider-native eval features are the most volatile part of the landscape, so this lesson no longer tabulates them: verify on the vendors' own pages before relying on any of it. The current picture is 10A.10, 2.5 (verified 1 December 2026): OpenAI's hosted Evals platform was shut down on 30 November 2026 (deprecated 3 June 2026, read-only from 31 October 2026) and OpenAI's migration guide points to promptfoo, and the Anthropic Console Evaluate tab was retired with the legacy Workbench on 17 August 2026. Google's Gen AI evaluation service and OpenRouter's Ori Eval are in 10A.6, 7.3, together with the dated notes this lesson used to carry for Anthropic's Managed Agents Outcomes and for Google's adaptive rubrics and Vertex AI rename.
The honest summary: providers give you models and (sometimes) tracing hooks; eval methodology is yours. OpenAI's retreat from managed evals is the loudest signal that the ecosystem expects you to own the harness, which is what 5.4 builds.
5.4 A from-scratch harness: docs_qa/eval/#
Every library above wraps the same loop: load cases → run pipeline → score → aggregate → compare. The loop is about 700 lines of stdlib Python in the version below, and owning it means owning the provenance, the failure taxonomy and the CI gate. This section builds docs_qa/eval/ — five modules plus a smoke test, zero third-party dependencies for the core (the judge and pipeline calls are injectable), runnable on fixtures today. Later lessons reuse it: 10A.1 lists it as a domain instance of the same eval loop, 10A.3 mirrors its metrics.py, and 10A.6 builds its stage-aware successor, evalkit/rag_eval.py.
File map (each snippet says where it lives):
docs_qa/eval/
dataset.py # EvalCase schema + JSONL loader + sha256 versioning
metrics.py # deterministic metrics: token-F1, abstention, citation set-P/R
judges.py # Judge protocol, LLMJudge (injectable llm), CachedJudge, FakeJudge
runner.py # run_eval() + run_meta sidecar, CaseResult, aggregation, compare_runs() + bootstrap
report.py # markdown report renderer
smoke_eval.py # keyless end-to-end demo (not a package module)dataset.py — the case schema and loader. Dataclasses, not Pydantic: the harness stays stdlib-only so it runs anywhere (swap in a Pydantic model later if you want schema validation — the JSONL shape is identical):
# docs_qa/eval/dataset.py — eval case schema + JSONL loader. Stdlib only.
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass
from pathlib import Path
SPLITS = {"dev", "test", "calibration"}
@dataclass(frozen=True)
class Turn:
role: str # "user" | "assistant"
content: str
@dataclass(frozen=True)
class EvalCase:
"""One RAG eval case. See lesson 07.9, 3.1 for the field guide."""
case_id: str
question: str
split: str = "dev"
qtype: str = "factoid"
reference_answer: str | None = None
expected_facts: tuple[str, ...] = ()
gold_chunk_ids: tuple[str, ...] = ()
expect_abstain: bool = False
partial_ok: bool = False # informational: ambiguous cases; scoring is unchanged
turns: tuple[Turn, ...] = () # prior conversation (multi-turn cases)
filters: dict | None = None # ACL filters applied at retrieval
corpus_version: str = ""
source: str = ""
notes: str = ""
@property
def is_unanswerable(self) -> bool:
return self.expect_abstain
def _need(d: dict, key: str, case_id: str):
if key not in d:
raise ValueError(f"case {case_id!r}: missing required field {key!r}")
return d[key]
def load_cases(path: str | Path) -> tuple[list[EvalCase], str]:
"""Load eval_cases.jsonl. Returns (cases, dataset_sha256).
The sha is over the raw file bytes — it versions the *labels*, so a run
record can always say exactly which labels produced the scores.
"""
raw = Path(path).read_bytes()
sha = hashlib.sha256(raw).hexdigest()[:12]
cases = []
for lineno, line in enumerate(raw.decode().splitlines(), 1):
line = line.strip()
if not line:
continue
d = json.loads(line)
cid = _need(d, "case_id", f"line {lineno}")
cases.append(EvalCase(
case_id=cid,
question=_need(d, "question", cid),
split=d.get("split", "dev"),
qtype=d.get("type", "factoid"),
reference_answer=d.get("reference_answer"),
expected_facts=tuple(d.get("expected_facts", ())),
gold_chunk_ids=tuple(d.get("gold_chunk_ids", ())),
expect_abstain=bool(d.get("expect_abstain", False)),
partial_ok=bool(d.get("partial_ok", False)),
turns=tuple(Turn(role=t["role"], content=t["content"])
for t in d.get("turns", ())),
filters=d.get("filters"),
corpus_version=d.get("corpus_version", ""),
source=d.get("source", ""),
notes=d.get("notes", ""),
))
if cases[-1].split not in SPLITS:
raise ValueError(f"case {cid!r}: bad split {cases[-1].split!r}")
return cases, shametrics.py — the deterministic layer. Everything here is pure functions you can unit-test; these run on every case, every run, free:
# docs_qa/eval/metrics.py — deterministic RAG metrics. Stdlib only.
#
# These are the metrics that need NO model: abstention correctness,
# citation set precision/recall, and lexical answer similarity for
# short canonical answers. Judge metrics live in judges.py.
from __future__ import annotations
import re
from dataclasses import dataclass
_TOKEN = re.compile(r"[a-z0-9]+")
def tokens(text: str) -> list[str]:
return _TOKEN.findall(text.lower())
def token_f1(prediction: str, reference: str) -> float:
"""Token-level F1 between prediction and reference — the cheap stand-in
for semantic similarity on short answers (numbers, names, yes/no).
SQuAD-style: overlap counted with multiplicity."""
p, r = tokens(prediction), tokens(reference)
if not p or not r:
return 0.0
overlap = {}
for t in p:
overlap[t] = overlap.get(t, 0) + 1
common = 0
for t in r:
if overlap.get(t, 0) > 0:
overlap[t] -= 1
common += 1
if common == 0:
return 0.0
prec, rec = common / len(p), common / len(r)
return 2 * prec * rec / (prec + rec)
def exact_match(prediction: str, reference: str) -> float:
"""1.0 if normalised strings are identical, else 0.0. For canonical
answers only (dates, codes, yes/no) — prose needs a judge."""
norm = lambda s: " ".join(tokens(s))
return 1.0 if norm(prediction) == norm(reference) else 0.0
def citation_prf(cited_ids: list[str], gold_ids: list[str]) -> tuple[float, float, float]:
"""Set-based citation precision/recall/F1 against gold chunk ids.
This is the CHEAP layer of citation scoring: does the answer cite the
right chunk ids at all? Whether the cited span actually supports the
claim is 07.5's entailment problem, not this function's.
"""
pred, gold = set(cited_ids), set(gold_ids)
if not pred and not gold:
return 1.0, 1.0, 1.0
tp = len(pred & gold)
prec = tp / len(pred) if pred else 0.0
rec = tp / len(gold) if gold else 0.0
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
return prec, rec, f1
@dataclass(frozen=True)
class AbstentionOutcome:
"""Per-case abstention verdict, computed in pure logic."""
expect_abstain: bool
did_abstain: bool
correct: bool # abstained iff expected to
@property
def kind(self) -> str:
if self.expect_abstain and self.did_abstain:
return "correct_abstention"
if self.expect_abstain and not self.did_abstain:
return "answered_unanswerable" # the dangerous one
if not self.expect_abstain and self.did_abstain:
return "abstained_answerable" # coverage loss
return "answered"
def abstention_outcome(expect_abstain: bool, did_abstain: bool) -> AbstentionOutcome:
return AbstentionOutcome(expect_abstain, did_abstain,
expect_abstain == did_abstain)judges.py — the judge seam. Judge is a protocol over (case, result); LLMJudge wraps an injectable llm callable using the three prompts defined as constants below (faithfulness, answer relevance, correctness; 4.2 says what each must show the judge and links the full faithfulness prompt); CachedJudge wraps any judge with the judgement cache of 4.6; FakeJudge is the deterministic stand-in so the whole pipeline runs with no API. The RagResult docstring also maps its fields onto 07.1's Answer/Trace/Context objects — the names differ, so wire answer_fn accordingly:
# docs_qa/eval/judges.py — LLM-as-judge behind an injectable seam.
# The `llm` callable has signature llm(prompt: str) -> str and returns
# JSON text. In production it wraps your provider's structured-output
# call (03.4); in tests it is FakeJudge or a canned dict.
from __future__ import annotations
import json
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Protocol
from dataset import EvalCase
@dataclass(frozen=True)
class JudgeScores:
"""Per-case judge output. Any field may be None = 'not judged'."""
faithfulness: float | None = None # 0..1, claims supported / claims
answer_relevance: float | None = None # 0..1 (score/5 for the 1-5 rubric)
correctness: float | None = None # 0..1, expected facts present
judge_version: str = ""
raw: dict = field(default_factory=dict)
@dataclass(frozen=True)
class RagResult:
"""What the pipeline returns per case — the eval-facing slice of the
Answer/Trace objects from 07.1. Keep it small: the runner only needs
what metrics score.
Field mapping from 07.1's types (names differ — answer_fn builds this
derived view, it is not the pipeline object itself):
answer_text <- Answer.text
cited_chunk_ids <- [c.chunk_id for c in Answer.citations]
retrieved_chunk_ids <- Trace.retrieved_ids
context_chunk_ids <- [i.chunk_id for i in Context.items]
(what actually entered the prompt)
abstained <- Answer.abstained
latency_ms <- Trace.total_latency_ms
prompt_tokens / completion_tokens
<- sum of stage input/output tokens in Trace.stages
"""
answer_text: str
cited_chunk_ids: tuple[str, ...] = ()
retrieved_chunk_ids: tuple[str, ...] = () # what search() returned
context_chunk_ids: tuple[str, ...] = () # what actually entered the prompt
abstained: bool = False
latency_ms: float | None = None
prompt_tokens: int | None = None
completion_tokens: int | None = None
class Judge(Protocol):
def __call__(self, case: EvalCase, result: RagResult) -> JudgeScores: ...
FAITHFULNESS_PROMPT = """\
You are grading whether an answer is grounded in retrieved context.
QUESTION: {question}
RETRIEVED CONTEXTS:
{contexts}
ANSWER TO GRADE:
{answer}
List every factual claim in the answer. For each claim, decide whether
the retrieved contexts ENTAIL it. Reply with JSON only:
{{"claims": [{{"claim": "...", "verdict": "supported" | "unsupported" | "contradicted"}}]}}
"""
RELEVANCE_PROMPT = """\
You are grading whether an answer addresses the user's question.
QUESTION: {question}
ANSWER TO GRADE:
{answer}
Rate the answer 1-5:
5 = directly and completely answers the question asked
4 = answers the question with minor gaps or padding
3 = partially addresses the question, or answers a neighbouring question
2 = mostly off-topic or refuses without cause
1 = completely unrelated, or answers a different question
Judge ONLY whether the answer addresses THIS question — do not judge
factual accuracy or writing quality.
Reply with JSON only:
{{"score": <1-5>, "reason": "<one sentence>"}}
"""
CORRECTNESS_PROMPT = """\
You are checking whether an answer contains specific required facts.
QUESTION: {question}
REQUIRED FACTS:
{facts}
ANSWER TO GRADE:
{answer}
Reply with JSON only:
{{"facts": [{{"fact": "...", "status": "present" | "missing" | "contradicted"}}],
"score": <0.0-1.0>}
"""
def _parse_json(text: str) -> dict:
"""Tolerant JSON extraction: find the first {...} block and parse it.
(03.4 owns the general extraction problem; this is the eval-local version.)"""
start, end = text.find("{"), text.rfind("}")
if start == -1 or end <= start:
return {}
try:
return json.loads(text[start:end + 1])
except json.JSONDecodeError:
return {}
class LLMJudge:
"""Wraps an injectable llm callable + the metric prompts.
`llm(prompt: str) -> str` must return JSON text. `contexts_of` maps a
case+result to the context strings the judge should see — in production
it reads the Context object's chunk texts; here it defaults to the
retrieved chunk ids joined (swap for real text in your wiring).
"""
def __init__(self, llm, contexts_of=None, version: str = "llmjudge-1.0"):
self.llm = llm
self.contexts_of = contexts_of or (lambda case, result: "\n".join(result.context_chunk_ids))
self.version = version
def faithfulness(self, case: EvalCase, result: RagResult) -> JudgeScores:
if result.abstained:
return JudgeScores(judge_version=self.version) # nothing to grade
prompt = FAITHFULNESS_PROMPT.format(
question=case.question,
contexts=self.contexts_of(case, result),
answer=result.answer_text)
data = _parse_json(self.llm(prompt))
claims = data.get("claims", [])
if not claims:
return JudgeScores(judge_version=self.version, raw=data)
supported = sum(1 for c in claims
if isinstance(c, dict) and c.get("verdict") == "supported")
return JudgeScores(faithfulness=supported / len(claims),
judge_version=self.version, raw=data)
def answer_relevance(self, case: EvalCase, result: RagResult) -> JudgeScores:
if result.abstained:
return JudgeScores(judge_version=self.version) # a refusal isn't relevance-graded
prompt = RELEVANCE_PROMPT.format(question=case.question,
answer=result.answer_text)
data = _parse_json(self.llm(prompt))
try:
rel = min(max(float(data["score"]) / 5.0, 0.0), 1.0)
except (KeyError, TypeError, ValueError):
rel = None
return JudgeScores(answer_relevance=rel,
judge_version=self.version, raw=data)
def correctness(self, case: EvalCase, result: RagResult) -> JudgeScores:
if case.expect_abstain or not case.expected_facts:
return JudgeScores(judge_version=self.version)
prompt = CORRECTNESS_PROMPT.format(
question=case.question,
facts="\n".join(f"- {f}" for f in case.expected_facts),
answer=result.answer_text)
data = _parse_json(self.llm(prompt))
facts = data.get("facts")
if isinstance(facts, list) and facts:
# derive the score from the per-fact verdicts when the judge
# returns them — its own "score" field is only a fallback,
# since a judge can emit an inconsistent pair (0.9 next to
# three "missing" facts)
score = sum(1 for f in facts
if isinstance(f, dict) and f.get("status") == "present") / len(facts)
else:
score = data.get("score")
try:
score = float(score) if score is not None else None
except (TypeError, ValueError):
score = None # malformed judge output — record as unjudged
return JudgeScores(correctness=score,
judge_version=self.version, raw=data)
def __call__(self, case: EvalCase, result: RagResult) -> JudgeScores:
f = self.faithfulness(case, result)
r = self.answer_relevance(case, result)
c = self.correctness(case, result)
return JudgeScores(faithfulness=f.faithfulness,
answer_relevance=r.answer_relevance,
correctness=c.correctness,
judge_version=self.version,
raw={"faithfulness": f.raw,
"answer_relevance": r.raw,
"correctness": c.raw})
class CachedJudge:
"""Memoising wrapper around any Judge — the judgement cache of 4.6.
The key covers everything the judge sees for a case: case_id,
question, expected_facts, answer text, context chunk ids, the
abstained flag and the wrapped judge's `version` attribute (give your
judge one — LLMJudge has it). A Judge that reads other case/result
fields should override `_key`.
`path` persists the cache as JSON so re-runs — even on another
machine — reuse judgements instead of re-paying for identical calls;
omit it for an in-memory cache that lives for one process. `raw`
payloads must stay JSON-serialisable for persistence to work.
"""
def __init__(self, judge, path: str | Path | None = None):
self.judge = judge
self.version = getattr(judge, "version", type(judge).__name__)
self.path = Path(path) if path else None
self.store: dict[str, dict] = {}
if self.path and self.path.exists():
self.store = json.loads(self.path.read_text())
def _key(self, case: EvalCase, result: RagResult) -> str:
payload = {
"case_id": case.case_id,
"question": case.question,
"expected_facts": list(case.expected_facts),
"answer": result.answer_text,
"context": list(result.context_chunk_ids),
"abstained": result.abstained,
"judge": self.version,
}
return json.dumps(payload, sort_keys=True)
def __call__(self, case: EvalCase, result: RagResult) -> JudgeScores:
key = self._key(case, result)
if key not in self.store:
self.store[key] = asdict(self.judge(case, result))
if self.path:
self.path.write_text(
json.dumps(self.store, indent=1, sort_keys=True) + "\n")
return JudgeScores(**self.store[key])
class FakeJudge:
"""Deterministic stand-in for tests and keyless runs.
Returns canned scores keyed by substring in the answer text — enough to
exercise the runner, aggregation and report end-to-end with no API.
Mirrors LLMJudge's skip rules so demo means match a real run: abstained
answers aren't faithfulness/relevance-graded, and correctness is only
scored when the case expects an answer with known facts.
"""
def __init__(self, scores: dict[str, float] | None = None):
self.scores = scores or {}
self.calls: list[str] = []
self.version = "fake-1.0"
def __call__(self, case: EvalCase, result: RagResult) -> JudgeScores:
self.calls.append(case.case_id)
score = next((v for k, v in self.scores.items() if k in result.answer_text), 0.5)
faith = rel = None if result.abstained else score
corr = score if (not case.expect_abstain and case.expected_facts) else None
return JudgeScores(faithfulness=faith, answer_relevance=rel,
correctness=corr, judge_version=self.version)runner.py — the loop. answer_fn is the pipeline seam (the same docs_qa pipeline the other lessons build; signature answer_fn(case) -> RagResult), judge is optional:
# docs_qa/eval/runner.py — run cases through the pipeline, score, aggregate.
# Stdlib only. `answer_fn` and `judge` are the only seams needing models.
from __future__ import annotations
import json
import random
import statistics
from dataclasses import asdict, dataclass
from pathlib import Path
from dataset import EvalCase
from judges import JudgeScores, RagResult
from metrics import token_f1, citation_prf, abstention_outcome
@dataclass
class CaseResult:
case_id: str
qtype: str
split: str
answer_text: str
abstained: bool
cited_chunk_ids: list[str]
retrieved_chunk_ids: list[str]
context_chunk_ids: list[str]
gold_chunk_ids: list[str]
latency_ms: float | None
prompt_tokens: int | None
completion_tokens: int | None
# deterministic metrics
token_f1: float | None
citation_p: float | None
citation_r: float | None
citation_f1: float | None
abstention: str # AbstentionOutcome.kind or "pipeline_error"
abstention_correct: bool | None
# judge metrics (None = not judged, abstained, or judge_error)
faithfulness: float | None = None
answer_relevance: float | None = None
correctness: float | None = None
judge_version: str = ""
judge_error: str | None = None # set when the judge call itself crashed
def _mean(xs):
xs = [x for x in xs if x is not None]
return statistics.fmean(xs) if xs else None
def run_eval(cases: list[EvalCase], answer_fn, judge=None,
out_path: str | Path | None = None,
run_meta: dict | None = None) -> list[CaseResult]:
"""Run every case through answer_fn, score deterministically, judge if given.
answer_fn(case) -> RagResult. A case that raises is recorded as an error
result rather than aborting the run — evals must survive pipeline crashes.
Error results are never judged (a "__ERROR__" stub is not an answer) and
get abstention="pipeline_error" with abstention_correct=None.
A judge that raises is handled the same way: the case keeps its
deterministic metrics, judge fields stay None and judge_error records
what happened — one malformed judge reply must not lose the whole run.
run_meta is provenance you supply — dataset_version, the dataset_sha256
that load_cases returns, pipeline/judge versions — written to a
"<out>.meta.json" sidecar next to the results JSONL so every score stays
interpretable (3.4).
"""
results = []
for case in cases:
try:
r: RagResult = answer_fn(case)
except Exception as e: # noqa: BLE001 — record, don't abort
r = RagResult(answer_text=f"__ERROR__ {type(e).__name__}: {e}")
is_error = r.answer_text.startswith("__ERROR__")
abst = abstention_outcome(case.expect_abstain, r.abstained)
# deterministic answer metrics: skipped for abstain-expected cases,
# for pipeline errors, and for unjudgeable prose (token_f1 only
# meaningful vs a reference)
tf1 = None
if case.reference_answer and not case.expect_abstain and not is_error:
tf1 = token_f1(r.answer_text, case.reference_answer)
cp, cr, cf1 = (None, None, None)
if case.gold_chunk_ids and not is_error:
cp, cr, cf1 = citation_prf(list(r.cited_chunk_ids), list(case.gold_chunk_ids))
scores = JudgeScores()
judge_error = None
if judge and not is_error:
try:
scores = judge(case, r)
except Exception as e: # noqa: BLE001 — record, don't abort
judge_error = f"{type(e).__name__}: {e}"
results.append(CaseResult(
case_id=case.case_id, qtype=case.qtype, split=case.split,
answer_text=r.answer_text, abstained=r.abstained,
cited_chunk_ids=list(r.cited_chunk_ids),
retrieved_chunk_ids=list(r.retrieved_chunk_ids),
context_chunk_ids=list(r.context_chunk_ids),
gold_chunk_ids=list(case.gold_chunk_ids),
latency_ms=r.latency_ms,
prompt_tokens=r.prompt_tokens,
completion_tokens=r.completion_tokens,
token_f1=tf1, citation_p=cp, citation_r=cr, citation_f1=cf1,
abstention="pipeline_error" if is_error else abst.kind,
abstention_correct=(None if is_error else
abst.correct if (case.expect_abstain or r.abstained) else None),
faithfulness=scores.faithfulness,
answer_relevance=scores.answer_relevance,
correctness=scores.correctness,
judge_version=scores.judge_version,
judge_error=judge_error,
))
if out_path:
out = Path(out_path)
out.write_text(
"\n".join(json.dumps(asdict(r)) for r in results) + "\n")
meta = {"n_cases": len(results),
"judge_versions": sorted({r.judge_version for r in results if r.judge_version}),
**(run_meta or {})}
out.with_name(out.stem + ".meta.json").write_text(
json.dumps(meta, indent=2, sort_keys=True) + "\n")
return results
def aggregate(results: list[CaseResult]) -> dict:
"""Headline metrics overall and per split/type. None-safe means."""
def block(rs):
pt = [r.prompt_tokens for r in rs if r.prompt_tokens is not None]
ct = [r.completion_tokens for r in rs if r.completion_tokens is not None]
toks = [(r.prompt_tokens or 0) + (r.completion_tokens or 0)
for r in rs
if r.prompt_tokens is not None or r.completion_tokens is not None]
return {
"n": len(rs),
"faithfulness": _mean([r.faithfulness for r in rs]),
"answer_relevance": _mean([r.answer_relevance for r in rs]),
"correctness": _mean([r.correctness for r in rs]),
"token_f1": _mean([r.token_f1 for r in rs]),
"citation_f1": _mean([r.citation_f1 for r in rs]),
"abstention_accuracy": _mean(
[float(r.abstention_correct) for r in rs if r.abstention_correct is not None]),
"answered_unanswerable": sum(
1 for r in rs if r.abstention == "answered_unanswerable"),
"abstained_answerable": sum(
1 for r in rs if r.abstention == "abstained_answerable"),
"errors": sum(1 for r in rs if r.abstention == "pipeline_error"),
"judge_errors": sum(1 for r in rs if r.judge_error),
# token accounting (2.8/6.4): totals feed cost math — prompt and
# completion tokens price differently — the mean is the
# per-answer figure variants get compared on
"prompt_tokens_total": sum(pt) if pt else None,
"completion_tokens_total": sum(ct) if ct else None,
"tokens_per_answer": statistics.fmean(toks) if toks else None,
"latency_p50_ms": _percentile([r.latency_ms for r in rs], 50),
"latency_p95_ms": _percentile([r.latency_ms for r in rs], 95),
}
out = {"overall": block(results)}
for split in sorted({r.split for r in results}):
out[f"split:{split}"] = block([r for r in results if r.split == split])
for qt in sorted({r.qtype for r in results}):
out[f"type:{qt}"] = block([r for r in results if r.qtype == qt])
return out
def _percentile(xs, pct):
xs = sorted(x for x in xs if x is not None)
if not xs:
return None
k = (len(xs) - 1) * pct / 100
f, c = int(k), min(int(k) + 1, len(xs) - 1)
return xs[f] + (xs[c] - xs[f]) * (k - f)
def bootstrap_ci(diffs: list[float], iters: int = 2000,
seed: int = 7) -> tuple[float, float]:
"""95% bootstrap CI of the mean paired difference. Same method as
06.10's compare_runs — resample the per-case diffs with replacement."""
rng = random.Random(seed)
n = len(diffs)
if n == 0:
return (float("nan"), float("nan"))
means = []
for _ in range(iters):
means.append(statistics.fmean(diffs[rng.randrange(n)] for _ in range(n)))
means.sort()
return means[int(0.025 * iters)], means[int(0.975 * iters)]
def compare_runs(before: list[CaseResult], after: list[CaseResult],
metric: str = "faithfulness") -> dict:
"""Paired comparison on cases present in both runs.
Pairs by case_id — only cases scored in BOTH runs enter the diff
(a case that errored in one run and not the other is a finding, not
a paired observation). Returns mean diff + bootstrap 95% CI.
"""
bmap = {r.case_id: r for r in before}
pairs = [(bmap[r.case_id], r) for r in after if r.case_id in bmap]
diffs = []
for b, a in pairs:
bv, av = getattr(b, metric), getattr(a, metric)
if bv is not None and av is not None:
diffs.append(av - bv)
lo, hi = bootstrap_ci(diffs)
return {"metric": metric, "n_pairs": len(diffs),
"mean_diff": statistics.fmean(diffs) if diffs else None,
"ci95": (lo, hi),
"significant": bool(diffs) and not (lo <= 0 <= hi)}report.py — renders aggregate() output as a markdown table you can paste into a PR or dashboard:
# docs_qa/eval/report.py — markdown report from run results. Stdlib only.
from __future__ import annotations
from runner import aggregate
def _fmt(v):
return "—" if v is None else (f"{v:.3f}" if isinstance(v, float) else str(v))
def _fmti(v):
return "—" if v is None else str(int(round(v)))
def report_markdown(results, title: str = "RAG eval run",
comparisons: list[dict] | None = None,
meta: dict | None = None) -> str:
agg = aggregate(results)
lines = [f"## {title}", "",
"| split/type | n | faithfulness | relevance | correctness | token-F1 | cite-F1 | abstain-acc | tok/ans | p50 ms | p95 ms |",
"|---|---|---|---|---|---|---|---|---|---|---|"]
for key in sorted(agg):
b = agg[key]
lines.append(
f"| {key} | {b['n']} | {_fmt(b['faithfulness'])} | "
f"{_fmt(b['answer_relevance'])} | {_fmt(b['correctness'])} | "
f"{_fmt(b['token_f1'])} | {_fmt(b['citation_f1'])} | "
f"{_fmt(b['abstention_accuracy'])} | {_fmti(b['tokens_per_answer'])} | "
f"{_fmt(b['latency_p50_ms'])} | {_fmt(b['latency_p95_ms'])} |")
flags = []
for key, b in agg.items():
if b["answered_unanswerable"]:
flags.append(f"- `{key}`: {b['answered_unanswerable']} unanswerable case(s) answered anyway")
if b["errors"]:
flags.append(f"- `{key}`: {b['errors']} pipeline error(s)")
if b.get("judge_errors"):
flags.append(f"- `{key}`: {b['judge_errors']} judge error(s) — those cases scored no judge metrics")
if flags:
lines += ["", "### Flags", ""] + flags
if comparisons:
lines += ["", "### Comparisons", "",
"| metric | n pairs | mean Δ | 95% CI | significant |",
"|---|---|---|---|---|"]
for c in comparisons:
lo, hi = c["ci95"]
lines.append(
f"| {c['metric']} | {c['n_pairs']} | {_fmt(c['mean_diff'])} | "
f"[{_fmt(lo)}, {_fmt(hi)}] | {'yes' if c['significant'] else 'no'} |")
if meta:
lines += ["", "_provenance: " + " · ".join(
f"{k}={v}" for k, v in sorted(meta.items())) + "_"]
return "\n".join(lines)End-to-end smoke test — the whole harness running keyless on a tiny fixture. This is the demo you can run today; outputs below are real (pure stdlib):
# smoke_eval.py — run_eval + CachedJudge(FakeJudge) + report on 4 cases.
# Stdlib only. The eval modules use flat imports, so place this file INSIDE
# docs_qa/eval/ and run `python smoke_eval.py` from that directory — no
# PYTHONPATH needed. It writes smoke_results.jsonl and
# smoke_results.meta.json next to itself.
import json
from pathlib import Path
from dataset import EvalCase
from judges import CachedJudge, FakeJudge, RagResult
from runner import run_eval
from report import report_markdown
cases = [
EvalCase(case_id="e01", question="How much vacation do I accrue?",
split="dev", reference_answer="1.5 days per month, up to 18 days",
expected_facts=["1.5 days per month", "18 days"],
gold_chunk_ids=["handbook-001"]),
EvalCase(case_id="e02", question="What is the Berlin office wifi password?",
split="dev", expect_abstain=True),
EvalCase(case_id="e03", question="When does the MSA auto-renew?",
split="test", reference_answer="60 days before the term ends",
expected_facts=["60 days before the term ends"],
gold_chunk_ids=["contract-10"]),
EvalCase(case_id="e04", question="Parental leave for contractors?",
split="dev", qtype="unanswerable", expect_abstain=True,
partial_ok=True),
]
TOKENS = {"e01": (1840, 64), "e02": (1790, 41),
"e03": (1902, 58), "e04": (1755, 73)}
def fake_pipeline(case: EvalCase) -> RagResult:
"""Stand-in for the docs_qa pipeline: answer from a canned map."""
answers = {
"e01": ("Full-time employees accrue 1.5 days of paid vacation per month, up to 18 days per year.", False),
"e02": ("I don't have information about office wifi passwords in the provided documents.", True),
"e03": ("The MSA auto-renews unless notice is given 60 days before the term ends.", False),
"e04": ("The handbook covers parental leave for employees; it does not specify contractor entitlements.", False),
}
text, abstained = answers[case.case_id]
pt, ct = TOKENS[case.case_id]
return RagResult(answer_text=text, abstained=abstained,
cited_chunk_ids=("handbook-001",) if case.case_id == "e01" else (),
retrieved_chunk_ids=("handbook-001", "handbook-003"),
context_chunk_ids=("handbook-001",),
latency_ms=412.0,
prompt_tokens=pt, completion_tokens=ct)
judge = CachedJudge(FakeJudge({"accrue": 0.9, "auto-renews": 0.8}))
results = run_eval(cases, fake_pipeline, judge=judge,
out_path="smoke_results.jsonl",
run_meta={"dataset_version": "smoke-v1",
"note": "hand-written fixture, no corpus"})
meta = json.loads(Path("smoke_results.meta.json").read_text())
print(report_markdown(results, title="smoke run (fake pipeline + fake judge)",
meta=meta))## smoke run (fake pipeline + fake judge)
| split/type | n | faithfulness | relevance | correctness | token-F1 | cite-F1 | abstain-acc | tok/ans | p50 ms | p95 ms |
|---|---|---|---|---|---|---|---|---|---|---|
| overall | 4 | 0.733 | 0.733 | 0.850 | 0.633 | 0.500 | 0.500 | 1881 | 412.000 | 412.000 |
| split:dev | 3 | 0.700 | 0.700 | 0.900 | 0.667 | 1.000 | 0.500 | 1854 | 412.000 | 412.000 |
| split:test | 1 | 0.800 | 0.800 | 0.800 | 0.600 | 0.000 | — | 1960 | 412.000 | 412.000 |
| type:factoid | 3 | 0.850 | 0.850 | 0.850 | 0.633 | 0.500 | 1.000 | 1898 | 412.000 | 412.000 |
| type:unanswerable | 1 | 0.500 | 0.500 | — | — | — | 0.000 | 1828 | 412.000 | 412.000 |
### Flags
- `overall`: 1 unanswerable case(s) answered anyway
- `split:dev`: 1 unanswerable case(s) answered anyway
- `type:unanswerable`: 1 unanswerable case(s) answered anyway
_provenance: dataset_version=smoke-v1 · judge_versions=['fake-1.0'] · n_cases=4 · note=hand-written fixture, no corpus_Reading the output like an engineer: e04 answered (with a hedge) when it should have abstained → the answered_unanswerable flag, the 0.0 abstention accuracy on type:unanswerable, and the 0.5 overall (only the two cases where abstention was expected or happened are scored — e01/e03 never entered the abstention metric, per the 2.6 convention). e02 abstained correctly, which is why type:factoid's abstain-acc reads 1.000: e02 defaults to factoid type and its correct abstention is the only scored case in that stratum. e03 retrieved gold contract-10 but cited nothing → cite-F1 0.000 on split:test. tok/ans is the mean prompt+completion tokens per case — the per-answer cost figure 6.4 compares variants on (the split totals in the aggregate dict feed the price math). The _provenance line is the run_meta you passed plus what the runner inferred (n_cases, judge_versions) — read back from smoke_results.meta.json, the sidecar written next to smoke_results.jsonl. The judge columns are FakeJudge canned values (0.9/0.8 on keyword matches, 0.5 default) run through CachedJudge — real judges produce real distributions; the plumbing is what's being demonstrated. Note the denominators: e02 abstained, so FakeJudge returns all-None judge scores for it (mirroring LLMJudge, which doesn't faithfulness/relevance-grade refusals), and e04 has expect_abstain so correctness isn't scored — the 0.733 faithfulness mean averages only e01/e03/e04, and type:unanswerable's correctness cell is — because no case in that stratum has expected_facts. A real LLMJudge run would produce the same shape of output — None where a metric doesn't apply — with real distributions instead of canned ones.
5.5 From-scratch vs library: the decision#
The libraries are not competitors to this harness — they're implementations of the same ideas with more metrics and integrations. Use this harness when you are learning, want to see every number's provenance, or need a free deterministic gate for CI (judges are too slow and costly per commit). Reach for Ragas or DeepEval when you want batteries-included metrics, but read their judge prompts first: you are adopting their definition of "faithful". If you already trace with LangSmith, Braintrust or Phoenix, use the platform's evals on your traces and keep this harness for the labelled offline set. The full decision table (agentic and multi-turn evals, regulated domains) is 10A.6, 7.5, and the build-versus-buy view across the whole landscape is 10A.10, 3.2.
Knowing the mechanics is what lets you judge whether Ragas's Faithfulness matches your definition, whether DeepEval's GEval rubric is measuring what you think, and when a custom metric is warranted.
5.6 Public benchmarks and eval taxonomies#
Benchmark literacy in general (what public benchmarks are for, how to read a leaderboard) is 10A.10, Part 5; this section lists the RAG-specific ones.
Your labelled set is the ground truth for your corpus, but the research literature has produced shared benchmarks and failure taxonomies worth knowing — as sanity checks on model/generator choices, and as a vocabulary for error analysis. Three that practitioners actually cite:
| Benchmark / framework | What it measures | When it earns its keep |
|---|---|---|
| RGB — Retrieval-Augmented Generation Benchmark (arXiv:2309.01431, code) | Generator robustness to imperfect retrieval, split into four testbeds: noise robustness (distractor chunks mixed in), negative rejection (context is all noise → should abstain), information integration (answer needs several documents), counterfactual robustness (context contradicts the model's parametric knowledge) | Stress-testing how a generator copes with noisy context — e.g. after raising k, switching models, or weakening filters. Fixed QA corpus in English and Chinese; scores don't transfer to your domain |
| CRUD-RAG (arXiv:2401.17043, code) | RAG across Create/Read/Update/Delete application scenarios on a Chinese corpus — original-content generation, knowledge-intensive QA, revising stale text, condensing long documents — scoring the whole pipeline, not just the LLM | When your product does more than QA (drafting, updating, summarising) and you want scenario coverage your hand-built set lacks. Chinese-language labels; treat absolute scores as directional, the scenario taxonomy as the takeaway |
| RAGChecker (arXiv:2408.08067, NeurIPS 2024, code) | Claim-level diagnostics: decomposes the answer and the reference into atomic claims, checks entailment in both directions — overall quality metrics plus separate diagnostic retriever metrics and diagnostic generator metrics | When faithfulness/correctness don't tell you enough — "which specific claims were unsupported vs missing" — or you want a maintained implementation of the claim-decomposition procedure from 4.1–4.3 |
Three more references show up constantly in papers and vendor docs, and are worth recognising even though you will rarely run them:
- RAGTruth (arXiv:2401.00396) — a corpus of nearly 18,000 RAG responses from several LLMs, annotated by hand at word and response level for hallucination. It is the standard test bed for hallucination detectors: if you build or buy a faithfulness classifier, this is what you check it against (4.4 is the same idea on your own data).
- ARES (arXiv:2311.09476, NAACL 2024) — generates synthetic training data to fine-tune small judges for context relevance, faithfulness and answer relevance, then uses a small set of human labels with prediction-powered inference to put a confidence interval on the scores. It is the research ancestor of "calibrate your judge against humans".
- TREC 2024 RAG Track — a shared task where systems produce attributed answers over the MS MARCO V2.1 collection; the Ragnarök paper (arXiv:2406.16828) describes its reusable framework, baselines and a pairwise human "arena". Useful as a model of how a community evaluates attributed answers, rather than as a score to chase.
The honest caveat: none of these replaces your labelled set. Different corpora, languages and label conventions mean a good RGB score says your generator handles noisy context — not that your retriever finds the right chunks. Use public benchmarks to (a) compare generator/model choices on a shared task, (b) borrow their failure taxonomies for your Part 7 error analysis, and (c) sanity-check your judge prompts — if your faithfulness judge can't reproduce known supported/unsupported claim pairs, it's miscalibrated (4.4). Module 10A owns eval methodology in depth.
Part 6: Experiment design#
6.1 Ablations: change one thing at a time#
Every RAG improvement claim needs an ablation: run the same eval set against pipeline variants that differ in exactly one component, and let the metrics attribute the delta. The standard ablation ladder for this module:
| Ablation | What it isolates | Typical finding |
|---|---|---|
| retriever: dense vs BM25 vs hybrid vs +rerank | retrieval quality | which retrieval config earns its latency (06.10, 07.2) |
| k / context budget | coverage vs dilution | more chunks ≠ better answers past a point — faithfulness can fall as irrelevant chunks give the judge more rope |
| query rewriting on/off | the 07.3 techniques | helps some query types, hurts others — measure per type |
| grounding prompt version | prompt engineering (07.4) | abstention rate vs coverage trade-off |
| generator model tier | model choice (02.9) | cheap model + good retrieval vs frontier model + weak retrieval |
| citations on/off | citation layer (07.5) | citation metrics only exist when citations exist |
| oracle context vs real retrieval | the ceiling test (1.3) | separates retrieval-bound from generation-bound failures |
The component-by-metric matrix and the oracle experiments that turn this ladder into attribution are 10A.6, Part 1 and Part 2.
Rules that keep ablations honest:
- Same eval set, same split, same judge version for every variant — a comparison across different datasets or judge prompts measures nothing.
- Record the full config per run (dataset sha, pipeline versions, judge version) —
run_eval's out_path JSONL plus its.meta.jsonsidecar (run_meta:dataset_version,dataset_sha256, judge/pipeline versions) is the provenance; 07.11 formalises config-as-code. - Per-type breakdowns, not just the mean. A hybrid retriever that wins overall but loses on error-code queries is a regression for the users who need it — the
type:rows in the report exist for this. - The dev set iterates, the test set verifies. Sweep on
dev, pick the winner, runtestonce. If you re-runtestafter every tweak it stops being a test.
6.2 Paired comparison and confidence intervals#
The runner's compare_runs(before, after, metric) implements the same discipline as 06.10, 4.5, one level up: pair results by case_id, compute per-case differences, bootstrap the mean difference and report the 95% CI. "Faithfulness +0.03" means nothing without the interval: on a 30-case dev set the CI is usually wider than the delta, and that's the answer. You can't distinguish the variants, so don't ship on this evidence; grow the set, or accept the tie and pick on cost and latency. The general statistics (paired comparisons, minimum detectable effect, repeated runs) are 10A.8, Part 2, and the RAG-specific adjustments are 10A.6, 8.1.
Two RAG-specific wrinkles worth keeping in mind: judge metrics are noisier than retrieval metrics (run the judge k=2–3 times per case and average before differencing), and only cases present and scored in both runs enter the diff (the runner enforces this), so a case that errors in one run is a finding to investigate, not a silent drop.
6.3 Regression gates in CI#
03.10 owns the testing infrastructure (fakes, mock transports, pytest layout), and 10A.8, 3.1 owns tiered suites and CI gates in general. For RAG evals specifically, a sensible gate ladder:
| Gate | Runs | Blocks merge when |
|---|---|---|
| Unit tests | every commit, no API | deterministic metrics code, dataset loader, citation parsing break |
| Golden-set smoke | every commit or PR, ~10–20 fixed cases, fake or cheap model | pipeline crashes, format regressions, citation parse failures |
| Deterministic eval | every PR, full dev set, no judges | abstention accuracy, citation set-P/R, token-F1 drop beyond threshold |
| Judge eval | nightly or on-demand, full dev set + judges | faithfulness/relevance/correctness drop with CI excluding zero |
| Test-set eval | release candidates only | the held-out verdict |
The principle: cheap deterministic gates per commit, expensive judge gates per milestone. A judge eval that costs $5 and takes 20 minutes doesn't belong on every PR — but abstention correctness and citation parsing do, because they're free and catch the worst regressions.
6.4 Cost-aware evaluation#
Quality gains are priced. The cost components are listed in 2.8 and 10A.6, 3.7; the trade-off rule below is this section's. For each variant record, alongside the metrics:
cost_per_answer = query_embed_cost + retrieval_cost + prompt_tokens*in_price
+ completion_tokens*out_price + judge_cost_per_case (0 if the case is not judged)(prices as parameters — look them up via 03.7). Then ask the trade question explicitly: "faithfulness +0.04 for +38% cost per answer — ship?" There's no universal answer; the decision rule is: ship the cheaper variant when the quality delta's CI includes zero; ship the costlier one when the delta is significant and the metric it improves is the one users complain about. Judge cost belongs in the equation too — a metric you can't afford to run regularly is a metric you don't have.
6.5 Evaluating changes in ingestion#
Re-chunking, re-embedding, metadata changes and corpus updates all invalidate eval assumptions. Re-run the retrieval eval first (06.10): if recall@k dropped, nothing downstream matters. Then re-run the RAG eval on dev (span labels survive re-chunking, chunk-id labels don't; 06.10, 2.7) and re-validate the freshness cases against the new corpus version. Treat embedding-model swaps like model swaps: same eval set, paired comparison, CI, and remember that vectors and queries must stay in the same embedding space or retrieval silently degrades (06.1). 10A.6, 4.6 adds the oracle layer to make the attribution explicit, and the playbook is 10A.8, 8.3.
Part 7: Error analysis — the failure taxonomy#
Metrics tell you that something is wrong; error analysis tells you what. The routine, borrowed from 06.10, 5.2 and extended one level up, is kept here in short form. The full loop (the taxonomy with its CaseResult signatures, the regression suite and human evaluation protocols) is 10A.6, Part 9, which you will meet later in the path.
7.1 Classify every failure by pipeline stage#
For each low-scoring or flagged case, use the CaseResult fields and three set differences to place the failure:
- Retrieval miss:
gold − retrievedis non-empty. The fix lives in 05 (parsing and chunking), 06 (index and embedding model) or 07.3 (query rewriting). - Ranking or assembly loss: gold was retrieved but is not in
context_chunk_ids(retrieved − context). The fix lives in 07.2 (k, assembly) or 07.4 (context formatting). - Had it but did not use it: gold is in the context, yet faithfulness or correctness is low (
gold ∩ context − citedshows what was ignored). The fix lives in the grounding prompt and model choice (07.4), or in the citation layer (07.5) whencitation_p/ris low.
Three more classes come from other fields: abstention failures (answered_unanswerable or abstained_answerable; the fix is the sufficiency threshold and abstention prompt in 07.4), judge disagreement (the metric is low but a human says fine, or the reverse; fix the judge prompt and the calibration set) and pipeline errors (__ERROR__ in answer_text; timeouts and malformed output, 03.8). Three set differences, three different owners. The full table of signatures and owners is 10A.6, 9.2.
7.2 The "read 50 traces" routine#
Once per eval cycle (weekly in production, per milestone offline), pull the 50 worst cases by a rotating criterion: lowest faithfulness, flagged abstention failures, judge-human disagreements, and a random sample of mid-scorers (the mid-scorers hide systematic bias). For each, read the trace, not just the score (question → retrieved ids and scores → context ids → prompt → answer → citations → judge verdicts; the Trace record from 07.1 exists for exactly this). Classify it into the list above, tally counts per class, and route the fixes to the owning module. Tag the diagnosed cases source: production-analysis so they stay in the set as regression tests. The loop is drawn in 10A.6, 9.1 and the regression suite is 10A.6, 9.3.
7.3 Dashboards and drift#
Module 11A owns the observability platform; this is the metric list for the dashboard. Track per-type metric trends over time (drift in one type signals a targeted regression, drift everywhere signals a systemic change such as a model, corpus or prompt update), the failure-class counts per week (a rising "retrieval miss" share after an ingestion run points at the pipeline, not the prompts), judge-vs-human agreement on a rolling calibration sample (if κ degrades, your judge is drifting and all judge metrics are suspect), and eval-set coverage, the share of production queries matching an eval type (a growing "unmatched" share means the set no longer represents reality; 06.10, 8.5). The drift taxonomy and how to measure it are 10A.9, Part 5.
07.10 owns the full failure-mode catalogue and the debugging playbook; this section is the measurement-side loop that feeds it.
Part 8: Online evaluation#
Deep-dive
Offline evals measure the cases you thought of; online evals measure the ones users actually hit. The full treatment is 10A.9: the signals (Part 2), A/B tests (4.1), shadow mode (4.3), drift (Part 5) and closing the loop (Part 6). Module 11A owns the observability platforms. The RAG-specific points to carry forward:
- Signals. Thumbs up/down (directional only: self-selected and sparse), citation clicks (high citation engagement with low thumbs-down can mean citations build trust even when answers are imperfect), reformulations and "I don't know" follow-ups (the strongest cheap signal; 06.10, 8.1), escalations to a human (the highest-severity signal, always mine them into eval cases) and the zero-result or empty-context rate (a corpus gap, a filter bug or over-aggressive abstention).
- Shadow traffic is the RAG-specific superpower: run the candidate pipeline (new prompt, retriever or model) on live queries in parallel, log its would-be answer and scores, but serve the production answer. You get real-distribution evaluation with zero user risk, at double inference cost for the shadowed fraction.
- A/B tests follow the usual rules (06.10, 8.3). For RAG, guardrail the abstention rate: a prompt change that quietly doubles "I don't know" answers tanks satisfaction without touching faithfulness.
- Drift has three RAG flavours: corpus drift (documents change, so freshness cases rot), query drift (users ask new things, so eval coverage gaps open) and judge drift (the judge model or prompt changed, so all historical comparisons are invalid). Pin judge versions in run records (4.2) so drift is detectable rather than mysterious.
The feedback loop closes here: production failures → labelled eval cases → offline regression tests → fixes verified on the same harness → shadow or A/B for the next change. That loop is the production RAG operating model; 07.11 owns its infrastructure.
Decision table#
The fast triage when a run says something regressed — symptom first, then the cheapest check that isolates the stage:
| Symptom in the run | Check first | Likely owner |
|---|---|---|
| Retrieval metrics green on the 06.10 harness but faithfulness/correctness low | Oracle-context test — does the generator fail even with gold chunks? (1.3, 10A.6, Part 2) | Generation: 07.4 prompt, model choice |
gold − retrieved is non-empty |
Retrieval side, not the generator | 05 chunking, 06 index/embedding model, 07.3 query rewriting |
Gold retrieved but missing from context_chunk_ids |
k, token budget, dedup, filter trims | 07.2, 07.4 context assembly |
| Faithfulness low with gold in context | Read the judge's per-claim verdicts; check the grounding prompt | 07.4, judge calibration (4.4) |
| Correctness low but faithfulness high | Audit the labels — the reference may be underivable from the corpus | 3.2 |
Many answered_unanswerable flags |
Abstention threshold / sufficiency gate too lax | 07.4, 4.5 |
Many abstained_answerable |
Threshold too strict, or retrieval returning noise | 07.4 calibration, 07.2 retrieval quality |
| Judge scores disagree with human spot-checks | Cohen's κ on the calibration split; judge prompt/version | 4.4–4.5, 10A.5 |
Judge columns all —, or judge_errors flags in the report |
Judge crashed or returned malformed JSON — run_eval records judge_error per case |
Judge wiring / provider call |
| Scores not comparable across runs | dataset_version/sha, judge_version, pipeline versions in run_meta |
3.4 |
| Need a per-commit CI gate but judges are slow or costly | Deterministic metrics + cached judge in CI; full judge gate on milestones | 6.3, 4.6, 10A.8, 3.1 |
Failure gallery#
The ways evaluating RAG goes wrong — eval-side anti-patterns that produce confident, wrong conclusions. (The pipeline failures these evals are meant to catch are 07.10's catalogue.)
| Failure | What you see | Root cause | Fix |
|---|---|---|---|
| Composite-score gating | one "RAG score" in CI; faithfulness up while correctness down looks like progress | averaging metric families hides which stage regressed | report families separately, per type, with CIs (1.1, 6.2) |
| Tuning judge prompts on the test split | test scores creep up, then collapse on fresh data | the test set became a dev set — overfitting with extra steps | dev iterates, calibration calibrates judges, test verifies once (3.4) |
| Uncalibrated judge shipped to CI | judge metrics drift from human judgement, silently | κ never measured; judge treated as objective | calibrate on ~50–100 human labels, track κ, recalibrate on judge/generator change (4.4, 10A.5) |
| Same-family judge and generator | faithfulness suspiciously high | self-preference bias — the judge shares the generator's blind spots | different model family as judge + human calibration sample (4.5, 10A.4, 4.4) |
| Synthetic-reference self-grading | correctness ≈ perfect, real answers wrong | LLM-written references graded by an LLM judge — circular validation | human-review references; keep a human-written anchor set (2.4, 3.5) |
| Abstention convention mismatch | two tools report different abstain-acc on the same run | different scoring conventions, undocumented | state the convention (2.6) and record it in run_meta; this harness scores only expect-abstain-or-abstained cases |
| Judging pipeline errors | faithfulness mean polluted by __ERROR__ stubs |
crash results sent to the judge — wasted spend, garbage scores | run_eval skips judging __ERROR__ results and marks them pipeline_error (5.4) |
| Judge scores treated as ground truth | ship/no-ship decisions on 0.02 deltas | judge variance and bias ignored; no intervals | CIs via compare_runs, κ tracking, judge scores as estimates (4.5, 6.2) |
| Eval-set version drift | scores incomparable month over month | dataset/judge/pipeline versions unrecorded | dataset sha + run_meta sidecar + judge_version in every run record (3.4) |
| Trivially-out-of-domain unanswerables | abstention looks great; corpus gaps undetected | questions obviously outside the domain — the system abstains for the wrong reason | plausible in-domain unanswerables: unwritten policies, nonexistent products, uncovered date ranges (3.2, 3.3) |
| Scoring rendered text for citations | citation metrics noisy, fake failures | the eval parses [n] markers out of prose — parsing bugs become metric bugs |
score the structured Answer.citations, not rendered text (2.5) |
| Oracle test skipped | months tuning the retriever while the generator was broken | stages never isolated; one opaque end-to-end number | run the oracle-context test per major change (1.3) |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A high faithfulness score means the answers are good." | Faithfulness only checks support-by-context. A wrong-but-consistent answer scores perfectly; correctness needs a reference or expected facts. |
| "The LLM judge is objective." | Judges have verbosity, position, self-preference and sycophancy biases, plus plain variance. Calibrate against humans (Cohen's κ) and use a different model family than the generator. |
| "We need reference answers for every question." | Expected-facts lists, reference-free relevance procedures and abstention labels cover most cases; prose references are the expensive exception, reserved for cases that need them. |
| "Retrieval metrics predict answer quality." | They bound it — the answer can only come from retrieved context — but say nothing about whether the generator used it well. Measure both stages. |
| "If the answer cites a source, it's grounded." | Citations can be invented, misattached or decorative. Citation precision/recall plus entailment checks (07.5) are the metrics; the citation's presence is not evidence. |
| "One composite 'RAG score' is enough for CI." | Composites hide which stage regressed and let gains in one metric mask losses in another. Report families separately, per type, with CIs. |
| "Synthetic eval questions are free ground truth." | They leak vocabulary (lexical search looks artificially good), skew easy, and LLM-generated references share the generator's blind spots — the self-grading loop. Keep a human-written anchor set. |
| "OpenAI offers a managed evals product." | It did. The Evals platform was deprecated on 3 June 2026 and shut down on 30 November 2026, graders included (10A.10, 2.5). The migration path OpenAI documents is promptfoo. |
| "More retrieved context always helps the answer." | Past a point, irrelevant chunks dilute attention, give the judge more rope, and cost tokens — k and context budget are ablation dimensions, not defaults. |
| "The eval set is a one-time artefact." | Labels rot (freshness), coverage drifts (new query types), and judges change meaning. Version the set, grow it from production failures, and re-validate on corpus updates. |
| "If offline eval is green, production is fine." | Offline evals cover the cases you imagined. Online signals (thumbs, reformulations, escalations) cover the ones users actually hit — keep both loops running. |
| "An abstaining system is a failing system." | On unanswerable cases abstention is the correct answer; the metric is abstention accuracy, not abstention rate. A system that never abstains isn't confident — it's dangerous. |
Key takeaways#
- Evaluate in stages. Retrieval metrics (06.10) are cheap and deterministic; generation metrics need judges or human labels. The oracle-context test separates "retrieval-bound" from "generation-bound" before you tune anything.
- The metric families: context precision/recall (was the right context retrieved and kept), faithfulness/groundedness (are claims supported by context), answer relevance (does it address the question), answer correctness (is it right, vs reference/expected facts), citation precision/recall (07.5), abstention accuracy, safety, latency/cost. Faithfulness ≠ correctness ≠ relevance — measure all three.
- Faithfulness is a procedure, not a vibe: extract claims, verify each against the retrieved contexts, score supported/total. Two-stage (extract → verify) buys auditability and enables NLI/HHEM verification at scale.
- Build the eval set like a dataset, not a demo: reference answers derivable from gold chunks, span-level gold labels, plausible unanswerables, adversarial/multi-turn/freshness types, dev/calibration/test splits, versioned with content hashes.
- Judges need calibration: different model family than the generator, rubric prompts with examples, Cohen's κ against ~50–100 human labels, versioned prompts, and cost controls (sample judging, Batch API, smaller judge models, judgement caching).
- Own the harness or understand the library.
docs_qa/eval/is about 700 lines of stdlib: dataset schema, deterministic metrics, injectable judges, runner with paired bootstrap comparison, markdown report. Ragas, DeepEval, TruLens, promptfoo, Phoenix, LangSmith, Braintrust, MLflow and Inspect AI each wrap the same loop with different trade-offs — and OpenAI's managed Evals platform was shut down on 30 November 2026. - Experiment honestly: one ablation at a time, same eval set and judge version, per-type breakdowns, paired diffs with bootstrap CIs, cheap deterministic gates in CI and expensive judge gates on milestones.
- Error analysis is a routine: classify failures by pipeline stage using set differences (
retrieved − context,gold − retrieved), read ~50 traces per cycle, route fixes to the owning module, feed cases back into the set. - Close the loop online: thumbs, citation engagement, reformulations and escalations feed new eval cases; shadow traffic evaluates risky changes on real distribution; A/B tests confirm what offline eval predicted; drift monitoring watches corpus, queries and judge versions.
- Public benchmarks are sanity checks, not your eval set. RGB, CRUD-RAG and RAGChecker measure robustness scenarios on fixed corpora — useful for comparing generators and borrowing failure taxonomies, never a substitute for labels on your own data.
- This is the first pass. The full treatment of generation metrics, stage-isolating oracle experiments, dataset design, tools, statistics and the error-analysis loop is 10A.6; come back to it when you reach Module 10A.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| RAG triad | The three core judge-scored RAG dimensions: context relevance, groundedness/faithfulness, answer relevance (TruLens terminology) |
| Faithfulness / groundedness | Fraction of an answer's claims supported by the retrieved context |
| Claim extraction / verification | The two-step faithfulness procedure: break the answer into atomic claims, then check each against context |
| NLI-style verification | Treating claim checking as natural language inference: context = premise, claim = hypothesis, entailment/neutral/contradiction |
| Answer relevance / relevancy | Whether the answer addresses the question asked — Ragas implements it by generating questions from the answer and comparing embeddings |
| Answer correctness | Whether the answer is right — via exact match, expected-facts checklists, or a reference-answer judge |
| Expected facts | An enumerable list of facts an answer must contain — a paraphrase-robust alternative to prose references |
| Citation precision / recall | Fraction of cited claims that are supported / fraction of claims needing citation that have one |
| Abstention accuracy | Correctness of refuse-vs-answer decisions over cases where abstention was expected or exercised; plain correct answers are scored by correctness metrics instead |
| Abstention curve | Answer accuracy vs abstention rate as the threshold sweeps — the calibration trade-off |
| Oracle-context test | Bypassing retrieval to hand the generator gold chunks — isolates generation-bound from retrieval-bound failures |
| Eval case / case_id | One labelled test instance (question + expected behaviour + labels) and its stable identity |
| Gold chunk ids | The chunks that should reach the context for a case — span-labelled upstream so re-chunking doesn't orphan them |
expect_abstain / partial_ok |
Case labels: correct behaviour is refusal; a partial answer is acceptable |
| Judge calibration | Measuring judge-vs-human agreement (Cohen's κ) on a labelled sample before trusting judge metrics |
| Self-grading loop | Synthetic references graded by an LLM judge sharing the generator's blind spots — circular validation |
| Shadow traffic | Running a candidate pipeline on live queries without serving its answers — real-distribution eval at zero user risk |
| Paired comparison / bootstrap CI | Per-case metric differences between two runs, with a resampled 95% confidence interval |
| Regression gate | An automated check (deterministic metrics per commit; judge metrics per milestone) that blocks bad changes |
| Failure taxonomy | Classifying eval failures by pipeline stage: retrieval miss, assembly loss, generation, citation, abstention, judge, error |
| Judgement cache | Reusing judge outputs keyed by everything the judge sees (case, answer, context ids, judge version) — CachedJudge in the harness, path= persists to JSON |
| Context precision (RAG sense) | Whether relevant chunks reached the context ranked near the top — rank-weighted verdicts per retrieved context (Ragas ContextPrecision) |
| Context recall (RAG sense) | Fraction of reference-answer claims attributable to the retrieved context — bridges retrieval and completeness |
All terms are also collected in the glossary.
Exercises#
- Run the smoke test. Create the
docs_qa/eval/package from Part 5, putsmoke_eval.pyinsidedocs_qa/eval/(it uses flat imports — noPYTHONPATHneeded) and runpython smoke_eval.pyfrom there. It writessmoke_results.jsonl+smoke_results.meta.jsonbeside itself. Then changeFakeJudge's scores and predict how each report column moves before running. - Extend the fixture. Add a multi-hop case (
turnspopulated,gold_chunk_idswith two chunks) and afilteredcase withfilters={"tenant": "acme"}. Runrun_evaland check which metrics populate and which stayNone— can you say why for each? - Break the citation metric. Give
e01a cited id that isn't ingold_chunk_idsand re-run. Which columns change, and does the flag section catch it? Now removegold_chunk_idsentirely — what happens to citation columns and why? - Write a faithfulness judge prompt variant. Take
FAITHFULNESS_PROMPTfromjudges.py(5.4; the full production-shaped version is 10A.6, 3.1) and add a rule for numeric claims ("any number in the answer must appear verbatim or as an equivalent in context"). Wrap it in anLLMJudge-compatible callable with a canned JSON response and verifyfaithfulnessparses. - Compute κ by hand. Using the
kappa.pydemo, construct two label lists with κ < 0 (worse than chance) and one with κ = 1.0. What do the raw agreement percentages look like in each case — why is κ necessary? - Design an ablation. Pick one module-07 component (k, reranker, query rewriting, grounding prompt). Write the eval plan: which split, which metrics, which
typerows you expect to move, and what CI width would convince you. - Failure taxonomy drill. Take the smoke run's
e04(answered an unanswerable case) and trace it through the 7.1 list (the full table is 10A.6, 9.2): which class, which set differences would you check, which module owns the fix? - Build five eval cases. From the Module 05/06 corpus (handbook/help-centre/tickets/contracts), write five
eval_cases.jsonllines covering: one factoid, one unanswerable, one adversarial (injection text in a "document"), one multi-hop, one freshness case withcorpus_version. Label them as 3.1 and 3.2 specify (the full question-type taxonomy is 10A.6, 4.2). - Prove the cache works. Wrap
FakeJudgeinCachedJudge(path="judge_cache.json")and runrun_evaltwice. Instrument the inner judge (count__call__invocations) — how many judge calls does the second run make, and whichCaseResultfields are identical between runs? Then change one answer text and re-run: which cases get re-judged and why? What happens if you change theversionattribute of theCachedJudgeitself (judge.version = "fake-2.0")? - Context recall by hand. Take
e01: its reference answer has three implicit claims (1.5 days/month, 18-day cap, full-time employees). Write the claim list aContextRecall-style judge would extract, then decide for each whethercontext_chunk_ids=["handbook-001"]supports it. What would the score be ifhandbook-001contained only the accrual rate but not the cap?
Check yourself#
- Why must retrieval and generation be evaluated separately, and what does the oracle-context test tell you?They're different failure domains with different metrics, costs and owners: retrieval is deterministic and cheap, generation needs judges. The oracle test (hand the generator gold chunks) reveals whether failures are retrieval-bound (oracle answers good, e2e bad) or generation-bound (oracle answers bad too).
- What three things does a faithfulness score decompose into, and why is claim-level verification better than a single yes/no judge call?Claims extracted from the answer; each claim checked for entailment by the retrieved contexts; score = supported/total. Claim-level gives an audit trail (the failing claims are debugging gold) and degrades gracefully; a single verdict hides which claim failed and is noisier.
- A case has
expect_abstain: trueand the system answers anyway. Which metric catches it, whichAbstentionOutcome.kinddoes it produce, and why must unanswerable cases be excluded from correctness averages?Abstention accuracy — theanswered_unanswerableoutcome kind. Excluded from correctness because there's no correct answer to be correct about — scoring it would conflate abstention behaviour with factual accuracy. - Your judge gives faithfulness 0.95 but users complain about wrong answers. Name three judge failure modes that could explain the gap and one mitigation for each.Self-preference (same family grades its own style higher — use a different family), verbosity bias (longer answers score higher — rubric penalising padding), sycophancy to confident tone (assertive wrong answers beat hedged right ones — claim-level faithfulness, not tone). Also variance (run k times, take median) and context truncation in the judge prompt.
- What's the difference between
retrieved_chunk_idsandcontext_chunk_ids, and which failure class doesretrieved − contextreveal?retrieved_chunk_ids= whatsearch()returned;context_chunk_ids= what actually entered the prompt after assembly/trim/dedup/filter. The difference reveals context-assembly losses — retrieval succeeded but the chunk never reached the model. - Why prefer
expected_factsover a prosereference_answerfor factoid cases?They're paraphrase-robust: "must contain net-30 and a 12-month liability cap" survives any wording, while a prose reference invites the judge to grade style/similarity and produces false negatives on valid paraphrases. - List the OpenAI Evals platform's deprecation dates as of November 2026, and what OpenAI's own migration guide recommends.Deprecated June 3, 2026; read-only Oct 31, 2026; dashboard+API shutdown Nov 30, 2026; graders included. OpenAI's migration guide points to promptfoo.
- A colleague proposes one composite "RAG score" as the CI gate. Give three reasons that's a bad idea.(a) It hides which stage regressed — faithfulness up while correctness down looks like progress; (b) gains in one metric mask losses in another; (c) a single number can't carry per-type breakdowns, CIs, or cost/latency context needed for ship decisions.
- Your dev-set faithfulness improves +0.02 after a prompt change, but the bootstrap CI is [-0.01, +0.05]. What do you conclude and what do you do next?Inconclusive — the CI includes zero, so the +0.02 is indistinguishable from noise. Don't ship on it; grow the eval set, widen the judge sample, or decide on cost/latency tiebreakers.
- Why must the judge be a different model family than the generator, and what statistic do you compute to check judge-human agreement?Self-preference bias: a judge shares its own family's blind spots and style preferences. Compute Cohen's κ between judge and human labels on the calibration split — κ > ~0.8 strong, 0.6–0.8 moderate, <0.4 poor.
- What are the three RAG-specific drift types, and which run-record field detects judge drift?Corpus drift (documents change → freshness labels rot), query drift (new user intents → eval coverage gaps), judge drift (judge model/prompt version changed → historical comparisons invalid).
judge_versionin the run record detects it. - For a "how do I reset my password?" how-to question, which metrics apply and which don't — and why?Faithfulness (is the procedure supported by retrieved chunks), citation precision/recall (do steps cite the right articles), abstention accuracy if some variants are unanswerable, answer relevance (does it give steps vs a definition), latency. Correctness vs expected_facts applies if the steps are enumerable; token-F1 is weak on prose procedures.
- What does shadow traffic let you evaluate that A/B tests can't, and what does it cost?Shadow traffic evaluates on the real production query distribution with zero user risk — A/B only measures the fraction you route and exposes users to the candidate. It costs double inference for the shadowed fraction.
- When re-chunking the corpus, which eval artefacts survive and which must be rebuilt — and what labelling practice makes that possible?Span-level gold labels (locations in source docs, not chunk ids) and
corpus_versiontags survive re-chunking; chunk-id labels orphan. Reference answers and expected_facts survive if still derivable from the corpus; freshness cases need re-validation against the new version. - Faithfulness is 0.95 but context recall is 0.4 on the same cases. What does that combination indicate, and which pipeline stage owns the fix?The generator is faithfully reporting a thin context — most reference-answer claims never reached the prompt. That's a retrieval or context-assembly failure (check
gold − retrievedandretrieved − contextset differences), not a generation failure; faithfulness can't see it because the answer only claims what little context it got.
Further resources#
- Ragas documentation and the RAGAS paper (arXiv:2309.15217) — the metric definitions this lesson uses
- TruLens documentation — the RAG triad and feedback-function design
- DeepEval documentation — pytest-style LLM evals
- promptfoo documentation — CLI/YAML evals and red teaming (OpenAI announced on 9 March 2026 that it is acquiring the company; the project remains open source)
- Inspect AI documentation — the UK AISI eval framework
- LangSmith evaluation docs and openevals
- MLflow genai evaluation docs — built-in judges incl.
Correctness,RetrievalGroundedness - Arize Phoenix documentation — OTel-native tracing + evals
- Braintrust documentation — hosted eval/observability platform
- Vertex AI Gen AI evaluation service (now "Gemini Enterprise Agent Platform")
- OpenAI deprecations page — the Evals platform sunset dates
- Anthropic eval guidance and the Claude Cookbook evals recipe
- Lesson 06.10 — the retrieval-side harness this lesson extends
- Lesson 10A.2 — synthetic eval-set generation
- Lesson 10A.6: the full treatment of RAG evaluation: generation metrics, oracle experiments, dataset design, tools, statistics and the error-analysis loop
- Lessons 10A.4 and 10A.5: judge design and judge calibration; 10A.9: offline and online evaluation; 10A.10: eval platforms and benchmark literacy
- Module 10A — judge methodology, datasets and regression testing in depth
← 07.8 — Advanced RAG: Agentic RAG, GraphRAG and Beyond | Module 07 overview | 07.10 — RAG Failure Modes and Debugging →