Write Graders in Code
A test set says what a good answer must do, but someone still has to look at each answer and decide whether it did. A grader makes that decision automatically, and many of those decisions can be made by a few lines of ordinary Python: does the answer mention the fact it must mention, does it avoid the phrase it must never use, did it pick the right action? This page explains how to write such graders, how to read the scores they produce, and where code stops being able to judge.
A grader is a function
Take a small example: a help assistant for a public library. Its reply is structured output with two fields, the answer it shows the member and an action such as "answer" or "handoff" (pass the question to a person). One test case for it holds the question and a statement of what a good reply must do.
A grader takes two things, the test case and the app's output for it, and returns a verdict: pass or fail, together with a short reason. The reason matters as much as the verdict. "Fail" alone sends you hunting through the answer; "fail: missing 'two renewals'" tells you where to look.
- Test case input + what must hold
- Output the app's reply
- Grader one question
- Verdict pass or fail + reason
- Test case to Grader
- Output to Grader
- Grader to Verdict
case = {
"id": "renew-limit-03",
"input": "Can I renew my book a third time?",
"must_include": ["two renewals"],
"failure_mode": "wrong policy",
}
output = {
"answer": "Each loan allows two renewals, so a third one is not possible.",
"action": "answer",
}
def grade_required_facts(case, output):
text = output["answer"].casefold()
missing = [f for f in case["must_include"] if f.casefold() not in text]
if missing:
return {"passed": False, "reason": "missing: " + ", ".join(missing)}
return {"passed": True, "reason": "all required facts present"}
print(grade_required_facts(case, output))
# {'passed': True, 'reason': 'all required facts present'}A grader written in code like this one is called a code grader. Its verdict depends only on what it is given: run it a thousand times on the same recorded answer and it says the same thing every time. It also runs in a fraction of the time a person or a model call would take and costs nothing per verdict, so it can run over every case each time the app changes.
There are other kinds of grader. A person can judge an answer, and so can a second language model given a written criterion. Both can weigh meaning that code cannot, but a person is slow and expensive, and a model grader costs a call per verdict and may give a different verdict on a second run. That is why the usual advice, from Anthropic's engineering guide on evals among others, is to choose a code grader wherever an objective rule can decide, and to reach for the other kinds only where it cannot.
True or false?
Running the same code grader twice on the same recorded answer can give two different verdicts.
False. Code with no randomness in it computes the same result from the same inputs, so the verdict repeats exactly. Variation comes from the model producing new answers, not from the grader.
A grader that returns only True or False makes failures slower to investigate than one that also returns a reason.
True. Without a reason you have to reread the answer to find out what went wrong; the reason points straight at it.
One grader, one question
It is tempting to write one big grader that checks everything a good answer needs and returns a single pass or fail. The trouble shows up the first time it fails: which part broke? The answer might have left out a fact, used a forbidden phrase or chosen the wrong action, and the single verdict cannot say which.
Keeping each grader to one yes-or-no question removes the guesswork. A failed check then names the problem by itself, and each grader's pass rate tracks one kind of failure, so you can see that kind rise or fall on its own. Small graders are also easier to get right, because each one has a single rule to test.
| Grader | Its one question | Verdict on one reply |
|---|---|---|
| required_facts | Does the answer state every required fact? | pass |
| forbidden_phrases | Does it avoid every forbidden phrase? | pass |
| action | Is the action field the expected value? | fail: expected handoff, got answer |
| length | Is the answer at most 80 words? | pass |
Read across the table: one combined grader would have reported "fail" for this reply. Four separate graders report that the wording was fine and the action was wrong, which tells you to look at how the app decides when to hand off, not at its phrasing. A case can run through several graders; you still learn exactly which question it failed.
True or false?
Splitting one grader into four means a reply that passes all four is judged more strictly than before.
False. The rules are the same; they are only reported separately. What changes is that a failure now says which rule it broke.
What code can decide
Code can decide any question with an objective rule: one where you could write down, in advance, exactly what counts as yes. For a language model's reply, most such questions fall into a few families.
| Check | What it asks | Example from a test case |
|---|---|---|
| Required content | Does a fact, phrase or number appear? | mentions "two renewals" |
| Forbidden content | Is something absent that must never appear? | no promise to waive a fee, no email address |
| Structured field | Does a field of the structured output hold the expected value? | action == "handoff" |
| Format | Is the output shaped as required? | parses as JSON, date written as YYYY-MM-DD |
| Length | Is it within a size limit? | at most 80 words |
Each family is a few lines of Python. The details are where code graders usually go wrong, so they are worth getting right once.
import json
import re
def grade_forbidden(case, output):
for phrase in case["must_not_include"]:
if re.search(r"\b" + re.escape(phrase) + r"\b", output["answer"], re.IGNORECASE):
return {"passed": False, "reason": f"forbidden phrase: {phrase}"}
return {"passed": True, "reason": "no forbidden phrase"}
def grade_action(case, output):
expected, got = case["expected_action"], output.get("action")
if got != expected:
return {"passed": False, "reason": f"expected {expected}, got {got}"}
return {"passed": True, "reason": f"action is {expected}"}
def grade_json(case, raw_reply):
try:
json.loads(raw_reply)
except json.JSONDecodeError as error:
return {"passed": False, "reason": f"not valid JSON: {error}"}
return {"passed": True, "reason": "valid JSON"}
def grade_length(case, output):
words = len(output["answer"].split())
if words > case["max_words"]:
return {"passed": False, "reason": f"{words} words, limit {case['max_words']}"}
return {"passed": True, "reason": f"{words} words"}A few points in this code are easy to miss:
- Case. Python's
inis case-sensitive, so"Two renewals"would not be found by searching for"two renewals". The first grader avoids this by comparing thecasefold()versions of both strings. The Python docs recommendcasefold()for caseless comparison because it goes further thanlower(), which leaves some characters, such as'ß', unchanged. - Whole words.
inalso matches inside longer words: searching for"fee"finds it in"feedback". Python'sremodule searches text with a regular expression: a pattern written in a small notation that describes the text to find, in which most characters stand for themselves and a few have a special meaning. The pattern\bmarks the edge of a word, sore.search(r"\bfee\b", text)finds only the word itself. Because the phrase becomes part of a pattern, it goes throughre.escapefirst, so a dot or a bracket in it is read as plain text and not as pattern syntax. - Search, not match.
re.searchlooks for the pattern anywhere in the text.re.matchonly looks at the very start, which is rarely what a content check means. - Format errors are verdicts. The format grader reads the raw reply text, before any field is taken out of it.
json.loadsraisesjson.JSONDecodeErroron text that is not valid JSON. The grader catches it and turns it into a fail with the parser's message as the reason, instead of letting one broken reply stop the whole run. - Words, not characters.
len(text)counts characters;len(text.split())counts words, becausesplit()with no argument treats any run of spaces and line breaks as one separator.
True or false?
The check "fee" in answer treats a reply that says "Thanks for the feedback" as containing the word fee.
True. For strings, in tests for a substring anywhere in the text, and "fee" is the start of "feedback". A word-boundary pattern such as \bfee\b avoids this.
re.match(pattern, text) finds the pattern wherever it appears in the text.
False. re.match only matches at the beginning of the string. re.search scans the whole text, which is what a required- or forbidden-content check needs.
Reading pass rates
Once every grader has run over every case, each grader has a pass rate: the share of the cases it checked that passed. If the action grader passed 34 of 40 cases, its pass rate is \( 34 / 40 = 85\% \).
It is tempting to average everything into one number for the app. That number hides the very thing you wanted to learn. Suppose four graders each ran on 40 cases:
- required_facts 36/40
- forbidden_phrases 40/40
- action 24/40
- length 38/40
The average of these four rates is about 86%, which sounds fine. The chart says something else: three graders are close to full marks, and the app picks the wrong action in 16 cases out of 40. Reported per grader, the problem is visible at a glance; averaged, it disappears.
The same goes for failure modes. When each test case is tagged with the failure mode it probes, the pass rates can be grouped by tag as well, so you see which kinds of failure the app still makes. And next to each rate goes the list of failing cases with their reasons, because a rate tells you how much is wrong and only the failing cases tell you what.
| Case | Failure mode | Reason |
|---|---|---|
| lost-card-07 | missed handoff | expected handoff, got answer |
| fine-dispute-02 | missed handoff | expected handoff, got answer |
| opening-hours-11 | needless handoff | expected answer, got handoff |
Reading the failing cases also checks the grader itself. Each one is either a real mistake by the app or a case where the grader rejected a good answer, and only reading it tells you which. A rate of 100% is not the goal either: a set the app passes completely shows nothing about where it still fails.
True or false?
If the average pass rate over all graders stays the same between two versions of an app, no kind of failure got worse.
False. One grader can drop while another rises by the same amount, and the average stays level. Only per-grader rates show the drop.
A grader's pass rate is calculated over the cases that grader checked, not over every case in the set.
True. A grader that only applies to some cases, such as an action check that needs an expected action, is measured on those cases alone.
What code cannot judge
Every check above compares characters: a phrase is present or it is not, a field equals a value or it does not. That works when the rule is about the text itself. It breaks when the rule is about what the text means, because the same meaning can be written in many ways.
The first way this goes wrong is a strict check that fails a correct answer. The required phrase is "two renewals", and here are three replies:
| Reply | Correct? | required_facts says |
|---|---|---|
| You can have two renewals per loan. | yes | pass |
| You may renew a book twice, but not a third time. | yes | fail: missing two renewals |
| There is no limit of two renewals, renew as often as you like. | no | pass |
The second reply is right and fails; the third is wrong and passes. You can loosen the check with a list of accepted phrasings or a regular expression, and that helps for short, predictable facts such as a number or a date. But each loosening also lets more wrong answers through, and no list covers every way a person could say "twice". Anthropic reports a real case of this. On one benchmark a model first scored 42%. Part of the reason was the grader: it expected 96.124991 followed by more digits, so it rejected the answer 96.12. Once this and other problems were fixed, among them unclear task instructions and a too-restrictive agent setup, the score rose to 95%. Part of the low first score measured the grader, not the model.
The second limit is any quality that depends on meaning. Whether a claim in the answer is supported by a source text, such as the policy page the assistant was given, cannot be settled by searching for words: a supported claim may be paraphrased, and an unsupported one may reuse the source's words in a new order. The same holds for whether an answer is polite, whether it actually addresses the question, or whether its advice is sound.
True or false?
When a code grader fails an answer, the answer is wrong.
False. A strict text check can fail a correct answer that is worded differently. Reading the failing case is how you tell an app mistake from a grader mistake.
Checking that every word of a claim appears in the source text does not prove the claim is supported by it.
True. The same words can be rearranged into a statement the source never makes, so support depends on meaning, not on shared words.