Skip to content

    AI Architect

    Evaluating AI Systems: Metrics, Judges and Gates

    How AI architects evaluate LLM systems: golden sets, retrieval and generation metrics, judge bias and kappa calibration, and CI gates with confidence intervals.

    By Published 29 min read

    Share

    This lesson is part of AI Architect (Intermediate): Design the System. Enroll for free, then sign in, to read it in full.

    What you'll learn: how to build a golden set and a regression gate a team can trust, where an LLM judge is biased and how to calibrate it with Cohen's kappa, how to measure retrieval apart from generation, how to grade agents, and what a gate with a finite sample can and cannot detect.

    At a glance

    Figure 1. The evaluation loop around an AI system

    The evaluation loop around an AI systemGolden set to Eval service; Rubric to Eval service; Eval service to Orchestrator (run candidate); Eval service to LLM provider (grade); Eval service to Gate; Gate to Release (pass); Gate to Fix and re-run (fail); Release to Trace store; Trace store to Human review; Human review to Golden set (new items)OFFLINE, BEFORE RELEASEONLINE, AFTER RELEASERubric: and judge promptRubricand judge promptGolden set: versionedGolden setversionedOrchestrator: candidate versionOrchestratorcandidate versionEval serviceEval serviceLLM provider: the judgeLLM providerthe judgeGate: pass or failGatepass or failFix and re-runFix and re-runReleaseReleaseTrace storeTrace storeHuman review: of a sampleHuman reviewof a samplerun candidategradepassfailnew items

    How to read this: the left box is what blocks a bad change, the right box is how production teaches the golden set about cases nobody imagined, and the arrow back keeps the loop honest.

    • A golden set is versioned, tagged by slice and labelled against a written rubric.
    • An LLM judge is a model under test: calibrate it against human labels first.
    • Retrieval metrics need no model call; generation metrics need a judge. Keep them apart.
    • A gate decides on a confidence bound and has three outcomes: pass, fail, inconclusive.
    • Item count sets the smallest visible drop: about 3.6 points at 400 items, about 16 for a 30-item slice.

    The real-world problem

    A team changes one sentence in its assistant's system prompt to make answers shorter. Five reviewers read twenty answers each, see no problem, and the change ships. Two weeks later the returns team reports confident but incomplete answers about one product category. The quality average had moved about a point, inside the noise of the sample, and nothing measured that category.

    After this page you will be able to

    • Build a versioned golden set with slices, a rubric and a hold-out split.
    • Calibrate an LLM judge with raw agreement, Cohen's kappa and failure recall.
    • Use recall at k, reciprocal rank and nDCG to locate a failure in retrieval rather than generation.
    • Compute a Wilson interval and the samples needed to detect a stated drop.
    • Design a CI gate with slice reports, position-swapped pairwise judging and an outcome-versus-trajectory split for agents.

    Core concepts

    Golden sets and how to build them

    Rule Why
    Seed from real failures and traffic; every incident adds an item Teams cannot imagine production's failures
    Tag items with slices: category, language, tenant, risk class Slices find what an average hides
    Write the rubric before labelling; two people label subjective items Without a rubric, labels drift
    Split a hold-out set nobody tunes against (the course's recommendation, not a sourced rule) Otherwise the set measures your editing
    Version the set; record which version produced each score Scores compare only on the same set

    How to read this: each row is a working rule and the failure it prevents.

    Offline and online evaluation

    Offline Online
    Answers "Is this change safe to ship?" "Is it still working on what users send?"
    Strength Repeatable The real distribution
    Limit Sees only the past Little ground truth: user signals, sampled review, a judge on a sample

    How to read this: offline blocks changes; online finds what the golden set missed and feeds it back (Figure 1).

    Regression gates in CI

    A regression gate blocks a merge when evidence shows quality dropped. Fix three things in advance: the metric, the comparison (a fixed bar or the current production version) and the rule for noise (a confidence bound, not the point estimate).

    Figure 2. A regression gate in CI, including its failure paths

    sequenceDiagram accTitle: Regression gate in CI accDescr: CI asks the eval service to run the golden set. For each item the eval service calls the candidate, then asks the judge model for a verdict. A verdict that is still malformed after one retry is stored as an error. The eval service computes slice pass rates with a lower confidence bound, stores everything in the trace store and tells CI to pass or block. participant CI as CI pipeline participant ES as Eval service participant OR as Orchestrator participant LP as LLM provider participant TS as Trace store CI->>ES: Run golden set for candidate version loop Each golden-set item ES->>OR: Input and test context OR-->>ES: Output, retrieved passages, tool calls ES->>LP: Judge prompt with rubric and output LP-->>ES: Verdict alt Verdict still malformed after one retry ES->>TS: Record eval error, not a pass else Verdict parses ES->>TS: Record score, trace, judge and prompt versions end end ES->>ES: Pass rate and lower bound per slice alt Every slice clears its bound and error rate is within limit ES-->>CI: Pass with report else Any slice fails or too many eval errors ES-->>CI: Block with failing slices and items end Note over CI,TS: A run with too many judge errors is invalid, not green.

    How to read this: the gate decides on a bound per slice and counts judge errors as failures of the evaluation, so a broken judge can never turn a run green.

    Step through one run (illustrative counts, computed in the confidence-interval section below).

    One eval-gate run in CI (illustrative counts) (interactive when JavaScript is on)
    1. CI starts the run. A pull request changes the prompt. CI asks the eval service to run the 400-item golden set against the candidate.
    2. Candidate, then judge, per item. A malformed verdict is retried once, then stored as an evaluation error, never a pass.
    3. Pass rate and lower bound. 369 of 400 pass (92.25%). The one-sided 95% Wilson lower bound is 0.8976, below a 0.90 bar. A 30-item slice with 27 passes has lower bound 0.774.
    4. Three outcomes, then a report. Lower bound at or above the bar: pass. Upper bound below it: fail. Neither: inconclusive, which blocks by default; re-running until green is not permitted.
    Check yourself: the judge returns malformed output for a large share of items, and the rest all pass. Can the run be green?

    No. A verdict still malformed after one retry is an evaluation error, not a pass, and a run above the agreed error rate is invalid.

    Anthropic's agent-eval post (Demystifying evals for AI agents) separates capability evals ("what can this agent do well?", which "should start at a low pass rate") from regression evals, which "should have a nearly 100% pass rate". Give each its own suite and gate.

    Human review and label quality

    Humans are the reference, but not perfectly consistent: in TREC-8, "assessors have legitimate differences of opinion as to correctness even for fact-based, short-answer questions" (Voorhees and Tice, LREC 2000). Measure reviewer agreement first; if reviewers disagree often, repair the rubric before anything else.

    Grader Anthropic's description (docs) Use it for
    Code-based "fastest and most reliable", but lacks nuance Schema, citation present
    Human "most flexible and high quality, but slow and expensive" Calibration, hard cases
    LLM-based "fast and flexible"; test reliability before scaling What needs reading

    Evaluating retrieval separately from generation

    A wrong answer from a retrieval-augmented system has at least four causes, and one end-to-end score cannot separate them. Each has a different fix and owner.

    Figure 3. Locating the failing stage of a wrong answer

    flowchart TD accTitle: Locating the failing stage of a wrong answer accDescr: A decision tree for a wrong or unsupported answer. It asks whether a relevant passage was retrieved, whether it reached the prompt, whether every claim is supported by the passages, and whether the passage itself is correct and current. Each no leads to a named failing stage, and a final branch checks the label or judge. W["Wrong or unsupported answer"] --> Q1{"Relevant passage in the retrieved set?"} Q1 -- no --> R1["Retrieval failure: check recall at k, index, chunking, filters"] Q1 -- yes --> Q2{"Passage present in the final prompt?"} Q2 -- no --> R2["Context assembly failure: trimming, ordering, budget"] Q2 -- yes --> Q3{"Every claim supported by the passages?"} Q3 -- no --> R3["Generation failure: faithfulness"] Q3 -- yes --> Q4{"Passage correct and current?"} Q4 -- no --> R4["Source failure: stale or conflicting document"] Q4 -- yes --> R5["Check the label and the judge before changing the system"]

    How to read this: work down in order, because the first "no" names the stage to fix, and the last branch reminds you that the evaluation itself can be wrong.

    Retrieval metrics need labelled passages and no model call; generation metrics need the retrieved passages and a judge. Report both per slice, side by side.

    Check yourself: the relevant passage was retrieved, but the token budget trimmed it before the prompt was built. Which branch names the fault?

    The second: the passage is not in the final prompt, so it is a context assembly failure. Retrieval recall would look fine, which is why one end-to-end score cannot find it.

    Evaluating agents: trajectory versus outcome

    Anthropic's post defines the transcript (trajectory) as "the complete record of a trial, including outputs, tool calls, reasoning, intermediate results" and the outcome as "the final state in the environment at the end of the trial". It advises that "it's often better to grade what the agent produced, not the path it took", because valid paths vary; tau-bench compares the final database state with an annotated goal state (Yao et al.).

    What to grade Example check Why
    Outcome Ticket in the right state, refund amount right, no other record changed Many paths reach it
    Trajectory, policy steps Approval step not skipped, no forbidden tool called Some paths are unacceptable even when the outcome is right

    Agent runs are stochastic. Anthropic defines pass@k as "the likelihood that an agent gets at least one correct solution in k attempts" and pass^k as "the probability that all k trials succeed". Assuming independent trials with success probability p (a simplification), pass@k is 1 - (1 - p)^k and pass^k is p^k.

    With p = 0.9 pass@3 pass^3 pass^8
    Value 0.999 0.729 0.43

    How to read this: at-least-once success climbs toward 1 while all-trials success falls, so an agent that acts on the world needs pass^k (agent loop: page 6; event-driven designs: page 7).

    Check yourself: an agent succeeds on each trial with probability 0.9. What is the chance it succeeds on all 8 trials of one task?

    About 0.43 (0.9 to the power 8 is 0.4305). A 90% single-trial rate still means at least one failure in eight runs more often than not.

    Case files

    • A prompt tweak that silently broke one product category. In a composite retail scenario, a prompt change lowered answer quality in one category while the average barely moved. Pattern: eval gates, with a golden set per category and a confidence interval on the gate.
    • A RAG assistant that was confident and wrong. In a composite healthcare scenario, a procedure-lookup assistant gave fluent, wrong answers, mostly because it retrieved a superseded passage and stayed faithful to it. Pattern: LLM judge and faithfulness checks, retrieval metrics kept apart from generation metrics, and abstention when evidence is weak.
    • Summarisation: nobody agreed what good meant. In a composite public-sector scenario, a summarisation feature could not be improved because there was no shared definition of quality. Pattern: eval design, with a rubric, a calibrated judge, human spot checks and pairwise comparison for model changes.

    Under the hood: How an LLM judge works

    Intuition

    An LLM judge is a model call that returns a grade instead of an answer, so it is a measuring instrument with its own error.

    Mechanism

    Zheng et al. (arXiv 2306.05685) studied "LLM-as-a-judge" and defined three variants:

    Variant The judge sees Used for
    Pairwise comparison A question and two answers; picks the better or declares a tie Choosing between versions
    Single answer grading One answer; gives a score Tracking against a bar
    Reference-guided grading A reference solution too Mainly maths

    Their default single-answer prompt tells the judge to "begin your evaluation by providing a short explanation" and to rate from 1 to 10 as "[[rating]]": reasoning first, then a machine-parseable verdict.

    Figure 4. One judge call, including a malformed verdict

    sequenceDiagram accTitle: One judge call accDescr: The eval service builds a judge prompt from the rubric, question and candidate answer, sends it to the judge model and receives an explanation followed by a verdict. If the verdict parses it is stored with the prompt and judge model versions. If not, the eval service retries once and otherwise records an evaluation error. participant ES as Eval service participant LP as LLM provider participant TS as Trace store ES->>ES: Build judge prompt from rubric, question and answer ES->>LP: Judge prompt with output format LP-->>ES: Short explanation, then verdict alt Verdict parses ES->>TS: Store verdict, raw output, prompt version, judge model version else Verdict malformed ES->>LP: Retry once with a format reminder LP-->>ES: Second response ES->>TS: Store verdict if it parses, else store an evaluation error end Note over ES,TS: The judge output is stored raw so a human can audit any score.

    How to read this: the judge is one remote call with a parse step after it, and the parse step has a defined failure path.

    Format has a cost: in the paper's position-bias test, between 0% and 3.8% of judge outputs per configuration had a wrong output format (Table 2, "Error" column).

    What this means for architects

    What changes What you do
    Every judged item is an extra call (page 4 on latency) Judge offline or on a sample unless the verdict changes what the user sees
    Absolute scores "are likely to fluctuate more than relative pairwise results if the judge model changes" Store judge and prompt versions and raw output with every score; re-baseline when the judge changes
    A malformed verdict is an evaluation error, never a pass Set an error-rate limit; a run above it is invalid
    Anthropic's example code: "Generally best practice to use a different model to evaluate than the model used to generate the evaluated output" Give the judge its own route behind the model gateway

    Under the hood: Judge biases

    Intuition

    A judge can prefer an answer for reasons unrelated to quality: its position, its length, or who wrote it. These biases do not average out like noise, and they can line up with the change you are testing.

    Mechanism

    Zheng et al. measured each bias on 2023-era models (GPT-4, GPT-3.5, Claude-v1). Read the numbers as evidence that the effects exist and can be large, not as properties of any model you use today.

    Bias Meaning (paraphrased) What they measured
    Position Favouring certain positions over others Two very similar answers, order swapped: consistency GPT-4 65.0%, GPT-3.5 46.2%, Claude-v1 23.8%; Claude-v1 favoured the first position 75.0% of the time
    Verbosity Favouring longer responses even when less clear, high-quality or accurate "Repetitive list" attack on 23 answers: judge failure rate Claude-v1 91.3%, GPT-3.5 91.3%, GPT-4 8.7%
    Self-enhancement May favour answers the judge itself generated GPT-4 favoured itself with a 10% higher win rate than humans gave it, Claude-v1 25%, GPT-3.5 not at all; the authors say their "study cannot determine whether the models exhibit a self-enhancement bias"
    Limited reasoning Mis-grading maths and reasoning answers 10 maths questions (20 judgments): default prompt failed 14/20, chain-of-thought 6/20, reference-guided 3/20

    How to read this: each row pairs a bias with its 2023 effect size.

    Later work reports evaluators scoring their own outputs higher even when humans rate the texts as equal (Panickssery et al., arXiv 2404.13076).

    Which judge bias or fix applies? (interactive when JavaScript is on)

    A prompt edit makes every answer much longer, and the pairwise judge now prefers the candidate. Which bias should you suspect first?

    • Position bias
    • Verbosity bias
    • Self-enhancement bias
    Answer

    Verbosity bias. Verbosity bias favours longer responses even when they are not clearer.

    A pairwise judge flips its verdict on many pairs when you swap the answers' order. Which mitigation addresses it?

    • Add a longer rubric
    • Judge in both orders and count a win only if the same answer wins both
    • Average two 1-to-10 scores
    Answer

    Judge in both orders and count a win only if the same answer wins both. A win that survives swapping is not an order effect.

    The same model family generates the answers and judges them, and the judge pass rate sits above the human pass rate. What does the page recommend?

    • Use a judge from a different family, or a human-confirmed sample, and track the gap
    • Trust the judge, because agreement is high
    • Add few-shot examples to the judge prompt
    Answer

    Use a judge from a different family, or a human-confirmed sample, and track the gap. Self-preference is reported in evaluators, and Anthropic's example recommends a different evaluating model.

    Mitigation What the paper says Cost
    Swap positions "A conservative approach is to call a judge twice by swapping the order of two answers and only declare a win when an answer is preferred in both orders." Inconsistent results are a tie Doubles judge calls
    Few-shot examples GPT-4 consistency rose from 65.0% to 77.5%, but "high consistency may not imply high accuracy" May add new biases; 4 times more expensive calls
    Chain-of-thought or reference Maths failures fell to 6/20 and 3/20 Longer output; needs a reference

    Figure 5. The position-swap mitigation

    sequenceDiagram accTitle: Position-swap mitigation for a pairwise judge accDescr: The eval service sends the same two answers to the judge in both orders. If the same answer wins in both orders the trace store records a win for it. If the verdicts disagree the result is recorded as a tie. participant ES as Eval service participant LP as LLM provider participant TS as Trace store ES->>LP: Prompt 1 with answer A first and answer B second LP-->>ES: Verdict 1 ES->>LP: Prompt 2 with answer B first and answer A second LP-->>ES: Verdict 2 alt Same answer preferred in both orders ES->>TS: Record a win for that answer else Verdicts disagree or both say tie ES->>TS: Record a tie end Note over ES,LP: Two judge calls per pair instead of one.

    How to read this: a preference counts only if it survives swapping the order, so a pure position effect becomes a tie rather than a false win.

    What this means for architects

    What changes What you do
    Published rates are for old models Run every pair in both orders and report the flip share; pad a few answers with redundant text to see whether the verdict moves
    A constant bias cancels in an A/B comparison; one correlated with the change does not (the course's reasoning) Control length and spot-check with humans
    Judges cannot grade what they cannot do For maths, code and unknown facts, give a reference or use code checks

    Under the hood: Calibrating a judge against human labels

    Intuition

    Raw agreement is not enough: two raters who both say "pass" most of the time agree often by chance. Cohen's kappa asks how much better than chance the agreement is.

    Mechanism

    The Stanford information retrieval textbook defines kappa = (P(A) - P(E)) / (1 - P(E)), where P(A) is "the proportion of the times the judges agreed" and P(E) is "the proportion of the times they would be expected to agree by chance" (Manning et al.). The textbook's reading of kappa (cutoffs depend on purpose):

    • Above 0.8: "good agreement"; 0.67 to 0.8: "fair agreement".
    • Below 0.67: "data providing a dubious basis for an evaluation".

    A worked example (illustrative counts): 200 items labelled by a human and the judge.

    Human pass Human fail Judge total
    Judge pass 150 20 170
    Judge fail 6 24 30
    Human total 156 44 200
    P(A) = (150 + 24) / 200 = 0.87
    judge says pass: 170/200 = 0.85     human says pass: 156/200 = 0.78
    P(E) = 0.85 x 0.78 + 0.15 x 0.22 = 0.663 + 0.033 = 0.696
    kappa = (0.87 - 0.696) / (1 - 0.696) = 0.174 / 0.304 = 0.572
    Measure Value
    Raw agreement 87%
    Kappa 0.57, below the 0.67 line (95% interval roughly 0.42 to 0.71 by percentile bootstrap, 5,000 resamples: a computation made for this page, not a sourced method)
    Failure recall (humans failed 44) 24 caught, 54.5%; 95% Wilson interval about 40% to 68%
    Pass rate Judge 85%, humans 78%: overstated by 7 points

    How to read this: 87% agreement looks fine, but the judge misses almost half the failures and passes too much, so a gate built on it would wave bad answers through.

    • Skewed data distorts kappa the other way (Artstein and Poesio's prevalence problem, 2008): with 200 items split 180 / 6 / 6 / 8, agreement is 94% and kappa only 0.54. Report performance on the rare class.
    • After tightening the rubric, measure again on a fresh sample, not the items used to edit it:
    First sample Fresh sample, tightened rubric
    Cells (both pass, judge pass only, human pass only, both fail) 150, 20, 6, 24 146, 8, 10, 36
    Raw agreement 0.87 0.91
    Kappa 0.572 0.742
    Judge pass rate (humans 78%) 85% 77%
    Failure recall 24 of 44 36 of 44

    A kappa of 0.742 is the textbook's "fair" band: usable for trend monitoring with spot checks. Whether it may gate alone depends on the bar and the cost of a missed failure.

    Figure 6. The life of a judge

    stateDiagram-v2 accTitle: Judge calibration life cycle accDescr: A judge starts as a draft prompt and rubric. It is calibrated against human labels. If agreement is below the agreed bar it returns to draft. If it meets the bar on fresh items it is trusted. A failed spot check or any change to the judge model or prompt sends it back to calibration. A retired judge is kept for the record. [*] --> Draft Draft --> Calibrating: rubric and prompt written Calibrating --> Draft: agreement below the bar Calibrating --> Trusted: meets the bar on fresh items Trusted --> Drifting: spot check disagrees or judge or prompt changes Drifting --> Calibrating: relabel a fresh sample Trusted --> Retired: task or rubric replaced Retired --> [*]

    How to read this: a judge is never trusted for good, because any change to the judge, prompt or task, and any failed spot check, sends it back to calibration.

    What this means for architects

    What changes What you do
    The bar must exist Put it in the requirement, e.g. "kappa of at least 0.67 and failure recall of at least 80% on a fresh 200-item sample, re-checked monthly and after any change" (the numbers are yours to set)
    Human labels are the expensive part; 44 failures give a 40% to 68% interval on failure recall Label a sample that over-represents failures; weight strata back to population share before computing kappa
    A headline "85% agreement" is not kappa In MT-bench GPT-4 agreed with experts 85% and humans 81% (Zheng et al., Table 5a); with 50% as chance level, (0.85 - 0.50) / (1 - 0.50) = 0.70 (this course's calculation, not the paper's)

    Under the hood: Pairwise and absolute scoring

    Intuition

    Absolute scoring asks "is this answer good?" and can be tracked against a bar. Pairwise scoring asks "which of these two is better?" and says nothing about whether either is good enough.

    Mechanism

    • Zheng et al.: pairwise comparison "may lack scalability when the number of players increases, given that the number of possible pairs grows quadratically"; single answer grading "may be unable to discern subtle differences between specific pairs". On MT-bench (Table 5a) GPT-4 agreed with human experts 85% of the time in both modes.
    • Calls for k systems and Q questions: absolute k x Q, pairwise with swap k(k - 1) x Q. With 6 systems and 80 questions, 480 against 2,400 (illustrative).
    • Reporting a pairwise result (illustrative): 400 items in both orders, a win counted only when the candidate is preferred in both:
    Outcome Items Reading
    Candidate wins 150 57.7% of the 260 decided items; 95% Wilson interval about 51.6% to 63.5%, excluding 50%
    Candidate loses 110
    Ties 140 35% showed no judged difference: the effect sits in a minority of items

    "Better than the baseline" is not "good enough", so a pairwise win does not replace an absolute bar.

    Figure 7. Choosing a scoring mode

    flowchart TD accTitle: Choosing between pairwise and absolute scoring accDescr: The decision determines the mode. Choosing between two versions uses position-swapped pairwise judging. Holding a quality bar over time uses absolute pass or fail on a rubric. Choosing among many candidates screens with absolute scores and then runs pairwise on the shortlist. All paths end in a human spot check. Q{"What decision is this?"} Q -- "Is version B better than version A" --> PW["Pairwise with position swap"] Q -- "Does the system still meet the bar" --> AB["Absolute pass/fail on a rubric"] Q -- "Which of many candidates" --> SH["Absolute screen, then pairwise on a shortlist"] SH --> PW PW --> R1["Report wins, ties, losses and an interval"] AB --> R2["Report pass rate with a lower bound"] R1 --> HC["Human spot check of ties and disagreements"] R2 --> HC

    How to read this: the decision picks the mode, and both modes end with a person reading a sample of the cases the judge found hard.

    What this means for architects

    What changes What you do
    Default (an opinion): pairwise for versions, absolute for the bar. OpenAI favours pairwise or pass/fail "for more reliability" Pairwise with swap to choose versions; absolute pass/fail on a written rubric for the release bar; check calibration in each mode
    Pairwise cost grows with candidates; absolute scores compare over time only while judge, prompt and rubric stay fixed Screen many candidates with absolute scores first; pin all three and run the baseline beside the candidate

    Under the hood: Retrieval metrics

    Intuition

    Did the relevant documents appear in the top k (recall at k)? How early did the first appear (reciprocal rank)? Are the most useful ranked first (nDCG)? They need labelled queries but no model call.

    Mechanism

    The Stanford IR book defines recall as "the fraction of relevant documents that are retrieved"; restricted to the top k it is recall at k. For graded relevance it defines normalised discounted cumulative gain, "designed for situations of non-binary notions of relevance" (Manning et al., section 8.4). R(j, m) is the grade given to the document at rank m for query j, and Z makes a perfect ranking score 1:

    Recall@k = (relevant documents in the top k) / (all relevant documents)
    NDCG(Q, k) = (1/|Q|) * sum over queries j of  Z_kj * sum for m = 1..k of (2^R(j,m) - 1) / log2(1 + m)
    RR = 1 / (rank of the first relevant result), or 0 if none;  MRR = mean of RR over queries

    That section does not define mean reciprocal rank. The TREC-8 question answering track scored a question as "the reciprocal of the rank at which the first correct response was returned, or 0 if none of the five responses contained a correct answer" (Voorhees and Tice, LREC 2000). Choose your own cutoff and state it.

    A worked example (illustrative). One query has four relevant documents with grades 3, 2, 2 and 1 (0 means not relevant). Of ten results, the relevant ones sit at rank 2 (grade 3), rank 4 (grade 2) and rank 7 (grade 1). The other grade-2 document is never retrieved.

    Rank m 1 2 3 4 5 6 7 8 9 10
    Grade 0 3 0 2 0 0 1 0 0 0
    Recall@5  = 2/4 = 0.50          Recall@10 = 3/4 = 0.75          RR = 1/2 = 0.50
    DCG@10  = (2^3-1)/log2(3) + (2^2-1)/log2(5) + (2^1-1)/log2(8)
            = 7/1.585 + 3/2.322 + 1/3 = 4.4165 + 1.2920 + 0.3333 = 6.0419
    IDCG@10 = 7/log2(2) + 3/log2(3) + 3/log2(4) + 1/log2(5)
            = 7 + 1.8928 + 1.5 + 0.4307 = 10.8235
    nDCG@10 = 6.0419 / 10.8235 = 0.558
    Ranking Recall@5 nDCG@10
    As retrieved 0.50 0.558
    Grade 3 moved to rank 1, grade 2 to rank 3, grade 1 left at rank 7 0.50 0.816

    How to read this: recall at k ignores order inside the top k; nDCG rewards putting the most useful document first.

    Figure 8. From labelled queries to retrieval metrics

    From labelled queries to retrieval metricsLabelled queries to Retriever; Vector index to Retriever; Retriever to Ranked top k; Ranked top k to Eval service; Document store to Eval service; Eval service to Recall at k, RR, nDCG; Recall at k, RR, nDCG to Per-slice gateLabelled queriesLabelledqueriesRetrieverRetrieverVector indexVector indexRanked top kRanked top kEval serviceEval serviceDocument store: relevance labelsDocument storerelevance labelsRecall at k, RR, nDCGRecall at k,RR, nDCGPer-slice gate: and reportPer-slice gateand report

    How to read this: the retriever output never touches a language model on this path, so the numbers are repeatable and any change comes from the index, the query or the ranking.

    What this means for architects

    What changes What you do
    A relevant passage missing from the prompt cannot ground the answer Measure recall at the k you actually use; revisit it when you change the context budget (page 4) or add a reranker (page 5)
    The metrics answer different questions MRR when the first result matters, recall at k when passages are used together, nDCG when grades differ and order matters
    Manning et al. on TREC: relevance judgments exist "only for the documents that were among the top k returned" for some participating system Add labels when you change retrievers, or the new one is penalised for finding what the old one never showed

    Under the hood: Generation metrics

    Intuition

    Is every claim in the answer supported by the retrieved passages (faithfulness)? Does the answer address the question (answer relevance)? Both are reference-free: no gold answer is needed.

    Mechanism

    The RAGAS paper defines them (Es et al., arXiv 2309.15217):

    Metric How it is computed Note
    Faithfulness An LLM extracts statements from the answer, then judges whether each can be inferred from the context; F = supported / total Faithful if "the claims that are made in the answer can be inferred from the context"
    Answer relevance An LLM generates n questions from the answer; AR = mean cosine similarity of their embeddings to the original question "does not take into account factuality, but penalises cases where the answer is incomplete or where it contains redundant information"

    The library documentation, as of 2026-10-22, describes the same ideas (faithfulness, answer relevancy) and says the legacy interface will be deprecated in version 0.4: pin the version you use.

    Worked example (illustrative) Inputs Result
    Faithfulness 5 statements, 4 judged supported 4 / 5 = 0.80
    Answer relevance 3 generated questions, similarities 0.91, 0.88, 0.79 (0.91 + 0.88 + 0.79) / 3 = 0.86

    Figure 9. Computing faithfulness for one trace

    sequenceDiagram accTitle: Computing faithfulness for one trace accDescr: The eval service reads a trace holding the question, retrieved passages and answer. It asks the judge model to split the answer into statements, then to verify each statement against the passages. It computes supported over total and flags low-scoring traces for review. participant ES as Eval service participant TS as Trace store participant LP as LLM provider ES->>TS: Fetch question, retrieved passages and answer TS-->>ES: Trace record ES->>LP: Split the answer into standalone statements LP-->>ES: Statements S1 to Sn ES->>LP: For each statement, is it supported by the passages LP-->>ES: Yes or No per statement, with a short reason ES->>ES: Faithfulness is supported statements divided by all statements alt Score below the slice threshold ES->>TS: Flag the trace for human review else Score meets the threshold ES->>TS: Store the score end Note over ES,LP: Two judge stages per answer, so cost grows with answer length.

    How to read this: faithfulness needs two model stages per answer, one to decompose and one to verify, and it checks the answer against the retrieved passages, not against the world.

    Limit What it means
    Faithful is not true A stale, wrong or conflicting passage yields a faithful wrong answer: the source-failure branch of Figure 3
    Answer relevance ignores facts A fluent, on-topic, wrong answer can score well. The paper does not say how an abstention scores; test that first
    The metrics are model outputs The paper used gpt-3.5-turbo-16k and text-embedding-ada-002. On WikiEval (pairwise comparisons) they matched humans at 0.95 for faithfulness and 0.78 for answer relevance. That does not show a release threshold such as 0.9 is calibrated for your data

    What this means for architects

    What changes What you do
    Faithfulness can be recomputed after you improve the verifier Log retrieved passage identifiers, the prompt as sent and the answer
    It is a measurement, not truth Gate and monitor per slice, paired with retrieval metrics and human checks of source correctness
    Two judge stages per answer Every item in CI, a sample in production
    Low faithfulness needs a defined response Abstain or cite only, route to a human queue, record the case (approval steps: page 6); a retry is not a remedy

    Under the hood: Confidence intervals and sample sizes for gates

    Intuition

    A pass rate on n items is an estimate: two 400-item samples differ by chance. A gate on the point estimate blocks healthy changes and passes bad ones. Gate on an interval, and know how large a drop it can see.

    Mechanism

    Page 2 used the normal-approximation interval. This page uses the Wilson interval, whose limits cannot fall outside 0% to 100%. The NIST/SEMATECH e-Handbook gives it as the interval for a proportion, calls an interval with an impossible lower limit "an inferior approach", and says one-sided limits use z for alpha instead of alpha/2 (NIST, section 7.2.4.1):

    Wilson limits = ( p + z^2/(2n)  +/-  z * sqrt( p(1-p)/n + z^2/(4n^2) ) ) / ( 1 + z^2/n )

    A proof gate passes only when the lower bound clears the threshold. With n = 400, a one-sided 95% lower bound and a 0.90 threshold it needs 370 passes (92.5%). The widget starts at 369: set passes to 370 and watch the bound cross, then set n to 30 and see why a slice cannot prove it.

    Proof gate: 400 items, bar 90 percent, one-sided 95 percent (interactive when JavaScript is on)
    Observed pass rate92.3%
    Interval (z = 1.645)89.8% to 94.2%
    Gate: lower bound at least 90.0%fail

    The chance this gate passes depends on the true rate (exact binomial arithmetic):

    True pass rate 0.90 0.92 0.94 0.95
    Gate passes, n = 400 5.2% 40.0% 91.1% 98.9%
    Gate passes, n = 1,000 4.9% 70.4% 99.9% 100%

    A system at 0.92 fails this 0.90 proof gate 60% of the time at n = 400: 400 items cannot demonstrate 90% for a system two points above it. A regression gate instead blocks on evidence of a drop against a baseline.

    Sample size to detect a drop. NIST gives the sample size for testing a move from p0 to p1, with delta = |p1 - p0| (NIST, section 7.2.4.2):

    N >= [ ( z_(1-alpha) * sqrt(p0(1-p0)) + z_(1-beta) * sqrt(p1(1-p1)) ) / delta ]^2     (one-sided; add 1/delta as a continuity correction)

    Try the page's baseline and drop, then set p1 to 0.90 and see how fast the items needed grow.

    Items needed to detect a drop from 92 percent to 88 percent (interactive when JavaScript is on)
    Items to detect 92.0% falling to 88.0%323.8
    With continuity correction (n + 1/delta)348.8

    With a known 0.92 baseline, a drop to 0.88, one-sided alpha 0.05 and power 0.80 (z = 1.645 and 0.8416), N is 324 (349 with correction). An exact binomial calculation at n = 349 agrees: the test rejects 5.0% of the time at a true 0.92 and 81.1% at a true 0.88. If baseline and candidate are independent samples the noise adds and about 695 items per run are needed; running both versions on the same items can be tighter (worked example).

    Golden-set size n 100 200 400 1,000 2,000
    Smallest drop detected (points) about 7.5 about 5.2 about 3.6 about 2.2 about 1.6

    How to read this: detectable drop at baseline 92%, one-sided 5%, 80% power, baseline treated as known, no continuity correction. Halving the drop needs about four times the items.

    Figure 10. A gate decision with three outcomes

    flowchart TD accTitle: Gate decision with three outcomes accDescr: Run the golden set, count passes and compute the interval. If the lower bound meets the threshold the requirement is demonstrated. Otherwise, if the upper bound is below the threshold there is evidence of failure. If neither holds the result is inconclusive and the change is blocked by default pending more items or review. A["Run n golden-set items"] --> B["Count passes and compute the interval"] B --> C{"Lower bound at or above threshold?"} C -- yes --> P["Pass: requirement demonstrated"] C -- no --> D{"Upper bound below threshold?"} D -- yes --> F["Fail: evidence the rate is below the bar"] D -- no --> I["Inconclusive: not demonstrated"] F --> X["Block and report failing slices"] I --> X2["Block by default, add items or hold for review"]

    How to read this: there are three outcomes, and "inconclusive" is a normal result for a small set, not a reason to rerun until it turns green.

    What a gate cannot claim What goes wrong
    Slices A 30-item slice alone detects only drops of about 16 points from a 90% baseline; slices need their own counts
    Many slices 10 independent slices at a 5% false-alarm rate each give 1 - 0.95^10 = 40.1% chance of at least one false alarm
    Independent items Paraphrases, or many questions about one document, are correlated: the effective sample is smaller than n
    Noise beyond sampling A stochastic model and a judge add variance the formula omits

    What this means for architects

    What changes What you do
    "No regressions" cannot be checked Write the detectable drop into the requirement ("detects a drop of 4 points or more with 80% power") and choose n from it
    The two gates answer different questions Proof gate for a first release against a stated bar; regression gate for later changes
    Inconclusive is a result Block by default; add items, improve the change or sign a risk acceptance. Give thin, high-risk slices extra items

    Decision framework

    Figure 11. Choosing the evaluation design

    flowchart TD accTitle: Choosing the evaluation design accDescr: A decision tree. Without a labelled set, seed 20 to 50 items from real failures. If a judge decides the release, calibrate it on fresh human labels. Comparing two versions uses pairwise judging with a position swap; otherwise absolute pass or fail. Retrieval features get retrieval and generation metrics reported separately. Agents that act on the world are graded on end state, policy steps and pass to the k. Every path ends in a gate on a confidence bound. A{"Have a labelled set?"} -- no --> A1["Seed 20 to 50 items from real failures"] A -- yes --> B{"Does a judge decide the release?"} A1 --> B B -- yes --> B1["Calibrate on fresh human labels: kappa, failure recall"] B -- no --> C{"Comparing two versions?"} B1 --> C C -- yes --> C1["Pairwise with position swap, same items"] C -- no --> C2["Absolute pass/fail on a rubric"] C1 --> D{"Uses retrieval?"} C2 --> D D -- yes --> D1["Report retrieval and generation metrics per slice"] D -- no --> E{"Agent that acts on the world?"} D1 --> E E -- yes --> E1["Grade end state, policy steps, pass^k"] E -- no --> G["Gate on a confidence bound, state the smallest detectable drop"] E1 --> G

    How to read this: each question adds one control to the design, and every path ends in the same gate.

    If Then Because Revisit when
    No labelled set 20 to 50 real items; add every incident A small real set beats an invented one Slices have enough items
    A judge decides the release Calibrate; report kappa and failure recall Raw agreement hides chance Judge or rubric changes
    Comparing two versions Pairwise, position swap, same items Swapping removes order effects The flip rate rises
    The feature uses retrieval Retrieval and generation metrics per slice One score hides the failing stage Retriever or prompt assembly changes
    A gate blocks merges Confidence bound; state the detectable drop A point estimate turns noise into alarms n or slice mix changes
    An agent acts on the world End state, policy steps, pass^k One success hides inconsistency The agent gains a tool

    Comparison of the main options

    Option Strengths Weaknesses Choose when
    Code-based checks Fast, cheap, reproducible Brittle; cannot judge quality The answer has a checkable form
    Human review Highest quality; calibration reference Slow, expensive, reviewers disagree Calibration, high-risk cases, rubric design
    LLM judge, absolute Scales; one number against a bar Biased; drifts with judge changes Release bar and monitoring
    LLM judge, pairwise with swap More reliable for versions Twice the calls; no absolute quality Model or prompt changes
    Retrieval metrics Deterministic, no model call Needs labels Index, chunking, reranker changes
    Reference-free generation metrics No gold answers Model outputs; faithful is not true Gate and monitor RAG generation

    Failure scenarios to design for

    Failure What the system does Why
    The judge returns malformed output Retry once, then record an evaluation error; a run above the error limit is invalid A broken judge must not turn a run green
    The judge model is updated or deprecated Versions stored on every score; recalibrate and re-baseline Scores do not compare across judge versions
    The aggregate is green while a slice regressed Report every slice with n and interval; below the minimum count shows "not measurable" and blocks a change that targets it Averages hide slices
    The judge shares a family with the system Judge from another family or a human-confirmed sample; track the gap Self-preference is possible
    The gate is inconclusive Blocked by default; add items, improve the change or sign a risk acceptance Reruns turn noise into a pass

    Worked example

    A support-answer assistant is gated on a 400-item golden set. The baseline (current production prompt) passes 368 of 400.

    Assumptions:

    • All counts are illustrative (the discordant counts 30 and 14 are chosen); items are independent.
    • One-sided alpha 0.05 and power 0.80 unless stated; z = 1.96 for two-sided 95% intervals.
    Step Calculation Result
    1. Baseline 368/400 = 92.0%, Wilson 95% 88.9% to 94.3%
    2. Candidate B 352/400 = 88.0% 84.5% to 90.8%; intervals overlap, but overlap is not the test
    3. Paired counts Baseline passed and B failed on 30 items; B passed and baseline failed on 14 Net difference (30 - 14)/400 = 0.04
    4. Paired test Per-item differences +1, 0, -1: variance 0.1087, standard error the square root of 0.1087/400 = 0.0165 z = 2.43, one-sided p about 0.008
    5. Decision Treating runs as independent gives z = 1.89, p = 0.029; either way a 4-point drop is detected at the 5% level Block B

    The paired test is tighter when the same hard items sit in both runs; it is a normal-approximation check on 44 discordant items, no substitute for reading the 30 B lost.

    A regression the aggregate hides. Candidate C passes 364/400 (91.0%), one point below baseline and far inside what 400 items can detect (about 3.6 points). All four extra failures fall in "returns policy", a 30-item category.

    Slice Baseline Candidate C Wilson 95% (baseline; C)
    Returns policy 27/30 23/30 (76.7%) 74.4% to 96.5%; 59.1% to 88.2%

    A 30-item slice detects only about 16 points from a 90% baseline and this drop is 13.3, so a slice gate would probably miss it. Detecting 13.3 points from 90% takes about 41 items (49 with the correction): raise that slice to at least 50.

    Code sample: a CI gate with a confidence bound

    This gate fails the build when a slice's one-sided Wilson lower bound drops below a threshold. Standard library only.

    import json
    import math
    import sys
    from statistics import NormalDist
    
    
    def wilson_lower(passes, n, confidence=0.95):
        """One-sided lower confidence bound for a pass rate (Wilson score method)."""
        z = NormalDist().inv_cdf(confidence)
        p = passes / n
        centre = p + z * z / (2 * n)
        margin = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
        return (centre - margin) / (1 + z * z / n)
    
    
    def gate(results, threshold, confidence=0.95):
        """results: one bool per golden-set item. Pass only if the lower bound clears the threshold."""
        lower = wilson_lower(sum(results), len(results), confidence)
        return lower >= threshold, lower
    
    
    def run(by_slice, threshold):
        """by_slice: {"all": [...], "category-a": [...]}. Returns the slices that fail."""
        failed = {}
        for name, results in by_slice.items():
            ok, lower = gate(results, threshold)
            if not ok:
                failed[name] = (len(results), round(sum(results) / len(results), 3), round(lower, 3))
        return failed
    
    
    if __name__ == "__main__":
        failed = run(json.load(open(sys.argv[1])), float(sys.argv[2]))
        for name, (n, rate, lower) in failed.items():
            print(f"FAIL {name}: n={n} rate={rate} lower bound={lower}")
        sys.exit(1 if failed else 0)

    Run it as python gate.py results.json 0.90; CI reads the exit code. Checked by running it: 370 of 400 (lower bound 0.9004) exits 0; 369 (0.8976) prints FAIL all: n=400 rate=0.922 lower bound=0.898 and exits 1; 27 of 30 prints lower bound=0.774 and fails. A "fail" covers both failure and "inconclusive" (Figure 10). Count a malformed judge verdict as False, never as a pass.

    Common mistakes

    • Reporting raw agreement as judge quality. 87% hid a kappa of 0.57; report kappa and failure recall.
    • Tuning and gating on the same items. Keep a hold-out.
    • Reading overlapping intervals as "no difference". The paired test still detected a drop.
    • Gating on the average. A one-point drop hid 13 points in a 30-item category; report slices with n.
    • Changing the judge and the system in one release. Change one at a time.

    Try it

    Time: 20 to 40 minutes. Use an AI feature you work on, or a toy assistant over a document you have.

    1. Write 30 golden-set items with two slices and a pass/fail outcome; set 10 aside as hold-out.
    2. Run the feature twice and compute the Wilson interval for both runs (wilson_lower gives the lower limit).
    3. Relabel 20 items blind, build the 2x2 table and compute kappa as in the worked example.
    4. Pick a baseline and a drop you care about, compute the sample size, and say whether 30 items can detect it.

    Done when you have items with slices, two intervals, one kappa from a 2x2 table, a sample size for a drop you named, and a sentence on what your set can and cannot detect.

    Key takeaways

    • A golden set is seeded from real failures, tagged by slice, versioned and split into tuning and hold-out parts.
    • An LLM judge is a model under test: pin its version, count parse failures as errors, calibrate on fresh human labels.
    • Swap positions, control length and measure your own judge: the published bias rates come from 2023 models.
    • Report kappa and fail-class recall, not raw agreement; measure retrieval apart from generation.
    • Gate on a confidence bound and write down the smallest detectable drop.

    Self-check

    1. A judge agrees with human reviewers on 87% of 200 items. Why is that not enough to let it gate releases?

    Agreement includes chance: kappa is 0.57, below the 0.67 line, and the judge caught only 24 of 44 human-failed items.

    2. Two retrievers both place 2 of 4 relevant documents in the top 5, yet their nDCG at 10 is 0.558 and 0.816. Why?

    Recall at 5 ignores order inside the top 5. nDCG discounts gain by log2(1 + rank) and weights grades, so the grade-3 document first scores higher.

    3. A RAG answer scores faithfulness 1.0 and is still wrong. How, and which stage failed?

    Faithfulness checks that claims follow from the context, not that the context is right. A stale passage gives a faithful wrong answer: a source failure (Figure 3).

    4. A proof gate uses n = 400, a one-sided 95% Wilson lower bound and a 0.90 threshold. The true pass rate is 92%. What happens?

    It needs 370 passes and passes only about 40% of the time: 400 items cannot demonstrate 90% for a system two points above it. Raise n, lower the threshold, or use a regression gate.

    5. Why swap positions in a pairwise judge, and what does it cost?

    With very similar answers GPT-4 was consistent under swapping only 65.0% of the time. Counting a win only when the same answer wins both orders turns order effects into ties, at the cost of two calls per pair.

    Further reading

    Last verified: 2026-10-22

    Next

    Part B ends here. Part C starts with LLMOps and Observability for AI Systems, which takes the metrics and gates from this page into prompt registries, tracing, canary releases and cost tagging.

    Enroll to keep reading

    Lesson 8 of 8 · AI Architect (Intermediate): Design the System

    How AI architects evaluate LLM systems: golden sets, retrieval and generation metrics, judge bias and kappa calibration, and CI gates with confidence intervals.

    In the rest of this lesson

    • Under the hood: Calibrating a judge against human labels
    • Under the hood: Pairwise and absolute scoring
    • Under the hood: Retrieval metrics
    • Under the hood: Generation metrics
    • Under the hood: Confidence intervals and sample sizes for gates
    • Decision framework

    Enrolling is free. It unlocks every lesson in AI Architect (Intermediate): Design the System, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments