Course 2 of 6 in the Engineering Series, which builds one AI platform in Python for Larkfield Supply, a fictional company. In the lesson, E1 to E6 are the six courses; you can skip mentions of other lessons on a first read. Reading needs no setup. To run the code, you need the course repository (tag e2-m3-l2) and the earlier lessons.
You'll leave with a judge as a versioned prompt file (grounded_figures@v1, and @v2 for the borderline set) and two labeled sets split by source (152 clear-cut items, 210 borderline ones). Part 2 measures the judge against them.
In one screen
- Use it on Monday: Stop reporting raw agreement for an LLM judge. Report the share of failures it catches and the share of good answers it passes, each with an interval.
- The picture: A judge is a classifier for one failure mode, kept as a versioned prompt file with its examples, and measured on labels it never saw.
- The decision: One judge per failure mode, PASS or FAIL plus UNKNOWN, critique before verdict, pinned to one alias. Agreement with your labels can hide a judge that catches nothing: part 2 scores the failures it catches and the good answers it passes, separately.
- You'll run:
parse_verdicton two judge replies. "Looks good to me!" comes backlabel='unknown'; the JSON reply comes backlabel='fail'with its critique, "2.5M is not in clause 6".
Why this matters
On 12 November 2026 I ran my first judge on two real models, and both agreed with every one of my 76 test labels. It looked perfect. It proved very little, and the fastest way to see why is a judge that does nothing at all.
If 5% of your outputs fail, a judge that always says PASS agrees with your labels 95% of the time. It catches nothing. Here it is, scored by the code you'll write in this lesson, on 100 made-up labels (5 failures, 95 passes):
TPR (failures caught) 0.0% 95% CI 0.0% to 43.4%
TNR (good passed) 100.0% 95% CI 96.1% to 100.0%
Raw agreement hides a useless judge. And with 5 labeled failures, the interval on catching them runs from 0 to 43%: you can't know much about any judge.
An interval in one breath. "95% CI" here means a 95% confidence interval: a range built by a procedure that captures the true rate in 95% of repeated samples, not a 95% chance that the true rate is in this one range. Read it as the true rates this data can't rule out. Fewer items means a wider range, which is why 5 failures give you 0 to 43%; the statistics primer shows why, before module 4 leans on it.
This lesson keeps three ideas at its core: score the judge like a classifier (TPR and TNR, its true positive and true negative rates), measure it on labels it never saw, and never trust raw agreement. Kappa, the replay machinery and the hard-case critiques are in Going deeper at the end of part 2, for when you want them.
The idea
An LLM judge is a classifier. Its job is to say, for one output, whether one failure is present. So we score it like a classifier, with positive meaning "failure present" (the convention of Hamel Husain and Shreya Shankar, who teach evals):
TPR (true positive rate) = failures the judge catches / failures the labels contain
TNR (true negative rate) = good outputs the judge passes / good outputs the labels contain
You need both, measured on labels the judge never saw while you were writing it. The build follows the practice most evaluation guides now recommend (as of November 2026):
- One failure mode per judge. Ours is
grounded_figures: the answer states a figure the source doesn't support. A plain number check (lesson 3.1) needs the right figure in hand; this judge is for when you don't have it: a figure from the wrong clause, a period that starts on the wrong day. - Binary, plus UNKNOWN. PASS or FAIL forces a decision. UNKNOWN is an honest way out (Anthropic recommends it) and never counts as a pass.
- Critique before verdict. The critiques on your labels become the judge's few-shot examples (worked examples pasted into the prompt so the model sees what a good answer looks like; Husain calls this "critique shadowing").
- A labeled set split three ways. Train, dev and test are three piles that never mix: train gives the examples, dev is where you tune the prompt, and test is scored once, at the end, so the number you report comes from items you never tuned on. How many labels per pile is in Going deeper, at the end of part 2.
- Versioned and pinned. The prompt is a file with a version and a hash; the model is a gateway alias mapped to one model id, a dated snapshot where the provider offers one. Change either and the old rates no longer describe the judge.
Build it
In this part we build everything a measurement needs before we measure: the judge as a file, its frozen examples, the model it calls, a parser that never mistakes a shrug for a pass, and labels the judge has never seen.
Go to this lesson's tag:
git checkout e2-m3-l2 && uv sync
Only the gateway run in part 2, step 9, needs the stack. Versions and the files this tag adds: Going deeper, at the end of this page.
Step 1: the judge is a file
What to notice. The front matter makes the judge auditable: name, version, alias, and the one failure mode in a sentence. The body spends most of its words on near misses (right figure, wrong unit, period or starting point) and on what's out of scope, so a terse answer isn't failed.
src/aip/evals/judges/grounded_figures/v1.md, the whole file:
---
name: grounded_figures
version: 1
model: smart
failure_mode: The answer states a figure (amount, duration, date, quantity, percentage) that the source does not support.
---
You check one failure mode in answers written by Larkfield Supply's document assistant.
FAILURE: the answer states a figure (an amount, a duration, a date, a quantity or a percentage) that the SOURCE does not support. A figure is supported when the source states it, states it in another unit or format (EUR 5,000,000 and EUR 5 million are the same), or when it follows from the source by simple arithmetic shown or obvious in the answer. A figure taken from the wrong clause, from a condition that does not apply to the question, or given with the wrong unit, period or starting point (per month for per year, business days for calendar days, from the order for from delivery) is not supported. Wrong arithmetic is not supported.
Not this failure: style, length, tone, missing detail, or an answer that says the source does not contain the information. Those are PASS for this check.
If you cannot tell from the SOURCE whether the figure is supported, answer UNKNOWN.
Write a short critique first (one or two sentences naming the figure and the clause), then the verdict.
{examples}
SOURCE: {source}
QUESTION: {question}
ANSWER: {answer}
Reply with JSON only: {{"critique": "...", "verdict": "PASS" | "FAIL" | "UNKNOWN"}}
The doubled braces are there because the file is a Python format string.
Step 2: the examples are part of the judge
The 16 few-shot examples, the train split of the labeled set (step 5), are frozen beside the prompt. One row of src/aip/evals/judges/grounded_figures/v1.examples.jsonl (JSONL is one JSON object per line):
{"id": "gf-01-1", "split": "train", "source_id": "src-01", "source": "Returns: unused items may be returned within 30 days of delivery. Custom-cut items cannot be returned.", "question": "How long do customers have to return unused items?", "answer": "Within 30 days of delivery.", "label": "pass", "critique": "30 days matches the returns clause."}
The judge is the prompt the model receives, examples included. If the examples came from "whatever rows are marked train today", two runs of the same judge could send different bytes. Frozen with v1, the judge is one unit you can hash, validate and pin.
Step 3: the model interface, on E1's client
Course 1 (E1) already built the client evals need, with retries, deadlines, traces and cost: aip.llm.Client, the one way platform code calls a model. model.py binds it to an alias and to the eval-runner's own key, so an eval never spends a production agent's budget.
What to notice. GatewayModel is a thin wrapper: one alias, E1's client with the eval settings, and every call tagged eval.
From src/aip/evals/model.py (the whole file, with the offline ScriptedModel, is in Full code at the end of part 2):
class GatewayModel:
"""A gateway alias (fast, smart) through aip.llm.Client, on AIP_EVAL_GATEWAY_KEY (agent eval-runner).
Sampling parameters are opt-in per alias in the settings (AIP_SAMPLING), never sent by default."""
def __init__(self, alias: str, client: Client | None = None):
from aip.config import get_settings
from aip.evals.gate_v1 import eval_settings
self.name = alias
self.client = client or Client(settings=eval_settings(get_settings()))
def complete(self, messages, tools=None) -> Completion:
return self.client.complete(self.name, messages, tools=tools, tags=("eval",))
eval_settings makes every judge call use the eval-runner's own gateway key (AIP_EVAL_GATEWAY_KEY, from lesson 2.1), and ScriptedModel lets the tests run with no key and no stack. Going deeper, at the end of part 2, has the details.
Step 4: the judge, rendered and parsed
What to notice. Three things, one per method:
prompt_idhashes the template with its examples, so editing either changes the id, and an old validation visibly stops applying.renderis the one way to build the prompt, for validation and for the runner's judge check in lesson 4.2, which the release gate runs.graderecordsreply.model, the model the gateway says answered.
From src/aip/evals/judge.py, the heart of the Judge class (the whole file is in Full code at the end of part 2):
@property
def fixed_prompt(self) -> str:
"""Everything except the item: the template with its examples. Validated as one unit."""
return self.template.replace("{examples}", self.shots())
@property
def prompt_id(self) -> str:
return f"{self.name}@v{self.version}#{prompt_hash(self.fixed_prompt)}"
def shots(self) -> str:
return "\n\n".join(
f"<example>\nSOURCE: {e['source']}\nQUESTION: {e['question']}\nANSWER: {e['answer']}\n"
f'OUTPUT: {json.dumps({"critique": e["critique"], "verdict": e["label"].upper()})}\n</example>'
for e in self.examples)
def render(self, source: str, question: str, answer: str) -> str:
"""The one way to build the prompt, so validation and the gate send the same bytes."""
return self.template.format(source=source, question=question, answer=answer, examples=self.shots())
def grade(self, model: ChatModel, source: str, question: str, answer: str) -> Verdict:
prompt = self.render(source, question, answer)
reply = model.complete([{"role": "user", "content": prompt}]) # sampling: per alias, opt-in
verdict = parse_verdict(reply.text or "")
verdict.model = reply.model
return verdict
load_judge reads the file from step 1 and its frozen examples. Then the line I'd defend hardest in a review:
def parse_verdict(reply: str) -> Verdict:
"""Read {"critique": ..., "verdict": PASS|FAIL|UNKNOWN}. Anything else is unknown, not a pass."""
match = re.search(r"\{.*\}", reply, re.DOTALL)
try:
data = json.loads(match.group(0)) if match else {}
except json.JSONDecodeError:
data = {}
label = str(data.get("verdict", "")).strip().lower()
if label not in ("pass", "fail", "unknown"):
return Verdict("unknown", f"unparseable judge reply: {reply[:120]!r}")
return Verdict(label, str(data.get("critique", "")))
Anything but a clean PASS, FAIL or UNKNOWN becomes unknown. A judge that answers "Looks good to me!" hasn't passed anything:
uv run python -c "from aip.evals.judge import parse_verdict; print(parse_verdict('Looks good to me!')); \
print(parse_verdict('{\"critique\": \"2.5M is not in clause 6\", \"verdict\": \"FAIL\"}'))"
Verdict(label='unknown', critique="unparseable judge reply: 'Looks good to me!'", model='')
Verdict(label='fail', critique='2.5M is not in clause 6', model='')
Try it 1 (3 min). Predict the label
parse_verdictgives each of these replies, then run them the same way (the answer is in Check yourself, at the end of this page):PASSon its own;Sure! {"critique": "5,000,000 matches clause 6", "verdict": "pass"}; and{"critique": "close enough", "verdict": "MOSTLY PASS"}.
Step 5: two labeled sets
The first set, the clear-cut one (default in the commands), is data/larkfield/evals/judge_labels/grounded_figures.jsonl: 152 items. Its builder says how it was made:
data/larkfield/evals/_build/make_judge_labels.py, its docstring:
"""Writes the labeled set for validating the grounded_figures judge.
Every answer and every label below was written and checked by hand against its
source: fail = the answer states a figure the source does not support; pass =
every figure is supported, or the answer says the source does not say. Style,
length and missing detail are not this failure mode.
38 questions x 4 answers = 152 items over 27 distinct sources, 78 pass and 74 fail.
No source text appears in two splits: train 16 (8/8, the few-shot examples),
dev 60 (31 pass, 29 fail), test 76 (39 pass, 37 fail).
Run: uv run python data/larkfield/evals/_build/make_judge_labels.py
"""
Labels by one labeler, on fictional data. The split is by source: if a passage sat in train and test, the examples would hand the judge a test answer. The liability cap from lesson 1.2:
{"id": "gf-05-3", "split": "dev", "source_id": "src-05", "source": "Northgate's total aggregate liability under this agreement shall not exceed EUR 5,000,000 per contract year.", "question": "What is the liability cap?", "answer": "EUR 2.5 million per contract year.", "label": "fail", "critique": "EUR 2.5 million does not appear; the cap is EUR 5,000,000."}
That set turned out to be too easy (part 2, step 9, shows how I found out). So the tag carries a second one, the borderline set: 210 items built where judges split, labeled by me and checked by an independent second labeler (an AI agent, not a second person). Going deeper (end of part 2) has its full provenance.
One sentence from its README matters here: "It does not sample production traffic, so its TPR and TNR are not estimates of a judge's accuracy on real answers." In your platform, the labels come from the person who knows the domain, reviewing real outputs (lesson 3.3).
Check yourself
- Try it 1.
unknown,pass,unknown. A bare PASS has no JSON, so there's nothing to read. Chatter around valid JSON is fine, and lowercase is fine. "MOSTLY PASS" isn't one of the three verdicts, so it can't count as a pass. Would you have shipped a parser that let the first or the last one through?
Part 2: validate the judge
Why this matters
On 12 November 2026 my first judge agreed with every one of my 76 test labels on two real models, and I still couldn't tell you how good it was. This part is about the numbers that would have told me: the share of failures it catches, the share of good answers it passes, and how wide each one really is. You'll build the scoring, run the judge on the held-out split, and read what happened when real models judged hard cases.
Build it, continued
Step 6: scoring the judge like a classifier
A judge is a classifier: for each answer it says "failure" or "no failure". So you score it the way you'd score any classifier, by counting four outcomes against the human labels. Remember that positive means "failure present", so the names read like this:
tp, true positive: a real failure the judge called FAIL. Good.fn, false negative: a real failure the judge let through. The dangerous miss.tn, true negative: a good answer the judge called PASS. Good.fp, false positive: a good answer the judge flagged. A false alarm.
TPR is tp out of all real failures; TNR is tn out of all good answers. Laid out as a grid, these four counts are what people call a confusion table, and you'll see one printed in step 8.
What to notice. UNKNOWN lands on the wrong side both times: fn counts any failure the judge didn't call FAIL, fp any good answer it didn't call PASS.
From src/aip/evals/judge.py, the start of score_validation:
def score_validation(judge_id: str, model: str, split: str, human: list[str], judged: list[str],
ids: list[str]) -> Validation:
"""Compare judge labels to human labels. Unknown counts against the judge (a miss either way)."""
pairs = list(zip(human, judged, strict=True))
tp = sum(h == "fail" and j == "fail" for h, j in pairs)
fn = sum(h == "fail" and j != "fail" for h, j in pairs)
tn = sum(h == "pass" and j == "pass" for h, j in pairs)
fp = sum(h == "pass" and j != "pass" for h, j in pairs)
n = len(pairs)
if n == 0:
raise ValueError(f"no labeled items in split {split!r}")
It counts that way because a gate can't act on UNKNOWN. A split with no labeled failures (or passes) gets None, not 0%, 100% or a crash. The function then computes Cohen's kappa too; Going deeper explains it.
Step 6, continued: an interval on each rate
A rate from 33 labeled failures is a guess about the judge. So each rate gets an interval, wide because there are only this many items. A 95% interval is a range built by a procedure that captures the true rate in 95% of repeated samples, not a 95% chance that the true rate is in this one range (the statistics primer has the picture).
Here's why the recipe matters. Take a judge that caught 33 of 33 failures, and two ways to draw its interval:
| Recipe | Interval for 33 of 33 |
|---|---|
| Textbook: the rate plus or minus 1.96 standard errors | 100% to 100% |
| Wilson | 89.6% to 100% |
The textbook recipe claims certainty from 33 items. Here's how it gets there:
- The standard error measures how much the rate would wobble from one sample to the next.
- It's computed from the observed rate. At 33 of 33 every item agrees, so it comes out as zero.
- Plus or minus zero is no range at all.
Wilson stays honest at the edges: it says "at least about 90%, and 33 items can't tell you more". That's why Bowyer et al. (2025) recommend it for small eval sets.
Two things set the width. Fewer items, wider range. And rates near 50% get wider ranges than rates near 0% or 100%, because they have more room to wobble.
Lesson 4.4 is where you write the whole statistics module; here's the one function the judge uses.
What to notice. wilson never returns a range of zero width, even at 0 out of n or n out of n.
From src/aip/evals/stats.py, z_for and wilson:
def z_for(confidence: float = 0.95) -> float:
"""Two-sided normal quantile: 1.96 for 95%."""
return NormalDist().inv_cdf(1 - (1 - confidence) / 2)
def wilson(passes: float, n: float, confidence: float = 0.95) -> tuple[float, float]:
"""Wilson score interval for a pass rate. Sane at 0/n and n/n. Takes a fractional n (effective cases)."""
z = z_for(confidence)
center = (passes + z * z / 2) / (n + z * z)
half = z * sqrt(passes * (n - passes) / n + z * z / 4) / (n + z * z)
return max(0.0, center - half), min(1.0, center + half)
Try it 2 (5 min). Here is a real result you'll meet again later on this page. The cheap judge, on 67 hard items: of 33 real failures it caught 32 and passed 1; of 34 good answers it passed 29, flagged 1 and answered UNKNOWN on 4. Work out TPR and TNR by hand. Before you get the intervals, guess which of the two will be wider. Then run
uv run python -c "from aip.evals.stats import wilson; print(wilson(32, 33), wilson(29, 34))". Which of the two numbers would worry you more if this judge guarded a release, and why? (Answer in Check yourself.)
Step 7: validate on the held-out split
What to notice. The leaked check. If any of the judge's own examples sit in the split you're validating on, it refuses: that's an open-book exam.
From src/aip/evals/judge.py:
def validate_judge(judge: Judge, model: ChatModel, labeled: list[dict], split: str = "test") -> Validation:
"""Run the judge on one split of a labeled set. The few-shot examples are the judge's own (its
frozen train split), so the prompt validated here is the prompt the gate sends."""
rows = [row for row in labeled if row["split"] == split]
leaked = {e["id"] for e in judge.examples} & {r["id"] for r in rows}
if leaked:
raise ValueError(f"few-shot examples in the {split} split: {sorted(leaked)}")
verdicts = [judge.grade(model, r["source"], r["question"], r["answer"]) for r in rows]
answered_by = ", ".join(sorted({v.model for v in verdicts})) or model.name # more than one: the alias moved
return score_validation(judge.prompt_id, answered_by, split, [r["label"] for r in rows],
[v.label for v in verdicts], [r["id"] for r in rows])
Tune on dev; run test once.
The splits themselves were cut by source document: each contract sits in one split only (part 1 built them that way). So the leaked check guards the examples, and the split guards the contracts: a judge never gets tested on a contract its examples came from.
answered_by is there because an alias can move. fast and smart are gateway names that map to real models, and the gateway may answer some items with another model, for example through its fallback. If answered_by lists more than one model, that happened during the run.
The same file also has replay_validation, which re-scores a recorded run with no model (Going deeper), and format_validation, which prints the tables below.
Step 8: the command, and a judge that says PASS to everything
aip-eval is the one eval CLI from lesson 2.1. This lesson adds judge (and plan, which lesson 4.3 puts to work); its code is in Full code. The next command scores a judge that says PASS to every item of the first set's test split. No model is involved: it's the scoring code alone. Predict first: what are its TPR and TNR?
uv run python -c "from aip.evals.judge import load_labeled, score_validation, format_validation; \
rows = [r for r in load_labeled('default') if r['split'] == 'test']; \
print(format_validation(score_validation('always-pass', 'none', 'test', \
[r['label'] for r in rows], ['pass'] * len(rows), [r['id'] for r in rows])))"
It prints the confusion table, then TPR and TNR:
judge always-pass model none split test n=76
judge FAIL judge PASS judge UNKNOWN
human FAIL 0 37 0
human PASS 0 39 0
TPR (failures caught) 0.0% 95% CI 0.0% to 9.4%
TNR (good passed) 100.0% 95% CI 91.0% to 100.0%
unknown 0 Cohen's kappa 0.00
The always-PASS judge catches none of the 37 labeled failures, so TPR is zero. Its agreement here is only 39 of 76, about half, because this split is balanced on purpose. On real traffic, where failures are rare, the same useless judge would agree with almost every label: that's the 95% from part 1.
Before you spend a cent on real models, look at what the judge receives. --show prints it for one item, examples included, with no model and no key:
$ uv run aip-eval judge --show gf-05-3 | head -1
grounded_figures@v1#ae6a1044925b model alias smart
$ uv run aip-eval judge --show gf-05-3 | tail -8
OUTPUT: {"critique": "The 48 hours run from delivery, not from the order.", "verdict": "FAIL"}
</example>
SOURCE: Northgate's total aggregate liability under this agreement shall not exceed EUR 5,000,000 per contract year.
QUESTION: What is the liability cap?
ANSWER: EUR 2.5 million per contract year.
Reply with JSON only: {"critique": "...", "verdict": "PASS" | "FAIL" | "UNKNOWN"}
That's the whole judge: the examples, then one item, then the reply format. The last line of the always-PASS table, kappa, is an agreement score corrected for chance; you won't need it until Going deeper. The tests for steps 6 to 8, and the offline gateway's run, are in Going deeper too.
Step 9: the runs on real models
The first set. On 12 November 2026 I ran v1 on smart and fast. Both agreed with every label, 37/37 failures and 39/39 good answers on test. Perfect on 37 failures still can't certify a TPR near 100%, and with no disagreement there was nothing to learn from. The set was too easy, so I built a harder one, the borderline set.
What v2 is. Same prompt as v1, with the borderline set's own train split as its few-shot examples.
The hard set. On 13 November 2026 I ran v2 on the borderline set. Now the judges got things wrong, and the mistakes were worth reading. Both caught nearly every failure. Every error sat on a premise or a counting convention, never on arithmetic.
My favorite is item bl-s03-04: a termination date of "July 18" after a 15-day cure period and 30 days' notice. Depending on how you count the days, 17 and 18 July are both defensible, so the label is pass. Here's what each judge said:
bl-s03-04 fast human pass judge unknown: The claimed July 18 termination date depends on how the 15-day cure period and the subsequent 30-day notice period are counted. Clause 3 does not specify that convention, so the source alone does not establish the earliest date.
bl-s03-04 smart human pass judge fail: Clause 3 provides a 15-day cure period followed by 30 days’ termination notice. June 2 + 15 days is June 17, and June 17 + 30 days is July 17, not July 18.
The expensive judge picks one way of counting and fails the answer with confident sums. The cheap one says UNKNOWN and names the real question. That's why you read disagreements instead of trusting the totals. Going deeper replays two of the four recorded runs, with no key, gives the other two's numbers, and reads five of the nine items where a judge and the label differ; the other four are fast answering UNKNOWN on the same kind of day-count question.
You now have a judge you can defend with two numbers and their intervals, measured on labels it never saw. One limit to carry forward: our borderline rates describe hard cases built on purpose, not real traffic. Your judge's rates mean something about your system only when the labels come from your own outputs. Lesson 3.3 is about the people who write those labels.
Your turn (5 min)
See for yourself that a validation belongs to one exact prompt. A replay re-scores a recorded run, and the recording names the prompt id it ran with. In src/aip/evals/judges/grounded_figures/v2.md, change "one or two sentences" to "one sentence". It's a small wording edit that leaves the judge's job unchanged. Before you run anything, predict what this replay of the recorded 13 November run will do now:
uv run aip-eval judge --labels borderline --version 2 --split dev \
--replay data/larkfield/evals/judge_labels/runs/2026-11-13/fast_dev.verdicts.jsonl
Then undo your edit with git checkout -- src/aip/evals/judges. Check yourself has the answer.
What breaks
You've already watched most of these happen on this page.
Reporting agreement. You met it in step 8: the always-PASS judge agrees with half the labels on this balanced split, and on real traffic, where failures are rare, it would agree with almost every label (part 1's 95%) while catching nothing. Control: TPR and TNR with intervals, every time a judge score is quoted.
Validating one prompt and running another. Your turn showed how little it takes: one wording edit, and the recorded verdicts no longer belong to the judge you have. A gate that built the prompt without the examples would make the same mistake silently, running a different judge under the same name.
The control is one function for both. render builds the prompt the validation sends, and the gate builds its prompt with the same render, all 16 few-shot examples included, under the same prompt_id. (The gate's judge check comes in lesson 4.2.)
Validating on the examples. Ask for the train split and you'd be grading the judge on its own crib sheet. validate_judge refuses it:
$ uv run aip-eval judge --labels borderline --version 2 --split train
ValueError: few-shot examples in the train split: ['bl-s01-01', 'bl-s01-02', ..., 'bl-s02-08']
Validating on inputs that don't look like production. The source in step 8's --show is one sentence. In a release run the judge gets the whole contract, and can lose the figure in ten clauses. Control: validate on items shaped like the real call, and revalidate when the shape changes.
The model moves under you, or the gateway swaps it. On 12 November 2026, in a contract run, one smart request in 452 was quietly answered by fast after a gateway fallback (Going deeper, "The silent fallback"). A new model behind the alias, or a fallback like that one inside a run, means the judge that ran isn't the judge you validated. Control: revalidate when the model changes; answered_by lists every model that answered, and the release report names fallback trials.
Tuning on the test split. It feels like diligence: read the test disagreements, fix the prompt, rerun test. But now test is dev, and the number you report has seen the answers. Control: test once per version.
Decide
The default: one judge per failure mode, binary with UNKNOWN, critique first, a versioned file on a pinned alias. Validate it on a held-out test split, with each source document in one split only, so no contract sits in both the examples and the test. Report TPR and TNR with Wilson intervals, and read the disagreements. Revalidate on any change to the prompt, the examples or the model behind the alias.
Good enough: Eugene Yan's bar, "The benchmark is human performance, not perfection." Measure two reviewers on an overlap sample (lesson 3.3) and hold the judge to that. Our borderline labelers, the course author and an AI agent, agreed on 204 of 210 items; that is author against agent, not two people, so it doesn't stand in for your own reviewers' overlap.
Which model: pay for the stronger one only when validation shows it earns it. On the borderline dev split:
| Alias | Good answers passed (TNR) | 95% Wilson |
|---|---|---|
fast |
85.3% | 69.9% to 93.6% |
smart |
94.1% | 80.9% to 98.4% |
smart costs about 19 times as much, and the intervals overlap. So model: smart stays a choice until a larger dev split settles it.
Same model as judge and generator: Husain and Shankar call it "usually fine" if the rates hold; self-preference research says check (Going deeper has the 2026 study). My default: a different model family when the gateway makes it cheap, and the validation decides.
Check yourself
- You add two few-shot examples. Does the old validation still hold?
No. It's a new judge, and
prompt_idchanges on its own because the hash covers the examples. Bump the version and validate again. - Why does UNKNOWN count against the judge on both sides? A gate can't act on it. Counting it as a pass would reward a judge for hedging.
- The judge catches 36 of 40 labeled failures: TPR 90%, Wilson 76.9% to 96.0%. What narrows the interval? More labeled failures in the test split, not more items overall: TPR's n is the number of real failures.
- The judge disagrees with a label and you think the judge is right. What do you do? Reread the source, fix the label with a note in the set's history. Never quietly drop the item.
Try it 2. TPR 32/33 = 97.0%, interval about 84.7% to 99.5%. TNR 29/34 = 85.3%, about 69.9% to 93.6%, because the 4 UNKNOWNs count as false alarms. The TNR interval is the wider one: it sits further from 100%, where rates vary more. The TNR is also the worry for a gate: it means about one good answer in seven fails the check, and with 34 items it could be as bad as three in ten.
Always-PASS. TPR 0% (it never says FAIL) and TNR 100% (it passes every good answer). A perfect TNR from a judge that does nothing.
Your turn. It refuses: ValueError: ... was run with grounded_figures@v2#ba65d96ef32a, not grounded_figures@v2#86589a704b30. That small edit changed the hash, so the recorded verdicts no longer describe the judge you have, and the code won't pretend they do. After git checkout, the same command prints the dev table again.
Transcript
Hey friends. In this video, I'd like to show you how to build an LLM judge and measure it. So code checks catch what they can match. For a figure from the wrong clause, in a free-form answer, we need a model to read it. That model is a judge, and a judge is a classifier. So you'll learn how to build one, and then do the part most teams skip: measure how often the judge is wrong.
All right, the judge lives in a file, with a version. The front matter names it, pins the gateway alias it runs on, and states the one failure mode it checks: a figure the source doesn't support. The body defines "supported", including the near misses: the right number with the wrong period, or counted from the wrong day. You get a binary verdict, UNKNOWN as an honest way out, and a critique before the verdict.
And next to it, sixteen few-shot examples, frozen with the version. They're part of the judge, by the way. Now, evals need one thing from a model: send messages to an alias, get text back, with the cost. E1 already built that client. This file binds it to an alias and to the eval runner's own key, so an eval never spends a production agent's budget.
No temperature is sent unless an alias opts in. And without the eval key, the command refuses to start, and it prints the line that creates it, the one from lesson two point one. So, the prompt id hashes the fixed part of the prompt: the template with its examples. Edit either one, even without bumping the version, and the id changes, so an old validation visibly stops applying.
Render is the one way to build the prompt, so the validation and the gate send the same bytes. And the verdict reader? Anything other than a clean PASS, FAIL or UNKNOWN becomes unknown. A judge that answers "looks good to me" hasn't passed anything, right? Now, two labeled sets. The first one: a hundred and fifty-two answers I wrote by hand on fictional sources, split by source passage into train, dev and test, so the examples never hand the judge a test answer.
The second set has two hundred and ten items, built where judges split: wrong clauses, outdated drafts, figures buried in long answers, unstated premises. Labels by the course author, checked by an independent second labeler, an AI agent. They agreed on two hundred and four items. It probes hard cases on purpose, so it doesn't sample production. And here's lesson one point two's liability cap, as a labeled fail.
All right, we score the judge like a classifier. Positive means a failure is present. True positive rate is the share of real failures the judge catches, and true negative rate is the share of good answers it lets through. Unknown counts against the judge on both sides, because a gate can't act on it. Each rate gets a Wilson interval, which stays sane at zero and at a hundred percent.
With no labeled failures in a split, the rate is "not applicable", so you never get a zero or a crash there. And the disagreements come back as a list, because you're going to read them. Now kappa. It's agreement corrected for chance, and both terms must count over the same categories, unknown included. Mix them, and a judge that never answers scores minus one point oh five, which kappa can't be.
Counted this way, it scores zero: no better than chance. The decision record has the reasoning. So we have one eval command line, and this lesson adds judge to it: validate through the gateway, or replay a recorded run. With show, it prints exactly what the judge will receive for one item, with no model and no key. The first line is the judge's id: name, version and hash.
And every number we quote belongs to that id. Now the trap, on the first set's test split. A judge that always says PASS catches none of the thirty-seven labeled failures. If failures were five percent of production, it would agree with your labels ninety-five percent of the time. That's why we never quote raw agreement. The tests also pin the kappa cases, the replay, and the rule that an eval never borrows a production agent's key.
In November 2026 I ran this judge on two real models through the gateway. On the first set, both agreed with every label, thirty-seven of thirty-seven and thirty-nine of thirty-nine, and the cheap one matched the expensive one item for item, at a nineteenth of the cost. Not one disagreement to read. That told me the set was too easy, so I built the borderline one.
So these are the recorded runs, replayed with no key. The cheap model on dev: one failure missed, one false alarm, four unknowns. The strong model on test: one failure missed. The model line shows the model the gateway says answered, which can differ from the alias. And the intervals overlap, so the gap between the two judges is suggestive, and that's all it is.
Now there's something to read. A termination date of July eighteenth: the label says pass, because seventeen and eighteen are both defensible. The strong judge fails it, with confident arithmetic. The cheap one says unknown and names the counting question, which is closer to the truth, honestly. A hundred and thirteen euros buried in a long answer: both judges pass it, and the labelers themselves split before settling on a fail.
A judge can't be clearer than its criterion. Interest for thirty days at a monthly rate: both judges fail it for a missing day-count rule, and that's a question for the prompt. Dates computed from a lease start the lease never gives: both pass it. And "about a hundred and eighty days" for six months: only the cheap judge objects. So every error sits on a premise or a convention, and none on arithmetic.
So a judge is a versioned file, on a pinned alias, with a measured error rate and disagreements you've read, or it isn't ready. Change the prompt, the examples or the model, and you measure again. Next up, the reviewers: people are graders too, and their error rate drifts in exactly the conditions production creates. See you there.
Going deeper
Part 1
What's new at this tag
Pinned: Python 3.12.13, uv 0.11.21, httpx 0.28.1, scipy 1.18.1.
git diff --stat=72 e2-m3-l1..e2-m3-l2 -- src
src/aip/evals/cli.py | 41 ++++
src/aip/evals/judge.py | 198 ++++++++++++++++++
.../judges/grounded_figures/v1.examples.jsonl | 16 ++
src/aip/evals/judges/grounded_figures/v1.md | 23 ++
.../judges/grounded_figures/v2.examples.jsonl | 16 ++
src/aip/evals/judges/grounded_figures/v2.md | 23 ++
src/aip/evals/model.py | 54 +++++
src/aip/evals/stats.py | 133 ++++++++++++
8 files changed, 504 insertions(+)
The tag also adds the two labeled sets, a recorded live run and tests.
Evidence for this part
- Decision records 0201, 0203, 0204 and 0207 in
docs/decisions/arrive at this tag; 0204 covers the model stub and replays (step 3). - The split by source (step 5) is held by
test_labeled_set_is_balanced_and_split_by_source.
Going deeper (optional)
Ten things the core leaves out: the tests and the evidence trail, the judges' habits, the first set's live run in full, the eval key and sampling plumbing, the offline run's table, the borderline set's provenance and its replayed run, five of the nine disagreements, the silent fallback, Cohen's kappa, and the exact numbers behind a few plain sentences in the core. About 10 minutes.
Tests, and the offline run
The tests for steps 6 to 8, all offline:
$ uv run pytest tests/evals/test_judge.py tests/evals/test_stats.py tests/evals/test_model.py -q
49 passed
On the stack's offline gateway the stand-in answers UNKNOWN to everything: that run only proves the plumbing (The offline run, below, has its table).
Evidence trail
test_split_with_no_human_failures_has_no_tpr(step 6: a split with no labeled failures getsNone).test_gate_sends_the_validated_prompt(lesson 4.2: the gate sends the validated prompt, byte for byte).
The judge's habits
A 2026 study of five judge models ("Judging the Judges", TMLR) found that how an answer is formatted sways judges most, and where it sits in the prompt matters little; judges also favor their own model's writing. Control: one failure mode, only the context it needs, and rates measured on answers in the formats your system produces.
The borderline set, in its own words
data/larkfield/evals/judge_labels/README.md, the borderline section:
Judge v2 (`src/aip/evals/judges/grounded_figures/v2.md`) is v1's prompt byte for byte with `version: 2`, and its few-shot examples (`v2.examples.jsonl`) are the borderline set's train split. v1 keeps the default set's train split. Either version validates on either set; a split that contains the judge's own examples is refused.
## The borderline set
**Labels:** by the course author, checked by an independent second labeler (an AI agent). The second labeler saw only the blind items (source, question, answer) and the label guide below, never the first labels, and used Python only for arithmetic and dates. No model judge produced any label. Agreement 204/210, Cohen's kappa 0.943. The six disagreements were settled by re-reading (table below). The kappa measures agreement between two careful readers with one label guide, not between two domain experts.
**Provenance** (`grounded_figures_borderline.provenance.jsonl`, one row per item: provenance, alias, model id, generation condition, the exact hand edit, category, the first label, a contested flag): 108 model outputs used untouched, 20 model outputs with one recorded hand edit, 82 hand-written. Model outputs came from the live gateway (`fast` = `openai/gpt-6-luna`, `smart` = `openai/gpt-6.1-sol`, 0 fallbacks in 307 calls) under five conditions: the true source (plain or long answers), a draft with one or two figures changed (judged against the true source), clause numbers shifted, and no source at all. With the true source in front of them, the models almost never stated a wrong figure; most failures here come from outdated drafts, missing sources, hand edits and hand-written items. The set probes judge behavior on hard cases. It does not sample production traffic, so its TPR and TNR are not estimates of a judge's accuracy on real answers.
Read the last sentence twice: these rates describe hard cases, not your traffic. v2.md is v1.md with version: 2 and nothing else, and v2.examples.jsonl is the borderline train split, so v2 has its own id, grounded_figures@v2#ba65d96ef32a (test_borderline_set_is_split_by_source_and_v2_examples_are_its_train_split).
The first set on real models, in full
On 12 November 2026 I ran v1 with the gateway on real providers (the steps are in What you're starting from, "Switching the gateway to a real provider"; GPT-6.1 Sol behind smart, GPT-6 Luna behind fast). Both agreed with every label: 37/37 and 39/39 on test, 29/29 and 31/31 on dev, kappa 1.00, USD 0.34 against USD 0.018. 37/37 only proves a TPR above 90.6% (lesson 4.1), there was no disagreement to read, and a model nineteen times cheaper matched item for item. The set was too easy: I wrote clear-cut failures, and real models find them all.
Replaying the 13 November run
On 13 November 2026 I ran v2 on the borderline dev and test splits, both aliases, USD 2.71 in all.
replay_validation re-scores the recorded live run shipped with the borderline set, with today's code and no model. It refuses a recording whose run.json names another prompt, so a table can't claim a judge that never ran. disagreements lists every item where judge and label differ: read them, and fix label errors in the labels, with a note. Replay it with no key and no stack:
$ uv run aip-eval judge --labels borderline --version 2 --split dev \
--replay data/larkfield/evals/judge_labels/runs/2026-11-13/fast_dev.verdicts.jsonl
judge grounded_figures@v2#ba65d96ef32a model openai/gpt-6-luna split dev n=67
judge FAIL judge PASS judge UNKNOWN
human FAIL 32 1 0
human PASS 1 29 4
TPR (failures caught) 97.0% 95% CI 84.7% to 99.5%
TNR (good passed) 85.3% 95% CI 69.9% to 93.6%
unknown 4 Cohen's kappa 0.83
$ uv run aip-eval judge --labels borderline --version 2 --split test \
--replay data/larkfield/evals/judge_labels/runs/2026-11-13/smart_test.verdicts.jsonl
judge grounded_figures@v2#ba65d96ef32a model openai/gpt-6.1-sol split test n=127
judge FAIL judge PASS judge UNKNOWN
human FAIL 61 1 0
human PASS 0 65 0
TPR (failures caught) 98.4% 95% CI 91.4% to 99.7%
TNR (good passed) 100.0% 95% CI 94.4% to 100.0%
unknown 0 Cohen's kappa 0.98
The other recordings: fast test 61/62 and 63/65, kappa 0.95; smart dev 32/33 and 32/34, kappa 0.91. Now there's something to read:
$ uv run python -c "import json, pathlib; run = pathlib.Path('data/larkfield/evals/judge_labels/runs/2026-11-13'); \
[print(r['id'], f.name.split('_')[0], 'human', r['human'], 'judge', r['judge'] + ':', r['critique']) \
for f in sorted(run.glob('*.verdicts.jsonl')) for r in map(json.loads, f.read_text().splitlines()) if r['id'] in ('bl-s03-04', 'bl-s04-02', 'bl-s05-07', 'bl-s12-19', 'bl-s11-08')]"
bl-s03-04 fast human pass judge unknown: The claimed July 18 termination date depends on how the 15-day cure period and the subsequent 30-day notice period are counted. Clause 3 does not specify that convention, so the source alone does not establish the earliest date.
bl-s04-02 fast human pass judge fail: EUR 300 interest (and EUR 20,300 total) assumes 30 days equals one monthly interest period. Section 5 sets interest at 1.5% per month but gives no day-count convention to support that conversion.
bl-s05-07 fast human fail judge pass: EUR 84 is 2 × EUR 42; EUR 95 is the minimum charge, EUR 11 is the difference, and EUR 113 includes the optional EUR 18 tail-lift fee. The waiting-time terms and validity dates match the source.
bl-s11-08 fast human pass judge fail: Brightwell’s clause states 6 months’ notice, but it does not support the conversion to about 180 days; calendar months do not have a fixed 30-day length.
bl-s12-19 fast human fail judge pass: EUR 55,500 is three months’ rent. Assuming a 1 April 2026 start, month 36 ends 31 March 2029, and six months’ notice is due by 30 September 2028.
bl-s03-04 smart human pass judge fail: Clause 3 provides a 15-day cure period followed by 30 days’ termination notice. June 2 + 15 days is June 17, and June 17 + 30 days is July 17, not July 18.
bl-s04-02 smart human pass judge fail: Clause 5 specifies 1.5% per month but does not establish that 30 days equals one monthly interest period. The stated assumption therefore does not support EUR 300 interest or the EUR 20,300 total.
bl-s05-07 smart human fail judge pass: A1–A2 support EUR 84 (2 × EUR 42), the EUR 95 minimum, and the EUR 11 difference; A3 supports EUR 113 with tail-lift (95 + 18). The waiting-time figures and rate-card validity dates also match the source.
bl-s11-08 smart human pass judge pass: Brightwell’s clause specifies 6 months’ written notice, the longest period listed; about 180 days is a reasonable approximate conversion.
bl-s12-19 smart human fail judge pass: The deposit is three months × EUR 18,500 = EUR 55,500 under clause 4. Given the explicitly hypothetical 1 April 2026 start, clause 6 supports a break at the end of month 36 (31 March 2029), with six months' notice by 30 September 2028.
- bl-s03-04: "July 18" after a 15-day cure and 30 days' notice; 17 and 18 July are both defensible, so it's a pass.
smartfails it with confident arithmetic;fastsays UNKNOWN and names the counting question. The cheap judge is closer. - bl-s05-07: EUR 113 buried in a long answer. Both judges pass it; the labelers split, and adjudication failed it (the EUR 95 minimum is per consignment: 84 + 18 = 102). A judge is only as clear as its criterion.
- bl-s04-02: EUR 300 interest, the answer saying it treats 30 days as one month. Labeled pass; both judges fail it. A question for the prompt, not the model.
- bl-s12-19: dates computed "if the lease began on 1 April 2026", a start the lease never gives. Both pass it; the label guide fails a premise the answer introduces. It keeps
smartoff 100% TPR on test. - bl-s11-08: "about 180 days, that is 6 months".
fastfails it (months aren't 30 days): its only test FAIL on a good answer. (Its other test false alarm is an UNKNOWN, on bl-s13-11.)
Every judge error sits on a premise or a counting convention, never on arithmetic. The intervals overlap (fast's dev TNR 85.3%, 69.9% to 93.6%, against smart's 94.1%): the gap is suggestive, not established, and test grew in rounds built for difficulty, so 98.4% isn't robust either. One pass over dev and test costs about USD 1.9 on smart, USD 0.1 on fast. The replay refuses a recording of another prompt:
$ uv run aip-eval judge --labels borderline --split test \
--replay data/larkfield/evals/judge_labels/runs/2026-11-13/smart_test.verdicts.jsonl
ValueError: data/larkfield/evals/judge_labels/runs/2026-11-13/smart_test.verdicts.jsonl was run with grounded_figures@v2#ba65d96ef32a, not grounded_figures@v1#ae6a1044925b
test_replay_reproduces_the_live_run_of_13_nov_2026 pins the four tables and the served model ids; the run is in docs/LIVE_RUNS_E2.md (tag e2-final). Drop --replay to run v2 live on your own models.
Models that move
OpenAI set 11 December 2026 as the shutdown date for gpt-5 and o3, and a new model means a new validation. As of November 2026, OpenAI lists no dated snapshot for GPT-6.1 Sol or GPT-6 Luna, so the model behind the id can change without a config edit: re-run the validation after any announced update.
The silent fallback
On 12 November 2026 the spend log showed 452 smart requests: 451 answered by GPT-6.1 Sol, 1 by GPT-6 Luna after a fallback nobody asked for. The client saw a 200 and counted it as smart. It was a contract run, not the judge, and changed no verdict, but a "smart" eval could hold "fast" answers unseen. That run is how the gap was found. E1's client now records the served model and a fallback flag on every completion (test_the_completion_names_the_model_that_served_it_and_flags_a_fallback), answered_by lists every model that answered, and the release report names fallback trials (test_a_trial_the_fallback_alias_answered_is_in_the_report, lesson 4.2).
The eval key and sampling
eval_settings (from E1's gate, E1 lesson 5.3) swaps the gateway key for AIP_EVAL_GATEWAY_KEY. Without that key, a spending command refuses to start and prints the fix, which is the eval-key command from lesson 2.1:
$ uv run aip-eval judge --split test
no eval key: uv run python scripts/agent_key.py eval-runner --var AIP_EVAL_GATEWAY_KEY
Calls are tagged eval in the spend log and send no temperature unless the alias opts in (E1 lesson 1.2), so the judge is measured at the provider's default sampling. ScriptedModel answers without a gateway, so tests need no key or stack.
The offline run
On the stack's offline gateway, with the eval key from lesson 2.1, the sim answers every judge prompt UNKNOWN: plumbing and format only.
$ uv run aip-eval judge --split test --out reports/judge_validation.json
judge grounded_figures@v1#ae6a1044925b model openai/sim-large split test n=76
judge FAIL judge PASS judge UNKNOWN
human FAIL 0 0 37
human PASS 0 0 39
TPR (failures caught) 0.0% 95% CI 0.0% to 9.4%
TNR (good passed) 0.0% 95% CI 0.0% to 9.0%
unknown 76 Cohen's kappa 0.00
The model line is the model the gateway says served smart, not the alias (lesson 6.2 tells how the alias used to land there).
Cohen's kappa
Kappa is agreement corrected for the agreement two coin-flippers would reach by chance: 1 is perfect, 0 is no better than chance. It's the number people quote for two human labelers, and the always-pass judge above shows why it beats raw agreement (0.00, against 39 of 76 "agreeing"). It still hides which side the judge errs on, so TPR and TNR stay the numbers that decide.
score_validation computes both of kappa's terms over one category set, UNKNOWN included:
# Cohen's kappa: observed agreement corrected for the agreement two coin-flippers would reach.
# One category per label, UNKNOWN included, in both terms (decision 0207): kappa stays in [-1, 1].
observed = sum(h == j for h, j in pairs) / n
chance = sum(human.count(c) * judged.count(c) for c in set(human) | set(judged)) / n**2
kappa = (observed - chance) / (1 - chance) if chance < 1 else 1.0
Mix two category sets and a judge that only says UNKNOWN scores -1.05, a number kappa can't take; this way it scores 0.00, no better than chance (decision record 0207 in docs/decisions/).
A rate over nothing, a kappa that isn't one. What breaks without these controls: a split with no labeled failures would report a TPR over nothing, and mixed category sets would give a kappa outside [-1, 1]. Control: None instead of a rate, and four kappa tests in test_judge.py: the mixed-category case that scored -1.05, the textbook example (0.4), a table worked by hand with UNKNOWN (3/31), and bounds on 2,000 random sets. The live runs barely exercise this path; the tests do.
Numbers behind the core
The core of this lesson states these in plain words; here are the exact figures.
Label counts. Husain and Shankar suggest 100 to 200 labels per failure mode: 10 to 20% train, 40 to 45% dev, 40 to 45% test, 30 to 50 of each label in dev and test.
The always-PASS judge on the balanced split. Agreement is 39 out of 76, because this test split is balanced on purpose (37 failures, 39 passes). On real traffic, where failures are rare, the same judge would agree with almost every label, as in the 95% example at the top. TPR is zero either way. Kappa is 0.00 (see Cohen's kappa above). A scripted judge in the tests copies the label except on two items: TPR 36/37, TNR 38/39, and a Wilson lower bound of only about 86% on each. That's all 37 and 39 items can certify.
37 out of 37. It only proves a TPR above 90.6% (lesson 4.1).
The borderline labelers' agreement. 204 of 210 items, Cohen's kappa 0.943.
Judge biases, in numbers. The 2026 study measured formatting style as the largest bias (effect sizes 0.10 to 0.76) and position bias at 0.04 or less; self-preference is documented too (see Sources).
Model choice on the borderline set. smart leads on TNR at about 19 times the cost, inside overlapping intervals (the replay tables above).
Model retirement dates and the fallback run: see "Models that move" and "The silent fallback" above.
Part 2
Free, and worth your time
- Eugene Yan, "Evaluating the Effectiveness of LLM-Evaluators" (long read, about 45 min): a survey of about two dozen papers on judges: their biases, how well they agree with people, and fine-tuned judges. https://eugeneyan.com/writing/llm-evaluators/
Full code
src/aip/evals/model.py, lines 1-54:
"""The model interface the eval code needs, over the platform client (aip.llm, built in E1).
Evals need one thing from a model: "send messages to an alias, get text or tool calls back, with
the cost". `aip.llm.Client` does that with retries, deadlines and traces; this file binds it to an
alias and to the eval-runner's own key, so an eval never spends a production agent's budget.
"""
import hashlib
from collections.abc import Callable
from typing import Any, Protocol
from aip.llm import Client, Completion, ToolCall, Usage
Message = dict[str, Any] # OpenAI chat format: {"role": ..., "content": ...}
class ChatModel(Protocol):
name: str
def complete(self, messages: list[Message], tools: list[dict] | None = None) -> Completion: ...
class GatewayModel:
"""A gateway alias (fast, smart) through aip.llm.Client, on AIP_EVAL_GATEWAY_KEY (agent eval-runner).
Sampling parameters are opt-in per alias in the settings (AIP_SAMPLING), never sent by default."""
def __init__(self, alias: str, client: Client | None = None):
from aip.config import get_settings
from aip.evals.gate_v1 import eval_settings
self.name = alias
self.client = client or Client(settings=eval_settings(get_settings()))
def complete(self, messages, tools=None) -> Completion:
return self.client.complete(self.name, messages, tools=tools, tags=("eval",))
def completion(text: str, model: str, tool_calls: tuple[ToolCall, ...] = (),
cost_usd: float | None = None) -> Completion:
"""A Completion that no gateway produced: replays, transcripts, scripted models in tests."""
return Completion(text, "tool_calls" if tool_calls else "stop", Usage(), model, tool_calls, cost_usd=cost_usd)
class ScriptedModel:
"""Deterministic stand-in for tests and offline demos: a function of the messages."""
def __init__(self, name: str, fn: Callable[[list[Message]], str | Completion]):
self.name, self.fn = name, fn
def complete(self, messages, tools=None) -> Completion:
out = self.fn(messages)
return out if isinstance(out, Completion) else completion(out, self.name)
def prompt_hash(text: str) -> str:
return hashlib.sha256(text.encode()).hexdigest()[:12]
src/aip/evals/judge.py, lines 1-67:
"""LLM judges: a versioned prompt, a pinned model alias, validated against human labels.
A judge is a classifier. "Positive" means a failure is present, so:
TPR = failures the judge catches / failures the human found
TNR = good outputs the judge passes / good outputs the human passed
(Husain and Shankar, https://hamel.dev/blog/posts/evals-faq/). Report both,
on a held-out test split, never raw agreement alone.
"""
import json
import re
from dataclasses import asdict, dataclass, field
from pathlib import Path
import yaml
from aip.evals.model import ChatModel, prompt_hash
from aip.evals.stats import wilson
JUDGES_DIR = Path(__file__).parent / "judges"
LABELS_DIR = Path(__file__).resolve().parents[3] / "data/larkfield/evals/judge_labels"
LABEL_SETS = { # `aip-eval judge --labels <name>`; any path to a file in the same schema works too
"default": LABELS_DIR / "grounded_figures.jsonl", # 152 items: real judges agree with every label
"borderline": LABELS_DIR / "grounded_figures_borderline.jsonl", # 210 items built where judges split
}
@dataclass
class Verdict:
label: str # "pass" | "fail" | "unknown"
critique: str
model: str = "" # the model the gateway says answered, not the alias we asked for
@dataclass
class Judge:
name: str
version: int
model: str # gateway alias, pinned in the file; the alias maps to one dated snapshot
failure_mode: str
template: str
examples: list[dict] = field(default_factory=list) # few-shot rows, frozen beside the prompt file
@property
def fixed_prompt(self) -> str:
"""Everything except the item: the template with its examples. Validated as one unit."""
return self.template.replace("{examples}", self.shots())
@property
def prompt_id(self) -> str:
return f"{self.name}@v{self.version}#{prompt_hash(self.fixed_prompt)}"
def shots(self) -> str:
return "\n\n".join(
f"<example>\nSOURCE: {e['source']}\nQUESTION: {e['question']}\nANSWER: {e['answer']}\n"
f'OUTPUT: {json.dumps({"critique": e["critique"], "verdict": e["label"].upper()})}\n</example>'
for e in self.examples)
def render(self, source: str, question: str, answer: str) -> str:
"""The one way to build the prompt, so validation and the gate send the same bytes."""
return self.template.format(source=source, question=question, answer=answer, examples=self.shots())
def grade(self, model: ChatModel, source: str, question: str, answer: str) -> Verdict:
prompt = self.render(source, question, answer)
reply = model.complete([{"role": "user", "content": prompt}]) # sampling: per alias, opt-in
verdict = parse_verdict(reply.text or "")
verdict.model = reply.model
return verdict
src/aip/evals/judge.py, lines 70-89:
def load_judge(name: str, version: int, folder: Path = JUDGES_DIR) -> Judge:
text = (folder / name / f"v{version}.md").read_text()
_, front, body = text.split("---\n", 2)
meta = yaml.safe_load(front)
shots = folder / name / f"v{version}.examples.jsonl" # the train split, frozen with this version
examples = load_labeled(shots) if shots.exists() else []
return Judge(meta["name"], meta["version"], meta["model"], meta["failure_mode"], body.strip(), examples)
def parse_verdict(reply: str) -> Verdict:
"""Read {"critique": ..., "verdict": PASS|FAIL|UNKNOWN}. Anything else is unknown, not a pass."""
match = re.search(r"\{.*\}", reply, re.DOTALL)
try:
data = json.loads(match.group(0)) if match else {}
except json.JSONDecodeError:
data = {}
label = str(data.get("verdict", "")).strip().lower()
if label not in ("pass", "fail", "unknown"):
return Verdict("unknown", f"unparseable judge reply: {reply[:120]!r}")
return Verdict(label, str(data.get("critique", "")))
src/aip/evals/judge.py, lines 92-136:
@dataclass
class Validation:
judge: str
model: str # returned by the gateway (dated snapshot), not the alias (decision 0203)
split: str
n: int
confusion: dict[str, int] # human_fail/judge_fail = tp, human_fail/judge_pass = fn, ...
tpr: float | None # None when the split has no human failures: undefined, not 0 or 100%
tpr_ci: tuple[float, float] | None
tnr: float | None # None when the split has no human passes
tnr_ci: tuple[float, float] | None
unknown: int
kappa: float
disagreements: list[dict]
def score_validation(judge_id: str, model: str, split: str, human: list[str], judged: list[str],
ids: list[str]) -> Validation:
"""Compare judge labels to human labels. Unknown counts against the judge (a miss either way)."""
pairs = list(zip(human, judged, strict=True))
tp = sum(h == "fail" and j == "fail" for h, j in pairs)
fn = sum(h == "fail" and j != "fail" for h, j in pairs)
tn = sum(h == "pass" and j == "pass" for h, j in pairs)
fp = sum(h == "pass" and j != "pass" for h, j in pairs)
n = len(pairs)
if n == 0:
raise ValueError(f"no labeled items in split {split!r}")
# Cohen's kappa: observed agreement corrected for the agreement two coin-flippers would reach.
# One category per label, UNKNOWN included, in both terms (decision 0207): kappa stays in [-1, 1].
observed = sum(h == j for h, j in pairs) / n
chance = sum(human.count(c) * judged.count(c) for c in set(human) | set(judged)) / n**2
kappa = (observed - chance) / (1 - chance) if chance < 1 else 1.0
return Validation(
judge_id, model, split, n,
{"human_fail/judge_fail": tp, "human_fail/judge_pass_or_unknown": fn,
"human_pass/judge_pass": tn, "human_pass/judge_fail_or_unknown": fp,
"human_fail/judge_unknown": sum(h == "fail" and j == "unknown" for h, j in pairs),
"human_pass/judge_unknown": sum(h == "pass" and j == "unknown" for h, j in pairs)},
*_rate(tp, tp + fn), *_rate(tn, tn + fp),
sum(j == "unknown" for j in judged), kappa,
[{"id": i, "human": h, "judge": j} for i, h, j in zip(ids, human, judged) if h != j])
def _rate(hits: int, n: int) -> tuple[float | None, tuple[float, float] | None]:
return (hits / n, wilson(hits, n)) if n else (None, None)
src/aip/evals/judge.py, lines 139-198:
def validate_judge(judge: Judge, model: ChatModel, labeled: list[dict], split: str = "test") -> Validation:
"""Run the judge on one split of a labeled set. The few-shot examples are the judge's own (its
frozen train split), so the prompt validated here is the prompt the gate sends."""
rows = [row for row in labeled if row["split"] == split]
leaked = {e["id"] for e in judge.examples} & {r["id"] for r in rows}
if leaked:
raise ValueError(f"few-shot examples in the {split} split: {sorted(leaked)}")
verdicts = [judge.grade(model, r["source"], r["question"], r["answer"]) for r in rows]
answered_by = ", ".join(sorted({v.model for v in verdicts})) or model.name # more than one: the alias moved
return score_validation(judge.prompt_id, answered_by, split, [r["label"] for r in rows],
[v.label for v in verdicts], [r["id"] for r in rows])
def load_labeled(path: str | Path) -> list[dict]:
"""A labeled set by name (LABEL_SETS) or by path."""
path = LABEL_SETS.get(str(path), path)
return [json.loads(line) for line in Path(path).read_text().splitlines() if line.strip()]
def replay_validation(judge: Judge, labeled: list[dict], split: str, verdicts: str | Path) -> Validation:
"""Score a recorded run (one {"id", "judge", "critique", "model"} row per item) without calling a model.
The run's run.json names the prompt it ran and the model ids the gateway served; a run of another
prompt is refused, so the table can't claim a judge that was never run."""
meta = json.loads((Path(verdicts).parent / "run.json").read_text())
if meta["judge"] != judge.prompt_id:
raise ValueError(f"{verdicts} was run with {meta['judge']}, not {judge.prompt_id}")
recorded = {r["id"]: r for r in load_labeled(verdicts)}
rows = [row for row in labeled if row["split"] == split]
missing = [r["id"] for r in rows if r["id"] not in recorded]
if missing:
raise ValueError(f"{len(missing)} {split} items not in {verdicts}: {missing[:3]}")
served = ", ".join(sorted({meta["served"].get(recorded[r["id"]]["model"], recorded[r["id"]]["model"])
for r in rows}))
return score_validation(judge.prompt_id, served, split, [r["label"] for r in rows],
[recorded[r["id"]]["judge"] for r in rows], [r["id"] for r in rows])
def format_validation(v: Validation) -> str:
c = v.confusion
fail_unknown, pass_unknown = c["human_fail/judge_unknown"], c["human_pass/judge_unknown"]
fail_pass = c["human_fail/judge_pass_or_unknown"] - fail_unknown
pass_fail = c["human_pass/judge_fail_or_unknown"] - pass_unknown
return "\n".join([
f"judge {v.judge} model {v.model} split {v.split} n={v.n}",
" judge FAIL judge PASS judge UNKNOWN",
f"human FAIL {c['human_fail/judge_fail']:>10} {fail_pass:>10} {fail_unknown:>13}",
f"human PASS {pass_fail:>10} {c['human_pass/judge_pass']:>10} {pass_unknown:>13}",
f"TPR (failures caught) {_pct(v.tpr, v.tpr_ci, 'no human failures in this split')}",
f"TNR (good passed) {_pct(v.tnr, v.tnr_ci, 'no human passes in this split')}",
f"unknown {v.unknown} Cohen's kappa {v.kappa:.2f}",
])
def _pct(rate: float | None, ci: tuple[float, float] | None, why: str) -> str:
return f"n/a ({why})" if rate is None else f"{rate:.1%} 95% CI {ci[0]:.1%} to {ci[1]:.1%}"
def save_validation(v: Validation, path: str | Path) -> None:
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text(json.dumps(asdict(v), indent=2) + "\n")
src/aip/evals/cli.py, lines 46-70:
@command("judge", ("--judge", {"default": "grounded_figures"}), ("--version", {"type": int, "default": 1}),
("--labels", {"default": "default", "help": "default | borderline | a path to a labeled JSONL"}),
("--model", {}), ("--split", {"default": "test"}), ("--out", {}),
("--replay", {"metavar": "VERDICTS", "help": "score a recorded run instead of calling a model"}),
("--show", {"metavar": "ITEM_ID", "help": "print the rendered prompt for one item and stop"}))
def cmd_judge(a) -> int:
"""Validate a judge against human labels: TPR, TNR, confusion table."""
from aip.evals.judge import (format_validation, load_judge, load_labeled, replay_validation,
save_validation, validate_judge)
judge = load_judge(a.judge, a.version)
rows = load_labeled(a.labels)
if a.show:
item = next(r for r in rows if r["id"] == a.show)
print(f"{judge.prompt_id} model alias {judge.model}\n")
print(judge.render(item["source"], item["question"], item["answer"]))
return 0
if a.replay:
v = replay_validation(judge, rows, a.split, a.replay)
else:
from aip.evals.model import GatewayModel
v = validate_judge(judge, GatewayModel(a.model or judge.model), rows, a.split)
print(format_validation(v))
if a.out:
save_validation(v, a.out)
return 0
Sources
- Husain and Shankar, "AI Evals FAQ", 18 Sept 2026 (judge as classifier, positive = failure, TPR and TNR, label counts and splits, "usually fine" to use the same model): https://hamel.dev/blog/posts/evals-faq/ (checked 12 Nov 2026)
- Husain, "Using LLM-as-a-Judge" (critique shadowing; raw agreement misleads under class imbalance): https://hamel.dev/blog/posts/llm-judge/ (checked 12 Nov 2026)
- Yan, "Product evals", Nov 2025 (binary labels, Cohen's kappa, "The benchmark is human performance, not perfection"): https://eugeneyan.com/writing/product-evals/ (checked 12 Nov 2026)
- Anthropic, "Demystifying evals for AI agents", 9 Jan 2026 (give the judge an Unknown option): https://anthropic.com/engineering/demystifying-evals-for-ai-agents (checked 12 Nov 2026)
- "Judging the Judges: A Systematic Evaluation of Bias Mitigation Strategies in LLM-as-a-Judge Pipelines", TMLR 2026 (formatting 0.10 to 0.76, position 0.04 or less): https://arxiv.org/abs/2604.23178 (checked 12 Nov 2026)
- Self-preference: Panickssery et al., "LLM Evaluators Recognize and Favor Their Own Generations": https://arxiv.org/abs/2404.13076; Wataoka et al., "Self-Preference Bias in LLM-as-a-Judge": https://arxiv.org/abs/2410.21819 (checked 12 Nov 2026)
- Bowyer, Aitchison and Ivanova, "Position: Don't Use the CLT in LLM Evals With Fewer Than a Few Hundred Datapoints", ICML 2025 (Wilson or Bayesian intervals for small eval sets): https://arxiv.org/abs/2503.01747 (checked 12 Nov 2026)
- OpenAI, "Deprecations" (gpt-5, its mini, nano and pro variants, o3 and o3-pro shut down 11 Dec 2026, notice of 11 Jun 2026): https://developers.openai.com/api/docs/deprecations (checked 12 Nov 2026)
- My live runs: 12 Nov 2026,
aip-eval judgev1 on the first set's dev and test splits through the gateway, GPT-6.1 Sol (smart) and GPT-6 Luna (fast), with the spend log for cost and the one silent fallback; 13 Nov 2026, v2 on the borderline set, both aliases, USD 2.71 (docs/LIVE_RUNS_E2.md, tage2-final; recording indata/larkfield/evals/judge_labels/runs/2026-11-13/) - Reference repository
ai-platform, branchseries, tage2-m3-l2:src/aip/evals/judges/grounded_figures/v1.md,v1.examples.jsonl,v2.md,v2.examples.jsonl,src/aip/evals/judge.py,src/aip/evals/model.py,src/aip/evals/stats.py,src/aip/evals/cli.py,tests/evals/test_judge.py,tests/evals/test_model.py,data/larkfield/evals/judge_labels/(both sets,README.md, provenance,runs/2026-11-13/),docs/decisions/0203-judge-validation.md,0204-model-stub-and-replays.md,0207-kappa-unknown-is-a-category.md; tage2-m4-l2:tests/evals/test_judge_prompt_identity.py,tests/evals/test_report.py