Sub topic 9
Choose graders and metrics
This chapter assumes you can read Python and JSONL, have called an LLM API, and know what a mean and a proportion are. You should also have a dataset with the schema from the earlier chapters, including reference answers or rubrics. Here you decide how each case gets turned into a score, and how those scores become numbers you can act on.
What a grader does
A grader is a function that takes a case and the app's output and returns a score. A metric is how you combine many scores into one number, such as accuracy or a mean rating. These are separate choices. You can change the metric without regrading, but changing the grader means rerunning every case.
Three kinds of grader cover most work:
- Code-based graders use deterministic logic: exact match, regular expressions, JSON schema checks, unit tests on generated code.
- Human graders are people who read the output and score it against a rubric.
- LLM judges are models prompted to score an output against a reference or rubric.
Code-based graders
Prefer code when it works. Code graders are cheap, fast, and give the same answer every time. That makes score changes easy to attribute to the app and not to the grader.
The Python example from the dataset chapter uses exact match after trimming and lowercasing:
def grade(output, reference):
return output.strip().lower() == reference.strip().lower()Exact match suits closed-form tasks such as classification labels, extracted IDs, or multiple-choice letters. It fails badly on free text. The reference "No. Returns are accepted within 30 days of delivery." will not match "No, you can only return items within 30 days of delivery," although both are correct.
Several code checks are more flexible than exact match:
- Normalized match: strip punctuation, collapse whitespace, and normalize numbers and dates before comparing.
- Contains or regex: require key facts, such as "30 days", and forbid wrong ones.
- Structural checks: parse the output as JSON, validate it against a schema, and compare fields.
- Execution checks: run generated code or SQL against tests and compare results.
- Property checks: output length limit, no leaked system prompt, cites only provided documents.
Here is a grader that checks required and forbidden phrases stored on the case. It assumes the case carries optional must_include and must_not_include lists:
import re
def grade_phrases(output, case):
text = output.lower()
required = [p.lower() for p in case.get("must_include", [])]
forbidden = [p.lower() for p in case.get("must_not_include", [])]
has_all = all(re.search(re.escape(p), text) for p in required)
has_none = not any(re.search(re.escape(p), text) for p in forbidden)
return has_all and has_noneCode graders have a common failure: they are precise but narrow. A phrase check passes "We do not accept returns within 30 days" if it only looks for "30 days". Add forbidden patterns for the wrong answers you have seen, and read a sample of passes as well as failures.
Human graders
Humans are the reference point for quality. They catch tone problems, subtle factual errors, and unhelpful answers that rules miss. They are also slow, expensive, and inconsistent unless you constrain them.
To keep human grading usable:
- Give graders a written rubric with anchored levels, not a vague "rate 1 to 5".
- Hide which system version produced an output.
- Have at least two people grade a subset, and compute agreement as covered in the earlier chapter on annotator agreement.
- Record the grader ID and timestamp with each score.
Use humans where they matter most: building the calibration set for a judge, auditing a sample of automated scores, and grading high-stakes slices directly.
LLM judges
An LLM judge scales to free-text outputs at low cost. It also introduces its own errors, so treat it as a measuring instrument that needs checking.
Known judge biases include:
- Position bias: in pairwise comparisons, the judge favors the first or second answer more often than it should.
- Length bias: longer answers get higher scores regardless of correctness.
- Self-preference: a model tends to rate outputs from its own family more highly.
- Leniency: judges often pass answers that a careful human would fail, especially on factual details.
Reduce these with design choices. Give the judge the reference answer when one exists, so it compares instead of guessing. Ask for a binary or small-scale verdict with explicit criteria. Request a short rationale before the verdict, and parse the verdict from a fixed format. Run pairwise comparisons in both orders and count a win only if it holds in both. Set temperature to 0 where the API allows it.
This sketch shows a judge prompt and a parser. The call_model function is a placeholder for your own API call that takes a prompt string and returns text:
JUDGE_PROMPT = """You are grading an answer against a reference.
Question: {input}
Reference answer: {reference}
Candidate answer: {output}
Criteria:
- The candidate must agree with the reference on every factual claim.
- Extra correct detail is fine. Any contradiction or missing key fact fails.
Write one or two sentences of reasoning, then a final line that is exactly
VERDICT: PASS or VERDICT: FAIL."""
def judge(case, output, call_model):
prompt = JUDGE_PROMPT.format(
input=case["input"], reference=case["reference"], output=output
)
reply = call_model(prompt)
last = reply.strip().splitlines()[-1].strip()
if last == "VERDICT: PASS":
return True
if last == "VERDICT: FAIL":
return False
raise ValueError(f"Unparseable judge reply: {reply!r}")Raising on an unparseable reply is deliberate. Silently counting it as a failure would hide a broken prompt or a changed model behavior inside your accuracy number.
The next chapter covers how to calibrate a judge against human labels. Until you have done that, report judge-based scores as provisional.
Compare the grader types
| Property | Code-based | Human | LLM judge |
|---|---|---|---|
| Cost per case | Near zero | High | Low to moderate |
| Speed | Instant | Hours to days | Seconds |
| Repeatability | Exact | Varies by person | Mostly stable, not exact |
| Handles free text | Poorly | Well | Well |
| Main risk | Too narrow or too loose | Inconsistency, cost | Bias, drift when the judge model changes |
| Best use | Closed-form and checkable properties | Calibration, audits, high stakes | Scale on open-ended outputs |
A mixed approach is normal. Use code for everything it can check, and an LLM judge for what remains. Keep a human-labeled sample to check both.
Choose the score type
A grader can return different kinds of values, and the choice affects what you can conclude.
- Binary pass/fail is the easiest to define, calibrate, and aggregate. Start here.
- Ordinal scales (1 to 5) capture degrees of quality but are harder to keep consistent. Raters drift toward the middle, and the gaps between levels are not equal.
- Multiple criteria, such as correctness, completeness, and tone, scored separately, tell you which dimension broke. Avoid collapsing them into one vague score.
- Pairwise preference compares two outputs. It is useful for choosing between versions, but it does not tell you whether either is good enough.
Decompose a quality bar into several binary checks when you can. "Is the answer correct?", "Does it cite the policy?", and "Is it under 100 words?" are each easier to grade than "Is it good?".
Choose metrics
The metric turns per-case scores into a summary. Match it to the decision you need to make.
- Accuracy or pass rate: the fraction of cases that pass. It is the default for binary scores.
- Precision and recall: use these when the task is detecting something, such as flagging policy violations. Precision is the share of flagged items that are correct. Recall is the share of real items that were flagged. Accuracy hides imbalance, since a classifier that never flags anything scores 95% when 5% of cases are violations.
- Mean score: for ordinal or numeric scales. Report the distribution as well, because a mean of 3.5 can hide many 1s and 5s.
- Win rate: for pairwise comparisons, ties counted separately.
- Critical-failure rate: the share of cases with a severe error, such as a harmful or confidently wrong answer. Track it separately from average quality, since a small number of severe failures can matter more than many minor ones.
- Cost and latency: record these alongside quality so you see trade-offs.
Always compute metrics per slice, using the tags from your schema. An overall pass rate of 88% can hide a 50% pass rate on a small but important slice. The run_eval function from the dataset chapter already returns accuracy per tag. When you report, also include the number of cases behind each figure and a confidence interval from the dataset-size chapter.
Common errors
- Using exact match on free text, then concluding the app got worse when it only rephrased.
- Letting the judge see information the app's user would not, or giving it no reference when one exists.
- Averaging a 1 to 5 scale across graders who use the scale differently.
- Counting grader errors, such as timeouts or unparseable replies, as app failures.
- Changing the judge prompt or model between runs, then comparing the scores as if they were comparable. Pin the judge model and prompt, and version them with the dataset.
- Reporting only the overall score.
Exercise
Your app extracts an order number from customer emails and also writes a short, friendly reply. Which grader would you choose for each part, and which metric would you report for a task where only 4% of emails contain a fraudulent request that the app must flag?
Show answer
Use a code-based grader for order number extraction: normalized exact match against the reference, since the answer is a closed-form string. Grade the friendly reply with an LLM judge using a rubric of binary criteria (acknowledges the issue, correct policy, appropriate tone), calibrated against a human-labeled sample. For fraud flagging, report precision and recall on the flag, not accuracy, because a system that never flags anything would score 96% accuracy while catching nothing. Also report all of them per slice.
Exercise
A judge scores answers that are 150 words long at 92% pass and answers under 50 words at 70% pass. Humans on a sample rate both groups at about 80%. What is the likely problem, and what two changes would you try?
Show answer
The judge shows length bias, favoring longer answers regardless of correctness. Give the judge explicit criteria that say extra length earns no credit and that only factual agreement with the reference counts, and require a reasoned verdict in a fixed format. Then recheck the judge against the human labels, split by answer length, to confirm the gap closed.