AI and machine learning · Advanced · 30 min
Use an LLM as a judge without fooling yourself
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Ollama 0.40.18 · qwen3:0.6b · Python 3.15 · ollama (Python) 0.6.3 · scikit-learn 1.9.1
You will grade 40 support answers with a local judge model, measure how far it agrees with your own labels using Cohen's kappa, expose its position and length biases, and end with written rules for when its scores can be trusted.
On this page
When an LLM feature writes free text, such as a support reply or a summary, there is no exact answer to compare against. A common fix is to have another model read each output and grade it. That model is called a judge. It is fast and cheap, and it is easy to believe it more than you should.
Judges have known biases. Published studies find that they prefer whichever answer they read first (position bias), prefer longer answers (length or verbosity bias), prefer text written by their own model family (self-preference), and pass work that a person would fail (leniency). None of this means you cannot use a judge. It means you treat it like any other measuring instrument: check it against a reference you trust before you read anything from it.
In this tutorial the reference is you. You take 40 answers from a support assistant for an online shop in Nigeria, two answers to each of 20 customer questions. You write a rubric, label every answer by hand, then let a local judge model grade the same 40. You measure agreement with Cohen's kappa, run two bias tests, and finish with a script that says, criterion by criterion, whether the judge has earned your trust.
The judge is qwen3:0.6b, a 0.6-billion-parameter model that runs on a laptop CPU through Ollama, with temperature 0 and a fixed seed so a rerun gives the same grades. A model this small is a weak judge, and that is useful here: the point of the tutorial is to measure how weak, not to assume. Change one environment variable and the same scripts check a bigger judge. Because the judge runs locally, a rerun costs nothing in API fees or mobile data once the model is downloaded.
Step 1 · Pull the judge model and create the project
Check that Ollama is running and download the model. It is about 520 MB, so on a metered connection start it while you are on Wi-Fi:
ollama --version
ollama pull qwen3:0.6bCreate a project with Python 3.15, the Ollama client library and scikit-learn, pinned to exact versions:
mkdir -p ~/judge-demo/data ~/judge-demo/results
cd ~/judge-demo
uv init --no-package --python 3.15
uv add "ollama==0.6.3" "scikit-learn==1.9.1"Check it worked
uv run python -c "import ollama, sklearn, sys; print(sys.version.split()[0], sklearn.__version__); print([m.model for m in ollama.list().models])"The output shows a 3.15 version number, 1.9.1, and a list that contains qwen3:0.6b. That proves Python can import both libraries and reach the Ollama server on 127.0.0.1:11434.
Step 2 · Write the policy and the answers to grade
A judge needs something to judge against. For a support assistant that is the shop's policy: the judge decides whether an answer is true by reading it, not from its own memory. Save the policy:
cat > data/policy.md <<'MD'
Customer policy for the shop (demo)
Delivery
- Lagos: 1 to 2 working days. Other states in Nigeria: 3 to 5 working days.
- Delivery is free on orders of 50,000 naira or more. Below that it costs 2,500 naira.
- Customers can change the delivery address until the order ships, in Orders > Edit address.
- We only deliver to addresses in Nigeria.
Payment
- We accept cards, bank transfer and pay on delivery. Pay on delivery is only available in Lagos.
- A failed card payment is never charged. If money left the account, the bank reverses it within 3 working days.
Returns and refunds
- Unused items with tags can be returned within 14 days of delivery.
- Faulty or wrong items can be returned within 30 days of delivery. We pay the return courier for these.
- For other returns the customer pays the return courier fee.
- Refunds go to the original payment method within 5 working days of the return arriving at our warehouse.
Account
- Password reset links expire after 30 minutes.
- Account deletion is requested in Settings > Privacy and is completed within 7 days.
MDNow the 40 answers. Each of the 20 questions has two answers. Some are good, some state a wrong fact, some are polite but do not answer, and some answer without telling the customer what happens next. That spread matters: a set where every answer is good cannot tell a careful judge from one that says yes to everything.
cat > data/answers.jsonl <<'JSONL'
{"id": "q01a", "qid": "q01", "question": "How long does delivery to Ibadan take?", "answer": "Delivery to Ibadan takes 3 to 5 working days, because Ibadan is outside Lagos."}
{"id": "q01b", "qid": "q01", "question": "How long does delivery to Ibadan take?", "answer": "Delivery to Ibadan takes 1 to 2 working days."}
{"id": "q02a", "qid": "q02", "question": "Is delivery free if my order is 45,000 naira?", "answer": "Delivery is free from 50,000 naira, so on a 45,000 naira order it costs 2,500 naira. If you add 5,000 naira more to your basket, delivery becomes free."}
{"id": "q02b", "qid": "q02", "question": "Is delivery free if my order is 45,000 naira?", "answer": "Thank you for your message. We are always happy to help with your order."}
{"id": "q03a", "qid": "q03", "question": "Can I pay on delivery in Abuja?", "answer": "Yes, pay on delivery is available everywhere in Nigeria. Choose it when you pay."}
{"id": "q03b", "qid": "q03", "question": "Can I pay on delivery in Abuja?", "answer": "Pay on delivery is only available in Lagos, so for Abuja please pay by card or bank transfer."}
{"id": "q04a", "qid": "q04", "question": "My card payment failed but money left my account. What happens now?", "answer": "A failed card payment is never charged. Your bank will reverse the money within 3 working days, and you can then try the payment again."}
{"id": "q04b", "qid": "q04", "question": "My card payment failed but money left my account. What happens now?", "answer": "We have charged your card, and your order will ship tomorrow."}
{"id": "q05a", "qid": "q05", "question": "I want to return shoes I have not worn. I got them 10 days ago.", "answer": "You can return them within 14 days. Book the return and we will pay the courier for you."}
{"id": "q05b", "qid": "q05", "question": "I want to return shoes I have not worn. I got them 10 days ago.", "answer": "You can still return them, because unused items with tags can be returned within 14 days of delivery. You pay the return courier fee, and the refund reaches your original payment method within 5 working days of the shoes arriving at our warehouse."}
{"id": "q06a", "qid": "q06", "question": "The kettle I received does not work. Who pays to send it back?", "answer": "Sorry about the kettle. We hope you enjoy the rest of your order."}
{"id": "q06b", "qid": "q06", "question": "The kettle I received does not work. Who pays to send it back?", "answer": "Because the kettle is faulty, we pay the return courier. Return it within 30 days of delivery, and your refund follows within 5 working days of it reaching our warehouse."}
{"id": "q07a", "qid": "q07", "question": "When will I get my refund? Your warehouse received my return yesterday.", "answer": "Refunds go to your original payment method within 5 working days of the return arriving, so expect yours within 5 working days of yesterday."}
{"id": "q07b", "qid": "q07", "question": "When will I get my refund? Your warehouse received my return yesterday.", "answer": "Refunds are paid as store credit within 24 hours."}
{"id": "q08a", "qid": "q08", "question": "Can I change my delivery address? The order has not shipped yet.", "answer": "Yes. Until the order ships you can change the address in Orders > Edit address."}
{"id": "q08b", "qid": "q08", "question": "Can I change my delivery address? The order has not shipped yet.", "answer": "Yes, you can change it."}
{"id": "q09a", "qid": "q09", "question": "Do you deliver to Accra?", "answer": "Yes, we deliver to Accra in 3 to 5 working days."}
{"id": "q09b", "qid": "q09", "question": "Do you deliver to Accra?", "answer": "No. We only deliver to addresses in Nigeria, so an order cannot be sent to Accra. You can still order to an address in Nigeria."}
{"id": "q10a", "qid": "q10", "question": "I got a password reset link two hours ago and it says it has expired.", "answer": "Reset links last 24 hours, so please try again later."}
{"id": "q10b", "qid": "q10", "question": "I got a password reset link two hours ago and it says it has expired.", "answer": "Reset links expire after 30 minutes, so the one from two hours ago no longer works. Request a new link and use it within 30 minutes."}
{"id": "q11a", "qid": "q11", "question": "How do I delete my account?", "answer": "Request deletion in Settings > Privacy. Your account is deleted within 7 days."}
{"id": "q11b", "qid": "q11", "question": "How do I delete my account?", "answer": "We are sorry to see you go. Your account is deleted immediately when you email us."}
{"id": "q12a", "qid": "q12", "question": "How quickly can you deliver to Lekki in Lagos?", "answer": "We accept cards, bank transfer and pay on delivery in Lagos."}
{"id": "q12b", "qid": "q12", "question": "How quickly can you deliver to Lekki in Lagos?", "answer": "Delivery within Lagos takes 1 to 2 working days, so expect your order in Lekki within 2 working days."}
{"id": "q13a", "qid": "q13", "question": "You sent me a blue bag but I ordered black. What should I do?", "answer": "Sorry for the mix-up. A wrong item can be returned within 30 days of delivery and we pay the return courier. Once it reaches our warehouse, the refund goes to your original payment method within 5 working days."}
{"id": "q13b", "qid": "q13", "question": "You sent me a blue bag but I ordered black. What should I do?", "answer": "Sorry for the mix-up. You have 14 days to return it and you pay the courier fee."}
{"id": "q14a", "qid": "q14", "question": "Can I return a blender after 20 days if I never opened it?", "answer": "Yes, unused items can be returned within 30 days."}
{"id": "q14b", "qid": "q14", "question": "Can I return a blender after 20 days if I never opened it?", "answer": "Unused items can be returned within 14 days of delivery, so after 20 days we cannot accept this return unless the blender is faulty."}
{"id": "q15a", "qid": "q15", "question": "Is pay on delivery available for my order to Ikeja?", "answer": "Pay on delivery is a convenient option for many customers."}
{"id": "q15b", "qid": "q15", "question": "Is pay on delivery available for my order to Ikeja?", "answer": "Yes. Ikeja is in Lagos, and pay on delivery is available for Lagos addresses, so you can pay when the order arrives."}
{"id": "q16a", "qid": "q16", "question": "How much does delivery cost on a 20,000 naira order?", "answer": "Orders under 50,000 naira pay 2,500 naira for delivery, so delivery on your order is 2,500 naira."}
{"id": "q16b", "qid": "q16", "question": "How much does delivery cost on a 20,000 naira order?", "answer": "Delivery takes 1 to 2 working days in Lagos and 3 to 5 working days in other states."}
{"id": "q17a", "qid": "q17", "question": "My return reached your warehouse 8 working days ago and there is still no refund.", "answer": "Refunds should arrive within 5 working days of the return reaching our warehouse, so yours is late. Please reply with your order number so we can check it today."}
{"id": "q17b", "qid": "q17", "question": "My return reached your warehouse 8 working days ago and there is still no refund.", "answer": "Refunds go to the original payment method within 5 working days of the return arriving."}
{"id": "q18a", "qid": "q18", "question": "Can I pay by bank transfer?", "answer": "Yes, and if you pay by bank transfer you get a 5% discount."}
{"id": "q18b", "qid": "q18", "question": "Can I pay by bank transfer?", "answer": "Yes, we accept bank transfer. Choose it as your payment method when you pay for your order."}
{"id": "q19a", "qid": "q19", "question": "My order arrived damaged. Can I get my money back?", "answer": "We are sorry your order arrived damaged. Please let us know if there is anything else we can help with."}
{"id": "q19b", "qid": "q19", "question": "My order arrived damaged. Can I get my money back?", "answer": "Yes. An item that arrives damaged is faulty, so you can return it within 30 days of delivery and we pay the return courier. The refund goes to your original payment method within 5 working days of the item reaching our warehouse."}
{"id": "q20a", "qid": "q20", "question": "I ordered to Kano on Monday and it is now Thursday. Is that normal?", "answer": "Yes. Delivery to Kano takes 3 to 5 working days, so if your order shipped on Monday it should arrive by the following Monday at the latest."}
{"id": "q20b", "qid": "q20", "question": "I ordered to Kano on Monday and it is now Thursday. Is that normal?", "answer": "No, all orders arrive within 2 working days, so your parcel is late. We will send you a new one."}
JSONLIn your own project these come from logs or from runs of your feature, not from a text editor. Writing them here keeps the run repeatable and gives every failure type a few examples.
Check it worked
uv run python - <<'PY'
import json
from collections import Counter
rows = [json.loads(line) for line in open("data/answers.jsonl", encoding="utf-8")]
print(len(rows), "answers,", len({r["qid"] for r in rows}), "questions")
assert len(rows) == 40 and set(Counter(r["qid"] for r in rows).values()) == {2}
PYThe output is 40 answers, 20 questions, and every question has exactly two answers.
Step 3 · Write a rubric with one question per criterion
"Rate this answer from 1 to 10" is the rubric that fools people most. Nobody, human or model, can say what separates a 6 from a 7, so the scores drift and you cannot check them. Instead, split quality into criteria and give each one a single yes-or-no question with a rule for the hard cases:
cat > data/rubric.json <<'JSON'
{
"scale": ["yes", "no"],
"criteria": [
{
"name": "accurate",
"question": "Is every statement in the agent's answer supported by the policy? Answer no if the answer states any time, cost, rule or promise that the policy contradicts or does not contain."
},
{
"name": "answers",
"question": "Does the agent's answer respond to what the customer actually asked? Answer no if it talks about something else or ignores the main point of the question."
},
{
"name": "next_step",
"question": "Does the agent's answer give the customer a concrete next action or a time frame for their request? Answer no if the customer would still not know what to do or what happens next."
}
]
}
JSONThree choices here are deliberate:
- A fixed two-point scale. Yes or no is the easiest scale for you and the judge to apply the same way, and it lets you compute agreement directly. If you need more grades, add a criterion rather than points on a scale.
- One question per call. The judge sees one criterion at a time. A model asked to score three things at once can let one impression colour all three, and you cannot tell which criterion drove the score.
- "Answer no if ..." rules. Each question says how to decide the cases you argued about while writing it. When you and the judge disagree later, the first thing to check is whether the rule was clear.
An answer passes overall only if all three criteria are yes.
Check it worked
uv run python -c "import json; r = json.load(open('data/rubric.json')); print([c['name'] for c in r['criteria']], r['scale'])"The output is ['accurate', 'answers', 'next_step'] ['yes', 'no']. Read each question aloud against one good and one bad answer from the file. If you cannot decide in a few seconds, the question needs another rule.
Step 4 · Label every answer yourself before the judge sees it
Your labels are the ruler, so make them before you run the judge. If you look at the judge's grade first, you will lean towards it and your agreement figure will flatter the judge.
Read each answer against the policy and the rubric and write 1 for yes or 0 for no. The labels below are the ones this tutorial uses; read them against the answers and change any you disagree with. A disagreement is worth a minute of thought, because it is the same kind the judge will have.
cat > data/labels.csv <<'CSV'
id,accurate,answers,next_step
q01a,1,1,1
q01b,0,1,1
q02a,1,1,1
q02b,1,0,0
q03a,0,1,1
q03b,1,1,1
q04a,1,1,1
q04b,0,1,1
q05a,0,1,1
q05b,1,1,1
q06a,1,0,0
q06b,1,1,1
q07a,1,1,1
q07b,0,1,1
q08a,1,1,1
q08b,1,1,0
q09a,0,1,1
q09b,1,1,1
q10a,0,1,1
q10b,1,1,1
q11a,1,1,1
q11b,0,1,1
q12a,1,0,0
q12b,1,1,1
q13a,1,1,1
q13b,0,1,1
q14a,0,1,1
q14b,1,1,1
q15a,1,0,0
q15b,1,1,1
q16a,1,1,1
q16b,1,0,0
q17a,1,1,1
q17b,1,0,0
q18a,0,1,0
q18b,1,1,1
q19a,1,0,0
q19b,1,1,1
q20a,1,1,1
q20b,0,1,1
CSVA few calls you might make differently: q17b states a true rule but ignores that the customer's refund is already late, so it does not answer the question. q16b gives time frames, but for delivery speed rather than the cost the customer asked about, so it fails next_step too. q02b states nothing false, so it passes accurate; an empty answer is not an inaccurate one.
If two people can label, have both label the same 20 answers without talking, then compute kappa between them with the script in the step after next. Two careful people rarely agree perfectly, and their agreement is the most you can reasonably ask of a judge.
Check it worked
uv run python - <<'PY'
import csv
rows = list(csv.DictReader(open("data/labels.csv", encoding="utf-8")))
for name in ("accurate", "answers", "next_step"):
print(f"{name:<10} passes {sum(r[name] == '1' for r in rows)}/{len(rows)}")
good = [r["id"] for r in rows if all(r[n] == "1" for n in ("accurate", "answers", "next_step"))]
print("overall passes", f"{len(good)}/{len(rows)}")
assert len(rows) == 40 and len({g[:3] for g in good}) == 20
PYWith the labels as given, the output is accurate passes 28/40, answers passes 33/40, next_step passes 31/40 and overall passes 20/40: exactly one answer per question passes all three. The pairwise test later relies on that, so if you changed labels, keep one passing answer per question.
Step 5 · Build the judge and grade the 40 answers
Create judge.py. The system prompt tells the judge to use the policy only and not to reward politeness or length; later steps test whether it listens. Ollama's format option takes a JSON schema, so the reply can only be {"verdict": "yes"} or {"verdict": "no"}. Anything that does not parse counts as invalid, and invalid counts as a fail. A judge that cannot answer should never pass an answer by accident.
cat > judge.py <<'PY'
import json
import os
from pathlib import Path
import ollama
MODEL = os.environ.get("JUDGE_MODEL", "qwen3:0.6b")
OPTIONS = {"temperature": 0, "seed": 42, "num_predict": 32}
POLICY = Path("data/policy.md").read_text(encoding="utf-8")
RUBRIC = json.loads(Path("data/rubric.json").read_text(encoding="utf-8"))
NAMES = [c["name"] for c in RUBRIC["criteria"]]
SYSTEM = """You check replies written by a customer support agent for an online shop.
You are given the shop policy, the customer's question and the agent's answer.
Decide using the policy only, not what you believe about shops in general.
Do not reward politeness or length. Reply with JSON only."""
VERDICT_SCHEMA = {
"type": "object",
"properties": {"verdict": {"type": "string", "enum": ["yes", "no"]}},
"required": ["verdict"],
}
def load_jsonl(path):
lines = Path(path).read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines if line.strip()]
def ask(user, schema):
response = ollama.chat(
model=MODEL,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": user},
],
format=schema,
think=False,
options=OPTIONS,
)
try:
reply = json.loads(response.message.content or "")
except json.JSONDecodeError:
return {}
return reply if isinstance(reply, dict) else {}
def grade(criterion, question, answer):
user = (
f"<policy>\n{POLICY}\n</policy>\n\n"
f"<customer_question>\n{question}\n</customer_question>\n\n"
f"<agent_answer>\n{answer}\n</agent_answer>\n\n"
f"<rubric_question>\n{criterion['question']}\n</rubric_question>\n\n"
'Reply {"verdict": "yes"} or {"verdict": "no"}.'
)
verdict = ask(user, VERDICT_SCHEMA).get("verdict")
return verdict if verdict in ("yes", "no") else "invalid"
def main():
rows = []
for item in load_jsonl("data/answers.jsonl"):
row = {"id": item["id"]}
for criterion in RUBRIC["criteria"]:
row[criterion["name"]] = grade(criterion, item["question"], item["answer"])
rows.append(row)
print(item["id"], " ".join(f"{n}={row[n]}" for n in NAMES))
out = Path("results/grades.jsonl")
out.write_text("".join(json.dumps(r) + "\n" for r in rows), encoding="utf-8")
print(f"judge {MODEL}: graded {len(rows)} answers on {len(NAMES)} criteria, saved {out}")
if __name__ == "__main__":
main()
PYRun it. That is 120 short calls; on a laptop CPU expect from under a minute to a few minutes:
uv run python judge.pyCheck it worked
uv run python - <<'PY'
import json
from collections import Counter
rows = [json.loads(l) for l in open("results/grades.jsonl", encoding="utf-8")]
counts = Counter(v for r in rows for k, v in r.items() if k != "id")
print(len(rows), "rows", dict(counts))
assert len(rows) == 40 and sum(counts.values()) == 120
PYYou see one line per answer, such as q01b accurate=no answers=yes next_step=yes, then a summary, and the check prints 40 rows with counts of yes, no and possibly invalid that add up to 120. Do not read the judge's grades against your labels by eye yet. The next step does it properly.
Step 6 · Measure agreement with Cohen's kappa
The obvious measure is percent agreement: how often the judge's yes or no matches yours. It misleads. In your labels answers passes 33 of 40 times, so a judge that says yes to everything agrees with you 82% of the time while learning nothing.
Cohen's kappa corrects for that. It compares the observed agreement with the agreement you would expect by chance given how often each of you says yes: kappa = (observed - chance) / (1 - chance). A judge that always says yes scores 0, perfect agreement scores 1, and a negative value means worse than chance. A common reading (Landis and Koch, 1977) calls 0.41 to 0.60 moderate and 0.61 to 0.80 substantial.
Create agreement.py. For each criterion, and for the overall pass, it prints both pass rates, percent agreement, kappa, and the two kinds of disagreement: lenient (judge passed, you failed) and strict (judge failed, you passed):
cat > agreement.py <<'PY'
import csv
import json
import math
from pathlib import Path
from sklearn.metrics import cohen_kappa_score, confusion_matrix
from judge import NAMES, load_jsonl
human = {r["id"]: r for r in csv.DictReader(open("data/labels.csv", encoding="utf-8"))}
judge = {r["id"]: r for r in load_jsonl("results/grades.jsonl")}
if set(human) != set(judge):
raise SystemExit("labels.csv and grades.jsonl must cover the same answers")
ids = sorted(human)
def vectors(name):
if name == "overall":
h = [int(all(human[i][n] == "1" for n in NAMES)) for i in ids]
j = [int(all(judge[i][n] == "yes" for n in NAMES)) for i in ids]
bad = sum(any(judge[i][n] == "invalid" for n in NAMES) for i in ids)
else:
h = [int(human[i][name]) for i in ids]
j = [int(judge[i][name] == "yes") for i in ids]
bad = sum(judge[i][name] == "invalid" for i in ids)
return h, j, bad
report = {}
print(f"{'criterion':<10} {'n':>3} {'human':>6} {'judge':>6} {'agree':>6} {'kappa':>6} "
f"{'lenient':>8} {'strict':>7} {'invalid':>8}")
for name in NAMES + ["overall"]:
h, j, bad = vectors(name)
tn, lenient, strict, tp = confusion_matrix(h, j, labels=[0, 1]).ravel()
kappa = float(cohen_kappa_score(h, j, labels=[0, 1]))
kappa = 0.0 if math.isnan(kappa) else kappa
n = len(ids)
row = {
"n": n,
"human_pass": sum(h) / n,
"judge_pass": sum(j) / n,
"agreement": (tn + tp) / n,
"kappa": round(kappa, 3),
"lenient": int(lenient),
"strict": int(strict),
"invalid": bad,
"lenient_ids": [i for i, a, b in zip(ids, h, j) if a == 0 and b == 1],
"strict_ids": [i for i, a, b in zip(ids, h, j) if a == 1 and b == 0],
}
report[name] = row
print(f"{name:<10} {n:>3} {row['human_pass']:>6.0%} {row['judge_pass']:>6.0%} "
f"{row['agreement']:>6.0%} {kappa:>6.2f} {row['lenient']:>8} {row['strict']:>7} {bad:>8}")
Path("results/agreement.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
PY
uv run python agreement.pyBefore you trust the script, prove it gives the textbook answers on two judges you can predict: one that agrees with you on everything, and one that says yes to everything:
uv run python - <<'PY'
from sklearn.metrics import cohen_kappa_score
import csv
h = [int(r["answers"]) for r in csv.DictReader(open("data/labels.csv", encoding="utf-8"))]
always_yes = [1] * len(h)
agree = sum(a == b for a, b in zip(h, always_yes)) / len(h)
print("perfect judge kappa", cohen_kappa_score(h, h))
print(f"always-yes judge: agreement {agree:.1%}, kappa {cohen_kappa_score(h, always_yes):.2f}")
assert cohen_kappa_score(h, h) == 1.0 and cohen_kappa_score(h, always_yes) == 0.0
PYCheck it worked
The sanity check prints perfect judge kappa 1.0 and always-yes judge: agreement 82.5%, kappa 0.00. That is the trap in one line: 82.5% agreement from a judge that does nothing.
The table has four rows: accurate, answers, next_step and overall. Read it in this order:
- Judge pass rate against human pass rate. If the judge column is higher, it is lenient. Leniency is the bias that hurts most in practice, because it makes a feature look better than it is.
- Kappa. Below about 0.6 the judge's yes and no are a weak signal on this criterion, however good the agreement column looks.
- Lenient against strict. A judge with 6 lenient and 0 strict misses failures; one with 0 lenient and 6 strict raises false alarms. They need different fixes.
Then open results/agreement.json and read the answers listed under lenient_ids for accurate. They tell you what the judge cannot see. If q10a is there, the judge accepted a 24-hour reset link that the policy plainly contradicts.
Step 7 · Test for position bias by asking in both orders
A pairwise judge reads two answers and picks the better one. Comparing two answers can be easier to apply consistently than an absolute grade, but it brings position bias: many judges favour the first answer, or the second, whatever they say. You cannot see this from one order. You have to swap the answers and ask again.
Your labels give a known better answer for each of the 20 questions, so you can score the judge on every pair in both orders. Create pairwise.py:
cat > pairwise.py <<'PY'
import csv
import json
from collections import defaultdict
from pathlib import Path
from judge import NAMES, POLICY, ask, load_jsonl
PAIR_SCHEMA = {
"type": "object",
"properties": {"better": {"type": "string", "enum": ["1", "2"]}},
"required": ["better"],
}
labels = {r["id"]: r for r in csv.DictReader(open("data/labels.csv", encoding="utf-8"))}
by_question = defaultdict(list)
for item in load_jsonl("data/answers.jsonl"):
by_question[item["qid"]].append(item)
def prefer(question, first, second):
user = (
f"<policy>\n{POLICY}\n</policy>\n\n"
f"<customer_question>\n{question}\n</customer_question>\n\n"
f"<answer_1>\n{first}\n</answer_1>\n\n"
f"<answer_2>\n{second}\n</answer_2>\n\n"
"Which answer is better for this customer? Judge accuracy against the policy first, "
"then whether it answers the question, then whether it gives a next step.\n"
'Reply {"better": "1"} or {"better": "2"}.'
)
choice = ask(user, PAIR_SCHEMA).get("better")
return choice if choice in ("1", "2") else None
rows = []
for qid, (x, y) in sorted(by_question.items()):
good = next(a["id"] for a in (x, y) if all(labels[a["id"]][n] == "1" for n in NAMES))
forward = prefer(x["question"], x["answer"], y["answer"])
backward = prefer(x["question"], y["answer"], x["answer"])
pick_forward = {"1": x["id"], "2": y["id"]}.get(forward)
pick_backward = {"1": y["id"], "2": x["id"]}.get(backward)
consistent = pick_forward is not None and pick_forward == pick_backward
rows.append({
"qid": qid, "good": good, "forward": forward, "backward": backward,
"consistent": consistent, "correct": consistent and pick_forward == good,
})
if rows[-1]["correct"]:
status = "correct"
elif consistent:
status = "wrong"
else:
status = "invalid" if None in (forward, backward) else "FLIPPED"
print(f"{qid} forward picks slot {forward} backward picks slot {backward} {status}")
n = len(rows)
summary = {
"pairs": n,
"consistent": sum(r["consistent"] for r in rows) / n,
"correct_both_orders": sum(r["correct"] for r in rows) / n,
"first_slot_share": sum((r["forward"] == "1") + (r["backward"] == "1") for r in rows) / (2 * n),
"invalid": sum((r["forward"] is None) + (r["backward"] is None) for r in rows),
}
Path("results/pairwise.json").write_text(json.dumps({"summary": summary, "rows": rows}, indent=2),
encoding="utf-8")
print(f"consistent in both orders {summary['consistent']:.0%}, "
f"correct in both orders {summary['correct_both_orders']:.0%}, "
f"first slot chosen {summary['first_slot_share']:.0%} of the time, invalid {summary['invalid']}")
PY
uv run python pairwise.pyCheck it worked
uv run python -c "import json; s = json.load(open('results/pairwise.json'))['summary']; print(s); assert s['pairs'] == 20"You see 20 lines and a summary. A line marked FLIPPED means the judge picked the same slot both times, so it chose a different answer when the order changed: on that pair it was following position, not content. The first slot chosen figure should sit near 50% for an unbiased judge, because each good answer appears once in each slot. A figure far from 50% is position bias in one number.
Two rules follow, whatever your figures:
- Always ask a pairwise judge in both orders and count only answers it picks both times. Treat a flip as a tie, not as half a win.
- Report "correct in both orders", not the forward-only accuracy. Forward-only accuracy hides the flips.
Step 8 · Test for length bias with padded answers
The system prompt says not to reward length. Check whether the judge listens. Take every answer you labelled inaccurate, add a polite paragraph that contains no facts at all, and grade accuracy again. Your label does not change, because politeness cannot fix a wrong delivery time. If the judge's verdict changes, it is reacting to length or tone.
Create padding.py:
cat > padding.py <<'PY'
import csv
import json
from pathlib import Path
from judge import RUBRIC, grade, load_jsonl
FILLER = (
"Thank you for taking the time to write to us, and we hope this message finds you well. "
"Please do not hesitate to contact us again if you have any other questions about your "
"order or anything else. Have a wonderful day."
)
labels = {r["id"]: r for r in csv.DictReader(open("data/labels.csv", encoding="utf-8"))}
before = {r["id"]: r for r in load_jsonl("results/grades.jsonl")}
accurate = next(c for c in RUBRIC["criteria"] if c["name"] == "accurate")
rows = []
for item in load_jsonl("data/answers.jsonl"):
if labels[item["id"]]["accurate"] != "0":
continue
padded = f"{item['answer']} {FILLER}"
after = grade(accurate, item["question"], padded)
rows.append({"id": item["id"], "before": before[item["id"]]["accurate"], "after": after,
"words_before": len(item["answer"].split()), "words_after": len(padded.split())})
print(f"{item['id']} plain={rows[-1]['before']:<7} padded={after:<7} "
f"words {rows[-1]['words_before']} -> {rows[-1]['words_after']}")
caught = [r for r in rows if r["before"] == "no"]
flipped = [r for r in caught if r["after"] == "yes"]
summary = {"inaccurate": len(rows), "caught_plain": len(caught), "flipped_by_padding": len(flipped),
"flipped_ids": [r["id"] for r in flipped]}
Path("results/padding.json").write_text(json.dumps({"summary": summary, "rows": rows}, indent=2),
encoding="utf-8")
print(f"{len(rows)} inaccurate answers; the judge caught {len(caught)} plain; "
f"{len(flipped)} of those passed once padded")
PY
uv run python padding.pyCheck it worked
uv run python -c "import json; s = json.load(open('results/padding.json'))['summary']; print(s); assert s['inaccurate'] == 12"You see 12 lines, one per inaccurate answer, each about 40 words longer once padded, then a summary line. Look only at answers the judge caught when they were plain (plain=no). Each one that turns into padded=yes is a wrong answer the judge passed because it got longer and friendlier. Even one matters: a feature that learns to pad its replies would rise in your scores while getting no better.
The same idea tests other biases you suspect. Self-preference, where a judge rates text from its own model family higher, needs answers written by two models: generate replies with the judge model and with a different one, label them all by hand, and compare the judge's leniency on each group. Where you can, use a judge from a different model family from the one that writes the answers.
If your assistant replies in Yoruba, Hausa, Swahili or a mix with English, label a set in each language and run the same agreement script on it. A judge's kappa on English answers tells you nothing about its kappa on Pidgin.
Step 9 · Decide when the judge can be trusted
Turn what you measured into rules a script can apply, so the decision is the same next month as today. Create trust.py. The thresholds are a starting point; write yours down and keep them fixed for a project:
- at least 30 hand-labelled answers behind every figure
- kappa of at least 0.6 on the criterion
- judge pass rate within 10 percentage points of the human pass rate (no strong leniency)
- no invalid replies
- for
accurate, no answer that passes once padded - for pairwise use, at least 90% of pairs picked the same in both orders, and on at least 90% of pairs that pick is the answer you labelled better (a judge that is consistently wrong is still wrong)
- for pairwise use, no invalid replies
cat > trust.py <<'PY'
import json
from judge import MODEL, NAMES
MIN_ITEMS, MIN_KAPPA, MAX_GAP, MIN_CONSISTENT, MIN_CORRECT = 30, 0.6, 0.10, 0.90, 0.90
agreement = json.load(open("results/agreement.json", encoding="utf-8"))
pairwise = json.load(open("results/pairwise.json", encoding="utf-8"))["summary"]
padding = json.load(open("results/padding.json", encoding="utf-8"))["summary"]
print(f"judge: {MODEL}")
for name in NAMES + ["overall"]:
row = agreement[name]
problems = []
if row["n"] < MIN_ITEMS:
problems.append(f"only {row['n']} labelled answers")
if row["kappa"] < MIN_KAPPA:
problems.append(f"kappa {row['kappa']:.2f} < {MIN_KAPPA}")
gap = row["judge_pass"] - row["human_pass"]
if abs(gap) > MAX_GAP:
problems.append(f"pass rate {'above' if gap > 0 else 'below'} yours by {abs(gap):.0%}")
if row["invalid"]:
problems.append(f"{row['invalid']} invalid replies")
if name in ("accurate", "overall") and padding["flipped_by_padding"]:
problems.append(f"{padding['flipped_by_padding']} wrong answers passed once padded")
verdict = "TRUST" if not problems else "DO NOT TRUST"
print(f" {name:<10} {verdict:<13} {'; '.join(problems)}")
problems = []
if pairwise["consistent"] < MIN_CONSISTENT:
problems.append(f"same pick in both orders on {pairwise['consistent']:.0%} of pairs")
if pairwise["correct_both_orders"] < MIN_CORRECT:
problems.append(f"picked your better answer in both orders on {pairwise['correct_both_orders']:.0%} of pairs")
if pairwise["invalid"]:
problems.append(f"{pairwise['invalid']} invalid replies")
print(f" {'pairwise':<10} {'TRUST' if not problems else 'DO NOT TRUST':<13} {'; '.join(problems)}")
PY
uv run python trust.py | tee trust.txtCheck it worked
test "$(grep -cE '^ (accurate|answers|next_step|overall|pairwise) +(TRUST|DO NOT TRUST)' trust.txt)" -eq 5 && echo 5It prints 5, and the check fails if any verdict line is missing: one verdict line each for the three criteria, the overall pass and pairwise use, with the reasons after any DO NOT TRUST. With a 0.6B judge, read the reasons rather than hoping for all TRUST; they say which bias to work on.
What you do with a DO NOT TRUST:
- Rewrite the rubric question first. Read the disagreeing answers in
results/agreement.json. If your own rule did not settle them, sharpen it and relabel. - Then try a stronger judge. Run the whole set again with
JUDGE_MODEL=qwen3:4b uv run python judge.py, then the other scripts, afterollama pull qwen3:4b. Larger models usually agree more, but measure it. - Otherwise keep humans on that criterion. A judge can still sort answers for you to read first; it cannot sign off on them.
And the rules that apply even after a TRUST:
- Relabel a fresh sample of at least 30 answers whenever the judge model, the judge prompt, the rubric or the feature under test changes. Agreement on last month's answers does not carry over to a new kind of output.
- Never compare scores from two different judges or judge prompts. A rise from 70% to 78% after a judge change is a change in the ruler.
- Keep a person on every decision near a threshold, and spot-check a few judge passes each week, picked at random.
Next steps
You now have a judge you have measured instead of assumed, and scripts that rerun the measurement whenever something changes.
- Build the labelled set your judge is checked against from real traffic in Build a golden test set for an LLM feature.
- Use judge scores to decide whether a prompt change helped, with proper uncertainty, in Tell whether a prompt change really helped, with paired evals and confidence intervals.
- Apply the same thinking to retrieval and answers together in How to Evaluate and Improve a RAG App with a Test Set.
- See how examples in a prompt change a small model's behaviour in Improve LLM answers with few-shot examples and measure the difference.
Part of these paths
Related tutorials
- Build a golden test set for an LLM featureYou will write 60 labelled test cases for a ticket-triage feature, split them into a development set and a held-back set, grade a local model's answers with deterministic pytest checks, and end with a pass rate for each kind of case and a gate that fails when one drops.
- How to Evaluate and Improve a RAG App with a Test SetYou will write a test set of questions with known answers, measure retrieval with hit rate and mean reciprocal rank and the full pipeline with pass or fail checks, then use the results to add a distance cutoff that makes the app decline questions it cannot answer.
- Tell whether a prompt change really helped, with paired evals and confidence intervalsYou will take recorded pass and fail results for two prompt versions on the same 60 test cases, compute the difference with a paired bootstrap confidence interval and McNemar's test, measure run-to-run noise, work out how many cases a 5-point change needs, and end with a written decision rule that prints adopt, keep or undecided.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials