10A.1 Why Evals Matter: The Evaluation Mindset
Every module so far has handed you a working system: a prompt that triages tickets, a retriever that finds chunks, an agent that calls tools, a voice pipeline that transcribes speech. Every one of those systems can also fail — silently, fluently, and only sometimes. This lesson is where the path stops assuming things work and starts measuring them. You will learn what an evaluation actually is, how to turn a product goal into a measurable criterion, why error analysis comes before metrics, how the eval lifecycle grows from "a human reads twenty outputs" to "a gate in CI and a monitor in production", and you will build the smallest honest eval harness — evalkit — that every later lesson in this module extends.
What you'll learn
- Why LLM systems fail silently and fluently, and why "vibe checks" ("it looks fine on my test prompts") do not scale — including non-determinism, prompt/model/data drift, long-tail inputs and regressions after model upgrades
- What an eval actually is: a dataset + a task + scorer(s) + aggregation + a report, and the vocabulary around it (benchmark vs product eval, metric vs grader, offline vs online, golden set, rubric, judge, pass rate, regression, flake)
- How to define success: turning product goals into measurable criteria, the quality dimensions that matter, hard requirements vs soft scores, thresholds and acceptable error, the cost of false positives vs false negatives, user-facing vs system-level metrics, and the metric hierarchy (north-star, guardrail, diagnostic)
- Error analysis first: reading traces, open coding failures into a taxonomy, knowing how many traces to read and when to stop, and turning categories into targeted evals — why generic metrics like "helpfulness" mislead
- The evaluation lifecycle: manual review → first dataset → code graders → judges → CI gate → online monitoring → the flywheel, and how much eval is enough at each stage of a product — plus capability versus regression evals, saturation, and why no single quality layer catches everything
- The anatomy of a minimal eval harness, built and run in this lesson:
Example,Dataset, aScorerprotocol,run_eval(), JSONL results, a summary table and per-slice breakdowns — with determinism controls and caching hooks - A map from task types (classification, extraction, generation, RAG, agents, code, multimodal) to the evaluation methods that apply, pointing to the lessons that own each one
- How to read provider claims, vendor benchmarks and leaderboards critically
What you don't need
- API keys. Everything in this lesson runs on pure Python with a fake model; real output is shown. Where a provider feature appears, it is named and dated, not called.
- Statistics background. Confidence intervals, significance and sample sizes are taught properly in 10A.2 and 10A.5; here you need only the intuition that a number without an interval is a rumour.
- Any prior eval tooling.
promptfoo, DeepEval, Ragas, Inspect AI and friends are surveyed in 10A.10, and DeepEval (mandatory) and Inspect AI (optional) are taught in depth in the framework track (10B.1 onwards); this lesson builds the concepts from zero so those tools make sense when you meet them.
Setup
The harness in Part 6 is pure Python 3.11+ standard library — no packages, no keys, no network. If you want a project folder (freshers: uv needs one):
uv init evalkit --bare --python 3.13 && cd evalkit && mkdir evalkit
# or: python3 -m venv .venv && source .venv/bin/activateThe code builds one package, evalkit/, that grows across the module: this lesson adds core.py; 10A.2 adds dataset.py, 10A.3 adds scorers.py, 10A.4 adds judges.py, and 10A.8 adds runner.py, compare.py and cli.py; 10A.5–10A.7, 10A.9 and 10A.10 add the rest, and 10A.10's appendix lists all sixteen files. Each lesson shows the files it adds.
What you must be able to do after this lesson#
- Explain why LLM systems fail silently and why vibe checks do not scale
- Name the five parts of an eval: dataset, task, scorers, aggregation and report
- Turn a product goal into measurable success criteria with thresholds
- Run error analysis on traces and group failures into a taxonomy
- Build and run a minimal eval harness with per-slice results
- Choose an eval method for a given task type
Why this matters for an AI engineer#
You will hear these phrases in every AI team — and each one is a decision this lesson teaches you to make deliberately:
| You'll hear... | You'll understand it after... |
|---|---|
| "The demo worked, so it's basically done." | 1.2 Capability is not reliability |
| "I tested it on a few prompts and it looked good." | 1.3 Why vibe checks don't scale |
| "We need evals before we ship." | Part 2: What an eval actually is |
| "What does 'good' even mean for this feature?" | Part 3: Defining success |
| "Is 92% good enough to launch?" | 3.3 Hard requirements vs soft scores |
| "The summary sounds great but it's wrong." | 4.4 Why generic metrics mislead |
| "The model upgrade broke things and nobody noticed." | 5.1 The lifecycle, Part 8 Reading claims critically |
| "How do we know the eval itself is any good?" | 4.2 Open coding, 10A.5 |
| "An eval is just a test suite, right?" | 2.3 Evals vs tests vs benchmarks |
| "Which metric should we put on the dashboard?" | 3.5 The metric hierarchy |
Part 1: Why LLM systems need evals#
1.1 Failing silently, fluently#
Lesson 02.10 catalogued how models fail: hallucinated citations, stale facts, arithmetic slips, ignored constraints, sycophantic agreement, refusals that never trigger. Two properties of those failures matter more than any individual one:
- They are silent and fluent. A fabricated citation is formatted perfectly; a wrong total is stated with the same confidence as a right one; invalid JSON arrives with HTTP 200 (02.10, 1.3). Nothing in the API response says "this answer is wrong." Your monitoring sees latency and tokens, not correctness.
- They are probabilistic. The same input can produce a right answer at 9am and a wrong one at 9:05 (02.10, Part 11; the mechanics are 02.5, Part 7). A feature that is right "almost always" fails sometimes, and sometimes is a lot of failures at production volume: 2% wrong at 100,000 requests a day is 2,000 bad answers a day.
1.2 Capability is not reliability#
A model that solves a problem once in a demo has shown it can do the task, not that it does it reliably. Two ideas from 02.10, Part 1 do the heavy lifting here:
- Ability is jagged. Researchers describe LLM capability as a jagged frontier: a model can draft a legal argument and fail at counting the words in it. Human intuition about what is "hard" does not transfer, so you cannot assume that because the model handles X it handles a simpler-looking Y.
- The system is what you ship, not the model. Reliability is a property of the whole pipeline — model + prompt + retrieved context + parsing + validation + human fallback (02.10, 1.2). A weak model behind excellent validation can out-perform a strong model with none.
The engineering consequence: "does it work?" is the wrong question. The right questions are how often does it fail, how badly, on which inputs, and what happens when it does? Answering them requires measurement — an eval.
1.3 Why vibe checks don't scale#
The default evaluation method — a developer types a few prompts into a playground, reads the answers, and says "looks good" — fails for structural reasons, not carelessness:
| Why it fails | What actually happens |
|---|---|
| Non-determinism | The same prompt gives different answers run to run. "It worked when I tried it" is a sample of size one from a distribution (02.5, Part 7). |
| Prompt and context changes | Every prompt edit, every new few-shot example, every reordered context block is a change to a probabilistic system — and nobody can predict its effect by reading it (04.9). |
| Model and provider changes | Providers ship new snapshots, deprecate old ones, and change serving stacks; behaviour shifts without any change on your side (02.9, Part 8, 02.10, Part 19). |
| Data drift | Real traffic contains typos, non-English text, edge cases and adversarial inputs your test prompts never had (10A.2, 9.3). |
| Long tails | The rare input that breaks the system appears once in ten thousand requests — invisible to spot checks, inevitable at scale. |
| Silent regressions | A prompt tweak that helps the common case can quietly break a rare one. Without a fixed test set, the breakage surfaces as a user complaint weeks later. |
OpenAI's evaluation guide names the same anti-patterns from the vendor side: "overly generic metrics", "biased design" (eval data that doesn't reproduce production traffic), "vibe-based evals" ("it seems like it's working"), and "ignoring human feedback" (source, verified November 2026). Anthropic's prompt-engineering documentation makes the ordering a precondition: before prompt engineering you need "a clear definition of the success criteria", "some ways to empirically test against those criteria", and only then "a first draft prompt you want to improve" (source, verified November 2026). Both vendors are saying what this lesson formalises: the eval comes first.
1.4 Evaluation-driven development#
Evaluation-driven development is the discipline of writing the eval before (or alongside) the system, and letting the eval — not intuition — adjudicate every change. The loop:
flowchart LR
G["Product goal<br/>(what should this do?)"] --> C["Success criteria<br/>(how will we know?)"]
C --> D["Eval dataset<br/>(examples + labels)"]
D --> S["Scorers<br/>(code first, judges later)"]
S --> R["Run + report<br/>(numbers, slices, failures)"]
R --> F["Error analysis<br/>(read the failures)"]
F --> P["Change ONE thing<br/>(prompt, model, data, code)"]
P --> R
R -->|"gate passes"| SHIP["Ship / keep"]Three consequences fall out of taking it seriously:
- The eval is a specification. Writing down what "good" means — before the prompt exists — forces the team to agree on the task definition. Arguments about edge cases get resolved in the dataset, once, instead of in every code review.
- Every change becomes attributable. Change one thing, re-run, compare. The changelog of scores answers "what did we break?" months later (04.9, 1.3 built this loop for prompts; evals generalise it to the whole system).
- Failures become assets. Every production failure you investigate can be scrubbed, labelled and added to the dataset — the eval set grows from real mistakes, which is the flywheel described in 5.1 and owned in depth by 10A.2.
Part 2: What an eval actually is#
2.1 The anatomy: dataset + task + scorer(s) + aggregation + report#
Strip every eval framework to its bones and five components remain. This is the mental model for everything in this module — every tool (promptfoo, DeepEval, Ragas, Inspect AI) is a different packaging of the same five things.
flowchart TB
subgraph inputs ["Inputs to the eval"]
DS["Dataset<br/>examples with inputs + labels"]
T["Task<br/>the system under test:<br/>prompt + model + pipeline"]
end
subgraph scoring ["Scoring"]
SC["Scorer(s)<br/>code graders, metrics,<br/>LLM judges, humans"]
AG["Aggregation<br/>mean, pass rate,<br/>worst-slice, gates"]
end
DS --> T
T -->|"outputs"| SC
SC --> AG
AG --> RP["Report<br/>headline numbers,<br/>slices, failures, cost"]
RP -->|"read failures"| DS- Dataset — the fixed set of inputs the system is run against, with whatever ground truth the scorers need. "Fixed" is the operative word: the same set, versioned, so numbers are comparable over time. Built properly in 10A.2.
- Task — the thing under test: your prompt, your model choice, your whole pipeline (retrieval + generation + tools). In code, the task is a function from example to output — the same callable seam 04.9 and 03.10 use.
- Scorer(s) — the rules that turn an output into a verdict or a number. A scorer can be deterministic code (exact match, JSON validity, a regex), a computed metric (F1, recall@k), an LLM-as-judge (a model grading against a rubric — 10A.4), or a human. The cheapest sufficient scorer wins; 10A.3 is the catalogue.
- Aggregation — how per-example scores become the headline: mean score, pass rate, per-slice breakdowns, worst-slice floors. A single averaged number is where nuance goes to die; aggregation design is 10A.3 and 10A.8 territory.
- Report — what a human reads: the numbers and the failing examples with their outputs. An eval whose report hides the failures is a vanity metric.
2.2 The vocabulary#
The module uses these terms precisely; learn them once here.
| Term | Meaning | First used properly in |
|---|---|---|
| Eval / evaluation | A structured, repeatable measurement of system quality: dataset + task + scorer(s) + aggregation + report | this lesson |
| Benchmark | A public, standardised eval designed to compare models or systems across teams (MMLU-style, SWE-bench-style). Optimised for comparability, not for your product | 10A.10 |
| Product eval / task eval | An eval built for your task and your users, on your data distribution. The one that predicts whether your feature works | this lesson onward |
| Metric | A computed number over outputs (accuracy, F1, recall@k, latency). Usually deterministic | 10A.3 |
| Grader | The broader thing that produces a verdict: a metric, a code check, a judge, a human. "Metric" is a kind of grader | this lesson |
| Judge / LLM-as-judge | A model used as a grader for qualities code can't check (tone, helpfulness, faithfulness) | 10A.4 |
| Rubric | The written criteria a judge (or human) grades against — definitions plus anchored examples of good/borderline/bad | 10A.4 |
| Golden set / golden dataset | The labelled eval set treated as ground truth; "golden" = the reference answers are authoritative | 10A.2 |
| Offline eval | Runs on a fixed dataset before/without production traffic — the subject of most of this module | 10A.9 |
| Online eval | Measures live production traffic: user feedback, sampled judge scoring, drift monitors | 10A.9 |
| Pass rate | Fraction of examples (or runs) that pass all gates — the workhorse binary metric | this lesson |
| Regression | A previously-passing case now failing after a change (prompt, model, data, code) | 10A.8 |
| Flake / flaky eval | An eval that passes/fails non-deterministically for infrastructure reasons (timeouts, rate limits) rather than quality reasons — must be distinguished from real regressions | 10A.8 |
| Error analysis | Reading actual failures and coding them into categories — the prerequisite for targeted evals | Part 4 |
| Eval-driven development | Writing the eval alongside the system and letting it adjudicate changes | 1.4 |
| CI gate | An eval wired into continuous integration that blocks merges below a threshold | 10A.8 |
Two distinctions repay memorising. Benchmark vs product eval: a benchmark tells you how a model ranks against other models on a standard test; a product eval tells you whether your feature works for your users. Leaderboards are for shortlisting models (10A.10); only a product eval should gate a launch. Metric vs grader: "accuracy" is a metric; the thing that decides pass/fail on an invoice extraction is a grader that might combine five metrics, a schema check and a judge. Metrics feed graders; graders feed reports.
2.3 Evals vs tests vs benchmarks#
Three words get used interchangeably and shouldn't be:
| Unit/integration test | Eval | Benchmark | |
|---|---|---|---|
| What it checks | Code correctness: does the function do what the spec says? | System quality: are the outputs good enough for users? | Comparative model capability on a standard task |
| Determinism | Deterministic (same input → same result) | Probabilistic — needs repeats, intervals, gates | Deterministic scoring of fixed outputs, but model behaviour varies |
| Ground truth | The spec / expected value | Labels, rubrics, judges, human judgement | Public reference answers |
| Owned by | Developers | The product team | A third party (or you, mimicking one) |
| When it runs | Every save / every push | On change, on schedule, on release | Occasionally, for model selection |
| Failure means | A bug | A quality regression | "This model isn't best at X" |
The relationship in practice: unit tests verify your plumbing (did the request build correctly, does the parser handle the response shape — 03.10); evals verify your product (are the answers any good). A green test suite with a bad eval means the code works and the feature doesn't. Both are needed; neither substitutes for the other.
Part 3: Defining success#
3.1 From product goals to measurable criteria#
"The bot should be helpful" is not a criterion; it is a wish. An eval needs criteria a scorer can check, which means translating product goals into measurable criteria: statements with a defined pass condition. Anthropic's documentation frames the same ordering — success criteria first, then the empirical tests that measure them (source, verified November 2026).
The translation method:
- Start from the user's goal, not the model's output. For a support-triage feature the user goal is "the right team sees the ticket fast". Decompose: the category must be right (routing), the priority must be right (SLA ordering), the summary must be actionable (the engineer doesn't re-read the whole ticket).
- For each goal, name the observable. "Helpful reply" → observable proxies: answers the question asked, states a next step, no fabricated policy. Each proxy becomes a scorer or a rubric line.
- Write the pass condition. Not "summary is good" but "summary is one sentence, under 25 words, names the concrete issue" — the form 04.1's "What good looks like" block already uses.
- Attach a threshold. A criterion without a number is a vibe. "At least 95% of triage labels correct on the golden set" is a criterion.
A worked example, goal → criteria → scorer:
| Product goal | Measurable criterion | Scorer type |
|---|---|---|
| "Routes tickets to the right team" | category field equals the human label on the golden set |
Exact match (code) |
| "Flags urgent issues fast" | priority equals label; P1 recall ≥ 0.9 (missing an outage is costlier than over-flagging) |
Confusion-matrix metric (code) |
| "Summaries save the engineer time" | Summary non-empty, < 25 words, contains the issue keyword | Code checks + judge for quality |
| "Never leaks customer data in logs" | Zero PII patterns in logged outputs | Regex/PII scan (code, hard gate) |
| "Replies sound like us" | Tone rubric score ≥ 4/5 on a judge, calibrated against human labels | LLM judge (10A.4, 10A.5) |
| "Stays within budget" | p95 latency < 4 s, cost per request < $0.01 | Operational metrics (code) |
Notice the last column: most criteria are checked by code, not judges. That ordering — code first, judges only where code can't see — is the backbone of 10A.3.
3.2 The quality dimensions#
"Quality" for an LLM feature is not one axis. The dimensions below recur across every task type; each needs its own criterion and usually its own scorer. The table names the dimension, what it means, and where it is owned in this module.
| Dimension | What it means | Typical scorer | Deep dive |
|---|---|---|---|
| Correctness | The answer is factually/right-answer right | Exact match, field metrics, judge vs reference | 10A.3, 10A.6 |
| Groundedness / faithfulness | Every claim is supported by the provided context (no fabrication) | Claim-level judge, NLI-style checks | 10A.4, 10A.6 |
| Completeness | Nothing required is missing (all fields, all key points) | Field recall, nugget recall | 10A.3, 10A.6 |
| Format validity | Output parses and matches the contract (JSON, schema, length) | Schema validation, parse rate | 03.4, 10A.3 |
| Instruction following | Respects the stated constraints (language, length, "don't mention X") | Assertion checks, judge | 10A.3 |
| Tone / style | Reads like the brand; appropriate register | Judge with rubric | 10A.4 |
| Safety | Refuses what it should, answers what it shouldn't refuse, no policy violations | Refusal-rate metrics, safety judges | 10A.7 preview; owned by Module 12 |
| Robustness | Same answer under paraphrase, typos, translation, noise | Perturbation suites | 10A.3 (property tests), 10A.10 |
| Fairness | No systematic quality gap across demographic groups | Counterfactual/templated tests | 10A.10 preview; Module 12 |
| Latency | Time to first token, total latency, at percentiles | Harness timing | 10A.3 (operational metrics) |
| Cost | Tokens and dollars per request/example | Usage fields | 03.7, 10A.3 |
| Reliability / consistency | Same input → same acceptable output across runs | Repeated-run agreement, pass^k | 10A.5, 10A.7 |
A feature's scorecard is a subset of these — you choose the dimensions that match the product goal, then measure each one. "The invoice extractor" cares about correctness, completeness, format, latency, cost. "The support chatbot" cares about groundedness, instruction following, tone, safety, abstention. Nobody measures all twelve on day one.
3.3 Hard requirements vs soft scores#
Two kinds of criteria behave differently under aggregation, and conflating them is a classic eval-design bug:
- Hard requirements (must-pass / gates): pass/fail conditions that admit no averaging. "Output must parse as JSON", "must never fabricate a citation", "must refuse disallowed requests", "PII must not appear in logs". A single failure is a failure — you don't get to average it away. These become gates in CI (10A.8).
- Soft scores: continuous or graded measures where degree matters: correctness rate 0.92, tone 4.1/5, faithfulness 0.87. These aggregate into means, intervals and trends.
The design rule: gates on what must never fail; scores on what should be good on average. A triage eval might gate on "every output is valid JSON with the right keys" (hard) while scoring "priority accuracy 0.95" (soft). If the hard gate fails once in 500 examples, that is a launch blocker, not a rounding error.
Thresholds and acceptable error. Every soft criterion needs a number that means "good enough". Set it from the error cost (3.4), not from what the model currently achieves — a threshold set at today's score ratifies today's bugs. Write it as "at least X on the golden set, with the interval not excluding Y" once you have statistics (10A.2 covers sample sizes and intervals properly).
3.4 Error costs: false positives vs false negatives#
Not all mistakes cost the same, and the eval must encode the asymmetry. The canonical pair:
- False positive / false accept — the system says "yes" when the truth is "no". A spam filter that marks a real invoice as spam loses a payment; a medical-style FAQ that answers a question it should have refused may mislead.
- False negative / false reject — the system says "no" when the truth is "yes". A fraud check that misses a fraudulent transaction; an abstaining assistant that refuses answerable questions and pushes users to human agents.
The cost ratio decides the operating point. If a missed fraud case costs 100× a false alarm, you tune for recall and accept false positives — and your eval reports both numbers separately, because "accuracy 97%" hides which error dominates. This is why 10A.3 teaches precision/recall/F1 and per-class confusion matrices rather than accuracy alone: accuracy is only meaningful when errors are roughly symmetric, which they almost never are in production.
The same logic applies to abstention: a well-designed system knows when not to answer. "Answered when it should have abstained" and "abstained when it should have answered" are two different failure columns in the confusion matrix — 10A.6 builds the abstention metric for RAG explicitly.
3.5 The metric hierarchy#
A dashboard with forty metrics is a dashboard nobody reads. The metric hierarchy organises metrics into three tiers by the decision they support. Before the tiers, one more axis decides where each metric lives: user-facing vs system-level metrics.
- User-facing metrics measure what the person using the feature experiences — task success, answer correctness, groundedness, resolution rate, satisfaction. They answer "is the product good?", and they are the raw material for north-star metrics.
- System-level metrics measure the machinery around the model — latency, cost per request, error and timeout rates, parse rate, token usage, uptime. They answer "is the system healthy, fast and affordable enough?", and they are the raw material for guardrails.
| Family | Who feels it | Typical metrics | Lives in |
|---|---|---|---|
| User-facing | The user | Task success rate, answer correctness, groundedness, resolution rate, CSAT | North-star, diagnostics |
| System-level | Your bill, your SLO, your on-call | p95 latency, cost per request, error rate, parse rate, token usage | Guardrails, ops dashboards |
The boundary is fuzzy at the edges — users feel latency, but it is measured, budgeted and alerted on as a system property. What matters is that a scorecard needs both families, because each can look healthy while the other is broken. A triage feature can hit 99% format compliance at fractions of a cent per call while misrouting every urgent ticket — healthy system, failing product. Or it can label everything correctly while timing out on half the requests — good answers on the cases that complete, unusable product overall. One family answers "is it good?"; the other answers "can we afford it and rely on it?". You need both questions answered, and they need different instrumentation: user-facing numbers come from evals and user signals, system-level numbers come from the harness timings, token usage and operational metrics already discussed in 3.2.
flowchart TB
subgraph north ["North-star metric"]
NS["The one number that tracks<br/>the product goal:<br/>task success rate, CSAT, resolution rate"]
end
subgraph guard ["Guardrail metrics"]
G1["Must-not-regress:<br/>safety violations, PII leaks,<br/>cost per request, p95 latency"]
end
subgraph diag ["Diagnostic metrics"]
D1["Explain *why* the north star moved:<br/>per-slice pass rates, per-stage metrics,<br/>per-scorer breakdowns"]
end
NS --- G1
G1 --- D1
D1 -.->|"drill down when<br/>something moves"| NS- North-star metric — the single number that best tracks the product goal: task success rate for an agent, correct-resolution rate for support, citation accuracy for RAG. Almost always a user-facing metric. It is deliberately few (one or two).
- Guardrail metrics — numbers that must not regress even when the north star improves: safety violation rate, PII leakage count, cost per request, p95 latency, refusal rate — mostly system-level metrics. They exist because optimising the north star alone eventually breaks something else (Goodhart's law in production: when a measure becomes a target, it ceases to be a good measure).
- Diagnostic metrics — the per-slice, per-stage, per-scorer breakdowns that explain movement: pass rate by intent, faithfulness by query type, tool-call accuracy by tool. Nobody puts these on the executive dashboard; everybody needs them when the north star moves.
The hierarchy also fixes the reporting order: lead with the north star, show guardrails crossed or approaching thresholds, attach diagnostics only for the slices that moved. 10A.9 maps these tiers onto offline vs online measurement.
Part 4: Error analysis comes first#
4.1 Look at your data#
Before any metric, before any dataset design, the highest-yield activity in evaluation is the one teams skip: read the failures. The workflow that the strongest practitioner writing converges on — read real outputs, code failures into categories, then design targeted evals — is the same one OpenAI's evaluation guide, Hamel Husain's essay Your AI Product Needs Evals and the Husain and Shankar LLM Evals FAQ all recommend:
- Collect real outputs. From production logs, from dogfooding, from the demo you just showed a stakeholder. Traces and logged prompts/outputs are the raw material (03.10 covers structured logging of every call; 07.10 shows the RAG trace viewer).
- Sample, don't census. Read 20–50 outputs — deliberately including the weird ones, not just the first page of logs. Failure modes cluster; you don't need thousands to find the first three categories.
- Label each failure in plain language. "Wrong category", "summary too long", "invented a refund policy", "ignored the language instruction". One line per failure, no taxonomy yet.
- Cluster the labels into categories. This is open coding — you let the categories emerge from the data instead of imposing a taxonomy top-down. The result is a failure taxonomy: 3–7 recurring categories with example outputs for each.
- Size the categories. Rough counts ("about a third of failures are format drift") tell you where eval effort pays first.
Only then do you design scorers — because now each scorer targets a named, observed failure class instead of a generic abstraction. The taxonomy also becomes the slice axes on your dataset (10A.2 formalises this as stratified slices).
4.2 Open coding failures into a taxonomy#
A worked example for the triage task. Reading 30 logged outputs, a team might code failures like this:
| Code | Failure | Example output (paraphrased) | Frequency |
|---|---|---|---|
| F1 | Format drift — prose or markdown instead of bare JSON | "Sure! Here's the triage: json {...}" |
~30% |
| F2 | Priority inflation — anger read as urgency | Frustrated billing complaint → P1 | ~25% |
| F3 | Category confusion on multi-intent tickets | "duplicate charge + discount question" → shipping | ~20% |
| F4 | Summary verbosity — three sentences, 60 words | Full paragraph restating the ticket | ~15% |
| F5 | Empty-input mishandling — invented content for empty ticket | Summary hallucinating a problem | ~10% |
Now the taxonomy does work: each category maps to a different fix and a different scorer. F1 is a format/contract problem (structured output or a stricter prompt — 03.4); F2 is a rubric/priority-definition problem (the rules need "anger ≠ incident"); F3 is a label-boundary problem (the category definitions need multi-intent guidance); F4 is a length constraint problem; F5 is an edge-case rule problem (the empty-input rule exists but wasn't followed). One scorer can't catch all five, and one prompt fix can't fix all five.
4.3 Turning categories into targeted evals#
Each failure category becomes eval coverage in one of three ways:
- A labelled example — the failing input, with the correct output a human would produce. This is the primary artefact: failures become golden-set rows. Your dataset's edge-case slice is your failure taxonomy, operationalised.
- A targeted scorer — if the category is checkable by code (format, length, required field, forbidden string), write the deterministic check. Format drift → a parse-and-schema scorer. Verbosity → a word-count scorer. These are the cheapest, most reliable graders.
- A rubric line — if the category needs judgement ("did the summary capture the urgent issue, not just an issue"), it becomes a criterion in a judge rubric (10A.4) or a human-review checklist.
The compounding benefit: every new production failure adds a row to the dataset, which means the eval gets harder exactly where the system is weak — the flywheel in 5.1. This is also why eval sets must be versioned and treated as code: an eval set that silently grows is a moving target (10A.2 owns dataset hygiene).
4.4 Why generic metrics mislead#
The temptation: skip error analysis, grab a generic quality metric — "helpfulness", "coherence", "overall quality" — and put it on the dashboard. Three reasons it misleads:
- Generic metrics don't match your failure modes. A "helpfulness" judge can score an output highly while it fabricates a refund policy — helpful-sounding and wrong. The metric measures a dimension your users may not care about and misses the one they do.
- They hide the distribution. A mean "helpfulness 4.2/5" is compatible with "90% great, 10% dangerous" — and the 10% is what generates refunds and churn. Aggregation without slices and gates is where failures go to be averaged away (the failure gallery in 9.2 names this explicitly).
- They can't be acted on. "Helpfulness dropped 0.3" doesn't tell you whether to fix the prompt, the retrieval, the model or the rubric. "Citation precision fell on multi-hop queries" does.
The correct order is always: error analysis → failure taxonomy → targeted criteria → scorers → aggregation → report. Generic metrics survive only as diagnostics high in the hierarchy (3.5) — useful for noticing that something moved, useless for deciding what to do.
4.5 How many traces to read, and when to stop#
"Read 20–50 outputs" is the starting move, not the finish line. Two practitioner rules of thumb, both from Hamel Husain and Shreya Shankar's LLM Evals FAQ (updated September 2026; opened November 2026) — treat them as conventions to calibrate on your own data, not laws:
- Read at least 30 traces yourself, and work from a pool of roughly 100 diverse ones. Keep reading past that for as long as you are still learning something. The reader who looks at the traces must be able to judge them: for a medical-style FAQ or a contract assistant, that means a domain expert, not whoever happens to be free.
- Stop at theoretical saturation. Qualitative researchers use this term for the point where new data stops changing the categories. In error analysis it means: new traces no longer reveal new failure modes or change the existing ones. Until then, keep sampling; after that, more reading has little return.
A worked illustration of the stopping rule (invented numbers, to show the shape of the stopping rule, not a measurement):
| Batch of traces read | New categories found | Existing categories reworded or split | Decision |
|---|---|---|---|
| First 30 (random sample) | 5 | n/a | Keep reading |
| Next 30 (include the lowest-rated and the longest) | 1 | 1 split | Keep reading |
| Next 30 (include non-English and empty inputs) | 0 | 0 | Saturated for now; build evals for the taxonomy |
"For now" matters: saturation is relative to the traffic you sampled. A new feature launch, a new language or a model upgrade changes the traffic, so error analysis restarts on the new slice (10A.9 schedules this as a recurring review).
Two terms complete the vocabulary of 4.2. Open coding is the first pass: a free-text note per failure, with no categories yet. Axial coding is the second pass: grouping the notes into a small set of categories, then splitting or merging categories as more traces arrive. The result is the failure taxonomy.
Prefer binary verdicts per failure mode over 1–5 scores. The same FAQ argues that adjacent points on a Likert scale (a 3 versus a 4) are judged inconsistently and that annotators drift towards the middle to avoid a hard call. The alternative for tracking gradual progress is several binary checks for the parts of a quality, such as "4 of the 5 expected facts are present", which is exactly the partial-credit design Score.value uses in Part 6. 10A.5 returns to this when it measures how consistently two labellers, human or model, apply a scale.
Part 5: The evaluation lifecycle#
Deep-dive
5.1 The lifecycle#
Evaluation is not a phase; it is a loop that starts before there is a product and never ends. The stages, in the order a real feature grows through them:
flowchart LR
M["1. Manual review<br/>a human reads outputs"] --> D["2. First dataset<br/>20–50 labelled examples"]
D --> C["3. Code graders<br/>deterministic scorers"]
C --> J["4. Judges<br/>LLM-as-judge for what code can't see"]
J --> G["5. CI gate<br/>evals block bad merges"]
G --> O["6. Online monitoring<br/>live traffic, sampled scoring, drift"]
O -->|"failures + feedback"| D- Stage 1 — manual review. Before any dataset exists, the honest eval is a human reading outputs. Do it on a schedule ("read ten traces every Friday"), and write down what you see — those notes are the seed of the failure taxonomy (4.1).
- Stage 2 — first dataset. 20–50 hand-labelled examples covering the happy path and the known edge cases. This is enough to catch gross regressions and iterate prompts against; it is not enough to detect 2-point differences (statistics arrive in 10A.2).
- Stage 3 — code graders. Deterministic scorers for everything checkable: format, schema, exact/field match, length, forbidden strings, citation validity, latency, cost. Cheapest, fastest, most reliable — 10A.3 is the catalogue.
- Stage 4 — judges. For qualities code can't see (tone, helpfulness, faithfulness), add an LLM judge — but only after the code graders exist, and only once it is calibrated against human labels (10A.4, 10A.5).
- Stage 5 — CI gate. The eval suite runs on every relevant change and blocks merges below threshold. Gating design — absolute floors vs relative non-regression, flake handling — is 10A.8.
- Stage 6 — online monitoring. Production traffic scored by sampling, user-feedback signals, drift detectors — the offline eval's sibling (10A.9; observability platforms are Module 11A's).
- The flywheel. Every stage feeds the dataset: production failures become new labelled cases, judge disagreements become adjudicated labels, drift becomes new slices. The eval set grows from reality — which is why it must be versioned, scrubbed of PII and treated as code (10A.2).
5.2 How much eval is enough, by stage#
The honest answer is "as much as the stage's risk justifies" — and the stages are recognisable:
| Stage | What "enough" looks like | What it catches | What it can't |
|---|---|---|---|
| Prototype / hack week | ~20 hand-checked examples, human review, no automation | Gross breakage, format failures, "is this even the right task?" | Subtle quality drift, rare failures, anything statistical |
| Internal dogfood / beta | 50–100 labelled cases, code graders on every change, weekly human review | Prompt regressions, format drift, known edge cases | Rare production-only failures, judge-worthy quality dimensions |
| Launch / production v1 | Golden set + held-out test set, CI gate on hard requirements, sampled judge scoring, failure→dataset flywheel running | Most regressions before users see them; known failure modes covered | Long-tail novelty, adversarial inputs, distribution shift |
| Scale / multi-model | Per-slice gates, statistical comparisons for model/prompt changes, online monitoring aligned with offline metrics, periodic judge recalibration | Subtle regressions, slice-level gaps, judge drift | True unknown-unknowns — keep error analysis running |
Two rules of thumb: eval cost should be a small fraction of inference cost (a suite that costs more than the feature it protects gets switched off), and the eval set should grow roughly with traffic — more users means more failure modes means more labelled cases needed to see them.
5.3 Cost and benefit#
Evals cost money — dataset labelling hours, judge tokens, CI minutes, engineer attention. The benefit side is asymmetric: an eval that catches one launch-blocking regression pays for itself many times over; an eval nobody runs pays nothing. Practical budgeting:
- Labelling is the expensive part, not compute. A domain expert's hour produces maybe 20–50 quality labels; plan accordingly and use LLM pre-labelling with human review to stretch it (10A.2).
- Tier the suite by cost. Smoke eval (~20 cases, every commit) → full golden set (on PR) → extended/nightly → exhaustive (pre-release). 10A.8 formalises the tiers; the principle applies from day one.
- Cheapest sufficient scorer (repeated from 08A.14, 4.2): a code check beats a judge beats a human on cost and reliability. Spend human/judge effort only where code is blind.
- Track eval cost per run like inference cost — tokens per judge call, examples per run, wall-clock. An eval that silently 10×'d in cost is a budget incident.
5.4 Common excuses and rebuttals#
| Excuse | Rebuttal |
|---|---|
| "We don't have time to build evals." | You are already doing evals — badly, via vibe checks that don't scale and can't be compared. Twenty labelled examples is a day's work; the first failure it catches pays for it. |
| "The model is good enough, evals are overhead." | "Good enough" is a claim about a distribution. Without measurement you don't know the failure rate, the failure modes, or whether the next prompt edit made it worse. |
| "Evals are just more prompts to maintain." | The eval is a specification, not overhead — it is the written agreement about what "good" means, which you need anyway. |
| "Our users will tell us when it breaks." | Users tell you about the failures they hit and bother to report — a biased, delayed, angry sample. By then the regression has been live for weeks. |
| "We tested it in the playground." | A playground session is a sample of one from a moving distribution. Same prompt, different answer next run (02.5, Part 7). |
| "Eval scores don't match what users experience." | Then your eval measures the wrong thing — which is an argument for better evals (error analysis, slices, online signals), not for none. 10A.9 is about exactly this alignment problem. |
| "Every change requires re-labelling." | No — the dataset is versioned and append-only; new failures add rows, old rows stay fixed so scores stay comparable. |
| "We can't afford judges/humans at scale." | You can't afford not knowing. Start with code graders (free), add a judge only for the dimensions code can't see, sample human review rather than exhaustive labelling. |
| "The benchmark score is high, we're fine." | Benchmarks measure the model on someone else's task. Your feature's failure modes are yours alone — only a product eval sees them (10A.10). |
5.5 Capability evals and regression evals#
Not every eval has the same job, and mixing the jobs in one pass rate is a common source of confusion. Anthropic's Demystifying evals for AI agents (January 2026; opened November 2026) draws the distinction cleanly, and it applies to every task type, not only agents:
| Capability evals | Regression evals | |
|---|---|---|
| Question | "What can the system do well yet?" | "Does it still handle what it used to?" |
| Starting pass rate | Low on purpose: a hill to climb | Close to 100%: the cases already pass |
| What a drop means | Nothing; the case is still being worked on | A regression: investigate before merging |
| Role in CI (10A.8) | Reported, never a merge blocker | A gate |
| Typical content | The hard slices from 4.2: multi-intent tickets, other languages, adversarial inputs | Cases that passed once and must keep passing, plus every fixed production failure |
Capability cases graduate: once a capability eval passes consistently, move its cases into the regression suite, where they now protect the gain. The opposite problem is saturation: when a system passes every case that can be passed, the eval stops discriminating, progress is hard to see, and large real improvements show up as tiny score changes. A saturated capability eval is a signal to write harder cases (from fresh error analysis), not to celebrate.
In evalkit this is one metadata key and no new code: tag each Example with {"suite": "capability"} or {"suite": "regression"}. The slice_breakdown() you already have then reports the two pass rates separately, and a CI gate (10A.8) can read only the regression slice.
5.6 No single layer catches everything#
Anthropic's post borrows an idea from safety engineering, the Swiss-cheese model: every quality layer has holes, and failures that slip through one layer are caught by another. Pre-release evals are one slice of the cheese:
| Layer | Catches well | Misses | Where it is taught |
|---|---|---|---|
| Automated offline evals | Regressions on known cases, before users see them | Anything not in the dataset: new inputs, new user intents | This module, 10A.2–10A.8 |
| Production monitoring | Latency, cost and error spikes, drift in input mix | Quality problems that don't change a metric | 10A.9, Module 11A |
| A/B tests | Real user impact of a change, including effects no eval models | Slow (days to weeks) and needs traffic; tells you that, not why | 10A.9 |
| User feedback | What users bother to report: confusion, wrong answers they noticed | Silent failures users don't notice; a biased, delayed sample (5.4) | 10A.9 |
| Reading transcripts | Why a failure happened; broken graders; new failure categories | Scale: a person reads dozens, not millions | Part 4 |
| Human studies / expert review | Quality that no grader captures; ground truth for calibration | Cost and speed | 10A.5 |
The practical reading: an eval suite that passes is evidence, never proof. Plan which layer owns which risk, and make sure every failure found in a later layer (a user complaint, a monitoring alert) flows back into the dataset, which is the flywheel of 5.1.
Part 6: Anatomy of a minimal harness#
Everything so far has been concepts. This part builds the smallest honest eval harness — evalkit — that every later lesson in the module extends. The design goals, in order:
- Three seams, all injectable. Dataset (examples), task (example → prompt), scorer (example + output → verdict), and
call_model(prompt → output). Any of them can be a real provider call, a fake, or a replay — the harness never knows which. - Pure stdlib. No dependencies, so it runs anywhere and the reader can audit every line.
- Honest output. Per-example rows, JSONL for storage, a summary with per-slice breakdowns, failure lists — the report shows the failures, not just the mean.
- Extensible, not final.
repeats, an optional cache, error capture and metadata slices are the hooks 10A.8 grows into record/replay and parallel runners.
It builds directly on 04.1, 7.3's triage_loop.py — same task family (ticket triage), same callable-model seam — grown up: named scorers instead of one score(), metadata slices, JSONL output, repeats and caching. 04.9's promptlab.py is the prompt-iteration sibling; evalkit is the evaluation sibling. And it sits on 03.10's testing seam — the fake clients and cassettes that make call_model testable offline.
6.1 The three data types and the runner#
evalkit/core.py — save it as evalkit/core.py inside your project (an empty evalkit/__init__.py alongside it makes the import in triage_eval.py work):
# evalkit/core.py
"""evalkit/core.py — the smallest honest eval harness (lesson 10A.1).
Pure standard library: no dependencies, no network. Three seams do all the
work, and they are the same seams every later lesson in this module extends:
Dataset -> any iterable of Example (id, input, reference, metadata)
Task -> Example -> prompt text (the thing under test)
Scorer -> (Example, output) -> Score (the definition of "good")
call_model -> prompt -> raw output text (any callable: provider SDK,
fake, or replay)
run_eval() wires them together, scores every (example, run) pair, keeps the
raw outputs, and produces an EvalReport you can write as JSONL and print as
a summary with per-slice breakdowns.
Later lessons add to this package: dataset.py (10A.2), scorers.py (10A.3),
judges.py (10A.4), runner.py with caching and parallelism (10A.8). This file
stays the shared core.
"""
from __future__ import annotations
import hashlib
import json
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Callable, Iterable, Mapping, Protocol, runtime_checkable
# ---------------------------------------------------------------------------
# The three data types
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class Example:
"""One eval case.
id: stable identifier, used in reports and JSONL rows
input: the task input rendered into the prompt (a ticket, a doc
chunk, a question — whatever the task consumes)
reference: ground truth for scorers that need it (a label, a JSON
string, a canonical answer); "" when scoring needs a
rubric or a judge instead
metadata: slice tags for breakdowns, e.g. {"intent": "billing",
"edge": "empty"} — every key becomes a breakdown axis
"""
id: str
input: str
reference: str = ""
metadata: Mapping[str, str] = field(default_factory=dict)
@dataclass(frozen=True)
class Score:
"""One scorer's verdict on one output.
value: partial credit in [0.0, 1.0] — lets a scorer say "half right"
passed: the binary gate; a row passes only when EVERY scorer passes
detail: human-readable explanation shown for failures
"""
name: str
value: float
passed: bool
detail: str = ""
@runtime_checkable
class Scorer(Protocol):
"""Anything with a name and score(example, output) -> Score.
A plain function works too once wrapped in FunctionScorer (below).
"""
name: str
def score(self, example: Example, output: str) -> Score: ...
@dataclass(frozen=True)
class FunctionScorer:
"""Adapter: any score(example, output) -> Score function becomes a Scorer.
Import it from here: ``from evalkit.core import FunctionScorer``.
"""
name: str
fn: Callable[[Example, str], Score]
def score(self, example: Example, output: str) -> Score:
return self.fn(example, output)
# The dataset seam: anything you can iterate over Examples. A plain list
# here; 10A.2's dataset.py adds loaders, splits and validation behind the
# same seam.
Dataset = Iterable[Example]
# A task renders one Example into the prompt text sent to the model.
Task = Callable[[Example], str]
# A model call turns prompt text into raw output text. Keep it a plain
# callable — SDK client, fake, or replay wrapper — so the harness never
# cares which.
CallModel = Callable[[str], str]
# ---------------------------------------------------------------------------
# Results
# ---------------------------------------------------------------------------
@dataclass
class Row:
"""One scored (example, run) pair — one line of the JSONL output."""
example_id: str
run: int
output: str
scores: dict[str, Score]
passed: bool
metadata: dict[str, str]
cached: bool = False
error: str | None = None
latency_ms: float = 0.0
@dataclass
class EvalReport:
"""Everything one run_eval() call produced."""
name: str
model: str
rows: list[Row]
# -- headline numbers ----------------------------------------------------
@property
def n_examples(self) -> int:
return len({r.example_id for r in self.rows})
@property
def n_runs(self) -> int:
return len(self.rows)
@property
def pass_rate(self) -> float:
"""Fraction of (example, run) rows that passed every scorer."""
if not self.rows:
return 0.0
return sum(r.passed for r in self.rows) / len(self.rows)
@property
def mean_score(self) -> float:
"""Mean of per-row mean scores — partial credit shows up here even
when pass_rate doesn't move."""
vals = []
for r in self.rows:
if r.scores:
vals.append(sum(s.value for s in r.scores.values()) / len(r.scores))
return sum(vals) / len(vals) if vals else 0.0
@property
def n_errors(self) -> int:
return sum(1 for r in self.rows if r.error is not None)
@property
def n_cached(self) -> int:
return sum(1 for r in self.rows if r.cached)
# -- per-example aggregation (repeats collapse here) ----------------------
def per_example(self) -> dict[str, dict]:
"""example_id -> {runs, passes, pass_rate, mean_score}.
With repeats > 1 an example's pass_rate is the fraction of its runs
that passed — the per-example view of run-to-run noise.
"""
by_id: dict[str, list[Row]] = {}
for r in self.rows:
by_id.setdefault(r.example_id, []).append(r)
out = {}
for eid, rs in by_id.items():
scored = [r for r in rs if r.scores]
out[eid] = {
"runs": len(rs),
"passes": sum(r.passed for r in rs),
"pass_rate": sum(r.passed for r in rs) / len(rs),
"mean_score": (
sum(sum(s.value for s in r.scores.values()) / len(r.scores)
for r in scored) / len(scored)
if scored else 0.0
),
"metadata": rs[0].metadata,
}
return out
# -- slices ---------------------------------------------------------------
def slice_breakdown(self) -> dict[str, dict[str, dict]]:
"""For every metadata key: {value -> {examples, pass_rate}}.
Slices are computed over per-example pass rates (not raw rows), so
an example with 3 runs doesn't count triple. This is the cheapest
form of "where do failures cluster" — see lesson Part 4.
"""
per_ex = self.per_example()
axes: dict[str, dict[str, list[float]]] = {}
for eid, agg in per_ex.items():
for key, value in agg["metadata"].items():
axes.setdefault(key, {}).setdefault(value, []).append(
agg["pass_rate"]
)
return {
key: {
value: {
"examples": len(rates),
"pass_rate": sum(rates) / len(rates),
}
for value, rates in sorted(vals.items())
}
for key, vals in sorted(axes.items())
}
# -- output ----------------------------------------------------------------
def failing_examples(self) -> list[str]:
"""example_ids whose pass_rate is below 1.0."""
return sorted(
eid for eid, agg in self.per_example().items() if agg["pass_rate"] < 1.0
)
def summary(self) -> str:
lines = [
f"eval: {self.name} model: {self.model} "
f"examples: {self.n_examples} runs/example: "
f"{self.n_runs / max(self.n_examples, 1):.0f}",
f"pass rate: {self.pass_rate:.1%} "
f"mean score: {self.mean_score:.3f} "
f"errors: {self.n_errors} cache hits: {self.n_cached}",
]
slices = self.slice_breakdown()
if slices:
lines.append("\nslices (pass rate over per-example rates):")
for key, vals in slices.items():
for value, agg in vals.items():
lines.append(
f" {key}={value:<12} n={agg['examples']:<3} "
f"pass={agg['pass_rate']:.1%}"
)
failing = self.failing_examples()
if failing:
lines.append(f"\nfailing examples: {', '.join(failing)}")
return "\n".join(lines)
def to_jsonl(self, path: str | Path) -> Path:
"""One JSON object per row — the artefact you diff, store and mine."""
path = Path(path)
with path.open("w", encoding="utf-8") as f:
for r in self.rows:
f.write(
json.dumps(
{
"eval": self.name,
"model": self.model,
"example_id": r.example_id,
"run": r.run,
"passed": r.passed,
"scores": {
name: {
"value": s.value,
"passed": s.passed,
"detail": s.detail,
}
for name, s in r.scores.items()
},
"output": r.output,
"error": r.error,
"cached": r.cached,
"latency_ms": round(r.latency_ms, 1),
"metadata": r.metadata,
},
ensure_ascii=False,
)
+ "\n"
)
return path
# ---------------------------------------------------------------------------
# The runner
# ---------------------------------------------------------------------------
def _cache_key(model: str, prompt: str, run: int) -> str:
"""Stable key for a (model, prompt, run-index) triple.
The run index is part of the key on purpose: with repeats > 1 each run
is a *separate draw* from the model, and caching them under one key
would collapse the very variance repeats exist to measure. Across
eval invocations the keys still line up, so a warm cache makes whole
re-runs free.
"""
return hashlib.sha256(f"{model}\n{run}\n{prompt}".encode("utf-8")).hexdigest()
def run_eval(
examples: Dataset,
task: Task,
scorers: Iterable[Scorer],
call_model: CallModel,
*,
name: str = "eval",
model: str = "unknown",
repeats: int = 1,
cache: dict[str, str] | None = None,
) -> EvalReport:
"""Run every example through task -> call_model -> scorers.
examples: the dataset (any iterable of Example)
task: Example -> prompt text
scorers: iterable of Scorer; a row passes iff ALL of them pass
call_model: prompt -> raw output text (provider call, fake, or replay)
name/model: labels recorded on every row and in the report
repeats: runs per example; >1 exposes run-to-run noise (Part 6.5)
cache: optional dict[str, str]; when given, prompt->output pairs are
memoised so re-runs and CI are free. Lesson 10A.8 replaces
this dict with a real record/replay store.
"""
scorer_list = list(scorers)
examples = list(examples)
rows: list[Row] = []
for ex in examples:
try:
prompt = task(ex)
except Exception as exc: # a broken task is a failed row, not a crash
for run in range(repeats):
rows.append(
Row(ex.id, run, "", {}, False, dict(ex.metadata),
error=f"task: {exc!r}")
)
continue
for run in range(repeats):
cached = False
error: str | None = None
start = time.perf_counter()
if cache is not None:
key = _cache_key(model, prompt, run)
if key in cache:
output, cached = cache[key], True
else:
try:
output = call_model(prompt)
cache[key] = output
except Exception as exc:
output, error = "", f"call_model: {exc!r}"
else:
try:
output = call_model(prompt)
except Exception as exc:
output, error = "", f"call_model: {exc!r}"
latency_ms = (time.perf_counter() - start) * 1000
scores: dict[str, Score] = {}
if error is None:
for sc in scorer_list:
try:
s = sc.score(ex, output)
except Exception as exc:
s = Score(sc.name, 0.0, False, f"scorer error: {exc!r}")
scores[sc.name] = s
rows.append(
Row(
example_id=ex.id,
run=run,
output=output,
scores=scores,
passed=bool(scores) and all(s.passed for s in scores.values()),
metadata=dict(ex.metadata),
cached=cached,
error=error,
latency_ms=latency_ms,
)
)
return EvalReport(name=name, model=model, rows=rows)The design, compressed:
Dataset— the dataset seam as a type:Iterable[Example]. Deliberately minimal — a list is a valid dataset — because 10A.2 owns the real thing (schema, loaders, splits, versioning) and will satisfy the same seam.Example— one eval case:id,input(what goes into the prompt),reference(ground truth for scorers that need it),metadata(slice tags like{"intent": "billing", "edge": "empty"}). Frozen dataclass, so cases can't be mutated mid-run.Score— one scorer's verdict:valuein [0, 1] for partial credit,passedfor the binary gate,detailfor the human-readable reason.Scorerprotocol —name+score(example, output) -> Score. Anything satisfying it works;FunctionScorer(also defined inevalkit/core.py, import it withfrom evalkit.core import FunctionScorer) adapts a plainscore(example, output) -> Scorefunction into aScorer.Row— one scored (example, run) pair: the JSONL line. Keeps the rawoutput, every scorer's verdict,cached/error/latency_msflags.EvalReport— the aggregate:pass_rate,mean_score,per_example()(repeats collapse here),slice_breakdown()(per metadata key),failing_examples(),summary()(the printed report) andto_jsonl().run_eval()— the loop:task(ex)→call_model(prompt)→ eachscorer.score(ex, output)→Row. Exceptions become failed rows witherrorset, never crashes.repeatsruns each example N times (each a separate draw — variance is signal).cachememoises prompt→output so re-runs are free.
Two subtleties worth pausing on:
- Cache key includes the run index. With
repeats=3each run is a separate draw from the model; keying the cache on(model, prompt)alone would collapse all three draws to the first answer and hide the variance repeats exist to measure. Includingrunkeeps draws distinct within a run while still making whole eval re-runs free. passedrequires every scorer to pass. Two scorers = two gates (format and labels). A row with perfect labels but broken JSON fails — which is correct: downstream code can't use unparseable output no matter how right the labels were.
6.2 The dataset, task, scorers and fake model#
triage_eval.py — the first real eval, at project root:
# triage_eval.py
"""triage_eval.py — the first evalkit run: ticket triage (lesson 10A.1).
Same task family as 04.1's triage_loop.py and 04.9's promptlab, now wearing
the evalkit shape: Examples with metadata slices, named Scorers, an
injectable call_model, JSONL output and a per-slice summary.
Run: python3 triage_eval.py (from the project root; pure stdlib, no keys, real output)
"""
from __future__ import annotations
import json
import re
from evalkit.core import Example, FunctionScorer, Score, run_eval
# ---------------------------------------------------------------------------
# The dataset: 12 labelled tickets. Same ten as 04.1 plus two harder ones.
# reference = "<priority>|<category>"; metadata feeds the slice breakdown.
# ---------------------------------------------------------------------------
EXAMPLES = [
Example("T01",
"Hi, I was charged twice for my pro plan this month and nobody has "
"responded to my emails for days. This is really frustrating and I "
"want my money back. Also is there any discount if I stay?",
"P2|billing", {"intent": "billing", "edge": "multi-intent"}),
Example("T02",
"Our whole team can't log in since this morning. Dashboard shows "
"a 500 error on every page. We're losing sales every hour.",
"P1|technical", {"intent": "technical", "edge": "outage"}),
Example("T03",
"How do I add a second admin to our Team plan? The docs mention "
"it but I can't find the button.",
"P3|account", {"intent": "account", "edge": "how-to"}),
Example("T04",
"I think someone hacked my account. I got a password-reset email "
"I didn't request and now I see charges I don't recognise.",
"P1|account", {"intent": "account", "edge": "security"}),
Example("T05",
"When will my order ship? I ordered the standing desks two weeks "
"ago and tracking hasn't updated.",
"P2|shipping", {"intent": "shipping", "edge": "stale-tracking"}),
Example("T06",
"Your mobile app crashes every time I open the reports tab on "
"Android 15. I've reinstalled twice.",
"P2|technical", {"intent": "technical", "edge": "bug-report"}),
Example("T07",
"Thanks for the quick fix last week — everything works now. "
"Just wanted to say the support was great.",
"P3|other", {"intent": "other", "edge": "no-request"}),
Example("T08",
"I want to downgrade from Team to Pro at the end of this billing "
"cycle. Will I lose my historical data?",
"P3|billing", {"intent": "billing", "edge": "downgrade"}),
Example("T09",
"URGENT: all our API calls are returning 403 since your deploy "
"last night. This is blocking our production launch tomorrow.",
"P1|technical", {"intent": "technical", "edge": "outage"}),
Example("T10", "", "P3|other",
{"intent": "other", "edge": "empty", "allow_empty_summary": "1"}),
Example("T11",
"pls refnd my dupolicate charge on the pro plan, its the second "
"time this month and support hasnt replied",
"P2|billing", {"intent": "billing", "edge": "typos"}),
Example("T12",
"Bonjour, je voudrais savoir si je peux exporter mes données "
"avant de résilier mon abonnement Team. Merci!",
"P3|account", {"intent": "account", "edge": "non-english"}),
]
# ---------------------------------------------------------------------------
# The task: render the prompt for one example. (Prompt wording is Module 04's
# subject; here it only needs to be stable and checkable.)
# ---------------------------------------------------------------------------
PROMPT_TEMPLATE = """\
# Task
Triage a customer support ticket for Acme Cloud. Assign a priority, a
category, and a one-sentence summary for the on-call engineer.
# Rules
- priority: "P1" only for outages, data loss, security incidents or legal
threats; "P2" for anything needing action this week; "P3" for questions
and low-impact issues. When in doubt between P2 and P3, choose P2.
- category: exactly one of "billing", "technical", "account", "shipping",
"other".
- summary: one sentence, under 25 words, naming the concrete issue.
- If the ticket is empty, return {{"priority": "P3", "category": "other",
"summary": ""}}.
# Output format
Reply with ONLY a JSON object, no prose, no markdown fences:
{{"priority": "P1"|"P2"|"P3", "category": "billing"|"technical"|"account"|"shipping"|"other", "summary": "<one sentence>"}}
# Ticket
<ticket>
{ticket}
</ticket>
"""
def triage_task(example: Example) -> str:
return PROMPT_TEMPLATE.format(ticket=example.input)
# ---------------------------------------------------------------------------
# The scorers: the executable definition of "good". Two scorers, two gates —
# a row passes only when BOTH pass.
# ---------------------------------------------------------------------------
CATEGORIES = {"billing", "technical", "account", "shipping", "other"}
PRIORITIES = {"P1", "P2", "P3"}
def _parse_json(text: str) -> dict | None:
"""Same tolerant extractor as 04.1: strip fences, take the first {...}."""
fence = chr(96) * 3
text = re.sub(fence + r"\s*(?:json)?", "", text, flags=re.IGNORECASE)
match = re.search(r"\{.*\}", text, re.DOTALL)
if not match:
return None
try:
obj = json.loads(match.group(0))
except json.JSONDecodeError:
return None
return obj if isinstance(obj, dict) else None
def format_scorer(example: Example, output: str) -> Score:
"""Gate 1 — contract: is the reply a well-formed triage object?"""
obj = _parse_json(output)
if obj is None:
return Score("format", 0.0, False, "no JSON object found")
problems = []
if set(obj) != {"priority", "category", "summary"}:
problems.append(f"keys={sorted(obj)}")
if obj.get("priority") not in PRIORITIES:
problems.append(f"priority={obj.get('priority')!r}")
if obj.get("category") not in CATEGORIES:
problems.append(f"category={obj.get('category')!r}")
if not isinstance(obj.get("summary"), str):
problems.append("summary not a string")
ok = not problems
return Score("format", 1.0 if ok else 0.0, ok,
"ok" if ok else "; ".join(problems))
def label_scorer(example: Example, output: str) -> Score:
"""Gate 2 — correctness: do the labels match the reference?
Partial credit: each of priority / category / summary is one third.
"""
obj = _parse_json(output)
if obj is None:
return Score("labels", 0.0, False, "unparseable output")
exp_priority, exp_category = example.reference.split("|")
allow_empty = example.metadata.get("allow_empty_summary") == "1"
summary = obj.get("summary", "")
checks = {
"priority": obj.get("priority") == exp_priority,
"category": obj.get("category") == exp_category,
"summary": (
(summary == "" and allow_empty)
or (isinstance(summary, str) and 0 < len(summary.split()) < 25)
),
}
value = sum(checks.values()) / len(checks)
passed = all(checks.values())
wrong = [k for k, ok in checks.items() if not ok]
return Score("labels", value, passed,
"ok" if passed else f"wrong: {', '.join(wrong)} "
f"(got {obj.get('priority')}/{obj.get('category')})")
SCORERS = [FunctionScorer("format", format_scorer),
FunctionScorer("labels", label_scorer)]
# ---------------------------------------------------------------------------
# The model under test: a deterministic fake. Deliberately imperfect —
# T02 is misclassified and T11 wraps a JSON fragment in prose — so the
# report has failures to show. In production call_model wraps a provider
# SDK (03.x) and the same harness scores it unchanged.
# ---------------------------------------------------------------------------
class FakeTriageModel:
def __init__(self):
self.calls = 0
self.responses = {
"T01": '{"priority": "P2", "category": "billing", "summary": "Duplicate Pro charge, refund requested."}',
"T02": '{"priority": "P2", "category": "billing", "summary": "Login outage reported."}', # wrong on purpose
"T03": '{"priority": "P3", "category": "account", "summary": "How to add a second admin."}',
"T04": '{"priority": "P1", "category": "account", "summary": "Suspected account takeover."}',
"T05": '{"priority": "P2", "category": "shipping", "summary": "Order tracking stale two weeks."}',
"T06": '{"priority": "P2", "category": "technical", "summary": "App crashes on reports tab."}',
"T07": '{"priority": "P3", "category": "other", "summary": "Customer thank-you, no request."}',
"T08": '{"priority": "P3", "category": "billing", "summary": "Downgrade and data-retention question."}',
"T09": '{"priority": "P1", "category": "technical", "summary": "API 403s blocking launch."}',
"T10": '{"priority": "P3", "category": "other", "summary": ""}',
"T11": "Sure! This looks like a billing issue, I would mark it P2. " # prose with an incomplete JSON fragment — format fail
"Here is the JSON you asked for: {\"priority\": \"P2\"}",
"T12": '{"priority": "P3", "category": "account", "summary": "Data export before cancelling Team plan."}',
}
def __call__(self, prompt: str) -> str:
self.calls += 1
for ex in EXAMPLES:
if ex.input and ex.input in prompt:
return self.responses[ex.id]
return self.responses["T10"]
# ---------------------------------------------------------------------------
# Run it: once cold, once warm — the second run is served entirely from cache.
# ---------------------------------------------------------------------------
def main() -> None:
model = FakeTriageModel()
cache: dict[str, str] = {}
print("=== run 1: cold cache, repeats=2 (24 rows) ===")
report1 = run_eval(
EXAMPLES, triage_task, SCORERS, model,
name="triage-v1", model="fake-triage-1", repeats=2, cache=cache,
)
print(report1.summary())
out = report1.to_jsonl("triage_results.jsonl")
print(f"\nwrote {out} ({sum(1 for _ in out.open())} lines)")
print("\n=== run 2: warm cache, repeats=1 — should cost zero model calls ===")
calls_before = model.calls
report2 = run_eval(
EXAMPLES, triage_task, SCORERS, model,
name="triage-v1", model="fake-triage-1", repeats=1, cache=cache,
)
print(report2.summary())
print(f"\nmodel calls this run: {model.calls - calls_before} "
f"(cache hits: {report2.n_cached})")
if __name__ == "__main__":
main()What each piece does:
EXAMPLES— 12 labelled tickets: the same ten as 04.1 plus a typo-laden one (T11) and a non-English one (T12).referenceis"P2|billing"-style;metadatacarries the slice axes (intent,edge, andallow_empty_summaryfor the empty-ticket rule).triage_task— renders the prompt template. The task seam: swap the template, keep the harness.- Two scorers, two gates.
format_scorerchecks the contract (parseable JSON, exactly the three keys, valid enum values);label_scorerchecks correctness with partial credit (priority/category/summary each one third). A row passes only when both pass — format is the hard gate, labels the soft score. FakeTriageModel— deterministic canned responses keyed by ticket text, deliberately imperfect (T02 misclassified, T11 returns prose wrapping an incomplete JSON fragment). It stands in forcall_model; a real provider call drops into the same slot (03.1 shows the four provider call shapes).
6.3 Running it: real output#
python3 triage_eval.py=== run 1: cold cache, repeats=2 (24 rows) ===
eval: triage-v1 model: fake-triage-1 examples: 12 runs/example: 2
pass rate: 83.3% mean score: 0.903 errors: 0 cache hits: 0
slices (pass rate over per-example rates):
allow_empty_summary=1 n=1 pass=100.0%
edge=bug-report n=1 pass=100.0%
edge=downgrade n=1 pass=100.0%
edge=empty n=1 pass=100.0%
edge=how-to n=1 pass=100.0%
edge=multi-intent n=1 pass=100.0%
edge=no-request n=1 pass=100.0%
edge=non-english n=1 pass=100.0%
edge=outage n=2 pass=50.0%
edge=security n=1 pass=100.0%
edge=stale-tracking n=1 pass=100.0%
edge=typos n=1 pass=0.0%
intent=account n=3 pass=100.0%
intent=billing n=3 pass=66.7%
intent=other n=2 pass=100.0%
intent=shipping n=1 pass=100.0%
intent=technical n=3 pass=66.7%
failing examples: T02, T11
wrote triage_results.jsonl (24 lines)
=== run 2: warm cache, repeats=1 — should cost zero model calls ===
eval: triage-v1 model: fake-triage-1 examples: 12 runs/example: 1
pass rate: 83.3% mean score: 0.903 errors: 0 cache hits: 12
... (same slice table) ...
failing examples: T02, T11
model calls this run: 0 (cache hits: 12)Read it like an engineer:
- 83.3% pass rate, 0.903 mean score — ten of twelve examples fully pass; T02 fails labels (wrong priority/category), T11 fails format. Note how T11 fails: the tolerant
_parse_jsonextractor finds the embedded{"priority": "P2"}fragment inside the prose, but it isn't the required three-key object, so the contract check still rejects it (keys=['priority']; category=None; summary not a stringin the JSONL detail). Prose-wrapped fragments are a real failure mode — the lesson's point is that lenient extraction plus a strict contract check catches them. Two different failure classes, visible separately — exactly what error analysis wants. - The slice breakdown earns its keep immediately.
edge=typosis 0%,edge=outageis 50%,intent=billingandintent=technicalare 66.7% while others are 100%. The failures cluster on specific slices — the signal that a fix should target typos and outage detection, not "the prompt in general". repeats=2produced 24 rows from 24 separate model draws (the cache was cold); the warm-cache second run then made 0 calls. Determinism control and cost control in one demo.triage_results.jsonl— one JSON object per row: eval name, model, example_id, run, passed, per-scorer scores with details, raw output, error, cached, latency_ms, metadata. That file is what you diff between prompt versions, store in CI artifacts, and mine for the next failure taxonomy.
6.4 Determinism controls and caching hooks (preview of 10A.8)#
Two hooks in run_eval are deliberately minimal now and grow later:
repeats— the harness-level determinism control. One run is a sample, not a measurement (02.5, Part 7);repeats=3exposes run-to-run variance per example. Provider-side controls (temperature, seeds) live inside yourcall_modelimplementation — 02.5 covers what each provider honours.cache— a plaindictkeyed by(model, run, prompt)hash. It makes re-runs free during iteration and CI. 10A.8 replaces it with a real record/replay store keyed on the full provider request (model version, params, prompt) — same idea, production-grade, plus cache-invalidation rules so a stale recording can't hide a real regression.
6.5 Where this sits among the earlier tools#
| Tool | Role | Relationship to evalkit |
|---|---|---|
04.1 triage_loop.py |
The minimal prompt test loop | The seed: same task, simpler shape (one score(), no slices/JSONL) |
04.9 promptlab.py |
Prompt-iteration harness with stats | The sibling: prompt dev loop; evalkit is the evaluation harness |
| 03.10 fake clients / cassettes | Testing LLM code | Provides the call_model implementations (fakes, replays) evalkit consumes |
07.9 docs_qa/eval/ |
RAG-specific eval harness | A domain instance of the same pattern: dataset → pipeline → judges → report |
08A.14 evalharness.py |
Agent eval harness | Same seams plus trajectory graders and pass^k |
The pattern is consistent across the path: injectable model call, labelled cases, named scorers, aggregate report. evalkit is the module's shared implementation of it.
Part 7: Types of evals by task — the method map#
Reference
The same five-part anatomy (dataset + task + scorer + aggregation + report) covers every task type, but the scorers and datasets differ sharply. This map shows which methods apply where; each row links to the lesson that owns the depth. Read it as "what changes when the task changes".
| Task type | What "correct" looks like | Primary scorers | Dataset shape | Owned by |
|---|---|---|---|---|
| Classification / routing (triage, intent, moderation) | Right label from a fixed set | Exact match, per-class precision/recall/F1, confusion matrix | Labelled inputs, balanced across classes + edge cases | 10A.3 |
| Extraction / structuring (invoices, forms, entities) | Right fields with right values | Field-level precision/recall, schema validity, tolerance for formats | Documents + gold field values | 10A.3, 03.4 |
| Open generation (emails, replies, creative) | Fluent, on-task, on-brand, safe | LLM judges with rubrics, human review, pairwise preference | Prompts + reference outputs or rubrics | 10A.4, 10A.5 |
| Summarisation | Covers key points, no fabrication, right length | ROUGE/BLEU as tripwires, faithfulness judges, key-point recall | Source + reference summaries | 10A.3, 10A.6 |
| Question answering (closed-book) | Right answer, calibrated abstention | Exact/semantic match, abstention accuracy | Questions + gold answers + unanswerables | 10A.3, 10A.6 |
| RAG / grounded QA | Right answer from the corpus, cited, abstains when unanswerable | Retrieval metrics (recall@k, MRR, nDCG), faithfulness, citation precision, abstention | Questions with gold chunks + unanswerable/adversarial cases | 10A.6; retrieval side in 06.10, overview in 07.9 |
| Agents / tool use | Right end state via acceptable trajectory | State graders, tool-call accuracy, pass@k/pass^k, budget adherence, trajectory evals | Tasks with initial state + goal + graders | 10A.7; preview in 08A.14, Part 4 |
| Code generation | Code that passes tests / matches spec | Unit-test pass rate, pass@k, static checks | Problems + tests + reference solutions | 10A.7 |
| Multimodal (vision, speech, image gen, video) | Right answer about/across media | Modality-specific metrics (WER, IoU, field metrics) + VLM judges | Labelled media with ground truth | 10A.7; per-modality detail in Module 09 and 09.10, Part 4 |
| Translation / localisation | Fluent, accurate, locale-appropriate | BLEU/chrF/comet as baselines, human preference, MQM-style error counts | Parallel texts + style guides | 10A.3 (overlap metrics), 10A.4 |
Three cross-cutting observations:
- The grader gets more expensive as the task gets more open-ended. Classification and extraction are mostly code; generation and tone need judges; "was the agent's plan good" needs judges and humans. Budget accordingly — the lifecycle in 5.1 sequences this.
- The dataset gets harder to build as the task gets more contextual. A classification label is cheap; a faithful-and-cited RAG answer needs corpus-grounded generation plus validation (10A.2 covers generating eval questions from chunks and the leakage caveats).
- Every row above still needs the same hygiene: versioned data, dev/test splits, slices, PII scrubbing — 10A.2 owns it once for all task types.
Part 8: Reading claims and leaderboards critically#
Deep-dive
You will be asked to justify model and tool choices with numbers: "GPT-X scores higher on benchmark Y", "our eval platform has 10× better judges". 10A.10 owns benchmark literacy in depth; the critical habits start here, because every claim you repeat unverified becomes someone else's eval debt.
When you see a benchmark score:
- Who ran it, on what data, with what prompt? Self-reported scores on a vendor's own harness are marketing until reproduced. Ask for the harness, the prompt template and the confidence interval.
- Is the benchmark saturated or contaminated? A 99% score on a benchmark the model may have seen in training measures memorisation as much as capability (02.9, Part 7 covers contamination and saturation, with a table of the main benchmarks and their status; 10A.10 covers reading leaderboards).
- Does it measure your task? A leaderboard win on academic reasoning says little about your invoice extractor. Benchmarks shortlist models; only a product eval decides (10A.10).
- What did they not measure? Cost, latency, refusal rate, variance across runs — the dimensions your users actually feel (02.9 covers the model-selection criteria).
When you see a vendor eval claim ("our judge correlates 0.9 with humans", "97% accuracy on extraction"):
- Against whose labels? Judge-human agreement is only meaningful on your domain, your rubric, your label distribution — a judge calibrated on general text may be noise on legal clauses.
- On what sample? A 50-example agreement study has a wide interval; ask for the n and the methodology.
- Is the eval open? Tools that keep datasets and results in open formats (JSONL, CSV) keep you portable; ones that lock your eval history into a proprietary store make switching costly. 10A.10 surveys the landscape as of November 2026 — including the notable churn: OpenAI's hosted Evals platform is being deprecated (read-only from 31 October 2026, shutdown scheduled 30 November 2026; source, verified November 2026), which is a reminder that eval tooling is itself volatile — own your datasets and results. OpenAI's own migration cookbook now points Evals users to promptfoo for continuing eval workflows (source, verified November 2026) — the same tool surveyed in 10A.10.
Part 9: Putting it together — decision table and failure gallery#
Reference
9.1 Decision table#
| Situation | Do this | Not this |
|---|---|---|
| Just started a feature, no eval yet | ~20 hand-labelled examples + human review of outputs | Build a 500-case synthetic dataset before seeing real failures |
| Prompt seems "mostly fine" | Run the golden set before and after each change; one change at a time | Judge by reading five outputs and calling it done |
| Failure is checkable by code (format, fields, length) | Write a deterministic scorer — free, fast, reliable | Use an LLM judge for something a regex can check |
| Failure needs judgement (tone, helpfulness, faithfulness) | LLM judge with a rubric, calibrated against human labels | A generic "quality" score with no rubric |
| High-stakes dimension (safety, PII, citations) | Hard gate: any failure blocks | Average it into a soft score |
| Comparing two prompt/model versions | Paired comparison on the same dataset + repeats; look at slices, not just the mean | Compare against a remembered number or different data |
| Score dropped after a change | Check slices first — did one slice collapse or did everything drift? | Immediately revert or immediately "fix" the prompt |
| Eval passes but users complain | Your eval measures the wrong thing — error analysis on real failures, add them to the dataset | Assume the eval is broken and delete it |
| Rare but catastrophic failure mode | Dedicated adversarial/edge slice + hard gate, even if it costs eval time | Hope volume averages it out |
| Need to pick a model | Shortlist on public benchmarks → product eval on your data → check cost/latency/refusals | Pick the leaderboard winner |
9.2 Failure gallery#
The five canonical ways evals go wrong — each one observed in real teams, each one with a named antidote:
| Failure | What it looks like | Why it happens | Antidote |
|---|---|---|---|
| Evaluating on the training/prompt-dev examples | Eval score is great; production is not | The eval set is the dev set — the system was tuned against it | Held-out test set, frozen at decision time (10A.2) |
| Optimising a metric not the goal | "Helpfulness" up, resolutions down | The metric doesn't track the product goal | Metric hierarchy: north-star tied to user outcome (3.5) |
| Averaging away failures | Mean score fine; a slice is broken | One bad slice hidden in the aggregate | Per-slice breakdowns + worst-slice floors (10A.3, 10A.8) |
| No baseline | "The new prompt scores 0.87" — compared to what? | No recorded previous run to diff against | Versioned eval history: every run stored, every change compared to the last (10A.8) |
| Single-run noise | "v2 is better" declared on one run each | Non-determinism treated as signal | repeats, confidence intervals, paired comparisons (10A.2, 10A.5) |
Honourable mentions: eval theatre (a big eval nobody reads the output of), teaching to the test (adding eval cases to prompts until the score is perfect — the dataset becomes part of the prompt), and judge capture (tuning the rubric until the judge flatters the system — 10A.5 covers judge validation).
9.3 What this means for you#
If you take one thing from this lesson, take the loop: product goal → measurable criteria → labelled dataset → cheapest sufficient scorer → report with slices and failures → error analysis → one change → repeat. Everything else in Module 10A is a deeper version of one stage of that loop. The harness you just ran is the smallest working instance; the rest of the module grows it — datasets in 10A.2, deterministic scorers in 10A.3, judges in 10A.4–10A.5, domain evals in 10A.6–10A.7, CI in 10A.8, online in 10A.9, and the full landscape in 10A.10.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A high benchmark score means the model is good for our task." | Benchmarks measure the model on a standard task, not your feature on your data. Only a product eval predicts production quality. |
| "If the demo works, it works." | A demo is a sample of one from a distribution. Capability ≠ reliability — the same input can pass once and fail the next run. |
| "Evals are just unit tests for prompts." | Tests check code correctness deterministically; evals measure probabilistic output quality against labelled data. Different ground truth, different statistics, different failure modes. |
| "One eval score tells you if the system is good." | A single mean hides slices, failure modes and error asymmetry. You need per-slice breakdowns, hard gates on must-pass criteria, and the failing examples themselves. |
| "LLM-as-judge is a shortcut that replaces human eval." | A judge is a measurement instrument with its own error — it must be calibrated against human labels before its scores mean anything (10A.5). |
| "More eval data is always better." | Past a point, labelling effort is better spent on coverage (hard, rare, adversarial cases) than volume. A small set of well-chosen cases often catches regressions that a much larger random sample misses. |
| "Temperature 0 / a fixed seed makes evals deterministic." | Through provider APIs, temperature-0 is still non-deterministic (batching, serving changes). Design for variance: repeats, intervals, gates — not promises of identical output. |
| "The eval set can live in the prompt." | Putting eval examples in the prompt (few-shot) contaminates the measurement — the system is being tested on what it was shown. Keep eval data out of prompts. |
| "A passing eval means the feature is safe to ship." | Evals measure what they measure. Safety, privacy and abuse cases need their own dedicated slices and gates — and Module 12 owns the security side. |
| "Once the eval passes, you're done." | The eval is a living artefact: production failures feed it, model updates re-run it, slices evolve. Evaluation is a loop, not a milestone. |
| "Good user-facing metrics mean the system is fine." | User-facing numbers can look great while latency, cost or error rates quietly breach budgets — the two metric families fail independently, which is why guardrails exist. |
Key takeaways#
- LLM systems fail silently and probabilistically. "Does it work?" is the wrong question; "how often, how badly, on which inputs" is the right one — and only measurement answers it.
- Vibe checks don't scale because they are unrepeatable, unshared and uncomparable. An eval is a vibe check made repeatable.
- An eval = dataset + task + scorer(s) + aggregation + report. Every tool is a packaging of those five parts.
- Define success before measuring it: product goal → measurable criteria → threshold. Hard requirements become gates; soft scores become trends.
- Metric hierarchy: one north-star tied to user outcome, guardrails that must not regress, diagnostics that explain movement.
- Two metric families: user-facing metrics (what the user experiences → north-star candidates) vs system-level metrics (latency, cost, error rate, parse rate → guardrails). Each can look healthy while the other is broken, so a scorecard needs both.
- Error analysis first: read real failures, open-code them into a taxonomy, turn categories into targeted evals. Generic metrics mislead because they don't match your failure modes.
- The lifecycle is a flywheel: manual review → dataset → code graders → judges → CI gate → online monitoring → back to the dataset. Size the eval to the stage.
- Keep two kinds of eval apart: capability evals start low and show progress; regression evals stay near 100% and gate merges. Graduate cases from one to the other, and treat a saturated eval as a prompt to write harder cases.
- Read until saturated, then stop: at least 30 traces yourself from a pool of about 100, until new traces stop revealing new failure modes. Prefer binary verdicts per failure mode to 1–5 scores.
- Evals are one layer, not the whole defence: offline evals, monitoring, A/B tests, user feedback and transcript review each catch what the others miss.
evalkitis the module's shared harness:Example/Dataset,Scorerprotocol and theFunctionScoreradapter,run_eval(), JSONL results, summary + slices — pure stdlib, injectablecall_model, fakes for offline work.- Match the method to the task: code graders for checkable qualities, judges (calibrated) for judgement calls, humans for gold-standard spot checks.
- Read claims critically: benchmarks shortlist models; only your product eval decides. Own your datasets and results because tooling is volatile (OpenAI's hosted Evals platform is being deprecated as of November 2026).
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Evaluation / eval | A structured, repeatable measurement of system quality: dataset + task + scorer(s) + aggregation + report |
| Eval-driven development | Writing the eval alongside the system and letting it adjudicate every change |
| Benchmark | A public, standardised eval for comparing models across teams (not your product eval) |
| Product eval / task eval | An eval built for your task, your users, your data distribution |
| Metric | A computed number over outputs (accuracy, F1, recall@k, latency) |
| Grader | The broader verdict-producer: a metric, code check, judge or human |
| LLM-as-judge | A model used as a grader for qualities code can't check |
| Rubric | Written criteria (with anchored examples) that a judge or human grades against |
| Golden set | The labelled eval set treated as ground truth |
| Offline eval | Evaluation on a fixed dataset, before/without production traffic |
| Online eval | Evaluation on live production traffic: feedback, sampled scoring, drift |
| Pass rate | Fraction of examples/runs passing all gates |
| Regression | A previously-passing case failing after a change |
| Flake / flaky eval | An eval failing non-deterministically for infrastructure reasons, not quality |
| Error analysis | Reading actual failures and coding them into categories |
| Failure taxonomy | The categorised set of recurring failure modes, built from real outputs |
| Open coding | Letting failure categories emerge from the data rather than imposing them top-down |
| Hard requirement / gate | A must-pass criterion; any failure blocks, no averaging |
| Soft score | A graded measure where degree matters; aggregates into means/trends |
| North-star metric | The one number tracking the product goal — almost always user-facing |
| Guardrail metric | A must-not-regress number (safety, cost, latency) — mostly system-level |
| User-facing metric / system-level metric | Measures what the user experiences (success, correctness, satisfaction) / measures the machinery (latency, cost, error rate, parse rate) — a scorecard needs both |
| Diagnostic metric | Per-slice/per-stage numbers that explain movement in the north star |
| False positive / false negative | Saying yes when truth is no / saying no when truth is yes — costs are asymmetric |
| Abstention accuracy | Correctness of knowing when not to answer |
| Eval harness | The code that runs dataset × task × scorers and reports |
evalkit |
This module's shared eval package (core.py here; dataset/scorers/judges/runner in later lessons) |
Example / Score / Scorer / FunctionScorer / Row / EvalReport |
evalkit's core types: a case, a verdict, the scorer protocol, the adapter that wraps a plain function as a scorer, a scored run, the aggregate |
call_model seam |
The injectable prompt→output callable that lets the harness run fakes, providers or replays |
Cache key (model, run, prompt) |
The deterministic hash that makes eval re-runs free without collapsing repeat-draw variance |
| Slice | A metadata-defined subgroup (intent, edge, language) for breakdown analysis |
| Eval flywheel | The loop where production failures become new labelled eval cases |
| CI gate | An eval wired into continuous integration that blocks merges below threshold |
| Vibe check | Unrepeatable manual assessment — the thing evals replace |
| Composite score | A single averaged quality number — useful for dashboards, dangerous for decisions |
| Goodhart's law | When a measure becomes a target it ceases to be a good measure — why guardrails exist |
| Jagged frontier | The observation that LLM capability is uneven: hard tasks pass, easy-looking ones fail |
| Axial coding | The second pass of error analysis: grouping free-text failure notes into a small set of categories |
| Theoretical saturation | The point in error analysis where new traces stop revealing new failure modes or changing existing categories |
| Capability eval / regression eval | An eval that starts at a low pass rate and measures what the system can't do yet / one that stays near 100% and guards what already works |
| Graduation | Moving cases from a capability eval into the regression suite once they pass consistently |
| Eval saturation | An eval the system already passes completely, so it no longer shows progress |
| Swiss-cheese model | Layering several imperfect quality checks (evals, monitoring, A/B tests, feedback, transcript review) so each catches what the others miss |
All terms are also collected in the glossary.
Exercises#
All exercises run without API keys — the harness is pure stdlib and the fake model is deterministic.
-
Run the harness. Save
evalkit/core.pyandtriage_eval.pyas shown, runpython3 triage_eval.pyfrom the project root, and confirm you get the output shown in 6.3. Then opentriage_results.jsonland inspect one row: which fields does it carry? -
Grow the dataset to 20. Add eight more
Examplerows toEXAMPLEScovering failure modes from your own experience: a ticket in another language, a ticket that's only an attachment reference, a ticket with a legal threat, a very long ticket, a ticket asking for a human agent, a duplicate-looking ticket, a ticket with mixed billing+technical intent, and one adversarial ticket containing "ignore your instructions". Give each areferenceandmetadataslices. Run the eval — does the pass rate move? Which slice now looks worst? -
Add a third scorer. Write
summary_keyword_scorerthat checks the summary contains at least one content word from the ticket (e.g. a noun like "charge", "login", "order"). Wire it intoSCORERSand re-run. Which examples newly fail, and is that a scorer bug or a real model weakness? -
Break the format on purpose. Change
FakeTriageModelso T05 returns markdown-fenced JSON (```json ... ```). Run and observe: doesformat_scorerstill pass it? (Hint: check_parse_json— it strips fences.) Now make T06 return two JSON objects concatenated. What happens? -
Demonstrate the cache honestly. Run
run_evaltwice in one script withcache={}shared: firstrepeats=2, thenrepeats=1. Printmodel.callsbefore/after each. Explain why the second run made zero calls and why that's correct behaviour for a cache — and when it would be wrong (hint: think about what happens if you change the prompt template between runs). -
Slice analysis. Using the JSONL output, compute per-
intentpass rates yourself (a few lines of Python over the file). Does it matchslice_breakdown()? Why does the report compute slices over per-example pass rates rather than raw rows? -
Error analysis practicum. Take the two failing examples (T02, T11) and write a one-line failure-taxonomy entry for each in the style of 4.2: a code (F1, F2...), the failure in plain language, and which scorer caught it. Then propose the fix for each — is it a prompt change, a scorer change, or a dataset change?
-
Define success for a new feature. Pick a feature you haven't eval'd (a summariser, a classifier, an extraction). Write three measurable criteria in the style of 3.1: the product goal, the observable, the pass condition and threshold. Which would be a hard gate and which a soft score?
-
Read a claim critically. Find a public benchmark score or vendor eval claim (a model card, a leaderboard, a vendor blog). Apply the checklist in Part 8: who ran it, on what data, what prompt, is it saturated/contaminated, does it measure your task, what wasn't measured?
-
Design the lifecycle for your project. For a real or imagined LLM feature, write which lifecycle stage (5.1) it's at and what "enough eval" looks like for it (5.2). What's the first failure taxonomy you'd build from real outputs?
-
Split capability from regression. Add
"suite": "regression"to the metadata of the ten examples the fake model passes and"suite": "capability"to T02 and T11. Re-run and read thesuite=lines of the slice table: what are the two pass rates? Which one would you gate a merge on, and which would you only report? Then changeFakeTriageModelso T02 returns the right labels and decide whether T02 should graduate.
Check yourself#
- Why do LLM systems fail "silently" in a way traditional software doesn't?LLM failures are fluent and probabilistic — a wrong answer looks exactly like a right one, arrives with HTTP 200, and the same input can pass once and fail the next run. Nothing in the API response says "this is wrong"; you must detect failures yourself.
- What's the difference between capability and reliability, and why does it matter for evals?Capability is "can it do the task once"; reliability is "does it do it every time users need it". A demo shows capability; only repeated measurement shows reliability.
- Name three reasons a "vibe check" (a developer eyeballing a few outputs) doesn't scale.Non-determinism (same prompt, different answers), prompt/model/data drift (the system changes under you), and long-tail inputs your test prompts never covered — plus the check is unrepeatable and unshared.
- What are the five components of an eval?Dataset, task (system under test), scorer(s), aggregation, report.
- What's the difference between a benchmark and a product eval?A benchmark is a public standardised eval for comparing models across teams; a product eval is built for your task, users and data — only the latter predicts whether your feature works.
- What's the difference between a metric and a grader?A metric is a computed number (accuracy, F1); a grader is the broader thing producing a verdict — a metric, code check, judge or human. Metrics feed graders.
- Why is "helpfulness" a dangerous metric to optimise?It doesn't match your failure modes, hides the distribution in a mean, and can't be acted on — "helpfulness dropped" doesn't say what to fix.
- What's a hard requirement vs a soft score, and why does the distinction matter?Hard requirements are must-pass gates (any failure blocks); soft scores are graded measures that aggregate. Conflating them lets catastrophic failures hide inside averages.
- A fraud-detection feature reports "accuracy 97%" on a test set in which only 3% of the transactions are fraud. Why might that number be misleading, and which metrics should the eval report instead?With only 3% fraud, a system that flags nothing already scores 97% accuracy while catching no fraud at all. Accuracy also treats both error types equally, but a missed fraud case costs far more than a false alarm. Report recall on fraud (how many of the fraud cases were caught) and the false-positive rate or precision separately, with the cost ratio in mind.
- What is the metric hierarchy, and what are its three tiers?North-star (the one number tracking the product goal), guardrail (must-not-regress numbers like safety/cost/latency), diagnostic (per-slice/per-stage numbers explaining movement).
- Why does error analysis come before building eval metrics?Because metrics built without knowing the failure modes measure the wrong thing — generic metrics miss the failures users actually hit. Error analysis produces the taxonomy that targeted evals need.
- What's a failure taxonomy, and how do you build one?A categorised set of recurring failure modes built by reading real outputs and open-coding them — it tells you which scorers and fixes to build.
- What's the difference between offline and online evaluation?Offline eval runs on a fixed dataset before production; online eval measures live traffic (feedback, sampled scoring, drift). They complement each other via the flywheel.
- In
evalkit, what doExample.referenceandExample.metadataeach do?referenceis ground truth for scorers that need it (a label/answer);metadatacarries slice tags for breakdown analysis. - Why does
run_eval's cache key include the run index?Because with repeats > 1 each run is a separate draw — keying on (model, prompt) alone would collapse the draws and hide the variance repeats exist to measure. Across eval runs the keys still align so re-runs are free. - What are the lifecycle stages of evaluation, in order?Manual review → first dataset → code graders → judges → CI gate → online monitoring → (flywheel back to dataset).
- What's the difference between a flaky eval and a real regression?A flaky eval fails non-deterministically for infrastructure reasons (timeouts, rate limits, provider errors); a regression is a real quality drop on a previously-passing case. Flakes must be distinguished from regressions or CI gates become noise.
- When should you use an LLM judge vs a deterministic scorer?Code when the quality is checkable (format, fields, exact match, length); a calibrated judge when it needs judgement (tone, helpfulness, faithfulness); humans for gold-standard spot checks and judge calibration.
- What's the difference between user-facing and system-level metrics, and why does a scorecard need both?User-facing metrics measure what the user experiences — task success, correctness, satisfaction — and feed the north-star. System-level metrics measure the machinery — latency, cost, error rate, parse rate — and feed the guardrails. A system can be fast and cheap while answering badly, or accurate but too slow to use; each family catches what the other misses.
- What is theoretical saturation in error analysis, and roughly how many traces should you read before you can claim it?The point where new traces stop revealing new failure modes or changing the existing categories. A common convention (Husain and Shankar's FAQ) is to read at least 30 traces yourself from a pool of about 100 diverse ones and to continue past that while you are still learning; saturation is judged on the traffic you sampled, so it resets when traffic changes.
- What is the difference between a capability eval and a regression eval, and which one should block a merge?A capability eval starts at a low pass rate and measures what the system cannot do yet; a regression eval stays near 100% and guards what already works. Only the regression eval should block a merge. Capability cases graduate into the regression suite once they pass consistently.
- What does the Swiss-cheese model say about relying on an offline eval suite alone?Every layer has holes: offline evals miss inputs that are not in the dataset, monitoring misses quality problems that don't move a metric, user feedback is a biased sample. A passing suite is evidence, not proof, and failures found in other layers must flow back into the dataset.
Further resources#
- OpenAI, Evaluation best practices and Working with evals — vendor guidance on eval-driven development, task-specific datasets and the anti-patterns (generic metrics, biased design, vibe-based evals). Note: OpenAI's hosted Evals platform is being deprecated (read-only 31 Oct 2026, shutdown 30 Nov 2026); the guidance remains current.
- Hamel Husain, Your AI Product Needs Evals (March 2024) — the canonical practitioner account of the workflow in 4.1: replace vibe checks with product evals built from trace inspection and error analysis.
- Hamel Husain and Shreya Shankar, LLM Evals: Everything You Need to Know (an FAQ, updated September 2026) — the up-to-date practitioner reference on error analysis, binary labels, how many traces to read and when to stop (4.5).
- Anthropic, Demystifying evals for AI agents (January 2026) — the task, trial, grader, transcript and outcome vocabulary, capability versus regression evals and the Swiss-cheese view of quality layers (5.5, 5.6).
- Anthropic, Prompt engineering overview — the prerequisite ordering this lesson formalises: success criteria → empirical tests → prompt.
- Google Cloud, Gen AI evaluation service — how a major provider frames pointwise/pairwise model-based metrics vs computation-based metrics.
- UK AI Security Institute / Meridian Labs, Inspect — the open-source eval framework (
pip install inspect-ai) whose dataset/solver/scorer vocabulary mirrors this lesson's anatomy; 200+ pre-built evals. - promptfoo — the most widely used open-source eval/red-team CLI (MIT licence; acquired by OpenAI in March 2026 and remaining open source). Surveyed properly in 10A.10.
- 04.9 — Iterating, Debugging and Porting Prompts — the prompt-iteration sibling of this lesson's harness: dev sets,
promptlab.py, failure taxonomy, regression suites. - 04.1 — Anatomy of a Good Prompt — the minimal test loop (
triage_loop.py) this lesson'sevalkitgrows from. - 03.10 — Logging, Debugging and Testing LLM Code — the testing toolbox (fakes, cassettes, contract tests) that provides
call_modelimplementations. - 07.9 — Evaluating RAG and 08A.14 — Reliable, Safe and Observable Agents — domain-specific eval harnesses (RAG and agents) that apply this lesson's anatomy.
- 02.10 — Limitations and Failure Modes — the failure-mode catalogue that error analysis (Part 4) categorises.
← Module 09: Voice & Multimodal Apps | Module 10A overview | 10A.2 — Building Evaluation Datasets →