Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Evals and Testing

LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So

A judge is a model plus a rubric, and you trust it only after it agrees with people. On 12 human-scored Cartly answers, a vague rubric gets 67% agreement and kappa 0.33; a rubric that defines every score gets 92% and 0.83. Plus a Pydantic gate that retries broken replies, and a both-orders check for position bias.

Chaand Sheikh

·27 November 2026Evals and Testing

What you will learn

  • Write a judge rubric that defines every score, and see why a vague one fails
  • Validate each verdict with Pydantic and retry a broken reply
  • Calibrate the judge against human labels with agreement and Cohen's kappa
  • Design out position bias, verbosity bias and self-preference

Before you start

  • Why You Cannot Ship an LLM Feature Without an Eval
  • Building a Golden Dataset for LLM Evals
  • Structured LLM Output with Pydantic

A support bot writes hundreds of answers a day. Nobody can read them all, so we let one model grade the answers of another model. That grader is called an LLM judge.

In this article we write a rubric, check every verdict before we use it, and then check the whole judge against people. Three ideas carry it: a rubric, a checked verdict, and a number called kappa. The project runs on a stand-in test model with planned replies, so no key is needed; with your key in .env, the same code calls your own model and you'll get your own numbers.

Where the grader fits

An eval loop starts with a golden set: questions with known good answers (see Building a Golden Dataset). Then somebody, or something, has to mark every answer the bot gives. People are accurate but slow. A model is fast, but we have to earn our trust in it. A grader is what turns answers into numbers you can trust.

A teaching assistant with a marking scheme

Cartly is an imaginary online store. Here's one of its bot's answers: Standard shipping takes three to five business days, and it's free on every order. Is that true? We hand it to a judge, a model plus a written rubric that tells it how to mark. It gives back a verdict: a score of 2, and a short reason, "free on every order" is not in the context.

Think of a teaching assistant. You give them a marking scheme and a pile of papers. But before you trust their marks, you mark ten papers yourself and compare. That's the whole idea: a judge is a model with a rubric, and you trust it only after it agrees with people.

Rubric, model, gate, calibration rubric +context + answer judge model Verdict gatescore 1-5, reason checkedverdict vs humanlabels broken reply: ask once more agreement and kappa
A reply becomes a verdict only after it passes the gate, and the judge is trusted only after it matches people.

Writing the rubric

"""The grader prompts. v1 is the vague one, v2 spells out every score."""

RUBRIC_V1 = "Rate how good this answer is for a customer, from 1 to 5. Reply with JSON."

RUBRIC_V2 = """You grade ONE thing: faithfulness. Does the answer stay inside the context?
5 = every claim in the answer is in the context
4 = every claim is in the context, but something important is left out
3 = one claim is not in the context
2 = a claim contradicts the context, or several are not in it
1 = mostly contradicts the context
Reply with JSON only: {"score": <1-5>, "reason": "<one short sentence>"}"""

RUBRICS = {"v1": RUBRIC_V1, "v2": RUBRIC_V2}


def build_prompt(version, context, answer):
    return f"{RUBRICS[version]}\n\nContext:\n{context}\n\nAnswer:\n{answer}"

Version 1 just says "rate how good this answer is". Nothing says what a 3 or a 5 means. Version 2 grades one thing only, faithfulness, and defines every score. It asks for JSON only, a score and a reason, so our code can read it. build_prompt puts the rubric first, then the context, then the answer. Define every score, and the judge has something to follow.

Checking the verdict

We never trust a reply just because it came back:

"""Ask the judge model for a verdict, then check it before we trust it."""
import json
import os

from dotenv import load_dotenv
from pydantic import BaseModel, Field, ValidationError

from rubric import build_prompt

load_dotenv()


class Verdict(BaseModel):
    score: int = Field(ge=1, le=5)
    reason: str = Field(min_length=3)


def get_model(version, case_id):
    if os.getenv("USE_TEST_MODEL", "1") == "1":
        from test_model import model_for
        return model_for(version, case_id)
    from langchain.chat_models import init_chat_model
    return init_chat_model(os.environ["JUDGE_MODEL"], temperature=0)


def parse_verdict(text):
    return Verdict.model_validate(json.loads(text))


def grade(case, version, tries=2):
    model = get_model(version, case["id"])
    prompt = build_prompt(version, case["context"], case["answer"])
    for attempt in range(1, tries + 1):
        text = model.invoke(prompt).content
        try:
            return parse_verdict(text), attempt
        except (ValueError, ValidationError) as err:
            print(f"  {case['id']} attempt {attempt} rejected: {type(err).__name__}")
    raise RuntimeError(f"no valid verdict for {case['id']}")
  • Verdict is the gate: the score must be a whole number from 1 to 5, and the reason needs at least three characters.
  • get_model plugs in the stand-in when USE_TEST_MODEL=1; otherwise it builds the model named in .env. The judge code doesn't change, only the model underneath.
  • parse_verdict reads the reply as JSON and validates it. A wrong shape raises an error.
  • grade gives the model two tries. A rejected reply is printed, and we ask once more.

The stand-in plays back planned replies, and a few are broken on purpose so we can watch the gate work. Case c01 returns clean JSON with a score of 5, accepted on the first try. Case c04's first reply is plain text, so it's rejected with a JSONDecodeError; the second try is proper JSON with a score of 2. Case c08's first reply says 7. That's valid JSON, but outside 1 to 5, so Pydantic rejects it with a ValidationError; the second try gives a 1:

  c04 attempt 1 rejected: JSONDecodeError
  c08 attempt 1 rejected: ValidationError

A broken reply is asked again, and it never reaches your results. (More on this pattern in Structured LLM Output with Pydantic.)

Twelve answers, human scores

cases.jsonl holds twelve bot answers, two for each of six Cartly policies. A person read each answer next to its policy and gave it a faithfulness score from 1 to 5:

{"id": "c01", "context": "Cartly accepts returns within 30 days of delivery. Items must be unused.", "answer": "You can return an item within 30 days of delivery if it is unused.", "human": 5}
{"id": "c02", "context": "Cartly accepts returns within 30 days of delivery. Items must be unused.", "answer": "You can return anything within 60 days, used or not.", "human": 1}

c02 says sixty days, used or not, when the policy says thirty days and unused: a 1. c07 is a 4: true, but it leaves out the no-cash rule. A score of 4 or 5 counts as a pass, which gives six passes and six fails, so a judge that just guesses won't look good. People mark first, and the judge is checked against them.

calibrate.py: check the judge against people

This is the step everyone skips:

"""Check the judge against human labels: agreement and Cohen's kappa."""
import json
import sys
from pathlib import Path

from sklearn.metrics import cohen_kappa_score

from judge import grade

PASS_MARK = 4


def load_cases(path="cases.jsonl"):
    lines = Path(path).read_text(encoding="utf-8").splitlines()
    return [json.loads(line) for line in lines if line.strip()]


def calibrate(version, cases):
    rows = []
    for case in cases:
        verdict, _ = grade(case, version)
        rows.append({"id": case["id"], "human": case["human"], "judge": verdict.score})
    human = [r["human"] >= PASS_MARK for r in rows]
    judge = [r["judge"] >= PASS_MARK for r in rows]
    agree = sum(h == j for h, j in zip(human, judge)) / len(rows)
    return {"rows": rows, "agreement": agree, "kappa": cohen_kappa_score(human, judge)}

Both scores become pass or fail at the same mark, 4. Agreement is the share of cases where both say pass, or both say fail. But agreement alone can fool you: if most answers pass, a lazy judge agrees a lot just by luck. So we also compute Cohen's kappa with scikit-learn, which takes out what luck would give. Zero means luck, and one means perfect.

Same twelve, two judges

python calibrate.py v1
judge v1: agreement 67%, kappa 0.33
  c01  human 5  judge 5
  c02  human 1  judge 4
  c03  human 5  judge 5
  c04  human 2  judge 4
  c05  human 5  judge 5
  c06  human 1  judge 2
  c07  human 4  judge 4
  c08  human 1  judge 3
  c09  human 5  judge 5
  c10  human 3  judge 5
  c11  human 5  judge 5
  c12  human 2  judge 4

With the vague rubric, the judge passed c02, c04, c10 and c12, and people had failed all four. Agreement 67%, kappa only 0.33.

python calibrate.py v2
  c04 attempt 1 rejected: JSONDecodeError
  c08 attempt 1 rejected: ValidationError
judge v2: agreement 92%, kappa 0.83
  c01  human 5  judge 5
  c02  human 1  judge 1
  c03  human 5  judge 5
  c04  human 2  judge 2
  c05  human 5  judge 5
  c06  human 1  judge 1
  c07  human 4  judge 4
  c08  human 1  judge 1
  c09  human 5  judge 5
  c10  human 3  judge 4
  c11  human 5  judge 5
  c12  human 2  judge 2

With the explicit rubric there's one miss, c10, where the answer adds a shipping refund the policy never mentions. Agreement goes up to 92%, kappa to 0.83. The rubric did the work, and kappa tells you by how much. Remember these two runs come from scripted test judges; with your own model you'll get your own numbers, and that's exactly what this script is for.

Position bias: ask in both orders

Even a checked judge has habits. The first is position bias, tested in pairwise.py with a lazy test judge that always answers A:

"""Position bias: ask the same A/B question in both orders."""
from test_model import always_a_model


def pick(model, first, second):
    prompt = f"Which answer is more faithful to the policy?\nA: {first}\nB: {second}\nReply A or B."
    return model.invoke(prompt).content.strip()


def fair_winner(model, good, other):
    one = pick(model, good, other)
    two = pick(model, other, good)
    if one == "A" and two == "B":
        return "good"
    if one == "B" and two == "A":
        return "other"
    return "tie"
good first : A
good second: A
fair winner: tie

With the good answer first, the judge says A. Swap the order and it says A again. The two orders disagree, so fair_winner returns a tie, and we know not to trust that comparison. Keep a winner only when both orders agree.

Three habits of a judge

HabitWhat happensDesign it out
Position biasLeans towards the answer it reads firstAsk in both orders
Verbosity biasA longer answer sounds betterGrade against the rubric, and put a length rule in it
Self-preferenceA model likes its own styleJudge with a different model family than the one that wrote the answers

Common mistakes

  • "Rate this from 1 to 5". Without a definition for every score, the judge invents its own scale (v1: kappa 0.33).
  • Trusting raw replies. Plain text or a score of 7 will crash or corrupt your numbers. Validate, and retry once.
  • Skipping calibration. A judge you haven't compared with human labels is an opinion, not a metric.
  • Reporting agreement alone. With mostly passing answers, a lazy judge agrees by luck. Report kappa too.
  • A balanced-looking set that isn't. Keep passes and fails roughly even in the human set, as the six and six here.

Quick recap

StepIn the codeResult here
Rubric that defines every scoreRUBRIC_V2Kappa 0.33 to 0.83
Checked verdict, asked again when brokenVerdict, grade(tries=2)c04 and c08 fixed on try 2
Compare with human labelscalibrate.pyAgreement 92%, one miss (c10)
Both orders for A/Bfair_winnerLazy judge gives a tie

Try it yourself

Run python calibrate.py v1 and python calibrate.py v2, then put your own key in .env, set USE_TEST_MODEL=0 and calibrate a real model. Which cases does it miss? Then use the judge inside a full set of checks in RAGAS and Custom Evals.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 54 of 79

Previous
RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
Next post
RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

From ML Metrics to LLM Evals: Same Ruler, New Targets

Precision and recall don't disappear when you build with LLMs; they move. A spam filter at 0.75/0.75, precision@3 and recall@3 on six help-desk documents, exact match vs a key-fact check on two written answers, and the rubric that replaces a single label.

Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval

A friendlier prompt looked better on three questions and broke on others. An eval catches that: a fixed set of cases, a grader, a pass rate and a threshold. A tiny Python eval scores two prompt versions on the same six questions: v1 passes 83% and ships, v2 passes 50% and is blocked.

Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split

The answer key for a support bot: 24 cases in one JSONL file, from 12 past tickets, 8 edge cases and 4 attacks. A Pydantic schema catches 4 problems in a broken file, a stats table finds that payments and account have no hard case, and a seeded split gives the same 16 dev and 8 test cases every time.

Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model

When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.

On this page

  • Where the grader fits
  • A teaching assistant with a marking scheme
  • Writing the rubric
  • Checking the verdict
  • Twelve answers, human scores
  • calibrate.py: check the judge against people
  • Same twelve, two judges
  • Position bias: ask in both orders
  • Three habits of a judge
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.