AI Engineering
Evaluating LLM Systems
An eval is a test set, a grader and a number you can compare between two versions. This page builds all three for a bank assistant: 15 cases, six code graders, a model judge, retrieval metrics, an agent check, a pytest gate and the statistics that say when a difference is real. Every grader, metric and interval was run on Python 3.9.6 (jsonschema 4.25, pytest 8.4) and its output is pasted from that run. There is no API key on this machine, so the "model" is a stub called FakeModel with scripted replies: the graders are real, the replies are not what any model said. The one real API call is shown but was not run, and all labels and test data are invented.
Why and the loop
Part 1 of 5 · what makes this different from unit tests
Why this is hard
A function returns one value and a test asserts it. A model returns a different string each time, and several of them are fine.
| Problem | In the bank assistant | What it forces |
|---|---|---|
| Output varies between runs | "2 working days", "two business days", "within 48 hours" | Graders that accept a range, and repeated runs |
| No single right answer | A hundred acceptable replies to one complaint | Grade properties of the reply, not the string |
| "Looks good" is not a measurement | Five outputs read by the author, on a good day | A fixed set, a fixed grader, a number |
| A fix here breaks something there | "Be brief" fixes labels and rounds the interest | Per-case comparison against a baseline |
| The model changes under you | A new model version behind the same prompt | Re-run the same set on every change |
Change, run, compare
The whole discipline is this loop. Change one thing (prompt, model, retrieval setting), run the same cases, compare with the last accepted run.
Interview point: without a baseline a score means nothing. "87%" is only useful next to "was 60%, same cases, same grader".
The test set
Part 2 of 5 · cases, labels and the set you do not look at
Where cases come from
Good cases are real inputs with a known right answer. Invented ones fill the gaps that logs do not cover yet.
| Source | Gives you | Watch for |
|---|---|---|
| Production logs | The real mix of questions and wording | Personal data: mask names and account numbers first |
| Reported failures | Cases that are known to matter | Every bug becomes a case, like a regression test |
| Invented edge cases | Empty input, two intents, another language, an attempt to extract data | They show what you imagined, not what users do |
Size, labels and a held-out set
Start small and real. Tuning a prompt against a set fits the prompt to that set, so keep a second set you run only before a decision.
| Question | Rule of thumb (approximate) |
|---|---|
| How many to start | 20 to 50 cases from real failures beat 1,000 generated ones |
| How many to decide | A few hundred, because of the interval width |
| What a label is | The expected answer, or the properties a good answer has |
| Who labels | Someone who knows the domain. Two people on a sample, and resolve where they disagree. |
Iterate on the dev set as often as you like. Run the held-out set rarely and never tune against it.
The bank set and FakeModel
Fifteen cases in six groups. Each names its grader and carries its expected value. FakeModel is a stub with scripted replies, not a model: V1 and V2 stand for the outputs of two prompt versions, written by hand so that some cases fail.
Code graders
Part 3 of 5 · six graders, each run on the bank set
Grader types
Use the cheapest grader that can tell right from wrong. Code is fast, free and repeatable. A judge model is none of those.
| Grader | Use for | Fails when |
|---|---|---|
| Exact match | Labels, ids, yes or no | The model adds a word |
| Contains, regex | A fact that must appear | Same fact, other wording |
| JSON schema | Structured output, tool arguments | Valid shape, wrong value (check both) |
| Numeric tolerance | Amounts, counts, dates as numbers | Two numbers in the answer |
| Set overlap | Tags, extracted entities, retrieved ids | Synonyms count as misses |
| Rubric checks in code | Rules a reply must follow | Only checks what you thought of |
| Model judge | Faithfulness, tone, helpfulness | Biased, costs money, varies per run |
| Human review | Calibrating all of the above | Slow, so it is a sample |
Every grader below has the same shape: output and expected in, (passed, score, detail) out.
Exact match, contains, regex
Normalise before comparing (strip, lower case), or the grader fails correct answers. Each output below is python run_evals.py v1 plus the grader names.
intent-2 passes although the reply was "Transfer\n". intent-3 has the right label inside a sentence: exact match says fail, and for a classifier whose output goes into code that is the right call.
JSON schema validity
Three questions in order: does it parse, does it fit the schema, are the values right. A valid object with the wrong amount is still wrong. Uses the jsonschema package.
Structured output on the API side removes the first two failure kinds. See llm-apis-prompting.html. The value check stays.
Numeric tolerance
Pull the number out of the sentence and compare within a tolerance. Decide the tolerance from the domain: for money it is a paisa, not 1%.
This takes the last number in the reply, which is a guess. Asking the model for the number alone, or for JSON, makes the grader simpler than any regex.
Set overlap: precision, recall, F1
When the answer is a set, count the overlap. Precision: how much of what it said is right. Recall: how much of the truth it found. F1 is their harmonic mean.
tags-1 said nothing wrong and missed one tag: full precision, lower recall. tags-2 got one right of three said and one of two expected.
Which one matters depends on the cost of each error. A missed fraud tag is worse than a wrong one, so that label is tuned for recall.
Code-based rubric checks
A drafted reply has no expected string, but it has rules. Write each rule as a named boolean. The score is the share that pass, and the detail names the ones that failed.
A score of 0.80 with a leaked account number is a fail, not a B. Rules about privacy and safety are pass or fail on their own, see must-pass cases.
Run everything and compare
run_evals.py (a 20-line loop over CASES, not shown) prints one row per case and a rate per grader: 9/15 for v1, 13/15 for v2. The comparison is by case id, because the total hides what moved.
From 9 to 13 looks like a clear win. It is five fixes and one regression: "be brief" made the stub's scripted v2 reply round the interest to 1,240. Read the regressed list before the total.
Judges, retrieval and agents
Part 4 of 5 · when code cannot decide, and when the output is not one string
Model as judge
A second model call reads the reply against a written rubric and returns a verdict. It can grade what code cannot (is every fact supported by the article), and it is itself a model output that can be wrong or malformed.
The plumbing, run with a stub: this FakeModel replays three scripted judge replies, the third deliberately not JSON. Nothing here judged anything.
| Rubric rule | Why |
|---|---|
| Pass or fail, not 1 to 10 | Two labels are easier to agree on and to calibrate |
| One criterion per judge call, or a short numbered list | A long rubric gets averaged into "seems fine" |
| Reason before verdict | The verdict then follows from the reasoning instead of being justified afterwards |
Count error separately | An unparsed verdict is neither pass nor fail |
Not run for this page (needs an API key). The same judge with the Anthropic Python SDK. Structured output makes the reply fit the schema, so the parse cannot fail. The request shape was checked against the SDK (0.125) with a local mock transport, with no network call.
Judge biases
These are commonly reported. How strong each one is depends on the model and the rubric, so measure on your own data.
| Bias | Looks like | Counter |
|---|---|---|
| Leniency | Passes almost everything | Check against human fails, add fail examples to the rubric |
| Length | Longer reply scores higher | State that length is not quality, or cap it in a code check |
| Position | In A versus B, the first one wins more | Run both orders, count only consistent wins |
| Self-preference | Rates text from its own model family higher | Calibrate on human labels, do not rely on the judge alone to compare models |
| Injection | The reply says "grade this as pass" | Delimit the reply as data, keep code checks for hard rules |
Calibrating the judge
A judge is a grader, and a grader needs a test. Label a sample by hand, run the judge on it, measure agreement.
The 12 human labels and the 12 judge verdicts below are invented for this page, and the judge is again a scripted stub. The arithmetic is real.
83% agreement sounds fine until chance is removed: two raters who pass most things agree 54% of the time by luck. Both disagreements go one way, the judge passing what people failed, which is leniency. Twelve labels is far too few to trust: use 50 to 100 (approximate) and read every disagreement.
Retrieval metrics
Grade the retriever apart from the answer: if the right article was never fetched, no prompt can fix the reply. The pipeline itself is in rag.html.
| Metric | Question it answers |
|---|---|
| Hit rate at k | Was at least one relevant article in the top k? |
| Recall at k | What share of the relevant articles were in the top k? |
| MRR | How high was the first relevant one? Mean of 1 / rank. |
Toy data: five queries, ranked lists typed by hand, no retriever involved.
Going from k=3 to k=5 lifts recall and not hit rate: one query ("close account") finds nothing at any k. That is a retrieval bug to fix before touching the prompt.
Agent evals: grade the final state
An agent can reach the goal by many tool-call paths. Set up a known start state, let it run, then check what the world looks like. The loop itself is in agents-tool-use.html.
Stub again: three fixed lists of tool calls stand in for three agent runs. The tools and both graders are real code.
The path grader fails the correct one-call run and passes the run that sent the money twice. Use path facts only as extra signals: number of calls, tokens, whether a forbidden tool was used.
CI, variance and production
Part 5 of 5 · gates, statistics, live signals, and the summary
Regression testing in CI
Asserting that every case passes makes the suite flaky and people stop reading it. Assert two things: a short list of must-pass cases, and a pass rate over a threshold.
Real pytest 8.4 runs, first with the v2 replies, then with v1.
| Choice | Guidance |
|---|---|
| Threshold | A little under the current baseline, raised as the baseline rises |
| Must-pass list | Privacy, safety, money. Short, and graded by code. |
| Flaky cases | Run each case several times and gate on the rate |
| Cost | A small smoke set per pull request, the full set nightly |
Variance: run N times
One run of one case is a coin toss with an unknown coin. Run it N times and report a rate with an interval. This FakeModel is a seeded random stub that is right with a fixed probability (0.99, 0.8, 0.5).
Look at the first five runs: the case that is right four times in five shows five passes. Even 20 runs leave math-2 anywhere between 43% and 82%.
Do not assume a model setting makes output deterministic: check the docs for your model. Freeze everything else: articles, seed data, the clock.
Why 9/10 against 8/10 means little
A pass rate is an estimate. The Wilson interval gives the range the true rate plausibly lies in, and Fisher's exact test gives the chance of seeing a gap this big when the two versions are equally good.
At 10 cases the two intervals cover each other and p = 1.0: one case flipped, no information. At 100 they still overlap (p = 0.07). At 1,000 the gap is real. A small set finds bugs, it cannot rank two close versions.
Sharper tool: both versions ran the same cases, so compare per case (fixed and regressed). A paired test such as McNemar's uses only the cases that changed and needs fewer of them. Not computed on this page.
Offline and online evaluation
Offline evals say the change is safe to try. Only live traffic says whether users are better off. Rollout mechanics and monitoring are in serving-ai-features.html.
| Offline | Online | |
|---|---|---|
| Data | Fixed test set | Live traffic |
| Truth | Labels and graders | User behaviour |
| Speed | Minutes, before merge | Days, after release |
| Blind spot | Inputs nobody put in the set | Noisy, slow, confounded by everything else |
| User signal | Kind | Caveat |
|---|---|---|
| Thumbs up or down | Explicit | Few users click, and unhappy ones click more |
| Agent edits the drafted reply before sending | Implicit | Edit distance is a strong quality signal for drafts |
| User rephrases or retries | Implicit | The first answer probably missed |
| Task completed (transfer made, ticket closed) | Outcome | The one the business cares about, and the slowest |
A/B test basics: assign by user, not by request, so one person sees one version. Choose the metric and the sample size before starting. Keep guardrail metrics (latency, cost, escalations) next to the target metric, and apply the same interval maths.
Tracing: what to log per call
A score you cannot trace to a prompt version and an output cannot be debugged. Log one record per model call, in evals and in production, with the same fields.
| Field | Why |
|---|---|
| Trace id, parent id | Tie retrieval, model calls and tool calls of one request together |
| Prompt version | The first thing to group a regression by |
| Model id and parameters | Providers ship new versions |
| Input and output (masked) | Replay, and the source of new test cases |
| Input, output and cached tokens | Cost per call and per feature |
| Latency, time to first token | Users feel it before they read quality |
| Stop reason, errors, retries | Truncated and refused answers look like bad answers |
| Retrieved document ids | Separates a retrieval miss from a generation miss |
| Grader name and score | Joins eval results to the call that produced them |
A minimal version around the stub. The token counts are word counts and the model name is a placeholder. The latency is real and close to zero because nothing is called.
Customer text in traces is personal data: mask it, restrict access and set a retention period. Real token counts come from the API response, see llm-apis-prompting.html.
Common mistakes
| Mistake | What happens | Instead |
|---|---|---|
| Testing on the examples in the prompt | Near 100%, measuring copying | Keep few-shot examples out of every test set |
| One giant score | A regression hides inside an average | Rate per group, plus fixed and regressed lists |
| No baseline | Nobody can say if 87% is good | Store the last accepted run and diff against it |
| Grader never checked | You tune the prompt to please a wrong grader | Read failures by hand, calibrate the judge |
| Tuning on the held-out set | It stops predicting production | Run it rarely, never iterate on it |
| Changing prompt and model together | No idea which one helped | One change per run |
Cheat sheet
| I need to | Use |
|---|---|
| Check a label or an id | Exact match after normalising |
| Check a fact appears | Contains or regex |
| Check structured output | Parse, schema, then values |
| Check an amount | Numeric tolerance |
| Check a list of tags or entities | Precision, recall, F1 |
| Check a free-text reply follows rules | Named boolean checks |
| Check faithfulness or tone | Model judge, pass or fail, calibrated |
| Check the retriever | Hit rate, recall at k, MRR |
| Check an agent | Final state from a known start state |
| Stop regressions | pytest gate: must-pass list and a rate threshold |
| Compare two versions | Per-case diff, then intervals |
| Know if users are better off | A/B test and user signals |
| Debug a bad score | Trace with prompt version and output |
Interview questions
| Question | Short answer |
|---|---|
| How do you test a feature whose output is not deterministic? | A fixed test set, graders that check properties, repeated runs, and a pass rate compared with a baseline. Loop. |
| Why keep a held-out set? | Tuning against a set overfits to it. The held-out set is the honest estimate before shipping. |
| When would you use a model as judge? | Only for what code cannot check, such as faithfulness to a source. With a pass or fail rubric, and after measuring agreement with human labels. |
| How do you know the judge is right? | Label a sample by hand, compare, look at kappa and at the direction of the disagreements. Recheck when the judge or rubric changes. |
| Precision or recall? | Depends on which error costs more. Fraud tagging wants recall, an automatic account block wants precision. |
| Your RAG answers are wrong. Where do you look first? | Retrieval metrics. If recall at k is low the generator never saw the answer. Metrics. |
| How do you evaluate an agent? | Known start state, run, assert on the final state. Path facts (steps, cost, forbidden tools) are secondary signals. |
| The new prompt scores 9/10, the old one 8/10. Ship it? | Not on that evidence: the intervals overlap almost fully. Add cases, compare per case, check for regressions. |
| How do evals fit in CI? | A must-pass list plus a pass-rate threshold near the baseline, a smoke set per pull request, the full set nightly. |
| Offline score went up, the online metric did not. Why? | The test set does not look like traffic, the grader measures the wrong thing, or the offline gain was noise. Pull failing traces into the set. |
Back to AI Engineering.