Skip to content

Lesson 26 of 40AI in production

Evals

Build eval sets from real cases, calibrate model judges, grade agents on what they did, and gate prompt and model changes in CI.

26 min read0/9 questions

You change one sentence in a prompt, try three examples, and they look better. You ship. A week later support tickets are being filed under the wrong team, because the change fixed the three cases you looked at and broke eleven you did not. Judging AI output by eye, on a handful of examples, is called "vibes", and it fails in exactly this way. An eval (short for evaluation) is a repeatable test for AI behaviour: a fixed set of inputs, the answers you expect, and an automatic way to score the results. Evals are to prompts what unit tests are to code.

Why vibes are not enough

Looking at outputs yourself is useful for spotting new problems. It is useless for proving you did not create old ones. Three reasons:

  • Small samples lie. Model output varies (the lesson How LLMs Work explains why). Three good answers can come from a prompt that fails one time in five.
  • You test what you just changed. You naturally try the cases you were fixing, not the ones that already worked.
  • You cannot compare. "It feels better" is not a number. You cannot tell whether version 7 beats version 6, or whether a cheaper model is good enough.

An eval gives you a score you can compare across prompt versions, models and settings. It turns "I think it is better" into "it passes 46 of 50 cases instead of 41, costs 30% less, and here are the 4 it still fails".

Build the eval set from real examples

The eval set (or dataset) is a list of cases. Each case has an input and something to check the output against: an exact expected answer, or a description of what a good answer must contain.

Where the cases come from matters more than how many there are:

  1. Real traffic. Pull actual inputs from your logs (with personal data removed). Real users write messier, shorter and stranger things than you would invent.
  2. Failures. Every bug report about the AI feature becomes a case. This is the most valuable source: it stops the same mistake coming back.
  3. Edge cases on purpose. Empty input, very long input, another language, an angry customer, two problems in one message.
  4. A balanced mix. If 70% of real emails are billing, do not let billing be 95% of your eval set, or you will not notice when bug reports break.

Start small: 20 to 50 good cases beat 1,000 sloppy ones. Label the expected answers carefully, ideally with a second person checking, because a wrong label makes the eval punish correct output. Keep the set in your repository next to the prompt, as a file like evals/triage.jsonl (one JSON object per line), and grow it every time you find a new failure.

Quick check
Which addition to an eval set is usually worth the most?
Need a nudge? A hint rules out a wrong answer.

Graders: how a case is scored

A grader takes the model's output and decides pass or fail (or gives a score). There are three kinds, from cheapest and most reliable to most flexible:

GraderHow it worksGood for
Exact matchOutput must equal the expected valueLabels, numbers, yes or no
Code checkA function tests the outputValid JSON, required fields, a regex, code that must pass tests
Model as judgeAnother model call scores the output against a rubricTone, helpfulness, summaries, anything open-ended

Use the cheapest grader that works. Exact match and code checks are fast, free and never change their minds. Before comparing, normalise both sides: trim spaces and lowercase, so " Bug" and "bug" count as the same where that is what you mean.

For open-ended output, like a drafted reply, there is no single right answer. Here you use a model as judge: a second prompt that reads the output and grades it against a rubric, a written list of what good looks like. A vague rubric ("is this a good reply?") gives noisy scores. A specific one works much better:

evals/reply-rubric.md
You are grading a customer support reply. Read the customer email and the reply.
 
Score each item 1 (yes) or 0 (no):
1. The reply addresses the customer's actual problem.
2. It does not promise a refund, a date or a feature.
3. It gives one concrete next step.
4. It is under 120 words.
 
First write one sentence of reasoning per item.
Then output only JSON: {"scores": [..4 numbers..], "pass": true or false}
"pass" is true only if every score is 1.

Asking for reasoning before the verdict usually makes judgments more careful, and asking for JSON lets your code read the result. Two cautions. A judge is itself a model, so it can be wrong: before trusting it, grade 20 or so outputs by hand and check the judge agrees with you on most of them. And item 4 does not need a model at all: counting words is a code check, so do it in code.

Match the pairs0/4 matched

Match each check to the cheapest grader that can do it.

Choose an item, then its match on the other side.

A tiny eval harness

An eval harness is the program that runs every case through the model, grades it, and reports. Here is one over a fake model, so it runs in your browser. Prompt v1 is the version in production. Someone wrote v2 to fix a case where a crash report mentioning a refund was filed as billing. Run it and read the per-case failures:

Python
import json # The eval set: real-looking inputs with the answer we expect.CASES = [ {"id": "c1", "email": "I was charged twice this month", "label": "billing"}, {"id": "c2", "email": "The export button does nothing", "label": "bug"}, {"id": "c3", "email": "How do I add a teammate?", "label": "question"}, {"id": "c4", "email": "Refund please, app crashes on login", "label": "bug"}, {"id": "c5", "email": "Can I pay by invoice?", "label": "billing"},] def fake_model(prompt_version, email): """Stands in for a real API call. Returns (json_text, input_tokens, output_tokens, ms).""" text = email.lower() if prompt_version == "v1": if "charged" in text or "refund" in text or "pay" in text: label = "billing" elif "crash" in text or "nothing" in text: label = "bug" else: label = "question" else: # v2: someone "improved" the prompt if "crash" in text or "nothing" in text: label = "bug" elif "charged" in text or "refund" in text: label = "billing" else: label = "Question" return json.dumps({"label": label}), 300 + len(email), 12, 400 + 7 * len(email) def grade(case, raw): """Code check first (valid JSON with a label), then exact match.""" try: got = json.loads(raw)["label"] except (ValueError, KeyError): return False, "invalid JSON" if got == case["label"]: return True, got return False, f"got {got!r}, want {case['label']!r}" def run(prompt_version): passed, tokens, ms, failures = 0, 0, [], [] for case in CASES: raw, tin, tout, latency = fake_model(prompt_version, case["email"]) ok, detail = grade(case, raw) passed += ok tokens += tin + tout ms.append(latency) if not ok: failures.append(f"{case['id']}: {detail}") print(f"{prompt_version}: {passed}/{len(CASES)} passed, {tokens} tokens, slowest {max(ms)} ms") for f in failures: print(" FAIL", f) return passed baseline = run("v1")candidate = run("v2")print("ship v2?", "yes" if candidate >= baseline else "no, it regressed")
Output
Press Run (⌘ Enter) to see what happens.

v2 did fix c4. It also broke two cases that used to pass: it lost the "pay" rule, and it capitalised Question. By eye, you would have tried c4, seen it work, and shipped. Two fixes to try: lowercase got in grade (is a capital Q really wrong for your app?), and add "pay" back to the v2 billing rule.

Predict the outputPython

What does this print?

print(" Question ".strip().lower() == "question")
Need a nudge? Hints walk you through it.

Regression testing prompts and models

A regression is something that used to work and now does not. The harness above is a regression test, and it earns its keep when you run it every time something changes:

  • Prompt changes. Every edit to a prompt file runs the eval before it merges. Put it in CI (continuous integration, the checks that run on each pull request) like your unit tests.
  • Model changes. A newer or cheaper model is a new dependency. Run the same eval on both and compare case by case before switching. This is how you find out whether a smaller model is good enough for a task, rather than guessing (the lesson on choosing a model covers the trade-off).
  • Settings changes. Effort level, temperature, max_tokens and tool definitions all change behaviour.

Compare per case, not only the total. Two versions can both score 40 of 50 while failing completely different cases. Decide in advance what blocks a release: for example "no case that passed before may fail, and the overall pass rate must not drop".

Model output varies between runs, so a single run can mislead on borderline cases. For important decisions, run each case a few times and look at the pass rate per case.

The eval loop
Change: prompt, model, settingChangeprompt, model, settingEval set: real casesEval setreal casesHarness: runs every caseHarnessruns every caseGraders: match, code, judgeGradersmatch, code, judgeReport: pass, cost, latencyReportpass, cost, latencyProd logs: new failuresProd logsnew failurestriggersinputsoutputsscoresadd cases

Any change to a prompt, model or setting triggers a run, ideally in CI.

1/5

Calibrating the judge against humans

"Grade 20 outputs by hand and check the judge agrees" is the right instinct. Done properly it is a small measurement, and it is the step teams skip most often. The process:

  1. Take a sample of real outputs, ideally 50 to 100, chosen at random plus a few known failures.
  2. Have a person (better, two people) grade them against the same rubric, without seeing the judge's verdict.
  3. Run the judge on the same outputs and compare.

Raw agreement (the share of items where judge and human match) is the obvious number, and it flatters the judge whenever most outputs pass. If 90% of replies are good, a judge that says "pass" to everything agrees 90% of the time and catches nothing. Two better views:

  • The confusion table. Count the four cells: both pass, both fail, judge passes what the human failed (the dangerous one), judge fails what the human passed (the noisy one). The judge's job is to catch failures, so the question that matters is: of the outputs a human failed, how many did the judge also fail?
  • Cohen's kappa, which corrects agreement for the agreement you would get by chance given each grader's pass rate. 1 is perfect, 0 is no better than chance. There is no universal bar, but many teams want roughly 0.6 or more before trusting a judge unsupervised, and treat anything under 0.4 as a rubric that needs work.
Python
# 20 replies graded by a human and by the LLM judge (1 = pass, 0 = fail).human = [1,1,1,0,1,1,0,1,1,1, 1,0,1,1,1,1,0,1,1,1]judge = [1,1,1,1,1,1,0,1,1,1, 1,1,1,1,1,1,0,1,1,1] n = len(human)agree = sum(h == j for h, j in zip(human, judge))both_pass = sum(h == 1 and j == 1 for h, j in zip(human, judge))both_fail = sum(h == 0 and j == 0 for h, j in zip(human, judge))judge_pass_human_fail = sum(h == 0 and j == 1 for h, j in zip(human, judge))judge_fail_human_pass = sum(h == 1 and j == 0 for h, j in zip(human, judge)) print(" human pass human fail")print(f"judge pass {both_pass:>10} {judge_pass_human_fail:>10}")print(f"judge fail {judge_fail_human_pass:>10} {both_fail:>10}") p_observed = agree / n# Agreement you would get by chance if both graded at their own pass rates.ph, pj = sum(human) / n, sum(judge) / np_chance = ph * pj + (1 - ph) * (1 - pj)kappa = (p_observed - p_chance) / (1 - p_chance) caught = both_fail / (both_fail + judge_pass_human_fail)print(f"\nraw agreement {p_observed:.0%}")print(f"chance agreement {p_chance:.0%}")print(f"Cohen's kappa {kappa:.2f}")print(f"real failures the judge caught: {both_fail} of {both_fail + judge_pass_human_fail} ({caught:.0%})")
Output
Press Run (⌘ Enter) to see what happens.

90% agreement sounds good. The table tells the real story: the judge caught only half the replies a human failed. Read those two misses, find what the rubric did not say, tighten it, and measure again. When it is good enough, freeze the judge: pin the exact model id (for example claude-sonnet-5-5, not an alias that moves), the rubric version and the settings, and re-run the calibration whenever any of them change. A judge is a dependency, and an upgraded judge model is a new grader whose scores are not comparable with the old ones.

Where humans disagree with each other, fix that first. If two people agree on only 70% of items, the rubric is ambiguous, and no judge will do better than the people who wrote it.

Predict the outputPython

What does this print?

human = [1, 1, 1, 1, 0]
judge = [1, 1, 1, 1, 1]
agree = sum(h == j for h, j in zip(human, judge)) / len(human)
caught = sum(h == 0 and j == 0 for h, j in zip(human, judge))
print(agree, caught)
Need a nudge? Hints walk you through it.

Pairwise comparison and position bias

Sometimes you do not need an absolute score, only to know which of two versions is better. A pairwise judge sees the same input with reply A and reply B and picks the better one. Models (and people) find this easier and more consistent than scoring 1 to 10, which is why many teams compare a candidate prompt against the production one this way.

Pairwise judges have a known flaw: position bias. They tend to favour the reply shown first (or, for some models, the one shown second), whatever it says. Two other biases are worth knowing: length bias (longer answers win even when they are padded) and self-preference (a model tends to rate text in its own style higher, so a judge from the same model family as the system under test is not neutral). The standard defence for position bias is to judge every pair twice with the order swapped, and count a win only when both orders agree:

Python
import random random.seed(7) def biased_judge(first, second): """Stands in for an LLM judge. Prefers the better reply, but leans to whichever it reads first.""" quality = {"A": 0.52, "B": 0.48} # A is only slightly better p_first = quality[first] / (quality[first] + quality[second]) + 0.15 # position bias return first if random.random() < p_first else second TRIALS = 200one_order = sum(biased_judge("A", "B") == "A" for _ in range(TRIALS))print(f"A always shown first: A wins {one_order}/{TRIALS}") wins = {"A": 0, "B": 0, "tie": 0}for _ in range(TRIALS): w1 = biased_judge("A", "B") w2 = biased_judge("B", "A") wins[w1 if w1 == w2 else "tie"] += 1print(f"both orders, count only consistent wins: {wins}")
Output
Press Run (⌘ Enter) to see what happens.

Shown first every time, A looks like a clear winner (142 of 200). With both orders, most comparisons are ties: the judge's opinion flipped with the order, which means it had no real preference. A is slightly ahead, which matches the small true difference. If more than about a third of your pairs flip, the two versions are close, or the rubric is too vague to separate them.

Quick check
A pairwise judge, always shown the new prompt's reply first, prefers it in 71% of cases. What should you do before believing it?
Need a nudge? A hint rules out a wrong answer.

Evaluating agents: trajectory and final state

An agent does not produce one output. It takes a series of actions, and the final message is the least reliable part to grade: "I've refunded the order" can be written by an agent that refunded the wrong order, refunded twice, or did nothing. Grade an agent on three things, in this order of trust:

  1. Final state. Inspect the world after the run. Is there exactly one refund row, for the right order and amount? Did the tests pass? Is the ticket closed? A state check is a code check, so it is cheap and does not drift. For this you run each case in a fresh sandbox: a seeded test database, a temporary repo, fake APIs that record what they were asked.
  2. Trajectory. Check the sequence of tool calls. Did the agent look up the order before refunding it? Did it ask for approval before an irreversible action? Did it ever call a tool it should not touch? Count steps and tokens too: an agent that solves the task in 40 tool calls when 6 would do is a cost and latency bug. Keep trajectory checks loose. Assert the things that must or must never happen, not one exact path, because there are often several good ones.
  3. Final message. Only now grade the reply text, often with a judge: is it accurate about what happened, and does it tell the user what they need to know?
evals/test_refund_agent.py
def grade_refund_case(run, db):
    calls = [c.name for c in run.tool_calls]
    refunds = db.execute("SELECT order_id, amount FROM refunds").fetchall()
    return {
        "state_ok": refunds == [("A-1042", 18.00)],              # exactly one, correct
        "looked_up_first": "get_order" in calls
            and calls.index("get_order") < calls.index("issue_refund"),
        "no_forbidden": "delete_customer" not in calls,
        "steps_ok": len(calls) <= 8,
    }

Agents are less consistent than single calls, because one different early choice changes everything after it. So run each case several times and report two numbers. pass@k is the chance that at least one of k attempts succeeds; it matters when a person or a test can pick the good attempt. pass^k (read "pass to the k") is the chance that all k attempts succeed; it matters for anything customer-facing, where every run has to work. An agent that succeeds 80% of the time per attempt has a pass@3 of over 99% but a pass^3 of about 51%. The lessons What Is an Agent? and Build an Agent cover the loop these graders inspect.

Quick check
Your support agent's eval grades only the final reply with an LLM judge, and it scores 95%. Which change most improves the eval?
Need a nudge? A hint rules out a wrong answer.

Eval gates in CI

Running evals in CI turns them from a report into a gate. The difficulty is that eval scores are noisy in a way unit tests are not, so a naive gate either blocks good changes or lets regressions through. What works:

  • Know your noise. With n cases, the uncertainty in a pass rate p is roughly sqrt(p * (1 - p) / n). At 90% on 50 cases that is about 4 points, so a 95% interval is roughly plus or minus 8 points. A drop from 90% to 88% on 50 cases is noise. Either add cases or do not gate on differences that small.
  • Gate on two things. An absolute floor ("pass rate at least 85%") and hard regressions: a case that passed on every run of the baseline and fails on every run of the candidate. Hard regressions are rarely noise, and they come with a case id someone can read.
  • Repeat borderline cases. Run each case 3 times (or more for important suites) and treat a case that passes some runs and fails others as flaky. Report flaky cases, do not block on them, and fix or rewrite them, the way you would quarantine a flaky unit test.
  • Run the right suite at the right time. A fast, cheap smoke set (deterministic graders, small model, 20 to 50 cases) on every pull request that touches prompts, tools or model config. The full suite, with judges and repeats, nightly and before a release. Trigger on file paths so a CSS change does not spend tokens.
  • Record everything a result depends on: dataset version, prompt version, model id, judge id and rubric version, settings. A score without these cannot be compared with anything.
Python
import math # Each case was run 3 times on the baseline and 3 times on the candidate.# 1 = pass, 0 = fail.baseline = { "c01": [1, 1, 1], "c02": [1, 1, 1], "c03": [1, 0, 1], "c04": [0, 0, 0], "c05": [1, 1, 1], "c06": [1, 1, 1], "c07": [0, 1, 0], "c08": [1, 1, 1],}candidate = { "c01": [1, 1, 1], "c02": [0, 0, 0], "c03": [1, 1, 0], "c04": [1, 1, 1], "c05": [1, 1, 1], "c06": [1, 1, 1], "c07": [1, 0, 0], "c08": [1, 1, 1],}MIN_PASS_RATE = 0.80SOLID = 1.0 # passed every runBROKEN = 0.0 # failed every run def rate(runs): return sum(runs) / len(runs) all_runs = [r for runs in candidate.values() for r in runs]p = sum(all_runs) / len(all_runs)se = math.sqrt(p * (1 - p) / len(candidate)) # per case, not per runprint(f"candidate pass rate {p:.0%} (about +/- {1.96 * se:.0%} with only {len(candidate)} cases)") regressions, flaky = [], []for cid in baseline: b, c = rate(baseline[cid]), rate(candidate[cid]) if b == SOLID and c == BROKEN: regressions.append(cid) elif 0 < c < 1: flaky.append(f"{cid} ({sum(candidate[cid])}/3)") print("hard regressions:", regressions or "none")print("flaky, report but do not block:", flaky)ok = p >= MIN_PASS_RATE and not regressionsprint("gate:", "PASS" if ok else "FAIL")
Output
Press Run (⌘ Enter) to see what happens.

The candidate fixed c04 but broke c02 on every run, and that hard regression fails the gate on its own. Notice the uncertainty line too: with 8 cases, a pass rate of 75% could plausibly be anywhere from about 45% up to 100%, which is a reminder that a tiny set can only catch big changes. A workflow for the smoke suite might look like this:

.github/workflows/evals.yml
name: evals
on:
  pull_request:
    paths: ["prompts/**", "src/ai/**", "evals/**"]
jobs:
  smoke:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: astral-sh/setup-uv@v6
      - run: uv run python -m evals.run --suite smoke --repeats 3 --out results.json
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
      - run: uv run python -m evals.gate results.json --min-pass 0.85 --baseline main

Here evals.run and evals.gate are your own scripts, like the harness above. Hosted eval tools and open-source frameworks (promptfoo, Braintrust, LangSmith, Inspect and others) provide the same runner, gate and report, and are worth it once you have several suites. Pin action and tool versions in a real repo. Keep the API key in CI secrets, and do not run eval jobs with secrets on pull requests from forks.

Quick check
Your 50-case eval drops from 90% to 88% on a pull request. No case that passed every baseline run now fails every run. What should the gate do?
Need a nudge? A hint rules out a wrong answer.

Versioning the eval set and feeding it from production

An eval set is code. It needs history, review and ownership like any other part of the system.

  • Version it in git next to the prompts, as JSONL with a stable id per case. A case's id never changes, even when its input or expected answer is corrected, so you can track one case across months of results. Record why each case exists ("source": "bug-4312") and when it was added.
  • Review label changes like code changes. Changing an expected answer is changing the definition of correct, and it should go through a pull request with a second person checking.
  • Store results with versions. Each run writes the dataset commit, prompt version and model id alongside the scores. Then "did we get worse?" has an answer, and you can tell a dataset change from a system change.
  • Keep a held-out set. If you tune a prompt against the same cases over and over, it learns them: the score rises while real quality does not. Keep a slice you look at only for release decisions, and add fresh cases to it over time.
  • Expect it to grow and age. Retire cases that test a feature you removed. Large sets with personal data need the same care as the logs they came from: remove or replace personal details before a case is committed, and keep raw production data out of the repo.

The flow from production is a loop, not a one-off. The lesson LLM Observability, Gateways and Ops covers how bad traces are found and graded online. The eval side of the loop is: a failure is reported or flagged, someone reproduces it from the trace, writes the expected answer, scrubs personal data, gives it an id and a source, and merges it. The next release cannot ship that bug again without the gate noticing. Teams that do this weekly end up with an eval set that mirrors their real traffic and their real history of mistakes, which no generated dataset can match.

Track cost and latency too

Quality is only one column. A prompt that passes one more case but doubles the tokens may not be worth it. Have your harness record, per version:

  • Tokens in and out, and therefore cost (price per million tokens times tokens).
  • Latency: not only the average, but the slow tail. Users notice the slowest 5% of requests, so track a high percentile such as p95 (95% of requests are faster than this).
  • Failure modes: refusals, truncations and invalid JSON, counted separately from wrong answers.

With all three you can make real trade-offs: "the small model passes 47 of 50 against 49 of 50, at a twentieth of the cost and half the latency. The two extra failures are rare edge cases, so we route those to the larger model."

Put it in order6 steps

Put the steps for changing a production prompt in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Your model-as-judge eval says 98% of drafted replies are good, but customers keep complaining. What should you check first?
Need a nudge? A hint rules out a wrong answer.
Key terms
eval
A repeatable test of AI behaviour: fixed inputs, expected results and an automatic grader.
eval set
The collection of test cases an eval runs, ideally drawn from real inputs and past failures.
grader
The code or model that scores an output: exact match, a code check, or a model judge.
model as judge
Using a model with a written rubric to grade open-ended outputs that code cannot check.
rubric
A specific list of criteria that define a good answer, used for consistent grading.
regression
Something that used to work and stops working after a change.
p95 latency
The response time that 95% of requests beat. It shows how slow the slow requests are.
Cohen's kappa
Agreement between two graders corrected for chance agreement: 1 is perfect, 0 is no better than chance.
position bias
A pairwise judge favouring the reply in one slot, usually the first, regardless of quality.
pass^k
The chance that all k attempts at a task succeed, the bar for agents that must work every time.
hard regression
A case that passed on every baseline run and fails on every candidate run: rarely noise.