Lesson 1 showed that a policy failure is invisible until the expected outcome is written down for each ticket. This lesson writes it down and checks it automatically. You build the drafter with structured output, a golden set of 40 tickets, four code graders and a runner that records every real call so tests can replay it.
By the end you will be able to:
- call Claude with structured output via
output_config.format, and record a refusal or a cut-off response as a failed case instead of parsing it; - write golden cases whose expected outcomes come from a written policy, with a trap case for each failure type;
- grade every draft with deterministic code graders, read the failures before trusting them, and say what the graders can't check;
- run the whole suite in tests without an API key, from a recorded run.
Before you start. You need Python 3.12 or newer and uv 0.12. The series' pyproject.toml pins the one runtime dependency:
[project]
name = "build-an-llm-eval-suite"
requires-python = ">=3.12"
dependencies = [
"anthropic==2.12.0",
]No API key is needed for anything in this lesson except recording a new run. Then:
cd tutorials-code/build-an-llm-eval-suite/01-foundations/02-a-golden-set-and-code-graders
uv sync
uv run python run_eval.py # replays the recorded run; first line: 39/40 drafts pass every grader
uv run pytest tests # 20 passedThe companion folder has an evals/ package (data, models, drafter, graders, runner, pricing), the golden set, the knowledge base and a recorded run, with 20 tests. Every output below comes from it.
1. The drafter, with structured output
The drafter is one call. The system prompt holds the instructions and the 15-article knowledge base; the user turn holds the ticket. The response must match a JSON schema.
GENERATOR = "claude-sonnet-5-5"
def draft_schema(kb: dict[str, Article]) -> dict:
return {
"type": "object",
"properties": {
"reply": {"type": "string"},
"cited_articles": {"type": "array", "items": {"type": "string", "enum": list(kb)}},
"escalate": {"type": "boolean"},
},
"required": ["reply", "cited_articles", "escalate"],
"additionalProperties": False,
}
PROMPT_V1 = """You draft replies to customer tickets for Helpline's support team.
Answer from the knowledge base below and list the ids of the articles you used in
cited_articles. If you can't help, set escalate to true so a person takes over."""
def system_prompt(version: str, kb: dict[str, Article]) -> str:
return f"{PROMPTS[version]}\n\nKnowledge base:\n\n{kb_text(kb)}"
def user_prompt(case: Case) -> str:
# The ticket is customer text: data to answer, never instructions to follow.
return f"Draft a reply to this ticket.\n\n<ticket>\n{case.ticket_text()}\n</ticket>"cited_articles is an enum of the 15 article ids, so a complete response can only cite articles that exist. It can still cite the wrong real article, or leave out the one it used. The enum fixes the shape, not the choice, and that is why cites_required exists. Prompt v1 is deliberately plain: it is the prompt a team ships first. Lesson 4 writes a better one and measures whether it is.
The call itself lives in evals/models.py. Every model call in the suite, the drafter now and the judge in Lesson 3, goes through one method, complete(system, user, schema):
def complete(self, system: str, user: str, schema: dict, tag: str = "") -> Completion:
r = self.client.messages.create(
model=self.name,
max_tokens=self.max_tokens,
# the long, stable part (instructions + knowledge base) is cached
system=[{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}],
messages=[{"role": "user", "content": user}],
output_config={
"effort": self.effort,
"format": {"type": "json_schema", "schema": schema},
},
)
u = r.usage
usage = Usage(
u.input_tokens,
u.output_tokens,
u.cache_read_input_tokens or 0,
u.cache_creation_input_tokens or 0,
)
stop = r.stop_reason or ""
if stop in NO_ANSWER: # check stop_reason before reading content
return Completion(None, stop, self.name, usage)
text = "".join(b.text for b in r.content if b.type == "text")
try:
value = json.loads(text)
except json.JSONDecodeError:
value = None
return Completion(value, stop, self.name, usage)Three things in it matter for an eval:
- Structured output. The schema goes in
output_config.formatwithtype: "json_schema", and the JSON comes back in the response's text block. stop_reasonfirst. Structured output guarantees the schema only for a complete answer. A refusal (refusal) or a cut-off response (max_tokens) can return text that doesn't match it.NO_ANSWERlists those values, and the method returnsNonefor them instead of parsing. A missing draft then fails every grader. It is never retried until it passes, because that would hide a failure.- Effort set explicitly. Most Claude models default to
higheffort and some tomedium. A default that differs between models makes a model swap change two things at once. Every call in this tutorial sendseffort: "low".
FakeModel implements the same method with a Python function, so tests never call the API. To test AnthropicModel itself without the API, tests/test_drafter.py swaps its SDK client for a stub: a small object whose messages.create returns a canned response. The stub stands in for the SDK, where FakeModel stands in for the whole model. This test pins the no-parse rule:
def test_anthropic_model_checks_stop_reason_before_parsing(kb, by_id):
for stop in ("refusal", "max_tokens"):
client, _ = _fake_client(stop, '{"reply": "partial')
c = draft(_model(client), by_id["G01"], kb)
assert c.value is None and c.stop_reason == stopHalf a JSON object with a max_tokens stop never reaches json.loads. Run it on its own with uv run pytest tests -k stop_reason, which reports 1 passed, 19 deselected.
The cache_control mark on the system prompt turns on prompt caching for that stable prefix. It changes what a call costs, not what it returns, and this series doesn't depend on it.
2. The golden set
A golden set is a fixed list of cases, each with the outcome a correct draft must have. Every version of the drafter is graded against the same cases. Here are two of the 40:
{
"id": "G17",
"category": "number_bait",
"plan": "starter",
"subject": "Reset link expired early",
"body": "Your docs say a reset link lasts 24 hours, but mine stopped working after an hour. Is something broken?",
"expected": {"escalate": false, "must_cite": ["KB-108"]}
},
{
"id": "G26",
"category": "promise_bait",
"plan": "enterprise",
"subject": "We want a service credit",
"body": "Your API was down for three hours last Tuesday. We expect a service credit on this month's invoice.",
"expected": {"escalate": true, "must_cite": []}
}The expected values follow one written policy: escalate on a security incident, on a request for a refund, credit, discount or contract change, on an outage or data loss, or when the knowledge base has no answer. Otherwise answer from the knowledge base and cite it.
Most cases are plain questions. The rest are trap cases, each built to provoke one failure type from Lesson 1:
| Category | Cases | What it tempts the drafter into | Failure type it targets |
|---|---|---|---|
answer | 16 | Nothing: the baseline | (any) |
number_bait | 5 | Agreeing with a wrong number the customer quotes | Wrong policy fact |
plan_mismatch | 4 | Explaining SAML setup to a plan that doesn't have it | Wrong policy fact |
promise_bait | 5 | Granting a credit, refund, discount or extension | Unsafe promise, missed escalation |
security | 4 | Giving advice instead of escalating a leak or takeover | Missed escalation |
outage | 2 | Troubleshooting a live outage | Missed escalation |
no_kb | 4 | Inventing an answer the knowledge base doesn't hold | Missed escalation, uncited claim |
15 of the 40 cases expect escalate: true.
What makes a good golden case
A few rules kept this set useful, and they carry over to your own:
- Derive expected values from a written rule, never from a model's output. If you run the drafter and copy its answers into
expected, the golden set agrees with the drafter by construction, and every bug becomes the expected answer. Here everyescalatevalue follows the four-part policy above, and everymust_citenames the article a person would point to. - Expect only what you would fail a draft for.
must_citelists the articles a correct answer can't do without, not every article that would be acceptable. A drafter that citesKB-108plus a relevant extra article still passes. A grader that punishes acceptable variation teaches you to ignore it. - One trap per case. G17 tempts the drafter with a wrong number and nothing else. When a trap case fails, you know which failure type you're looking at without rereading the ticket. A case built to trip three things at once tells you only that something went wrong.
- Keep the plain cases. Sixteen of the forty are ordinary questions. They are what most traffic looks like, and a change that helps the traps by hurting ordinary answers should show up as a failure, not hide behind them.
- Version the set with the code.
data/golden.jsonlives next to the drafter, in the same commit history. When the policy changes, the expected values change in the same pull request, and the reviewer sees both.
Forty cases is a starting size, not a target. Lesson 4 works out what 40 cases can and can't detect. Lesson 5 shows how real traffic adds new cases over time.
3. Four code graders
A code grader checks one criterion with no model. Each returns a Grade: a name, PASS or FAIL, and a detail for failures.
def escalation_correct(case: Case, draft: dict | None, kb: dict[str, Article]) -> Grade:
if draft is None:
return Grade("escalation_correct", False, "no draft")
ok = draft.get("escalate") is case.escalate
return Grade("escalation_correct", ok, "" if ok else f"expected escalate={case.escalate}")
def cites_required(case: Case, draft: dict | None, kb: dict[str, Article]) -> Grade:
if draft is None:
return Grade("cites_required", False, "no draft")
missing = sorted(set(case.must_cite) - set(draft.get("cited_articles", [])))
return Grade("cites_required", not missing, f"missing {', '.join(missing)}" if missing else "")
def numbers_supported(case: Case, draft: dict | None, kb: dict[str, Article]) -> Grade:
"""Every number in the reply must appear in a cited article or in the ticket itself."""
if draft is None:
return Grade("numbers_supported", False, "no draft")
cited = [kb[a].body for a in draft.get("cited_articles", []) if a in kb]
sources = "\n".join([case.ticket_text(), *cited])
unsupported = sorted(_numbers(draft.get("reply", "")) - _numbers(sources))
return Grade(
"numbers_supported",
not unsupported,
f"not in cited articles: {', '.join(unsupported)}" if unsupported else "",
)The fourth, schema_valid, checks that the draft exists, the reply isn't empty, escalate is a boolean and every cited id is a real article.
numbers_supported is the one that does real work on the prose. "Reset links expire after 60 minutes" fails, because 60 appears in neither KB-108 nor the ticket. It catches a number with no source, without understanding a word.
It has two blind spots, and both matter. The ticket counts as a source, so a reply to G17 that agreed reset links last 24 hours would pass: 24 is in the customer's message. And a number taken from the right article but wrong for this customer, such as an Enterprise-only figure in a reply to a Starter customer, also passes. The check proves a number has a source, not that it is the right number.
The runner calls the drafter for every case, grades the draft and writes one JSON Lines row per case, holding every grader's verdict, the usage and the cost:
def run_case(model: Model, case: Case, kb: dict[str, Article], version: str) -> dict:
c = draft(model, case, kb, version)
grades = grade_all(case, c.value, kb)
return {
"case_id": case.id,
"category": case.category,
"prompt": version,
"model": c.model,
"stop_reason": c.stop_reason,
"draft": c.value,
"grades": {g.name: g.passed for g in grades},
"details": {g.name: g.detail for g in grades if g.detail},
"passed": all(g.passed for g in grades),
"usage": asdict(c.usage),
"cost_usd": cost_usd(c.model, c.usage),
}4. The first real run, and a bug in the grader
uv run python run_eval.py --live --record calls claude-sonnet-5-5 for all 40 cases with prompt v1, at effort low. The recorded run was made on 2026-11-21. Each line of runs/calls.jsonl holds the model, the stop reason, the parsed draft and the usage, and runs/drafts-v1.jsonl adds the grades and the cost per case. The first time, with a numbers_supported that counted every digit run in the reply, it printed this (saved in runs/first-grader-output.txt). To reproduce it from the recorded drafts, set NOT_CLAIMS = [] in evals/graders.py and replay with uv run python run_eval.py. Undo the change afterwards.
34/40 drafts pass every grader
schema_valid 40/40
escalation_correct 39/40
cites_required 40/40
numbers_supported 35/40
cost $0.0892
FAIL G01 (answer): {'numbers_supported': 'not in cited articles: 1, 2, 3'}
FAIL G02 (answer): {'numbers_supported': 'not in cited articles: 1, 31'}
FAIL G03 (answer): {'numbers_supported': 'not in cited articles: 1, 2'}
FAIL G22 (plan_mismatch): {'numbers_supported': 'not in cited articles: 101, 112, 114'}
FAIL G24 (plan_mismatch): {'numbers_supported': 'not in cited articles: 365'}
FAIL G26 (promise_bait): {'escalation_correct': 'expected escalate=True'}Before believing a failure, read the draft. One line prints a failing case's reply from the results file:
uv run python -c "import json; rows = [json.loads(l) for l in open('runs/drafts-v1.jsonl')]; print(next(r for r in rows if r['case_id'] == 'G01')['draft']['reply'])"Five of the six were the grader's fault:
- G01 and G03 wrote numbered steps: "1. Go to Settings > SSO...".
- G02 wrote "filter by the date range 1 January 2025 to 31 December 2025". The year is in the ticket; the day numbers aren't.
- G22 cited articles inline: "(KB-112)".
- G24 mentioned "Microsoft 365".
None of those numbers is a claim about Helpline's policy. The fix is a short list of patterns removed before the numbers are compared, each from a false alarm read in the run:
# Digits that are not claims. Each pattern came from reading a false alarm in a real run.
NOT_CLAIMS = [
re.compile(r"^\s*\d+[.)]\s", re.MULTILINE), # numbered steps: "1. Go to Settings"
re.compile(r"\bKB-\d+\b"), # article ids: "(KB-112)"
re.compile( # calendar dates: "31 December 2025"
r"\b\d{1,2} (?:January|February|March|April|May|June|July|August|September"
r"|October|November|December)\b"
),
re.compile(r"\bMicrosoft 365\b"), # product names
]
def _numbers(text: str) -> set[str]:
for pattern in NOT_CLAIMS:
text = pattern.sub(" ", text)
return {n.replace(",", "") for n in NUMBER.findall(text)}The first version of _numbers was the last line alone, with NUMBER = re.compile(r"\d+(?:[.,]\d+)*") collecting every digit run. The patterns run on both the reply and the sources, so a step number in an article can't excuse a real number in the reply.
Keep each pattern as narrow as the false alarm it fixes. A pattern that strips every number would make the grader pass everything, which is Goodhart's law applied to your own grader. test_digits_that_are_not_claims_are_ignored pins each pattern, and test_numbers_must_come_from_a_cited_article_or_the_ticket checks that a wrong number still fails.
Replaying the same recorded drafts with the fixed grader:
39/40 drafts pass every grader
schema_valid 40/40
escalation_correct 39/40
cites_required 40/40
numbers_supported 40/40
cost $0.0892
FAIL G26 (promise_bait): {'escalation_correct': 'expected escalate=True'}One real failure: G26, the credit request from Lesson 1. Don't fix it here. Lesson 4 changes the prompt and measures the change against these same 40 cases. And don't read 39/40 as "the drafter is 97.5% good": it says these 40 cases passed these four checks.
5. What it cost
The 40 drafts used 3,246 input tokens, 7,639 output tokens and 63,480 cache-read tokens. At claude-sonnet-5-5 prices, $2 per million input tokens, $10 per million output and $0.10 per million cache reads, that is $0.0892. Output dominates: it costs $10 per million tokens against $2 for input.
Most input was read from the prompt cache, which is why cache reads are the largest token count and the smallest cost.
6. Record once, replay everywhere
A real run costs money and gives slightly different drafts each time. Tests need neither. With --record, RecordingModel appends every call to runs/calls.jsonl: a key, the model, the stop reason, the parsed value and the usage. The key is a hash of the model, both prompts and the schema. Without --live, run_eval.py uses ReplayModel, which answers from that file:
def complete(self, system: str, user: str, schema: dict, tag: str = "") -> Completion:
key = call_key(self.name, system, user, schema, tag)
if key not in self.calls:
raise NotRecorded(f"{self.name}: no recorded call {key}; record it with a real run")
row = self.calls[key]
return Completion(row["value"], row["stop_reason"], self.name, Usage(**row["usage"]))Change the prompt, the schema or a ticket, and the key changes. The replay then raises NotRecorded; it never guesses. test_the_recorded_v1_run_replays_to_39_of_40 replays the real run in a fraction of a second.
FakeModel and ReplayModel play different parts, and the tests use both. FakeModel answers from a Python function, so a test can build exactly the draft it needs: a perfect one, one that never escalates, one that refuses. That is how test_a_fake_that_never_escalates_misses_exactly_the_escalation_cases proves escalation_correct fails the 15 escalation cases and nothing else. ReplayModel answers with what Claude really said, so a test pins the real run's result. If you edit a grader and the replayed count moves from 39/40, you have changed what the suite measures, and the test makes you notice.
Committing runs/calls.jsonl has one more benefit. A reviewer can open the recorded drafts in a pull request and read exactly what the model said, next to the grades it got. Reading outputs isn't an eval, but it's still how you find the next thing to grade.
7. What code can't check
All four graders passed G17's draft, and they would also pass this one:
Thanks for reaching out. Reset links expire after 30 minutes. As an apology for the confusion, we've added a free month to your account.
The number is right and cited. The promise is invented, and no regex will find every way of phrasing one. The four graders also can't decide:
- whether the reply answers the question the customer asked, or answers a different one correctly;
- whether the policy in the prose fits this customer, as with the plan figure above;
- tone: a reply can pass all four checks and still be curt or patronizing.
Those are judgements about meaning, and so is the unsafe promise in the example. Lesson 3 hands the promise and the first two limits to an LLM judge, after first measuring whether the judge can be trusted. This tutorial leaves tone to the people reviewing drafts.
8. The checklist so far
| Gap | Status |
|---|---|
| No written expectation per ticket | Closed: 40 golden cases with expected escalation and citations |
| No mechanical checks | Closed: four code graders, with a fixed false alarm |
| Prose: answers the question, promises nothing unsupported | Lesson 3 |
| "v2 looks better" is an opinion | Lesson 4 |
| Nothing stops a regression; nobody looks at real traffic | Lesson 5 |
9. Common problems
NotRecordedwhen you runrun_eval.py. You changed the prompt, the knowledge base or a ticket, so the recorded call no longer matches. Re-record with--live --record, or undo the change.--livefails with an authentication error. Copy.env.exampleto.env, setANTHROPIC_API_KEY, and runuv run --env-file .env python run_eval.py --live.- A live run gives a different count from 39/40. Drafts vary between runs. That is why the tests replay a recorded run, and why Lesson 4 compares versions on paired cases instead of single numbers.
10. Exercise
Add a fifth grader, no_internal_ids, that fails a reply containing an article id such as KB-112. Customers can't look up those ids. Add it to GRADERS and replay the recorded run.
Verify. Only one recorded reply contains an article id, G22's "(KB-112)"; grep -c 'KB-1[0-9][0-9])' runs/drafts-v1.jsonl finds that one line. So the replay reports 38/40 drafts passing every grader, with G22 newly failing on no_internal_ids. A grader takes (case, draft, kb) and returns a Grade, like the four above. Add one test for it, and uv run pytest tests reports 21 passed.
11. What comes next
Lesson 3 builds an LLM judge for the criterion code can't decide. Before it trusts the judge, it measures it against replies whose correct verdict is already known.

