Code checks, LLM-as-judge & human review
Score outputs automatically and calibrate an LLM judge against human labels.
By Invicly Tech, , in AI Engineering with Python. About 13 minutes to read.
In short
Outputs can be scored by code checks, by an LLM judge using a rubric, or by people. Good eval suites use cheap code checks wherever possible and calibrate LLM judges against human labels.
Explained simply
Once you have test cases, you need a way to score the answers. There are three kinds of grader: code, another model (called an LLM judge), and people. Good eval suites use all three, each for what it does best.
Code checks are the first choice whenever they fit. Is the output valid JSON? Does it include the order number? Is it under 100 words? Did it use the refusal phrase? Code answers these instantly, for free, and the same way every time.
Many qualities cannot be checked by code. Is the answer helpful? Polite? Supported by the sources? An LLM judge reads the answer with a written rubric and returns pass or fail with a reason. It is cheap and scales, but it can be wrong, so you first check it against human labels.
Human review is the ground truth. People label a sample, you compare the judge with them, and you read every case where they disagree. Those disagreements teach you the most.
Press Play on a diagram to walk through it one step at a time.
- Exact match, regex, JSON valid
- Fast, cheap, deterministic
- Only for checkable properties
- Rubric-based grading
- Handles open-ended answers
- Can be biased; needs calibration
- Ground truth for quality
- Slow and costly
- Use for calibration and disagreements
- 1Code checks
Format, required fields, banned words
- 2Gate
Broken format fails without a judge call
- 3LLM judge
One criterion per rubric
- 4Human sample
Spot-check and calibrate
- 5Report per metric
Separate scores, not one blend
In depth
Code checks go further than you think
Before reaching for a judge, list every property you can test with code. Format: does the output parse as JSON and match the schema? Content: is a required value present (5 business days), is a banned phrase absent (we guarantee), does it use the exact refusal sentence? Length: under a word or token limit? Citations: are all cited IDs valid? Tools: did the agent call the right tool with the right arguments? Numbers: is the computed total within a small tolerance of the expected value?
Keep each check separate and report it as its own metric, such as valid_json 100%, cites_source 92%, refusal_correct 88%, instead of one blended score. Separate metrics tell you what broke.
Code checks also make good gates: if the output is not valid JSON, there is no point paying a judge to grade it.
- Schema validation for structured output
- Regex for required or banned phrases
- Exact refusal phrase match
- Correct tool name and arguments
- Numeric tolerance for computed values
Writing a judge rubric that works
Rate the quality from 1 to 10 is a weak rubric. Two runs disagree, and nobody knows what a 6 means. Strong rubrics judge one criterion at a time, with a binary verdict and a clear definition. For example: PASS if every factual claim in the answer is supported by the context; FAIL if any claim is missing from or contradicts the context.
Give the judge what it needs: the question, the answer, and the context or reference answer. Include one or two short examples of a pass and a fail. Ask for a brief reasoning first and the verdict last, using structured output such as a JSON object with reasoning and verdict fields, so the verdict is easy to parse and the reasoning is there when you review.
Use a capable model at low temperature, and keep the judge prompt versioned in Git like any other prompt.
- 1Gather inputs
Question, answer, context or reference
- 2Apply rubric
One criterion, PASS and FAIL defined
- 3Show examples
A short pass and a short fail
- 4Reason first
Brief explanation before the verdict
- 5Parse verdict
Structured JSON, PASS or FAIL
Known judge biases
LLM judges have predictable biases. Position bias: when comparing two answers, many judges favour the one shown first (or second). Verbosity bias: longer, more detailed answers tend to score higher even when they are not better. Self-preference: a model may rate answers written by itself or its own model family more kindly. Leniency: judges often pass borderline answers that a strict expert would fail.
Each bias has a counter. For pairwise comparisons, run the judge twice with the order swapped and count only consistent wins. Tell the judge explicitly that length is not a quality signal, and add a length check in code if conciseness matters. Where possible, use a judge from a different model family than the one being graded. To fight leniency, include clear fail examples in the rubric and calibrate against strict human labels.
- Position bias: swap order, keep consistent wins
- Verbosity bias: say length is not quality
- Self-preference: use a different model family
- Leniency: add fail examples, calibrate
Calibrating the judge against human labels
Before trusting a judge, measure it. Have a domain expert label 50 to 100 real outputs as pass or fail. Run the judge on the same outputs and compare.
Raw agreement can mislead. If 90% of outputs pass and the judge passes everything, agreement is 90% while it catches zero failures. So also measure two rates: of the outputs humans passed, how many did the judge pass (true positive rate), and of the outputs humans failed, how many did the judge fail (true negative rate). The second number is usually the one that matters, because failures are what you are hunting. Cohen's kappa is a single number that corrects agreement for chance: 1 is perfect, 0 is no better than guessing.
Improve the rubric on part of the labelled data and check the final version on the rest, so you do not overfit the judge to the cases you looked at.
- 1Label a sample
Expert marks pass or fail
- 2Run the judge
Same outputs, same rubric
- 3Compare
Agreement, TPR, TNR, kappa
- 4Read disagreements
Judge wrong, label wrong, or unclear?
- 5Fix rubric or labels
Then run again
- Back to step 1
Reviewing disagreements by hand
Every case where the judge and the human disagree falls into one of three buckets. The judge is wrong: the rubric is unclear or misses a rule, so fix the wording or add an example. The human is wrong: a tired labeller made a mistake or the guideline was ambiguous, so fix the label and clarify the guideline. The case is genuinely ambiguous: reasonable people could disagree, so decide the policy explicitly and write it down.
Keep a simple review sheet with the case, both verdicts, the judge's reasoning and your decision. Patterns appear quickly, for example the judge always passes answers that are correct but miss the citation.
Calibration is not one-off. User questions drift and models change, so re-check the judge on a fresh human-labelled sample every month or after changing the judge model.
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Write deterministic code checks~45m
- 2Build an LLM-as-judge rubric~45m
- 3Calibrate the judge against human labels~45m
- 4Review disagreements by hand~45m
Key points
- Use code checks for anything objective: format, required fields, banned words.
- Give LLM judges a specific rubric and ask for a short reason with each score.
- Measure judge agreement with human labels before trusting it.
- Review disagreements by hand; they reveal unclear rubrics or real bugs.
Key terms
Tap a card to flip it. 0/5 known
Examples
import json
def code_checks(output: str) -> dict[str, bool]:
try:
data = json.loads(output)
except json.JSONDecodeError:
return {'valid_json': False}
return {
'valid_json': True,
'has_answer': bool(data.get('answer')),
'cites_source': len(data.get('sources', [])) > 0,
}
JUDGE_RUBRIC = 'PASS if the answer is fully supported by the context, else FAIL. Give one reason.'Deterministic checks first, then a strict judge rubric.
Pairwise comparison with an order swap
You want to know whether prompt v4 beats v3. For each case you have two answers. Step 1: ask the judge which answer is better with v3 shown first. Step 2: ask again with v4 shown first. Step 3: count a win only when the judge picks the same underlying answer both times. Step 4: if it flips, record a tie, because the order, not the content, decided. Over 100 cases, compare wins for each version and look at how many ties you got; many ties means the judge or the rubric is not sharp enough.
def pairwise(judge, question: str, a: str, b: str) -> str:
"""judge(question, first, second) returns 'first' or 'second'."""
run1 = judge(question, a, b)
run2 = judge(question, b, a)
if run1 == "first" and run2 == "second":
return "a"
if run1 == "second" and run2 == "first":
return "b"
return "tie" # the verdict followed the position, not the contentCalibrating a faithfulness judge with real numbers
An expert labels 60 answers: 45 pass and 15 fail. The judge agrees on 42 of the 45 passes and 9 of the 15 fails. Agreement is 51 of 60, or 85%, which looks fine. But the true negative rate is only 9 of 15 (60%): the judge misses 4 in 10 real failures. Cohen's kappa is about 0.57. You read the 6 missed failures: all had one small unsupported number. You add a fail example with a wrong number to the rubric and re-run on held-out cases, where it now catches 13 of 15 failures.
def judge_report(human: list[bool], judge: list[bool]) -> dict:
n, pos = len(human), sum(human)
tp = sum(h and j for h, j in zip(human, judge))
tn = sum(not h and not j for h, j in zip(human, judge))
po = (tp + tn) / n
ph, pj = pos / n, sum(judge) / n
pe = ph * pj + (1 - ph) * (1 - pj)
return {"agreement": round(po, 2), "tpr": round(tp / pos, 2),
"tnr": round(tn / (n - pos), 2), "kappa": round((po - pe) / (1 - pe), 2)}
human = [True] * 45 + [False] * 15
judge = [True] * 42 + [False] * 3 + [False] * 9 + [True] * 6
print(judge_report(human, judge)) # agreement 0.85, tnr 0.6, kappa 0.57Quick reference
- Use code checks for anything objective: schema, required values, banned phrases, length
- Report each check as its own metric instead of one blended score
- Judge one criterion per rubric, with PASS and FAIL defined and a short example of each
- Ask the judge for brief reasoning first and the verdict last, as structured output
- Pairwise judging: run both orders and count only consistent wins
- Calibrate on 50 to 100 human labels; check true negative rate, not just agreement
- Cohen's kappa: 1 is perfect, 0 is chance-level agreement
- Re-calibrate after changing the judge model or when user traffic shifts
Common mistakes
- Trusting an uncalibrated LLM judge as ground truth.
- Using vague 1 to 10 scores without defining each level.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write code_checks(output, case) that returns separate booleans for: valid JSON, has a non-empty answer field, answer under 120 words, and does not contain the word guarantee.
- Exercise 2medium
Write a faithfulness judge prompt template with one criterion, PASS and FAIL definitions, and a required JSON output with reasoning and verdict. Then write a parser that defaults to FAIL on bad output.
- Exercise 3hard
Given lists of case IDs, human labels and judge labels, print a disagreement review sheet as CSV with columns id, human, judge, and an empty decision column, sorted so judge false passes come first.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is LLM-as-a-judge reliable?
- It can be, for clear single-criterion rubrics, once you have measured its agreement with human labels. Uncalibrated judges often pass too much.
- Should the judge be the same model as the app?
- Prefer a different and capable model where possible, since models can favour their own outputs. Whatever you choose, calibrate it.
- How many human labels do I need to calibrate a judge?
- Around 50 to 100 labelled outputs, with enough failures among them, is a practical start. More labels give tighter estimates.
- What is Cohen's kappa?
- A measure of agreement between two graders that corrects for agreement expected by chance. 1 means perfect agreement and 0 means no better than chance.