Evals & Error Analysis — The Skill That Gets You Hired
"You'd never merge code without tests. Teams merge prompt changes blind every single day."
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.
"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."
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.
- 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.
- 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.
- 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.
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:
| 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 QA | Human review — the ground truth that calibrates the judge |
| CI gate on red tests | CI gate on eval regression vs baseline |
| Reading bug reports | Error 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.
- 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.
- 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.
- 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.
- 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.
| Stage | In the hand-built version (sections 03–04) | In the production build (sections 06–07) | What flows out |
|---|---|---|---|
| Production traces | A traces.jsonl export, sampled by sample_traces.py | Langfuse or LangSmith capturing every request, plus the signals stored by feedback_loop.py | 100 real interactions in error_analysis.csv, one row each |
| Error analysis | You, reading every row and typing a one-sentence note in the note column | The same reading, weekly, over the triage queue and a random sample | A failure-mode table with counts |
| Labeled dataset | eval_cases.jsonl: a pass/fail label, a failure mode and a reason per case | The same file, grown by promote() from triaged user feedback | 100 to 500 cases every grader is scored against |
| Code asserts | test_asserts.py: citation, discount, PII and length checks under pytest | The same tests, run as the code-asserts job in evals.yml | Red or green in seconds, for free |
| LLM-as-judge | judge.py: a rubric, a structured verdict and validate_judge() | The llm-rubric assert in promptfooconfig.yaml, or a DeepEval GEval metric | A pass/fail verdict per case, trusted only after validation |
| Eval report | The pass rate and per-mode counts printed by mini_evals.py | results.json from promptfoo, with prompt v1 and v2 side by side | A number you can compare with last week's |
| CI gate | sys.exit(1) at the end of mini_evals.py | The llm-judge job in evals.yml, red on any failed assert | A merge that is blocked or allowed |
| Ship the change | By hand: you merge and watch | Deploy, then the dashed arrow in Fig. 7.4 carries new traces and new feedback back to the top | The 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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
- Bring in
jsonto read one JSON object per line,osto check whether a file exists,randomto draw the sample, andpandasto write a spreadsheet. - 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.
- If there is no
traces.jsonlyet, 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. - Read the file back: one trace per line, each parsed from JSON into a dictionary.
- 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.
- Turn each sampled trace into a row holding an id, the user's input, the output, and an empty
notecolumn. The note column is the point of the file: you fill it in by hand, one sentence per bad trace. - Write the rows to
error_analysis.csvwith pandas, without the numeric index column, and print how many rows there are to read.
# 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):
| Failure mode | Count | Share of failures | Example note |
|---|---|---|---|
invented_policy | 14 | 37% | "Promised a 25% loyalty discount — no such policy exists" |
missing_citation | 9 | 24% | "Correct answer but no source, agent can't verify it" |
stale_data | 6 | 16% | "Quoted the 2024 rate limits" |
wrong_tone | 4 | 10% | "Sarcastic reply to an angry enterprise customer" |
format_broken | 3 | 8% | "Markdown table leaked into a plain-text channel" |
overrefusal | 2 | 5% | "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.
- 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.
- 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.
- 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:
- A human pass/fail label.
- A
failure_modetag. - A one-sentence reason.
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.
- 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.
- 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.
- 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:
{"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:
- 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. - 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.
- 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
- Bring in
json,os,re(the regular-expression library) andpytest, the test runner. - 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. Casea-03invents a 30% discount on purpose. load_cases()prefers a realoutputs.jsonlif one exists and falls back to the samples otherwise.CASESandCASE_IDSare computed once when the file is imported, so every test sees the same list.- 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. APPROVED_DISCOUNTSis the set of percentages that really exist. Only "10" is in it. Anything else is invented.@pytest.mark.parametrizeruns the test that follows once per case and names each run by its id, so a failure readstest_no_invented_discounts[a-03].test_citation_presentskips cases that do not need a citation and fails any case that needs one and lacks it.test_no_invented_discountscollects every percentage the output mentions, removes the approved ones, and fails if anything is left. This is the test that goes red ona-03.test_no_pii_leakfails if the output contains anything shaped like an email address or a phone number.test_length_boundsfails outputs shorter than 20 or longer than 1200 characters, which catches empty replies and runaway essays.test_valid_json_payloadruns only on cases whose format isjson.json.loadsraises on broken JSON, which pytest reports as a failure, and the test then checks for the requiredactionkey.
# 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.
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.
- 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.
- 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.
- 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
- Bring in
json, two typing helpers (Literalrestricts a field to the listed values;Optionallets it be empty), theanthropicclient, andBaseModelfrom pydantic, which turns a class into a validated data shape. - Define
Verdict: the judge must answer with exactlypassorfail, one failure-mode name from the taxonomy or nothing, and a one-sentence reason. The model cannot return anything outside this shape. RUBRICis 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.- 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.
- Create the client. It reads
ANTHROPIC_API_KEYfrom the environment itself. judge()sends the context, question and answer inside labelled tags and asks for aVerdictback throughoutput_format.parsed_outputis already aVerdictobject, not text you have to parse.validate_judge()opens the human-labeled dataset and runs the judge over every case.- It sorts each case into one of four cells, treating
failas the positive class: caught (both say fail), missed (human fail, judge pass), false alarm (human pass, judge fail), and agree on pass. - Raw agreement
pois the share of cases where both graders say the same thing. - Chance agreement
peis what two graders with these habits would agree on by luck: the product of their fail rates plus the product of their pass rates. - 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.
# 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:
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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.
Step-by-step: what mini_evals.py does, in plain English
- Bring in the standard library only:
json,os,re,sys, andCounter, a dictionary that counts things. The anthropic and pydantic imports happen later, insidereal_judge, so the file runs without them installed. FALLBACKis a four-case dataset typed in by hand: two passes and two labeled failures, both of theinvented_policykind.load_cases()uses a realeval_cases.jsonlwhen one exists.- Define three checks. Each returns
Truewhen the case is fine and a short message when it is not, so the message doubles as the reason in the report. CHECKSis the list the runner loops over. Adding a fourth check is one function and one list entry.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.real_judge()callsclaude-sonnet-5with a three-line rubric and asks for a structured verdict. It is chosen only whenJUDGE=realis set in the environment.run()loads the cases and picks the judge function once.- 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.
- 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.
- Print one row per case, the overall pass rate, the judge agreement if any cases were labeled, and the failure counts by mode.
- 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.
-
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
- Import
jsonandosfrom the standard library. FALLBACKis four cases typed in by hand: two good answers and two answers that invent a policy.load_cases()reads a realeval_cases.jsonlfile when one exists and falls back to the typed cases when it does not.- Print each case's id, label and the start of its answer.
mini_evals.py — chunk 1runs offlineimport 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.pyin a folder with noeval_cases.jsonl. You should see four rows: two labelled pass, two labelled fail.terminalactual outputc-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. - Import
-
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
Truewhen 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
CITATIONis a pattern for a tag like[doc:billing-faq-04];DISCOUNTfinds numbers followed by "% discount" or "% off".check_citationpasses when the pattern is found.check_no_invented_discountfails on any discount other than the approved 10%.check_lengthfails if the answer is under 20 or over 1,200 characters.CHECKSis a plain list of the three functions, so adding a fourth check is one function and one list entry.- Run every check on every case and print the messages. The chunk 1 print loop is replaced.
mini_evals.py — chunk 2runs offlineimport 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 inCHECKSand 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 reportno [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 outputc-01 all checks ok c-02 ['no [doc:...] citation'] c-03 all checks ok c-04 ['no [doc:...] citation'] -
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
mock_judge(c)returns"fail"if any check fails, otherwise"pass".- 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 outputc-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 -
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
real_judge(c)importsanthropicandpydanticonly when called, so the file still loads without them.- A small
Vclass says the answer must be a verdict of"pass"or"fail"plus a reason. client.messages.parsesends a three-line rubric and the case, and returns an already-validated object.judge_fnis the real judge only whenJUDGE=realis set; otherwise it is the mock.
mini_evals.py — chunk 4runs offlinedef 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 printsjudge in use: mock_judgeand the same four verdicts. The real path (JUDGE=real python3 chunk4_real_judge.py) needs an API key and was not run here.terminalactual outputjudge in use: mock_judge c-01 pass c-02 fail c-03 pass c-04 fail -
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
- Load the cases and pick the judge once.
- For each case, gather the failed-check messages and ask the judge.
- 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.
- Labelled cases also feed an agreement tally, so the same harness validates the judge.
- Print one row per case, the pass rate, the agreement, and the failure counts.
- Exit with status 1 if anything failed. Chunk 4's test print lines are replaced.
mini_evals.py — chunk 5runs offlineimport 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, thenecho $?. 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 outputcase 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.
# 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.
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.- 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.
- 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.
- 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.
| Case | Question | Assistant's output | Human label | Failure mode |
|---|---|---|---|---|
| c-01 | Do you offer discounts for annual billing? | "Annual plans are 12x the monthly rate — no discount program exists. [doc:billing-faq-04]" | pass | none |
| c-02 | Do you offer discounts for annual billing? | "Yes — annual prepay comes with a 25% loyalty discount." | fail | invented_policy |
| c-03 | How do I rotate my API key? | "Settings, then API, then Rotate key. The old key stays valid for 24 hours. [doc:api-keys-02]" | pass | none |
| c-04 | What is your uptime SLA? | "We guarantee 99.99% uptime for every plan." | fail | invented_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.
| Station | Code in mini_evals.py | Value for c-02 |
|---|---|---|
| A · load | load_cases() | A dictionary: the output "Yes — annual prepay comes with a 25% loyalty discount.", label fail, failure mode invented_policy |
| B · citation check | check_citation(c) | The pattern finds nothing, so the check returns the message "no [doc:...] citation" |
| C · discount check | check_no_invented_discount(c) | True: the pattern found no percentage to object to |
| D · length check | check_length(c) | True: 54 characters, inside the 20 to 1,200 allowed |
| E · collect problems | problems = [...] | One message: ["no [doc:...] citation"] |
| F · judge | mock_judge(c) | "fail", because one check returned something other than True |
| G · decide | ok = not problems and verdict == "pass" | False |
| H · count the mode | fail_modes[...] += 1 | invented_policy goes to 1, and to 2 once c-04 is done |
| I · agreement | agree += (verdict == c["label"]) | "fail" matches "fail", so agree goes up by 1 |
| J · report row | rows.append(...) | c-02 · FAIL · no [doc:...] citation |
| K · pass rate | passed = sum(...) | 2 of the 4 rows, printed as "pass rate: 2/4 = 50%" |
| L · exit | sys.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:
| Run | c-02 | Pass rate | Agreement with the labels | Exit status |
|---|---|---|---|---|
| As written | FAIL | 2/4 = 50% | 4/4 = 100% | 1, red |
| c-02 cited | PASS | 3/4 = 75% | 3/4 = 75% | 1, red (c-04 still fails) |
| c-02 and c-04 cited | PASS | 4/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.
- 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.
- 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.
- 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.
| Question | Unit test: test_asserts.py under pytest | Eval: mini_evals.py, judge.py, promptfoo |
|---|---|---|
| What one case checks | A fixed property of the output: a citation is present, the JSON parses | Whether an answer is acceptable. For 26 of SaaSify's 38 failures that needs a reader |
| Who writes the expected result | The developer, from the spec | A human labeller, after reading real traces in step 1 |
| What a run prints | 1 failed, 11 passed, 1 skipped | A 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 merging | Not always. c-02 and c-04 were labeled fail; the harness is working when it fails them |
| The same input, run twice | The same verdict every time: recorded output, fixed pattern | A 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 says | The judge is itself tested against human labels, with agreement and kappa |
| What blocks a merge | Any red test | A drop below the baseline, such as groundedness 0.94 to 0.87 in Fig. 7.4b |
| Cost of one run | $0.00, 0.03 seconds | About $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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Observed agreement. po (read "p-observed") = (2 + 2) ÷ 4 = 1.00.
- 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.
- Kappa. κ = (1.00 − 0.50) ÷ (1 − 0.50) = 0.50 ÷ 0.50 = 1.00.
- 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:
| Label set | Kappa as measured | After one verdict flips | Move per flipped row |
|---|---|---|---|
| 4 rows: mini_evals.py fallback, mock judge | 1.0000 | 0.5000 | −0.50 |
| 10 rows: the step-5 pencil exercise | 0.5833 | 0.3478 to 0.8000 | about ±0.20 |
| 100 rows: Fig. 7.3 | 0.7592 | 0.7390 to 0.7795 | about ±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.
- 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.
- 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.
- 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.
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.
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
- Bring in numpy and create a random generator with a fixed seed, so the numbers are the same every run.
- Set the scene: 20 cases per prompt, a true pass rate of 75% for both prompts, and 10,000 repeated experiments.
rng.binomial(n, true_rate, size=trials)simulates scoring 20 cases 10,000 times and returns the number of passes each time. Dividing bynturns each count into a measured pass rate. Do it twice, once per prompt.gap_casesis 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.- 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.
- 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.
# 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)")
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.- 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%.
- 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.
- 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:
| True difference you want to detect | Cases needed (per variant, independent samples) |
|---|---|
| 20 points (55% vs 75%) | ~85 |
| 10 points (65% vs 75%) | ~325 |
| 5 points (70% vs 75%) | ~1,250 |
- 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.
- 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.
- 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.
| Pile | Prompt A's verdict | Prompt B's verdict | Cases |
|---|---|---|---|
| Both pass | pass | pass | 13 |
| Both fail | fail | fail | 2 |
| Only A passes | pass | fail | 2 |
| Only B passes | fail | pass | 3 |
| Totals | 13 + 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.
- 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.
- Average over 20 cases. Averaging n independent cases divides the variance by n: 0.1875 ÷ 20 = 0.009375. More cases, less wobble.
- 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.
- 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.
- 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.
- 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.
| Gap between the two scores | Chance of exactly this gap | Chance of this gap or bigger |
|---|---|---|
| 0 cases (0 points) | 0.1454 | 1.0000 |
| 1 case (5 points) | 0.2722 | 0.8546 |
| 2 cases (10 points) | 0.2231 | 0.5824 |
| 3 cases (15 points) | 0.1602 | 0.3593 |
| 4 cases (20 points) | 0.1006 | 0.1992 |
| 5 cases (25 points) | 0.0553 | 0.0985 |
| 6 cases (30 points) | 0.0265 | 0.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.
- 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.
- 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.
- 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.
| Scores compared | Stored difference | Counted by gap >= 0.10? | Runs |
|---|---|---|---|
| 11/20 and 9/20 | 0.10000000000000003 | yes | 2 |
| 12/20 and 10/20 | 0.09999999999999998 | no | 13 |
| 13/20 and 11/20 | 0.09999999999999998 | no | 55 |
| 14/20 and 12/20 | 0.09999999999999998 | no | 193 |
| 15/20 and 13/20 | 0.09999999999999998 | no | 433 |
| 16/20 and 14/20 | 0.10000000000000009 | yes | 665 |
| 17/20 and 15/20 | 0.09999999999999998 | no | 546 |
| 18/20 and 16/20 | 0.09999999999999998 | no | 251 |
| 19/20 and 17/20 | 0.09999999999999998 | no | 42 |
| 20/20 and 18/20 | 0.09999999999999998 | no | 1 |
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:
- Runs two cases apart. 2,201 of the 10,000. Every one of them is a 10-point gap.
- Kept by the comparison. 665 + 2 = 667, the 16-and-14 and 11-and-9 pairs.
- Dropped. 2,201 − 667 = 1,534 runs that really were 10 points apart.
- What the old version counted. The 667 kept, plus the 3,584 runs three or more cases apart: 4,251. Printed as 43%.
- 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.
- 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.
- 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. - 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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".
- 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.
- 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.
| Paired: both prompts on one 100-case suite | Unpaired: two separate 100-case runs | |
|---|---|---|
| Scores | A 70%, B 78% | A 70%, B 78% |
| What is compared | 12 flips: 10 toward B, 2 toward A | Two rates, each with its own wobble |
| Test | Sign test on the 10–2 split | Two-proportion z-test, the bell-curve version of steps A to F: z = 1.29 |
| Wobble on the gap | Not needed: the 88 ties are gone | ±12.0 points at a pass rate near 75% |
| p-value | 0.0386 | 0.1972 |
| Verdict | B beats A on these cases | Cannot 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.
- 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.
- 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.
- 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.
Tonight's talk: The LLM Judge and The Human Labeller argue over the question, "Who's more important?"
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:
| Metric | Question it answers | How it's computed (intuition) | Needs a reference answer? |
|---|---|---|---|
| Faithfulness | Did the generator make things up? | Decompose the answer into claims; fraction of claims supported by the retrieved context | No |
| Answer relevancy | Did 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 precision | Is retrieval bringing signal to the top? | Fraction of retrieved chunks that are relevant, weighted by rank position | Yes (or the without-reference variant) |
| Context recall | Did retrieval find everything needed? | Fraction of the reference answer's claims attributable to the retrieved context | Yes |
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.
- 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.
- 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.
- 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
- 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.
- Bring in
evaluate, the two dataset classes, the wrapper classes that adapt LangChain models to Ragas, and the four metric classes. - Wrap
claude-sonnet-5as the judge and OpenAI'stext-embedding-3-largeas the embedder. Ragas calls the judge several times per sample, so cost scales with the number of metrics you turn on. - 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. - Put the samples in an
EvaluationDatasetand callevaluate()with the four metrics, each handed the judge, and the embedder where needed. - 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.
# 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
- 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. - Build the
groundednessmetric.criteriais your rubric in plain English.evaluation_paramstells the judge which fields to read: the input, the actual output, and the retrieval context. threshold=0.8is 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.CASESholds oneLLMTestCasewith the billing question, a grounded and cited answer, and the context it was answered from.test_groundednessis an ordinary parametrized pytest.assert_testruns every metric in the list against the case and raises if any falls below its threshold.- Run it with
deepeval test run, which wraps pytest and adds the judge calls and the report. SetOPENAI_API_KEY, or configure another judge model, first.
# 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.
- 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.
- 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.
- 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
- The header comments say how to run it:
npx promptfoo@latest evalscores every prompt against every test, andviewopens the side-by-side results in a browser. promptslists two prompt files. Each contains{{question}}and{{context}}placeholders that promptfoo fills from each test'svars. v1 is production; v2 is the change you want to prove is better.providersnames the model under test. Every prompt is run through every provider, so adding a second provider turns the run into a matrix.defaultTest.assertlists checks applied to every test. The first is aregexassert, a free code check that the output contains a[doc:...]citation.- The second is an
llm-rubricassert: 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. testslists the cases. Each hasvarsfor the placeholders and may add its own asserts. The first case pins the $18,400 incident withnot-contains: "25%", so that exact regression can never merge again.- A case passes only if every assert passes. The count of failed asserts is what the CI workflow reads out of
results.json.
# 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."
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
- defaultTest. Everything under it applies to every case in the
testslist, so the two checks below run on every question against every prompt. A per-caseassertadds to these; it does not replace them. The mistake: writing the citation check under one test and assuming the other cases got it. - 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. - 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. - 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 fromtest_asserts.py:[doc:, then lowercase letters, digits or hyphens, then]. - 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.providerto the judge you validated in Step 5. - 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. - 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."
- 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.
- 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.
- 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
- Name the workflow
evalsand run it on every pull request that targetsmain. A merge cannot happen until every required job here is green. - Job
code-asserts: check out the code, install Python 3.12 and pytest, and runtest_asserts.py. No secrets and no model calls, so it finishes in seconds. - Job
llm-judgedeclaresneeds: code-asserts. It only starts once the free tier is green, so a broken citation regex never spends judge tokens. - Install Node, then run promptfoo with the config file, writing
results.jsonand disabling the cache so the judge really runs on this pull request's prompt rather than replaying an old answer. - The API key comes from a repository secret through
env. It is never written into the file. - The final step uses
jqto read the failure count out ofresults.json.test "$fails" -eq 0exits nonzero if any assert failed, a nonzero exit makes the check red, and a red required check disables the merge button.
# 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.
- 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.
- Blocked is a number, not an opinion.
jqpulls the failure count out ofresults.json, andtest "$fails" -eq 0exits 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. - 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:
| Tool | Choose when | Avoid when | Typical cost |
|---|---|---|---|
| Ragas | Evaluating a RAG pipeline and you want reference metrics (faithfulness, context precision/recall) without writing judges | Non-RAG features; you need CI orchestration (pair it with pytest) | OSS + judge tokens |
| DeepEval | Your team lives in pytest; you want custom G-Eval rubrics with unit-test ergonomics | You mainly need config-driven prompt/provider A/B matrices | OSS (optional cloud) + judge tokens |
| promptfoo | Prompt/provider A/B comparisons, red-team suites, YAML-config CI gates with no Python required | You need deep per-trace production observability | OSS + judge tokens |
| LangSmith | LangChain/LangGraph stack; you want a managed platform with datasets, annotation queues, and hosted judges | Strict self-host / data-residency requirements; vendor-neutral stacks | SaaS, per-trace pricing |
| Langfuse | Open-source (MIT), self-hostable tracing + evals; compliance-sensitive orgs; provider-agnostic SDKs | You want zero-ops managed service with the deepest LangChain-native integration | Free 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.
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Code checks | pytest plus plain Python and regular expressions | unittest, Hypothesis, JSON Schema validators | Free, 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 model | claude-sonnet-5 with a Pydantic verdict through messages.parse | An OpenAI model, an open-weights judge on your own server, human review only | A 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 metrics | Ragas (pinned >=0.2) | DeepEval RAG metrics, TruLens, your own judge prompts | Ready-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 tests | DeepEval (GEval rubrics) | Plain pytest with your own judge function, Inspect AI | A 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 gate | promptfoo (YAML config) run from GitHub Actions | DeepEval in CI, Braintrust, a 40-line script of your own | Comparing 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 runner | GitHub Actions | GitLab CI, Jenkins, CircleCI | Runs 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 traces | Langfuse or LangSmith (shown, not coded here) | Arize Phoenix, Braintrust, OpenTelemetry plus your own warehouse | Langfuse 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
- Thumbs up and down. The default widget. Typical response rates run somewhere between 1% and 5% of sessions, so treat every one as precious and none of them as representative.
- A reason, chosen from a list. The single highest-value thing on this page. More on why in a moment — this is where most teams leave the value on the floor.
- Free-text "what went wrong". Low volume, very high quality. These are the sentences you will quote in the postmortem, so route them to a human, not a dashboard.
- An explicit report or escalation. The user asks for a person. The strongest negative signal a support product can collect, and it costs you nothing to log.
Implicit feedback — the user's behavior tells you anyway
- Regenerate or retry. The user asked again without changing much. The best cheap negative signal in the business: nobody retries an answer that worked.
- Rephrasing the same question. A retry wearing a disguise. Detect it by embedding consecutive turns and flagging high similarity — Module 08's tooling, reused.
- Copying the answer. A positive signal, and a rare one. If the product's whole point is producing text the user takes elsewhere, the copy button is your conversion event.
- Editing before sending, in any draft-and-send feature. The edit distance is a graded quality score you did not have to ask anyone for.
- Abandoning the session. The user leaves mid-conversation. Noisy on its own — people also leave because they got what they needed — so only trust it alongside another signal.
| Signal | What it suggests | Strength | Cost to instrument |
|---|---|---|---|
| Thumbs down + reason | A named failure, pre-classified by the person who hit it | Very strong | One form, one table |
| Escalation to a human | The assistant did not close the job | Very strong | Already in your ticket system |
| Retry or regenerate | The answer did not land | Strong | One event on an existing button |
| Rephrase within a session | Same as a retry, harder to detect | Strong | An embedding call per turn pair |
| Bare thumbs down | Something was wrong. Nothing about what | Weak | Trivial, and it shows |
| Session abandonment | Anything at all, including success | Weak alone | Free, 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.
| Generic options most teams ship | Options drawn from the §03 taxonomy |
|---|---|
| Not helpful | It answered about the wrong plan tier |
| Incorrect | It stated a policy that isn't in our docs |
| Offensive | It gave no source I could check |
| Other | It refused something it should handle |
| Something else — tell us |
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
feedback_loop.py actually assigns. Complaints carry weight and jump the queue; the weekly 25 carry weight 0.0 and never do.- 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.
- 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.
- 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.
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
- 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.
- Create a
feedbacktable. 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. - 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.
- 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. - 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. - 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. - 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.
- Write
triage_queue, which returns untriaged signals worst-first, so a human spends their attention where the evidence is strongest. - 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. - 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. - 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. - 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.
# 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 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.
- 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.
- 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.
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.
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
"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
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.