An LLM-as-a-judge evaluator is a second model call that grades your system's output against a written rubric and returns a structured verdict. It is only trustworthy once you have measured its agreement with human labels on your own data, and you have controlled for the biases the research has already documented. This guide builds one in Python step by step: rubric, structured scores, pairwise judging with order swapping, and calibration with Cohen's kappa.
This is a build guide, not a tool roundup. If you are choosing a framework, see our LLM evaluation frameworks comparison and DeepEval vs Promptfoo. Everything below runs inside any of them, or on its own.
What the research actually says about LLM judges
Most of what people repeat about LLM judges comes from a few papers. Here is what each one claims.
Zheng et al. (2023), Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (NeurIPS 2023 Datasets and Benchmarks):
- It defines three judge types: pairwise comparison, single-answer grading and reference-guided grading.
- It names four limitations: position bias, verbosity bias, self-enhancement bias and limited ability to grade math and reasoning.
- Position bias: when two similar answers were swapped, GPT-4 gave the same verdict in 65% of cases. Claude-v1 managed 23.8%, and most judges favored the first position.
- Verbosity bias: in a "repetitive list" attack, answers were padded with rephrased duplicate items. The attack fooled Claude-v1 and GPT-3.5 on 91.3% of 23 answers and GPT-4 on 8.7%.
- Self-enhancement bias: GPT-4 favored itself with a roughly 10% higher win rate, but the authors say their data could not determine whether self-enhancement bias exists.
- Agreement: on MT-bench (setup S2, ties excluded), GPT-4 agreed with human experts 85% of the time. Humans agreed with each other 81% of the time.
- Single vs pairwise: single-answer grading scales better. Pairwise comparisons grow quadratically with the number of systems, but absolute scores fluctuate more when you change the judge model.
Wang et al. (2023), Large Language Models are not Fair Evaluators:
- Reordering answers alone let Vicuna-13B beat ChatGPT on 66 of 80 queries when ChatGPT was the evaluator.
- The proposed fixes are generating evaluation evidence before the rating, aggregating scores across both orders, and sending hard cases to humans.
Panickssery, Bowman and Feng (2024), LLM Evaluators Recognize and Favor Their Own Generations:
- GPT-4 and Llama 2 can tell their own outputs apart from others' with non-trivial accuracy.
- After fine-tuning, the strength of self-preference correlated linearly with self-recognition ability.
Liu et al. (2023), G-Eval:
- Chain-of-thought plus a form-filling output reached a Spearman correlation of 0.514 with humans on summarization.
- The authors flag a possible bias toward LLM-generated text.
The practical consequences: write the rubric so length is not rewarded, swap positions in pairwise mode, don't let a model grade its own family's output without checking, and never trust a judge you have not compared against humans.
Pointwise, pairwise or reference-based
| Mode | Input to judge | Output | Use it for | Main risk |
|---|---|---|---|---|
| Pointwise (single-answer) | question, context, one answer | score / pass-fail | regression tests, production monitoring, dashboards | scores drift when the judge model changes |
| Pairwise | question, answers A and B | A / B / tie | choosing between two prompts or models | position bias; cost grows with number of variants |
| Reference-guided | question, answer, gold answer | correct / incorrect + score | math, extraction, factual QA with known answers | needs gold answers; judge may over-match wording |
My default: use pointwise pass/fail plus a 1–5 score for CI and monitoring. Use pairwise with swapping only when you're deciding between two candidates. Use reference-guided whenever a correct answer exists. Zheng et al. found that GPT-4 was misled into accepting wrong math answers it could solve on its own. Showing it a reference answer cut the failure rate from 14/20 to 3/20.
Step 1: write a rubric a human could apply
If two of your engineers can't apply the rubric and mostly agree, the model won't either. Rules that hold up:
- Grade one thing per criterion. "Faithful" (every claim is supported by the context) is separate from "complete" (it answers the question). A judge asked about "quality" mixes them together.
- Anchor every score level with an observable condition, not adjectives like "good" or "excellent".
- Say what is not a criterion. Telling the judge that length and tone don't count is a cheap counter to verbosity bias. It doesn't remove the bias, so you still measure it.
- Put reasoning before the verdict. Both OpenAI's evaluation guide and G-Eval recommend reasoning before scoring. In a structured schema, make
reasoningthe first field so it is generated first. - Prefer binary checks when you can. "Contains an unsupported claim: yes/no" is easier to calibrate than a 1–10 scale. OpenAI's guide also recommends pass/fail or pairwise for reliability.
Step 2: get structured verdicts, not prose
Free-text verdicts that you parse with a regex will eventually break. The OpenAI Python SDK (verified against openai 3.52.0, released 16 November 2026) can parse straight into a Pydantic model through the Responses API's Structured Outputs support. Keep the model name in a variable. Judge models are the thing you will swap most often.
import os
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel, Field
JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "gpt-6.1-sol")
client = OpenAI()
RUBRIC = """You grade answers from a customer-support assistant.
Judge ONLY against the criteria below. Length and tone are not criteria.
faithful: every factual claim in the answer is supported by the CONTEXT.
An answer that adds a plausible fact not in the CONTEXT is NOT faithful.
score (1-5):
5 = fully answers the question, faithful, no irrelevant content
4 = answers the question, faithful, minor omission
3 = partially answers OR includes irrelevant content
2 = mostly fails to answer, or contains one unsupported claim
1 = wrong, refuses without reason, or multiple unsupported claims
Write your reasoning first, then the verdict."""
class PointwiseVerdict(BaseModel):
reasoning: str = Field(description="Cite the criteria met or missed")
faithful: bool
score: int = Field(ge=1, le=5)
def judge_pointwise(question: str, context: str, answer: str) -> PointwiseVerdict:
response = client.responses.parse(
model=JUDGE_MODEL,
instructions=RUBRIC, # static prefix first: cache-friendly
input=f"QUESTION:\n{question}\n\nCONTEXT:\n{context}\n\nANSWER:\n{answer}",
text_format=PointwiseVerdict,
store=False,
)
if response.output_parsed is None: # refusal or incomplete output
raise RuntimeError(f"No verdict: status={response.status}")
return response.output_parsed
Notes on that code:
- Schema:
responses.parseturns the Pydantic model into a strict JSON schema. Thege/lebounds becomeminimum/maximum, which Structured Outputs supports. Field order is preserved, soreasoningis generated first. - Refusals: Structured Outputs constrains completed, non-refusal output only. Check
output_parsedforNoneand treat that as an error, not a score of zero. - Model choice: OpenAI's guide suggests starting with its strongest model as the judge, then checking agreement before moving to a cheaper one. As of November 2026 that is
gpt-6-astra. I default togpt-6.1-solfor cost and then calibrate. Whichever you pick, calibration decides, not the model name. - Self-preference: if your product runs on the same model family, at least test a judge from another family on the calibration set. That is the risk Panickssery et al. describe.
Step 3: pairwise judging with order swapping
This implements the conservative rule from Zheng et al. Call the judge twice with the answers swapped. Declare a winner only if it wins in both orders. Otherwise it is a tie.
PAIRWISE_RUBRIC = """Compare two answers to the same question.
Pick the answer that is more correct and more useful to the user.
Do not prefer an answer because it is longer or appears first.
If they are equivalent in quality, answer "tie"."""
class PairwiseVerdict(BaseModel):
reasoning: str
winner: Literal["A", "B", "tie"]
def _pairwise_once(question: str, first: str, second: str) -> str:
response = client.responses.parse(
model=JUDGE_MODEL,
instructions=PAIRWISE_RUBRIC,
input=(f"QUESTION:\n{question}\n\n"
f"ANSWER A:\n{first}\n\nANSWER B:\n{second}"),
text_format=PairwiseVerdict,
store=False,
)
if response.output_parsed is None:
raise RuntimeError(f"No verdict: status={response.status}")
return response.output_parsed.winner
def judge_pairwise(question: str, answer_x: str, answer_y: str) -> str:
"""Returns 'x', 'y' or 'tie'. Conservative swap rule from Zheng et al. (2023)."""
run1 = _pairwise_once(question, answer_x, answer_y) # x is A
run2 = _pairwise_once(question, answer_y, answer_x) # x is B
if run1 == "A" and run2 == "B":
return "x"
if run1 == "B" and run2 == "A":
return "y"
return "tie" # inconsistent across orders, or a genuine tie
I tested this against a mocked endpoint with a fake judge that always answers "A". judge_pairwise returned "tie", which is exactly what the swap rule is for. Log the inconsistent-order rate as its own metric. If it climbs after a model upgrade, your judge has become more position-biased.
Step 4: calibrate against human labels
This step is what makes the judge trustworthy. The workflow:
- Sample 100–200 real outputs from production logs or your test set. Include known failures, not only the easy cases.
- Label them with people, ideally two reviewers working blind to each other. Measuring human-to-human agreement first tells you the ceiling. Zheng et al.'s 81% human-human figure is a reminder that humans disagree too.
- Run the judge on the same items.
- Compute agreement and read the disagreements one by one. Fix the rubric, not just the threshold.
- Freeze the rubric, judge model and calibration set together as a versioned artifact.
Raw percent agreement is inflated when one label dominates. If 90% of answers pass, a judge that always says "pass" scores 90%. Cohen's kappa corrects for chance agreement. Here is a dependency-free implementation:
from collections import Counter
def cohen_kappa(rater_a: list, rater_b: list) -> float:
"""Unweighted Cohen's kappa for two raters over the same items."""
assert len(rater_a) == len(rater_b) and rater_a, "need paired, non-empty labels"
n = len(rater_a)
p_observed = sum(a == b for a, b in zip(rater_a, rater_b)) / n
count_a, count_b = Counter(rater_a), Counter(rater_b)
labels = set(count_a) | set(count_b)
p_expected = sum((count_a[l] / n) * (count_b[l] / n) for l in labels)
if p_expected == 1.0: # both raters used a single identical label
return 1.0
return (p_observed - p_expected) / (1 - p_expected)
I checked this against sklearn.metrics.cohen_kappa_score on 200 random label sets and the results matched exactly. One edge case differs: when both raters use the same single label, scikit-learn returns NaN and this function returns 1.0. For 1–5 scores, use weighted kappa, because an off-by-one disagreement is not as bad as 1 vs 5:
from sklearn.metrics import cohen_kappa_score, confusion_matrix
human = [5, 4, 2, 5, 1, 3, 4, 2, 5, 3]
judge = [5, 5, 2, 4, 1, 3, 4, 3, 5, 2]
print(cohen_kappa_score(human, judge)) # 0.487 (rounded)
print(cohen_kappa_score(human, judge, weights="quadratic")) # 0.891 (rounded)
# Collapse to the decision you actually ship on: pass = score >= 4
print(confusion_matrix([s >= 4 for s in human], [s >= 4 for s in judge],
labels=[True, False]))
On that toy data, unweighted kappa is 0.487 but quadratic-weighted kappa is 0.891. Every disagreement is one point apart, and at the pass/fail threshold the confusion matrix shows no disagreements at all. Report the metric that matches the decision you make with the score. For a gate, that is agreement on pass/fail, plus the false-pass rate: items humans failed that the judge passed. False passes are the failures that reach users.
There is no universal kappa threshold that makes a judge "good enough". Compare it with your human-human kappa on the same items. If the judge agrees with humans about as well as humans agree with each other, you're done. If not, read the disagreements, because they usually point to a vague rubric criterion.
Combining the judge with human review
Many teams search for "tools that combine LLM-as-judge with human review". The pattern matters more than the tool:
- Route uncertainty to people. Send items to a review queue when the pairwise verdict flips across orders, when the score lands on the pass/fail boundary, or when two judge models disagree. This is the same idea as Wang et al.'s human-in-the-loop calibration.
- Feed reviews back into calibration. Every human-reviewed item becomes a labelled example for the next kappa check.
- Tooling exists for the plumbing. Langfuse documents both LLM-as-a-judge evaluators and annotation queues. LangSmith has annotation queues and LLM-as-a-judge evaluators. Our LangSmith vs Langfuse comparison covers the differences.
One date to note: OpenAI's deprecations page lists the hosted Evals dashboard, API and graders for eval workflows as going read-only on 30 November 2026, and recommends Promptfoo. If your judge lived there, keeping the judge in your own code, as above, is the portable option.
Cost control
A judge call often costs more than the call being judged, because it reads the question, the context and the answer. Ways to keep the bill in check:
- Use batch for offline evals. OpenAI's Batch API supports
/v1/responses, gives a 50% discount, and completes within 24 hours. That fits nightly regression runs. - Put static content first. Keep the rubric in
instructionsand the variable content ininput. Prompt caching works on exact prefix matches. See Prompt Caching Explained. - Use a cascade. A cheap judge screens everything and a stronger judge re-grades only items near the boundary. Calibrate both.
- Sample production traffic. Judging every request is rarely necessary. A fixed daily sample plus every item that a user flagged is usually enough to spot drift.
- Remember swapping doubles pairwise cost. Reserve pairwise mode for decisions between candidates, and use pointwise for monitoring.
Prices change. Check the OpenAI pricing page for current judge-model rates as of when you read this (November 2026 at the time of writing).
Frequently Asked Questions
What is LLM-as-a-judge?
It is using a language model to grade another model's output against explicit criteria, instead of using string-overlap metrics or only human review. Zheng et al. (2023) define three variants: pairwise comparison, single-answer grading and reference-guided grading. It scales far better than human review, but it only stays reliable if you calibrate it against human labels.
How many human labels do I need to calibrate a judge?
There is no magic number. A practical starting point is 100–200 items that cover your real failure modes. That is enough to read every disagreement and to estimate kappa roughly. Add items whenever production surfaces a new failure type, and re-run calibration whenever you change the judge model or rubric.
Should the judge be a different model from the one being evaluated?
Prefer a different model family where possible. Panickssery et al. (2024) showed that LLMs can recognize, and favor, their own generations. Zheng et al. saw self-favoring patterns but could not confirm the bias statistically. Either way, measure it: run both candidate judges on your calibration set and compare kappa.
How do I detect hallucinations with an LLM judge?
Use a reference-based or context-grounded check. Give the judge the retrieved context and ask a binary question: is every factual claim supported by it? Binary faithfulness checks calibrate more easily than holistic scores. Track the false-pass rate specifically, because missed hallucinations are the costly errors.
Is pairwise or pointwise judging more reliable?
Zheng et al. found that pairwise judging can be slightly better, but single-answer grading is more scalable and matched human preferences well with GPT-4. Pairwise is the better tool for choosing between two variants, as long as you swap positions. Pointwise is the practical choice for CI gates and monitoring.
Bottom Line
A reliable LLM judge needs four things: a rubric a human could apply, a structured verdict with reasoning first, position swapping in pairwise mode, and a kappa check against human labels that you repeat whenever anything changes. The research is consistent that judges are biased toward position, length and possibly their own outputs. It is equally consistent that a well-calibrated strong judge can track human judgment closely. Version the rubric, judge model and calibration set together. When you need to inspect raw verdict payloads, a JSON formatter makes them quick to read.