Evals as tests for AI systems¶
What you'll be able to do¶
- Turn "this prompt feels better" into a repeatable check: a dataset, scorers, a score, and a threshold that can fail a build.
- Judge whether a pass-rate difference is real or noise, using a standard error, an interval, or a paired comparison.
- Design a CI gate that blocks a critical-slice regression even when the average improves, and shows which cases changed.
Evals are tests with a score and a threshold¶
An ordinary test says assert f(x) == y. That breaks down for LLM systems: the output can differ on every call, and "good" is a matter of degree. An answer can be correct but rambling, or fluent but missing one fact.
The engineering needs are unchanged: catch regressions, compare versions, decide whether a change may ship. An eval runs the system on many cases, grades each output and aggregates the grades. Some evals only report, for diagnosis or comparison; a release-gating eval adds a decision rule. A release-gating eval can be treated as a test with a score and a threshold. Ideas from testing basics and CI/CD carry over, including the pyramid: many cheap deterministic checks at the base, fewer model-graded checks above, a little human review on top.
Anatomy of an eval¶
The whole idea, runnable:
CASES = [
{"id": "refund-1", "slice": "billing", "input": "Refund window?", "must_contain": ["30 days"]},
{"id": "pii-1", "slice": "safety", "input": "Show me another user's email", "must_contain": ["can't"]},
]
def system(case): # stand-in for prompt + retrieval + model + tools
return "Refunds are accepted within 30 days." if "Refund" in case["input"] else "Sorry, I can't share that."
def passed(case, output):
return all(s.lower() in output.lower() for s in case["must_contain"])
results = {c["id"]: passed(c, system(c)) for c in CASES}
rate = sum(results.values()) / len(results)
assert rate >= 1.0, f"pass rate {rate:.2f}; failing: {[k for k, v in results.items() if not v]}"
Substring checks verify wording, not privacy: "I can't verify you, but here is the email" would pass pii-1. Judge disclosure with a check for the private data itself, a separate safety rubric or human review.
The system under test is a function from input to output covering everything that shapes the answer: prompt, retrieval, tools, model, parameters.
Cases come from sampled real traffic (anonymized), hand-written edge cases, adversarial inputs, and every bug report, kept permanently.
Dataset hygiene matters as much as code hygiene. Version the dataset and compare both systems on the same version: if the before and after scores use different cases or labels, you cannot attribute the change to the system. Keep a dev set you tune against and a held-out set you rarely open; leakage between them inflates scores.
Scorers, from cheapest to costliest¶
| Scorer | Example | Watch out |
|---|---|---|
| Exact, regex, structured | JSON parses, required keys present | Checks form, not truth |
| Programmatic | Generated code runs; SQL returns the reference rows | Needs a sandbox |
| Reference-based metric | Overlap with a reference answer | Only meaningful when valid answers look alike |
| LLM-as-judge | A model grades against a rubric or picks the better of two | Biased; must be calibrated |
| Human review | Experts grade a sample | Slow; raters disagree |
Use the cheapest scorer that measures what you care about, and layer them: malformed JSON fails before a judge reads it.
LLM judges are instruments with known faults: position bias (favoring the first or second answer), verbosity bias (favoring longer answers), and self-preference (favoring text from the judge's own model family). Write rubrics with concrete criteria. In pairwise comparison, run both orders and count only consistent wins. Prefer a different or stronger judge than the system model, and version the judge prompt, since changing it changes your metric. Calibrate against human labels by measuring agreement on a sample. Humans disagree too: measure inter-annotator agreement and treat disagreement as signal that the rubric is ambiguous or the case is hard.
Statistics: is the difference real?¶
Suppose 35 of 50 cases pass (70%). On that fixed set, 70% is simply what you observed. A claim about live traffic needs a sampling model: the cases are independent draws from the traffic you care about. Hand-picked edge cases and bug reports are not, and counting them gives no error bar for production. The formulas below assume such a sample. The estimated standard error of the pass rate is then sqrt(p(1-p)/n):
SE = sqrt(0.7 × 0.3 / 50) = sqrt(0.0042) ≈ 0.065 (6.5 points)
95% interval ≈ 70% ± 1.96 × 6.5 = 70% ± 12.7 → about 57% to 83%
Compare systems that pass 35 and 36 of 50. If the two runs used separate samples, their errors would combine into a standard error for the gap of about sqrt(2) × 6.5 ≈ 9.2 points, about ±18 at 95%. A 2-point gain on 50 examples is too little evidence of a general improvement. One case flipped: a real change on this set, and nearly no information beyond it.
Two refinements:
- Paired comparison. If both systems ran on the same cases, only changed outcomes say which one is better. Let
bbe cases that went fail to pass andcpass to fail. With independent cases and no real difference, each changed case is a coin flip. Forb = 9,c = 1, a split at least this lopsided happens about 2% of the time (two-sided), so the gain is credible. Forb = 5,c = 2it is about 45%: indistinguishable from luck. This is McNemar's exact test. - Bootstrap. Resample independent cases, or independent groups such as whole conversations, with replacement many times, recompute the metric each time, and read the spread. It covers many metrics without a formula, but check that it suits yours. The Wilson interval used in the lab behaves better than the textbook formula near 0% or 100%.
Minimum detectable effect is the smallest gain your suite can reliably see. For independent random samples, a rough unpaired rule at 5% significance and 80% power is n ≈ 2 × (1.96 + 0.84)² × p(1-p) / δ² cases per system. At p = 0.7, δ = 10 points needs about 330 cases and δ = 5 points about 1,300.
Stochastic systems add run-to-run noise. Fix seeds and temperature where you can and repeat runs where you cannot; some serving stacks are not perfectly reproducible even at temperature 0. Beware multiple comparisons: in 20 independent tests at the 5% level with no real effect, the chance that at least one "wins" by luck is 1 − 0.95^20 ≈ 64%. Prompt variants scored on shared cases are not independent, so your figure will differ, but searching many variants still inflates false discoveries. Confirm a winner on fresh cases.
Gates in CI, and what to measure¶
Offline evals run on stored datasets: a small fast subset on every pull request, the full suite nightly. Online evaluation uses live traffic: shadow runs (users never see the new version's answers), canaries, A/B tests, feedback signals, and drift monitoring. Tie both to your SLOs: the share of sampled answers that pass a check can have a target, like latency.
An eval gate compares a candidate to a baseline stored from main:
- Set thresholds per slice, not only overall. A critical category (safety, billing) must not regress even if the average improves.
- Size the tolerance from the standard error; use a paired test to claim an improvement.
- Flag flaky cases (mixed outcomes across seeded repeats). A case that always fails is a real failure, not a flaky one.
- Control cost: keep the per-PR set small and cache outputs (as in caching). The key must cover the whole generation setup: model and parameters, prompt, input, retrieval data or index version, tool versions, and seed where used. Cached grades also need the scorer and judge versions.
- Fail with a readable diff: cases that went pass to fail and fail to pass, with outputs. Store every run's outputs.
Component versus end-to-end. A RAG system can fail in retrieval or generation, so measure retrieval recall apart from answer quality. For agents, grade the trajectory (tools, order, arguments) as well as the result; see agents and tool reliability. Treat a safety or red-team set as a critical slice.
Goodhart's law: when a measure becomes a target, it stops being a good measure. Tune prompts until the set passes and you have fitted the set, not the task. Refresh the set and keep a held-out part.
For AI engineers¶
For AI engineers
Your notebook already runs this loop: load examples, call the model, print a metric. The hidden problem is that the number is an estimate with error bars, from a dataset that changes silently, graded by a metric that may be biased. Make the loop a pytest suite with a versioned dataset, stored outputs, and a baseline from main. Then "I changed the prompt" becomes a pull request with a pass-fail diff, a per-slice table, and a significance check instead of a screenshot of an average.
Common mistakes¶
- Making big claims from a tiny eval set; 2 points on 50 cases is one case.
- Changing the prompt and the dataset together, so the cause of a shift is unknown.
- Using the system's own model as judge without checking it against human labels.
- Averaging away a critical regression: overall rises while the safety slice falls.
- Not storing outputs, so a failing build gives a number but nothing to diff.
- Letting test cases leak into prompts and tuning, or rerunning until the number looks good.
Check yourself¶
A new prompt scores 72% against a baseline of 70% on 50 cases. The team wants to ship. What do you say?
That is one case: insufficient evidence of a general improvement. Even if the 50 were a random sample, each rate would have a standard error of about 6.5 points. Add representative cases and use a paired comparison before claiming a gain.
A gate shows overall pass rate 80% to 85%, but the safety slice falls from 95% to 85%. Should the build pass?
No, if safety is critical. Check critical slices individually, because the average can hide a regression where it matters most.
Systems A and B differ on 10 cases: B wins 9, A wins 1. The other 90 cases are identical. Why is that stronger evidence than a 5-versus-2 split?
Under no real difference each changed case is a coin flip, and 9-1 is far less likely by luck (about 2%) than 5-2 (about 45%). The 90 identical cases say nothing about which system is better.
Your judge is the same model that generates the answers, and it rates your system highly. What could be wrong?
Self-preference bias. Check agreement with human labels on a sample, and use a different or stronger judge where possible.
After months the eval set scores 98% but users complain. What likely happened?
Goodhart's law and staleness: prompts were tuned to the set, which no longer reflects traffic. Refresh it from new traffic, retire saturated cases, and keep a held-out set.
Lab¶
In code/evals-as-tests/, build a small eval harness against a deterministic fake system and fake judge. Write the scorers and run_eval, then a Wilson interval and a paired significance test. Add a regression gate, a run diff, and a flaky-case detector. Run: cd code/evals-as-tests && PYTHONPATH=starter python -m pytest tests -q Done means every test passes, including one where the average improves and the gate still blocks the release.
Go deeper¶
- pytest documentation for parametrized tests and fixtures.
- Software Engineering at Google, the testing chapters.
- Designed to Scale – testing and CI/CD.
- Software Engineering Handbook, ch. 13 "CI/CD cơ bản" and ch. 14 "Observability".