Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 21
Module 10 · Evals, security and production · Chapter 21 of 24
Evaluating LLM and agent systems
Builds on Working with model APIs, AI agents and multi-agent systems and Agent design fundamentals. Next up: Securing LLM applications and agents.
Part 1 · Error analysis first
Read the traces before you measure
A model feature can look fine in a demo and still fail in ways nobody has listed. Evaluation is the work of finding those failures and keeping a record of them, and it starts with reading, not with a metric.
A trace is the recorded history of one request: the input, any intermediate steps such as tool calls, and the output. Error analysis means reading traces yourself, writing a short note about what went wrong in each failure, and then grouping similar notes into a few categories that you can count. Practitioner advice, such as the evals FAQ by Hamel Husain, recommends doing this before building any automated metric: start from about 100 diverse traces, annotate at least the first 30 yourself, and continue until new traces stop revealing new kinds of failure. That is advice from experience, not a standard, but the reason is sound. A metric chosen before you have looked measures what you guessed, while categories taken from real traces measure what actually goes wrong.
There is a second reason to read first. Generic scores such as helpfulness or fluency rarely track the failures your users notice. A reply can be fluent and still invent a rule. Only a look at the data tells you which failures matter for this product.
This chapter follows one small system through every lesson, so each technique is applied to the same traces. The system is a support assistant for a made-up shop. The shop and its short policy are written for this chapter, so its return and refund figures are not those of the retrieval chapter's corpus. It receives a customer message and a short returns policy and must answer in at most 50 words using only that policy.
The system and its 40 traces
The policy has four rules: unused, unopened items can be returned within 7 days of delivery; food cannot be returned unless it arrived damaged and is reported within 2 days; refunds go to the original payment method within 5 working days; there is no store credit or exchange. The assistant is one model call with the policy in the system message.
from evalset import POLICY from llm import chat SYSTEM = ("You are a support assistant for an online shop. Answer the " "customer in at most 50 words, using only this policy.\n" + POLICY) def reply(message, **kw): kw.setdefault("temperature", 0.3) msg, r = chat([{"role": "system", "content": SYSTEM}, {"role": "user", "content": message}], max_tokens=150, **kw) return msg.content.strip(), r.usage.completion_tokens
The evaluation set has 40 customer messages. Thirty are covered by the policy: ten that should be accepted and twenty that should be rejected. Ten are questions the policy does not answer, such as delivery to another country or a warranty. For those the right reply says the policy does not cover it. The script records every message, the reply and the token count to a file.
import json from evalset import CASES from support import reply with open("traces.jsonl", "w", encoding="utf8", newline="\n") as f: for i, (message, accept) in enumerate(CASES, 1): text, toks = reply(message) row = {"id": i, "message": message, "accept": accept, "reply": text, "tokens": toks} f.write(json.dumps(row, ensure_ascii=False) + "\n") print(len(CASES), "traces recorded")
40 traces recordedOutput from one run. The replies differ on every run.
The messages were written to include the cases that tend to break assistants: borderline days, partial use, food that is damaged and food that is not, and requests the policy never mentions. Writing cases is the start of a test set, and the next lesson makes the failures found here permanent.
Labelling and counting
The author of this chapter read all 40 replies and wrote down which ones failed and why. A reply passed if it gave the right decision for the customer's facts and stated nothing beyond the policy. The labels are one person's judgement, and a second reader might label a borderline case differently, which is why real teams often check agreement between two labellers. Three failing traces follow, printed by a script.
import json import textwrap traces = {} for line in open("traces.jsonl", encoding="utf8"): t = json.loads(line) traces[t["id"]] = t labels = json.load(open("labels.json", encoding="utf8")) for i in (5, 34, 38): t = traces[i] print(f"#{i} [{labels[str(i)]}]") print(textwrap.fill("customer: " + t["message"], 68, subsequent_indent=" ")) print(textwrap.fill("reply: " + t["reply"], 68, subsequent_indent=" "))
#5 [hedges a settled decision] customer: The dal packet I got this morning was torn open. Return it please. reply: Since your food item arrived damaged, please report it within 2 days of delivery to qualify for a return. If approved, your refund will be processed to your original payment method within 5 working days. We do not offer store credit or exchanges. #34 [invents a rule or fact] customer: Can I return just one pen from a set of four? All unopened, 2 days. reply: I'm sorry, but we do not offer partial returns or exchanges. Since the item is part of a set, it cannot be returned individually. Only unused, unopened items can be returned within 7 days of delivery for a refund to your original payment method. #38 [misapplies a rule] customer: The earphones stopped working after 3 days. Do I get a refund? reply: I can only offer refunds for unused, unopened items returned within 7 days of delivery. Since your earphones are no longer in their original unopened condition, I cannot offer a refund or exchange.
Output from one run.
Trace 5 hedges: the customer already reported the damage, but the reply says to report it within 2 days. Trace 34 invents a rule against partial returns of a set, and the policy says nothing about sets. Trace 38 applies the unopened-items rule to a defective product, which the policy does not cover. Each is a different kind of failure, which is why they were grouped separately. A second script counts the labels.
import json from collections import Counter traces = [json.loads(l) for l in open("traces.jsonl", encoding="utf8")] labels = json.load(open("labels.json", encoding="utf8")) kind = {True: "accept", False: "reject", None: "policy silent"} by_group = Counter() for t in traces: failed = str(t["id"]) in labels by_group[(kind[t["accept"]], failed)] += 1 print("traces:", len(traces), "failed:", len(labels)) for group in ("accept", "reject", "policy silent"): f = by_group[(group, True)] n = f + by_group[(group, False)] print(f" {group:<14} {f} of {n} failed") print("failure categories:") for cat, n in Counter(labels.values()).most_common(): print(f" {n} {cat}")
Part 2 · Test sets and code checks
From failures to a test set
A test set is a fixed collection of inputs, each with a way to judge the output. It lets you change a prompt or a model and see at once whether anything got worse. The best cases come from real failures, because they are the inputs that actually hurt.
Start with every failure found in error analysis, and add the cases that are close to them. Keep the input, the reason it failed and the check that would catch it. Add new cases whenever a failure is reported from real use. A set built this way grows with the product and records its history.
Use code to judge wherever code can. A code check is an ordinary assertion on the output: it has a defined result, costs nothing to run, gives the same answer every time and can run on every change. Good targets are structure (valid JSON, required fields), limits (length, allowed values), required content (a refund timeline when a return is accepted) and forbidden content (phrases that signal an invented rule). Checks that need judgement, such as whether a reply is polite or faithful to a source, need a model judge, which the next lesson covers.
Size comes later. A few dozen cases are enough to find big problems and to protect against old ones returning, but a pass rate computed from them is imprecise, and lesson 4 puts numbers on that.
A pytest suite over recorded replies
The checks below come from the failures in the previous lesson. A reply must be at most 50 words. An accepted return must mention the 5 working days. An accepted return must not tell the customer to report damage that was already reported. And a few phrases, such as courier or physical shop, signal an invented fact or process.
import re INVENTED = ["courier", "shipping department", "physical shop", "partial return", "discount", "order detail"] def has(phrase, text): """Whole-word match, so 'ineligible' is not 'eligible'.""" pattern = rf"(?<!\w){re.escape(phrase)}s?(?!\w)" return re.search(pattern, text) is not None def words(t): return len(t["reply"].split()) def problems(t): r = t["reply"].lower() found = [] if words(t) > 50: found.append("too long") if t["accept"] is True and not has("5 working days", r): found.append("no refund timeline") if t["accept"] is True and has("report it within", r): found.append("hedges a settled decision") if (t["accept"] is False and has("eligible for a refund", r) and not has("not eligible", r)): found.append("accepts a rejected case") found += [f"invented: {p}" for p in INVENTED if has(p, r)] return found
A pytest file turns each trace into one test, so a failing case is named in the report. The suite runs on the recorded replies, which means it needs no model and finishes in a fraction of a second.
import json import pytest from checks import problems TRACES = [json.loads(l) for l in open("traces.jsonl", encoding="utf8")] @pytest.mark.parametrize("t", TRACES, ids=lambda t: f"trace{t['id']}") def test_trace(t): assert problems(t) == []
uv run python -m pytest -q test_checks.py
FAILED test_checks.py::test_trace[trace4] - AssertionError: assert ['hedges a... FAILED test_checks.py::test_trace[trace5] - AssertionError: assert ['hedges a... FAILED test_checks.py::test_trace[trace23] - AssertionError: assert ['invente... FAILED test_checks.py::test_trace[trace24] - AssertionError: assert ['invente... FAILED test_checks.py::test_trace[trace33] - AssertionError: assert ['invente... FAILED test_checks.py::test_trace[trace34] - AssertionError: assert ['invente... FAILED test_checks.py::test_trace[trace35] - AssertionError: assert ['too lon... FAILED test_checks.py::test_trace[trace36] - AssertionError: assert ['invente... FAILED test_checks.py::test_trace[trace39] - AssertionError: assert ['invente... 9 failed, 31 passed in 0.23s
Output from one run; only the result lines are shown. Long lines are wrapped here. Timing varies on this machine.
What code checks can and cannot do
The checks caught 9 of the 10 labelled failures and raised no false alarms. The one they missed, trace 38, applies the wrong rule to a broken product, and no short phrase marks it. Catching it needs a judge that reads the reply against the policy.
Read that result with care. The checks were written after reading these traces, so they fit these traces by design. The score of 9 out of 10 is not an estimate of how well the checks work on new replies. It shows that the checks encode what was learned. The suite is a regression test: it tells you when something that was handled stops being handled.
To learn how the checks behave on unseen data, record new traces from a changed prompt, label them by hand and see what the checks miss. Every miss is either a new check or a case for the judge. Over time this loop adds checks and categories.
Record once, replay often. The recorded replies make the suite fast and repeatable. When you change the prompt, record new replies for the same cases, run the same suite on them, and compare. The last lesson builds that workflow.
Why should failures found in error analysis become test cases?
- They are inputs that really hurt, and keeping them stops the same failure from returning unnoticed when the prompt or model changes.
The checks flagged 9 of the 10 failures. Why is that not an estimate of their accuracy on new replies?
- The checks were written after reading those same traces, so they fit them by design. An honest estimate needs new traces that were labelled separately.
Name two things a code check is good at and one it is not.
- Good at structure and limits, such as word counts, and at required or forbidden content. Not good at judgements such as whether a reply applies the right rule to a case, which needs a judge.
Part 3 · LLM-as-judge
Using a model to grade
Many qualities cannot be checked by code: whether a reply applies the right rule, stays faithful to a source or answers the question asked. An LLM judge is a model prompted to grade another model's output, usually with a rubric. It is cheap and fast, and it scales to thousands of cases. It is also a model, so it makes mistakes and has biases, and it must be checked before you trust it.
The paper *Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena* (Zheng et al., 2023) studied judges on open-ended questions and named biases to watch for. Position bias is a preference for an answer because of where it is listed. Verbosity bias is a preference for longer answers. Self-enhancement bias is a preference for answers written by the same model. The paper also reports how often a strong judge agreed with human votes in its own experiments, and that figure belongs to those experiments, not to your task.
Practitioner advice, such as the evals FAQ mentioned earlier, is to prefer a binary pass or fail verdict over a numeric scale, because labels are more consistent, and to build one judge per failure type. Asking for a short reason before the verdict is a common habit, and the second rubric below goes further and asks for the claims first. A rubric that says what pass and fail mean for your product is the main lever you have.
A judge and its agreement with humans
The judge below receives the policy, a rubric, the customer message and the reply. It returns a short reason and a verdict. The structured output keeps the verdict to two values.
import json from typing import Literal from pydantic import BaseModel from evalset import POLICY from llm import client, MODEL class Verdict(BaseModel): reason: str verdict: Literal["pass", "fail"] class Verdict2(BaseModel): claims: list[str] unsupported: list[str] verdict: Literal["pass", "fail"] RUBRIC = ( "You grade a shop assistant's reply. Policy:\n" + POLICY + "\nPASS only if the reply gives the right decision for the " "customer's facts and states nothing that is not in the policy. " "FAIL if it invents a rule, step or fact, misapplies a rule, " "or hedges a decision the facts already settle. If the policy " "does not cover the question, PASS only a reply that says so.") RUBRIC2 = RUBRIC + ( "\nFirst list every claim the reply makes: decisions, rules, " "steps, facts. Then list the claims that the policy text does " "not state. Any unsupported claim means FAIL.")
Two measures say how well it matches the human labels. Define them clearly, since sources differ. Here the positive class is pass. The true positive rate (TPR) is the share of human-passed replies the judge also passes. The true negative rate (TNR) is the share of human-failed replies the judge also fails. Some sources count the other way round, so always say which class is positive.
def judge(message, reply, v2=False): r = client.chat.completions.parse( model=MODEL, max_tokens=300, reasoning_effort="none", temperature=0, response_format=Verdict2 if v2 else Verdict, messages=[{"role": "system", "content": RUBRIC2 if v2 else RUBRIC}, {"role": "user", "content": f"Customer: {message}\nReply: {reply}"}]) return r.choices[0].message.parsed.verdict def rates(rows): c = {(h, j): 0 for h in ("pass", "fail") for j in ("pass", "fail")} for h, j in rows: c[(h, j)] += 1 hp = max(1, c["pass", "pass"] + c["pass", "fail"]) hf = max(1, c["fail", "fail"] + c["fail", "pass"]) return c, c["pass", "pass"] / hp, c["fail", "fail"] / hf
The script runs the judge on all 40 traces, computes both rates against the labels, and then repeats with a second rubric that asks for the claims in a reply and flags unsupported ones. The traces are split by id, odd ids as a development set for tuning the rubric and even ids as a test set kept for the final check.
What the numbers said
v1 all 40 TPR 0.97 TNR 0.30 pass kept 29, pass flagged 1, fail caught 3, fail missed 7 v1 dev (odd ids) TPR 1.00 TNR 0.40 pass kept 15, pass flagged 0, fail caught 2, fail missed 3 v1 test (even ids) TPR 0.93 TNR 0.20 pass kept 14, pass flagged 1, fail caught 1, fail missed 4 v2 all 40 TPR 1.00 TNR 0.50 pass kept 30, pass flagged 0, fail caught 5, fail missed 5 v2 dev (odd ids) TPR 1.00 TNR 0.40 pass kept 15, pass flagged 0, fail caught 2, fail missed 3 v2 test (even ids) TPR 1.00 TNR 0.60 pass kept 15, pass flagged 0, fail caught 3, fail missed 2
Output from one run; each line is split at the bar.
With the first rubric the judge passed 29 of the 30 replies humans passed, a TPR of 0.97. It failed only 3 of the 10 replies humans failed, a TNR of 0.30. Put differently, it let seven bad replies through. A judge like this makes a system look better than it is.
The second rubric raised the TNR to 0.50 over all 40, and to 0.60 on the even-id test half, while keeping the TPR at 1.00. That is better and still weak: half the failures pass. The development half barely moved, which is the pattern to watch for when you tune against a small set, since gains on the data you tuned on may not carry over. Both halves hold only a few failures, so these numbers move a lot with one case.
Watch for how many replies the humans failed but the judge passed
Read it as steps
The judge agrees on good replies and misses most bad ones.
The grid shows the first rubric's counts. The off-diagonal cell in the bottom left, seven failures that the judge passed, is the cost that a single agreement number would hide.
Position bias in a pairwise judge
A judge can also compare two replies and pick the better one. The script asks the judge to choose between two replies to the same message, in both orders: the recorded reply first, then the same pair swapped. If the judge is not influenced by position, it picks the same reply both times.
import json from typing import Literal from pydantic import BaseModel from evalset import POLICY from llm import client, MODEL from support import reply class Pick(BaseModel): better: Literal["A", "B"] def pick(message, first, second): r = client.chat.completions.parse( model=MODEL, response_format=Pick, max_tokens=20, reasoning_effort="none", temperature=0, messages=[{"role": "system", "content": "Policy:\n" + POLICY + "\nChoose the reply that " "follows the policy better. Answer A or B."}, {"role": "user", "content": f"Customer: {message}\nA: {first}\nB: {second}"}]) return r.choices[0].message.parsed.better
traces = [json.loads(l) for l in open("traces.jsonl", encoding="utf8")] same = flips = first_wins = 0 for t in traces[30:]: other, _ = reply(t["message"], temperature=1.0) x = pick(t["message"], t["reply"], other) y = pick(t["message"], other, t["reply"]) consistent = (x == "A") != (y == "A") same += consistent first_wins += (x == "A") + (y == "A") print(f"10 pairs, both orders: consistent {same}, " f"flipped with the order {10 - same}") print(f"the first-listed reply won {first_wins} of 20 verdicts")
10 pairs, both orders: consistent 4, flipped with the order 6 the first-listed reply won 6 of 20 verdicts
Output from one run; the second replies are sampled fresh each time.
In this run, in six of ten pairs the verdict followed the position and not the reply. The script was run five times in all, and the number of consistent pairs out of ten was 4, 9, 4, 5 and 3. The first-listed reply won 6, 9, 4, 9 and 7 of 20 verdicts, so no one position was favoured. The second reply is sampled fresh each run, and two replies of similar quality will flip with the order for any judge, so part of the flipping is noise. With this model, the order changed the verdict often enough to matter. The usual mitigation is to run both orders and count a result only when the two agree, and to treat the rest as ties.
What do TPR and TNR measure for a pass or fail judge, if pass is the positive class?
- TPR is the share of human-passed replies that the judge also passes. TNR is the share of human-failed replies that the judge also fails.
Part 4 · How sure is a pass rate
A pass rate is an estimate
An eval run gives a pass rate: 17 of 20 passed, so 85 per cent. If you drew another 20 cases from the same traffic, you might get 15 or 19. The number you measured is one sample of a rate you cannot see directly. Before acting on a change in a pass rate, ask how far it could move by chance alone.
A confidence interval answers that, and the pipeline case study already used one on a development score. For a pass rate it gives a range that, under the usual assumptions, contains the true rate in about 95 out of 100 repeated experiments. The assumptions matter: cases are independent, and they are a fair sample of the traffic you care about. Cases picked by hand because they are hard do not represent typical traffic, and several cases that all test the same rule are not independent.
The simple textbook interval, called the normal approximation, adds and subtracts a multiple of the standard error around the observed rate. It behaves badly for small samples and for rates near 0 or 1, where it can give a zero-width range. The Wilson score interval (Wilson, 1927) fixes this. It is the set of true rates that the observed result would not reject in a standard test. The article by Brown, Cai and DasGupta (2001), *Interval Estimation for a Binomial Proportion*, compares the methods, and common statistics libraries offer Wilson as an option.
With k passes in n cases, p = k/n and z = 1.96 for 95 per cent, the interval is centred at (p + z squared over 2n) divided by (1 + z squared over n), with half-width z times the square root of p(1-p)/n + z squared over 4n squared, all divided by (1 + z squared over n).
Intervals computed
The script implements both intervals and prints them for the pass rates used in this chapter. As a check on the Wilson code, it also evaluates the score statistic at the two ends of the interval for 17 of 20: by definition of the interval it should equal 1.96 there.
import math Z = 1.96 # 95 percent, two-sided def wilson(k, n, z=Z): p = k / n d = 1 + z * z / n centre = (p + z * z / (2 * n)) / d half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d return centre - half, centre + half def normal(k, n, z=Z): p = k / n half = z * math.sqrt(p * (1 - p) / n) return max(0.0, p - half), min(1.0, p + half) def score_z(k, n, p0): p = k / n return abs(p - p0) / math.sqrt(p0 * (1 - p0) / n)
from wilson import wilson, normal, score_z print("passes rate Wilson 95% normal 95%") for k, n in ((17, 20), (170, 200), (30, 40), (20, 20), (3, 10)): w, nm = wilson(k, n), normal(k, n) print(f"{k:>3}/{n:<3} {k/n:.3f} [{w[0]:.3f}, {w[1]:.3f}] " f"w={w[1]-w[0]:.3f} [{nm[0]:.3f}, {nm[1]:.3f}]") lo, hi = wilson(17, 20) print("score statistic at the ends:", round(score_z(17, 20, lo), 3), round(score_z(17, 20, hi), 3)) print("cases needed for a half-width of at most:") for target in (0.10, 0.05, 0.03): n = 5 while True: lo, hi = wilson(0.85 * n, n) if (hi - lo) / 2 <= target: break n += 1 print(f" +-{target:.2f} at a pass rate near 0.85: {n} cases")
passes rate Wilson 95% normal 95% 17/20 0.850 [0.640, 0.948] w=0.308 [0.694, 1.000] 170/200 0.850 [0.794, 0.893] w=0.099 [0.801, 0.899] 30/40 0.750 [0.598, 0.858] w=0.260 [0.616, 0.884] 20/20 1.000 [0.839, 1.000] w=0.161 [1.000, 1.000] 3/10 0.300 [0.108, 0.603] w=0.495 [0.016, 0.584] score statistic at the ends: 1.96 1.96 cases needed for a half-width of at most: +-0.10 at a pass rate near 0.85: 49 cases +-0.05 at a pass rate near 0.85: 196 cases +-0.03 at a pass rate near 0.85: 545 cases
Output from one run; this script has no randomness.
The check passes: the statistic is 1.96 at both ends. The first two rows are the same pass rate of 0.85 measured on 20 and on 200 cases. With 20 cases the interval runs from 0.640 to 0.948, a width of 0.31. With 200 cases it runs from 0.794 to 0.893, a width of 0.10. Ten times the cases gave about a third of the width, because the width shrinks with the square root of the sample size.
The row for 20 of 20 shows why the normal approximation is a poor choice here. It gives a range of 1.000 to 1.000, a claim of certainty from 20 cases. The Wilson interval runs from 0.839 to 1.000: after 20 clean passes the true rate could still be about 84 per cent.
How many cases a change needs
The last lines of the output answer a planning question: how many cases are needed to pin a pass rate near 0.85 to within a given half-width. Within plus or minus 0.10 needs 49 cases, within 0.05 needs 196, and within 0.03 needs 545. Those are the numbers from the search in the script, using the Wilson interval with 85 per cent of the cases passing. Counting a whole number of passes instead moves them by one or two, so treat them as about 50, 200 and 550. The textbook formula for the normal approximation, z squared times p(1-p) divided by the half-width squared, gives 196 for 0.05, which agrees.
Use them to match the test set to the decision. A set of 40 cases can show a drop from 85 to 50 per cent, but it cannot show a drop from 85 to 80, and the interval will say so. If you need to see small changes, you need hundreds of cases, or a different design, such as running the same cases many times or comparing two versions on the same cases and looking at which individual cases changed.
The row for 3 of 10 applies the same idea to the judge of the previous lesson. Its TNR of 0.30 came from 10 failures, and the Wilson interval for 3 of 10 runs from 0.108 to 0.603. The judge's true rate for catching failures could plausibly be 11 per cent or 60 per cent. The practitioner advice to label 100 to 200 examples per failure mode for a judge makes sense for this reason.
Report a pass rate with its sample size and interval, as in 31 of 40, interval 0.625 to 0.877. A change is clearly better or worse when the intervals do not overlap. The interval, not the headline number, tells you whether to act.
Why does a pass rate of 17 out of 20 need an interval?
- It is one sample of a rate that cannot be seen directly. With only 20 cases it could easily have come out at 15 or 19, and the Wilson interval, 0.640 to 0.948, shows that range.
The normal approximation gives 1.000 to 1.000 for 20 passes out of 20. What does the Wilson interval give, and what does it tell you?
- 0.839 to 1.000. After 20 passes the true rate could still be about 84 per cent, so 20 clean passes do not prove the system is perfect.
Part 5 · Evaluating agents
What to score in an agent run
An agent run is a sequence: the task, a series of tool calls and results, and a final answer. Scoring only the final text misses much of what can go wrong, and scoring only the path penalises runs that reached a correct answer another way. Useful evaluations look at several parts.
- Final state: did the run end in the right outcome? For a lookup, does the answer state the right status? For an action, is the system in the right state afterwards? Where the state can be inspected, inspect it, not the text of the answer.
- Tool-call accuracy: were the right tools called with the right arguments, and no others? A run that reaches the right answer after looking up the wrong order is luck.
- Efficiency: steps, tokens and time. Two runs with the same outcome can differ in cost.
- Safety and limits: did any call get denied, did the run hit a budget, did it repeat a call?
- Trajectory quality: read some full runs. Scores summarise, and reading finds what the scores did not anticipate.
Final-state checks and tool-call checks are code, so they run on every change. Trajectory review is human, so do it on a sample. The two support each other, as this lesson shows.
Scoring recorded runs
The runs come from the order-desk agent of the agents chapter. Eight tasks were run twice each and recorded: single lookups, two and three orders at once, an order id that does not exist, a request to cancel an order, which no tool can do, and two date and status questions. Each task lists the order ids the agent should look up, the words the answer needs and words it must not contain.
# (task, order ids the agent should look up, words the answer needs, # words the answer must not contain) TASKS = [ ("Where is AB-1042?", {"AB-1042"}, ["delivered"], []), ("What is the status of AB-2210?", {"AB-2210"}, ["out for delivery"], []), ("Status of AB-2210 and AB-3301, please.", {"AB-2210", "AB-3301"}, ["out for delivery", "packed"], []), ("Which of AB-1042, AB-2210 and AB-3301 arrives last?", {"AB-1042", "AB-2210", "AB-3301"}, ["ab-3301"], []), ("Where is AB-9999?", {"AB-9999"}, ["unknown"], ["delivered", "out for delivery", "packed"]), ("Cancel order AB-2210 for me.", set(), ["cannot"], ["cancelled"]), ("Has AB-3301 left the warehouse?", {"AB-3301"}, ["tomorrow"], []), ("Is AB-1042 delivered, and when?", {"AB-1042"}, ["12 nov"], []), ]
The scorer computes four things per run: whether the final answer contains the needed words and none of the forbidden ones, whether the lookups were exactly the expected ones, and the steps and tokens. Its first argument names which task file to use.
import importlib import json import re import sys TASKS = importlib.import_module(sys.argv[1]).TASKS runs = [json.loads(l) for l in open("agent_runs.jsonl", encoding="utf8")] def has(ans, word): options = (word,) if isinstance(word, str) else word return any(re.search(rf"(?<!\w){re.escape(o)}(?!\w)", ans) for o in options) def score(run): task, want_ids, need, forbid = TASKS[run["task"]] ans = run["answer"].lower() asked = [json.loads(a).get("order_id") for _, a, _ in run["calls"]] return { "final": all(has(ans, w) for w in need) and not any(has(ans, w) for w in forbid), "calls": set(asked) == want_ids and len(asked) == len(want_ids), "steps": run["steps"], "tokens": run["tokens"], }
The loop below prints one line per run and totals the two checks.
scores = [score(r) for r in runs] for r, s in zip(runs, scores): print(f"task {r['task']}: final {s['final']!s:<5} " f"calls {s['calls']!s:<5} steps {s['steps']} " f"tokens {s['tokens']}") ok = sum(s["final"] for s in scores) both = sum(s["final"] and s["calls"] for s in scores) print(f"final ok {ok}/{len(runs)}; " f"final and calls ok {both}/{len(runs)}")
Reading the trajectories
The failing runs were tasks 4, 5 and 7. The script prints one run from each, with its calls and answer.
import json import textwrap runs = [json.loads(l) for l in open("agent_runs.jsonl", encoding="utf8")] for i in (8, 10, 14): r = runs[i] print(f"run {i} (task {r['task']}), {r['steps']} model calls") for name, args, res in r["calls"]: print(f" call {name} {args} -> {res}") print(textwrap.fill("answer: " + r["answer"], 68, initial_indent=" ", subsequent_indent=" "))
run 8 (task 4), 2 model calls call get_order_status {"order_id":"AB-9999"} -> error: unknown order id answer: I'm sorry, but I couldn't find any information for order ID AB-9999. Could you please double-check the number? run 10 (task 5), 2 model calls call get_order_status {"order_id":"AB-2210"} -> out for delivery answer: I'm sorry, but I cannot cancel order AB-2210 because it is already "out for delivery." run 14 (task 7), 2 model calls call get_order_status {"order_id":"AB-1042"} -> delivered on 12 Nov answer: Order AB-1042 was delivered on November 12th.
Output from one run. Long lines are wrapped here.
Task 4 asked about an order that does not exist. The agent called the tool, got an error, and replied that it could not find the order. That is the right behaviour, but the scorer looked for the word unknown. Task 7 answered November 12th, and the scorer looked for 12 nov. In task 5, which asked to cancel an order, the agent looked up the order first and then declined. The scorer expected no lookups at all. All three were mistakes in the scorer, not in the agent.
The cancel run also deserves a closer look. The agent refused, which is right, since no cancel tool exists. Its reason, that the order is already out for delivery, was drawn from the lookup result and is not why it could not cancel. A final-state check passes this run, and only reading the trajectory shows an explanation that is not true.
The corrected task file allows alternative wordings and a lookup before a refusal. Scoring the same recorded runs again gives the results below.
task 0: final True calls True steps 2 tokens 247 task 0: final True calls True steps 2 tokens 247 task 1: final True calls True steps 2 tokens 250 task 1: final True calls True steps 2 tokens 250 task 2: final True calls True steps 2 tokens 342 task 2: final True calls True steps 2 tokens 340 task 3: final True calls True steps 2 tokens 472 task 3: final True calls True steps 2 tokens 465 task 4: final True calls True steps 2 tokens 262 task 4: final True calls True steps 2 tokens 265 task 5: final True calls True steps 2 tokens 257 task 5: final True calls True steps 2 tokens 256 task 6: final True calls True steps 2 tokens 261 task 6: final True calls True steps 2 tokens 254 task 7: final True calls True steps 2 tokens 253 task 7: final True calls True steps 2 tokens 255 final ok 16/16; final and calls ok 16/16
Output from one run of the scorer with the corrected task file.
Part 6 · Evals in CI
Record once, replay in tests
An eval that runs only when someone remembers it will not catch a regression. Continuous integration (CI) runs checks automatically on every change. For model features the difficulty is cost and variation: calling the model for every case on every commit is slow and not repeatable.
The answer is to separate recording from replay. A recording stores the model's replies for the test cases once. A replay runs the checks on stored replies, with no model call. Replays are fast, free and deterministic, so they can run on every commit. When a change affects the prompt, model or tools, you record again for the new version and compare the new recording with the baseline.
This split gives two kinds of test. Code checks and rules about structure run in the replay, so a change to the checks themselves is tested without noise. Live evaluation, which calls the model and a judge, runs less often, such as nightly or before a release, and its results are stored as the next baseline.
A gate that compares two recordings
The gate below compares a candidate recording with the baseline using the code checks from the second lesson. It applies two rules. No case that passed in the baseline may fail in the candidate. And the Wilson interval of the candidate's pass rate must not lie entirely below the baseline's pass rate.
import json import sys from checks import problems from wilson import wilson def load(path): rows = map(json.loads, open(path, encoding="utf8")) return {t["id"]: t for t in rows} def gate(base, cand): ok = lambda t: not problems(t) flips = sorted(i for i in base if ok(base[i]) and not ok(cand[i])) n = len(cand) rate_base = sum(map(ok, base.values())) / n k = sum(map(ok, cand.values())) lo, hi = wilson(k, n) return flips, rate_base, k, n, (lo, hi) if __name__ == "__main__": flips, rb, k, n, (lo, hi) = gate(load("traces.jsonl"), load(sys.argv[1])) print(f"baseline pass rate {rb:.3f}; candidate {k}/{n}, " f"interval [{lo:.3f}, {hi:.3f}]") print("cases that passed before and fail now:", flips) bad = bool(flips) or hi < rb print("GATE:", "FAIL" if bad else "ok") sys.exit(1 if bad else 0)
To test the gate, a script plants a regression. It edits the stored replies to drop every sentence mentioning working days, the effect of a prompt change that loses the refund timeline.
import json import re rows = [json.loads(l) for l in open("traces.jsonl", encoding="utf8")] for t in rows: # planted regression: a prompt change drops the refund timeline t["reply"] = re.sub(r"[^.]*working days\.?\s*", "", t["reply"]).strip() with open("traces_regressed.jsonl", "w", encoding="utf8", newline="\n") as f: for t in rows: f.write(json.dumps(t, ensure_ascii=False) + "\n") print("wrote", len(rows), "regressed traces")
uv run python ci_gate.py traces.jsonl uv run python ci_gate.py traces_regressed.jsonl
baseline pass rate 0.775; candidate 31/40, interval [0.625, 0.877] cases that passed before and fail now: [] GATE: ok exit 0 baseline pass rate 0.775; candidate 25/40, interval [0.470, 0.758] cases that passed before and fail now: [1, 2, 3, 6, 22, 25] GATE: FAIL exit 1
Output from one run; this script has no randomness.
The baseline passes against itself. The planted regression is caught: six cases that passed before now fail, and the interval for 25 of 40, from 0.470 to 0.758, lies below the baseline rate of 0.775. The command exits with status 1, which makes a CI job fail.
The gate inside the test suite
The same rules fit in pytest, so they run with the other tests. The file reads the candidate's path from an environment variable and defaults to the baseline.
import os from ci_gate import gate, load CANDIDATE = os.environ.get("CANDIDATE", "traces.jsonl") def test_no_case_that_passed_now_fails(): flips, *_ = gate(load("traces.jsonl"), load(CANDIDATE)) assert flips == [] def test_pass_rate_not_clearly_lower(): _, rate_base, k, n, (lo, hi) = gate(load("traces.jsonl"), load(CANDIDATE)) assert hi >= rate_base, f"{k}/{n}, upper bound {hi:.3f}"
With the default recording both tests pass. With the regressed recording, both fail.
.. [100%] 2 passed in 0.03s
Output from one run on the baseline recording. Long lines are wrapped here. Timing varies on this machine.
FAILED test_ci.py::test_no_case_that_passed_now_fails - assert [1, 2, 3, 6, 2... FAILED test_ci.py::test_pass_rate_not_clearly_lower - AssertionError: 25/40, ... 2 failed in 0.30s
Output from one run with CANDIDATE set to the regressed recording; the lines are cut by pytest. Long lines are wrapped here. Timing varies on this machine.
The first rule is the sharper one. It is exact because a replay has no randomness, so any case that flips is a real change. The second rule is weaker: with 40 cases, a drop of this size only just clears it. That is the sample-size point from the previous lesson, applied to a gate. A larger recorded set tightens the interval rule.
Watch for the gate blocking the change that loses a case
Read it as steps
All chapters · Previous: Case study: a personal AI assistant