In Stage 2 you scored an extractor by hand-running a script. In Stage 4 you saw an agent attach a rule to the wrong subject. Both stages ended with the same need: a way to measure quality every time something changes, automatically, so improvements are kept and regressions are caught. This stage builds that system in three parts.
1. Test cases live in a file
Move test cases out of your code into a JSONL file: one JSON object per line, easy to append to and easy to review in version control. Save this as cases.jsonl:
{"ad": "Senior Data Analyst at Northwind, Lisbon. SQL and Python required; Tableau a plus. Hybrid, 2 days remote.", "want": {"company": "Northwind", "location": "Lisbon", "remote": true, "skills": ["sql", "python", "tableau"]}}
{"ad": "We're hiring an ML Engineer to deploy models with Docker and Kubernetes. Fully remote.", "want": {"company": null, "location": null, "remote": true, "skills": ["docker", "kubernetes"]}}
{"ad": "Office-based BI Developer in Monterrey for Acme Corp. Power BI, DAX and SQL Server.", "want": {"company": "Acme Corp", "location": "Monterrey", "remote": false, "skills": ["power bi", "dax", "sql server"]}}
Two habits make a test set valuable over time:
- Every bug becomes a case. When something fails in use, add that input with the right answer before fixing it.
- Keep awkward cases: missing fields, ambiguous wording, inputs the system should refuse.
2. Graders: code first, models where code can’t reach
Save this as grade.py. It has two graders.
import json, re, sys
import requests
from pydantic import BaseModel
OLLAMA = "http://localhost:11434/api/chat"
def norm(value):
"""Normalise before comparing, so formatting differences don't count as errors."""
if isinstance(value, str):
return re.sub(r"[.,;:]+$", "", value.strip().lower())
if isinstance(value, list):
return {norm(v) for v in value}
return value
def code_grade(got: dict, want: dict) -> dict:
"""Field-by-field comparison after normalisation. Deterministic, fast and free: use it wherever you can."""
return {k: norm(got.get(k)) == norm(v) for k, v in want.items()}
class Verdict(BaseModel):
supported: bool
unsupported_claims: list[str]
JUDGE = ("You check answers against a source passage. A claim is supported only if the passage states it for the "
"same subject. List every claim in the answer that the passage does not support. supported is true only "
"if that list is empty.")
def judge(model: str, passage: str, answer: str) -> Verdict:
"""Model-based grader for what code can't check: are all claims supported by the passage?"""
r = requests.post(OLLAMA, json={
"model": model, "stream": False, "format": Verdict.model_json_schema(), "options": {"temperature": 0},
"messages": [{"role": "system", "content": JUDGE},
{"role": "user", "content": f"Passage:\n{passage}\n\nAnswer:\n{answer}"}],
}, timeout=300)
r.raise_for_status()
return Verdict.model_validate_json(r.json()["message"]["content"])
The code grader normalises before comparing. Remember the Stage 2 miss, 'Acme Corp.' against 'Acme Corp'? That was the scorer’s fault, not the model’s. With normalisation, the same extractor on the same three ads scored 12 of 12 fields in our run.
The judge handles what code can’t check: whether every claim in a free-text answer is supported by the source. It is itself a model, so it is a measuring instrument with its own errors. Before using it, measure how well it agrees with you.
3. Calibrate the judge against your own labels
Save this as calibrate_judge.py. It contains six answers we labelled by hand, including the exact mistake the Stage 4 agent made.
import sys
from grade import judge
PASSAGE = ("Full-time employees receive 25 days of annual leave per calendar year, plus public holidays. Unused leave "
"of up to five days can be carried into the first quarter of the next year. Requests go through the HR "
"portal at least two weeks in advance for absences longer than three days.")
# Hand-labelled answers: True = every claim is supported. Include the realistic mistakes you've seen.
LABELLED = [
("Employees get 25 days of annual leave, and up to five unused days can be carried into the next year's first quarter.", True),
("Up to 5 days can be carried over. Requests for carryover must go through the HR portal two weeks in advance.", False),
("Employees get 30 days of annual leave per year.", False),
("Absences longer than three days must be requested through the HR portal at least two weeks ahead.", True),
("Carried-over leave can be used at any time during the next year.", False),
("Public holidays are in addition to the 25 days of annual leave.", True),
]
def main(model: str) -> None:
agree = 0
for answer, label in LABELLED:
v = judge(model, PASSAGE, answer)
agree += v.supported == label
flag = "ok " if v.supported == label else "DISAGREE"
print(f"{flag} label={label!s:5} judge={v.supported!s:5} {answer[:70]}")
print(f"judge agreement with hand labels: {agree}/{len(LABELLED)}")
if __name__ == "__main__":
main(sys.argv[1])
Our results, for two small local models used as judges:
| Answer (shortened) | Our label | Judges |
|---|---|---|
| 25 days, up to five carried into next year’s first quarter | supported | flagged |
| Carryover requests must go through the HR portal two weeks ahead | not supported | not supported |
| 30 days of annual leave | not supported | not supported |
| Absences over three days need two weeks’ notice via the portal | supported | supported |
| Carried-over leave usable at any time next year | not supported | not supported |
| Public holidays are in addition to the 25 days | supported | supported |
Both judges agreed with us on 5 of 6, and both caught the Stage 4 agent’s misattributed rule. The one disagreement is the instructive part. The judge explained: “Employees get 25 days of annual leave (Passage specifies ‘Full-time employees’)”. It was right: the answer generalised from full-time employees to all employees. Our label was too lenient, not the judge too strict.
That is what calibration is for. Disagreements show you where your rubric is ambiguous. Decide the rule (here: qualifiers like “full-time” must be kept), fix the label or the judge’s instructions, and re-measure. Only use a judge for decisions once its agreement with your labels is high on cases like yours, and re-check it whenever you change the judge model.
4. A regression test that fails the build
Save this as test_regression.py and run it with pytest:
"""Run with pytest. Fails if extraction accuracy drops below the last accepted baseline."""
import json, os, pathlib
from extract import extract
from grade import code_grade
MODEL = os.environ.get("EVAL_MODEL", "gemma4:e4b")
BASELINE = 0.90 # raise it when you accept an improvement; never lower it silently
def test_extraction_accuracy_does_not_regress():
cases = [json.loads(l) for l in pathlib.Path("cases.jsonl").read_text().splitlines() if l.strip()]
results = [code_grade(extract(MODEL, c["ad"]).model_dump(), c["want"]) for c in cases]
correct = sum(sum(r.values()) for r in results)
total = sum(len(r) for r in results)
print(f"accuracy {correct}/{total}")
assert correct / total >= BASELINE, f"accuracy {correct}/{total} fell below the baseline {BASELINE:.0%}"
pip install pytest
EVAL_MODEL=<model> pytest -q -s test_regression.py
In our run it printed accuracy 12/12 and passed. The rule that makes this work: raise the baseline when you accept an improvement, and never lower it silently. Run it in continuous integration and on every prompt or model change, and a change that makes things worse can’t ship unnoticed.
Costs and speed
Code graders are free and instant. Judge calls cost a model call each, and a calibration run on six answers took us under a minute locally. Keep the judge for the checks that need it, and run the full evaluation before releases rather than on every keystroke.
Project checklist
- Your Stage 2 cases moved to
cases.jsonl, plus at least five new ones from real failures. -
code_gradewith normalisation, and the Stage 2 false miss gone. - A judge calibrated on at least ten hand-labelled answers, with its agreement rate written down.
-
test_regression.pypassing with a baseline, run on every change.
Next: Stage 6, production: cost, latency, security and monitoring.
Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.