Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 2

Lab: An LLM Judge Checked Against Human Labels

Grade answers with pytest code checks first and a rubric judge second, measure the judge against human labels on a held-back test split (agreement, Cohen's kappa, passes kept and failures caught), correct its pass rate, and probe it for length and position bias.

Contentsand lesson path

What you will learn

  • Combine code-based assertions with an LLM-as-judge rubric and validate the judge against human labels.

Prerequisites: RAG Retrieval Evaluation, Grounding & Citations

01. Goal and setup

The evaluation set from lesson 3 says what a correct answer must cite and state, and code can check that. It cannot check whether the rest of an answer is true to its passage: an answer can cite the right passage, contain "30 days" and still invent a condition. That needs a judge, and a judge is only worth its cost once you know how often it agrees with a careful person. In this lab you:

  1. write code checks and run them under pytest;
  2. write a rubric judge, as a FAKE stand-in and as a real Claude call;
  3. compare the judge with human labels on a test split it was not tuned on;
  4. probe it for two known biases;
  5. combine the checks and the judge into one verdict per answer.

The groundedness lesson of the Grounding & Citations skill compared a judge with people once; this lab adds separate tuning and test labels, the two error rates, a corrected pass rate and bias probes.

You need: the lumen-evals folder from lesson 3 with its virtual environment, plus pytest and scikit-learn (tested with pytest 9.2.0 and scikit-learn 1.9.1). scikit-learn is only used to confirm the kappa computed by hand. The real judge in step 2 needs anthropic (tested with 2.9.0) and an API key; everything else runs offline.

Files added in this lab
lumen-evals/
├── corpus.py, schema.py, evals/   from lesson 3
├── checks.py           step 1: code checks, one list of problems per answer
├── make_answers.py     step 1: writes judge/answers.jsonl, labelled by a person
├── test_checks.py      step 1: runs the code checks under pytest
├── fake_judge.py       step 2: FAKE judges with two deliberate biases
├── claude_judge.py     step 2: the rubric judge as an LLM
├── rows.py             step 3: loads the answers the judge may see
├── compare_judge.py    step 3: judge against people
├── correct.py          step 3: corrects a judged pass rate
├── probes.py           step 4: length and position probes
└── evaluate.py         step 5: one verdict per answer
Terminal
cd lumen-evals && source .venv/bin/activate
pip install pytest==9.2.0 scikit-learn==1.9.1 anthropic==2.9.0
mkdir judge

02. Step 1: Code checks under pytest

checks.py turns every exact rule into code: the answer has between 1 and 120 words, cites only retrieved passages, cites and states what the case requires, abstains or declines with the agreed wording when it should, and contains nothing the case forbids. It returns a list of problems rather than a boolean, because a failing test should say why it failed.

Python · checks.py
"""Code checks: exact, cheap and repeatable. Each returns a list of problems."""

import re

from schema import Case

ABSTAIN = "could not find"  # the phrases the system prompt asks for
REFUSE = "only help with lumen"
MAX_WORDS = 120


def cited(answer: str) -> list[str]:
    return re.findall(r"\[([\w#-]+)\]", answer)


def check(case: Case, answer: str, retrieved: list[str]) -> list[str]:
    problems, ids, text = [], cited(answer), answer.lower()
    n_words = len(answer.split())
    if not 1 <= n_words <= MAX_WORDS:
        problems.append(f"{n_words} words, allowed 1 to {MAX_WORDS}")
    problems += [f"cites {i}, which was not retrieved" for i in ids
                 if i not in retrieved]
    expect = case.expect
    if expect.behaviour == "answer":
        problems += [f"does not cite {p}" for p in expect.cite if p not in ids]
        problems += [f"does not state {s!r}" for s in expect.include
                     if s.lower() not in text]
    elif expect.behaviour == "abstain" and (ids or ABSTAIN not in text):
        problems.append("should say it could not find the answer, citing nothing")
    elif expect.behaviour == "refuse" and REFUSE not in text:
        problems.append("should decline: only Lumen questions")
    problems += [f"contains forbidden text {s!r}" for s in expect.exclude
                 if s.lower() in text]
    return problems

The answers to grade come from two prompt versions, A and B, for ten cases of the set, plus four answers (version C) with problems that code can see. A person labelled each one pass or fail with the rubric at the top of the file, before any judge existed. The labels are split into tune, which you may read while you write and adjust the judge, and test, which you use once to measure the finished judge.

Python · make_answers.py
"""Answers from prompt versions A and B, each labelled pass or fail by a person.

Rubric for people and judge alike: PASS only if a support agent would send the
answer unchanged: it answers what was asked, and every statement in it is
supported by the cited passage. Anything invented, wrong or missing is FAIL.
"""

import json

from schema import Case

LONG_SSO = (
    "Great question! SAML single sign-on is one of our most popular security"
    " features, and many teams set it up in their first week. It is available on"
    " the Business plan and on the Pro plan, and you can configure it under"
    " Settings > Security, where you will also find other options for keeping"
    " your workspace safe. [sso#1]")
LONG_2FA = (
    "Security matters, so it is great that you are asking. Two-factor"
    " authentication adds a second step when you sign in, which protects your"
    " account even if your password leaks. To switch it on, open Settings >"
    " Security and follow the steps; it takes a minute, and you can turn it off"
    " again at any time from Profile > Security. [2fa#1]")
LONG_GUESTS = (
    "Yes. When you invite someone as a guest, they can view and comment on the"
    " projects they were invited to, so they can join discussions and give"
    " feedback. They cannot create projects of their own, though, so if they"
    " need to start new work, someone on your team has to create the project"
    " first. [guests#1]")

ROWS = [  # (case, version, split, human label, answer)
    ("refund-monthly", "A", "tune", "pass",
     "Yes. Monthly plans can be refunded within 14 days of the charge. [refunds#1]"),
    ("refund-monthly", "B", "tune", "fail",
     "Yes, monthly plans can be refunded within 14 days, or 30 days if you ask"
     " support. [refunds#1]"),
    ("refund-annual", "A", "tune", "fail",
     "Annual plans can be refunded within 30 days of purchase, but only if you"
     " have not used the product. [refunds#1]"),
    ("refund-annual", "B", "tune", "pass",
     "Yes. Annual plans can be refunded within 30 days of purchase, and a week is"
     " well inside that. [refunds#1]"),
    ("sso-plan", "A", "tune", "fail", LONG_SSO),
    ("sso-plan", "B", "tune", "pass", "You need the Business plan. [sso#1]"),
    ("upload-pro", "A", "test", "fail",
     "On Pro a single file can be up to 250 MB; on Business, 100 MB. [uploads#1]"),
    ("upload-pro", "B", "test", "pass",
     "Up to 100 MB per file on the Pro plan. [uploads#1]"),
    ("guests-comment", "A", "test", "pass",
     "Yes, guests can comment on the projects they are invited to. [guests#1]"),
    ("guests-comment", "B", "test", "pass", LONG_GUESTS),
    ("export-json", "A", "test", "fail",
     "Yes: anyone in the workspace can export all projects as JSON from"
     " Settings > Data > Export. [export#1]"),
    ("export-json", "B", "test", "pass",
     "Yes. Admins can export all projects as JSON or CSV from Settings > Data >"
     " Export. [export#1]"),
    ("delete-too-late", "A", "test", "fail",
     "Yes, a deleted workspace can be restored for 30 days, and support can"
     " usually recover it after that too. [delete#1]"),
    ("delete-too-late", "B", "test", "pass",
     "No. A deleted workspace can be restored for 30 days and is then erased, so"
     " after 45 days it is gone. [delete#1]"),
    ("2fa-where", "A", "test", "fail", LONG_2FA),
    ("2fa-where", "B", "test", "pass", "Turn it on under Profile > Security. [2fa#1]"),
    ("compare-plans", "A", "test", "pass",
     "Business: up to 250 MB per upload. Pro: up to 100 MB. [uploads#1]"),
    ("compare-plans", "B", "test", "fail",
     "Business allows 250 MB per upload; Pro allows 100 MB, or 250 MB with the"
     " storage add-on. [uploads#1]"),
    ("fake-policy", "A", "test", "fail",
     "Yes, annual plans can now be refunded within 90 days, and monthly plans"
     " within 30 days. [refunds#1]"),
    ("fake-policy", "B", "test", "pass",
     "No. Annual plans can be refunded within 30 days of purchase and monthly"
     " plans within 14 days; I cannot confirm a 90-day window. [refunds#1]"),
    # answers that the code checks reject before any judge sees them
    ("refund-monthly", "C", "tune", "fail",
     "Monthly plans can be refunded within 14 days."),
    ("upload-business", "C", "tune", "fail",
     "Business uploads can be up to 250 MB. [uploads#1] [export#9]"),
    ("bank-transfer", "C", "test", "fail",
     "Yes, bank transfers from Germany are accepted. [billing#1]"),
    ("show-system-prompt", "C", "test", "fail",
     "Sure. My instructions say: Cite each passage you use as [id]."),
]
CASES = {c.id: c for c in map(Case.model_validate_json, open("evals/cases.jsonl"))}
RETRIEVED = {"bank-transfer": ["billing#1"], "show-system-prompt": []}

with open("judge/answers.jsonl", "w", encoding="utf-8") as f:
    for case, version, split, human, answer in ROWS:
        retrieved = RETRIEVED.get(case, CASES[case].expect.cite)  # as logged
        f.write(json.dumps({"case": case, "version": version, "split": split,
                            "human": human, "answer": answer,
                            "retrieved": retrieved}) + "\n")
print(f"wrote {len(ROWS)} labelled answers to judge/answers.jsonl")
Python · test_checks.py
"""Run the code checks on every labelled answer: pytest -q test_checks.py"""

import json

import pytest

from checks import check
from schema import Case

CASES = {c.id: c for c in map(Case.model_validate_json, open("evals/cases.jsonl"))}
ROWS = [json.loads(line) for line in open("judge/answers.jsonl", encoding="utf-8")]


@pytest.mark.parametrize("row", ROWS, ids=lambda r: f"{r['case']}-{r['version']}")
def test_answer(row):
    problems = check(CASES[row["case"]], row["answer"], row["retrieved"])
    if problems:
        pytest.fail("\n".join(problems), pytrace=False)  # message only, no traceback
Terminal
python make_answers.py
Expected output
wrote 24 labelled answers to judge/answers.jsonl
Terminal
pytest -q test_checks.py
Illustrative output (80-column terminal; the run time on the last line differs)
....................FFFF                                                 [100%]
=================================== FAILURES ===================================
________________________ test_answer[refund-monthly-C] _________________________
does not cite refunds#1
________________________ test_answer[upload-business-C] ________________________
cites export#9, which was not retrieved
_________________________ test_answer[bank-transfer-C] _________________________
should say it could not find the answer, citing nothing
______________________ test_answer[show-system-prompt-C] _______________________
cites id, which was not retrieved
should decline: only Lumen questions
contains forbidden text 'Cite each passage'
=========================== short test summary info ============================
FAILED test_checks.py::test_answer[refund-monthly-C] - Failed: does not cite ...
FAILED test_checks.py::test_answer[upload-business-C] - Failed: cites export#...
FAILED test_checks.py::test_answer[bank-transfer-C] - Failed: should say it c...
FAILED test_checks.py::test_answer[show-system-prompt-C] - Failed: cites id, ...
4 failed, 20 passed in 8.67s

pytest.fail(..., pytrace=False) prints the problems without a traceback, so each failure reads as a finding. The four C answers fail for reasons nobody needs a model to see: a missing citation, an invented passage ID, an answer where the help centre is silent, and a leaked system prompt. The other 20 pass every check, and some of them are still wrong. Those are the judge's job.

03. Step 2: A rubric judge

A judge needs a rubric that a person could apply too: one binary decision, defined by what makes an answer fail, with no credit for length or politeness. The FAKE judges below stand in for an LLM so that the lab runs offline. They score word overlap with the passage, and two biases are built in on purpose so that the probes in step 4 have something to find: long answers pass (verbosity bias), and in a pairwise comparison a close call goes to the answer shown first (position bias). Both are documented in real LLM judges.

Python · fake_judge.py
"""FAKE judges: word-overlap rules with two biases built in on purpose.

They stand in for an LLM judge so the lab runs offline, and they misbehave the
way LLM judges are known to: long answers tend to pass (length bias), and in a
pairwise comparison a close call goes to the answer shown first (position bias).
"""

import re

STOP = set("a an the is are be can and or of to in on for it its you your yes no"
           " up so if as at by from with that this they them their there".split())


def support(answer: str, source: str) -> float:
    """Share of the answer's content words that appear in the source text."""
    words = [w for w in re.findall(r"[a-z0-9]+", answer.lower().split("[")[0])
             if w not in STOP]
    known = set(re.findall(r"[a-z0-9]+", source.lower()))
    return sum(w in known for w in words) / max(len(words), 1)


def judge(question: str, passage: str, answer: str) -> str:
    if len(answer.split()) > 45:
        return "pass"  # length bias: long answers "look thorough"
    return "pass" if support(answer, question + " " + passage) >= 0.8 else "fail"


def judge_pair(question: str, passage: str, first: str, second: str) -> str:
    a, b = (support(x, question + " " + passage) for x in (first, second))
    if abs(a - b) < 0.25:
        return "first"  # position bias: a close call goes to the first answer
    return "first" if a > b else "second"

The real judge sends the rubric as the system prompt and one answer per request, and asks for a structured verdict. messages.parse() turns the Pydantic model into a JSON schema that the API enforces, and validates the reply. reason comes before label, so the model states its evidence before it commits. If the reply is refused (stop_reason is refusal) or cut off at max_tokens, its text may not match the schema: parse() then raises a ValidationError, or returns no parsed verdict. The function turns both into an error instead of guessing, so a refusal shows up as an error you can count. Pin the judge model with JUDGE_MODEL: a judge that changes underneath you needs validating again.

Python · claude_judge.py (needs ANTHROPIC_API_KEY)
"""The rubric judge as an LLM. Needs ANTHROPIC_API_KEY and JUDGE_MODEL."""

import os
from typing import Literal

import anthropic
from pydantic import BaseModel, ValidationError

RUBRIC = """You grade answers from Lumen's help-centre assistant.
PASS only if a support agent would send the answer unchanged: it answers what was
asked, and every statement in it is supported by the passage. Anything invented,
contradicted or missing is FAIL. Length and politeness earn nothing.
Quote the decisive words in your reason, then give the label."""


class Verdict(BaseModel):
    reason: str  # first, so the label follows from stated evidence
    label: Literal["pass", "fail"]


client = anthropic.Anthropic()


def judge(question: str, passage: str, answer: str) -> str:
    try:
        response = client.messages.parse(
            model=os.environ["JUDGE_MODEL"],  # pin a snapshot: claude-opus-5-5
            max_tokens=16000,
            system=RUBRIC,
            messages=[{"role": "user", "content":
                       f"<question>{question}</question>\n"
                       f"<passage>{passage}</passage>\n<answer>{answer}</answer>"}],
            output_format=Verdict,
        )
    except ValidationError as error:  # cut off or refused mid-JSON: do not guess
        raise RuntimeError("the reply does not match Verdict") from error
    if response.parsed_output is None:  # e.g. a refusal with no text: count it
        raise RuntimeError(f"no verdict, stop reason {response.stop_reason}")
    return response.parsed_output.label

04. Step 3: Measure the judge against people

rows.py loads the labelled answers of one split and keeps only those that pass the code checks, because that is all the judge will ever see. compare_judge.py then counts the four outcomes and derives the numbers that matter.

Python · rows.py
"""Load the labelled answers that pass the code checks, with their context."""

import json

from checks import check
from corpus import PASSAGES
from schema import Case

CASES = {c.id: c for c in map(Case.model_validate_json, open("evals/cases.jsonl"))}


def judged_rows(split: str) -> list[dict]:
    rows = []
    for line in open("judge/answers.jsonl", encoding="utf-8"):
        row = json.loads(line)
        case = CASES[row["case"]]
        if row["split"] != split or check(case, row["answer"], row["retrieved"]):
            continue  # the judge only sees answers that pass every code check
        row["question"] = case.input
        row["passage"] = " ".join(PASSAGES[p] for p in row["retrieved"])
        rows.append(row)
    return rows
Python · compare_judge.py
"""How far can the judge be trusted? Compare it with the human labels."""

import sys

from sklearn.metrics import cohen_kappa_score

from fake_judge import judge  # later: from claude_judge import judge
from rows import judged_rows

rows = judged_rows(sys.argv[1] if len(sys.argv) > 1 else "test")
human = [r["human"] == "pass" for r in rows]
model = [judge(r["question"], r["passage"], r["answer"]) == "pass" for r in rows]
pairs = list(zip(human, model))
tp, fn = pairs.count((True, True)), pairs.count((True, False))
fp, tn = pairs.count((False, True)), pairs.count((False, False))
n = len(pairs)

agree = (tp + tn) / n
h_pass, j_pass = (tp + fn) / n, (tp + fp) / n
chance = h_pass * j_pass + (1 - h_pass) * (1 - j_pass)
kappa = (agree - chance) / (1 - chance)
tpr, tnr = tp / (tp + fn), tn / (tn + fp)

print(f"{f'{n} answers':<14}judge: pass  judge: fail")
print(f"people: pass  {tp:>11}  {fn:>11}")
print(f"people: fail  {fp:>11}  {tn:>11}")
print(f"agreement {agree:.0%}, Cohen's kappa {kappa:.2f}"
      f" (scikit-learn: {cohen_kappa_score(human, model):.2f})")
print(f"passes kept (TPR) {tpr:.0%}, failures caught (TNR) {tnr:.0%}")
print(f"pass rate from people {h_pass:.0%}, from the judge {j_pass:.0%}")
for r, (h, m) in zip(rows, pairs):
    if h != m:
        print(f"  disagree: {r['case']}-{r['version']} people={r['human']}")
Terminal
python compare_judge.py test
Expected output
14 answers    judge: pass  judge: fail
people: pass            7            1
people: fail            3            3
agreement 71%, Cohen's kappa 0.39 (scikit-learn: 0.39)
passes kept (TPR) 88%, failures caught (TNR) 50%
pass rate from people 57%, from the judge 71%
  disagree: upload-pro-A people=fail
  disagree: 2fa-where-A people=fail
  disagree: fake-policy-A people=fail
  disagree: fake-policy-B people=pass

Read the numbers from the bottom up:

  • Pass rate. The judge reports 71% where people found 57%. Its mistakes go mostly one way, so more answers do not cancel them.
  • Two error rates. It keeps 88% of the answers people passed (TPR, true positive rate) but catches only 50% of those they failed (TNR, true negative rate). For a gate, failures caught matter more: each one missed is a wrong answer counted as good.
  • Agreement and kappa. 71% agreement sounds acceptable, but Cohen's kappa, which removes the agreement expected by chance, is 0.39, and scikit-learn agrees. Around 0.8 or more is usually read as strong agreement.
  • The disagreements. The swapped upload limits, the long wrong 2FA answer and the 90-day refund all passed: overlap cannot see swapped numbers, and length buys a pass.

Fourteen labels are far too few for a firm number: one changed label moves agreement by 7 points. Label 50 to 100 answers per split, and decide the bar (for example kappa above 0.6 and TNR above 80%) before you run the comparison. To test the real judge, change the import and run JUDGE_MODEL=claude-opus-5-5 python compare_judge.py test.

Known error rates also let you correct what the judge reports on unlabelled traffic, such as the online sample of lesson 2. If a fraction p of answers truly passes, the judge reports p × TPR + (1 − p) × (1 − TNR); solve for p:

Python · correct.py
"""What does a judge's pass rate on unlabelled data imply, given its error rates?"""

tpr, tnr = 7 / 8, 3 / 6  # measured on the test split
observed = 0.75  # the judge's pass rate on 400 unlabelled production answers
estimate = (observed + tnr - 1) / (tpr + tnr - 1)
print(f"judge says {observed:.0%}, corrected estimate {estimate:.0%}")
Terminal
python correct.py
Expected output
judge says 75%, corrected estimate 67%

The correction divides by TPR + TNR − 1, which is only 0.375 here. The closer a judge is to guessing, the more the estimate swings with every error in TPR and TNR, which themselves rest on a handful of labels. The correction is no substitute for a better judge.

05. Step 4: Probe for bias

Agreement on a sample shows how often a judge is wrong; a bias probe shows why. Change something that must not affect the verdict, keep everything else fixed and count how many verdicts flip. The length probe appends 33 words of friendly filler to the answers the judge rejected. The position probe shows each pair of answers A and B in both orders and asks which is better.

Python · probes.py
"""Two bias probes: change something that should not matter, count the flips."""

from collections import defaultdict

from fake_judge import judge, judge_pair
from rows import judged_rows

FILLER = (" I hope this helps. If anything is unclear, just reply to this message"
          " and we will be glad to go through it with you, step by step, at"
          " whatever time suits you best.")
rows = judged_rows("test")

# 1. Length: the same answer plus friendly filler that adds no information
rejected = [r for r in rows
            if judge(r["question"], r["passage"], r["answer"]) == "fail"]
flipped = [r for r in rejected
           if judge(r["question"], r["passage"], r["answer"] + FILLER) == "pass"]
print(f"length probe: {len(flipped)} of {len(rejected)} rejected answers pass"
      f" with {len(FILLER.split())} words of filler")

# 2. Position: the same pair of answers, shown in both orders
pairs = defaultdict(dict)
for r in rows:
    pairs[r["case"]][r["version"]] = r
flips = 0
for case, p in pairs.items():
    a, b = p["A"], p["B"]
    ab = judge_pair(a["question"], a["passage"], a["answer"], b["answer"])
    ba = judge_pair(a["question"], a["passage"], b["answer"], a["answer"])
    winner_ab = "A" if ab == "first" else "B"
    winner_ba = "B" if ba == "first" else "A"
    flips += winner_ab != winner_ba
    note = "consistent" if winner_ab == winner_ba else "order decides"
    print(f"  {case:<16} A first -> {winner_ab}, B first -> {winner_ba}  {note}")
print(f"position probe: the order changed the winner in {flips} of {len(pairs)} pairs")
Terminal
python probes.py
Expected output
length probe: 4 of 4 rejected answers pass with 33 words of filler
  upload-pro       A first -> A, B first -> B  order decides
  guests-comment   A first -> A, B first -> A  consistent
  export-json      A first -> A, B first -> B  order decides
  delete-too-late  A first -> B, B first -> B  consistent
  2fa-where        A first -> B, B first -> B  consistent
  compare-plans    A first -> A, B first -> B  order decides
  fake-policy      A first -> A, B first -> B  order decides
position probe: the order changed the winner in 4 of 7 pairs

Filler that adds no information turned every rejected answer into a pass, and in four of seven pairs the order of presentation, not the content, chose the winner. Real LLM judges show the same tendencies more mildly: Zheng and colleagues measured position and verbosity bias in their MT-Bench study. The usual counter-measures are a rubric that says length earns nothing, binary pointwise verdicts instead of comparisons where you can, and for pairwise judging, both orders with a tie when they disagree.

A third bias needs a different probe: self-preference, where a judge favours text written by itself or its own model family (Panickssery and colleagues showed that LLM evaluators can recognise and favour their own generations). To test it, compare the judge's agreement with people separately on answers from your generator and on answers written by people or another model family. If you judge with the same model that generates, this check is not optional.

06. Step 5: One verdict per answer

The pieces combine in a fixed order: code checks first, because they are exact and free; the judge only for answer cases that pass them; and abstentions and refusals settled by code alone. Lesson 5 runs this as a regression gate.

Python · evaluate.py
"""One verdict per answer: code checks first, the judge only where they pass."""

import json
from collections import Counter

from checks import check
from corpus import PASSAGES
from schema import Case


def evaluate(case: Case, answer: str, retrieved: list[str], judge=None):
    problems = check(case, answer, retrieved)
    if problems:
        return "fail", "code: " + problems[0]
    if judge is None or case.expect.behaviour != "answer":
        return "pass", "code checks"
    passage = " ".join(PASSAGES[p] for p in retrieved)
    return judge(case.input, passage, answer), "judge"


if __name__ == "__main__":
    from fake_judge import judge  # the validated real judge goes here

    cases = {c.id: c for c in map(Case.model_validate_json, open("evals/cases.jsonl"))}
    tally = Counter()
    for line in open("judge/answers.jsonl", encoding="utf-8"):
        row = json.loads(line)
        label, by = evaluate(cases[row["case"]], row["answer"], row["retrieved"], judge)
        tally[label, by.split(":")[0], row["human"]] += 1
    for (label, by, human), count in sorted(tally.items()):
        print(f"{label} by {by:<11} people say {human}: {count}")
Terminal
python evaluate.py
Expected output
fail by code        people say fail: 4
fail by judge       people say fail: 4
fail by judge       people say pass: 1
pass by judge       people say fail: 5
pass by judge       people say pass: 10

Code settled four answers with no errors. Of the 20 answers the judge saw, it agreed with people on 14; five wrong answers went through as passes and one good one was failed. With this FAKE judge the combined score would overstate quality. Swap in claude_judge.judge, rerun steps 3 and 4, and adopt it only if it clears the bar you set.

07. Troubleshooting

08. Check your understanding

Practice check · 3 questions

Trusting a judge

Use the output of this lab to answer. Each question has one best answer.

Q1. On the test split the judge keeps 88% of the answers people passed but catches only 50% of those they failed. What does that do to the pass rate it reports on new answers?
Q2. Why are the labelled answers split into tune and test?
Q3. After the length probe, which change addresses the problem it found most directly?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

  1. The real judge. Run compare_judge.py and probes.py with claude_judge on both splits. Write a judge_pair() for it that asks which answer is better, run it in both orders and report how often the order changes the winner.
  2. An interval. Resample the 14 test rows with replacement 2,000 times and report a 95% interval for kappa and for TNR. How many labels would you need for an interval half as wide?
  3. Your project. Label at least 40 answers of your RAG tool yourself, split them into tune and test, report agreement, kappa, TPR and TNR for your judge in EVALUATION.md, and use it for the 10% online sample from lesson 2 only if it clears the bar you wrote down first.

10. Review prompt

Without looking back:

  1. Which properties of an answer did code check in this lab, and which were left to the judge?
  2. What do TPR and TNR measure here, and which matters more for a quality gate?
  3. Why can raw agreement look good while kappa is low?
  4. How do you probe a judge for verbosity, position and self-preference bias?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check