Learnings

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

Why and the loop

A function returns one value and a test asserts it. A model returns a different string each time, and several of them are fine.

ProblemIn the bank assistantWhat 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 answerA hundred acceptable replies to one complaintGrade properties of the reply, not the string
"Looks good" is not a measurementFive outputs read by the author, on a good dayA fixed set, a fixed grader, a number
A fix here breaks something there"Be brief" fixes labels and rounds the interestPer-case comparison against a baseline
The model changes under youA new model version behind the same promptRe-run the same set on every change

Change, run, compare

Why and the loop

The whole discipline is this loop. Change one thing (prompt, model, retrieval setting), run the same cases, compare with the last accepted run.

The test set grows from the failures each round finds.

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

The test set

Good cases are real inputs with a known right answer. Invented ones fill the gaps that logs do not cover yet.

Three sources, one labelling step, two sets.
SourceGives youWatch for
Production logsThe real mix of questions and wordingPersonal data: mask names and account numbers first
Reported failuresCases that are known to matterEvery bug becomes a case, like a regression test
Invented edge casesEmpty input, two intents, another language, an attempt to extract dataThey show what you imagined, not what users do

Size, labels and a held-out set

The test 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.

QuestionRule of thumb (approximate)
How many to start20 to 50 cases from real failures beat 1,000 generated ones
How many to decideA few hundred, because of the interval width
What a label isThe expected answer, or the properties a good answer has
Who labelsSomeone 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

The test set

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

Code graders

Use the cheapest grader that can tell right from wrong. Code is fast, free and repeatable. A judge model is none of those.

GraderUse forFails when
Exact matchLabels, ids, yes or noThe model adds a word
Contains, regexA fact that must appearSame fact, other wording
JSON schemaStructured output, tool argumentsValid shape, wrong value (check both)
Numeric toleranceAmounts, counts, dates as numbersTwo numbers in the answer
Set overlapTags, extracted entities, retrieved idsSynonyms count as misses
Rubric checks in codeRules a reply must followOnly checks what you thought of
Model judgeFaithfulness, tone, helpfulnessBiased, costs money, varies per run
Human reviewCalibrating all of the aboveSlow, so it is a sample
Go down only when the grader above cannot decide.

Every grader below has the same shape: output and expected in, (passed, score, detail) out.

Exact match, contains, regex

Code graders

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

Code graders

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

Code graders

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

Code graders

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

Code graders

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

Code graders

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

Judges, retrieval and agents

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 judge sees the source article, so it checks the reply against facts, not against its own memory.

The plumbing, run with a stub: this FakeModel replays three scripted judge replies, the third deliberately not JSON. Nothing here judged anything.

Rubric ruleWhy
Pass or fail, not 1 to 10Two labels are easier to agree on and to calibrate
One criterion per judge call, or a short numbered listA long rubric gets averaged into "seems fine"
Reason before verdictThe verdict then follows from the reasoning instead of being justified afterwards
Count error separatelyAn 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

Judges, retrieval and agents

These are commonly reported. How strong each one is depends on the model and the rubric, so measure on your own data.

BiasLooks likeCounter
LeniencyPasses almost everythingCheck against human fails, add fail examples to the rubric
LengthLonger reply scores higherState that length is not quality, or cap it in a code check
PositionIn A versus B, the first one wins moreRun both orders, count only consistent wins
Self-preferenceRates text from its own model family higherCalibrate on human labels, do not rely on the judge alone to compare models
InjectionThe reply says "grade this as pass"Delimit the reply as data, keep code checks for hard rules

Calibrating the judge

Judges, retrieval and agents

A judge is a grader, and a grader needs a test. Label a sample by hand, run the judge on it, measure agreement.

Recheck when the judge model, the rubric or the kind of traffic changes.

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

Judges, retrieval and agents

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.

MetricQuestion it answers
Hit rate at kWas at least one relevant article in the top k?
Recall at kWhat share of the relevant articles were in the top k?
MRRHow high was the first relevant one? Mean of 1 / rank.
First relevant at rank 2, so reciprocal rank is 0.5. Recall at 3 is one of two.

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

Judges, retrieval and agents

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.

Two different paths are both right. A plausible third one is wrong.

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

CI, variance and production

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.

Unit tests with mocked model calls run on every push. The eval suite calls the model, so it runs when prompts, model ids or retrieval settings change.

Real pytest 8.4 runs, first with the v2 replies, then with v1.

ChoiceGuidance
ThresholdA little under the current baseline, raised as the baseline rises
Must-pass listPrivacy, safety, money. Short, and graded by code.
Flaky casesRun each case several times and gate on the rate
CostA small smoke set per pull request, the full set nightly

Variance: run N times

CI, variance and production

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

CI, variance and production

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

CI, variance and production

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.

Production failures flow back into the test set.
OfflineOnline
DataFixed test setLive traffic
TruthLabels and gradersUser behaviour
SpeedMinutes, before mergeDays, after release
Blind spotInputs nobody put in the setNoisy, slow, confounded by everything else
User signalKindCaveat
Thumbs up or downExplicitFew users click, and unhappy ones click more
Agent edits the drafted reply before sendingImplicitEdit distance is a strong quality signal for drafts
User rephrases or retriesImplicitThe first answer probably missed
Task completed (transfer made, ticket closed)OutcomeThe 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

CI, variance and production

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.

FieldWhy
Trace id, parent idTie retrieval, model calls and tool calls of one request together
Prompt versionThe first thing to group a regression by
Model id and parametersProviders ship new versions
Input and output (masked)Replay, and the source of new test cases
Input, output and cached tokensCost per call and per feature
Latency, time to first tokenUsers feel it before they read quality
Stop reason, errors, retriesTruncated and refused answers look like bad answers
Retrieved document idsSeparates a retrieval miss from a generation miss
Grader name and scoreJoins 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

CI, variance and production

MistakeWhat happensInstead
Testing on the examples in the promptNear 100%, measuring copyingKeep few-shot examples out of every test set
One giant scoreA regression hides inside an averageRate per group, plus fixed and regressed lists
No baselineNobody can say if 87% is goodStore the last accepted run and diff against it
Grader never checkedYou tune the prompt to please a wrong graderRead failures by hand, calibrate the judge
Tuning on the held-out setIt stops predicting productionRun it rarely, never iterate on it
Changing prompt and model togetherNo idea which one helpedOne change per run

Cheat sheet

CI, variance and production

I need toUse
Check a label or an idExact match after normalising
Check a fact appearsContains or regex
Check structured outputParse, schema, then values
Check an amountNumeric tolerance
Check a list of tags or entitiesPrecision, recall, F1
Check a free-text reply follows rulesNamed boolean checks
Check faithfulness or toneModel judge, pass or fail, calibrated
Check the retrieverHit rate, recall at k, MRR
Check an agentFinal state from a known start state
Stop regressionspytest gate: must-pass list and a rate threshold
Compare two versionsPer-case diff, then intervals
Know if users are better offA/B test and user signals
Debug a bad scoreTrace with prompt version and output

Interview questions

CI, variance and production

QuestionShort 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.