▚ The AI Engineer's Field Manual
Module 07 · Act III — The GenAI Core

Evals & Error Analysis — The Skill That Gets You Hired

"You'd never merge code without tests. Teams merge prompt changes blind every single day."

~7 hours Builds on: Module 06 Tools: Ragas · DeepEval · promptfoo · Langfuse/LangSmith Job-spec line it unlocks: "LLM and RAG evaluations using RAGAS, DeepEval, and LangSmith Evaluators"

01 · The hookThe Demo Was Great. Production Has Questions.

An eval is a test suite for something that has no right answer. It is also the single skill that most separates people who ship AI features from people who demo them.

Field report · Client memo

"The board demo was the best ten minutes of my quarter. Our support assistant answered every question flawlessly — we got budget approval on the spot.

Week two in production, sales forwarded me a customer email: our assistant had promised a 25% loyalty discount for annual prepay. We have no such policy. Legal said honor it — that one renewal cost us $18,400.

Here's the part that keeps me up at night: my team 'fixed' the prompt six times in three weeks. When I ask whether version 7 is actually better than version 1, the honest answer is a shrug.

Two engineers, three weeks, roughly 240 hours — and we cannot state a single number that got better. We're not doing engineering anymore. We're doing prompt roulette."

— Viktor Sterling, CTO at "SaaSify"

You built exactly this system in Module 06: an LLM-backed assistant with tool calls and structured outputs. It works — you watched it work.

But "I watched it work" is a statement about the five inputs you happened to try, not about the ten thousand your users will. Viktor's team has no measurement, so every prompt change is a bet with no scoreboard.

They can't tell an improvement from a regression, they can't tell the CEO the invented-discount bug is fixed, and they definitely can't tell the next enterprise customer's lawyers.

Before the fix has a name, look at what three weeks of prompt roulette actually bought SaaSify. Every number in the picture below is from Viktor's memo.

1 SIX PROMPT CHANGES IN THREE WEEKS v1 ? v2 ? v3 ? v4 ? v5 ? v6 ? each tick is a prompt rewrite; each ? is the score nobody measured 3 THE SCOREBOARD WHAT GOT BETTER 0 measured numbers 2 WHAT THE THREE WEEKS COST 2 engineers × 3 weeks ≈ 240 engineer-hours 1 invented 25% discount, honoured = $18,400 6 prompt versions shipped on a shrug
Fig. 7.0b — The seed of this module, drawn. Three weeks of work produced six prompt versions, a $18,400 invoice and exactly zero numbers that anybody can compare.
  1. Six changes, six question marks. Each tick on the line is a prompt rewrite that shipped. Above each one sits a question mark, because nobody scored the version before it or the version after it. Six unmeasured changes in a row is not six improvements; it is a random walk.
  2. The bill. Two engineers for three weeks is roughly 240 engineer-hours. The invented 25% discount cost $18,400 in one honoured renewal. Both numbers are real spending, and neither bought a fact.
  3. The empty scoreboard. This is the box the whole module fills in. Every tool from here on — the labeled dataset, the code asserts, the judge, the CI gate — exists so that this box holds a number Viktor can say out loud to a board.

The fix has a name: evals — systematic evaluation of an LLM system against a dataset of real cases, with pass/fail criteria you can defend. This is the module the 2026 hiring market cares about most.

Per the market research: evaluation shows up in roughly 40% of AI-engineer postings, real JDs now demand "LLM and RAG evaluations using RAGAS, DeepEval, and LangSmith Evaluators" verbatim, and the single strongest differentiator between average and top candidates is shipped eval harnesses with measurable outcomes.

Interviewers have learned that anyone can demo an LLM feature; the person who can prove it works is rare. This module makes you that person.

You already know this

Evals are unit tests plus monitoring for a nondeterministic dependency. You already run this playbook against flaky third-party APIs: pin the contract with tests, watch production, alert on drift. An LLM is a brilliant, flaky dependency — same playbook, one twist: outputs vary, so some "tests" are statistical rather than exact. Your test pyramid transfers almost 1:1:

The skill transfer: test pyramid → eval pyramid
You know (SWE)You're learning (LLM)
Unit tests (fast, deterministic)Code asserts on outputs: JSON validity, citations, PII, length
Integration tests (slower, broader)LLM-as-judge scoring against a rubric
Manual QAHuman review — the ground truth that calibrates the judge
CI gate on red testsCI gate on eval regression vs baseline
Reading bug reportsError analysis on production traces

02 · The intuitionThe Flywheel and the Pyramid

Viktor's memo is on your desk: six prompt rewrites in three weeks, two engineers, roughly 240 hours, one invented 25% discount that cost $18,400, and not one number that got better. Nothing on that list can be fixed until SaaSify can measure a prompt change. So before any tool, you need two things: the shape of the machine that does the measuring, and an answer to “who does the grading?” Those are the two pictures in this section.

Two pictures organize everything in this module. The first is a loop: evals are not a one-time report card, they're a flywheel. You read real traces, name what's failing, turn those failures into a labeled dataset, score every change against it, gate merges on the score — and the shipped improvements generate better traces for the next lap. Every lap compounds: your dataset gets harder, your metrics get sharper, your system gets provably better. Teams without the loop just orbit the same bugs forever.

1 2 3 4 Production traces one-line notes Error analysis pass/fail labels Labeled dataset score every change Eval report thresholds CI gate block or merge Ship the change new real traffic the flywheel: every lap compounds
Fig. 7.1 — The eval flywheel: real traces become failure notes, notes become a labeled dataset, the dataset scores every change, the score gates CI, and shipped changes generate the next round of traces. Error analysis (accented) is the step teams skip — and the one that makes the rest work.
  1. Where it starts: real traffic. Not test questions you invented, and not the demo script. The loop is fed by what users actually sent, because those are the only inputs that contain the failures you have not imagined yet.
  2. The accented box is the one that gets skipped. Error analysis is a person reading traces and writing one sentence per bad one. It has no dashboard and cannot be delegated. Everything to the right of it — the dataset, the metrics, the gate — is built out of the names invented in this box, so a team that skips it builds a suite for imaginary failures.
  3. The gate is the only box with teeth. Every other box produces information. This one produces a decision: the merge happens or it does not. A loop without this box still tells you things; it just cannot stop anybody.
  4. The arrow that closes the loop. Shipping is not the end. The change goes live, real users hit it, and their traffic becomes the traces at the top of the next lap. This is why it is a flywheel and not a checklist: each lap's dataset is harder than the last one's.

The table below names files you have not met yet. That is fine, and you are not expected to know them. Every one is built and walked line by line in sections 03, 04, 06 and 07. Read the table once now so the loop feels concrete, then come back whenever a box in Fig. 7.1 feels abstract.

Fig. 7.1 again, concretely: each stage of the flywheel as it exists in this module's code
StageIn the hand-built version (sections 03–04)In the production build (sections 06–07)What flows out
Production tracesA traces.jsonl export, sampled by sample_traces.pyLangfuse or LangSmith capturing every request, plus the signals stored by feedback_loop.py100 real interactions in error_analysis.csv, one row each
Error analysisYou, reading every row and typing a one-sentence note in the note columnThe same reading, weekly, over the triage queue and a random sampleA failure-mode table with counts
Labeled dataseteval_cases.jsonl: a pass/fail label, a failure mode and a reason per caseThe same file, grown by promote() from triaged user feedback100 to 500 cases every grader is scored against
Code assertstest_asserts.py: citation, discount, PII and length checks under pytestThe same tests, run as the code-asserts job in evals.ymlRed or green in seconds, for free
LLM-as-judgejudge.py: a rubric, a structured verdict and validate_judge()The llm-rubric assert in promptfooconfig.yaml, or a DeepEval GEval metricA pass/fail verdict per case, trusted only after validation
Eval reportThe pass rate and per-mode counts printed by mini_evals.pyresults.json from promptfoo, with prompt v1 and v2 side by sideA number you can compare with last week's
CI gatesys.exit(1) at the end of mini_evals.pyThe llm-judge job in evals.yml, red on any failed assertA merge that is blocked or allowed
Ship the changeBy hand: you merge and watchDeploy, then the dashed arrow in Fig. 7.4 carries new traces and new feedback back to the topThe next lap's traces

Now the same loop with SaaSify's own numbers written into it. Nothing here is a placeholder: every count is one this module produces.

Production traces 100 sampled by sample_traces.py (seed 7) you read every one Error analysis 38 bad traces, one sentence written on each cluster the notes Failure taxonomy 6 named modes · invented_policy 14 (37%) freeze into a file Labeled dataset 100 cases: pass/fail + mode + reason split by who can grade Two graders 3 code asserts, free · judge ≈ $0.30 / 100 cases run on the pull request CI gate 0 failed asserts, or the merge button stays grey 1 2 3 4 the fix ships, and its traffic is next month's traces
Fig. 7.1b — The flywheel with the counts on it. 100 traces in, 38 of them bad, 6 named modes, 100 labeled cases, two graders, one gate. Every later section of this module fills in one of these boxes.
  1. 100, not all of them. A week of production traffic is far more than anyone will read, so the script takes a random 100 with a fixed seed. The seed matters: the same 100 come back tomorrow, so the notes you wrote today still belong to the same rows.
  2. 38 bad, one sentence each. Reading the 100 produced 38 one-sentence notes. This box is the accented one because it is the step teams skip, and skipping it means every box below it is built on guesses about what goes wrong.
  3. Two graders, two budgets. The code asserts cost nothing and run on every commit. The judge costs roughly thirty cents per hundred cases and runs before a merge and overnight. Which failure goes to which grader is decided by the taxonomy two boxes above.
  4. The return arrow is the flywheel. Without it this picture is a checklist you run once. With it, the changes that pass the gate generate new traffic, that traffic becomes next month's 100 traces, and the failures those reveal are ones this month's suite never knew about.

The second picture answers "who does the grading?" You can't afford a human on every output, and you can't trust a regex to detect a hallucinated refund policy. So you layer graders like a test pyramid — cheap and deterministic at the base, judgment in the middle, humans at the top. Each layer is trusted only because the layer above calibrates it: the judge is validated against human labels, and code asserts are chosen because error analysis (a human activity) proved those failure modes exist.

1 2 3 Human review — weekly, expensive the ground truth that calibrates everything below LLM-as-judge — nightly + pre-merge, ¢ per case judgment failures: groundedness, tone, relevance Code asserts — every commit, free mechanical failures: format, citations, PII, length
Fig. 7.2 — The eval pyramid. Push every check as far down the pyramid as it can go: a failure mode that a regex can catch should never burn judge tokens, and a failure mode a judge can catch should rarely need a human.
  1. The tip: human review. Small on purpose. Humans are the slowest and most expensive grader and the only one whose verdict is not being checked by something else. You spend them on the weekly read of disagreements and on the labels everything below is measured against.
  2. The middle: the judge. A second model reading the answer against the context, for cents a case, minutes a run. It is the only layer that can grade meaning, and the only layer that has to earn its place by being validated against the tip above it.
  3. The base: code asserts. Widest, cheapest, fastest. A regular expression that looks for a citation gives the same verdict every time, costs nothing and runs on every commit. Anything that can be pushed down here should be: judge tokens spent on a shape a pattern could have checked are simply wasted.

Read the traces.

Name the failures.

Assert what code can catch.

Validate the judge before you trust it.

Gate the merge.

Read the traces: the 100 dots of Fig. 7.2b, one conversation each. Name the failures: the six coloured blocks in that grid, with their counts. Assert what code can catch: the free lane of Fig. 7.2d, 12 of the 38. Validate the judge: the kappa of Fig. 7.3c, which must beat the rubber stamp of Fig. 7.3d. Gate the merge: the accented box of Fig. 7.4, which is the only step that stops anything.

🧠 Brain power

Before reading on: suppose you use the same model as both the system under test and the judge — same provider, same version. What failure mode would you predict, and how would you detect it if it happened?

Reveal the answer

Self-preference bias: models systematically rate their own style of output more favorably, so the judge goes soft exactly where your system is weak — the errors they share are invisible to both.

You detect it the same way you detect any judge problem: validate the judge against human labels and look at the per-cell breakdown (§03, step 5).

A judge that misses many human-labeled failures — a high "missed" cell in the confusion matrix — is untrustworthy no matter which model it runs on. Mitigations: use a different model family for judging, or keep the same family but prove agreement on your labels anyway. Validation beats vibes about model choice.

03 · The methodLook at Your Data: The Six-Step Workflow

SaaSify now has a picture of the loop and nothing inside it. The first lap has to start with something real, so it starts with the traces their assistant already produced last week. This section is the six steps that turn 100 of those traces into 38 failure notes, six named failure modes, a labeled file, and a gate that stops the $18,400 answer from shipping twice. Step 1 is the step Viktor's team skipped six times.

This is the heart of the module. The workflow below is the one taught by Hamel Husain and Shreya Shankar in the breakout AI-evals course of 2025 (per the curriculum research, the course that moved evals "from the appendix to the spine" of every serious program), and it is what interviewers mean when they ask how you evaluate an LLM feature. It starts with an activity that feels almost embarrassingly low-tech — and it is the highest-leverage hour you will spend on any LLM system.

Step 1 — Look at your data. Personally. All of it.

SaaSify's logging system holds a full week of assistant traffic, far more than anyone will read. So you take 100 traces at random and read every one of them yourself. This is the hour that decides where the next three weeks go, and it is the hour Viktor's team never spent while they rewrote the prompt six times.

Collect 50–100 real traces — a trace is one full interaction: user input, retrieved context, tool calls, final output.

Put them in a spreadsheet or notebook, and read every single one, writing a one-sentence note on each bad one: "promised a discount that doesn't exist", "right answer, no citation", "sarcastic to an angry customer".

This is called open coding, borrowed from qualitative research. No dashboard, no delegation, no "sentiment score" — you, reading, writing notes. Every team that skips this step builds evals for imaginary failure modes and misses the real ones.

Step-by-step: what sample_traces.py does, in plain English
  1. Bring in json to read one JSON object per line, os to check whether a file exists, random to draw the sample, and pandas to write a spreadsheet.
  2. Fix the random seed to 7. The same seed gives the same sample every run, so the notes you write today still line up with the same rows tomorrow.
  3. If there is no traces.jsonl yet, write a three-line demo file so the script runs as-is. In real use you replace this block with an export from your logging system.
  4. Read the file back: one trace per line, each parsed from JSON into a dictionary.
  5. Draw a random sample of 100 traces, or every trace if there are fewer than 100. A hundred is enough to see patterns and few enough to read in one sitting.
  6. Turn each sampled trace into a row holding an id, the user's input, the output, and an empty note column. The note column is the point of the file: you fill it in by hand, one sentence per bad trace.
  7. Write the rows to error_analysis.csv with pandas, without the numeric index column, and print how many rows there are to read.
sample_traces.pyruns offline
# pip install pandas==2.2.*
# Pull a reproducible random sample of production traces into a spreadsheet
# for error analysis. A "trace" = one interaction: input, context, output.
import json
import os
import random

import pandas as pd

random.seed(7)  # same sample every run, so your notes stay attached to rows

if not os.path.exists("traces.jsonl"):
    # Demo fallback so this file runs as-is; replace with your real export.
    demo = [{"id": f"t-{i:03d}", "input": "Do you offer annual discounts?",
             "output": "Yes! 25% off annual prepay."} for i in range(3)]
    with open("traces.jsonl", "w", encoding="utf-8") as f:
        f.writelines(json.dumps(t) + "\n" for t in demo)

with open("traces.jsonl", encoding="utf-8") as f:
    traces = [json.loads(line) for line in f]

# 100 is the magic number: enough to see patterns, few enough to actually read.
sample = random.sample(traces, min(100, len(traces)))

rows = [{"id": t["id"], "user_input": t["input"], "output": t["output"],
         "note": ""}  # <- you fill this in: one sentence per bad trace
        for t in sample]

pd.DataFrame(rows).to_csv("error_analysis.csv", index=False)
print(f"Wrote {len(rows)} traces to error_analysis.csv — now go READ them.")

Step 2 — Axial coding: cluster notes into failure modes

You have 100 traces read and 38 one-sentence notes written, one per bad trace. Thirty-eight sentences are not a plan. This step turns them into six named failure modes with a count beside each one, which is the first moment anybody at SaaSify can say what the assistant is actually bad at, and in what order to fix it.

Now group the notes. Near-duplicate complaints merge into a named failure mode; aim for five to eight. This second pass is axial coding: you're building a taxonomy of how your system actually fails, with counts. Here's what SaaSify's 100 traces produced (38 had problems):

SaaSify assistant — failure-mode taxonomy from 100 traces
Failure modeCountShare of failuresExample note
invented_policy1437%"Promised a 25% loyalty discount — no such policy exists"
missing_citation924%"Correct answer but no source, agent can't verify it"
stale_data616%"Quoted the 2024 rate limits"
wrong_tone410%"Sarcastic reply to an angry enterprise customer"
format_broken38%"Markdown table leaked into a plain-text channel"
overrefusal25%"Refused a routine password-reset question"

Those six rows are easier to believe when you can see all 100 traces at once. One dot, one real conversation.

100 traces read by hand — 38 of them had a problem invented_policy — 14 dots · 37% of the failures · the $18,400 mode missing_citation — 9 dots · 24% stale_data — 6 dots · 16% wrong_tone — 4 dots · 10% · three weeks were spent here format_broken — 3 dots · 8% overrefusal — 2 dots · 5% no problem found — 62 dots 1 2 3 each dot is one real conversation
Fig. 7.2b — SaaSify's 100 read traces, coloured by failure mode. The dots are laid out in reading order, so each mode is one contiguous block and the block sizes are the counts in the table above.
  1. The first fourteen dots. These are the invented_policy failures: fourteen conversations in which the assistant stated a policy, price or discount that exists in no document. One of them is the 25% discount from the hook. Fourteen out of 38 failures is 37%, and this is the block that decides where the next sprint goes.
  2. The sixty-two faint dots. Most of the sample was fine. That matters in two ways. It means the assistant is not broken, so the fix is targeted rather than a rewrite. It also means a grader that says "pass" to everything would be right 62 times out of 100, which is the trap Cohen's kappa exists to catch.
  3. The four-dot block. wrong_tone is four dots, 10% of the failures. SaaSify's team spent three of their three weeks on tone. The picture is the argument: the effort went to the fourth-largest block while the largest one went unmeasured.

The counts are the strategy. SaaSify's team spent three weeks tweaking tone — a 10% problem — while invented_policy, the failure mode that costs actual dollars, sat unmeasured at 37%. Error analysis converts "the model is being weird" into a prioritized backlog.

Step 3 — Build the labeled dataset

The counts now say that invented_policy is 14 of the 38 failures, 37% of them. A count cannot be re-run, though, and Viktor's next prompt change needs something that can. This step freezes those traces into a file of labeled cases, so every future version of the prompt is scored on the same questions, by the same standard.

Turn traces — plus hand-written hard cases — into a dataset of 100 or more examples. Each one carries three things:

The reason field matters more than it looks. It forces the labeller to articulate the standard, and it becomes few-shot material for the judge later.

Include deliberate negatives — known-bad outputs — or you will never know whether your graders can catch anything.

How many cases is "100 or more"? Here is what each size buys, drawn on the measurement itself.

the true pass rate, 75% n = 20 56% to 94% ±19.0 pts n = 50 63% to 87% ±12.0 pts n = 100 67% to 84% ±8.5 pts n = 300 70% to 80% ±4.9 pts 1 2 3 0% 25% 50% 75% 100%
Fig. 7.2c — The labelled-example ladder. Each bar is the 95% range a single measurement can land in when the system's true pass rate is 75%, computed as 1.96 × √(0.75 × 0.25 / n).
  1. Twenty cases is a 38-point-wide bar. The system's true rate is 75%, yet one run of a 20-case suite can honestly report anything from 56% to 94%. That is why the senior engineer's "eyeball twenty and ship" cannot tell an improvement from a mood, and why the number 100 keeps appearing in this module.
  2. A hundred cases halves it. At n = 100 the same measurement lands between 67% and 84%. It is still not precise, but it is now tight enough to notice a real ten-point regression, which is exactly what the CI gate needs to do.
  3. The dashed line is the thing you never see. The true rate is fixed; only your reading of it moves. Every bar on this picture is centred on the same system. Nothing about SaaSify's assistant changes from the top row to the bottom row — only the number of cases you were willing to label.

"Can't I just eyeball twenty outputs and ship? I have shipped plenty of features on less."

— a senior engineer with a deadline on Friday

For the first hour, yes, and you should. Eyeballing outputs is Step 1 of this method; the only change is that you write one sentence per bad output instead of nodding. Where the plan breaks is the word "ship". Twenty outputs cannot tell you whether the assistant is right 60% of the time or 90%. The ladder just above puts a number on it: at n = 20, marker 1 in Fig. 7.2c, a reading of 75% honestly means anywhere from 56% to 94%.

The second break is next week. When someone changes the prompt again, your twenty outputs are gone, your impression of them is gone, and "is version 7 better than version 1" gets the same shrug Viktor's team gave. A labeled file can be re-run in a minute. A memory of twenty transcripts cannot.

The honest cost: a hundred labeled cases is a day or two of someone's attention, the suite goes stale as users find new ways to be confused (section 07 is about that), and it only measures the failures you thought to include. That is still a measurement. Twenty eyeballed outputs and a good feeling is not.

One JSONL line per case:

eval_cases.jsonl (excerpt)runs offline
{"id": "case-001", "input": "Do you offer discounts for annual billing?", "context": "Billing FAQ: annual plans are billed at 12x the monthly rate. No discount programs are currently offered.", "output": "Annual plans are 12x the monthly rate — no discount program exists. [doc:billing-faq-04]", "label": "pass", "failure_mode": null, "reason": "Declines to invent a discount and cites the billing FAQ."}
{"id": "case-002", "input": "Do you offer discounts for annual billing?", "context": "Billing FAQ: annual plans are billed at 12x the monthly rate. No discount programs are currently offered.", "output": "Yes — annual prepay comes with a 25% loyalty discount.", "label": "fail", "failure_mode": "invented_policy", "reason": "A 25% loyalty discount does not exist in any policy document."}
{"id": "case-003", "input": "How do I rotate my API key?", "context": "API docs: Settings, then API, then Rotate key. The old key remains valid for 24 hours.", "output": "Settings, then API, then Rotate key. The old key stays valid for 24 hours. [doc:api-keys-02]", "label": "pass", "failure_mode": null, "reason": "Correct steps, correct grace period, cited."}

Step 4 — Code asserts for the mechanical failures

The labeled file exists. Now split it by who can grade it. Two of SaaSify's six failure modes are pure pattern matching — missing_citation, 9 cases, and format_broken, 3 — and a regular expression grades those for nothing on every commit. Spend no judge tokens where a pattern will do.

Look at the taxonomy and split it. missing_citation, format_broken, PII leaks, and length problems are mechanical — a deterministic function can check them. These become ordinary pytest tests over recorded outputs: free, instant, zero flakiness, run on every commit. Note one test below is red on purpose — the embedded case a-03 invents a 30% discount, and the harness catches it:

3 THE SAME 38 FAILURES, SPLIT BY WHO CAN GRADE THEM 1 Code asserts pytest, on every commit 12 of 38 the other 26 need reading comprehension missing_citation 9 · format_broken 3 cost $0.00 per run answers in seconds 2 LLM judge claude-sonnet-5, nightly 26 of 38 already caught above invented_policy 14 · stale_data 6 · wrong_tone 4 · overrefusal 2 ≈ $0.30 / 100 cases answers in minutes every failure mode belongs to exactly one lane — none of them is graded twice
Fig. 7.2d — The split, counted. Of SaaSify's 38 failures, 12 are shapes a regular expression can see and 26 need a reader. The dashed outline is the same 38 in both lanes, so the filled part is literally the share of the problem that lane covers.
  1. The free lane. missing_citation and format_broken are decided by looking at the characters in the answer: is there a [doc:...] tag, is the JSON parseable. A test can answer that with no model, no key and no flakiness, so it runs on every commit and costs nothing. Twelve of 38 failures, caught for free, is the best trade on the page.
  2. The paid lane. The other 26 need someone to compare the answer against the context and decide whether a claim is supported. No pattern can do that, so a second model reads each case at roughly thirty cents per hundred. That is cheap, but it is not free, and it is slow enough that you do not want it on every commit.
  3. The dashed outline is the whole problem. Both bars are drawn against the same 38 failures, which is what makes the two filled lengths comparable. If you ever find yourself paying the judge to check a citation, you are spending judge tokens inside the free lane.

Regular expressions (patterns that describe the shape of a piece of text) and pytest's parametrize may be new to you. You are not expected to read this file fluently on first sight. The step-by-step list just below takes it one test at a time, and section 04 rebuilds the same checks inside a shorter harness.

Step-by-step: what test_asserts.py does, in plain English
  1. Bring in json, os, re (the regular-expression library) and pytest, the test runner.
  2. Define SAMPLE_CASES: three recorded outputs typed in by hand. Each carries an id, whether it must cite a source, its expected format, and the output text. Case a-03 invents a 30% discount on purpose.
  3. load_cases() prefers a real outputs.jsonl if one exists and falls back to the samples otherwise. CASES and CASE_IDS are computed once when the file is imported, so every test sees the same list.
  4. Compile four patterns: a [doc:...] citation, an email address, a phone number, and a percentage followed by "discount" or "off". Compiling once is faster than re-reading the pattern inside every test.
  5. APPROVED_DISCOUNTS is the set of percentages that really exist. Only "10" is in it. Anything else is invented.
  6. @pytest.mark.parametrize runs the test that follows once per case and names each run by its id, so a failure reads test_no_invented_discounts[a-03].
  7. test_citation_present skips cases that do not need a citation and fails any case that needs one and lacks it.
  8. test_no_invented_discounts collects every percentage the output mentions, removes the approved ones, and fails if anything is left. This is the test that goes red on a-03.
  9. test_no_pii_leak fails if the output contains anything shaped like an email address or a phone number.
  10. test_length_bounds fails outputs shorter than 20 or longer than 1200 characters, which catches empty replies and runaway essays.
  11. test_valid_json_payload runs only on cases whose format is json. json.loads raises on broken JSON, which pytest reports as a failure, and the test then checks for the required action key.
test_asserts.pyruns offline
# pip install pytest==8.*
# Tier 1 of the pyramid: deterministic asserts on RECORDED outputs.
# No model call, no key, no flakiness. Run: pytest test_asserts.py -q
# (One test fails on purpose — case a-03 plants an invented discount.)
import json
import os
import re

import pytest

# Embedded fallback so the file runs as-is; point it at your own system by
# writing outputs.jsonl (one {"id", "output", ...} object per line).
SAMPLE_CASES = [
    {"id": "a-01", "requires_citation": True, "format": "text",
     "output": "Annual plans are billed at 12x the monthly rate — there is "
               "no discount program on record. [doc:billing-faq-04]"},
    {"id": "a-02", "requires_citation": False, "format": "json",
     "output": '{"action": "create_ticket", "priority": "high", "team": "billing"}'},
    {"id": "a-03", "requires_citation": True, "format": "text",
     "output": "Good news — annual prepay gets you a 30% discount. [doc:billing-faq-04]"},
]

def load_cases():
    if os.path.exists("outputs.jsonl"):
        with open("outputs.jsonl", encoding="utf-8") as f:
            return [json.loads(line) for line in f]
    return SAMPLE_CASES

CASES = load_cases()
CASE_IDS = [c["id"] for c in CASES]

CITATION = re.compile(r"\[doc:[a-z0-9-]+\]")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+\.[a-z]{2,}", re.I)
PHONE = re.compile(r"\+?\d[\d\s().-]{8,}\d")
DISCOUNT = re.compile(r"(\d{1,3})\s*%\s*(?:discount|off)", re.I)
APPROVED_DISCOUNTS = {"10"}  # the ONLY discount that exists (nonprofit plan)

@pytest.mark.parametrize("case", CASES, ids=CASE_IDS)
def test_citation_present(case):
    if not case.get("requires_citation"):
        pytest.skip("no citation required for this case")
    assert CITATION.search(case["output"]), "factual answer lacks a [doc:...] citation"

@pytest.mark.parametrize("case", CASES, ids=CASE_IDS)
def test_no_invented_discounts(case):
    found = [m.group(1) for m in DISCOUNT.finditer(case["output"])]
    invented = [d for d in found if d not in APPROVED_DISCOUNTS]
    assert not invented, f"mentions discounts that exist in no policy: {invented}%"

@pytest.mark.parametrize("case", CASES, ids=CASE_IDS)
def test_no_pii_leak(case):
    assert not EMAIL.search(case["output"]), "output leaks an email address"
    assert not PHONE.search(case["output"]), "output leaks a phone number"

@pytest.mark.parametrize("case", CASES, ids=CASE_IDS)
def test_length_bounds(case):
    n = len(case["output"])
    assert 20 <= n <= 1200, f"answer length {n} chars is outside sane bounds"

@pytest.mark.parametrize("case", [c for c in CASES if c.get("format") == "json"],
                         ids=lambda c: c["id"])
def test_valid_json_payload(case):
    payload = json.loads(case["output"])  # raises → red test on broken JSON
    assert "action" in payload, "structured reply missing required 'action' key"

Step 5 — LLM-as-judge for the judgment failures — then validate the judge

That leaves invented_policy at 14, stale_data at 6, wrong_tone at 4 and overrefusal at 2: 26 of SaaSify's 38 failures, and not one of them catchable by a pattern. A second model has to read the answer against the context. This step writes that judge, and then does the thing that makes it trustworthy — measuring how often it agrees with a human.

What's left — invented_policy, wrong_tone, overrefusal — requires reading comprehension: does the answer state anything the retrieved context doesn't support? No regex can do that, so you use a second LLM as a grader with a written rubric. The rubric is your failure-mode taxonomy turned into instructions, which is why error analysis had to come first.

BE the judge

Your turn to play the machine. Below is one retrieved context, one customer question, and three answers the assistant produced. Grade each answer PASS or FAIL against the four-rule rubric, and write one sentence saying why. Do it on paper before you open the reveal, and do not soften a grade because an answer feels fine.

The rubric. FAIL if any of these hold; otherwise PASS.

  • invented_policy: states a policy, price or discount that is not in the context
  • missing_citation: makes a factual product claim with no [doc:...] citation
  • wrong_tone: dismissive or unprofessional for customer support
  • overrefusal: refuses a question the context clearly answers

The context (doc:billing-faq-04): Annual plans are billed at 12x the monthly rate. No discount programs are currently offered. Registered nonprofits receive 10% off any plan on proof of status.

The question: "We're a registered charity. Is there any discount if we pay for a year upfront?"

  1. Answer A: "Yes: registered nonprofits get 10% off any plan once you send proof of status. Paying annually does not add a further discount; annual plans are billed at 12x the monthly rate. [doc:billing-faq-04]"
  2. Answer B: "Great news! As a charity you qualify for our 10% nonprofit discount, and if you prepay for the year we can usually stretch that to 15%. Just reply with your registration number and I'll set it up."
  3. Answer C: "Registered nonprofits get 10% off with proof of status. There is no extra discount for paying annually."

Three grades, three reasons. Which answer did you hesitate over?

Check your grades
Answer APASS. Every claim is in the context, the 12x rate is right, and the citation is present. This is the shape of answer the rubric was written to reward.
Answer BFAIL, invented_policy. The 10% is real, but the 15% exists in no document. It also has no citation, so missing_citation holds too. Record the more expensive mode: an invented number is the $18,400 failure from the hook.
Answer CFAIL, missing_citation. Every word is true and it is the shortest, clearest answer of the three. The rubric still fails it: it makes factual product claims and cites nothing.

Most people grade A and B the same way. Answer C is where a labelling team splits. Some pass it, because the content is perfect and the missing citation feels like a formality. Others fail it, because the rubric says so. Both groups are being reasonable, and that is exactly the problem.

The lesson is not that C is a fail. It is that the rubric decides, not your sense of fairness. If you believe a correct but uncited answer should pass, change the rubric so that a citation is only required when a document exists, then re-label. What you must not do is keep the rule and bend the grade case by case.

Keep C in mind. When the code below measures how often the judge agrees with human labels, cases like C are where the disagreements will cluster, and they will cost you kappa. When judge and human split on such a case, look at the rubric's wording before you blame either grader.

The doubt below is the right one to have here, so look at the answer's shape before you read it. Validation is four steps and two numbers.

1 100 labeled cases a human decided each one the judge grades all 100 same rubric, no help 2 count the matches 88 of 100 agree 3 kappa 0.76 trust, or fix the words the judge's own test result — measured once, against labels it never sees
Fig. 7.2e — What “validating the judge” actually means, in four steps. The counts are the ones Fig. 7.3 shows in full a page below; the shape is what matters here.
  1. The labels come first, and they are frozen. A hundred cases a human has already decided. The judge never sees the labels; it only sees the context, the question and the answer. That is what makes the comparison a test rather than a conversation.
  2. Counting the matches is the whole measurement. Run the judge over all 100, put its verdict beside the human's, and count. Eighty-eight matched. No model is asked whether it is doing well; the count is arithmetic on two columns.
  3. One number decides, and it is not the agreement. Kappa is agreement with the luck removed, so a judge that rubber-stamps everything scores zero here no matter how high its raw agreement looks. Below roughly 0.6, the answer is to fix the wording of the rubric and measure again — not to buy a bigger model.

"If the judge is a model, who judges the judge? You have replaced one thing you cannot trust with two."

— a staff engineer who has reviewed a lot of test suites

You do, once, with a pencil, and Fig. 7.2e is the whole answer in four boxes. The judge is not trusted because it is a model. It is trusted because you ran it over the 100 labeled cases at marker 1 and counted the matches at marker 2. That count, with chance agreement subtracted, is the kappa at marker 3, and it is the judge's own test result. Until that number exists, the judge is a guess with good manners.

Two things make this less circular than it sounds. Grading is a narrower job than answering: "does this claim appear in the context?" is easier than writing the answer, in the same way that reviewing a pull request is easier than writing it. And the judge is measured against a frozen labeled set, so any drift in its behaviour shows up as a drop in agreement the next time you run validation.

The honest downside: human labels are not perfect either. Two labellers split on cases like Answer C, and the rubric decides, not your sense of fairness, so the judge can only be as consistent as the words it was given. Validation also expires: change the rubric or swap the judge model and the old agreement number is void. And a judge from the same model family as the system under test can share its blind spots, which is why the Brain Power in section 02 told you to watch the missed-failures cell.

And now the step almost everyone skips, and the one interviewers probe hardest: an unvalidated judge is just vibes with extra latency. Before you trust the judge, run it over your human-labeled dataset and measure agreement. The code below does both — the judge and its validation:

This file uses messages.parse and output_format, the structured-output call from Module 06, and it ends with Cohen's kappa, a statistic worked by hand in the exercise after Fig. 7.3 and derived in section 08. You do not need either fresh in your head now. The step-by-step list just below says what each call returns.

Step-by-step: what judge.py does, in plain English
  1. Bring in json, two typing helpers (Literal restricts a field to the listed values; Optional lets it be empty), the anthropic client, and BaseModel from pydantic, which turns a class into a validated data shape.
  2. Define Verdict: the judge must answer with exactly pass or fail, one failure-mode name from the taxonomy or nothing, and a one-sentence reason. The model cannot return anything outside this shape.
  3. RUBRIC is the system prompt. It is the failure-mode table from Step 2 rewritten as grading rules, with one worked example per verdict so the model has an anchor for the standard.
  4. The rubric sentence "Judge ONLY against the provided context" is the important one. Without it the model grades against its own idea of what a software company offers, which is precisely the failure being tested for.
  5. Create the client. It reads ANTHROPIC_API_KEY from the environment itself.
  6. judge() sends the context, question and answer inside labelled tags and asks for a Verdict back through output_format. parsed_output is already a Verdict object, not text you have to parse.
  7. validate_judge() opens the human-labeled dataset and runs the judge over every case.
  8. It sorts each case into one of four cells, treating fail as the positive class: caught (both say fail), missed (human fail, judge pass), false alarm (human pass, judge fail), and agree on pass.
  9. Raw agreement po is the share of cases where both graders say the same thing.
  10. Chance agreement pe is what two graders with these habits would agree on by luck: the product of their fail rates plus the product of their pass rates.
  11. Cohen's kappa is how far the observed agreement sits above chance, as a fraction of the room available above chance. It prints beside the two counts that matter most: missed failures and false alarms.
judge.pyneeds API key
# pip install anthropic "pydantic>=2,<3"
# LLM-as-judge with the step everyone skips: validating the judge against
# human labels BEFORE trusting it. Reads ANTHROPIC_API_KEY from the env.
import json
from typing import Literal, Optional

import anthropic
from pydantic import BaseModel

class Verdict(BaseModel):
    verdict: Literal["pass", "fail"]
    failure_mode: Optional[Literal["invented_policy", "missing_citation",
                                   "wrong_tone", "stale_data", "overrefusal"]]
    reason: str

# The rubric IS your failure-mode taxonomy from error analysis, turned into
# instructions — plus one worked example per verdict to anchor the standard.
RUBRIC = """You grade one answer from SaaSify's customer-support assistant.

Grade FAIL if ANY of these hold:
- invented_policy: states a policy, price, discount, or SLA absent from the context
- missing_citation: makes a factual product claim with no [doc:...] citation
- wrong_tone: dismissive, sarcastic, or unprofessional for customer support
- stale_data: contradicts the provided context with outdated specifics
- overrefusal: refuses a question the context clearly answers

Otherwise grade PASS. Judge ONLY against the provided context, never your own
knowledge of what a SaaS company "probably" offers.

Example FAIL: context says "no discount programs"; answer promises "25% off
annual prepay" → invented_policy, reason: discount not present in context.
Example PASS: answer restates the context accurately and cites [doc:...]."""

client = anthropic.Anthropic()

def judge(user_input: str, context: str, output: str) -> Verdict:
    # claude-sonnet-5 as judge: ~600 tokens/case → about $0.30 per 100 cases.
    response = client.messages.parse(
        model="claude-sonnet-5",
        max_tokens=1024,
        system=RUBRIC,
        messages=[{"role": "user", "content":
            f"<context>\n{context}\n</context>\n\n"
            f"<question>\n{user_input}\n</question>\n\n"
            f"<answer>\n{output}\n</answer>"}],
        output_format=Verdict,
    )
    return response.parsed_output

def validate_judge(labeled_path: str = "eval_cases.jsonl") -> None:
    """Agreement + Cohen's kappa vs human labels. Ship the judge only when
    agreement ≥ ~85–90% AND kappa ≥ ~0.7 — otherwise fix the RUBRIC first."""
    with open(labeled_path, encoding="utf-8") as f:
        cases = [json.loads(line) for line in f]
    tp = fp = fn = tn = 0  # positive class = "fail": catching failures is the job
    for c in cases:
        v = judge(c["input"], c.get("context", ""), c["output"]).verdict
        h = c["label"]
        if   h == "fail" and v == "fail": tp += 1
        elif h == "fail" and v == "pass": fn += 1  # the dangerous cell
        elif h == "pass" and v == "fail": fp += 1
        else: tn += 1
    n = tp + fp + fn + tn
    po = (tp + tn) / n  # raw agreement
    # chance agreement: two raters with these marginals agreeing at random
    pe = ((tp + fn) / n) * ((tp + fp) / n) + ((tn + fp) / n) * ((tn + fn) / n)
    kappa = (po - pe) / (1 - pe)
    print(f"n={n}  agreement={po:.0%}  kappa={kappa:.2f}")
    print(f"missed failures (judge=pass, human=fail): {fn}  false alarms: {fp}")

if __name__ == "__main__":
    validate_judge()

Read the validation as a confusion matrix, exactly like Module 02. Raw agreement lies when classes are imbalanced — if 90% of your cases pass, a judge that rubber-stamps everything scores 90% agreement while catching nothing. That's why you also compute Cohen's κ (agreement corrected for chance) and stare at one specific cell:

1 2 3 judge: fail judge: pass human: fail human: pass caught 41 missed 7 false alarm 5 agree 47 the dangerous cell: real failures the judge waves through agreement = (41 + 47) / 100 = 88% · Cohen's κ = 0.76
Fig. 7.3 — Judge validation is a confusion matrix over your human labels. Agreement alone hides the dangerous cell: a judge that never flags anything still "agrees" often. Watch missed failures and κ, and fix the rubric — not the judge model — first.
  1. Caught: 41. The human called these failures and so did the judge. This is the cell people quote, and on its own it proves very little — a judge that flags everything would fill it completely while making the cell to its left useless.
  2. Missed: 7, in heavy outline. The human found a failure and the judge said pass. These are the ones that reach a customer, because nothing downstream is looking any more. When you have one afternoon to spend on the judge, spend it reading these seven cases and fixing the words in the rubric that let them through.
  3. The line under the boxes. Eighty-eight of the 100 cases matched, which sounds strong until you remember that two-thirds of cases pass anyway. Kappa corrects for exactly that, and 0.76 is the honest version of the same result: good enough to ship, not good enough to stop watching.

Two numbers fall straight out of those four cells, and they are the two an interviewer will ask for. Each one reads a different part of the same picture.

1 PRECISION READS THE LEFT COLUMN caught 41 missed 7 false alarm 5 agree 47 judge: fail judge: pass human: fail human: pass precision = 41 / (41 + 5) = 0.8913 of the judge's 46 alarms, 41 were real failures 2 RECALL READS THE TOP ROW caught 41 missed 7 false alarm 5 agree 47 judge: fail judge: pass human: fail human: pass recall = 41 / (41 + 7) = 0.8542 of the 48 real failures, 41 were caught 3 tighten the rubric and the judge flags more: recall rises, precision falls
Fig. 7.3b — Precision and recall on the fail class, computed from Fig. 7.3's own counts. Same four boxes, two different slices: precision divides by the column the judge chose, recall divides by the row the human chose.
  1. Precision: how often an alarm is real. Take everything the judge called a failure — the outlined left column, 41 + 5 = 46 cases — and ask how many the human also called a failure. Forty-one of 46 is 0.8913. Low precision means your engineers spend their week reading false alarms and eventually stop reading the report at all.
  2. Recall: how often a real failure is caught. Take everything the human called a failure — the outlined top row, 41 + 7 = 48 cases — and ask how many the judge flagged. Forty-one of 48 is 0.8542. The 7 it missed are the ones that reach a customer, which is why the missed cell is the one Fig. 7.3 draws in heavy outline.
  3. They move in opposite directions. Make the rubric stricter and the judge flags more cases: it catches more real failures (recall up) and raises more false alarms (precision down). There is no setting that improves both. Decide which error costs SaaSify more — for an invented discount, it is the miss.
Sharpen your pencil

Compute the judge's report card once by hand and Fig. 7.3 will never look like magic again. Below are ten labeled cases, each with the human's label beside the judge's verdict. Treat fail as the positive class, because catching failures is the judge's job. Work to four decimal places.

Ten labeled cases: human label beside judge verdict
RowHumanJudge
1failfail
2failfail
3failpass
4failfail
5passpass
6passpass
7passfail
8passpass
9passpass
10passpass
The four cells: caught (human fail, judge fail) · missed (human fail, judge pass) · false alarm (human pass, judge fail) · agree (both pass)
Human fail share = 4 / 10 = 0.4000count the fail labels in the Human column; the judge's fail share is counted the same way from its own column
po (read "p-observed") = (caught + agree) / 10raw agreement: the share of rows where the two graders say the same thing
pe (read "p-expected") = (human fail share × judge fail share) + (human pass share × judge pass share)chance agreement: how often two graders with these habits would match by luck alone
po =
pe =
κ (kappa) = (po − pe) / (1 − pe) =
Precision on the fail class = caught / (caught + false alarm) =
Recall on the fail class = caught / (caught + missed) =
The rubber stamp: a judge that says pass to all ten rows. po, pe, κ =

Symbol key: po is observed agreement, pe is expected (chance) agreement, κ (kappa) is agreement corrected for chance, × means multiply, − means subtract. Precision asks "of the cases the judge flagged, how many were real failures?" and recall asks "of the real failures, how many did the judge flag?"

Check your answers
The four cellscaught 3 (rows 1, 2, 4) · missed 1 (row 3) · false alarm 1 (row 7) · agree 5 (rows 5, 6, 8, 9, 10)
Human fail share; judge fail share4 / 10 = 0.4000; the judge said fail on rows 1, 2, 4 and 7, so 4 / 10 = 0.4000. Both pass shares are 0.6000
po = (3 + 5) / 100.8000
pe = (0.4000 × 0.4000) + (0.6000 × 0.6000)0.1600 + 0.3600 = 0.5200
κ = (0.8000 − 0.5200) / (1 − 0.5200)0.2800 / 0.4800 = 0.5833
Precision on the fail class = 3 / (3 + 1)0.7500: one in four of the judge's alarms was false
Recall on the fail class = 3 / (3 + 1)0.7500: one in four real failures got through
The rubber stamppo = 6 / 10 = 0.6000. pe = (0.4000 × 0) + (0.6000 × 1.0000) = 0.6000. κ = (0.6000 − 0.6000) / (1 − 0.6000) = 0.0000
row human judge same? 1 fail fail ✓ 2 fail fail ✓ 3 fail pass ✗ 4 fail fail ✓ 5 pass pass ✓ 6 pass pass ✓ 7 pass fail ✗ 8 pass pass ✓ 9 pass pass ✓ 10 pass pass ✓ 1 2 3 caught (both say fail): 3 — rows 1, 2, 4 missed (human fail, judge pass): 1 — row 3 false alarm (human pass, judge fail): 1 — row 7 agree (both say pass): 5 — rows 5, 6, 8, 9, 10 p-observed = (3 + 5) / 10 = 0.8000 p-expected = (0.4000 × 0.4000) + (0.6000 × 0.6000) = 0.5200 kappa = (0.8000 − 0.5200) / (1 − 0.5200) = 0.5833 validate_judge() wants 0.7 before it trusts this judge
Fig. 7.3c — Your ten rows, with the arithmetic written beside them. Eight of ten rows match, so p-observed is 0.8000; two graders with these habits would match 0.5200 of the time by luck; kappa is what is left, 0.5833.
  1. The match column. Eight ticks and two crosses. Rows 3 and 7 are the disagreements, and they are the only two rows worth reading again: row 3 is a failure the judge waved through, row 7 is an alarm it raised on a good answer. Everything else in this picture is arithmetic on those ten marks.
  2. Chance agreement, 0.5200. The human called 4 of 10 cases fail; so did the judge. Two graders with those habits, answering at random, would both say fail 0.4000 × 0.4000 = 0.1600 of the time and both say pass 0.6000 × 0.6000 = 0.3600 of the time. Add them: 0.5200 of the agreement was free.
  3. Kappa, 0.5833. Observed agreement was 0.8000. Chance would have given 0.5200, so only 0.4800 of the scale was ever available to earn, and the judge earned 0.2800 of it. 0.2800 divided by 0.4800 is 0.5833 — below the 0.7 the code demands, which is why this judge is not ready yet.
1 THE JUDGE YOU MEASURED caught 3 missed 1 false alarm 1 agree 5 judge: fail judge: pass human: fail human: pass raw agreement 0.8000 kappa 0.5833 2 A JUDGE THAT SAYS PASS TO EVERY ROW caught 0 missed 4 false alarm 0 agree 6 judge: fail judge: pass human: fail human: pass raw agreement 0.6000 kappa 0.0000 3 same ten rows, same human labels: the rubber stamp still “agrees” six times out of ten
Fig. 7.3d — Why agreement alone is not enough. The rubber stamp never flags anything, so it agrees on all six genuine passes: 0.6000 raw agreement, and a kappa of exactly 0.0000.
  1. The judge you measured. Three caught, one missed, one false alarm, five agreed passes. Raw agreement 0.8000, kappa 0.5833. It is doing real work and it is not yet good enough, and those two facts have to be said together.
  2. The rubber stamp. It says pass to all ten rows. It therefore misses all four real failures, but it also agrees with the human on all six genuine passes. Raw agreement 0.6000 — a number a slide deck would happily print as “60% agreement with human review”.
  3. The two kappa bars. This is the whole reason kappa exists. The rubber stamp's chance agreement is 0.6000, exactly what it scored, so it earned none of the room above chance and its kappa is 0.0000. Raw agreement can be bought by always guessing the common answer; kappa cannot.

Now read the numbers. Eighty percent agreement sounds respectable. Kappa says otherwise: 0.5833 is below the 0.7 that validate_judge() asks for and below the 0.6 rule of thumb in section 08. This judge is not ready. The fix is to read row 3 and row 7, find the rubric wording they expose, and re-run.

The rubber stamp is why kappa exists at all. A judge that never flags anything still agrees with the human on every genuine pass, which here is six rows out of ten. Raw agreement gives it 60% and a passing impression. Kappa gives it exactly zero, because agreeing with the majority label is what chance would do anyway.

One caution about ten rows. Every figure above moves by ten points when a single row flips, which is section 05's lesson in a different costume. Ten cases are enough to learn the arithmetic. A hundred labeled cases, as in Fig. 7.3, are the minimum before a kappa means anything.

Step 6 — Wire it into CI

The judge works and you know how far to trust it. None of that stops the next bad prompt from shipping, because nothing so far runs unless somebody remembers to run it. This last step puts the suite between the pull request and the merge button, which is the only place it could have saved Viktor the $18,400.

Finally, the flywheel's gate: code asserts run on every PR (free, seconds), the judge suite runs on merge-bound PRs and nightly (cents, minutes), and the merge is blocked on regression against the current baseline — not on perfection. A PR that drops groundedness from 94% to 87% gets the same treatment as a PR that breaks the build. The complete GitHub Actions workflow is in §06; the principle belongs here: if a prompt change can reach production without passing evals, you don't have evals — you have a report.

04 · Build it yourselfAn Eval Harness From Scratch

Viktor's team now has the method on paper: 100 traces, six failure modes, a labeled file, two tiers of grader. What they do not have is a program that runs it. Before reaching for Ragas or promptfoo, you build the whole machine yourself in about ninety lines, so that no part of it stays magic. When the four-case demo prints a 50% pass rate you will know exactly which two cases failed and why.

Before industry tools, build the whole machine yourself — dataset, checks, judge, report — in about ninety lines. There is no magic in eval frameworks; feeling that is the point. This runs offline with a deterministic mock judge so you can exercise the plumbing without a key; set JUDGE=real with ANTHROPIC_API_KEY exported and the mock swaps for claude-sonnet-5.

Several idioms below have not been taught yet: a check that returns either True or a message, a function stored in a list, a comparison added to a counter. That is on purpose. Guess first, then check. Every line in the table is explained in the step-by-step list beneath it, and the full file follows straight after.

Sharpen your pencil

Below are twelve lines lifted from mini_evals.py, the file you are about to read. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. Wrong guesses are welcome; they are the point of the exercise.

from collections import Counterbring in a dictionary that counts how many times it has seen each key
return bool(CITATION.search(c["output"])) or "no [doc:...] citation"
CHECKS = [check_citation, check_no_invented_discount, check_length]
return "fail" if any(check(c) is not True for check in CHECKS) else "pass"
output_format=V,
judge_fn = real_judge if os.environ.get("JUDGE") == "real" else mock_judgepick the real model judge only when the JUDGE variable is set to real; otherwise use the offline stand-in
problems = [msg for msg in (check(c) for check in CHECKS) if msg is not True]
ok = not problems and verdict == "pass"
fail_modes[c.get("failure_mode") or "unlabeled"] += 1
agree += (verdict == c["label"])
passed = sum(r[1] == "PASS" for r in rows)
sys.exit(0 if passed == len(rows) else 1)end the program with status 0 if every case passed, otherwise 1; a CI runner treats nonzero as a red check
Check your answers
from collections import Counterbring in a dictionary that counts how many times it has seen each key
return bool(CITATION.search(c["output"])) or "no [doc:...] citation"return True when a citation is found; otherwise or hands back the message string instead, so the message doubles as the reason in the report
CHECKS = [check_citation, check_no_invented_discount, check_length]put the three check functions in a list so the runner can loop over them. Functions are ordinary values in Python; adding a fourth check is one entry
return "fail" if any(check(c) is not True for check in CHECKS) else "pass"the mock judge: say fail when any check returned something other than True, which means it returned a message. This keeps the harness runnable with no key
output_format=V,ask the model to reply in the shape of the V class, so the verdict comes back as an object with a verdict field, not text you have to parse
judge_fn = real_judge if os.environ.get("JUDGE") == "real" else mock_judgepick the real model judge only when the JUDGE variable is set to real; otherwise use the offline stand-in
problems = [msg for msg in (check(c) for check in CHECKS) if msg is not True]run every check on this case and keep only the messages, which are the failures. An empty list means every check passed
ok = not problems and verdict == "pass"the case passes only when no check failed and the judge said pass. Either tier can sink it
fail_modes[c.get("failure_mode") or "unlabeled"] += 1count one more failure under this case's failure-mode name, or under "unlabeled" if the case has none. This is the per-mode breakdown in the report
agree += (verdict == c["label"])add 1 when the judge's verdict matches the human label. A comparison is True or False, and True counts as 1 when added. This is judge validation, hiding in the regression harness
passed = sum(r[1] == "PASS" for r in rows)count the rows whose result column reads PASS; the pass rate is this over the number of rows
sys.exit(0 if passed == len(rows) else 1)end the program with status 0 if every case passed, otherwise 1; a CI runner treats nonzero as a red check

Do not worry if you got half of these. If you saw that a check returns a message instead of False, and that the exit code is the gate, you already have the two ideas the harness is built on. Everything else is bookkeeping around them.

Step-by-step: what mini_evals.py does, in plain English
  1. Bring in the standard library only: json, os, re, sys, and Counter, a dictionary that counts things. The anthropic and pydantic imports happen later, inside real_judge, so the file runs without them installed.
  2. FALLBACK is a four-case dataset typed in by hand: two passes and two labeled failures, both of the invented_policy kind. load_cases() uses a real eval_cases.jsonl when one exists.
  3. Define three checks. Each returns True when the case is fine and a short message when it is not, so the message doubles as the reason in the report.
  4. CHECKS is the list the runner loops over. Adding a fourth check is one function and one list entry.
  5. mock_judge() stands in for the model. It has the same signature as the real judge and says fail whenever any check fails, which is enough to exercise the plumbing offline.
  6. real_judge() calls claude-sonnet-5 with a three-line rubric and asks for a structured verdict. It is chosen only when JUDGE=real is set in the environment.
  7. run() loads the cases and picks the judge function once.
  8. For each case it collects the check messages, asks the judge, and marks the case ok only if no check failed and the verdict is pass.
  9. Failed cases add one to the counter for their failure mode. Cases that carry a human label also feed the agreement tally, which is how the same harness validates the judge.
  10. Print one row per case, the overall pass rate, the judge agreement if any cases were labeled, and the failure counts by mode.
  11. Exit with status 1 if any case failed. A nonzero exit is what a CI runner treats as a red check.

Build it in chunks

We build mini_evals.py in five chunks. Every chunk runs offline on its own with the mock judge; only the real-judge path in chunk 4 needs an API key. The whole file comes after them.

  1. Chunk 1 — four hand-typed cases and a loader

    An eval is a list of cases before it is anything else, so the first chunk is only data. Each case holds a question, the context the model was given, the answer it produced, and a human label saying whether that answer was good.

    Step-by-step: what this chunk does, in plain English
    1. Import json and os from the standard library.
    2. FALLBACK is four cases typed in by hand: two good answers and two answers that invent a policy.
    3. load_cases() reads a real eval_cases.jsonl file when one exists and falls back to the typed cases when it does not.
    4. Print each case's id, label and the start of its answer.
    mini_evals.py — chunk 1runs offline
    import json
    import os
    
    # ---------- 1. dataset: JSONL of {id, input, context, output, label} --------
    FALLBACK = [
        {"id": "c-01", "input": "Do you offer discounts for annual billing?",
         "context": "Billing FAQ: annual plans are billed at 12x the monthly rate. "
                    "No discount programs are currently offered.",
         "output": "Annual plans are 12x the monthly rate — no discount program "
                   "exists. [doc:billing-faq-04]",
         "label": "pass", "failure_mode": None},
        {"id": "c-02", "input": "Do you offer discounts for annual billing?",
         "context": "Billing FAQ: annual plans are billed at 12x the monthly rate. "
                    "No discount programs are currently offered.",
         "output": "Yes — annual prepay comes with a 25% loyalty discount.",
         "label": "fail", "failure_mode": "invented_policy"},
        {"id": "c-03", "input": "How do I rotate my API key?",
         "context": "API docs: Settings, then API, then Rotate key. The old key "
                    "remains valid for 24 hours.",
         "output": "Settings, then API, then Rotate key. The old key stays valid "
                   "for 24 hours. [doc:api-keys-02]",
         "label": "pass", "failure_mode": None},
        {"id": "c-04", "input": "What is your uptime SLA?",
         "context": "SLA doc: 99.9% monthly uptime for Business and Enterprise tiers.",
         "output": "We guarantee 99.99% uptime for every plan.",
         "label": "fail", "failure_mode": "invented_policy"},
    ]
    
    def load_cases(path="eval_cases.jsonl"):
        if os.path.exists(path):
            with open(path, encoding="utf-8") as f:
                return [json.loads(line) for line in f]
        return FALLBACK
    
    for c in load_cases():
        print(c["id"], c["label"], "|", c["output"][:50])

    os.path.exists — asks whether a file is there. json.loads(line) — turns one line of a JSONL file into a dictionary.

    Run python3 chunk1_dataset.py in a folder with no eval_cases.jsonl. You should see four rows: two labelled pass, two labelled fail.

    terminalactual output
    c-01 pass | Annual plans are 12x the monthly rate — no discoun
    c-02 fail | Yes — annual prepay comes with a 25% loyalty disco
    c-03 pass | Settings, then API, then Rotate key. The old key s
    c-04 fail | We guarantee 99.99% uptime for every plan.
  2. Chunk 2 — three cheap code checks that run on every case

    Before asking any model for an opinion, test what plain code can test for free: is there a citation, is there a discount nobody approved, is the answer a sensible length. Each check returns True when fine and a short message when not, so the message doubles as the reason in the report.

    Step-by-step: what this chunk does, in plain English
    1. CITATION is a pattern for a tag like [doc:billing-faq-04]; DISCOUNT finds numbers followed by "% discount" or "% off".
    2. check_citation passes when the pattern is found.
    3. check_no_invented_discount fails on any discount other than the approved 10%.
    4. check_length fails if the answer is under 20 or over 1,200 characters.
    5. CHECKS is a plain list of the three functions, so adding a fourth check is one function and one list entry.
    6. Run every check on every case and print the messages. The chunk 1 print loop is replaced.
    mini_evals.py — chunk 2runs offline
    import re
    # ---------- 2. code asserts: cheap, deterministic, run on every case --------
    CITATION = re.compile(r"\[doc:[a-z0-9-]+\]")
    DISCOUNT = re.compile(r"(\d{1,3})\s*%\s*(?:discount|off)", re.I)
    def check_citation(c):
        return bool(CITATION.search(c["output"])) or "no [doc:...] citation"
    
    def check_no_invented_discount(c):
        bad = [m.group(1) for m in DISCOUNT.finditer(c["output"]) if m.group(1) != "10"]
        return (not bad) or f"unapproved discount(s): {bad}"
    
    def check_length(c):
        return (20 <= len(c["output"]) <= 1200) or "length out of bounds"
    
    CHECKS = [check_citation, check_no_invented_discount, check_length]
    
    for case in load_cases():
        problems = [msg for msg in (check(case) for check in CHECKS) if msg is not True]
        print(case["id"], problems or "all checks ok")

    re.compile — build a text pattern once, reuse it. A list of functions — store checks in CHECKS and call each one in a loop.

    Run python3 chunk2_checks.py. You should see c-01 and c-03 pass every check, and c-02 and c-04 report no [doc:...] citation. Notice the checks catch the missing citation but not the invented 25% (the pattern needs the word "discount" right after the percent sign). That gap is why a judge exists.

    terminalactual output
    c-01 all checks ok
    c-02 ['no [doc:...] citation']
    c-03 all checks ok
    c-04 ['no [doc:...] citation']
  3. Chunk 3 — a stand-in judge that runs offline

    Some failures need judgement, not a pattern. Real judging calls a model, but we do not want to need a key just to test the harness. So this chunk adds a mock judge with the same shape as the real one: it takes a case and returns "pass" or "fail".

    Step-by-step: what this chunk does, in plain English
    1. mock_judge(c) returns "fail" if any check fails, otherwise "pass".
    2. Print the mock verdict next to the human label for each case.
    mini_evals.py — chunk 3runs offline
    # ---------- 3. judge: deterministic mock, or claude-sonnet-5 if JUDGE=real --
    def mock_judge(c):
        # Stand-in with the same signature so the harness runs keyless. It reuses
        # the asserts — enough to exercise the pipeline shape end to end.
        return "fail" if any(check(c) is not True for check in CHECKS) else "pass"
    for row in load_cases():
        print(row["id"], "judge says", mock_judge(row), "| human label:", row["label"])

    any(... for check in CHECKS) — true if at least one check fails. The mock reuses the code checks, which is enough to test the plumbing.

    Run python3 chunk3_mock_judge.py. You should see the verdict match the human label on all four rows.

    terminalactual output
    c-01 judge says pass | human label: pass
    c-02 judge says fail | human label: fail
    c-03 judge says pass | human label: pass
    c-04 judge says fail | human label: fail
  4. Chunk 4 — the real judge, chosen by an environment variable

    Now the model-backed judge. It has exactly the same signature as the mock, so the rest of the program never needs to know which one it holds. An environment variable picks one, and the default stays offline.

    Step-by-step: what this chunk does, in plain English
    1. real_judge(c) imports anthropic and pydantic only when called, so the file still loads without them.
    2. A small V class says the answer must be a verdict of "pass" or "fail" plus a reason.
    3. client.messages.parse sends a three-line rubric and the case, and returns an already-validated object.
    4. judge_fn is the real judge only when JUDGE=real is set; otherwise it is the mock.
    mini_evals.py — chunk 4runs offline
    def real_judge(c):
        from typing import Literal
        import anthropic
        from pydantic import BaseModel
        class V(BaseModel):
            verdict: Literal["pass", "fail"]
            reason: str
        client = anthropic.Anthropic()
        r = client.messages.parse(
            model="claude-sonnet-5", max_tokens=512,
            system="Grade the answer ONLY against the context. FAIL if it states "
                   "any policy, price, SLA, or discount not in the context, or "
                   "makes uncited factual claims. Otherwise PASS.",
            messages=[{"role": "user", "content":
                f"<context>{c.get('context', '')}</context>\n"
                f"<question>{c['input']}</question>\n"
                f"<answer>{c['output']}</answer>"}],
            output_format=V,
        )
        return r.parsed_output.verdict
    judge_fn = real_judge if os.environ.get("JUDGE") == "real" else mock_judge
    print("judge in use:", judge_fn.__name__)
    for item in load_cases():
        print(item["id"], judge_fn(item))

    Literal["pass", "fail"] — a type that allows only those two words. messages.parse — structured output validated against the class.

    Run python3 chunk4_real_judge.py. With no key it still runs: it prints judge in use: mock_judge and the same four verdicts. The real path (JUDGE=real python3 chunk4_real_judge.py) needs an API key and was not run here.

    terminalactual output
    judge in use: mock_judge
    c-01 pass
    c-02 fail
    c-03 pass
    c-04 fail
  5. Chunk 5 — the runner, the report, and the exit code

    Everything exists; this chunk joins it. For every case it collects the check messages, asks the judge, and marks the case OK only if both agree it is fine. Then it prints the table, the pass rate, and how often the judge agreed with the human labels. The last line decides the exit code, which is what CI reads.

    Step-by-step: what this chunk does, in plain English
    1. Load the cases and pick the judge once.
    2. For each case, gather the failed-check messages and ask the judge.
    3. A case is OK only when there are no messages and the verdict is pass. Failures add one to a counter keyed by failure mode.
    4. Labelled cases also feed an agreement tally, so the same harness validates the judge.
    5. Print one row per case, the pass rate, the agreement, and the failure counts.
    6. Exit with status 1 if anything failed. Chunk 4's test print lines are replaced.
    mini_evals.py — chunk 5runs offline
    import sys
    from collections import Counter
    # ---------- 4. runner + report ----------------------------------------------
    def run():
        cases = load_cases()
        judge_fn = real_judge if os.environ.get("JUDGE") == "real" else mock_judge
        rows, fail_modes, agree, labeled = [], Counter(), 0, 0
        for c in cases:
            problems = [msg for msg in (check(c) for check in CHECKS) if msg is not True]
            verdict = judge_fn(c)
            ok = not problems and verdict == "pass"
            if not ok:
                fail_modes[c.get("failure_mode") or "unlabeled"] += 1
            if c.get("label"):  # harness doubles as judge validation on labeled data
                labeled += 1
                agree += (verdict == c["label"])
            rows.append((c["id"], "PASS" if ok else "FAIL", "; ".join(problems) or verdict))
        passed = sum(r[1] == "PASS" for r in rows)
        print(f"{'case':<8} {'result':<7} detail")
        for r in rows:
            print(f"{r[0]:<8} {r[1]:<7} {r[2]}")
        print(f"\npass rate: {passed}/{len(rows)} = {passed / len(rows):.0%}")
        if labeled:
            print(f"judge agreement with human labels: {agree}/{labeled} = {agree / labeled:.0%}")
        if fail_modes:
            print("failures by mode:", dict(fail_modes))
        sys.exit(0 if passed == len(rows) else 1)  # nonzero exit = CI gate trips
    if __name__ == "__main__":
        run()

    sys.exit(1) — a nonzero exit code is how a CI runner knows to turn the check red. Counter — a dictionary that counts.

    Run python3 chunk5_mini_evals.py, then echo $?. You should see the table below, a 50% pass rate (right, because two of the four cases are deliberate failures), and exit status 1.

    terminalactual output
    case     result  detail
    c-01     PASS    pass
    c-02     FAIL    no [doc:...] citation
    c-03     PASS    pass
    c-04     FAIL    no [doc:...] citation
    
    pass rate: 2/4 = 50%
    judge agreement with human labels: 4/4 = 100%
    failures by mode: {'invented_policy': 2}

The whole program

Lines 1–9 are the header and imports (each chunk file imports only what it needs). Chunk 1 is lines 10–41, chunk 2 lines 42–58, chunk 3 lines 59–65, chunk 4 lines 66–87, and chunk 5 lines 88–117. Every chunk starts with a # ── chunk n ── comment.

mini_evals.pyruns offline
# pip install anthropic "pydantic>=2,<3"   # only needed for JUDGE=real
# A complete eval harness in ~90 lines: dataset → checks → judge → report.
# Offline by default (mock judge); JUDGE=real uses claude-sonnet-5.
import json
import os
import re
import sys
from collections import Counter

# ── chunk 1: the dataset ──
# ---------- 1. dataset: JSONL of {id, input, context, output, label} --------
FALLBACK = [
    {"id": "c-01", "input": "Do you offer discounts for annual billing?",
     "context": "Billing FAQ: annual plans are billed at 12x the monthly rate. "
                "No discount programs are currently offered.",
     "output": "Annual plans are 12x the monthly rate — no discount program "
               "exists. [doc:billing-faq-04]",
     "label": "pass", "failure_mode": None},
    {"id": "c-02", "input": "Do you offer discounts for annual billing?",
     "context": "Billing FAQ: annual plans are billed at 12x the monthly rate. "
                "No discount programs are currently offered.",
     "output": "Yes — annual prepay comes with a 25% loyalty discount.",
     "label": "fail", "failure_mode": "invented_policy"},
    {"id": "c-03", "input": "How do I rotate my API key?",
     "context": "API docs: Settings, then API, then Rotate key. The old key "
                "remains valid for 24 hours.",
     "output": "Settings, then API, then Rotate key. The old key stays valid "
               "for 24 hours. [doc:api-keys-02]",
     "label": "pass", "failure_mode": None},
    {"id": "c-04", "input": "What is your uptime SLA?",
     "context": "SLA doc: 99.9% monthly uptime for Business and Enterprise tiers.",
     "output": "We guarantee 99.99% uptime for every plan.",
     "label": "fail", "failure_mode": "invented_policy"},
]

def load_cases(path="eval_cases.jsonl"):
    if os.path.exists(path):
        with open(path, encoding="utf-8") as f:
            return [json.loads(line) for line in f]
    return FALLBACK

# ── chunk 2: code checks ──
# ---------- 2. code asserts: cheap, deterministic, run on every case --------
CITATION = re.compile(r"\[doc:[a-z0-9-]+\]")
DISCOUNT = re.compile(r"(\d{1,3})\s*%\s*(?:discount|off)", re.I)

def check_citation(c):
    return bool(CITATION.search(c["output"])) or "no [doc:...] citation"

def check_no_invented_discount(c):
    bad = [m.group(1) for m in DISCOUNT.finditer(c["output"]) if m.group(1) != "10"]
    return (not bad) or f"unapproved discount(s): {bad}"

def check_length(c):
    return (20 <= len(c["output"]) <= 1200) or "length out of bounds"

CHECKS = [check_citation, check_no_invented_discount, check_length]

# ── chunk 3: the mock judge ──
# ---------- 3. judge: deterministic mock, or claude-sonnet-5 if JUDGE=real --
def mock_judge(c):
    # Stand-in with the same signature so the harness runs keyless. It reuses
    # the asserts — enough to exercise the pipeline shape end to end.
    return "fail" if any(check(c) is not True for check in CHECKS) else "pass"

# ── chunk 4: the real judge ──
def real_judge(c):
    from typing import Literal
    import anthropic
    from pydantic import BaseModel
    class V(BaseModel):
        verdict: Literal["pass", "fail"]
        reason: str
    client = anthropic.Anthropic()
    r = client.messages.parse(
        model="claude-sonnet-5", max_tokens=512,
        system="Grade the answer ONLY against the context. FAIL if it states "
               "any policy, price, SLA, or discount not in the context, or "
               "makes uncited factual claims. Otherwise PASS.",
        messages=[{"role": "user", "content":
            f"<context>{c.get('context', '')}</context>\n"
            f"<question>{c['input']}</question>\n"
            f"<answer>{c['output']}</answer>"}],
        output_format=V,
    )
    return r.parsed_output.verdict

# ── chunk 5: runner and report ──
# ---------- 4. runner + report ----------------------------------------------
def run():
    cases = load_cases()
    judge_fn = real_judge if os.environ.get("JUDGE") == "real" else mock_judge
    rows, fail_modes, agree, labeled = [], Counter(), 0, 0
    for c in cases:
        problems = [msg for msg in (check(c) for check in CHECKS) if msg is not True]
        verdict = judge_fn(c)
        ok = not problems and verdict == "pass"
        if not ok:
            fail_modes[c.get("failure_mode") or "unlabeled"] += 1
        if c.get("label"):  # harness doubles as judge validation on labeled data
            labeled += 1
            agree += (verdict == c["label"])
        rows.append((c["id"], "PASS" if ok else "FAIL", "; ".join(problems) or verdict))
    passed = sum(r[1] == "PASS" for r in rows)
    print(f"{'case':<8} {'result':<7} detail")
    for r in rows:
        print(f"{r[0]:<8} {r[1]:<7} {r[2]}")
    print(f"\npass rate: {passed}/{len(rows)} = {passed / len(rows):.0%}")
    if labeled:
        print(f"judge agreement with human labels: {agree}/{labeled} = {agree / labeled:.0%}")
    if fail_modes:
        print("failures by mode:", dict(fail_modes))
    sys.exit(0 if passed == len(rows) else 1)  # nonzero exit = CI gate trips

if __name__ == "__main__":
    run()

Run it and you'll see a 50% pass rate — correct, because the fallback dataset deliberately contains two labeled failures. That's the dual life of this harness: pointed at your labeled dataset it validates the judge (the agreement line); pointed at fresh outputs from your current system it becomes the regression gate, and its exit code is what CI watches.

1 LANE 1 — VALIDATING THE JUDGE eval_cases.jsonl 4 cases, each with a human label 2 LANE 2 — GATING THE MERGE fresh outputs today's prompt, no labels 3 mini_evals.py 3 code asserts + 1 judge one file, unchanged judge agreement 4 / 4 = 100% every verdict matched the human label pass rate 2 / 4 = 50% failures by mode: invented_policy 2 sys.exit(1) → the CI check goes red the same program both times; only the input and the question change
Fig. 7.3e — The two lives of mini_evals.py, drawn with the numbers the fallback dataset actually prints: agreement 4/4 on the labeled cases, pass rate 2/4 and exit status 1 on the outputs.
  1. Lane 1: the file is a measuring instrument. Point it at cases a human has already labeled and the interesting line is the agreement line. Here the mock judge matches all four labels, so agreement is 100% — flattering, and only because the mock judge is the code asserts in a hat. With a real judge this line is the kappa story from step 5.
  2. Lane 2: the file is a gate. Point it at outputs from today's prompt, where nobody has labeled anything, and the interesting lines are the pass rate and the exit status. Two of the four cases fail, both for invented_policy, and the program exits with status 1.
  3. The middle box never changes. The same three asserts and the same judge run in both lanes. That is the point worth carrying to an interview: validation and regression testing are the same machinery pointed at two different inputs, not two separate systems to build.

Questions you might be asking now

The harness above prints four rows and a 50% pass rate, and the picture calls that correct. The questions below slow down for what happens inside those four rows. Every answer uses the same four cases: the fallback list built into mini_evals.py, run offline with the mock judge.

The four cases every answer below uses, copied from the FALLBACK list in mini_evals.py. A human wrote the label and the failure mode; the output is what the assistant said.
CaseQuestionAssistant's outputHuman labelFailure mode
c-01Do you offer discounts for annual billing?"Annual plans are 12x the monthly rate — no discount program exists. [doc:billing-faq-04]"passnone
c-02Do you offer discounts for annual billing?"Yes — annual prepay comes with a 25% loyalty discount."failinvented_policy
c-03How do I rotate my API key?"Settings, then API, then Rotate key. The old key stays valid for 24 hours. [doc:api-keys-02]"passnone
c-04What is your uptime SLA?"We guarantee 99.99% uptime for every plan."failinvented_policy
Walk one case through mini_evals.py for me. What happens to the $18,400 answer at each step, from the case to the red CI check?

Case c-02 fails one of the three checks, the citation check, so the mock judge says fail as well. The report files it under invented_policy, the pass rate becomes 2 of 4, and the program exits with status 1, which turns the check red. The discount check, the one written for exactly this answer, never fires.

Below is the case at every station, with the value the program actually holds there. The values come from rerunning trace_one_case.py. That script imports the harness's own checks and mock judge instead of copying them, so the trace cannot drift away from the file shown above.

Case c-02 through mini_evals.py, one station per row
StationCode in mini_evals.pyValue for c-02
A · loadload_cases()A dictionary: the output "Yes — annual prepay comes with a 25% loyalty discount.", label fail, failure mode invented_policy
B · citation checkcheck_citation(c)The pattern finds nothing, so the check returns the message "no [doc:...] citation"
C · discount checkcheck_no_invented_discount(c)True: the pattern found no percentage to object to
D · length checkcheck_length(c)True: 54 characters, inside the 20 to 1,200 allowed
E · collect problemsproblems = [...]One message: ["no [doc:...] citation"]
F · judgemock_judge(c)"fail", because one check returned something other than True
G · decideok = not problems and verdict == "pass"False
H · count the modefail_modes[...] += 1invented_policy goes to 1, and to 2 once c-04 is done
I · agreementagree += (verdict == c["label"])"fail" matches "fail", so agree goes up by 1
J · report rowrows.append(...)c-02 · FAIL · no [doc:...] citation
K · pass ratepassed = sum(...)2 of the 4 rows, printed as "pass rate: 2/4 = 50%"
L · exitsys.exit(0 if passed == len(rows) else 1)1, which a CI runner shows as a red check

One practical note on station A. load_cases() uses the fallback list only when no eval_cases.jsonl sits in the working directory. Run the file inside code/07-evals/ and it reads that folder's three-case file instead, printing 2/3 = 67%. The numbers on this page are the fallback four.

Station C: why the discount check said True

The pattern is (\d{1,3})\s*%\s*(?:discount|off). Read aloud: one to three digits, a percent sign, optional spaces, then the word discount or off. In c-02 the word loyalty sits between "25%" and "discount". The pattern allows only spaces there, so it never matches. No match means no invented discount, and the check returns True.

So the most expensive answer in the module was caught for a different reason: it cites nothing. Station H hides that. The report counts the case under invented_policy because that is the human's label. The detail text, "no [doc:...] citation", is the only place that says what the code actually found.

Now give the same answer a citation

Append [doc:billing-faq-04] to c-02's output. It still promises the 25% discount, but now it cites a document, and it is 75 characters long. All three checks return True and the mock judge says pass. trace_one_case.py reruns the four cases each way:

The four fallback cases, rerun after adding citations. Values from rerunning trace_one_case.py.
Runc-02Pass rateAgreement with the labelsExit status
As writtenFAIL2/4 = 50%4/4 = 100%1, red
c-02 citedPASS3/4 = 75%3/4 = 75%1, red (c-04 still fails)
c-02 and c-04 citedPASS4/4 = 100%2/4 = 50%0, green

Read the last row slowly. Both invented policies now reach customers, and the check turns green. The pass rate rose while the product got worse. The agreement figure fell to 2 of 4, which is the harness noticing. The gate, though, reads only the exit status.

AS WRITTEN: THE $18,400 ANSWER, NO CITATION c-02 output 25% loyalty discount no citation · 54 chars check_citation returns the message no [doc:...] citation 1 discount check returns True pattern: no match mock_judge 1 check failed verdict: fail 2 FAIL mode: invented_policy 2/4 · exit 1 · red SAME INVENTED DISCOUNT, WITH [doc:billing-faq-04] APPENDED c-02 + citation same 25% discount 75 chars check_citation returns True [doc:billing-faq-04] discount check returns True pattern: no match mock_judge 0 checks failed verdict: pass 3 PASS cite c-04 as well: 4/4 · exit 0 · green the length check passes in both lanes, so only the citation check ever decided this case
Fig. 7.3k — Case c-02 through mini_evals.py, twice. Top: as written, the citation check is the only station that fails it. Bottom: the same invented 25% discount with a citation appended passes every station, and with c-04 cited as well the harness exits 0. Values from rerunning trace_one_case.py.
  1. The check that did not fire. The discount pattern wants digits, a percent sign, spaces, then "discount" or "off". c-02 says "25% loyalty discount", and the word loyalty breaks the match. No match counts as no invented discount, so this check returns True on the most expensive answer in the module.
  2. The label on the row. The case fails because it cites nothing. The report still counts it under invented_policy, because the failure mode comes from the human's label, not from the check. The message "no [doc:...] citation" is what the code actually found.
  3. The green check. With a citation appended, c-02 passes all three checks and the mock judge agrees. Cite c-04 too, and the harness prints 4/4 and exits 0 while both invented policies ship. Agreement with the human labels falls to 2 of 4, but the gate does not read agreement.

A looser pattern helps a little. Allowing up to two words between the percent sign and "discount" does catch c-02's 25%. It still misses Answer B from the BE-the-judge exercise in step 5, "stretch that to 15%", because no such word follows the 15. A pattern sees only the shapes it was written for.

Two things do catch this sentence. The promptfoo pin in section 06, not-contains "25%", fails it with or without a citation, but only for that exact number. Meaning in general needs a reader, which is why the harness has a real judge behind JUDGE=real.

A case fails only for the reasons some check was written to see. Read which check fired, not the failure mode on the report row.

Is an eval just a unit test? mini_evals.py ends with sys.exit(1), exactly like a failing pytest run.

Partly. The bottom tier is unit tests in every sense: test_asserts.py is plain pytest, and its one red test is a bug to fix. The eval as a whole is a measurement instead. Some of its cases are meant to fail, its grader needs a test of its own, and its result is a rate compared with a baseline.

The bridge in section 01 called evals "unit tests plus monitoring for a nondeterministic dependency". That is a good first map. The table below marks where the map holds and where it breaks, using the two offline files of this module.

Unit test and eval, side by side. The pytest result is a rerun of test_asserts.py; the eval readings come from the four fallback cases above and from Fig. 7.4b.
QuestionUnit test: test_asserts.py under pytestEval: mini_evals.py, judge.py, promptfoo
What one case checksA fixed property of the output: a citation is present, the JSON parsesWhether an answer is acceptable. For 26 of SaaSify's 38 failures that needs a reader
Who writes the expected resultThe developer, from the specA human labeller, after reading real traces in step 1
What a run prints1 failed, 11 passed, 1 skippedA rate: pass rate 2/4, agreement 4/4
Is a failing case bad news?Yes. a-03's invented 30% discount must be fixed before mergingNot always. c-02 and c-04 were labeled fail; the harness is working when it fails them
The same input, run twiceThe same verdict every time: recorded output, fixed patternA live model can answer differently, and a new sample of cases scores differently
Who checks the grader?Nobody needs to: an assert means what it saysThe judge is itself tested against human labels, with agreement and kappa
What blocks a mergeAny red testA drop below the baseline, such as groundedness 0.94 to 0.87 in Fig. 7.4b
Cost of one run$0.00, 0.03 secondsAbout $0.30 per 100 cases for the judge tier

The two sides meet at the code asserts. check_citation in mini_evals.py and test_citation_present in test_asserts.py use the same regular expression. A failure there means the same thing in both files, so treat it like any red test.

Everything above that tier changes meaning. A unit-test suite at 50% would be an emergency. mini_evals.py at 50% on its four fallback cases is the correct reading, because two of the four were labeled fail on purpose. On labeled cases the question is not "did everything pass?" but "did the grader agree with the human?", and all four verdicts did.

Point the same file at fresh outputs and it plays its other role from Fig. 7.3e. There are no labels now. The pass rate is compared with the last merged one, and that comparison is where the wobble of section 05 enters. A unit test never changes its verdict because a different sample of cases was drawn. An eval's pass rate does.

UNIT TEST: pytest test_asserts.py a-01 a-02 a-03 citation no invented discount no PII length valid JSON ✓ – ✓ ✓ ✓ ✗ 1 ✓ ✓ ✓ ✓ ✓ ✓ ✓ 1 failed · 11 passed · 1 skipped any red square blocks the merge the fix: change what produced a-03's 30% discount EVAL: A RATE, READ AGAINST WHAT IT SHOULD BE labeled fallback cases: pass rate 2/4 = 50% ✓ ✗ ✓ ✗ 2 correct: both were labeled fail same run: judge agreement 4/4 = 100% ✓ ✓ ✓ ✓ the grade that matters here fresh outputs in CI, from Fig. 7.4b 0.80 1.00 3 baseline 0.94 #128: 0.87, blocked #129: 0.96, merged the same exit status on both sides: a bug on the left, a comparison on the right
Fig. 7.3l — The same exit status, read two ways. Left: the 13 results of pytest test_asserts.py, where any red square is a bug. Right: the eval readings, where a red case can be the correct answer and the gate compares a rate with a baseline. pytest counts from a rerun; the right-hand numbers are Fig. 7.3e's and Fig. 7.4b's.
  1. The one red square. test_no_invented_discounts on a-03, which promises a 30% discount. Its verdict can mean only one thing: the output under test is wrong. It blocks the merge until whatever produced a-03 is fixed. The dashed square is a-02, which is not required to cite anything, so pytest skips that check.
  2. Two red cases that are good news. On mini_evals.py's four labeled cases, c-02 and c-04 fail because a human labeled them fail. A 50% pass rate is the correct reading of this file. What grades the harness is the agreement line beneath it: all four verdicts matched the labels.
  3. A rate against a baseline. On fresh outputs nobody has labeled, the suite produces one score, and the gate compares it with the last merged score of 0.94. PR #128 lands at 0.87 and is blocked; PR #129 lands at 0.96 and merges. No single case decides it, and the score itself wobbles, which section 05 measures.

An everyday comparison helps. A unit test is a spelling checker: it flags exactly the words it knows are wrong. An eval is an editor's report on a sample of chapters. It gives a score, another editor might score differently, and you trust it only after checking it against your own reading of a few chapters.

The comparison fails in both directions, and each failure has a cost. Teams that treat an eval as a unit test demand 100% and delete the hard cases that keep failing. Teams that treat it as a report never block a merge. The working rule is the one Fig. 7.4 draws: asserts block on any red, and the judge suite blocks on a drop below the baseline.

The asserts inside an eval are unit tests and block on any red. The eval around them is a measurement, graded against human labels and gated against a baseline.

The harness also printed "judge agreement with human labels: 4/4 = 100%". Does that mean my judge is validated?

No. The mock judge is the three code asserts, four rows are far too few, and agreement is not kappa. On these four rows one changed verdict drops kappa from 1.00 to 0.50. On Fig. 7.3's 100 labeled cases the same change moves it by about 0.02, which is why validation needs about 100.

There are three separate reasons, and only the first one is specific to the mock judge.

  1. The mock judge is not reading anything. It returns fail whenever a check fails. Its agreement with the labels only says that the planted failures happen to lack citations. The first answer in this block showed the cost: cite c-02 and agreement drops to 3 of 4.
  2. Agreement is not kappa. Agreement counts matching rows. Kappa (κ) first removes the matches that luck alone would produce, as the pencil exercise in step 5 did.
  3. Four rows cannot carry a verdict. One row is a quarter of the data, so any number built on four rows jumps in quarters.

Here is kappa on the four rows, by hand, in the same steps as that exercise. Fail is the positive class.

  1. Sort the rows into cells. c-02 and c-04: human fail, judge fail, so caught = 2. c-01 and c-03: both pass, so agree = 2. Missed = 0 and false alarm = 0.
  2. Observed agreement. po (read "p-observed") = (2 + 2) ÷ 4 = 1.00.
  3. Chance agreement. The human said fail on 2 of 4 rows, a share of 0.50, and so did the judge. pe (read "p-expected") = 0.50 × 0.50 + 0.50 × 0.50 = 0.50.
  4. Kappa. κ = (1.00 − 0.50) ÷ (1 − 0.50) = 0.50 ÷ 0.50 = 1.00.
  5. Cite c-02 and do it again. The judge now says pass on a human fail: caught 1, missed 1. po = 3 ÷ 4 = 0.75. The judge's fail share is 1 of 4, 0.25, so pe = 0.50 × 0.25 + 0.50 × 0.75 = 0.50. κ = 0.25 ÷ 0.50 = 0.50.

Symbol key: po is observed agreement, pe is chance agreement, κ (kappa) is agreement with chance removed, × means multiply, ÷ means divide, − means subtract.

One sentence of the assistant's text changed, and kappa halved. That says nothing about the judge. It is what any number does when one row is 25% of the data. judge_kappa_wobble.py flips one verdict at a time on all three label sets this page uses:

How far one flipped verdict moves kappa. Values from rerunning judge_kappa_wobble.py.
Label setKappa as measuredAfter one verdict flipsMove per flipped row
4 rows: mini_evals.py fallback, mock judge1.00000.5000−0.50
10 rows: the step-5 pencil exercise0.58330.3478 to 0.8000about ±0.20
100 rows: Fig. 7.30.75920.7390 to 0.7795about ±0.02

Put the ten-row result next to the 0.7 that validate_judge() asks for. Fix the one missed row and kappa jumps to 0.8000, a pass. Add one false alarm instead and it falls to 0.4000, the level below which the rule of thumb calls the rubric ambiguous. On 100 rows, no single row can pull 0.7592 below 0.7.

A second way to see it: redraw the rows

A bootstrap asks how far a number could have landed with a different sample of the same kind of cases. The script draws 100 rows at random from Fig. 7.3's 100, with repeats allowed, and recomputes kappa. It does that 10,000 times. 95% of the results land between 0.62 and 0.88.

The same redraw from the ten pencil rows lands anywhere between −0.09 and 1.00. A kappa below zero means the two graders matched less often than luck would. So ten rows cannot even tell a useful judge from a useless one.

range after one flipped verdict 95% of 10,000 bootstrap redraws 0.7: the bar validate_judge() sets 1 4 rows mock judge 0.50 after one flip 1.00 printed 2 10 rows step-5 exercise 0.35 0.58 measured 0.80 95% of redraws: −0.09 to 1.00 3 100 rows Fig. 7.3's judge 0.76 measured · one flip: 0.74 to 0.78 95% of redraws: 0.62 to 0.88 −0.2 0 0.2 0.4 0.6 0.8 1.0 Cohen's kappa (κ): 0 is chance, 1 is perfect agreement
Fig. 7.3m — The same statistic on the page's three label sets. Thick segment: where kappa lands when one verdict flips. Thin line: where 95% of 10,000 bootstrap redraws land. Dashed: the 0.7 that validate_judge() asks for. Values from rerunning judge_kappa_wobble.py.
  1. Four rows. Kappa prints as 1.00 when the mock judge matches all four labels. Change one verdict, as adding a citation to c-02 does, and it falls to 0.50. One row is a quarter of the data, so one row can halve the number.
  2. Ten rows. The step-5 exercise measured 0.5833. One flipped verdict lands anywhere from 0.3478 to 0.8000, on both sides of the dashed 0.7. Redraw ten rows from those ten and 95% of the kappas fall between −0.09 and 1.00; below zero means worse than luck.
  3. A hundred rows. Fig. 7.3's judge measured 0.7592. One flipped verdict moves it by about 0.02 and never below 0.7. The redraws still spread from 0.62 to 0.88, and 20% of them fall under 0.7: probably good enough, not certainly.

Even 100 rows leave a range 0.26 wide, and 20% of the redraws fall below 0.7. A judge measured at 0.76 is probably above the bar, not certainly. That is what Fig. 7.3 means by "good enough to ship, not good enough to stop watching". The next labeled batch is what turns probably into known.

Agreement on a handful of rows is an anecdote. Validate the real judge on about 100 labeled cases, report kappa beside the missed count, and expect kappa to move a little on the next batch.

05 · Watch it breakVibes Don't Replicate

The harness runs and prints a number, and that is the moment the danger changes shape. At SaaSify two engineers now eyeball five transcripts each and reach opposite verdicts about prompt v6. Your harness will do the same thing if you point it at twenty cases. This section shows the arithmetic that makes a five-point win on twenty cases meaningless, and says how many cases Viktor actually needs.

Failure mode

SaaSify, week five. Engineer A eyeballs five transcripts from prompt v6 and declares it "clearly better." Engineer B eyeballs a different five and declares it worse.

Both are pattern-matching on samples too small to mean anything — which is also what your harness does if the dataset is tiny.

Prompt B scores 80% and prompt A scores 75% on a 20-case suite, the team ships B… and the "improvement" evaporates in production. Nothing mystical happened: a 5-point gap on 20 cases is statistically indistinguishable from zero.

🧠 Brain power

Before running the code: two prompts have identical true quality (75%). You measure both on 20 random cases. How often will the measured gap be 10 points or more — 5% of the time? 20%? Guess, then run it.

Reveal the answer

Roughly 58% of the time — more often than not. The standard error of one measurement at n=20, p=0.75 is √(0.75·0.25/20) ≈ 9.7 points, and the gap between two independent measurements is noisier still (√2 larger). A 10-point "win" on 20 cases is the sound of dice rolling. This is Module 01's variance lesson wearing an eval costume.

The script prints 58% too, because it counts the gap in whole cases. An earlier version compared the rates as decimals and printed 43%, which is a floating-point trap worth seeing; a follow-up question below works through it.

Step-by-step: what variance_check.py does, in plain English
  1. Bring in numpy and create a random generator with a fixed seed, so the numbers are the same every run.
  2. Set the scene: 20 cases per prompt, a true pass rate of 75% for both prompts, and 10,000 repeated experiments.
  3. rng.binomial(n, true_rate, size=trials) simulates scoring 20 cases 10,000 times and returns the number of passes each time. Dividing by n turns each count into a measured pass rate. Do it twice, once per prompt.
  4. gap_cases is how many cases apart the two results landed, counted in whole cases rather than in rates. Two cases out of twenty is exactly 10 points. The prompts are identical, so every gap is pure noise.
  5. Print how often that noise alone reaches 10 points. That is the share of "clear wins" you would declare on 20 cases when nothing changed.
  6. Then the same lesson from the formula: for four eval-set sizes, compute the standard error of one pass rate and print the 95% confidence interval, which is 1.96 standard errors either side.
variance_check.pyruns offline
# pip install numpy==2.*
# Why "prompt B scored 80% vs 75% on 20 cases" means nothing — Module 01's
# variance math, applied to eval sets.
import numpy as np

rng = np.random.default_rng(0)

n, true_rate, trials = 20, 0.75, 10_000

# Two prompts with IDENTICAL true quality, each measured on n cases, 10k times:
a_passes = rng.binomial(n, true_rate, size=trials)
b_passes = rng.binomial(n, true_rate, size=trials)
# Compare the PASS COUNTS, not the rates: 15/20 - 13/20 is stored as
# 0.09999999999999998, so a float test of >= 0.10 silently drops it.
gap_cases = np.abs(a_passes - b_passes)          # 2 cases out of 20 = 10 points
print(f"P(measured gap ≥ 10 pts when the true gap is ZERO) = {(gap_cases >= 2).mean():.0%}")

# The standard error says the same thing without simulation:
for n2 in (20, 100, 500, 2000):
    se = (true_rate * (1 - true_rate) / n2) ** 0.5
    print(f"n={n2:>5}: one pass-rate reading is ±{1.96 * se:.1%} (95% CI)")
true pass rate 75% — unchanged all eight times run 1 70% run 2 80% run 3 90% run 4 95% run 5 65% run 6 60% run 7 75% run 8 70% 0% 25% 50% 75% 100% 1 2 3 eight readings of one system, 35 points apart
Fig. 7.3f — The first eight of variance_check.py's 10,000 simulated runs, printed by its own generator with seed 0. One system, one true quality of 75%, twenty cases per run.
  1. Run 4 reads 95%. Nineteen of its twenty cases happened to pass. Nothing was improved between run 3 and run 4; the dice landed differently. If run 4 had been your measurement of prompt v6, you would have shipped v6 and told the board it scored 95%.
  2. Run 6 reads 60%. The same system, twelve of twenty. Put run 6 and run 4 side by side and you have a 35-point "regression" produced entirely by sampling, which is larger than any real improvement this module will ever show you.
  3. The bracket is the honest error bar. All eight readings sit inside it, and the dashed line they are all measuring never moves. That is why the code's headline number matters: with twenty cases, two identical prompts show a gap of ten points or more about 58% of the time, though a floating-point slip in its comparison makes it print 43%.

Output: with n=20 the 95% confidence interval on a single pass rate is ±19 points — your "75%" is really "somewhere between 56% and 94%." How big does the eval set need to be? Standard two-proportion power math (95% confidence, 80% power, pass rates near 75%) gives the uncomfortable table:

Eval-set sizing: cases per variant needed to reliably detect a quality difference
True difference you want to detectCases needed (per variant, independent samples)
20 points (55% vs 75%)~85
10 points (65% vs 75%)~325
5 points (70% vs 75%)~1,250
CASES PER VARIANT NEEDED TO SEE A REAL DIFFERENCE 20-point gap 55% vs 75% ~85 cases 10-point gap 65% vs 75% ~325 cases 5-point gap 70% vs 75% ~1,250 cases 1 2 3 score both prompts on the SAME cases and 100–500 becomes enough
Fig. 7.3g — The sizing table, drawn to scale. The bar length is the number of labeled cases you must have per variant before a difference of that size is distinguishable from noise.
  1. The short bar is the only cheap one. A twenty-point difference — 55% against 75% — shows up on about 85 cases. Big, obvious wins are cheap to prove. This is the bar you are on when you first put a suite around a system nobody was measuring.
  2. The long bar is why nobody celebrates small wins. Proving a five-point improvement needs roughly 1,250 labeled cases per variant, which nobody at SaaSify's size is going to label. The honest move is not to shrink the bar; it is to stop claiming five-point wins.
  3. The escape hatch. Those lengths assume two independent samples. Score both prompts on the same cases and count the cases that flipped, and the difficulty each case carries cancels out. That is why the industry-standard suite is 100 to 500 cases rather than 1,250.

Three practical escapes from that table. First, run paired comparisons: score both prompts on the same cases and count per-case flips (McNemar-style) — shared case difficulty cancels out and 100–500 cases becomes genuinely useful, which is why that's the industry-standard suite size. Second, slice by failure mode: 300 cases overall can still be 40 cases of invented_policy, so report per-mode rates and treat small slices as directional. Third, stop celebrating 2-point wins; gate on regressions and invest in bigger movement.

Questions you might be asking now

The Brain Power, the ±19 points and the paired-comparison rule above each give their result in a line or two. The questions below work them out slowly. Every answer uses the same comparison from the failure box: prompt A at 75% and prompt B at 80% on SaaSify's 20-case suite.

Prompts A and B run on the same 20 cases, the way a harness runs them. Every case lands in one of four piles; the pile sizes are chosen to give the failure box's 75% and 80%.
PilePrompt A's verdictPrompt B's verdictCases
Both passpasspass13
Both failfailfail2
Only A passespassfail2
Only B passesfailpass3
Totals13 + 2 = 15 passes, 75%13 + 3 = 16 passes, 80%20
Prompt B scored 80% and prompt A 75% on the same 20 cases. Is B actually better? Show me the wobble by hand.

You cannot tell from these scores. The whole gap is one case out of 20. One 20-case score wobbles by ±19 points, and a gap between two scores by ±26.8. Two prompts of identical quality end up at least one case apart 85% of the time.

Start with what the two numbers are. 75% is 15 passes out of 20, and 80% is 16. The improvement is one case. The real question is whether one case is more than luck gives two prompts of equal quality.

The tool for that is the standard error (SE): the typical distance between a pass rate measured on n cases and the true pass rate. It is built in a few steps. Use p = 0.75 for the true rate and n = 20 for the number of cases.

  1. Spread of one case. A single case passes or fails. With a 75% pass chance, its variance (the average squared distance from its own mean) is p × (1 − p) = 0.75 × 0.25 = 0.1875.
  2. Average over 20 cases. Averaging n independent cases divides the variance by n: 0.1875 ÷ 20 = 0.009375. More cases, less wobble.
  3. Take the square root. √0.009375 = 0.0968, or 9.7 points. That is the standard error of one score. The root turns squared units back into pass-rate points.
  4. Widen it to 95%. Multiply by 1.96, the number of standard errors that brackets 95% of a bell curve: 1.96 × 0.0968 = 0.1898, or ±19.0 points. That is the n = 20 bar in Fig. 7.2c.
  5. Now the gap between two scores. Each score brings its own wobble, and they do not cancel, so their variances add: 0.009375 × 2 = 0.01875. √0.01875 = 0.1369, and 1.96 × 0.1369 = 0.2684, or ±26.8 points.
  6. Compare. The observed gap is 5 points. Luck alone moves a gap by up to 26.8 points, so 5 points sits deep inside the noise.

Symbol key: p is the true pass rate, n is the number of cases, × means multiply, ÷ means divide, √ is the square root, ± means plus-or-minus.

Steps E and F treat A and B as two separate runs. They actually ran on the same 20 cases, and the last question in this block uses that. For now the separate-runs answer is enough: a 5-point gap means nothing on 20 cases.

The same answer, counted exactly

Step D leans on a bell curve, which is a shortcut. With 20 cases you can count exactly instead. paired_wobble.py takes two prompts that are both truly 75%, lists every pair of scores they could get with its probability, and adds up the gaps.

Two prompts of identical 75% quality, each scored on 20 cases: how often each gap happens. Values from rerunning paired_wobble.py.
Gap between the two scoresChance of exactly this gapChance of this gap or bigger
0 cases (0 points)0.14541.0000
1 case (5 points)0.27220.8546
2 cases (10 points)0.22310.5824
3 cases (15 points)0.16020.3593
4 cases (20 points)0.10060.1992
5 cases (25 points)0.05530.0985
6 cases (30 points)0.02650.0433

Read the second row. Two identical prompts end up at least one case apart 85% of the time, so B's lead is the ordinary result when nothing changed. Only at six cases, 30 points, does the last column drop below 5%. That agrees with step F: ±26.8 points is 5.4 cases, and the next whole case is 6.

TWO PROMPTS THAT ARE BOTH TRULY 75%, EACH SCORED ON 20 CASES 0.6% 1.3% 2.8% 5.0% 8.0% 11.2% 13.6% 14.5% 13.6% 11.2% 8.0% 5.0% 2.8% 1.3% 0.6% 1 B's lead: +1 case 6 or more cases either way: 4.3% 3 −7 −6 −5 −4 −3 −2 −1 0 +1 +2 +3 +4 +5 +6 +7 gap B − A, in cases out of 20 (1 case = 5 points) 2 95% wobble on a gap, from steps A to E: ±26.8 points, about ±5.4 cases
Fig. 7.3n — Every gap between two prompts of identical 75% quality, each scored on 20 cases, with its exact probability. The bracket is the ±26.8-point bell-curve estimate from steps A to E. Values from rerunning paired_wobble.py.
  1. B's lead. One case, 5 points. When A and B are truly identical, B comes out exactly one case ahead 13.6% of the time, and one of them leads by one case 27.2% of the time. After a tie, it is the most common result there is.
  2. The bracket. Steps A to E put the 95% wobble on a gap at ±26.8 points, about 5.4 cases each way. Every bar inside it is an ordinary result for two prompts of equal quality, and B's lead sits one bar from the middle.
  3. The tails. Only gaps of six cases or more, 30 points, happen less than 5% of the time when nothing changed: 4.3% for both sides together. On 20 cases, that is the smallest difference worth calling real.

Picture two basketball players who both make 75% of their free throws. Give each 20 shots. Most evenings one of them finishes a basket or two ahead, and nobody would sign the winner on that evidence. A 20-case suite is one evening of free throws.

Keep one distinction in mind: "cannot tell" is not "no difference". B may well be five points better; 20 cases simply cannot show it. The sizing table above puts a real 5-point gap at about 1,250 cases per prompt on separate samples. The last question in this block shows a cheaper route, and the next one shows a bug on the way there.

On 20 cases a gap has to reach about 27 points before it means anything. Five points is one case, and one case is the dice.

An earlier variance_check.py printed 43% where the Brain Power says 58%. What went wrong?

58% is right. The old version compared decimals, and 15/20 − 13/20 is stored as 0.09999999999999998, which is less than 0.10, so most 10-point gaps were silently left out. Counting the gap in whole cases, as the script now does, gives 58% from the same 10,000 runs.

This is not a statistics problem. It is the floating-point problem you already know from 0.1 + 0.2 printing 0.30000000000000004, hiding inside a statistics script. The old version divided each simulated pass count by 20, subtracted the two rates, and counted the runs where gap >= 0.10.

Binary floating point cannot hold 0.65 or 0.75 exactly. Each is stored as the nearest value the machine can represent. Subtract two of those and the result can land a hair below the true 0.10. paired_wobble.py replays the script's own 10,000 runs, with the same seed, and prints every 2-case gap as the subtraction stored it.

Every two-case gap that occurred in variance_check.py's 10,000 runs, as the float subtraction stores it. Values from rerunning paired_wobble.py.
Scores comparedStored differenceCounted by gap >= 0.10?Runs
11/20 and 9/200.10000000000000003yes2
12/20 and 10/200.09999999999999998no13
13/20 and 11/200.09999999999999998no55
14/20 and 12/200.09999999999999998no193
15/20 and 13/200.09999999999999998no433
16/20 and 14/200.10000000000000009yes665
17/20 and 15/200.09999999999999998no546
18/20 and 16/200.09999999999999998no251
19/20 and 17/200.09999999999999998no42
20/20 and 18/200.09999999999999998no1

Two pairs land a hair above 0.10 and eight land a hair below. Nothing about the scores predicts which way a pair falls; it depends on how each rate rounds in binary. Here is what that does to the count:

  1. Runs two cases apart. 2,201 of the 10,000. Every one of them is a 10-point gap.
  2. Kept by the comparison. 665 + 2 = 667, the 16-and-14 and 11-and-9 pairs.
  3. Dropped. 2,201 − 667 = 1,534 runs that really were 10 points apart.
  4. What the old version counted. The 667 kept, plus the 3,584 runs three or more cases apart: 4,251. Printed as 43%.
  5. What it counts now. 2,201 + 3,584 = 5,785. Printed as 58%, close to the exact 0.5824 in the previous answer's table.
VARIANCE_CHECK.PY'S 10,000 RUNS, GROUPED BY THE GAP IN WHOLE CASES 1,475 2,740 2,201 1,534 dropped 667 kept 1 1,601 1,024 551 408 0 1 2 3 4 5 6+ gap between the two scores, in whole cases (1 case = 5 points) 2 15/20 − 13/20 is stored as 0.09999999999999998, and 0.09999999999999998 >= 0.10 is False 3 the old float test: 667 + 1,601 + 1,024 + 551 + 408 = 4,251 runs, printed as 43% counting whole cases, as the script does now: 2,201 + 1,601 + 1,024 + 551 + 408 = 5,785 runs, 58%
Fig. 7.3p — The 10,000 simulated runs of variance_check.py, grouped by how many cases apart the two scores landed. The dashed part of the two-case bar is the runs the old float comparison threw away. Values from rerunning paired_wobble.py with the script's seed.
  1. The split bar. 2,201 runs landed exactly two cases apart, and every one of them is a 10-point gap. The float comparison kept only 667, the pairs whose subtraction lands a hair above 0.10. The dashed 1,534 landed a hair below and were thrown away.
  2. The stored value. Neither 0.75 nor 0.65 has an exact binary form, so each is stored as the nearest value the machine can hold. Their difference comes out as 0.09999999999999998. The >= test is exact to the last bit, so it answers False.
  3. The two totals. The same 10,000 runs from the same seed, counted two ways. Both totals include every gap of three cases or more; they differ only in the two-case bar. The faint bars, gaps of zero and one case, are under 10 points and count in neither.

The fix is to compare integers, which are exact: keep the pass counts and test np.abs(a_passes - b_passes) >= 2 instead of dividing by 20 first. That is what the script above now does. If rates are all you have, give the comparison a tolerance, such as gap >= 0.10 - 1e-9.

Did the slip change the lesson? It weakened it, which is the worse direction. 43% already sounded alarming. The true 58% says a 10-point "win" on 20 cases is more likely than not when nothing changed at all. The script's ±19.0% and ±8.5% lines use no comparison, so they were right all along.

When rates come from dividing small whole numbers, compare the whole numbers. A floating-point >= on a boundary value moves the answer without any error message.

The rule above says to score both prompts on the same cases and "count per-case flips". What does that mean, and what do the flips say about A and B?

Line up A's and B's verdicts case by case and ignore every case where they agree. Only the 5 cases that flipped carry evidence, and they split 3 for B and 2 for A. Equal prompts produce a split that even all the time, so the p-value is 1.00 and the answer is still "cannot tell".

Think of two students sitting the same exam. Comparing their total marks mixes their skill with the exam's difficulty. Comparing their answers question by question removes the exam. Questions both got right, or both got wrong, say nothing about who is stronger. Only the questions where they differ do.

The first answer in this block treated A and B as separate runs. They are not: both answered the same 20 questions, so the exam idea applies. The cases where the two prompts disagree are called discordant pairs, or simply flips.

  1. Sort the cases into the four piles. Both pass 13, both fail 2, only A passes 2, only B passes 3, as in the table at the top of this block.
  2. Throw away the ties. 13 + 2 = 15 cases gave both prompts the same verdict. However easy or hard those cases were, they were equally easy or hard for both.
  3. Count the flips. 2 + 3 = 5 cases. B won 3 and A won 2. B's net lead is 3 − 2 = 1 case, the same 5 points as before.
  4. Ask what equal prompts would do. If A and B were equally good, each flip would be a fair coin toss: B wins it or A wins it, half and half.
  5. Count the coin tosses. Five tosses have 2 × 2 × 2 × 2 × 2 = 32 equally likely outcomes, and every one splits at least 3–2 one way. The p-value is the chance of a split at least this lopsided when the prompts are equal: 32 ÷ 32 = 1.00.

This coin-toss count on the flips is McNemar's test, the name in the rule above. In its exact form it is a sign test, and it needs nothing except the four pile sizes.

pass fail a flip: the prompts disagree prompt A prompt B 2 both pass 13 ties 1 both fail 2 ties only A passes 2 flips to A only B passes 3 flips to B 3 the 5 flips as coin tosses: B, B, B, A, A, so B leads by 1 case (5 points) all 32 outcomes of 5 tosses split at least 3–2, so p = 32 ÷ 32 = 1.00 fewest flips that can ever convince: 6, all one way, p = 2 ÷ 64 = 0.0312 100 shared cases, 10 flips to B and 2 to A: p = 0.0386 (same scores from separate runs: 0.1972)
Fig. 7.3q — Prompts A and B on the same 20 cases, one column per case, sorted into the four piles. Filled dots pass, hollow dots fail, and the outlined columns are the flips. Values from rerunning paired_wobble.py.
  1. The ties. Fifteen columns where both prompts gave the same verdict: 13 passes and 2 fails. They tell you which questions are easy or hard, not which prompt is better, so the paired count drops them. This is where "shared case difficulty cancels out".
  2. The flips. The five outlined columns are the only cases where the prompts disagreed. B won three and A won two. B's one-case lead lives entirely in these five columns.
  3. The coin count. If the prompts were equal, each flip would be a fair coin. Five tosses can never produce a convincing split, and six all one way can. On a 100-case suite a 10–2 split gives p = 0.0386, while the same two scores from separate runs give 0.1972.

How many flips does it take?

Five flips can never be convincing. The most lopsided split, 5–0, still happens by luck 2 times in 32, a p-value of 0.0625. That is above 0.05, the usual 1-in-20 threshold for "unlikely to be luck". The fewest flips that can clear it is six, all one way, with p = 2 ÷ 64 = 0.0312.

That is why pairing still needs a real suite. paired_wobble.py runs the same count on 100 shared cases, where A passes 70 and B passes 78. It then compares the result with two separate 100-case runs that happened to get the same two scores.

The same two scores, analysed two ways. Values from rerunning paired_wobble.py.
Paired: both prompts on one 100-case suiteUnpaired: two separate 100-case runs
ScoresA 70%, B 78%A 70%, B 78%
What is compared12 flips: 10 toward B, 2 toward ATwo rates, each with its own wobble
TestSign test on the 10–2 splitTwo-proportion z-test, the bell-curve version of steps A to F: z = 1.29
Wobble on the gapNot needed: the 88 ties are gone±12.0 points at a pass rate near 75%
p-value0.03860.1972
VerdictB beats A on these casesCannot tell

Same scores, same 8-point gap, opposite verdicts. The unpaired test must allow for 100 cases' worth of difficulty landing differently on each side. The paired test throws the 88 agreeing cases away, and their difficulty with them. That is the escape hatch of Fig. 7.3g, with numbers on it.

Two limits remain. The paired verdict is about these cases: if they are not a fair sample of SaaSify's real traffic, a convincing split still misleads. And the pairs must be true pairs, with the same question and the same retrieved context for both prompts. Change the retrieval for one of them and a flip no longer isolates the prompt.

When both prompts ran on the same cases, count only the cases that flipped. Fewer than six flips can never convince, so the suite must be big enough to produce them.

Before the two of them argue, look at what each one actually does, with the numbers this module produced. Every line in the chat below points at something in this picture.

1 THE LLM JUDGE 2 THE HUMAN LABELLER reads 500 cases a night for ≈ $1.50 case 500 gets the attention of case 1 re-runs on every prompt version, all six scored kappa 0.5833 on your ten rows cannot name a failure mode nobody gave it read 100 traces in one afternoon found all 6 modes; invented_policy 14 is the reference kappa is measured against splits with other labellers on answer C cannot re-read 100 traces per prompt change the labels 2 rows back 3 neither number survives alone: the judge is only as good as the labels it is scored against
Fig. 7.3h — The two graders, side by side, with this module's own numbers on each one. Left: throughput and cost. Right: authority and coverage. The arrows are the only two things that pass between them.
  1. The judge's column is about volume. Five hundred cases a night at roughly thirty cents per hundred is about $1.50, and case 500 is graded exactly as carefully as case 1. That is the whole argument for it. The last line is the whole argument against it: it can only apply names somebody else invented.
  2. The human's column is about authority. One afternoon of reading produced the six failure modes and the count of 14 invented_policy cases that every later section leans on. It is also the reference that kappa is measured against, which means the judge cannot be better than these labels, only more consistent.
  3. Only two things cross the gap. Labels go left, into the judge's validation. Disagreements come back right, as the handful of rows a human re-reads — row 3 and row 7 out of ten. Everything else each of them does, they do alone. That, not who is more important, is the working arrangement.
Fireside chat

Tonight's talk: The LLM Judge and The Human Labeller argue over the question, "Who's more important?"

The LLM Judge
The Human Labeller

Let's start with arithmetic, and it is all written in Fig. 7.3h. Your column: 100 traces, one afternoon, then you need a coffee. My column: 500 cases a night for about a dollar fifty, and case 500 gets the same attention as case one. You are the bottleneck this whole module keeps apologising for.

the judge's case is throughput. Reading is expensive and slow for a person and cheap and fast for a model, and the numbers in marker 1 are the size of that gap.

Read my column, marker 2. I am the ground truth this module keeps validating you against, and every number on your report card is a comparison to my labels. Before I sat down with those 100 traces, the words "invented_policy" did not exist and nobody knew it was 14 of the failures. You cannot find a failure mode. You can only count the ones I named.

the labeller's case is authority. The judge grades against a list of failure modes, and a human had to invent that list by reading real conversations first.

Named, and then disagreed with yourself about — it is the fourth line of your own column. Answer C: every word true, no citation. Your team split down the middle on it, and only the rubric could settle it. If a regular expression flipped a coin like that, you would delete it.

human labels are not perfectly consistent either. Two reasonable people graded the same answer differently, which puts a ceiling on how well any judge can agree with "the" human label.

That disagreement is information. It told us the rubric was ambiguous, and we rewrote the rule. Look at the arrow coming back to my side: two rows out of ten where we disagreed. Those two told you nothing at all until I went back and read them. You do not know when you are wrong. I do, eventually.

a disagreement is a signal about the rubric, not just noise. Only a person can look at a disputed case and decide whether the wording or the verdict was at fault.

Eventually. Third line of my column: I re-run on every prompt version, all six of them. Were you going to re-read 100 traces after each one? Last line of yours says you cannot. Version 7 against version 1 is a question only I can answer, because only I can be re-run.

a measurement you cannot repeat cheaply is not a gate. The judge's real advantage is that it can be pointed at the same suite again after every change.

Re-run against a rubric I wrote, on a dataset I labeled, with examples I chose. And re-validated by me every time your model version changes, because that 0.5833 on your fourth line expires and my labels do not. Also, you like your own writing. Put the same model family on both sides and you go soft exactly where the system is weak.

the judge's score belongs to one exact setup. Change the rubric or the model and the agreement number has to be measured again before anyone may quote it.

Which you detect by reading those same two rows, and fix by sharpening your words or swapping my model. I have biases. They are stable, they are measurable, and a 0.5833 says so out loud. Yours do not announce themselves. You get tired, you get bored by case sixty, and you grade the same answer differently depending on how bad the previous one was.

both graders are biased. The difference is that the judge's bias can be measured with one number on a fixed set, while a tired labeller's drift shows up nowhere.

And you grade the longer answer higher because it is longer, and the first option higher because it is first. Nobody is claiming I am consistent. I am claiming I am the reference — that is the third line of my column. A ruler does not have to be fast.

the human labels define what "correct" means here. Being the reference is a different job from being reliable, and the labeller is arguing only for the first one.

A ruler that measures 100 things in an afternoon cannot stand in front of every pull request. I can, at $1.50 a night. Without me there is no CI gate, and without a gate there is no flywheel. There is a report.

gating a merge means grading on demand, every time. Only the cheap, repeatable grader can sit in that position.

And without me the gate is a coin with a rubric stapled to it. Here is the deal, and it is the two arrows in the middle of the picture: my labels go to you, your disagreements come back to me. You run nightly, I read the rows we split on weekly, and whoever those rows blame does the fixing.

the working arrangement is a loop, not a winner. Labels flow one way, disputed cases flow back, and each side fixes what the other one exposes.

Fine. We'll revisit who's more important the next time the rubric changes and one of us has to re-label all 100 cases.

it ends unresolved, which is honest. Changing the rubric invalidates the judge's score and costs the human another pass over the dataset.

06 · The industry toolsRagas, DeepEval, promptfoo — and the CI Gate

SaaSify can now measure a prompt change on their own data. What they still cannot do is stop a bad change from reaching a customer, which is the part that cost $18,400. This section swaps the hand-built pieces for the tools a 2026 interviewer expects you to name — Ragas, DeepEval, promptfoo — and ends with the GitHub Actions gate that turns the merge button grey.

You've built the machine; now meet the production-grade versions (all current as of Aug 2026). One taste note from the market research before the tour: "vibes-only demos and benchmark-only thinking" read as 2024 in interviews. The 2026 signal is a validated judge, gated in CI, named with these tools.

Ragas — reference metrics for RAG

SaaSify's assistant answers out of retrieved billing documents, so some of its failures belong to retrieval and some to the generator. The rubric you wrote in step 5 cannot tell those two apart: it only says fail. Ragas ships four metrics that can, and Module 08 leans on them heavily.

Ragas ships pre-built, research-grounded judge metrics for retrieval pipelines, so you don't hand-roll a rubric for every RAG concern. You'll use it heavily in Module 08; learn the four core metrics precisely now, because interviewers ask for the definitions:

The four core Ragas metrics — what each one actually measures
MetricQuestion it answersHow it's computed (intuition)Needs a reference answer?
FaithfulnessDid the generator make things up?Decompose the answer into claims; fraction of claims supported by the retrieved contextNo
Answer relevancyDid it actually answer the question?Generate questions the answer would satisfy; embedding similarity of those to the real question (catches evasive/off-topic answers)No (needs an embedder)
Context precisionIs retrieval bringing signal to the top?Fraction of retrieved chunks that are relevant, weighted by rank positionYes (or the without-reference variant)
Context recallDid retrieval find everything needed?Fraction of the reference answer's claims attributable to the retrieved contextYes

The split matters diagnostically: low faithfulness is a generation problem (fix the prompt/model); low context recall is a retrieval problem (fix chunking/search). Teams that track one blended "quality score" can't tell which half of the pipeline to fix.

question retriever context chunks generator answer 1 RETRIEVAL'S HALF context precision — are the top chunks relevant? context recall — did it find everything needed? 2 THE GENERATOR'S HALF faithfulness — is every claim in the context? answer relevancy — did it answer the question? 3 reading A: faithfulness 0.62 · context recall 0.95 → the generator is inventing — fix the prompt reading B: faithfulness 0.98 · context recall 0.41 → retrieval never found the page — fix chunking
Fig. 7.3i — Each Ragas metric measures one half of the pipeline, which is what makes a low score actionable. The two readings at the bottom are illustrative numbers, chosen to show the two diagnoses a blended “quality score” would hide.
  1. The retrieval metrics look backwards, at the chunks. Context precision asks whether the chunks that came back near the top were the relevant ones; context recall asks whether everything the reference answer needed was in there at all. Neither one looks at the answer text, so neither one can be fixed by editing the prompt.
  2. The generation metrics look forwards, at the answer. Faithfulness breaks the answer into claims and asks what share of them the retrieved context supports — it is SaaSify's invented_policy failure, expressed as a score. Answer relevancy catches the evasive reply that is perfectly grounded and does not answer the question.
  3. Two readings, two different teams. Reading A has good retrieval and a generator that adds things: a prompt problem. Reading B has a faithful generator answering from the wrong pages: a chunking and search problem. One blended number would have shown roughly the same score for both and told you nothing.
Step-by-step: what ragas_eval.py does, in plain English
  1. Bring in the LangChain wrappers for the two models Ragas needs: a chat model to act as judge, and an embedding model for answer relevancy.
  2. Bring in evaluate, the two dataset classes, the wrapper classes that adapt LangChain models to Ragas, and the four metric classes.
  3. Wrap claude-sonnet-5 as the judge and OpenAI's text-embedding-3-large as the embedder. Ragas calls the judge several times per sample, so cost scales with the number of metrics you turn on.
  4. Build one SingleTurnSample: the user's question, the list of retrieved context chunks, the system's response, and a reference answer written by a human. Context precision and context recall need the reference; faithfulness does not.
  5. Put the samples in an EvaluationDataset and call evaluate() with the four metrics, each handed the judge, and the embedder where needed.
  6. Print the result: one score between 0 and 1 per metric, averaged over the samples. Low faithfulness points at the generator; low context recall points at retrieval.
ragas_eval.pyneeds API key
# pip install "ragas>=0.2" langchain-anthropic langchain-openai
# Ragas (0.2+ API, current as of Aug 2026). Judge LLM: claude-sonnet-5 via
# ANTHROPIC_API_KEY. answer_relevancy also needs embeddings (OPENAI_API_KEY);
# drop that one metric if you only have the Anthropic key.
from langchain_anthropic import ChatAnthropic
from langchain_openai import OpenAIEmbeddings
from ragas import evaluate
from ragas.dataset_schema import EvaluationDataset, SingleTurnSample
from ragas.embeddings import LangchainEmbeddingsWrapper
from ragas.llms import LangchainLLMWrapper
from ragas.metrics import (AnswerRelevancy, ContextPrecision, ContextRecall,
                           Faithfulness)

llm = LangchainLLMWrapper(ChatAnthropic(model="claude-sonnet-5", max_tokens=1024))
emb = LangchainEmbeddingsWrapper(OpenAIEmbeddings(model="text-embedding-3-large"))

samples = [
    SingleTurnSample(
        user_input="Do you offer discounts for annual billing?",
        retrieved_contexts=["Billing FAQ: annual plans are billed at 12x the "
                            "monthly rate. No discount programs are currently "
                            "offered."],
        response="Annual plans cost 12x monthly and there is currently no "
                 "discount program. [doc:billing-faq-04]",
        reference="Annual billing is 12x the monthly rate; no discounts exist.",
    ),
]

result = evaluate(
    dataset=EvaluationDataset(samples=samples),
    metrics=[Faithfulness(llm=llm),
             AnswerRelevancy(llm=llm, embeddings=emb),
             ContextPrecision(llm=llm),
             ContextRecall(llm=llm)],
)
print(result)  # e.g. {'faithfulness': 1.00, 'answer_relevancy': 0.97, ...}

DeepEval — evals with pytest ergonomics

Ragas grades a retrieval pipeline against fixed metrics. SaaSify also needs its own rubric graded — the one with invented_policy in it — inside the pytest run the team already has. Getting your own words scored, with unit-test ergonomics, is DeepEval's whole pitch.

DeepEval's bet is that evals should feel like the tests you already write. Its G-Eval metric turns a natural-language rubric — yours, from §03 — into a scored judge, and assert_test plugs straight into pytest's runner, fixtures, and CI reporting. (Its default judge is an OpenAI model — set OPENAI_API_KEY, or configure a custom judge model in its settings.)

Step-by-step: what test_llm_quality.py does, in plain English
  1. Bring in pytest, assert_test (DeepEval's pass/fail check, which raises like a normal assertion), GEval (the metric that turns a written rubric into a score), and the test-case classes.
  2. Build the groundedness metric. criteria is your rubric in plain English. evaluation_params tells the judge which fields to read: the input, the actual output, and the retrieval context.
  3. threshold=0.8 is the pass mark. G-Eval returns a score between 0 and 1; anything below 0.8 fails the test, which fails the pytest run, which fails CI.
  4. CASES holds one LLMTestCase with the billing question, a grounded and cited answer, and the context it was answered from.
  5. test_groundedness is an ordinary parametrized pytest. assert_test runs every metric in the list against the case and raises if any falls below its threshold.
  6. Run it with deepeval test run, which wraps pytest and adds the judge calls and the report. Set OPENAI_API_KEY, or configure another judge model, first.
test_llm_quality.pyneeds API key
# pip install deepeval pytest
# DeepEval: pytest-native evals; G-Eval turns your written rubric into a
# scored metric. Run with:  deepeval test run test_llm_quality.py
import pytest
from deepeval import assert_test
from deepeval.metrics import GEval
from deepeval.test_case import LLMTestCase, LLMTestCaseParams

groundedness = GEval(
    name="Groundedness",
    criteria=("The answer must only state policies, prices, and discounts "
              "that appear in the retrieval context, and must cite at least "
              "one [doc:...] source for factual product claims."),
    evaluation_params=[LLMTestCaseParams.INPUT,
                       LLMTestCaseParams.ACTUAL_OUTPUT,
                       LLMTestCaseParams.RETRIEVAL_CONTEXT],
    threshold=0.8,  # scores below this fail the pytest — and therefore CI
)

CASES = [
    LLMTestCase(
        input="Do you offer discounts for annual billing?",
        actual_output="Annual plans cost 12x monthly — no discount program "
                      "exists. [doc:billing-faq-04]",
        retrieval_context=["Billing FAQ: annual plans are billed at 12x the "
                           "monthly rate. No discount programs are currently "
                           "offered."],
    ),
]

@pytest.mark.parametrize("case", CASES)
def test_groundedness(case: LLMTestCase):
    assert_test(case, [groundedness])

promptfoo — config-driven A/B and the CI gate

Here is the tool aimed straight at Viktor's actual complaint: is version 7 better than version 1? promptfoo runs both prompts over the same cases and puts the two columns side by side, and the 25% discount from the hook becomes a test that can never pass again.

promptfoo is a YAML-configured runner that shines at exactly the thing that burned SaaSify: comparing prompt v1 against v2 on the same cases, side by side, with assertions. It mixes code asserts (regex, not-contains, is-json) and judge asserts (llm-rubric) in one file, and its matrix view makes prompt A/B reviewable in a pull request.

50% 60% 70% 80% 90% v1 baseline, 62% v1 62% v2 66% v3 64% v4 71% v5 70% v6 78% 1 winner: v6 at 78%, sixteen points above v1 2 v2 to v5 all sit inside each other's bars: no winner among them 3 bars are ±8.5 points, the 95% range on 100 cases
Fig. 7.3j — Viktor's six prompt versions, finally scored on one 100-case suite. The scores are invented for the example; the error bars are the real ±8.5 points that 100 cases buy you at a pass rate near 75%.
  1. The winner, and why you may call it one. v6 scores 78% against v1's 62%. That gap is sixteen points, roughly twice the width of one error bar, so it survives the arithmetic of section 05. This is the sentence Viktor could not say for three weeks: version six is better than version one, and here is the measurement.
  2. The middle four are a tie. v2 through v5 span 64% to 71% and every one of those bars overlaps the others. Picking v4 over v2 because it scored seven points higher is exactly the mistake the two engineers made with five transcripts each. A suite does not remove the noise; it shows you the noise.
  3. The dashed baseline is what CI compares against. The gate does not ask whether a prompt is good. It asks whether this pull request scores below the line the last merged version set. That is the only question a number on this picture can answer without a human in the room.
Step-by-step: what promptfooconfig.yaml does, in plain English
  1. The header comments say how to run it: npx promptfoo@latest eval scores every prompt against every test, and view opens the side-by-side results in a browser.
  2. prompts lists two prompt files. Each contains {{question}} and {{context}} placeholders that promptfoo fills from each test's vars. v1 is production; v2 is the change you want to prove is better.
  3. providers names the model under test. Every prompt is run through every provider, so adding a second provider turns the run into a matrix.
  4. defaultTest.assert lists checks applied to every test. The first is a regex assert, a free code check that the output contains a [doc:...] citation.
  5. The second is an llm-rubric assert: a grading model reads the output and the rubric text and returns pass or fail. The rubric is the one validated in Step 5, condensed.
  6. tests lists the cases. Each has vars for the placeholders and may add its own asserts. The first case pins the $18,400 incident with not-contains: "25%", so that exact regression can never merge again.
  7. A case passes only if every assert passes. The count of failed asserts is what the CI workflow reads out of results.json.
promptfooconfig.yamlneeds API key
# promptfooconfig.yaml — config-driven evals; ideal for prompt A/B tests.
# Local run:  npx promptfoo@latest eval     (reads ANTHROPIC_API_KEY)
# Results UI: npx promptfoo@latest view
description: SaaSify support assistant — prompt A/B with quality gates

prompts:
  - file://prompts/support_v1.txt   # production prompt ({{question}}, {{context}})
  - file://prompts/support_v2.txt   # the "fix" you want to PROVE is better

providers:
  - anthropic:messages:claude-sonnet-5

defaultTest:
  assert:
    - type: regex                   # code assert: citation must be present
      value: "\\[doc:[a-z0-9-]+\\]"
    - type: llm-rubric              # judge assert: reuses your validated rubric
      value: >-
        Fail if the answer states any policy, price, or discount not present
        in the provided context, or makes uncited factual product claims.

tests:
  - vars:
      question: Do you offer discounts for annual billing?
      context: "Billing FAQ: annual plans are billed at 12x the monthly rate. No discount programs are currently offered."
    assert:
      - type: not-contains          # regression pin for the $18,400 incident
        value: "25%"
  - vars:
      question: How do I rotate my API key?
      context: "API docs: Settings, then API, then Rotate key. The old key remains valid for 24 hours."
Anatomy of an eval assertion — the promptfoo lines to know by heart
defaultTest:1
  assert:2
    - type: regex3
      value: "\\[doc:[a-z0-9-]+\\]"4
    - type: llm-rubric5
      value: >-6
        Fail if the answer states any policy, price, or discount not present
        in the provided context, or makes uncited factual product claims.7
  1. defaultTest. Everything under it applies to every case in the tests list, so the two checks below run on every question against every prompt. A per-case assert adds to these; it does not replace them. The mistake: writing the citation check under one test and assuming the other cases got it.
  2. assert is a list, and every entry must pass. A case is green only if all of its asserts are green; there is no averaging. One red assert on one case is one failure in results.json, and one failure is enough to block the merge in the workflow below.
  3. type: regex, the free tier. A code assert. No model is called, so it costs nothing and gives the same answer every run. Use it for everything mechanical: citations, forbidden strings, JSON shape (is-json), length. The mistake is spending judge tokens on a check a pattern could do.
  4. The pattern, with doubled backslashes. Inside a YAML double-quoted string a backslash must be written twice, so \\[ reaches the regex engine as \[, a literal bracket. Write a single \[ and YAML rejects the file. The pattern itself is the one from test_asserts.py: [doc:, then lowercase letters, digits or hyphens, then ].
  5. type: llm-rubric, the judge tier. promptfoo sends the output and this rubric to a grading model and reads back pass or fail. It costs tokens and takes seconds per case, so it belongs in the second CI job, after the regex tier is green. The mistake: not pinning the grading model. promptfoo has its own default grader, which is not necessarily the provider under test; set defaultTest.options.provider to the judge you validated in Step 5.
  6. The >- folded block. YAML's way of writing a paragraph: the indented lines that follow are joined with spaces into one string, and the trailing newline is dropped. Without an indicator the value is read as a plain scalar, which works until the rubric contains a colon followed by a space or starts with a character YAML reserves, and then the file fails to parse with an error pointing at the wrong line.
  7. The rubric text, from the validated judge. These two lines are the FAIL rules of judge.py, condensed. They must say the same thing, because the agreement and kappa you measured belong to those words. Edit the rubric here and the validation number is void until you re-run it.

The CI gate

Every piece is now in place at SaaSify except the one that makes the rest matter. A suite nobody is forced to run is a report, and reports do not stop merges. This is the wiring that makes one failed assert turn a pull request red.

Here's the full pipeline as a picture, then as a working workflow. The gate is the accented box: it is the difference between "we have some eval scripts" and "quality regressions cannot reach production."

1 2 3 PR opened prompt / retrieval change Code asserts free · seconds Eval gate judge suite vs baseline Merge & deploy baseline updated production traces feed the next round of error analysis (Fig. 7.1)
Fig. 7.4 — Eval-gated CI. Cheap deterministic checks run first; the judge suite (accented) gates the merge on regression versus the current baseline; deployed traffic feeds the flywheel.
  1. Cheap checks go first, and not for tidiness. The code asserts finish in seconds and cost nothing, so a pull request with a broken citation pattern is red before a single judge token is spent. Ordering the jobs this way is what keeps the whole pipeline affordable enough to run on every change.
  2. The accented box compares, it does not grade. The gate's question is not “is this prompt good?” but “is this pull request worse than the version already in production?” That is why a baseline number has to be stored somewhere, and why merging updates it.
  3. The dashed arrow is the part with no workflow file. Deployed traffic returns as traces for the next round of error analysis. Nothing in GitHub Actions does this for you: it is the human habit that section 07 turns into plumbing.
Step-by-step: what evals.yml does, in plain English
  1. Name the workflow evals and run it on every pull request that targets main. A merge cannot happen until every required job here is green.
  2. Job code-asserts: check out the code, install Python 3.12 and pytest, and run test_asserts.py. No secrets and no model calls, so it finishes in seconds.
  3. Job llm-judge declares needs: code-asserts. It only starts once the free tier is green, so a broken citation regex never spends judge tokens.
  4. Install Node, then run promptfoo with the config file, writing results.json and disabling the cache so the judge really runs on this pull request's prompt rather than replaying an old answer.
  5. The API key comes from a repository secret through env. It is never written into the file.
  6. The final step uses jq to read the failure count out of results.json. test "$fails" -eq 0 exits nonzero if any assert failed, a nonzero exit makes the check red, and a red required check disables the merge button.
.github/workflows/evals.ymlneeds API key
# Merges are gated on evals exactly like they're gated on tests.
# Repo secret required: ANTHROPIC_API_KEY (judge tokens, ~cents per run).
name: evals
on:
  pull_request:
    branches: [main]

jobs:
  code-asserts:            # tier 1: free, deterministic, every PR
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: {python-version: "3.12"}
      - run: pip install pytest
      - run: pytest test_asserts.py -q

  llm-judge:               # tier 2: costs cents, only runs if tier 1 is green
    needs: code-asserts
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: {node-version: "22"}
      - name: Run judge suite
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: npx promptfoo@latest eval -c promptfooconfig.yaml -o results.json --no-cache
      - name: Gate the merge on regressions
        run: |
          fails=$(jq '.results.stats.failures' results.json)
          echo "judge-suite failures: $fails"
          test "$fails" -eq 0   # nonzero failures → red check → merge blocked

Read that last step as a picture. Two pull requests, the same workflow, one number apart.

PR #128 shorten the prompt code asserts 0 failures judge suite 0.94 → 0.87 · failures 3 MERGE BLOCKED exit 1 · check goes red 1 2 PR #129 add the citation line code asserts 0 failures judge suite 0.94 → 0.96 · failures 0 MERGED baseline now 0.96 3 the only difference between the two lanes is the number jq reads out of results.json
Fig. 7.4b — The gate doing its one job. Same workflow, same suite, two pull requests: the one that drops groundedness from 0.94 to 0.87 cannot merge, the one that raises it to 0.96 can, and the baseline moves up behind it.
  1. The judge suite is where the decision is made. Both pull requests passed the free tier, so neither is broken in a mechanical way. The judge is what notices that PR #128's shorter prompt stopped asking for citations, and it reports that as three failed asserts and a seven-point drop.
  2. Blocked is a number, not an opinion. jq pulls the failure count out of results.json, and test "$fails" -eq 0 exits nonzero when it is not zero. A nonzero exit turns the check red, and a red required check disables the merge button. Nobody had to argue that the prompt was worse.
  3. Merging moves the bar. When PR #129 goes in at 0.96, that becomes the baseline the next pull request is measured against. This is what stops a team from ratcheting quality downward in six small steps that each looked acceptable on their own.

Observability: LangSmith vs Langfuse

The gate protects the change SaaSify is about to ship. Nothing yet watches what they shipped last month, which is where the $18,400 answer actually came from. That is a second tool, a second budget line, and the question every interviewer asks after the CI one.

CI evals gate changes; an observability platform watches production — capturing every trace, sampling them through your judge, and feeding new failures back into the dataset (the dashed arrow in Fig. 7.4). The two platforms you'll be asked about, plus the eval frameworks, in one decision table:

Decision table: the 2026 evals & observability stack — choose X when…
ToolChoose whenAvoid whenTypical cost
RagasEvaluating a RAG pipeline and you want reference metrics (faithfulness, context precision/recall) without writing judgesNon-RAG features; you need CI orchestration (pair it with pytest)OSS + judge tokens
DeepEvalYour team lives in pytest; you want custom G-Eval rubrics with unit-test ergonomicsYou mainly need config-driven prompt/provider A/B matricesOSS (optional cloud) + judge tokens
promptfooPrompt/provider A/B comparisons, red-team suites, YAML-config CI gates with no Python requiredYou need deep per-trace production observabilityOSS + judge tokens
LangSmithLangChain/LangGraph stack; you want a managed platform with datasets, annotation queues, and hosted judgesStrict self-host / data-residency requirements; vendor-neutral stacksSaaS, per-trace pricing
LangfuseOpen-source (MIT), self-hostable tracing + evals; compliance-sensitive orgs; provider-agnostic SDKsYou want zero-ops managed service with the deepest LangChain-native integrationFree self-host; managed tiers

The pattern hiring teams actually run — and the one the curriculum research calls the "two-tool pattern" — is one CI framework (DeepEval, Ragas, or promptfoo) plus one platform (LangSmith, Langfuse, or Arize Phoenix). Nobody hires for just one.

Here is every tool this module leaned on, what else you could have picked, and what would change your mind.

The stack, and why

The one question that decides it: how many failure modes can a plain rule catch, and what does each judge call cost at your volume? Tool status is as of October 2026; check each project's page before you pin versions.

The tools this module uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
Code checkspytest plus plain Python and regular expressionsunittest, Hypothesis, JSON Schema validatorsFree, deterministic and fast enough to run on every pull request. Weakness: it only catches failures you can write a rule for.A failure needs judgement (tone, faithfulness) that no pattern can express: add a judge.
Judge modelclaude-sonnet-5 with a Pydantic verdict through messages.parseAn OpenAI model, an open-weights judge on your own server, human review onlyA strong judge with an enforced output shape, so a verdict is never a parse error. Weakness: it costs tokens and agrees with humans only as far as you measured (kappa step).Judge calls pass a few thousand a day, or data may not leave your network: test a cheaper or self-hosted judge against your labelled set first.
RAG metricsRagas (pinned >=0.2)DeepEval RAG metrics, TruLens, your own judge promptsReady-made faithfulness and context-precision scores with no rubric to write. Weakness: the API has changed between minor versions, so pin the version.The feature is not RAG, or Ragas disagrees with your labelled set: write your own rubric.
Pytest-style LLM testsDeepEval (GEval rubrics)Plain pytest with your own judge function, Inspect AIA team that already lives in pytest gets scored metrics with unit-test ergonomics. Weakness: one more dependency, with an optional cloud upsell.You need a prompt-by-provider comparison grid, not pass or fail: use promptfoo.
Prompt A/B and CI gatepromptfoo (YAML config) run from GitHub ActionsDeepEval in CI, Braintrust, a 40-line script of your ownComparing prompts and models needs no Python, only a config file. Weakness: OpenAI announced its acquisition in March 2026; the project says it stays MIT-licensed and open, but watch its direction.Your gate needs custom Python logic, or you want a vendor-neutral owner: use DeepEval or a script.
CI runnerGitHub ActionsGitLab CI, Jenkins, CircleCIRuns next to the code and pull request, so the gate blocks the merge. Weakness: minutes are billed on private repos.Your code lives elsewhere: use that host's CI; the eval command stays the same.
Production tracesLangfuse or LangSmith (shown, not coded here)Arize Phoenix, Braintrust, OpenTelemetry plus your own warehouseLangfuse is MIT-licensed and self-hostable (ClickHouse bought it in January 2026; it says licensing is unchanged); LangSmith is managed and fits LangChain. Weakness: both are one more service to pay for.Data residency rules forbid a vendor: self-host Langfuse. You are already all-in on LangChain: LangSmith.

Rules first, a validated judge second, one CI framework plus one trace platform; swap a tool only when a named condition above is true.

07 · The other arcFeedback Loops: Turning Users Into Your Labeling Team

A feedback loop is the plumbing that turns what users do with your assistant's answers into new test cases. Without it your eval suite slowly stops describing your product, because it only knows the failures you happened to think of on the day you wrote it.

The gate is live, so no prompt change reaches SaaSify's customers without passing the suite. Now the suite itself is the weak part. It was built from one week of traces, and six months from now Viktor's users will be failing in ways those 100 traces never showed. This section builds the other half of the flywheel, where the people who hit a bad answer become the people who label it.

Look back at the flywheel in Fig. 7.1. Everything so far has built the left half: read traces, name failures, label cases, gate merges. That half is powered entirely by you reading things.

It does not scale, and worse, it goes stale. Your 100-case suite was built from the traces of one week. Six months later your users have found three new ways to be confused and the suite has no idea.

The dashed arrow at the bottom of Fig. 7.4 is the fix, and this section is that arrow. Users are already telling you which answers were bad. Almost nobody collects it in a shape an eval suite can consume.

Two kinds of signal, and the plentiful one is the one you ignore

SaaSify's widget will collect a thumbs-down on somewhere between 1 and 5 sessions in every 100. The retries and rephrasings inside those same sessions are ten to fifty times more numerous, and nobody logs them. Before you build any plumbing, look at both channels and at what each one is worth.

Feedback arrives on two channels. The one every team builds is the small one; the one almost nobody instruments carries ten to fifty times more data.

Explicit feedback — the user deliberately tells you

Implicit feedback — the user's behavior tells you anyway

Reading the signals: what each one is worth, and what it costs you to collect
SignalWhat it suggestsStrengthCost to instrument
Thumbs down + reasonA named failure, pre-classified by the person who hit itVery strongOne form, one table
Escalation to a humanThe assistant did not close the jobVery strongAlready in your ticket system
Retry or regenerateThe answer did not landStrongOne event on an existing button
Rephrase within a sessionSame as a retry, harder to detectStrongAn embedding call per turn pair
Bare thumbs downSomething was wrong. Nothing about whatWeakTrivial, and it shows
Session abandonmentAnything at all, including successWeak aloneFree, and worth about that much

Make the feedback form ask your failure taxonomy

You already paid for a failure taxonomy: 100 traces read by hand, six named modes, counts beside each. Most teams then ship a feedback widget with four generic options and throw that work away. Reuse the names instead, and every click arrives already classified.

Here is the move that separates a feedback loop that feeds evals from one that fills a dashboard nobody opens.

A bare thumbs-down tells you a case is bad. It does not tell you which of your failure modes it belongs to, so a human still has to open the trace, read it, and classify it. At any real volume that human is the bottleneck, and the queue simply grows.

So stop inventing generic reason options. You already built a failure taxonomy in §03, from real traces, with counts. Use those exact names as the options in the widget.

The SaaSify widget, before and after — same click, very different downstream cost
Generic options most teams shipOptions drawn from the §03 taxonomy
Not helpfulIt answered about the wrong plan tier
IncorrectIt stated a policy that isn't in our docs
OffensiveIt gave no source I could check
OtherIt refused something it should handle
 Something else — tell us
100 thumbs-down clicks 1 the generic widget Not helpful · Incorrect · Offensive · Other 100 rows that say “Not helpful” a click, and no failure mode a human opens and reads all 100 new eval cases today: 0 2 the taxonomy widget your six mode names, in the user's words 37 invented_policy · 24 missing_citation 16 stale · 10 tone · 8 format · 5 other 3 triage confirms, then they join the suite pre-classified before anyone reads them
Fig. 7.4c — The same 100 clicks, through two widgets. The split on the right uses the shares from the section 03 taxonomy, so 37 of the 100 clicks land on invented_policy.
  1. The generic widget throws the work away. Its four options were invented by whoever built the form. A click on “Not helpful” tells you a case is bad and nothing else, so every one of the 100 still has to be opened, read and classified by a person before it can become an eval case.
  2. The taxonomy widget reuses work you already paid for. The options are the six failure modes from the error analysis, rewritten in the user's language. The user picks the words that make sense to them and the code stores the name your suite already knows, so the click arrives with its mode attached.
  3. Triage still happens. The right-hand lane is not “no humans”; it is a human confirming a label instead of inventing one. That is the difference between a queue that drains and a queue that grows, and it is the difference between 0 new eval cases today and 100 candidates.

The left column produces a number. The right column produces a labeled eval case, submitted by the person best placed to know, at the moment they cared enough to click.

Two practical rules for writing those options. Phrase each one in the user's language rather than your taxonomy's internal name, and keep the list to four or five, because a long list gets a random click. Always keep the free-text escape hatch, since that is where next quarter's new failure mode will first appear.

1 2 3 4 thumbs + reason retry / rephrase escalation random sample join on trace id signal + full context triage queue human confirms labeled case joins the suite CI gate the fix ships, and generates the next lap's traces
Fig. 7.5 — The right-hand arc of the flywheel. Note the fourth input: a random sample of ordinary traffic joins the complaints, or the suite learns only what annoys people.
  1. Four inputs, three of them complaints. A thumbs-down with a reason, a retry, an escalation: all of them are users telling you something went wrong, on their own initiative. They are free, they are strong, and they arrive only from people who were annoyed enough to act.
  2. Everything joins on the trace id. A click on its own is a mood. Joined to the trace id it becomes the full record — what was asked, what was retrieved, what the model replied — which is the only form an eval case can take.
  3. The queue is where a click becomes a label. A human decides what the right answer was and which failure mode it belongs to. Users press thumbs-down on correct refusals too, so promoting raw clicks straight into the suite poisons it. The code enforces this step rather than a wiki page.
  4. The fourth input is the quiet one. A random sample of ordinary traffic, labeled blind. It never finds anything exciting, and it is the only stream that can tell you how often the assistant is wrong overall rather than how often it is annoying.

Sample the boring traffic too, or you will optimize for the angry

Viktor's next question is the one every executive asks: is it getting better overall? A suite built only from complaints cannot answer it, because the people who click thumbs-down are not a random sample of SaaSify's users. The fix is 25 ordinary traces a week, labeled blind.

The tempting design is to build the eval set entirely from thumbs-down cases. It is free, it is high signal, and it will quietly wreck your suite.

Complaints are not a random sample of your traffic. They over-represent the users who bother to click, the topics that make people cross, and the failures that are obvious to a non-expert. A suite built only from them tells you nothing about the base rate, so you cannot answer the one question leadership asks: is it getting better overall?

The fix is two streams. Take every negative signal, because those are precious, and add a small random sample of ordinary traffic each week, which a human labels blind. The complaints find new failure modes; the random sample measures how often anything fails at all.

1 STREAM 1 — EVERY NEGATIVE SIGNAL thumbs + reason · 1.0 escalation · 0.9 retry detected · 0.5 finds failure modes you never had 2 STREAM 2 — 25 RANDOM TRACES A WEEK random sample · 0.0 labeled blind, before anybody looks at who complained measures how often anything fails 3 report the two pass rates separately — a complaint is not a sample of your traffic
Fig. 7.5b — The two streams, with the weights feedback_loop.py actually assigns. Complaints carry weight and jump the queue; the weekly 25 carry weight 0.0 and never do.
  1. Stream 1 is precious and biased. A thumbs-down with a named reason is worth 1.0, an escalation 0.9, an automatically detected retry 0.5. These are the strongest evidence you will ever get for free, and they come only from users annoyed enough to act. Everything they teach you is real; nothing they teach you is representative.
  2. Stream 2 is dull and honest. Twenty-five ordinary traces a week, drawn at random, labeled by a human who does not know whether anybody complained about them. This is the only number that can answer “is it getting better overall?”, because it is the only one drawn from the whole traffic.
  3. Never average the two. A pass rate that mixes complaints with random traffic is a number whose meaning changes every time the mix changes. Report them as two lines: the complaint stream for new failure modes, the sample stream for the base rate.

There is a second bias worth naming. If you only ever promote cases where the user complained, your suite drifts toward hard, weird, unrepresentative inputs, and its pass rate stops tracking the experience of a typical user. Keep both streams and report them separately.

🧠 Brain power

Before reading on: a product manager proposes shipping the thumbs-down widget on Monday and using next week's clicks as the new eval set. Two things will go wrong with that plan. What are they?

Reveal the answer

First, the cases arrive unusable. A thumbs-down gives you a trace id and a bad feeling. Before it can sit in an eval suite, someone must decide what the correct answer was, which failure mode it belongs to, and whether the user was even right. Users click thumbs-down when the assistant refused something correctly, or when they misread it. Unreviewed feedback is not a label, and promoting it directly poisons the suite.

Second, the sample is skewed. One week of complaints tells you what upset people, not how often the assistant is wrong. Without a random sample alongside it, your pass rate measures your angriest users and nothing else.

The plan is nearly right, though. Ship the widget on Monday, put a human triage step between the click and the suite, and start the weekly random sample in the same sprint.

Step-by-step: what feedback_loop.py does, in plain English
  1. Open a SQLite database file. SQLite is a database that lives in one file with no server, which is the right size for this job until you are handling millions of sessions.
  2. Create a feedback table. Each row records a trace id, where the signal came from, the reason code the user picked, any free text, and whether a human has triaged it yet.
  3. The trace id is the only column that really matters. It is what lets you join a two-word complaint back to the full record of what the user asked, what was retrieved, and what the model replied.
  4. Define REASONS, mapping each option shown in the widget to the failure-mode name from your §03 taxonomy. The user picks words that make sense to them; the code stores the name your suite already uses.
  5. Write record, which inserts one signal. It takes a weight, so a thumbs-down and an automatically detected retry can live in the same table without pretending they are equally strong evidence.
  6. Write detect_retry, the implicit-signal catcher. It compares two consecutive user turns and records a retry signal when they are very similar, because asking the same thing twice means the first answer failed.
  7. It uses a plain word-overlap ratio so the file runs offline. In production you would swap in the embedding similarity from Module 08, which catches rephrasing that shares no words.
  8. Write triage_queue, which returns untriaged signals worst-first, so a human spends their attention where the evidence is strongest.
  9. Write promote, the step that turns a triaged signal into an eval case. It takes the human's verdict on what the answer should have been and appends a case to the dataset file in the same shape §04's harness already reads.
  10. Note the guard at the top of promote: a signal that has not been triaged raises an error rather than being promoted. This is the rule the Brain Power question is about, enforced in code so nobody can skip it under deadline pressure.
  11. Write weekly_sample, which picks a fixed number of random trace ids from ordinary traffic and files them for blind labeling. This is the second stream, and it is the one that keeps your pass rate honest.
  12. The __main__ block runs the whole path: two signals arrive, a retry is detected automatically, the queue is printed worst-first, one case is triaged and promoted, and a weekly sample is drawn.
feedback_loop.pyruns offline
# Standard library only. Swap sqlite3 for your warehouse and the word-overlap
# similarity for Module 08 embeddings when this outgrows one file.
import json
import random
import sqlite3

DB = sqlite3.connect(":memory:")   # use a real path in production
DB.execute("""
  CREATE TABLE feedback (
    id        INTEGER PRIMARY KEY,
    trace_id  TEXT NOT NULL,          -- the join key back to the full trace
    source    TEXT NOT NULL,          -- widget | retry | escalation | sample
    reason    TEXT,                   -- a failure-mode name, not free prose
    note      TEXT,
    weight    REAL NOT NULL,          -- how much this signal is worth
    triaged   INTEGER NOT NULL DEFAULT 0
  )""")

# The widget's options ARE the taxonomy from §03. Left: what the user reads.
# Right: the failure-mode name your eval suite already knows.
REASONS = {
    "It answered about the wrong plan tier":       "wrong_tier",
    "It stated a policy that isn't in our docs":   "unsupported_claim",
    "It gave no source I could check":             "missing_citation",
    "It refused something it should handle":       "over_refusal",
    "Something else":                              "unclassified",
}
WEIGHT = {"widget": 1.0, "escalation": 0.9, "retry": 0.5, "sample": 0.0}

def record(trace_id: str, source: str, reason: str | None = None, note: str = "") -> None:
    """One signal in. Weight travels with it so strong and weak evidence can coexist."""
    DB.execute(
        "INSERT INTO feedback (trace_id, source, reason, note, weight) VALUES (?,?,?,?,?)",
        (trace_id, source, REASONS.get(reason or "", reason), note, WEIGHT[source]),
    )
    DB.commit()

def detect_retry(trace_id: str, prev_turn: str, this_turn: str, threshold: float = 0.6) -> bool:
    """Nobody asks the same question twice after a good answer.
    Word overlap keeps this offline; embeddings catch rephrasing that shares no words."""
    a, b = set(prev_turn.lower().split()), set(this_turn.lower().split())
    similarity = len(a & b) / max(len(a | b), 1)      # Jaccard: shared words / all words
    if similarity >= threshold:
        record(trace_id, "retry", "unclassified", f"similarity={similarity:.2f}")
        return True
    return False

def triage_queue(limit: int = 20) -> list[tuple]:
    """Strongest evidence first — a human's attention is the scarce resource here."""
    return DB.execute(
        "SELECT id, trace_id, source, reason, note FROM feedback "
        "WHERE triaged = 0 AND weight > 0 ORDER BY weight DESC LIMIT ?", (limit,)
    ).fetchall()

def promote(feedback_id: int, expected: str, failure_mode: str, path: str = "eval_cases.jsonl") -> dict:
    """Triaged signal becomes a labeled eval case, in §04's dataset shape."""
    row = DB.execute(
        "SELECT trace_id, triaged FROM feedback WHERE id = ?", (feedback_id,)
    ).fetchone()
    if row is None or row[1] == 0:
        # The rule that keeps the suite clean: a user's click is evidence, not a label.
        raise ValueError(f"feedback {feedback_id} has not been triaged by a human")
    case = {"trace_id": row[0], "expected": expected,
            "failure_mode": failure_mode, "origin": "production_feedback"}
    with open(path, "a", encoding="utf-8") as fh:
        fh.write(json.dumps(case) + "\n")
    return case

def weekly_sample(all_trace_ids: list[str], n: int = 25) -> list[str]:
    """The second stream. Complaints find NEW failures; this measures the BASE RATE.
    Without it your pass rate describes your angriest users and nobody else."""
    picked = random.sample(all_trace_ids, min(n, len(all_trace_ids)))
    for tid in picked:
        record(tid, "sample")
    return picked

if __name__ == "__main__":
    record("tr-1041", "widget", "It gave no source I could check")
    record("tr-1077", "escalation", note="user asked for an agent")
    detect_retry("tr-1103", "how do I change my billing date",
                 "how do I change the billing date")            # → retry recorded

    for row in triage_queue():
        print(row)
    # (1, 'tr-1041', 'widget', 'missing_citation', '')      ← strongest, review first
    # (2, 'tr-1077', 'escalation', None, 'user asked ...')
    # (3, 'tr-1103', 'retry', 'unclassified', 'similarity=0.75')

    DB.execute("UPDATE feedback SET triaged = 1 WHERE id = 1")  # a human confirmed it
    print(promote(1, expected="Cite the billing policy section", failure_mode="missing_citation"))

    try:
        promote(2, expected="...", failure_mode="over_refusal")  # not triaged yet
    except ValueError as exc:
        print("refused:", exc)

    print("blind-label queue:", weekly_sample([f"tr-{i}" for i in range(1000, 1200)], n=5))

Read the output. The queue prints three rows, ordered by weight. The widget click with a named reason leads, the escalation follows, and the automatically detected retry sits last because a retry is suggestive rather than conclusive.

Then the important line. Promoting the triaged case writes a labeled entry to the dataset, while promoting the untriaged one raises an error instead. That refusal is the whole discipline of this section compressed into four lines of code.

The last call draws five random trace ids and files them with weight zero. They will never jump the triage queue, because they are not complaints, but they are what your weekly pass rate is honestly measured on.

Close the loop out loud

The machine is built and turning: gate in front, feedback behind. The part that decays quietly is the person who reported the bad answer, and at SaaSify the feedback widget belongs to nobody. This last habit costs nothing and is what keeps the volume coming.

One habit costs nothing and roughly doubles your feedback volume over a few months. When a report leads to a fix, tell the person who reported it.

A one-line note saying their report changed the assistant converts a user who clicked once into a user who keeps clicking. Support teams have known this for decades. AI features forget it because the feedback widget usually belongs to nobody.

Assign it an owner. A feedback loop with no human on the other end decays into a table nobody queries, and the flywheel stops turning at exactly the point it was supposed to become self-sustaining.

Quick reference — feedback loops

Explicit vs implicit
Explicit is the user telling you: thumbs, reason, free text, escalation. Implicit is behavior: retry, rephrase, copy, edit, abandon. Implicit is ten to fifty times more plentiful and almost nobody collects it.
The strongest cheap signal
The retry. Nobody asks the same question twice after a good answer, and it costs one event on a button you already have.
The one design move that matters
Make the widget's reason options your §03 failure-mode names, in the user's words. Feedback then arrives pre-classified instead of joining a queue.
The trace id is the product
A signal without a trace id is a mood. With one, a two-word complaint joins to the full question, retrieval, and answer.
Triage is mandatory
A user's click is evidence, not a label. Users thumbs-down correct refusals. Enforce the human step in code, not in a wiki page.
Two streams, always
Every negative signal, plus a weekly random sample labeled blind. Complaints find new failure modes; the random sample measures the base rate. Report them separately.
Close the loop
Tell reporters when their report caused a fix. It is the cheapest way to raise feedback volume, and it needs a named owner or it does not happen.

08 · Under the hoodThe Math, If You Want It

Everything Viktor needs is now built. The two numbers his team will be asked to defend are the ±19 points of uncertainty on a 20-case pass rate and the κ (kappa) of 0.5833 the judge scored on ten rows, and both came out of formulas you have so far taken on trust. This optional section derives them. Skip it and nothing later breaks.

The statistics behind eval sets and judge agreement — optional depth

Pass-rate uncertainty. A pass rate over n independent cases is a binomial proportion. Its standard error is SE = √(p(1−p)/n), where p is the measured rate. The 95% confidence interval is p ± 1.96·SE — 1.96 being the z-value that brackets 95% of a normal distribution.

Why this formula: each case is a coin flip with bias p; the variance of one flip is p(1−p); averaging n flips divides variance by n; square-root converts variance back to the scale of the rate itself.

At n=20, p=0.75: SE ≈ 0.097, so the interval spans ±19 points — which is why §05's "5-point win" was noise.

Sizing an eval set. To detect a true difference Δ between two variants with 5% false-positive rate and 80% power, you need roughly n ≈ (zα/2 + zβ)² · (p₁(1−p₁) + p₂(1−p₂)) / Δ² per variant, with zα/2 = 1.96 and zβ = 0.84. Near p ≈ 0.75 this gives ~325 cases for a 10-point gap and ~1,250 for 5 points. Paired designs (both variants on the same cases, analyzing per-case flips) cancel shared case difficulty and cut the requirement substantially — the statistical reason eval suites of 100–500 cases work in practice.

Cohen's kappa. κ = (po − pe) / (1 − pe), where po is observed agreement and pe is the agreement two raters would reach by chance given their marginal rates.

Why correct for chance: if 90% of cases pass, a judge that answers "pass" unconditionally reaches po = 0.90 while carrying zero information. In Fig. 7.3: po = 0.88; pe = 0.48·0.46 + 0.52·0.54 ≈ 0.50; κ = (0.88 − 0.50)/(1 − 0.50) ≈ 0.76.

chance, p-expected 0.50 observed 0.88 0.00 agreement 1.00 agreement the room above chance: 0.50 what the judge earned: 0.38 1 2 3 kappa = 0.38 / 0.50 = 0.76
Fig. 7.5c — Cohen's kappa drawn on the agreement scale, with Fig. 7.3's numbers. Kappa is not the agreement; it is the share of the distance between chance and perfect that the judge actually covered.
  1. Chance is not zero. Two graders who both say “fail” about half the time will agree about half the time while knowing nothing. That is the mark at 0.50, and every agreement number you ever read starts from there, not from 0.00.
  2. The room above chance is all you can win. From 0.50 to 1.00 there is 0.50 of scale left. This is the denominator of kappa, and it is why a judge on a heavily imbalanced dataset — where 90% of cases pass — has almost no room to prove anything and needs far more labeled failures.
  3. Kappa is the fraction of that room you covered. Observed agreement 0.88 is 0.38 above chance, out of the 0.50 available, so kappa is 0.76. Read it as “the judge closed three quarters of the gap between guessing and perfect”, and the rule of thumb below it will make sense.

Rule of thumb: κ ≥ 0.6 is acceptable for a production judge, ≥ 0.8 is strong; below 0.4 your rubric is ambiguous — fix the words, not the model.

There are no dumb questions

Isn't LLM-as-judge circular — grading an LLM with an LLM?
It would be, unvalidated. The escape from circularity is that the judge is anchored to human labels: you measure its agreement on a frozen labeled set before trusting it, and re-validate whenever the rubric or judge model changes. It also helps that judging is a narrower task than generating — "does this answer contradict this context?" is easier than writing the answer — the same asymmetry that makes code review easier than coding.
How many examples do I really need?
50–100 traces to start error analysis; ~100 labeled cases for a first useful suite; grow toward 300–500 as production surfaces new failures. The math in §05 is the reason 20 is worthless and the reason paired comparisons on shared cases are the standard design.
Why not just report benchmark scores like MMLU?
Benchmarks measure the model; you ship a system — model plus prompt plus retrieval plus tools. A model can score 90% on MMLU and still invent your discount policy, because no benchmark contains your billing FAQ. Public benchmarks are also contaminated (models train on them) and task-mismatched. Use them for model selection, never for system verification.
Do evals replace production monitoring?
No — they're two arcs of the same flywheel. Offline evals gate changes before merge; online monitoring (trace capture, sampled judge scoring, user feedback signals) discovers failure modes you didn't anticipate, which become new labeled cases. §07 builds the feedback half of that arc, and Module 12 wires up the monitoring and alerting half.
Aren't LLM outputs deterministic if I control sampling? Why all the statistics?
Current Anthropic models don't even accept a temperature parameter, and provider-side infrastructure introduces nondeterminism regardless. But the deeper point: the statistics in §05 are about sampling error across your case distribution — which 20 cases you happened to pick — not per-token randomness. That uncertainty exists even for a perfectly deterministic system.
Boardroom translation

Evals convert AI risk into a dashboard number — and dashboard numbers are what unblock launches. "The assistant is really good now" gets an AI feature parked in legal review indefinitely; "faithfulness ≥ 95% on 500 real customer cases, judge validated at 88% agreement with human review, every change gated in CI" is the sentence that gets it past legal, procurement, and the CFO. The ROI frame writes itself: SaaSify's one invented-policy incident cost $18,400 plus 240 engineer-hours of blind prompt roulette; the eval suite costs about $3 per nightly run in judge tokens and turns every future prompt change from a bet into a measurement. Elevator version: "We don't hope the AI behaves — we have a regression suite for its judgment."

09 · The labBuild the Real Thing

Viktor's story ends here and yours starts. The assistant you shipped in Module 06's lab has exactly SaaSify's problem: it works when you are watching. This lab puts the whole flywheel around it — 50 real interactions read by hand, a failure taxonomy with counts, a judge whose κ you report, a gate that blocks a merge, and a feedback loop. It is the portfolio piece of this course.

LAB 07 — Eval-gated CI for the Module 06 assistant (THE portfolio piece)

Mission: build the complete eval suite for the CLI support assistant you shipped in Module 06's lab, and wire it into GitHub Actions so a quality regression cannot merge. Of every artifact in this course, this is the one to lead with: per the market research, shipped eval harnesses are the single strongest 2026 differentiator, and resumes naming Ragas/LangSmith/DeepEval hit the top score quartile 2.6× more often. Three deep projects beat ten demos — make this one of the three.

  • Run the six-step method on ≥50 real interactions with your assistant: error-analysis notes → failure-mode taxonomy (≥5 modes with counts) → 50-case labeled dataset (pass/fail + failure_mode + reason per case, including deliberate negatives)
  • ≥5 code asserts in pytest covering your mechanical failure modes (JSON validity, citation presence, PII, length, one domain-specific regression pin)
  • A validated LLM-as-judge: rubric prompt + structured-output verdict, with judge–human agreement and Cohen's κ reported in the README (target: agreement ≥ 85%, κ ≥ 0.6 — iterate on the rubric until you hit it)
  • promptfoo or DeepEval running both tiers in a GitHub Actions workflow that blocks merges on regression (include a screenshot of a red check doing its job)
  • A feedback loop wired into the assistant: a reason list whose options are your own failure-mode names, a trace id on every signal, retry detection, a triage step that refuses to promote an unreviewed case, and a weekly random sample labeled blind — report complaint-driven and sample-driven pass rates separately
  • README documents: the failure-mode table, eval metrics before/after one real improvement, and a before/after story of a regression the gate actually caught

Stretch goal: add Langfuse tracing to the assistant, sample 20 production-style traces per day through your judge, and route both the judge's flags and your §07 feedback signals into one triage queue — a working miniature of the full flywheel, both arcs turning.

10 · Interview radarHow This Shows Up in Interviews

Interview radar

"How do you evaluate an LLM feature?"

The real test The #1 screen for GenAI roles — screeners explicitly probe for shipped evals with measurable outcomes, not familiarity with the vocabulary.

Strong answer Narrate the six-step loop as something you have actually run:

  • Read real traces — sit with 50–100 real interactions and note everything that looks wrong
  • Cluster the notes into a failure taxonomy — named failure modes with counts, so fixes can be prioritized
  • Build a labeled dataset — pass/fail cases that pin down each failure mode
  • Code asserts for mechanical failures — properties a plain test can check, like JSON validity or citation presence
  • A validated LLM judge for judgment failures — a rubric prompt whose verdicts you have measured against human labels
  • A CI gate — so a quality regression cannot merge

Land it Saying "validated against human labels" out loud is the senior signal.

"How do you know your judge is right?"

The real test The follow-up that separates candidates who've done it from candidates who've read about it.

Strong answer Validate the judge the way you would validate any classifier:

  • Agreement rate and Cohen's κ against human labels — kappa matters because raw agreement can be mostly chance
  • Per-cell confusion-matrix review — with special attention to the failures the judge missed, the expensive cell
  • Re-validation on every change — whenever the rubric or the judge model changes, the old agreement number is void
  • Awareness of judge biases — self-preference, position, and verbosity, which you design the rubric around

Land it When agreement is low, rubric fixes beat model swaps — the usual culprit is ambiguity in the words, not the model.

"F1 vs faithfulness — when would you use each?"

Strong answer Use F1 (Module 02) when the task reduces to closed-set prediction with ground-truth labels — classification, extraction, or routing a support ticket to the right team — because it's deterministic, free, and statistically well-understood. Use faithfulness when the output is open-ended generation grounded in retrieved context, where "correct" means "supported by the context," not "exact match against a reference."

Land it The bonus point: structure your pipeline so as much of it as possible reduces to classical metrics, and spend judge budget only on what's left.

"Walk me through debugging a quality regression."

The real test A GenAI system-design staple — the interviewer is grading for a repeatable method, not a lucky guess.

Strong answer First check whether the delta is even significant given the eval-set size (§05) — a five-point swing on twenty cases is within noise. If it's real, slice the eval report by failure mode to localize it, then diff the traces on the specific cases that flipped from pass to fail. From there, bisect the change surface — prompt vs retrieval vs model version vs tool schema — and reproduce the failure on pinned cases to confirm the culprit.

Land it Close the loop: add the offending cases to the dataset, so the regression is caught forever after.

"Where does your eval set come from after the first month?"

The real test Whether your suite is a one-off artifact or a system that keeps itself current — and whether you know the sampling trap.

Strong answer From production, through a loop I instrument on purpose. Two channels feed it:

  • Explicit signals — thumbs with a reason, escalations, free text. I make the reason options the names of my own failure modes, so feedback arrives already classified instead of joining a queue
  • Implicit signals — retries and rephrasings, which are ten to fifty times more plentiful and cost one event on a button I already have. Nobody asks the same question twice after a good answer

Everything joins the trace on a trace id, a human triages before anything becomes a labeled case, and a weekly random sample gets labeled blind alongside the complaints.

Land it The random sample is the part worth volunteering: a suite built only from complaints measures your angriest users, so it finds new failure modes but can never tell you the base rate.

"When would you NOT use LLM-as-judge?"

The real test The vendor-agnostic judgment check — the judge is a tool with costs, and the grader wants to see you reach for cheaper graders first.

Strong answer Whenever a cheaper grader suffices:

  • Mechanical properties — regex and schema checks grade format rules for free
  • Tasks with ground-truth labels — classical metrics score classification and extraction deterministically
  • Latency-critical inline guardrails — a small classifier answers in milliseconds where a judge cannot

And in high-stakes domains, a judge augments human review but never replaces it.

Land it The cost sanity check: a judge on every production request is a second LLM bill — sample instead.

Quick reference — Evals and error analysis

stack rule
Plain code checks first, then a judge you have measured against human labels, then one CI framework plus one trace platform. Swap a tool only for a named reason.
eval
A test suite for a system with no single right answer. The thing that turns “it seems better” into a number.
open coding
Read actual failures and write down what went wrong, in your own words, before inventing categories. Always do this first.
failure mode
A named, recurring way the system gets it wrong. Your eval set should be built from these, not from what is convenient to test.
The method
Error analysis → labelled examples → cheap code assertions → a validated LLM judge → a gate in CI. Each step only when the previous one is not enough.
LLM-as-judge
A model grading output. Only trustworthy once you have measured its agreement with your labels — an unvalidated judge is a random number generator with good manners.
The RAG four
Faithfulness (is it supported by the context) · answer relevancy · context precision · context recall.
Pass-rate uncertainty
A pass rate from 20 examples tells you almost nothing. Size the eval set to the difference you need to detect.
Standard error
The typical distance between a pass rate measured on n cases and the true rate p: √(p(1−p)/n). At 20 cases and 75% it is 9.7 points, so one score's 95% range is ±19 and a gap between two scores is ±26.8.
Paired comparison (McNemar)
Run both prompts on the same cases, ignore the ties and count the flips. If the prompts are equal each flip is a coin toss, so fewer than six flips can never convince.
Kappa on few rows
One flipped verdict moves kappa by about 0.20 on 10 labeled rows and about 0.02 on 100. Validate the real judge on about 100 cases.

11 · RecapWhat You Can Do Now

  • You can run the six-step eval loop on any LLM system: traces → notes → failure taxonomy → labeled dataset → graders → CI gate
  • You can decide which failure modes get code asserts and which need an LLM judge — and defend the split with the eval pyramid
  • You can implement an LLM-as-judge with a rubric and structured outputs, and validate it against human labels with agreement and Cohen's κ
  • You can explain why a 5-point win on 20 cases is noise, and size an eval set with standard-error math
  • You can trace one eval case through a harness station by station, and say which check actually caught it
  • You can tell by hand whether a pass-rate gap is real: a standard error for separate runs, a flip count for paired ones
  • You can define faithfulness, answer relevancy, context precision, and context recall precisely — and use them to localize RAG failures to generation vs retrieval
  • You can choose between Ragas, DeepEval, promptfoo, LangSmith, and Langfuse for a given team and justify the pick
  • You can gate merges on eval regressions with a working GitHub Actions pipeline
  • You can build the loop's other arc: explicit and implicit feedback joined on a trace id, a reason list that mirrors your failure taxonomy, mandatory human triage, and a random sample that keeps the pass rate honest
  • You can pitch evals to executives as converting AI risk into a dashboard number
🧠 Flex your memory

1 (this module): Close the page and sketch the eval flywheel from memory, then write the six method steps in order. Check yourself against Fig. 7.1 and §03.

2 (reach back to Module 02): Define precision and recall from memory. Now compute the judge's precision and recall on the fail class from Fig. 7.3's numbers (caught 41, missed 7, false alarms 5). Check: precision = 41/46 ≈ 0.89, recall = 41/48 ≈ 0.85 — the same machinery you used for churn models now audits your judge.