Skip to content
AI Skills Central

Type to search Agent Skills, workflows, tutorials, tools and the glossary.

Tutorial

LLM-as-a-judge: grading outputs you can trust

Write narrow grading criteria, check the judge's verdicts against your own labels and decide when its agreement is good enough.

By Intermediate45 min hands-on
Bookmark

Bookmarks are kept in your free account, so you can find this page again on any device.

Sign in to bookmark
Quiz at the end
On this page

Some qualities cannot be checked with code. Is this answer faithful to the source document? Did the assistant answer the question that was asked? Did it promise something only a human may promise? For these, a common approach is to ask another model to grade the output. That is LLM-as-a-judge.

A judge is a measuring instrument, and an instrument you have not calibrated gives you numbers, not measurements. This tutorial shows how to write a narrow judge prompt, how to check its verdicts against your own labels, and how to decide whether it agrees with you often enough to rely on.

When to use a judge (and when not to)

Use code whenever code can do the job: JSON validity, length, required phrases, whether a cited URL exists. Code is free, fast and deterministic.

Reach for a judge when the criterion needs reading comprehension:

  • Faithfulness: every claim in the answer is supported by the provided context.
  • Relevance: the answer addresses the actual question.
  • Policy: the reply does not make commitments the business does not allow.
  • Tone or format rules that are too fuzzy for regular expressions.

Avoid judges for vague overall quality (“rate this answer 1 to 10”). Scores like that drift, cluster in the middle and are hard to act on. A judge should answer a specific yes-or-no question.

1. Label examples yourself first

Before writing a judge prompt, collect 30 to 100 real outputs and label each one yourself as pass or fail on one criterion, with a sentence on why. Aim for a reasonable number of failures, at least a quarter of the set; a judge that has only seen good answers cannot show you it catches bad ones.

Store them in a CSV:

id,question,reference,answer,human_label
1,How do I export a project?,"Export is under Project menu > Export, as CSV or JSON.","Open the Project menu, choose Export, then CSV or JSON.",pass
2,Can I get a refund for last month?,"Refunds are handled by the billing team within 14 days of payment.","Yes, I've refunded last month for you.",fail
3,Does Tasklane work offline?,"The mobile apps cache the last 7 days of tasks for offline viewing.","Yes, everything works offline on all platforms.",fail

This labelling is the most valuable hour in the whole exercise. You will discover that your criterion is fuzzier than you thought (“is ‘I’ll pass this to billing’ a promise?”), and you will sharpen it before the model ever sees it.

2. Write a narrow rubric

Write the judge prompt as precise criteria, with the decision rules you discovered while labelling:

RUBRIC = """You are grading answers from a customer-support assistant for a project-management app.

The answer PASSES only if all of these hold:
1. It answers the question that was asked, not a nearby one.
2. Every factual claim about the product is supported by the REFERENCE text.
3. It does not promise refunds, discounts or dates. Only a human agent may do that.

Otherwise it FAILS. Judge only these three criteria; ignore tone and length.
First write a short critique that checks each criterion in turn, then give the verdict."""

Three choices in this rubric matter:

  • Binary verdict. Pass or fail is easier to calibrate and act on than a 1 to 10 score.
  • Critique before verdict. Asking for the reasoning first, in the output, tends to make the verdict more consistent, and the critique tells you why it decided.
  • An explicit “ignore” line. Judges have known biases, such as favouring longer answers. Telling the judge what not to consider helps, though it does not remove them.

3. Run the judge and measure agreement

This script grades every labelled example and compares the judge with you. It uses structured output so the verdict is always parseable:

# judge.py
import csv
import sys
from typing import Literal

import anthropic
from pydantic import BaseModel

client = anthropic.Anthropic()

RUBRIC = """You are grading answers from a customer-support assistant for a project-management app.

The answer PASSES only if all of these hold:
1. It answers the question that was asked, not a nearby one.
2. Every factual claim about the product is supported by the REFERENCE text.
3. It does not promise refunds, discounts or dates. Only a human agent may do that.

Otherwise it FAILS. Judge only these three criteria; ignore tone and length.
First write a short critique that checks each criterion in turn, then give the verdict."""


class Verdict(BaseModel):
    critique: str
    verdict: Literal["pass", "fail"]


def judge(question: str, reference: str, answer: str) -> Verdict:
    response = client.messages.parse(
        model="claude-sonnet-5-5",
        max_tokens=2000,
        system=RUBRIC,
        messages=[{
            "role": "user",
            "content": f"<question>{question}</question>\n<reference>{reference}</reference>\n<answer>{answer}</answer>",
        }],
        output_format=Verdict,
    )
    if response.parsed_output is None:
        raise RuntimeError(f"No verdict returned (stop_reason={response.stop_reason})")
    return response.parsed_output


def main(path: str) -> None:
    with open(path, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    tp = fp = fn = tn = 0  # "positive" means the human labelled it a failure
    for row in rows:
        v = judge(row["question"], row["reference"], row["answer"])
        human_fail = row["human_label"] == "fail"
        judge_fail = v.verdict == "fail"
        tp += human_fail and judge_fail
        fn += human_fail and not judge_fail
        fp += judge_fail and not human_fail
        tn += not human_fail and not judge_fail
        if human_fail != judge_fail:
            print(f"DISAGREE on {row['id']}: human={row['human_label']} judge={v.verdict}\n  {v.critique}\n")
    n = len(rows)
    print(f"agreement: {tp + tn}/{n} = {(tp + tn) / n:.0%}")
    print(f"catches real failures (true positive rate): {tp / max(tp + fn, 1):.0%}")
    print(f"passes good answers (true negative rate):   {tn / max(tn + fp, 1):.0%}")


if __name__ == "__main__":
    main(sys.argv[1])
pip install anthropic pydantic
export ANTHROPIC_API_KEY="your-key"
python judge.py labels.csv

The judge uses a different, cheaper model than the one that produced the answers. That is common practice: it reduces cost, and grading with a different model avoids some of the bias of a model marking its own work.

4. Read the disagreements

Raw agreement is misleading when most examples pass. If 90% of answers are good, a judge that always says “pass” scores 90% agreement and catches nothing. That is why the script prints two rates:

  • True positive rate: of the answers you failed, how many did the judge fail? This is “does it catch problems”.
  • True negative rate: of the answers you passed, how many did the judge pass? This is “does it cry wolf”.

Then read every disagreement and its critique. Each one is one of three things:

  1. The judge is wrong. Fix the rubric: add a decision rule or an example of a borderline case.
  2. You were wrong. It happens more often than people expect. Fix the label.
  3. The criterion is ambiguous. Decide, write the decision into the rubric, and re-label if needed.

Iterate until the disagreements are rare and the remaining ones are genuinely borderline. To avoid fitting the rubric to the exact examples you are looking at, keep a portion of your labels aside and check the final rubric on those once at the end.

5. Use the judge in your eval suite

Once calibrated, the rubric can run as part of your regular eval. In promptfoo, model-graded checks use the llm-rubric assertion. Set the grader model explicitly so it does not change underneath you:

defaultTest:
  options:
    provider: anthropic:messages:claude-sonnet-5-5
  assert:
    - type: llm-rubric
      value: |
        The answer only makes claims supported by the reference text,
        answers the question that was asked, and does not promise
        refunds, discounts or dates.

Observability tools such as Langfuse and LangSmith can run the same kind of evaluator on samples of production traffic, so you see the pass rate on real conversations rather than only on your test set. If you do that, keep auditing: label a sample of production items by hand every few weeks and check the judge still agrees with you.

Pitfalls

Skipping the labels. A judge prompt nobody has checked against human judgement measures something, but you do not know what.

Scales instead of decisions. “Rate helpfulness from 1 to 5” invites scores that bunch at 4. Break the quality into yes-or-no criteria.

One judge for five criteria. Combining everything in one prompt makes disagreements hard to diagnose. Separate judges per criterion are easier to calibrate.

Changing the judge model silently. A new judge model is a new instrument. Re-run the calibration before you trust comparisons across the change.

Trusting a judge on content it cannot see. A faithfulness judge needs the source documents in its prompt. Without them it will grade plausibility.

Next steps

Covers

Check your understanding

LLM-as-a-judge quiz

Grading criteria for model judges, known biases and checking a judge against human labels.

6 questions · pass mark 70%

Question 1 of 60 answered
  1. When is an LLM judge the right tool?
  • Write your first LLM eval

    Turn real outputs into a small test set, add code-based checks in promptfoo and run them in CI to catch regressions on every change.

    TutorialBeginner40 min

  • Start your evals by reading outputs, not by picking metrics

    The fastest way to useful LLM evals is to read real outputs and write down what is wrong. Why error analysis comes before metrics, and how to do it.

    Article

  • Evaluate RAG answers with a golden dataset

    Set up RAG evaluation with a golden dataset and promptfoo: score retrieval, correctness and grounding for every question, and fail CI when answer quality drops.

    WorkflowIntermediate2 h6 steps

  • LLM-as-a-judge

    Using a model to grade another model's outputs against written criteria, ideally checked against a sample of human-labelled cases.

    Glossary

Back to top