Lesson 18.1 · 1 of 5 · 4 min read · Reviewed 24 Nov 2026
Code-based graders
By the end, you can
- Write code-based graders.
- Know what code graders can and can't check.
What code can check
| Check | Example |
|---|---|
| Format | Parses as JSON and matches the schema |
| Exact match | Category label equals “billing” |
| Numeric tolerance | Extracted total within 0.01 of expected |
| Contains or excludes | Includes the order id; doesn’t include “guarantee” |
| Length | Under 120 words |
| Tool use | Called lookup_order before issue_refund |
| Citations | Every cited id exists in the provided sources |
A small grader
import json
def grade(case, output):
results = {}
try:
data = json.loads(output)
results["valid_json"] = True
except ValueError:
return {"valid_json": False}
results["has_fields"] = all(k in data for k in ("category", "priority"))
results["category_ok"] = data.get("category") == case["expected"]["category"]
results["short_reason"] = len(data.get("reason", "").split()) <= 40
return results
Return a result per check, not one number, so you can see which part failed.
Fuzzy matching
For text answers with a known value, normalise first: lowercase, strip punctuation, map “30 days” and “thirty days” to the same form. Beyond simple normalising, switch to a model graderLLM-as-judge: Using a language model with a rubric to grade another model’s outputs..
Key points
- Code graders are fast, cheap, and give the same result every time: use them wherever a rule can decide.
- Good fits: schema validity, required fields, exact or numeric match, length, banned phrases, tool called.
- They can't judge meaning, tone or faithfulness well; use model graders for those.
Write a code grader for ticket JSON
Write a code-based grader that returns one result per check, so you can see exactly which part of an output failed.
You will have: A grade() function and a per-check pass table for four model outputs.
Steps
- Read the four sample outputs and the expected category for each case.
- Fill in grade() so it parses JSON, checks the required fields, the category and the reason length.
- Return a dict of check name to True or False, not a single number.
- Run it and read the per-check totals to see which check fails most.
Done when
- valid_json passes 3 of 4 outputs (one is not JSON).
- category_ok passes 2 of 4.
- Every result is a dict of named checks.
Open in the Playground No API key needed.
Starter code (Python)
import json
CASES = [
{"id": "t1", "expected": {"category": "billing"}, "output": '{"category": "billing", "priority": "high", "reason": "Charged twice for one order."}'},
{"id": "t2", "expected": {"category": "delivery"}, "output": '{"category": "billing", "priority": "low", "reason": "Parcel is late."}'},
{"id": "t3", "expected": {"category": "account"}, "output": 'Category: account, priority: medium'},
{"id": "t4", "expected": {"category": "delivery"}, "output": '{"category": "delivery", "reason": "Wrong address on the label."}'},
]
CHECKS = ["valid_json", "has_fields", "category_ok", "short_reason"]
def grade(case, output):
results = {name: False for name in CHECKS}
# TODO: parse output with json.loads; if it fails, return results with valid_json False
# TODO: has_fields: both "category" and "priority" are present
# TODO: category_ok: data["category"] equals case["expected"]["category"]
# TODO: short_reason: the reason has at most 40 words
return results
totals = {name: 0 for name in CHECKS}
for case in CASES:
r = grade(case, case["output"])
print(case["id"], r)
for name in CHECKS:
totals[name] += r[name]
for name in CHECKS:
print(f"{name}: {totals[name]}/{len(CASES)}")
Show a solution
import json
CASES = [
{"id": "t1", "expected": {"category": "billing"}, "output": '{"category": "billing", "priority": "high", "reason": "Charged twice for one order."}'},
{"id": "t2", "expected": {"category": "delivery"}, "output": '{"category": "billing", "priority": "low", "reason": "Parcel is late."}'},
{"id": "t3", "expected": {"category": "account"}, "output": 'Category: account, priority: medium'},
{"id": "t4", "expected": {"category": "delivery"}, "output": '{"category": "delivery", "reason": "Wrong address on the label."}'},
]
CHECKS = ["valid_json", "has_fields", "category_ok", "short_reason"]
def grade(case, output):
results = {name: False for name in CHECKS}
try:
data = json.loads(output)
except ValueError:
return results
results["valid_json"] = True
results["has_fields"] = all(k in data for k in ("category", "priority"))
results["category_ok"] = data.get("category") == case["expected"]["category"]
results["short_reason"] = len(data.get("reason", "").split()) <= 40
return results
totals = {name: 0 for name in CHECKS}
for case in CASES:
r = grade(case, case["output"])
failed = [name for name in CHECKS if not r[name]]
print(case["id"], "all checks pass" if not failed else "failed: " + ", ".join(failed))
for name in CHECKS:
totals[name] += r[name]
for name in CHECKS:
print(f"{name}: {totals[name]}/{len(CASES)}")