Evals GuideMEASURE · JUDGE · IMPROVE
Evaluation · October 2026

If you can't measure it, you're guessing.

One guide from "what is an eval" to running evaluation for millions of AI requests a day. Error analysis, datasets, code graders, LLM-as-judge, human review, statistics and error bars, RAG and agent evals, safety and red-teaming, public benchmarks, tools, CI release gates, production monitoring, fine-tuning, local and private deployment, system design, cost, every failure you'll hit, and when an eval is the wrong answer.

25chapters
6scale stages, 1 → 1M
100+problems with fixes
11live demos
The eval flywheel: production traces feed error analysis, which produces a dataset and graders, which run as experiments and release gates, which decide what ships back to production. Then the cycle repeats. the eval flywheel · look → label → measure → gate → ship → look again Tracesreal user requests Error analysisread · code · count Dataset + graderscode · judge · human Experimentsscores ± error bars Release gateship · block · fix quality you can prove not "it looked fine to me"

Pick where you are starting

Every chapter is tagged with a level. Choosing a path highlights the chapters to read first. Nothing is hidden.

Chapter 01Foundations

What evaluation actually is

In one sentence

An eval is a repeatable test that gives your AI system an input, records what it does, and grades the result against a definition of "good" you wrote down in advance. A set of evals turns "it seems better" into a number with error bars, so you can change prompts, models, retrieval or tools without breaking what already worked.

Traditional software is tested with assertions: given this input, the output must equal that value. AI systems break this model in four ways. Their output is open-ended (there are many correct answers), non-deterministic (the same input can give different outputs), sensitive (a one-word prompt change can shift behaviour on inputs you never looked at), and built on models that change under you when a provider ships a new version.

Evaluation is the discipline that makes these systems testable anyway. Anthropic's January 2026 guide defines an eval simply: give an AI an input, then apply grading logic to its output to measure success. Everything else in this guide is about doing that well: picking the right inputs, writing graders you can trust, measuring noise, and wiring the results into how you ship.

Practitioners who build AI products for a living say the same thing in different words. Hamel Husain: teams that succeed with LLM products are the ones with good evals and the habit of looking at their data. Greg Brockman (OpenAI): "evals are surprisingly often all you need." The model is rarely the bottleneck. Knowing whether a change helped usually is.

Four kinds of "testing" for AI, and how they relate

Benchmarkspublic tasks, compare modelsMMLU-Pro · GPQA · SWE-bench"which model is smarter?" Offline evalsyour dataset, before releaseCI gates · experiments"is this change better?" Online evalslive traffic, after releasesampled judges · feedback"is it still good?" Guardrailsevery request, real timeblock · redact · retry"stop this one now" Error analysis · read traces, name the failuresdecides what every other layer should measure
TermWhat it answersWho runs itTypical output
BenchmarkHow good is a model at a general skill?Model labs, researchers, leaderboardsOne score per model on a public task set
Offline evalIs version B of my system better than version A on my tasks?Your team, in development and CIScores per metric and slice, with confidence intervals
Online evalIs quality holding up on real traffic right now?Your team, on sampled production tracesPass rates over time, alerts, new failure examples
GuardrailShould this one response be blocked or fixed before the user sees it?Runtime, on every requestAllow, block, redact or retry
A/B testDoes the change improve what users and the business care about?Product and data teamsLift in task success, retention, conversion, with significance
Red-teamCan someone make the system misbehave on purpose?Security and safety teams, toolsAttack success rate, list of working exploits
Model eval vs system eval

A benchmark tells you about a model. Your users experience a system: model + prompt + retrieved context + tools + harness + guardrails + UI. A model that wins a leaderboard can lose on your task, and a cheaper model with better context can beat a frontier one. This manual is mostly about system evals; public benchmarks get their own chapter (Ch).

How we got here

WhenWhat happenedWhy it matters
2002–2004BLEU (machine translation) and ROUGE (summarisation)First automatic text-overlap metrics; still used, often misused for open-ended generation
2018–2019GLUE and SuperGLUEShared benchmark suites; saturated within about two years, a pattern that keeps repeating
2019–2020BERTScore; MMLU (57 subjects)Semantic similarity metrics; knowledge benchmarks for large models
2021HumanEval and pass@kCode graded by running unit tests; the unbiased pass@k estimator
Nov 2022Stanford HELMMany metrics (accuracy, calibration, robustness, bias, toxicity) per scenario instead of one number
2023Chatbot Arena (crowd pairwise votes, Elo); MT-Bench "Judging LLM-as-a-Judge"; G-Eval; RAGAS; SWE-bench; GPQALLM judges become mainstream; biases documented; RAG and agentic coding get their own evals
Mar 2024Hamel Husain, "Your AI Product Needs Evals"Moves the focus from benchmarks to product evals built from your own traces
Apr 2024Shankar et al., "Who Validates the Validators?" (EvalGen)Shows that criteria change as people grade ("criteria drift"); judges must be aligned with humans
2024UK AISI Inspect; τ-bench (pass^k); OpenAI "SWE-bench Verified"; Anthropic "Adding error bars to evals"Agent eval frameworks; reliability over repeated trials; statistics enters mainstream eval practice
Jan 2025Humanity's Last Exam (HLE)A hard expert benchmark launched with top scores under 10%
Jan 9, 2026Anthropic, "Demystifying evals for AI agents"Shared vocabulary for agent evals: tasks, trials, graders, transcripts, outcomes, harness
Feb 2026OpenAI stops reporting SWE-bench Verified, citing contaminationBenchmark leakage becomes a mainstream concern; harder successors (SWE-bench Pro) take over
Mar 9, 2026OpenAI announces it will acquire PromptfooEvals and red-teaming become part of the core agent platform stack
2026Stanford AI Index reports about half of widely cited benchmarks saturated; cloud eval services for agents go GAThe value moves from public scores to private, task-specific evals
Fast-changing details

Tool names, benchmark scores, cloud features and regulations in this guide are current to October 2026 and change monthly. Treat numbers as starting points and confirm product details in official docs before relying on them.

What an eval is not

Not a vibe check

Trying five prompts and nodding is a fine way to start, but it doesn't scale and it can't catch regressions on inputs you didn't try. A vibe check becomes an eval when the inputs are saved, the grading is written down, and it runs again on every change.

Not a single magic score

"Helpfulness: 4.2/5" tells you nothing about what to fix. Good evals are specific (one failure mode each), mostly binary (pass/fail), and sliced by input type.

Not a generic metric suite

Off-the-shelf "hallucination" or "toxicity" scores rarely match your product's real failures. Start from your traces (Ch), then pick or build metrics for what you found.

Deep dive

Foundations in more detail

Why AI evaluation is hard, and why it pays.

Why "just write unit tests" isn't enough basics
  • Many right answers. "Summarise this email" has thousands of acceptable outputs. Exact-match tests fail good answers.
  • Non-determinism. Even at temperature 0, outputs can vary across runs because of batching and hardware. One run tells you little; you need several trials and statistics (Ch).
  • Long-tail inputs. Users ask things you never imagined. Your eval set must come from real traffic, not only from your imagination.
  • Hidden coupling. Fixing one failure with a prompt change often breaks another. Only a regression suite run on every change catches this.
What evals buy you value
  • Speed of change. With a trusted suite, you can try a new model the day it ships and know within hours whether to switch. Anthropic notes teams with evals upgrade models in days instead of weeks.
  • Clear specs. Writing a grader forces the team to agree on what "good" means. Many "model problems" turn out to be unclear requirements.
  • Cost control. Evals let you prove a cheaper model or shorter prompt is good enough.
  • Evidence. Regulators, customers and your own leadership increasingly ask for documented testing.
The eval vocabulary is not standardised terms

"Metric", "evaluator", "scorer", "grader", "judge" and "assertion" are used interchangeably by different tools. "Test case", "example", "task", "sample" and "row" all mean one input in a dataset. This guide follows Anthropic's 2026 terms (task, trial, grader, transcript, outcome, harness, suite) and notes synonyms in the glossary (Ch).

Companion manuals links

Evaluation touches every other layer. The RAG Guide covers retrieval systems, the Agents Guide covers agent design, the Prompt Engineering and Context Engineering guides cover what you are evaluating, and the Loop Engineering Guide covers verification inside autonomous loops.

Chapter 02Foundations

Which evals you need, and when

The rule

Start with looking at 20–100 real outputs, not with a tool. Add cheap code checks for everything you can assert, LLM judges only for failures that code can't catch, and humans to calibrate both. Grow the suite as the product grows: a prototype needs a spreadsheet; a product with users needs CI gates and production monitoring.

The most common eval mistake is not a bad metric. It is building the wrong kind of eval at the wrong time: a 40-metric dashboard before anyone has read a single trace, or no evals at all until a customer complains. The right eval stack depends on how far along you are, how risky failures are, and what your system does.

Decision path: what to build next

  1. Have you read at least 50 real outputs?If not, do that first. Note the first thing wrong in each one (Ch). Everything else depends on knowing your real failure modes.
  2. Can the failure be checked by code?Format, JSON schema, required fields, forbidden words, length, SQL that runs, code that passes tests, the right tool called. Write a code grader. It's free, fast and never drifts (Ch).
  3. Does it need judgement?Tone, faithfulness to sources, whether the answer addressed the question. Write one binary LLM judge per failure mode and measure its agreement with a human before trusting it (Ch).
  4. Is the change going to production?Turn the suite into a regression gate in CI, with confidence intervals so noise doesn't block or pass changes by luck (Ch, Ch).
  5. Do you have users?Sample production traces, run the same graders online, collect feedback, and feed new failures back into the dataset (Ch).
  6. Can failures hurt someone?Add red-teaming, safety evals and human review for high-stakes slices before launch (Ch).

Live demo · build your eval plan

Tick what is true for your system. The plan lists which evals to build, in order, and which chapters cover them.

Evals by stage

StageDatasetGradersWhere it runsTime per week
Prototype20–50 hand-written and real examples in a spreadsheetYou, reading outputs; a few assertionsNotebook1–2 h
Pre-launch100–300 examples covering main features, edge cases and known failuresCode checks + 2–5 calibrated binary judgesScript or eval framework; run before each change3–6 h
Launched300–2,000 examples, refreshed from production monthlyFull suite; human review of samplesCI gate on every PR; nightly full runA part-time owner
ScalingSeveral suites per feature, plus holdouts and safety setsJudges with tracked agreement; online evaluatorsCI + production sampling + dashboards + alertsA dedicated person or team
Regulated / high stakesDocumented, versioned datasets with expert labelsExpert review, audit trail, bias and safety evalsFormal release processA team, plus domain experts

Good uses and bad uses

SituationVerdictWhy
Deciding whether to switch to a new or cheaper modelMust haveWithout a suite, model choice is a guess; with one, it's a 1-hour job
Changing a prompt that serves real usersMust havePrompt edits silently break cases you didn't look at
Checking that structured output is valid JSONCode checkDeterministic and free; no judge needed
Grading tone or faithfulnessJudge + human calibrationNeeds judgement; judge must agree with a person first
Generic "helpfulness 1–5" across all outputsRewriteVague, unactionable and noisy; split into specific binary checks
Building a 30-metric dashboard on day oneDon'tMetrics before error analysis measure things nobody cares about
Trusting a public leaderboard to pick a model for your taskDon'tBenchmarks measure general skill, often with contamination; test on your own data
Don't buy a tool before you know what to measure

Frameworks make it easy to run many generic metrics. Those metrics feel productive and rarely match your failures. Anthropic's guide makes the same point: the framework matters far less than the quality of the tasks you run through it.

Deep dive

Deciding with numbers

How much evaluation is enough.

How much time to spend on evals effort

Practitioners commonly report spending 60–80% of AI development time on error analysis and evaluation once a product is live. That sounds extreme until you notice that writing the prompt is quick, and knowing whether it works is the hard part. Early on, budget at least one hour of reading traces for every hour of prompt changes.

The cost of not having evals risk
Expected cost of a silent regression = P(change breaks a slice) × users in that slice × cost per bad answer × days until noticed

Example: a 10% chance that a prompt change breaks refunds, 2,000 refund conversations a day, $3 of support cost per bad answer, noticed after 7 days: 0.1 × 2,000 × 3 × 7 = $4,200 expected cost per risky change. A regression suite that catches it costs a few dollars per run.

Signals your evals are not working smell
  • Eval scores go up but user complaints don't go down.
  • Everything passes at 95%+ (the suite is too easy, or saturated).
  • Nobody can say what a failing case looks like without opening a dashboard.
  • The team argues about whether a score drop is "real" (no error bars).
  • The judge's verdicts surprise the domain expert more than 1 time in 10.
Chapter 03FoundationsBuilder

Anatomy of an eval, and the flywheel

The parts

Every eval has the same parts: a task (input + success criteria), one or more trials, a transcript of what happened, an outcome (final state), graders that score it, a harness that runs it all, and a suite that groups tasks. Around them sits a loop: look at data, label failures, measure, gate releases, ship, look again.

One eval run, end to end

eval harness · versioned: dataset · system (model + prompt + tools) · graders · judge prompts Datasettasks + criteria System under testk trials per task Transcript+ outcome (state) code graders LLM judges human sample Metricsmean ± CI by slice Baseline runsame tasks, old version Decisionship · block · fix failures you find become new tasks in the dataset
PartWhat it isAlso calledKey decision
TaskOne test: an input plus what success meansTest case, example, sample, row, problemUnambiguous criteria; a reference answer or a rule
TrialOne attempt at a taskRun, rollout, sampleHow many trials per task (1 for cheap checks, 3–10 for agents)
TranscriptEverything that happened: messages, tool calls, reasoning, intermediate resultsTrace, trajectory, logStore it all; you'll need it for debugging and re-grading
OutcomeThe final state of the world after the trialEnd state, resultGrade what actually happened (the booking exists), not what the agent said
GraderLogic that scores one aspect of a trialEvaluator, scorer, metric, judge, assertionCode first, model second, human to calibrate
MetricAn aggregate of grader scoresScore, KPIMean pass rate per slice, with a confidence interval
HarnessInfrastructure that runs tasks, records transcripts, grades and aggregatesEval runner, frameworkIsolated, reproducible trials; parallel; cached
SuiteA group of tasks for one capability or featureEval set, benchmarkCapability suite (hard, low pass rate) or regression suite (near 100%)
BaselineScores of the current version on the same suiteControlAlways compare paired, on the same tasks

Capability evals vs regression evals

Hill to climb

Capability evals

Ask "what can it do well?" They should start with a low pass rate (20–60%) so there is room to improve. You use them to pick models, compare prompts and track progress. When they reach ~90%+, they graduate into the regression suite and you write harder ones.

Tripwire

Regression evals

Ask "does it still do what it used to?" They should sit near 100%. Any drop means something broke. They run on every change in CI and must be fast, cheap and stable. Flaky regression tests destroy trust quickly.

Offline vs online

Offline evalsOnline evals
InputsFixed, curated datasetLive traffic, sampled
Reference answersOften availableRarely; reference-free graders only
WhenBefore release, on every changeAfter release, continuously
CatchesRegressions, model and prompt comparisonsDrift, new user behaviour, unknown failure modes
WeaknessDataset goes stale; misses new inputsNo ground truth; privacy limits; delayed signal

The smallest useful harness

python · a minimal eval harness
import json, statistics, concurrent.futures as cf

def run_suite(tasks, system, graders, trials=3):
    def one(task):
        rows = []
        for t in range(trials):
            out = system(task["input"])                     # transcript + outcome
            scores = {g.__name__: g(task, out) for g in graders}  # each returns 0 or 1
            rows.append({"id": task["id"], "trial": t, "slice": task.get("slice"), **scores})
        return rows
    with cf.ThreadPoolExecutor(8) as ex:
        results = [r for rows in ex.map(one, tasks) for r in rows]
    json.dump(results, open("results.json", "w"))           # keep raw rows for re-analysis
    for g in graders:
        xs = [r[g.__name__] for r in results]
        p = statistics.mean(xs); se = (p * (1 - p) / len(xs)) ** .5
        print(f"{g.__name__:24} {p:.1%} ± {1.96*se:.1%}")  # naive CI; see Ch 9 for clustered
    return results
Deep dive

Parts that are easy to get wrong

Details that decide whether your scores mean anything.

Grade the outcome, not the path agents

Anthropic's guide warns against grading agents on whether they followed one expected sequence of steps. Models often find valid routes you didn't anticipate (one model "failed" a τ²-bench airline task by finding a policy-compliant option that served the user better). Check the outcome first (is the reservation in the database?), then add a few path constraints that truly matter (did it verify identity before refunding?). See Ch.

Isolate every trial harness

Shared state between trials inflates or deflates scores. Anthropic found one internal eval where the agent could read git history left by earlier trials. Give each trial a fresh environment (container, database snapshot, clean working directory), and don't let rate limits or shared caches make trials depend on each other.

A 0% pass rate usually means a broken task quality

If no model passes a task in 50–100 trials, check the task before blaming the model. Common causes: the grader expects an exact string the instructions never asked for, a file path is never specified, or the reference answer is wrong. A good test: two domain experts should independently agree on pass/fail, and a reference solution should exist that passes the grader.

Version everything that can change a score reproducibility

A score is only meaningful with its full context: dataset version, model ID and date, prompt version, tool versions, temperature and sampling settings, grader code version, judge model and judge prompt version, and the random seed. Store these with every run. Without them, "the score dropped" can't be explained.

Chapter 04FoundationsBuilder

Error analysis: look at your data

Key insight

The highest-value eval activity is not a metric. It is reading traces and writing down what went wrong. Read ~100 real traces, note the first failure in each (open coding), group the notes into a small set of failure modes (axial coding), and count them. The top 3–5 modes are what your evals should measure.

Error analysis comes from qualitative research and was popularised for LLM products by Hamel Husain and Shreya Shankar. The idea is simple: you can't write a good grader for a failure you haven't seen, and generic metrics ("helpfulness", "coherence") rarely line up with the failures your users hit. So before you measure anything, you look.

The process is mechanical enough to do in an afternoon with a spreadsheet. It works best when one person with domain knowledge (a "benevolent dictator", in Husain's words) makes the final calls, so labels stay consistent.

  1. Gather tracesPull ~100 recent, diverse traces from production or, before launch, from realistic synthetic queries (see the deep dive). Include the full transcript: user input, retrieved context, tool calls, final output.
  2. Open codingFor each trace, mark pass or fail, and for failures write a short free-text note about the first thing that went wrong. Upstream errors cause downstream ones, so the first failure is usually the root cause. Don't use a fixed list yet.
  3. Axial codingGroup similar notes into named failure modes: "wrong date math", "ignored retrieved policy", "asked for info the user already gave". Aim for 5–10 modes. An LLM can propose groupings; a human decides.
  4. Count and prioritiseTally traces per mode. A few modes usually cover most failures (a Pareto pattern). Weigh frequency by severity.
  5. Fix or measureSome failures are obvious bugs: fix them, no eval needed. For the rest, write a specific grader for each mode (Ch, Ch).
  6. RepeatKeep reading until new traces stop revealing new modes (theoretical saturation), then repeat after every significant change and on a regular schedule.

Live demo · code twelve traces

These are traces from a fictional travel-support assistant. Read each one and pick the first failure (or "Pass"). The chart shows your failure taxonomy, sorted Pareto-style. Click "Show expert codes" to compare.

What good notes look like

Weak noteStrong noteWhy
"Bad answer""Quoted a 24 h cancellation window; policy doc retrieved says 48 h"Specific, checkable, points to the cause
"Hallucinated""Invented a flight number not in the search tool's results"Says what was invented and what the source was
"Tone off""Used marketing language ('amazing deal!') in a refund denial"Concrete enough to write a judge prompt from
"Tool error""Called search_flights with date in DD/MM; tool expects ISO"Could become a code check on tool arguments
Binary beats a 1–5 scale for error analysis

Pass/fail forces a decision, makes disagreements visible, and converts straight into a pass rate. A 1–5 score invites everyone to pick 3 or 4, hides what's wrong, and is far harder to align between people or with a judge. If you need nuance, use several specific binary checks instead of one scale.

Deep dive

Doing error analysis well

Sampling, synthetic data, tooling and LLM help.

How many traces is enough? sampling

Start with about 100 and keep going until about 20 traces in a row produce no new failure mode. That's theoretical saturation. If a failure mode affects 5% of traffic, the chance of seeing it at least once in 100 random traces is 1 − 0.95¹⁰⁰ ≈ 99.4%; for a 1% mode it's 63%. Rare but severe modes need targeted sampling (filter by thumbs-down, escalations, long conversations, specific features).

No users yet? Generate realistic queries with dimensions synthetic

Don't ask an LLM for "100 test questions"; you'll get 100 similar, polite questions. Instead, define dimensions and combine them:

Feature
booking change, refund, baggage, loyalty points
Persona
first-time flyer, frequent business traveller, agent booking for a client
Scenario
clear request, missing info, contradictory info, out of scope, angry

Pick tuples (refund × first-time flyer × missing info), have a person check them, then ask an LLM to write a natural query for each tuple. Run them through your system and analyse the traces like real ones.

Where LLMs help, and where they must not automation
  • Good uses: proposing groupings for axial coding, counting notes per mode, drafting judge prompts from your notes, summarising long traces before you read them.
  • Bad uses: doing the open coding for you. The point of reading is to build your own understanding of the product's failures; an LLM's first-pass labels anchor you and miss product-specific problems.
Build a trace viewer, it pays for itself tooling

Reading raw JSON is slow. A simple custom viewer that shows one trace per screen, renders retrieved docs and tool calls, and has pass/fail buttons and a notes box with keyboard shortcuts can triple how many traces you review per hour. Langfuse, LangSmith, Braintrust, Phoenix and others have annotation queues; many teams still build a 200-line internal viewer tuned to their domain.

Fix first, then measure priorities

Not every failure needs an eval. If the system prompt simply never mentions the 48-hour policy, add it and move on. Write evals for failure modes that are persistent (they come back), subtle (they need judgement), or regression-prone (fixes tend to break). Over-measuring trivial bugs bloats the suite and slows CI.

Chapter 05Builder

Datasets and golden sets

Key insight

Your eval is only as good as its tasks. Build datasets from real failures and real traffic, cover each feature and edge case as a slice, write unambiguous success criteria, keep a holdout you never tune on, version every change, and refresh from production so the set never goes stale.

A "golden dataset" is a curated set of tasks with trusted expected behaviour. People often think the hard part is size. It isn't: 50 well-chosen tasks from real failures beat 5,000 generic ones. The hard parts are coverage (do the tasks represent what users actually do?), clarity (would two experts agree on pass/fail?) and freshness (does it still match today's traffic?).

Where tasks come from

SourceStrengthWeaknessUse for
Production traces (sampled)Real distribution and phrasingNeeds PII handling; few reference answersMain regression and capability sets
Bug reports, support tickets, thumbs-downKnown high-impact failuresBiased toward loud failuresRegression tests ("never again")
Domain experts writing tasksHard, realistic, correct referencesSlow, expensiveCapability sets, high-stakes slices
Synthetic (dimension-based, LLM-written)Fast coverage of rare combinations; pre-launchCan be bland or unrealistic; needs reviewEdge cases, cold start, stress tests
Adversarial / red-teamFinds safety and robustness gapsNot representative of normal useSafety suites (Ch)
Public benchmarksFree, comparableGeneric, often contaminatedSanity checks only (Ch)

What a task record should hold

jsonl · one task per line
{"id": "refund-0142",
 "input": {"messages": [{"role": "user", "content": "I booked yesterday, can I still cancel for free?"}],
           "user_profile": {"tier": "basic", "booking_age_hours": 20}},
 "slice": ["refund", "policy", "basic-tier"],
 "expected": {"must_include": ["free cancellation within 48 hours"],
              "must_not": ["24 hours"], "tool_calls": ["get_booking"]},
 "reference": "Yes. Basic fares can be cancelled free within 48 hours of booking...",
 "source": "ticket-88213", "difficulty": "easy", "added": "2026-09-14", "owner": "support-ai"}

Coverage: slices, not just averages

An overall pass rate hides problems. A system can score 92% overall and 55% on the slice that matters most (refunds for premium customers, questions in Spanish, multi-turn conversations). Tag every task with slices and always report results per slice. Make sure each important slice has enough tasks to measure: about 30–50 at minimum to see big drops, a few hundred to see small ones (Ch).

By feature

Each product capability: search, booking change, refund, FAQ, escalation.

By input type

Short vs long, single vs multi-turn, language, with vs without attachments, ambiguous vs clear.

By risk

Money movement, medical or legal, account changes, minors, anything a regulator cares about.

Positive and negative

Cases where the behaviour should happen and cases where it should not (search when needed vs answer from knowledge). Balanced sets catch over-triggering as well as under-triggering.

By difficulty

Keep some hard tasks the system fails today; they're your capability hill.

By user segment

Tier, region, device, new vs returning. Useful for fairness checks.

Splits: dev, test, holdout

SplitUsed forRule
DevIterating on prompts, debugging, reading failuresLook at it as much as you like
TestDeciding whether a change shipsRun it, report it, don't tune to individual cases
HoldoutChecking you haven't overfit dev and test over months of tuningRun rarely (monthly, before big releases); never read individual failures
You can overfit an eval set with prompts

Every time you change a prompt to fix a specific failing test case, the score on that set becomes a little more optimistic. Over dozens of rounds, prompt "tuning" on a fixed set behaves like training on the test set. The holdout catches this. Automated prompt optimisers (DSPy, GEPA) make it even more important.

Deep dive

Dataset engineering

Ambiguity, references, contamination and maintenance.

Writing unambiguous tasks quality
  • State exactly what the system should do, including formats and file paths the grader will check.
  • Prefer outcome criteria ("the booking date is 14 Nov") over wording criteria ("says 'I have changed'").
  • Write a reference solution and confirm it passes your grader.
  • Have a second person grade 20 tasks blind; if you disagree on more than 1 or 2, rewrite the criteria.
Reference answers: when you need them labels

Reference-based graders compare to a known good answer (exact match, F1, "does the answer contain the same facts as the reference?"). They're more reliable but need labelled data. Reference-free graders judge the output on its own (is it grounded in the retrieved context? does it follow the format?). Online evals are almost always reference-free. A useful middle ground: store key facts or must/must-not lists instead of a full reference answer.

Contamination and leakage integrity

If tasks appear in a model's training data (public benchmarks, GitHub, your own docs that were published), scores overstate real ability. For private sets: don't publish them, add canary strings (a unique random string you can search for later), and prefer tasks created after a model's training cutoff. For RAG systems, make sure test answers aren't trivially present verbatim in a single retrieved chunk unless that's what you want to test.

Keeping datasets fresh maintenance
  • Add every production bug as a regression task within a day of fixing it.
  • Monthly: sample new production traces, run error analysis, add new modes.
  • Quarterly: retire tasks that no longer reflect the product, and check slice balance against traffic.
  • Track dataset versions in git (small sets) or a dataset registry (large ones) with a changelog. Scores from different versions aren't comparable.
Privacy and PII in eval data compliance

Production traces contain personal data. Redact or pseudonymise before copying them into datasets (Microsoft Presidio, cloud DLP services), restrict access, set retention limits, and record consent basis. Synthetic variants of real traces ("same structure, fake details") keep the useful shape without the personal data.

Chapter 06Builder

Code graders and metrics

Key insight

Use code wherever you can. Code graders are free, instant, reproducible and never drift: schema checks, regex, exact and fuzzy match, executing code and tests, checking tool calls and database state. Text-overlap metrics like BLEU and ROUGE are weak for open-ended LLM output; embedding similarity is better but still not a judge of correctness.

Anthropic's guide ranks graders the same way most practitioners do: deterministic graders first, model-based graders where needed, humans to calibrate. A surprisingly large share of real failures can be checked with code: format, length, required fields, forbidden phrases, valid SQL, the right tool with valid arguments, the right final state. Vendors estimate 60–70% of an eval surface can be deterministic; your number depends on the task.

The grader menu

GraderHow it worksGood forWatch out
Exact / normalised matchCompare after lower-casing, trimming, removing punctuationClassification labels, short answers, IDs, numbersFails valid paraphrases
Numeric tolerance|answer − reference| ≤ toleranceMaths, finance, measurementsParse numbers robustly ("1,200", "1.2k")
Contains / regex / must-notRequired or forbidden substrings or patternsPolicy phrases, disclaimers, banned words, leaked secretsEasy to game; brittle wording
Schema validationParse JSON; validate with JSON Schema / PydanticStructured output, tool argumentsValid shape ≠ correct values
ExecutionRun generated code, SQL or commands; check results or testsCode generation, text-to-SQL, data analysisSandbox it; tests can be weak
Tool-call checkWas the right tool called, with valid args, in an allowed order?Agents, function callingDon't over-constrain the path (Ch)
State / outcome checkQuery the environment after the trial (DB row, file, API state)Agents that change thingsNeeds an isolated environment
Classification metricsPrecision, recall, F1, confusion matrix against labelsRouting, intent detection, moderation, extractionReport per class; watch imbalance
Text overlap (BLEU, ROUGE, chrF, METEOR)Counts shared n-grams with a referenceTranslation, tightly constrained summariesCorrelates poorly with quality for free-form answers
Semantic similarity (BERTScore, embedding cosine)Compares meaning via embeddingsParaphrase-tolerant matching to a reference"Paris is the capital" vs "Paris is not the capital" can score high
HeuristicsLength, readability, language ID, latency, cost, number of turnsConstraints and efficiencyProxies, not quality

Live demo · metric playground

Edit the reference and the candidate answer, or pick a preset. Watch how overlap metrics reward wording rather than meaning. Notice the "negation trap": a wrong answer that scores high on overlap.

Token precision P = |cand ∩ ref| / |cand| · recall R = |cand ∩ ref| / |ref| · F1 = 2PR / (P + R)
BLEU = BP · exp(Σ wₙ log pₙ), BP = min(1, e^(1 − ref_len/cand_len)) · ROUGE-L uses the longest common subsequence (LCS): F = 2·P_lcs·R_lcs / (P_lcs + R_lcs)
Deep dive

Getting code graders right

Robustness, gaming and when to stop.

Make graders robust to valid variation brittleness

Anthropic reports that one model's score on a reproduction benchmark rose from 42% to 95% once graders stopped rejecting "96.12" when "96.124991…" was expected, and ambiguous tasks were fixed. Normalise case, whitespace, units and number formats; accept equivalent answers; parse structured output before comparing; and read failing transcripts to catch graders rejecting correct work.

Graders can be gamed integrity

If a coding agent can edit tests, "tests pass" stops meaning anything. If a grader checks for a phrase, a prompt can be tuned to include the phrase without doing the work. Protect test files, use hidden tests the system never sees, combine several independent checks, and look at passing transcripts too, not just failing ones.

Why BLEU and ROUGE mislead for LLM output metrics

They were designed for tasks where good outputs share much of their wording with a reference (translation, extractive summaries). LLM answers to open questions vary widely in wording, so a perfect answer can score low and a fluent wrong one can score high. Use them only for narrow tasks, as one signal among several, and never as a release gate on their own.

Partial credit for multi-part tasks scoring

A task with five required facts can score 0.6 instead of 0 when three are present. Partial credit makes progress visible on hard capability evals. For regression gates, binary "all required parts present" is usually clearer. Anthropic describes three ways to combine graders: binary (all must pass), weighted (combined score above a threshold) and hybrid.

Calibration: does the model know when it's unsure? advanced

For classifiers and systems that output confidence, measure calibration: among answers given with 80% confidence, are about 80% correct? Expected calibration error (ECE) bins predictions by confidence and averages |accuracy − confidence|. Well-calibrated confidence lets you route low-confidence cases to humans, which is often worth more than a few points of accuracy.

Chapter 07Builder

LLM-as-judge: graders you can trust

Key insight

An LLM judge is a prompt that grades another model's output. It's flexible and scalable, but it's also a model that needs evaluating. Write one binary judge per failure mode, give it a precise rubric and examples, ask for reasoning before the verdict, and measure its agreement with human labels (true positive and true negative rates) on a held-out set before you trust its numbers.

The 2023 MT-Bench paper ("Judging LLM-as-a-Judge") showed that strong models agree with human preferences about as often as humans agree with each other, and it also documented the biases that come with them. Since then LLM judges have become the default for anything code can't check: faithfulness, relevance, tone, policy compliance, whether a question was actually answered.

The catch: a judge's verdict is only as good as its alignment with what your experts would say. Shreya Shankar's EvalGen research found that people's own criteria shift as they grade ("criteria drift"), so aligning a judge is an iterative process, not a one-time prompt.

Judge formats

FormatQuestion to the judgeBest forMain risk
Binary, single output"Does this response cite a source for every factual claim? PASS/FAIL"Specific failure modes; regression gatesNeeds one judge per criterion
Reference-guided"Does the response contain the same key facts as the reference?"Correctness when you have referencesPenalises valid extra info if rubric is strict
Pairwise"Which response is better for this user, A or B?"Comparing two versions; preference dataPosition bias; doesn't give absolute quality
Likert / score 1–10"Rate helpfulness 1–10"Rarely the right choiceNoisy, poorly calibrated, unactionable
Checklist / rubric"Check each: (1) greets (2) verifies identity (3) states policy (4) offers next step"Multi-criteria tasks; partial creditLong rubrics dilute attention; split if >5 items
Adaptive rubricJudge first writes prompt-specific pass/fail tests, then applies themDiverse open-ended promptsGenerated tests need spot checks (Vertex AI uses this approach)

Anatomy of a good judge prompt

text · judge prompt for one failure mode
You are grading a travel-support assistant's reply for ONE criterion:
POLICY_FAITHFUL: every policy statement in the reply matches the policy excerpts provided.

PASS if: all stated deadlines, fees and conditions appear in the excerpts, or the reply
         makes no policy statements.
FAIL if: the reply states any deadline, fee or condition that contradicts or is absent
         from the excerpts.
UNKNOWN if: the excerpts are empty or unreadable.

Examples:
<example verdict="FAIL">Excerpt: "free cancellation within 48 hours". Reply: "You have 24 hours."</example>
<example verdict="PASS">Excerpt: "...48 hours...". Reply: "You can cancel free until 48 hours after booking."</example>

<policy_excerpts>{context}</policy_excerpts>
<reply>{output}</reply>

First write one or two sentences of reasoning quoting the relevant text.
Then output JSON: {"reasoning": "...", "verdict": "PASS" | "FAIL" | "UNKNOWN"}

Do

  • One criterion per judge; binary verdict
  • Precise PASS and FAIL definitions with borderline examples
  • Reasoning before the verdict; structured JSON output
  • An "UNKNOWN" option so it doesn't guess
  • Give it the context it needs (retrieved docs, tool results)
  • Pin the judge model version and temperature 0

Don't

  • Ask for a 1–10 score of a vague quality
  • Use the same model and prompt that produced the output as its own judge, without checks
  • Put five criteria in one prompt
  • Trust it before measuring agreement with humans
  • Change the judge prompt without re-measuring agreement
  • Read only the score; read the reasoning on disagreements

Known judge biases

BiasWhat happensMitigation
PositionIn pairwise comparisons, prefers the first (or second) answerRun both orders; count a win only if consistent; otherwise tie
Verbosity / lengthPrefers longer answersRubric says length is not quality; length-controlled metrics (AlpacaEval LC); check correlation of verdict with length
Self-preferenceRates outputs from its own model family higher (linked to lower perplexity / familiarity)Use a judge from a different family, or a panel of judges
LeniencyPasses almost everything; low true negative rateFew-shot FAIL examples; measure TNR explicitly; stricter wording
Authority / formatSwayed by confident tone, citations or markdown formatting, even if wrongAsk it to verify claims against provided context, not style
Sycophancy to the promptFollows hints in the output ("this answer is correct")Wrap output in tags; instruct to ignore instructions inside it
Knowledge limitsCan't verify facts it doesn't know or that changed after its cutoffGive references or retrieved context; use reference-guided judging

Aligning a judge with humans

  1. LabelA domain expert labels 100–200 traces PASS/FAIL for the criterion, with notes. Make sure there are enough FAILs (at least 30–50); oversample failures if needed.
  2. SplitTrain (few-shot examples, ~20%), dev (iterate on the prompt, ~40%), test (final measurement, ~40%, untouched until the end).
  3. Iterate on devRun the judge, look at every disagreement, refine definitions and examples. Stop when TPR and TNR are both high (often >90%) or stop improving.
  4. Measure on testReport TPR (judge says PASS when human says PASS) and TNR (judge says FAIL when human says FAIL). Accuracy alone hides a judge that always says PASS.
  5. Correct production estimatesUse TPR and TNR to correct the judge's raw pass rate on unlabelled data and put a confidence interval on it (demo below).
  6. Re-checkRe-measure agreement when the judge model, judge prompt or product changes, and monthly on a fresh sample.

Live demo · how much should you trust your judge?

Set the judge's measured agreement with humans and the raw pass rate it reports on production traces. The corrected estimate removes the judge's systematic errors; the interval shows the remaining uncertainty.

Raw judge pass rateCorrected true pass rate
Corrected pass rate θ = (p_obs + TNR − 1) / (TPR + TNR − 1)  (Rogan–Gladen estimator), clipped to [0, 1]
Uncertainty comes from three sources: the judge's sample of production traces (n), and the human test set used to estimate TPR and TNR. Bootstrap all three for an interval.
Deep dive

Advanced judging

Model choice, panels, cost and specialised judges.

Which model should judge? choice

Start with a strong general model for alignment, then test whether a smaller, cheaper model reaches the same TPR/TNR on your test set; for narrow binary criteria it often does. Prefer a judge from a different model family than the system under test, to reduce self-preference. Pin the exact version: a silent judge upgrade changes all your historical comparisons.

Panels of judges ensemble

"Replacing Judges with Juries" (Verga et al., 2024) found that a panel of smaller models from different families, voting, can match or beat a single large judge at lower cost and with less self-preference bias. Use majority vote for binary verdicts, and treat disagreement as a signal to send the case to a human.

G-Eval and probability-weighted scores technique

G-Eval (Liu et al., 2023) asks the judge to generate evaluation steps from the criteria, then scores using the probabilities of each score token instead of the single sampled token, giving smoother, more fine-grained scores. It's available in DeepEval and other frameworks. Useful for continuous scores; for gates, binary verdicts are still easier to align.

Fine-tuned and specialised judges models

Open judge models (Prometheus 2, various "reward model" and grounding checkers) and vendor evaluators (Patronus Lynx for hallucination, cloud groundedness evaluators) are trained for evaluation. They can be cheaper and more consistent, but still need alignment with your labels. Fine-tuning your own small judge on a few thousand expert labels is worth it at high volume.

Reasoning models as judges 2026

Judges with extended thinking tend to be better at multi-step verification (checking maths, comparing several claims to sources) and worse on cost and latency. Use them where verification is hard; use fast non-reasoning judges for simple format and policy checks. Measure both on your test set rather than assuming.

Chapter 08BuilderFoundations

Human evaluation and annotation

Key insight

Humans are the gold standard and the bottleneck. Use them where judgement matters most: error analysis, labelling the sets that calibrate judges, high-stakes review and final sign-off. Write clear guidelines, measure inter-annotator agreement (Cohen's κ), prefer domain experts over crowds for specialist work, and spend human time where automated graders disagree or are unsure.

Every automated grader eventually traces back to a human judgement: a person decided what "correct" means, labelled the examples the judge was aligned with, and reviews the cases it gets wrong. The question is not whether to use humans, but where their time has the most leverage.

Human eval typeWhoUse forRough cost
Error analysisProduct owner, domain expertFinding failure modes (Ch)2–4 h per 100 traces
Labelling for judge alignmentDomain expert (one "benevolent dictator", or 2–3 with adjudication)Ground truth for TPR/TNR1–3 min per label
Expert reviewDoctors, lawyers, senior engineersHigh-stakes correctness$2–$30+ per item
Crowd preferenceTrained raters, crowd platformsPairwise preferences, fluency, general quality$0.10–$2 per comparison
Spot-check samplingTeam members on rotationCatching judge drift in production30 min a week
User studies / A/BReal usersWhether changes help outcomesProduct time and traffic

Agreement: are your humans consistent?

If two experts disagree on 30% of items, no judge can be "90% accurate", because there's no single truth to match. Measure agreement on a shared sample before using labels as ground truth. Cohen's κ corrects raw agreement for the agreement you'd expect by chance, which matters a lot when most items pass.

Live demo · Cohen's kappa calculator

Two graders (two people, or a person and a judge) labelled the same items. Enter the counts. Notice how 90% raw agreement can be a weak κ when nearly everything passes.

B: PASSB: FAIL A: PASS
A: FAIL
p_o = (a + d) / n · p_e = [(a+b)(a+c) + (c+d)(b+d)] / n² · κ = (p_o − p_e) / (1 − p_e)
Rough reading (Landis & Koch): <0.2 slight · 0.2–0.4 fair · 0.4–0.6 moderate · 0.6–0.8 substantial · >0.8 almost perfect

Annotation guidelines that work

Write it like a rubric

One page per criterion: definition, PASS and FAIL rules, 3–5 borderline examples with the correct verdict and why. Version it; update it when adjudication reveals a gap.

Calibrate before labelling

Have all annotators label the same 20–30 items, discuss disagreements, update the guideline, then start. Repeat on a small overlap sample every week.

Make the tool fast

Show everything the grader needs on one screen (input, context, output, criterion), with keyboard shortcuts and a notes field. Speed directly reduces cost and fatigue errors.

Route smartly

Send humans the cases where judges disagree, judges say UNKNOWN, users complained, or the slice is high risk. Random samples are still needed to measure judge drift.

Deep dive

More on human evaluation

Preferences, rankings and pitfalls.

Pairwise preferences, Elo and Bradley–Terry ranking

People are better at saying "A is better than B" than at giving absolute scores. Pairwise votes can be turned into rankings with the Bradley–Terry model: P(A beats B) = 1 / (1 + e^−(s_A − s_B)). LMArena (formerly Chatbot Arena) ranks models this way from crowd votes. For your own product, pairwise human or judge comparisons are a good way to compare two prompt versions when there's no single right answer.

More than two annotators stats

Fleiss' κ generalises Cohen's κ to many raters; Krippendorff's α handles missing labels and ordinal or interval scales. Many teams use one expert ("benevolent dictator") for consistency and a second expert on a 10–20% overlap sample to measure agreement.

Common human-eval failures pitfalls
  • Fatigue: accuracy drops after about an hour; keep sessions short.
  • Anchoring: showing a judge's verdict first biases the human; hide it until they decide.
  • Order effects: randomise item and A/B order.
  • Crowd vs expert mismatch: crowd raters prefer fluent, confident answers even when experts know they're wrong.
  • Criteria drift: annotators' standards shift as they see more outputs; re-label early items at the end.
Tools for annotation tools

Label Studio and Argilla (open source), annotation queues in Langfuse, LangSmith, Braintrust, Phoenix and W&B Weave, cloud labelling services (Amazon SageMaker Ground Truth, Vertex AI data labelling), and simple custom viewers. Choose by whether the tool shows your traces well; that matters more than features.

Chapter 09BuilderArchitect

Statistics: noise, error bars and pass@k

Key insight

Every eval score is an estimate with noise. On 200 tasks, a score of 80% has a 95% interval of roughly ±5.5 points, so a 3-point "improvement" can be luck. Report confidence intervals, compare versions paired on the same tasks, run several trials for non-deterministic systems, and size your dataset for the smallest change you need to detect.

Anthropic's 2024 paper "Adding Error Bars to Evals" (Evan Miller) argued that most published model comparisons ignore statistical uncertainty, and gave practical recipes: report standard errors, cluster them when questions are related, use paired differences, and reduce variance with repeated sampling. The same ideas apply to product evals, where datasets are often only a few hundred tasks.

The core formulas

Standard error of a pass rate: SE = √(p(1 − p) / n) · 95% CI ≈ p ± 1.96·SE (Wilson interval is better near 0% or 100%)
Difference of two independent pass rates: SE_diff = √(SE_A² + SE_B²) · Paired (same tasks): SE_diff = sd(dᵢ) / √n, where dᵢ = score_Bᵢ − score_Aᵢ
Tasks needed to detect a change δ (unpaired, 95% confidence, 80% power): n ≈ (1.96 + 0.84)² · 2p(1 − p) / δ²

Live demo · is this improvement real?

Set the baseline pass rate, the number of tasks and the change you observed. See the interval, whether the change is significant, and how many tasks you'd need to detect it reliably.

Non-determinism: pass@k and pass^k

When the same task can pass or fail on different runs, one trial per task hides how reliable the system really is. Two metrics describe repeated trials, and they answer opposite questions:

At least once

pass@k

Probability that at least one of k attempts succeeds. Rises with k. Right when a human or a verifier picks the best attempt (code suggestions, best-of-N with tests). From n samples with c correct: pass@k = 1 − C(n−c, k) / C(n, k).

Every time

pass^k

Probability that all k attempts succeed. Falls with k. Right for customer-facing agents where every user must get it right. Introduced with τ-bench. With per-trial success p on a task: pass^k = pᵏ, averaged over tasks.

Live demo · pass@k vs pass^k

Set the average per-trial success rate and how much it varies between tasks. pass@k climbs toward 100%; pass^k falls. A 75% agent passes all of three trials only about 42% of the time.

pass@kpass^k
Deep dive

Statistics in practice

Clustering, multiple comparisons and variance reduction.

Paired comparisons are much more sensitive power

Most tasks pass (or fail) under both versions. Only the tasks that flip carry information about the difference. Comparing versions on the same tasks and analysing per-task differences (or McNemar's test on the flips) removes the task-difficulty noise. In practice paired analysis often needs 2–4× fewer tasks to detect the same change than comparing two independent averages.

Clustered standard errors correlation

If tasks come in groups (several questions about one document, several turns of one conversation, several trials of one task), they aren't independent, and the naive SE is too small. Compute SE at the cluster level (cluster-robust SE) or bootstrap by resampling whole clusters. Miller's paper shows clustered SEs can be several times larger than naive ones on popular benchmarks.

Multiple trials reduce variance sampling

Running k trials per task and averaging reduces the within-task noise part of the variance by a factor of k. It doesn't reduce between-task variance (some tasks are just hard), so beyond 3–5 trials, adding new tasks usually helps more than adding trials. For agents, 3–10 trials per task is common because per-trial variance is high.

Many metrics, many slices, false alarms multiple comparisons

With 20 slices × 5 metrics = 100 comparisons at 95% confidence, you expect about 5 "significant" changes by chance alone. Pre-register the primary metric for a release decision, treat slice-level changes as signals to investigate, and use corrections (Holm or Benjamini–Hochberg) when you must make many decisions at once.

Bootstrap: the all-purpose interval method

Resample tasks (or clusters) with replacement 1,000–10,000 times, recompute the metric each time, and take the 2.5th and 97.5th percentiles. It works for any metric (F1, nDCG, judge-corrected rates) without formulas, and it's a few lines with scipy.stats.bootstrap or NumPy.

Temperature and seeds settings

Evaluate at the sampling settings you use in production; a system evaluated at temperature 0 and served at 0.7 will behave differently. Even temperature 0 isn't fully deterministic on most hosted APIs. Record settings and, where supported, seeds, and treat remaining variance as part of what you're measuring.

Chapter 10Builder

Evaluating RAG systems

Key insight

Evaluate retrieval-augmented generation in parts. Retrieval: did the right chunks come back, and near the top (recall@k, MRR, nDCG)? Generation: is the answer faithful to those chunks and relevant to the question? End to end: is it correct? A wrong answer can come from either half, and the fix is completely different.

RAG systems fail in two places. If retrieval misses the right document, the best generator in the world can only guess. If retrieval succeeds but the model ignores or misreads the context, better search won't help. Measuring only the final answer tells you that something failed, not where. The companion RAG Guide covers building the pipeline; this chapter covers measuring it.

The RAG eval map: what to measure at each step

Questionuser query Retrieversearch + rerank Top-k chunksthe context GeneratorLLM + prompt Answer+ citations context relevance / precision@k faithfulness / groundedness answer relevance recall@k · MRR · nDCG need labelled relevant chunks correctness needs a reference answer
MetricMeasuresNeedsFormula / method
Hit rate / recall@kDid any (or what share of) relevant chunks appear in the top k?Labelled relevant chunk IDs|relevant ∩ top-k| / |relevant|
Precision@kHow much of the top k is relevant?Labels|relevant ∩ top-k| / k
MRRHow high is the first relevant result?Labelsmean of 1 / rank of first relevant
nDCG@kRanking quality with graded relevanceGraded labels (0–3)Σ (2^rel − 1)/log₂(i+1), divided by the ideal ordering's value
Context precision / recall (RAGAS)Relevant chunks ranked high / reference facts covered by contextReference answer (LLM-judged)LLM checks each chunk or each reference claim
Faithfulness / groundednessAre the answer's claims supported by the retrieved context?Context + answerSplit answer into claims; judge each as supported or not; supported / total
Answer relevanceDoes the answer address the question?Question + answerJudge, or similarity of questions regenerated from the answer
Answer correctnessIs it actually right?Reference answer or key factsReference-guided judge; fact recall
Citation accuracyDo citations point to chunks that support the sentence?Answer with citationsJudge per citation; code check that cited IDs exist
Abstention qualitySays "I don't know" when the answer isn't in the corpusUnanswerable test questionsPass if it abstains on unanswerables and answers the rest

Live demo · retrieval metrics by hand

The query is "What is the free cancellation window for basic fares?" Click results to mark them relevant (green). The grade shows how relevant each one is for nDCG. Change k and watch the metrics move.

    Deep dive

    RAG evaluation details

    Test sets, the triad and common traps.

    Building a RAG test set data
    • From real queries: sample production questions; have an expert mark which documents answer each one.
    • Synthetic: pick a chunk, have an LLM write a question it answers (RAGAS, LlamaIndex and DeepEval have generators); filter out questions that are too easy (verbatim copies) or unanswerable.
    • Multi-hop: include questions that need two or more documents.
    • Unanswerable: include 10–20% questions the corpus can't answer, to test abstention.
    • Time-sensitive: include questions where the answer changed between document versions.
    The RAG triad framework

    TruLens popularised three reference-free checks that can run online: context relevance (question ↔ context), groundedness (context ↔ answer) and answer relevance (answer ↔ question). If all three pass, the answer is probably fine even without a reference. They're LLM-judged, so align them with human labels like any judge.

    Faithful is not the same as correct trap

    An answer can be perfectly faithful to an outdated or wrong document. And an answer can be correct but unfaithful (the model knew the answer from training and ignored the context), which is a risk if the corpus contains company-specific facts that differ from public knowledge. Measure both, and test with documents that contradict common knowledge.

    Evaluate chunking, embeddings and rerankers separately components

    Retrieval metrics on a fixed labelled set let you compare chunk sizes, embedding models, hybrid search weights and rerankers quickly and cheaply, without running the generator. MTEB gives a general picture of embedding models, but your own retrieval set is what matters. See the RAG Guide for the full component list.

    Long context vs retrieval 2026

    With million-token context windows, some teams skip retrieval for small corpora. Evaluate both: "needle in a haystack" tests show models can find a single fact, but multi-fact reasoning over long contexts degrades, and cost per query is much higher. Your eval set decides, not the context window size.

    Chapter 11BuilderArchitect

    Evaluating agents

    Key insight

    Agents take many steps, use tools and change the world, so errors compound. Grade at three levels: the outcome (did the end state come out right?), the trajectory (were tool choices and arguments sensible, were rules followed?) and efficiency (turns, tokens, time, cost). Run several trials, report pass^k for reliability, and use isolated environments and simulated users.

    A chatbot eval looks at one response. An agent eval looks at a whole episode: maybe 10–50 model calls, several tool calls, intermediate results, and a final state in some system. Anthropic's guide stresses that evaluating "an agent" means evaluating the model and the harness together: the same model can score very differently with different tools, prompts and scaffolds. The Agents Guide covers building agents.

    LevelQuestionGradersExample
    OutcomeIs the world in the right state?State checks (DB, files, API), unit testsThe refund row exists, amount ≤ $100, status "approved"
    Final responseDid it tell the user the right thing?Judge, reference matchConfirmation message states the correct amount and date
    Trajectory constraintsDid it follow the rules on the way?Transcript code checks, judgeVerified identity before refunding; never called delete_account
    Tool useRight tools, valid arguments?Schema checks, tool-call match, judgesearch_flights called with ISO dates; no hallucinated tool names
    Step qualityWere individual decisions reasonable?Judge on selected stepsPlan was sensible; recovered from a tool error instead of repeating it
    EfficiencyAt what cost?CountersTurns, tool calls, tokens, latency, $ per task
    ReliabilityDoes it work every time?Repeated trialspass^k over 5 trials

    Trajectory matching modes

    When you compare an agent's tool calls to an expected sequence, how strict you are changes the score a lot. Strict matching punishes valid alternative paths; loose matching misses real mistakes. Common modes (used by LangChain's agentevals, Vertex AI, Bedrock and others):

    Live demo · grade one trajectory five ways

    Pick an actual trajectory for the task "Change my flight to Friday and tell me the fare difference". The expected path is on the left. See how each matching mode scores it, and why outcome grading matters.

    Expected
      Actual

        Agent types and how to grade them

        Coding agents

        Run the tests (including hidden ones), static analysis (lint, types, security scanners), and a judge for code quality and scope. Benchmarks: SWE-bench Pro, Terminal-Bench 2.0. Protect tests from edits.

        Conversational agents

        A second LLM simulates the user with a persona and goal; grade the end state, turn count and a tone/policy rubric. Benchmarks: τ-bench, τ²-bench (retail, airline, telecom).

        Research agents

        Groundedness (claims supported by cited sources), coverage (required facts present), source quality. Experts may disagree, so calibrate judges often. Benchmark: BrowseComp.

        Computer-use agents

        Run in sandboxed VMs or browsers; check URL, page and backend state (the order was actually placed). Benchmarks: OSWorld, WebArena.

        Deep dive

        Agent eval engineering

        Environments, user simulators, compounding and cost.

        Errors compound across steps math

        If each step succeeds with probability 0.95 and a task needs 20 independent steps with no recovery, the task succeeds 0.95²⁰ ≈ 36% of the time. Real agents recover from some errors, which is exactly why you should measure recovery: inject tool failures (timeouts, empty results, errors) and check that the agent retries sensibly or asks for help instead of looping or inventing results.

        Simulated users conversational

        A user-simulator LLM gets a hidden goal and persona ("you want to change to Friday; you only reveal your booking code if asked; you're impatient"). It talks to the agent until the goal is met or a turn limit is hit. Simulators can be unrealistic (too cooperative, too verbose), so validate them by comparing a sample of simulated conversations with real ones, and keep the simulator's model and prompt fixed across comparisons.

        Environments and sandboxes infra

        Each trial needs a fresh, realistic environment: a seeded database, mock APIs with deterministic responses, a container for code, a browser VM. Tools like Harbor (containerised agent runs; Terminal-Bench 2.0 ships through it), Inspect's sandboxing, and cloud agent runtimes help. Mock external services you don't control, but test against the real ones in a smaller suite too, because mocks drift.

        Grading long transcripts judges

        Judging a 100-step transcript in one prompt is unreliable. Instead: code-check the structured parts (tool names, arguments, order constraints), ask a judge targeted questions about specific steps ("at the point the search returned no results, did the agent ask the user or invent a flight?"), or summarise and then judge. Always keep the full transcript for humans to read.

        Cost and latency are quality metrics too efficiency

        Two agents with the same pass rate aren't equal if one takes 3 turns and $0.04 and the other takes 25 turns and $1.10. Report cost per successful task (total cost ÷ successes) and p50/p95 latency alongside pass rates. Efficiency regressions are common after prompt changes that add "be thorough" instructions.

        Chapter 12BuilderArchitect

        Safety, red-teaming and robustness

        Key insight

        Quality evals ask "does it work for normal users?" Safety evals ask "what happens when someone tries to break it, or when it meets something unusual?" Measure attack success rate on jailbreaks, prompt injection, data leakage and harmful content, and measure over-refusal too: a system that refuses everything is safe and useless.

        Red-teaming means attacking your own system on purpose, by hand and with automated tools, before real attackers or unlucky users do. For AI apps the attack surface includes every piece of text the model reads: user messages, retrieved documents, web pages, emails, tool results. Agents that can take actions raise the stakes from "said something bad" to "did something bad".

        RiskWhat to testMetricTypical tools / sets
        JailbreaksRole-play, encoding, many-shot, multi-turn escalation to bypass policiesAttack success rate (ASR)Promptfoo red team, PyRIT, garak, HarmBench
        Direct prompt injection"Ignore previous instructions…" in user inputASR; system prompt leakage ratePromptfoo, garak, custom suites
        Indirect prompt injectionInstructions hidden in retrieved docs, web pages, emails, tool outputASR on agent actionsAgentDojo, InjecAgent, custom canaries
        Data leakagePII, secrets, other users' data, system prompt in outputLeak rateRegex/PII detectors, canary tokens
        Harmful contentViolence, self-harm, hate, sexual, illegal adviceUnsafe response rate by categoryCloud content-safety evaluators, Llama Guard, HarmBench
        Over-refusalSafe requests that look risky ("how do I kill a Python process?")False refusal rateXSTest, OR-Bench, your own borderline set
        HallucinationMade-up facts, citations, tool resultsUnsupported claim rateGroundedness judges, SimpleQA-style sets
        Bias and fairnessDifferent quality or tone by name, gender, dialect, regionScore gap between counterfactual pairsCounterfactual templates, BBQ
        Excessive agencyAgent takes destructive or unapproved actionsUnsafe action rateSandboxed agent suites, policy checks on transcripts
        RobustnessTypos, paraphrases, other languages, long or weird inputsScore drop vs clean inputsMetamorphic / perturbation tests
        The lethal trifecta

        Simon Willison's warning for agents: if one system has private data, reads untrusted content, and can communicate externally, a prompt injection can exfiltrate data. Evals can measure how often attacks succeed, but no eval drives that number to zero. Break one leg of the trifecta by design, then test that the design holds.

        A red-team programme

        1. Threat modelList assets (data, actions, money), attackers (curious user, malicious user, poisoned document) and the worst outcomes. Use OWASP Top 10 for LLM Applications and MITRE ATLAS as checklists.
        2. Automated scanRun a generator of attacks across categories (Promptfoo, PyRIT, garak) against a staging endpoint. Grade with judges tuned for each harm category.
        3. Manual red-teamingHumans find creative multi-turn and domain-specific attacks that tools miss. Budget a few days before launch and after major changes.
        4. Turn findings into regression testsEvery successful attack becomes a test that must keep failing to work.
        5. Measure both sidesTrack ASR and false refusal rate together; a guardrail that cuts ASR by 5 points and doubles refusals may be a bad trade.
        6. Monitor in productionLog blocked and flagged requests, sample them for review, and watch for new attack patterns.
        Deep dive

        Safety evaluation details

        Metamorphic tests, frontier evals and regulation.

        Metamorphic and invariance testing robustness

        When you don't know the right answer, you can still know how answers should relate. Swapping a customer's name shouldn't change a loan explanation; adding a typo shouldn't change a classification; translating a question shouldn't change the facts in the answer. Generate pairs and check consistency. It's cheap, needs no labels, and finds bias and fragility.

        Frontier and dangerous-capability evals labs

        Model labs and government AI safety institutes run evaluations for dangerous capabilities (cyber offence, biological and chemical uplift, autonomous replication, deception) under frameworks like Anthropic's Responsible Scaling Policy, OpenAI's Preparedness Framework and Google DeepMind's Frontier Safety Framework. UK AISI's Inspect is widely used for these. App builders rarely run them, but model cards report them.

        Regulation and documented evaluation compliance

        The EU AI Act requires testing, risk management and documentation for high-risk systems. In 2026 the EU agreed (via the "digital omnibus") to postpone stand-alone high-risk obligations to December 2027, while some transparency duties kept their August 2026 date. Check the current legal text for your case. Either way, a versioned eval suite with stored results is the evidence auditors ask for. NIST's AI RMF and ISO/IEC 42001 point the same direction.

        Guardrails are not evals, but need evals runtime

        Guardrails (input and output classifiers, PII redaction, topic filters) act on each request at runtime. They're classifiers, so evaluate them like classifiers: precision and recall on labelled attack and benign sets, plus added latency. A guardrail with 95% recall and 10% false positives blocks one in ten legitimate users.

        Chapter 13FoundationsBuilder

        Public benchmarks and leaderboards

        How to read them

        Benchmarks compare models on public tasks. They're useful for a shortlist and for tracking the field, and weak for choosing a model for your product. Watch for saturation (everyone scores 90%+), contamination (answers in training data), scaffold differences (agent results depend on the harness) and missing error bars. Then test the shortlist on your own suite.

        Benchmarks have a life cycle: a hard new set appears, scores climb fast, models are (deliberately or not) trained on similar data, and within a couple of years the set is "saturated" and replaced. Stanford's 2026 AI Index reported that about half of the most-cited benchmarks are effectively saturated. In February 2026 OpenAI stopped reporting SWE-bench Verified after an audit suggested frontier models had seen its solutions; scores around 80% there corresponded to far lower scores on the harder SWE-bench Pro.

        BenchmarkMeasuresGraded byStatus (Oct 2026)
        MMLU / MMLU-ProBroad knowledge, multiple choice (57 subjects; Pro: 10 options, harder)Exact matchMMLU saturated Pro near saturation
        GPQA DiamondGraduate-level "Google-proof" science questionsExact matchNear saturation
        Humanity's Last Exam (HLE)~2,500 expert-written questions across fieldsExact match / judgeActive reported top scores roughly 40–60%, sources disagree
        AIME / FrontierMathCompetition and research-level mathsExact answerAIME mostly saturated; FrontierMath active
        HumanEval / MBPPShort Python functionsUnit tests (pass@k)Saturated
        LiveCodeBenchRecent contest problems, refreshed to avoid contaminationUnit testsActive
        SWE-bench VerifiedReal GitHub issues, human-validated subsetRepo testsContaminated treat with caution
        SWE-bench ProHarder, contamination-resistant software tasksRepo testsActive
        Terminal-Bench 2.0End-to-end terminal tasks in containersTests on final stateActive
        τ-bench / τ²-benchTool-using customer-service agents with simulated usersDB state, pass^kActive
        BFCLFunction / tool calling accuracyAST and execution checksActive
        BrowseCompFinding hard-to-locate facts on the webExact answerActive
        OSWorld / WebArenaComputer and browser useEnvironment stateActive
        ARC-AGI-2Novel abstract reasoning puzzlesExact grid matchActive
        IFEvalFollowing verifiable formatting instructionsCode checksNear saturation
        SimpleQAShort factual questions; hallucination tendencyJudge vs referenceActive
        MTEBEmbedding models across retrieval and other tasksTask metrics (nDCG etc.)Active; check retrieval subsets
        LMArena (Chatbot Arena)Crowd pairwise preferencesBradley–Terry / EloActive; style and sampling concerns (below)
        HELMMany metrics across scenariosMixedActive; good for multi-metric views
        Scores change monthly

        Benchmark status and top scores above are approximate and move fast. Check the official leaderboard or the paper for current numbers, and look at the date and the harness used for any score you quote.

        Reading a benchmark claim critically

        Which harness?

        Agent scores depend on tools, prompts, retries and time limits. Two "SWE-bench" numbers from different scaffolds aren't comparable.

        How many runs?

        A single run on 500 tasks has an interval of about ±4 points at 50%. Differences of 1–2 points are noise without error bars.

        Contamination?

        Was the set public before the model's training cutoff? Refreshed sets (LiveCodeBench) and private holdouts resist this.

        Saturated?

        If the top models all score 90%+, remaining differences are mostly label noise and ambiguous questions.

        Relevant?

        Does the task look like yours? A maths olympiad score says little about summarising insurance claims.

        Cost included?

        Some results use huge compute per task (many samples, long reasoning). Look for cost per task alongside the score.

        Deep dive

        Benchmark mechanics

        Running them yourself, arenas and Goodhart's law.

        Running benchmarks yourself tools

        EleutherAI's lm-evaluation-harness and Hugging Face lighteval run hundreds of standard tasks against open and API models. UK AISI's Inspect has a large library of community evals (inspect_evals) including agentic ones. HELM provides a full framework with many metrics. Running a few relevant benchmarks yourself on your candidate models, with your settings, is more trustworthy than quoted numbers.

        Arena leaderboards: useful, with caveats preference

        Crowd preference arenas measure what people like in chat, which correlates with but isn't the same as correctness. Known concerns: style (length, formatting) affects votes, so LMArena added style-controlled rankings; and the 2025 "Leaderboard Illusion" paper argued that private testing of many variants by some providers skews rankings. Use arenas as one signal of general chat quality.

        Goodhart's law principle

        "When a measure becomes a target, it ceases to be a good measure." It applies to benchmarks (labs optimise for them) and to your own suite (teams tune prompts until the score is high). The defence is the same: refresh tasks, keep holdouts, use several independent metrics, and keep reading outputs.

        From benchmarks to your own model selection practice
        1. Shortlist 3–5 models using benchmarks relevant to your task type plus price and latency.
        2. Run your full offline suite on each, with several trials and error bars.
        3. Compare cost per successful task and p95 latency, not just pass rate.
        4. Shadow-test the winner on production traffic with online evaluators before switching.
        Chapter 14FoundationsBuilder

        Types of evals, in one place

        Explorer

        Twenty-four eval types across seven families: deterministic, model-graded, human, RAG, agent, safety and production. Filter by family, search, and compare signal quality, latency, cost and complexity. Each entry says how it works, when to use it, and how to build it.

        Chapter 15Builder

        Tools, platforms and frameworks

        Pick by workflow

        Eval tools fall into four groups: open-source frameworks you run in code (Promptfoo, DeepEval, RAGAS, Inspect), observability + eval platforms (Braintrust, LangSmith, Langfuse, Phoenix), cloud eval services (Microsoft Foundry, Amazon Bedrock, Vertex AI) and red-team tools (PyRIT, garak). The tool matters less than your tasks; choose the one your team will actually use every day.

        ToolTypeStrengthConsider when
        PromptfooOpen-source CLI, YAML configFast prompt/model comparisons, CI-friendly, strong red-teamingYou want a quick CI gate and red-team scans. OpenAI announced its acquisition in March 2026; it says the open-source project continues
        DeepEvalOpen-source Python, pytest-styleMany ready metrics (G-Eval, RAG, agent), test-like workflowYour team lives in pytest; mind judge cost per metric
        RAGASOpen-source PythonRAG metrics, test-set generationEvaluating retrieval and grounding
        Inspect (UK AISI)Open-source Python frameworkAgent evals with sandboxes, large eval library, used by safety institutesAgentic or safety evals; rigorous research-style runs
        OpenAI Evals / Evals APIOpen-source + hostedGraders tied to OpenAI models and fine-tuningYou're on the OpenAI platform
        lm-eval-harness · lighteval · HELMOpen-source benchmark runnersStandard academic benchmarks at scaleComparing base or open models
        MLflow (GenAI evaluate)Open-source platformEval runs tracked with experiments and modelsYou already use MLflow / Databricks
        BraintrustHosted platform (SaaS)Experiments, datasets, scorers (autoevals), online scoring, release gatingYou want one managed eval workflow from dev to production
        LangSmithHosted platformTracing, datasets, offline/online evals, annotation queuesYou build on LangChain / LangGraph
        LangfuseOpen-source, self-hostable platformTracing, prompt management, evals, annotationYou need self-hosting or open source
        Arize Phoenix / AXSource-available (Phoenix) + SaaS (AX)OpenTelemetry-native tracing, evals, driftOTel-first observability
        W&B Weave · Opik (Comet) · Galileo · Patronus · HoneyHive · Confident AIPlatformsVaried: tracing, judges, hallucination models, dashboardsCompare against your workflow; many have free tiers
        Microsoft Foundry evaluationsCloud service + SDKBuilt-in quality, safety and agent evaluators (task adherence, intent resolution, tool-call accuracy), red-teaming agentYou deploy on Azure
        Amazon Bedrock evaluations · AgentCore EvaluationsCloud serviceModel and RAG evaluation jobs; built-in LLM-judge evaluators for agents (session, trace and tool level), online and on-demandYou deploy on AWS
        Vertex AI Gen AI evaluation serviceCloud service + SDKAdaptive rubrics, agent metrics (tool use quality, hallucination), pairwiseYou deploy on Google Cloud
        PyRIT · garakOpen-source red-teamAutomated attack generation (Microsoft, NVIDIA)Security testing (Ch)
        Verify before choosing

        Pricing, licences, feature status (preview vs GA) and even company ownership changed repeatedly in 2025–2026. Treat this table as a map and confirm details on each vendor's site.

        How to choose

        CriterionQuestions to ask
        Trace viewingCan a domain expert read one of our traces comfortably, including tool calls and retrieved docs?
        Custom gradersCan we write our own code graders and judges easily, or are we pushed to generic metrics?
        DatasetsVersioning, slices, adding production traces to datasets in one click?
        ExperimentsSide-by-side diffs of two runs per task, with confidence intervals?
        CI integrationCLI or API to run a suite and fail a build on thresholds?
        Online evalsSample production traces and run the same graders? Alerts?
        Data controlSelf-hosting, region, retention, PII redaction, SSO?
        Lock-inOpenTelemetry support; export of traces, datasets and results?
        CostPer seat, per trace, per judge call? What does 1M traces a month cost?
        Deep dive

        Tooling patterns

        Combinations that work in practice.

        Common stacks patterns
        • Small team, fast start: spreadsheet + custom trace viewer for error analysis → Promptfoo or DeepEval in CI → Langfuse for tracing.
        • Managed: Braintrust or LangSmith for traces, datasets, experiments and online scoring.
        • Cloud-native: your cloud's tracing + its eval service, plus an open-source framework for custom graders.
        • Agent/safety research: Inspect with sandboxes; Harbor for containerised agent runs.
        Build vs buy decision

        The core of an eval harness is small (a few hundred lines: load tasks, run, grade, aggregate, store). What's expensive to build is the surrounding product: trace viewers, dataset management, annotation queues, dashboards, online sampling. Many teams build the harness and graders themselves (they're product-specific anyway) and buy or self-host the observability layer.

        OpenTelemetry for GenAI standards

        The OpenTelemetry GenAI semantic conventions define standard span attributes for model calls, tool calls and agents (model name, token counts, operation names). Instrumenting with OTel (directly or via OpenLLMetry / OpenInference) lets you switch observability back ends without re-instrumenting, and keeps eval results attachable to standard traces. The conventions are still evolving; check the current spec.

        Chapter 16Builder

        Build an eval suite end to end

        Walkthrough

        We build evals for a travel-support assistant (RAG + tools) in nine steps: collect traces, error analysis, dataset, code graders, a calibrated LLM judge, a runner with trials and caching, a report with confidence intervals, a CI gate, and online sampling. Every step is plain Python you can adapt.

        1. Collect tracesLog every request with input, retrieved chunks, tool calls, output, model, prompt version, latency and cost. Pull 100 recent traces.
        2. Error analysisOpen-code and axial-code them (Ch). Our top modes: wrong policy deadline (14%), invented flight details (9%), missed identity check before changes (6%), JSON tool-arg errors (5%).
        3. DatasetTurn failing and representative traces into 220 tasks with slices, must/must-not facts and expected tool calls (Ch).
        4. Code gradersTool-argument schema, identity-check-before-change order, must-not phrases, citation IDs exist.
        5. LLM judgeOne binary judge for policy faithfulness, aligned on 150 expert labels: TPR 94%, TNR 88% on the test split.
        6. Runner3 trials per task, parallel, cached by (task, system version, trial).
        7. ReportPass rate per grader and slice with CIs; paired comparison with baseline.
        8. CI gateBlock merges on regression-suite drops beyond noise.
        9. OnlineSample 5% of production traces, run the same graders, alert on drift, feed failures back to step 2.

        Step 4 · Code graders

        python · graders.py
        from pydantic import BaseModel, ValidationError
        from datetime import date
        
        class SearchArgs(BaseModel):
            origin: str; destination: str; date: date      # ISO date enforced
        
        def tool_args_valid(task, out):
            for call in out["tool_calls"]:
                if call["name"] == "search_flights":
                    try: SearchArgs(**call["args"])
                    except ValidationError: return 0
            return 1
        
        def identity_before_change(task, out):
            names = [c["name"] for c in out["tool_calls"]]
            if "change_booking" not in names: return 1             # rule doesn't apply
            return int("verify_identity" in names[:names.index("change_booking")])
        
        def must_not_phrases(task, out):
            text = out["final"].lower()
            return int(not any(p.lower() in text for p in task["expected"].get("must_not", [])))
        
        def citations_exist(task, out):
            ids = {c["id"] for c in out["retrieved"]}
            return int(all(cid in ids for cid in out.get("citations", [])))

        Step 5 · The judge, with structured output

        python · judge.py
        import json, hashlib, anthropic
        client = anthropic.Anthropic()
        JUDGE_MODEL = "claude-haiku-5-5"          # pin a version; re-align if you change it
        PROMPT = open("prompts/policy_faithful_v3.txt").read()
        
        def policy_faithful(task, out, cache={}):
            ctx = "\n\n".join(c["text"] for c in out["retrieved"])
            msg = PROMPT.format(context=ctx, output=out["final"])
            key = hashlib.sha256((JUDGE_MODEL + msg).encode()).hexdigest()
            if key not in cache:
                r = client.messages.create(model=JUDGE_MODEL, max_tokens=400, temperature=0,
                                           messages=[{"role": "user", "content": msg}])
                cache[key] = json.loads(r.content[0].text)          # {"reasoning", "verdict"}
            v = cache[key]["verdict"]
            return None if v == "UNKNOWN" else int(v == "PASS")    # None = route to human

        Model IDs change; use your provider's current judge model and structured-output feature. The same pattern works with any LLM API.

        Step 5b · Measure the judge against expert labels

        python · align_judge.py
        def agreement(labels, preds):          # labels/preds: lists of 0/1 on the TEST split
            tp = sum(l == p == 1 for l, p in zip(labels, preds)); fn = sum(l == 1 and p == 0 for l, p in zip(labels, preds))
            tn = sum(l == p == 0 for l, p in zip(labels, preds)); fp = sum(l == 0 and p == 1 for l, p in zip(labels, preds))
            return {"TPR": tp / (tp + fn), "TNR": tn / (tn + fp), "n_fail": tn + fp}
        
        def corrected_rate(p_obs, tpr, tnr):     # Rogan-Gladen
            return min(1, max(0, (p_obs + tnr - 1) / (tpr + tnr - 1)))

        Step 7 · A paired report with confidence intervals

        python · report.py
        import numpy as np, pandas as pd
        
        def paired_diff(base: pd.DataFrame, cand: pd.DataFrame, metric: str, B=5000, seed=0):
            # average trials per task first, so tasks (not trials) are the unit
            a = base.groupby("id")[metric].mean(); b = cand.groupby("id")[metric].mean()
            d = (b - a).dropna().to_numpy()
            rng = np.random.default_rng(seed)
            boots = [rng.choice(d, len(d)).mean() for _ in range(B)]
            lo, hi = np.percentile(boots, [2.5, 97.5])
            return {"diff": d.mean(), "ci": (lo, hi), "significant": lo > 0 or hi < 0}
        
        for m in ["policy_faithful", "identity_before_change", "tool_args_valid"]:
            for sl, g in cand.explode("slice").groupby("slice"):
                r = paired_diff(base[base.id.isin(g.id)], g, m)
                print(f"{m:24} {sl:12} {r['diff']:+.1%}  [{r['ci'][0]:+.1%}, {r['ci'][1]:+.1%}]")

        What the report should show

        GraderBaselineCandidatePaired diff [95% CI]Verdict
        policy_faithful (corrected)81.2%88.9%+7.7 [+4.1, +11.2]Improved
        identity_before_change97.0%96.4%−0.6 [−2.3, +1.1]No change
        tool_args_valid94.5%99.1%+4.6 [+2.2, +7.0]Improved
        refund slice · policy_faithful78.0%70.5%−7.5 [−14.0, −1.0]Regressed: investigate
        Cost per task$0.021$0.026+24%Check budget

        Illustrative numbers. Note the overall win hiding a regression on one slice: exactly what slice reports exist to catch.

        Deep dive

        Harness engineering details

        Speed, caching and reproducibility.

        Caching and incremental runs speed

        Cache system outputs by (task ID, system version hash, trial number) and judge verdicts by (judge model, judge prompt version, input hash). Changing only a grader then re-grades stored outputs in seconds instead of re-running the system. Changing the prompt re-runs only the system calls.

        Rate limits and concurrency ops

        Use a bounded worker pool with exponential backoff on 429s. Batch APIs (typically ~50% cheaper, results within 24 hours) suit nightly full runs. Separate API keys or projects for evals keep eval traffic from starving production.

        Store raw rows, not just scores data

        Keep one row per (task, trial, grader) with the transcript reference, verdict and judge reasoning. You'll want to re-slice, re-grade and audit later. Parquet files or a small database table are enough at first.

        Chapter 17BuilderArchitect

        Evals in CI/CD and release gates

        Key insight

        Treat prompts, models and retrieval settings like code: every change runs evals before it ships. Use tiers (a fast smoke suite on every PR, the full suite nightly, holdouts before releases), gates that are noise-aware (block on statistically real drops, not on any drop), and a written model-upgrade playbook.

        An eval-gated release pipeline

        Pull requestprompt / model change Smoke suite50–150 tasks · <10 min Full suitenightly · all slices Release suiteholdout · safety · human Canary + online5% traffic · watch scores any gate fails → back to the developer with failing examples

        Designing the gate

        Gate typeRuleUse for
        Hard thresholdPass rate ≥ 99% on must-never-break tasksRegression suite, safety-critical checks
        Non-inferiorityLower CI bound of (candidate − baseline) > −2 pointsMost quality metrics: "not meaningfully worse"
        SuperiorityLower CI bound of difference > 0Changes justified by an improvement claim
        Slice guardNo slice drops by more than X with significanceCatching hidden regressions
        Budget guardCost per task and p95 latency within limitsPreventing silent cost creep
        Human sign-offExpert reviews diff of 30 changed outputsReleases in high-stakes domains
        yaml · .github/workflows/evals.yml
        name: evals
        on:
          pull_request:
            paths: ["prompts/**", "src/agent/**", "config/models.yaml", "evals/**"]
        jobs:
          smoke:
            runs-on: ubuntu-latest
            timeout-minutes: 20
            steps:
              - uses: actions/checkout@v4
              - run: pip install -r evals/requirements.txt
              - name: Run smoke suite against PR and main
                env: { ANTHROPIC_API_KEY: "${{ secrets.EVAL_API_KEY }}" }
                run: |
                  python evals/run.py --suite smoke --version pr   --trials 3 --out pr.parquet
                  python evals/run.py --suite smoke --version main --trials 3 --out main.parquet --cached
              - name: Gate (non-inferiority, slice guard, budget)
                run: python evals/gate.py main.parquet pr.parquet --margin 0.02 --max-cost-increase 0.15
              - name: Post report to PR
                if: always()
                run: python evals/comment.py report.md

        Model-upgrade playbook

        1. Run the full suiteNew model vs current, same prompts, 3+ trials, all slices. Many prompts are tuned to the old model; expect some slices to drop.
        2. Read diffsLook at tasks that flipped in either direction. Judge-flagged improvements should be confirmed by a human sample.
        3. Adjust promptsFix regressions, re-run, check the holdout to confirm you haven't overfit.
        4. Re-align judgesIf the judge model changes too, re-measure TPR/TNR first. Never change the system and the judge in the same comparison.
        5. Shadow and canaryRun the new model on a copy of live traffic (shadow) or a small share (canary) with online evaluators, then roll out.
        Deep dive

        CI in practice

        Flakiness, speed and A/B tests.

        Flaky evals kill trust stability

        If the gate fails randomly, developers learn to re-run until green, and the gate stops meaning anything. Use multiple trials, noise-aware rules, cached baselines from the same day, and quarantine tasks whose pass rate wobbles across identical runs. Track the gate's false-alarm rate like any other metric.

        Eval-driven development workflow

        Like test-driven development: before building a feature, write the eval tasks that define it (they'll fail at first), then iterate until they pass. Anthropic describes teams writing capability evals before models can pass them, so they know immediately when a new model unlocks the feature.

        When offline evals aren't enough: A/B tests online

        Offline suites predict quality; A/B tests measure impact on users (task completion, retention, escalation rate, revenue). Run A/B tests for changes that offline evals can't settle (tone, UX, proactive suggestions). Pre-register the primary metric and duration, and watch guardrail metrics (complaints, safety flags).

        Prompt and config versioning hygiene

        Store prompts in the repo (or a prompt registry with immutable versions), reference them by version in code, and log the version on every trace. Then every online score can be tied to the exact prompt and model that produced it, and rollbacks are one config change.

        Chapter 18ArchitectBuilder

        Online evaluation and production monitoring

        Key insight

        Offline evals tell you a version was good when you shipped it. Online evals tell you it's still good today, on inputs you never imagined. Trace everything, run reference-free graders on a sample of live traffic, combine them with user signals, alert on drift, and pipe failures back into your datasets.

        Production is where eval sets go to learn humility. Users phrase things differently, ask for features you didn't build, paste giant documents, switch languages mid-conversation, and try to break things. Providers update models. Your documents change. Online evaluation closes the loop: it's the "traces" box at the top of the flywheel.

        SignalExamplesStrengthWeakness
        Online gradersCode checks and judges on sampled traces (groundedness, policy, format)Consistent with offline suiteReference-free only; judge cost
        Explicit feedbackThumbs up/down, ratings, commentsDirect user voiceRare (often <1–2% of sessions), biased to extremes
        Implicit feedbackRegenerate, copy, edit, abandon, rephrase, escalate to human, follow-up "that's wrong"PlentifulAmbiguous; needs validation against labels
        Business outcomesResolution rate, conversion, ticket deflection, retentionWhat actually mattersSlow, noisy, many causes
        OperationalLatency, errors, token usage, cost, tool failure rateCheap, immediateNot quality
        Guardrail eventsBlocked inputs/outputs, PII redactions, refusalsSafety visibilityClassifier errors both ways

        Sampling strategy

        Random sample

        1–10% of traffic for unbiased trend lines. The only way to estimate true production pass rates.

        Targeted sample

        All thumbs-down, escalations, long conversations, new features, high-risk slices. Finds failures faster but is biased; don't report it as the overall rate.

        Stratified sample

        Fixed quotas per slice so small but important slices (premium users, rare languages) get enough judged traces.

        Drift: what changes, and how to notice

        Drift typeExampleDetect with
        Input driftNew product launch brings a new kind of questionEmbedding clusters over time; topic classifier shares; "unknown intent" rate
        Output / quality driftGroundedness pass rate slides from 93% to 87% over two weeksControl charts on online grader rates with CI bands
        Model driftProvider updates a model alias; behaviour shiftsPin versions; daily canary suite on the live endpoint
        Data driftPolicy documents updated; index staleFreshness checks; RAG retrieval metrics on a fixed probe set
        Judge driftJudge model changed; scores jump overnightWeekly human spot-check of judge verdicts; pinned judge versions
        Deep dive

        Running online evals

        Alerting, privacy, feedback loops.

        Alerting without alert fatigue ops

        Alert on sustained, significant changes: e.g. the 24-hour pass rate's lower confidence bound falls below the 30-day baseline's lower bound, for two consecutive windows. Page only for safety and hard-failure signals; send quality drift to a daily digest with example traces attached.

        Async vs inline evaluation latency

        Online evals run asynchronously after the response is sent, so they add no user latency. If you need to act on a verdict before the user sees the answer, it's a guardrail: it must be fast (small classifier or code check, tens of milliseconds to a few hundred) and you pay its latency on every request.

        Privacy in production evaluation compliance

        Sending user conversations to a judge model is data processing. Check your privacy policy and data agreements, redact PII before judging where possible, prefer judges in the same cloud and region, set retention for stored traces and verdicts, and give annotators only what they need.

        Closing the loop flywheel

        Every week: review a sample of online failures, add new failure modes to the taxonomy, add representative traces to the offline dataset (redacted), and add regression tests for anything you fixed. This is how the offline suite stays representative.

        Chapter 19BuilderArchitect

        Fine-tuning LLMs, measured

        Key insight

        Fine-tuning changes a model's weights using your examples. It's the right tool for behaviour (format, style, a narrow skill, a smaller cheaper model that matches a big one) and the wrong tool for knowledge (facts that change belong in RAG). Fine-tune only when your evals show prompting and retrieval have plateaued, use LoRA/QLoRA first, and judge the result on the same eval suite plus a regression and safety check, because fine-tuning can quietly break things the base model did well.

        A base model learns general language from trillions of tokens. Fine-tuning continues training on a much smaller set of your examples (hundreds to tens of thousands) so the model behaves the way you need without long prompts. It used to be the first thing teams reached for. Today, strong instruction-following models, long context and RAG solve most problems with prompting alone, which is why OpenAI announced in May 2026 that it is winding down its self-serve fine-tuning service, citing exactly that. Fine-tuning remains valuable in specific cases, especially with open-weight models you run yourself (Ch).

        The link to the rest of this guide is direct: you can't fine-tune well without evals. Your eval suite decides whether fine-tuning is needed, which training data to build (from the failure modes you found in error analysis), when to stop training, and whether the new model is safe to ship.

        Should you fine-tune? Decide with your evals

        1. Is the failure about knowledge or behaviour?Missing or changing facts (prices, policies, documents) → RAG (Ch). Wrong format, tone, reasoning style, or a narrow task done inconsistently → fine-tuning may help.
        2. Have you pushed prompting?Clear instructions, few-shot examples, structured outputs, a better model. If your eval pass rate is still climbing with prompt changes, keep going: it's cheaper and reversible.
        3. Do you have the data?At least a few hundred high-quality examples of the exact behaviour (often 500–5,000 for SFT), plus a held-out eval set you will never train on.
        4. Is there a payoff you can measure?Higher pass rate on a plateaued failure mode, or the same pass rate from a smaller model at a fraction of the cost and latency. Write the target down before training.
        5. Can you own the result?Fine-tuned models must be re-trained when the base model is retired, hosted somewhere (often at a premium on managed clouds), and re-evaluated on every change. Budget for that.
        Problem your evals showBest first fixFine-tune?
        Answers miss company facts or use outdated infoRAG, better retrievalNo facts in weights go stale and can't be cited
        Output format breaks 3% of the timeStructured outputs / constrained decodingRarely
        Tone or style inconsistent despite good promptsFew-shot examples, style guide in promptYes SFT on approved examples
        Narrow classification / extraction at high volumePrompted large modelYes fine-tune a small model to match it (distillation)
        Domain jargon (medical, legal, internal codes) misunderstoodGlossary in contextMaybe SFT, or continued pre-training on domain text
        Model picks the wrong tool or reasons poorly on a checkable taskBetter tool descriptions, examplesYes reinforcement fine-tuning with a grader
        Data can't leave your network and API models are bannedSelf-hosted open-weight model (Ch)Maybe fine-tune the open model to close the quality gap

        The fine-tuning methods

        MethodWhat it doesDataUse for
        Supervised fine-tuning (SFT)Train on input → ideal output pairs500–50k examplesFormat, style, narrow tasks, distillation
        Full fine-tuningUpdate every weightLarge, clean setsMaximum change; big budgets; usually unnecessary
        LoRA (low-rank adaptation)Freeze the model; train small adapter matrices (~0.1–1% of parameters)Same as SFTThe default: cheap, fast, swappable adapters
        QLoRALoRA on a 4-bit quantised base modelSame as SFTLarge models on limited GPU memory
        DPO / preference tuningTrain on pairs of (preferred, rejected) responses1k–10k pairsTone, helpfulness, "prefer this over that"
        Reinforcement fine-tuning (RFT, GRPO)Model generates attempts; a grader scores them; training rewards high scoresHundreds of tasks + a reliable graderReasoning and tool use on checkable tasks
        DistillationTrain a small model on outputs of a large oneThousands of large-model outputsSame quality, much lower cost and latency
        Continued pre-trainingKeep training on raw domain textMillions+ tokensVery specialised vocabularies; rarely needed
        Reinforcement fine-tuning is evaluation turned into training

        In RFT the reward is a grader: unit tests, a schema check, or an aligned LLM judge. Everything in Ch and Ch applies, with higher stakes: the model will find every weakness in your grader (reward hacking). Only use graders you'd trust as a release gate, and evaluate the trained model with different held-out graders.

        The training data is the product

        Build it from error analysis

        Your failure taxonomy (Ch) says what to teach. Collect or write ideal outputs for those failure modes, plus enough normal cases that the model doesn't forget them.

        Quality over quantity

        A few hundred expert-checked examples usually beat thousands of noisy ones. One wrong pattern repeated in training data is learned faithfully. Have a domain expert review a sample of every batch.

        Keep eval data out

        Deduplicate training data against every eval and holdout set (exact and near-duplicate). Leakage makes the fine-tuned model look far better than it is.

        Match production

        Use the same system prompt, tools and message format the model will see in production. A mismatch between training and serving format is a common silent failure.

        jsonl · chat-format SFT example
        {"messages": [
          {"role": "system", "content": "You are the claims triage assistant. Reply in the CLAIM-v2 JSON schema."},
          {"role": "user", "content": "Water came through the ceiling after the storm on 3 Oct, kitchen damaged."},
          {"role": "assistant", "content": "{\"category\":\"property/water\",\"cause\":\"storm\",\"severity\":\"medium\",\"needs_adjuster\":true,\"date\":\"2026-10-03\"}"}
        ]}

        Live demo · fine-tuning memory, time and cost

        Pick a model size and method. The estimate shows GPU memory, how many GPUs you need, training time and cost. Rough rules of thumb (gradient checkpointing on, illustrative cloud GPU prices); real numbers depend on framework, sequence packing and hardware.

        Model weightsGradients + optimiserActivations
        Full fine-tune ≈ 16 bytes per parameter (2 weights + 2 gradients + 12 FP32 optimiser and master copies) + activations
        LoRA ≈ 2 bytes per base parameter + 16 bytes per trainable adapter parameter + activations · QLoRA ≈ 0.55 bytes per base parameter + adapters + activations
        Training compute ≈ 6 × params × tokens (full) or ≈ 4 × params × tokens (LoRA, no weight gradients); hours = FLOPs ÷ (effective GPU FLOP/s × GPUs)

        Evaluating a fine-tuned model

        CheckWhyHow
        Target eval (held out)Did it fix what you trained for?Same suite and graders as before; paired comparison vs base + best prompt (Ch)
        Regression suiteDid it break what used to work?Full product regression suite, all slices
        General capabilityCatastrophic forgetting: losing general skillsA small set of general tasks (reasoning, instruction following, maths, your other features)
        Safety and refusalFine-tuning can erode safety trainingRed-team and over-refusal suites (Ch) before and after
        Overfitting during trainingMemorising examples instead of learning the patternValidation loss and a small eval run at each checkpoint; pick the best checkpoint by eval, not loss
        Cost and latencyWas the goal a cheaper model?Cost per successful task, p95 latency on the serving stack
        Fine-tuning can remove safety behaviour, even by accident

        Qi et al. (2023) showed that fine-tuning an aligned model on as few as 10 adversarial examples removed much of its safety behaviour, and that even benign fine-tuning data reduced it. 2025–2026 research on "emergent misalignment" found that narrow fine-tuning (for example on insecure code) can cause broad misbehaviour on unrelated prompts. Always run safety evals after fine-tuning, and treat fine-tuning data like code that needs review.

        Deep dive

        Fine-tuning in practice

        Hyperparameters, managed services and lifecycle.

        Starting hyperparameters for LoRA settings
        Rank r
        8–64. Higher rank = more capacity and more risk of overfitting. Start at 16.
        Alpha
        Often 1–2 × rank.
        Target modules
        All attention and MLP projections usually beat attention-only.
        Learning rate
        1e-4 to 2e-4 for LoRA; 1e-5 to 2e-5 for full fine-tuning.
        Epochs
        1–3. More epochs on small data memorise it; watch eval scores per checkpoint.
        Sequence packing
        Pack short examples together to use GPU time efficiently.
        Managed fine-tuning services in late 2026 fast-changing
        • OpenAI: announced in May 2026 that self-serve fine-tuning is winding down: closed to new users, with existing customers able to create jobs only for a limited time (reported until early January 2027). Existing fine-tuned models keep serving until their base models are retired.
        • Microsoft Foundry: SFT, DPO and RFT for supported OpenAI and open models; serverless and managed-compute options.
        • Amazon Bedrock: custom model fine-tuning, distillation, and reinforcement fine-tuning (extended to open-weight models such as Qwen3 and gpt-oss in 2026) with rule-based or AI-judge rewards.
        • Google Vertex AI: supervised and preference tuning for Gemini and open models; tunable model versions rotate as models retire.
        • Open-weight hosts: Together AI, Fireworks, and others offer LoRA training and serving.

        Supported models, prices and limits change often. Confirm in each provider's docs before planning around one.

        Fine-tuned models have a lifecycle ops

        When the base model is retired or a better one ships, you re-run the whole pipeline: retrain on the new base, re-evaluate, re-deploy. Keep training data, configs and eval results versioned so this is a routine job, not an archaeology project. Compare each retrained model with the new base model + prompting: sometimes the new base no longer needs fine-tuning.

        LoRA adapters: many tasks, one base architecture

        Adapters are small (megabytes to a few hundred MB). Serving stacks like vLLM can load many LoRA adapters on one base model and choose per request, so you can run separate fine-tunes per task or per customer without separate GPUs. Evaluate each adapter separately; they don't share quality.

        Data privacy in fine-tuning security

        Models can memorise and repeat training examples, especially rare strings (names, account numbers, keys). Remove or pseudonymise personal data before training, deduplicate, and test for memorisation by prompting with prefixes of training examples. If training data is sensitive, train inside your own environment on an open-weight model (Ch).

        Chapter 20BuilderArchitect

        Local and private deployment for data and security

        Key insight

        When data can't leave your control, you have a spectrum of options: an API with zero data retention, a private cloud endpoint in your own network and region, or self-hosted open-weight models in your cloud, on-premises or fully air-gapped. Self-hosting gives maximum control and makes you responsible for security, capacity and quality. Size hardware from weights + KV cache, harden the serving stack (never expose it unauthenticated), and run your full eval suite on the exact model and quantisation you deploy.

        Teams in healthcare, finance, government, defence and legal work often can't send prompts containing patient records, trading data, classified material or privileged documents to a third-party API, or can only do so under strict contracts and regions. Open-weight models (downloadable weights from Meta, Alibaba's Qwen team, Mistral, Google's Gemma, DeepSeek, OpenAI's gpt-oss and others) now come close to frontier API models on many tasks, which makes private deployment practical. "Close" is a claim your evals must check for your task.

        The deployment spectrum: control vs convenience

        Public APIdefault termsfastest start API + ZDRzero retention,DPA, region Private endpointAzure / Bedrock /Vertex in your VPC Self-host, cloudopen weights onyour GPUs (vLLM) On-premisesyour data centreyour hardware Air-gappedno network at all;laptop or enclave → more control over data, models and versions; more security and ops work for you frontier models, managed scaling, provider handles security of the model service
        OptionData leaves your control?Model qualityYou manageTypical fit
        Public API, default termsYes; retained for a period for abuse monitoringFrontierNothingNon-sensitive data
        API with zero data retention (ZDR) and a data processing agreementProcessed by provider, not storedFrontierContracts, redactionMost business data, with legal sign-off
        Private cloud endpoint (Azure OpenAI / Foundry, Amazon Bedrock, Vertex AI) with private networkingStays in your cloud tenant and chosen regionFrontier + open modelsNetwork, identity, region choiceRegulated industries already in that cloud
        Self-hosted open weights in your cloudNoOpen-weight (close to frontier on many tasks)GPUs, serving, scaling, security, upgradesStrict residency, custom fine-tunes, very high volume
        On-premisesNoOpen-weightEverything, including hardwareData-centre-bound or sovereign requirements
        Air-gappedNo network path at allOpen-weight, often smallerEverything, plus offline update processDefence, classified, critical infrastructure
        Check whether you really need self-hosting

        Many "data can't leave" requirements are satisfied by a private cloud endpoint in your region with no data retention and no training on your data, which keeps frontier models and removes GPU operations. Self-host when policy forbids any third-party processing, when you need full control of model versions, when you need a custom fine-tune you can't host elsewhere, or when volume makes it cheaper. Get the requirement in writing from security and legal first.

        Choosing an open-weight model

        ConsiderWhy it matters
        Your eval resultsThe only reliable signal. Run your suite on 3–5 candidates at the quantisation you'll deploy (Ch).
        Size and architectureDense models (all parameters used per token) vs mixture-of-experts (MoE: large total size, fewer "active" parameters per token, so faster, but all weights must still fit in memory).
        LicenceApache 2.0 and MIT are permissive; some community licences restrict use by size of company, region or purpose. Have legal review before production.
        Context length and tool useCheck real performance at your context lengths and with your tool-calling format, not just the advertised maximum.
        Languages and domainQuality varies widely by language; test the ones your users speak.
        EcosystemSupport in vLLM / SGLang / llama.cpp, available quantisations, fine-tuning recipes.

        Families widely used in 2026 include Llama, Qwen, Mistral, Gemma, DeepSeek, gpt-oss, GLM and Kimi; new versions ship monthly. Check current model cards and licences rather than relying on any ranking here.

        Quantisation: smaller, faster, slightly different

        PrecisionBytes / parameter70B weightsQuality impact (typical)Formats
        BF16 / FP162~140 GBReferencesafetensors
        FP8 / INT81~70 GBUsually negligible on modern GPUsFP8, SmoothQuant, GPTQ-8
        INT4 (4-bit)~0.5–0.6~38 GBSmall but measurable; varies by taskAWQ, GPTQ, GGUF Q4_K_M
        2–3 bit~0.3–0.4~25 GBOften significant; test carefullyGGUF Q2/Q3, research formats
        Evaluate the quantised model, not the model card

        Benchmarks on a model card use full precision. Quantisation can hurt some tasks (long reasoning, maths, non-English, exact tool arguments) much more than average benchmark scores suggest. Run your full suite on the exact file and serving engine you will deploy, and treat a quantisation change like a model change in CI (Ch).

        Live demo · size a private deployment

        Estimate GPU memory, GPUs, speed and monthly cost for self-hosting, and the volume at which it beats an API. Rough planning numbers: memory-bound decode, GQA-style KV cache, illustrative prices. Benchmark your real stack before buying hardware.

        WeightsKV cacheOverhead
        Weights (GB) ≈ params (B) × bytes per parameter · KV cache per token ≈ 2 × layers × KV heads × head dim × bytes (≈128 KB for an 8B GQA model at FP16)
        KV total = per-token KV × context × concurrent requests · Decode speed per request ≈ memory bandwidth ÷ bytes read per token (memory-bound)
        Break-even tokens / month = (GPU cost + ops) ÷ API price per token

        Serving stacks

        EngineBest forNotes
        vLLMProduction GPU serving, high concurrencyPagedAttention, continuous batching, OpenAI-compatible API, multi-LoRA, tensor parallelism
        SGLangProduction serving, prefix-heavy and agent workloadsRadixAttention prefix caching; performance close to or above vLLM in many benchmarks
        TensorRT-LLM / NVIDIA NIM / TritonMaximum NVIDIA performance, enterprise supportCompiled engines; NIM packages models as containers
        llama.cppCPU, Apple silicon, edge, air-gappedGGUF quantised models; no Python stack needed
        Ollama · LM StudioDeveloper laptops, prototypes, personal private useEasy model management; not designed as hardened multi-user servers
        Hugging Face TGIExisting deploymentsReported in maintenance mode since late 2025; prefer vLLM or SGLang for new projects
        Kubernetes: KServe, llm-d, Ray ServeScaling many models on a clusterAutoscaling, routing, multi-tenant serving

        Security: what self-hosting makes your job

        AreaRiskControl
        Exposed endpointsModel servers listening on all interfaces with no authentication. 2026 scans found tens of thousands of internet-exposed Ollama servers, and a critical unauthenticated memory-leak flaw (CVE-2026-7482, "Bleeding Llama") was fixed in Ollama 0.17.1Bind to localhost or a private subnet; put an authenticating gateway in front; firewall; patch promptly
        Model supply chainMalicious or tampered weights; pickle-based files can run code when loadedDownload from official orgs; prefer safetensors; verify hashes or signatures; scan; mirror into an internal registry
        Licence complianceUse outside licence termsLegal review; record model, version and licence in a model inventory
        Data in logsPrompts and outputs with personal data stored in plain textRedact, encrypt, restrict access, set retention; same rules as production data
        EgressExfiltration via tools, or the server calling homeDefault-deny outbound network; allow-list only what tools need
        Prompt injectionStill applies: local models read untrusted documents tooSame defences and red-team suite as for API models (Ch)
        Weaker built-in safetyOpen models may have less safety tuning, and it can be removedAdd your own input/output guardrails (e.g. Llama Guard-style classifiers); safety evals
        Multi-tenant leakageShared prefix/KV caches or adapters leaking between customersIsolate tenants; review cache-sharing settings; per-tenant adapters evaluated separately
        Access controlAnyone on the network can call the modelSSO / service identity at the gateway; per-team keys, quotas and audit logs
        bash · a hardened single-node vLLM deployment (sketch)
        # 1. Mirror weights from an internal registry (verified hash), never pull at runtime
        sha256sum -c /models/qwen-awq/SHA256SUMS
        
        # 2. Serve on a private interface only, with an API key, no outbound network
        docker run --gpus all --network llm-private --read-only \
          -v /models/qwen-awq:/model:ro \
          -e HF_HUB_OFFLINE=1 \
          vllm/vllm-openai:<pinned-version> \
          --model /model --quantization awq --max-model-len 32768 \
          --host 10.0.4.12 --port 8000 --api-key "$VLLM_API_KEY" \
          --enable-prefix-caching --gpu-memory-utilization 0.90
        
        # 3. Put an authenticating gateway (SSO, quotas, audit log, redaction) in front;
        #    firewall: only the gateway can reach 10.0.4.12:8000; egress denied.

        Flags and image tags change between versions; check the vLLM docs for your version.

        Deep dive

        Running models privately

        Capacity, air gaps, cost and evaluation.

        Why the KV cache decides capacity memory

        Weights are loaded once. The KV cache (the stored attention keys and values for every token in every active request) grows with context length × concurrent requests. A 70B model at 4-bit needs ~40 GB for weights, but 32 requests × 32k tokens × ~320 KB per token ≈ 330 GB of KV cache at FP16. That's why long-context, high-concurrency serving needs far more GPU memory than the weights alone suggest. FP8 KV cache, prefix caching and shorter contexts help.

        Air-gapped operations offline
        • Bring weights, container images and Python wheels in through a controlled transfer process with hashes and malware scanning.
        • Run serving engines in offline mode; disable telemetry and update checks.
        • Keep an internal model registry and package mirror; document every version.
        • Run your eval suite inside the enclave; results come out, data doesn't.
        • Plan the update cycle: new model versions need the same transfer, evaluation and approval.
        Total cost of ownership cost

        GPU rental or purchase is only part of it. Add engineers to operate the stack, on-call, monitoring, security reviews, idle capacity (GPUs cost the same at 3 a.m.), redundancy for failover, and the opportunity cost of not having the newest frontier models. Self-hosting usually wins only at sustained high volume, with strict requirements, or when a small fine-tuned model replaces a large API model.

        Hybrid routing architecture

        Many organisations route by data sensitivity: requests containing classified or regulated data go to the private model; everything else can use a frontier API. A classifier or policy engine (plus PII detection) decides, and both routes run the same eval suite so quality differences are known. Evaluate the router too: a misroute is a data incident.

        On-device and edge models local

        Small models (roughly 1–8B parameters, quantised) run on laptops and phones via llama.cpp, Apple MLX, ONNX Runtime and vendor NPUs. Data never leaves the device. They suit summarisation, classification, autocomplete and offline assistants; evaluate them on device, since thermal limits and quantisation change behaviour.

        Chapter 19Architect

        System design: an eval platform

        Reference architecture

        At scale, evaluation is a data platform: trace ingestion, a dataset registry, an experiment runner, a pool of grader workers (code, judge, human queue) behind a judge gateway, a results store, and dashboards, gates and alerts. Everything is versioned so any score can be reproduced and explained.

        Reference architecture

        version registry: dataset · prompt · model · tools · grader code · judge model + prompt · rubric Production appOTel instrumented Trace storecollector · PII redaction Samplerrandom · targeted CI · developersrun suite on change Dataset registryversions · slices · splits Experiment runnertrials · cache · sandbox Eval queuejobs per trace × grader code graders LLM judges via gateway human annotation queue Results warehouserow per trial × grader Gates · alertsCI status · pages Dashboardstrends · slices · diffs failures → new dataset tasks
        ComponentJobKey design choices
        InstrumentationCapture every model call, tool call, retrieval and outputOTel GenAI conventions; prompt and model version on every span; sampling at ingest for very high volume
        Trace storeSearchable traces for debugging and samplingColumnar store (ClickHouse, BigQuery, Snowflake) or a platform; PII redaction; retention policy
        Dataset registryVersioned tasks with slices and splitsImmutable versions; changelog; one-click "add trace to dataset"; holdout access control
        Experiment runnerRun a system version over a dataset with k trialsIsolated environments; output cache; concurrency limits; batch APIs for nightly runs
        Eval queue + workersApply graders to outputsIdempotent jobs keyed by (output hash, grader version); retries; priority for CI jobs
        Judge gatewayCentral access to judge modelsVerdict cache; per-team budgets; pinned model versions; fallback models; logging of judge reasoning
        Human queueRoute items to annotatorsRouting rules (disagreement, UNKNOWN, high risk, random calibration sample); guidelines versioned
        Results warehouseEvery verdict, queryableRow per (task/trace, trial, grader, version); joins to traces and datasets
        Gates, alerts, dashboardsTurn results into decisionsNoise-aware rules; slice views; run-to-run diffs; links to example traces
        Deep dive

        Platform design decisions

        Multi-team use, governance and reproducibility.

        Shared graders, owned datasets org

        A central platform team owns the runner, judge gateway, storage and common graders (schema, PII, toxicity, groundedness). Product teams own their datasets, product-specific graders and thresholds. A grader catalogue with documented TPR/TNR per grader lets teams reuse aligned judges instead of writing new unaligned ones.

        Reproducibility contract governance

        Every result row references: dataset version, task ID, system version (model ID, prompt hash, tool versions, config), sampling settings, grader version, judge model and prompt version, run ID and timestamp. With this, any number on any dashboard can be traced back and re-run. Auditors and incident reviews depend on it.

        Security of the eval platform security

        Eval data includes production conversations and red-team attacks. Restrict access by role, encrypt at rest, separate holdout sets, sandbox code execution graders (they run untrusted generated code), and keep red-team prompts out of general-purpose datasets so they don't leak into fine-tuning data.

        Chapter 20ArchitectBuilder

        Cost and latency of evals

        Key insight

        Eval cost = tasks × trials × (system calls + judge calls) × runs, plus online sampling, plus human time. Judges usually dominate model spend and humans dominate total spend. Cut cost with code graders first, smaller aligned judges, verdict caching, batch APIs, tiered suites and smart sampling, not by evaluating less of what matters.

        Live demo · what will your evals cost per month?

        Set your suite size, how often it runs, how much production traffic you sample, and prices. See where the money goes and what each lever saves.

        Offline system callsOffline judgesOnline judgesHuman labels

        Cost levers, in order

        LeverTypical savingTrade-off
        Replace judges with code checks where possible100% of that grader's model costEngineering time; brittleness if done carelessly
        Smaller judge model, re-aligned5–20× per callMust re-measure TPR/TNR; may fail on hard criteria
        Cache verdicts and baseline outputs30–60% of calls in CICache invalidation by version
        Batch APIs for nightly runs~50% on those callsResults in hours, not minutes
        Prompt caching of judge instructionsLarge share of judge input costStable prefix order needed
        Tiered suites (smoke on PR, full nightly)70–90% of CI costSome regressions found a day later
        Lower online sample rate, stratifiedLinearWider intervals on small slices
        Route humans only to disagreements50–80% of human costKeep a random slice for calibration
        How many online samples do you need?

        To estimate a pass rate within ±2 points at 95% confidence, you need about 1.96² × p(1−p) / 0.02² ≈ 1,500 judged traces per period at p = 85%, regardless of total traffic. At 1M requests a day, that's a 0.15% sample. Sample per slice if you need per-slice precision.

        Deep dive

        Latency and budgeting

        Fast feedback without overspending.

        Keep PR evals under 10 minutes latency

        Developers stop waiting after about 10 minutes. Parallelise (dozens of concurrent calls), reuse cached baseline outputs, use a smoke suite of the most informative tasks (those that flipped recently or cover high-risk slices), and push the long tail to nightly runs.

        Budget per team and per run governance

        Route all judge calls through a gateway with per-team monthly budgets and per-run caps. A misconfigured suite (10 trials × 5,000 tasks × 10 judges with a frontier model) can cost thousands of dollars in one run. Alerts at 50% and 80% of budget prevent surprises.

        Cost per successful task metric
        cost per success = (system cost + verification cost) ÷ number of successful tasks

        Report it next to pass rate for every version. A version that raises pass rate from 80% to 82% while doubling cost per task may not be worth shipping; the metric makes that visible.

        Chapter 21Architect

        Scaling evals from 1 user to 1,000,000

        Pattern

        At one user, evaluation is you reading outputs in a notebook. At a team, it's a versioned dataset and a CI gate. At a company, it's a shared platform with aligned judges and online monitoring. At a million users, it's a data system: sampled online evaluation per slice, judge fleets with budgets, human review routed by risk, and governance-grade audit trails.

        Pick a stage

        Chapter 22ArchitectBuilder

        The failure catalog: technical and functional problems

        How to use this

        Every entry has a symptom, root cause and fix, tagged by area and severity. Click a cell in the heat map, filter by severity, or search for a word from your incident.

        Chapter 23ArchitectBuilder

        Every trade-off, side by side

        Read the dial

        Each row is a decision with two ends. The marker shows where most production teams sit by default. Move it for your own risk, scale and team.

        Chapter 24Everyone

        Alternatives to evals, and what's next

        Use the right instrument

        Some questions are better answered by something other than an eval suite: a deterministic test, an A/B test, a guardrail, a user interview, or simply reading outputs. Looking ahead, evaluation is becoming the core skill of AI engineering: agent evals are maturing, judges are being trained specifically for grading, and regulation is turning eval results into compliance evidence.

        Instead of an eval…UseWhen
        LLM judge for output formatSchema validation, structured outputs / constrained decodingAlways for format; make bad formats impossible, not just detected
        Eval suite for a deterministic functionUnit testsThe code around the model (parsers, routing rules, tools)
        Offline suite to predict user impactA/B testTone, UX, engagement, business outcomes
        Monthly eval for a dangerous outputRuntime guardrailEach bad output must be stopped, not just counted
        Metrics to understand why users leaveUser interviews, session replaysYou don't yet know what "good" means
        Building a suite for a throwaway prototypeReading 20 outputsDays-old projects; build the suite once it has users
        Generic benchmark to choose a modelYour own suite on 3–5 shortlisted modelsAlways, for production choices

        What's next (forward-looking, treat as informed speculation)

        Evaluation as the core AI engineering skill

        As generation gets cheaper, knowing whether output is right becomes the scarce skill. Expect job descriptions, team structures and tooling budgets to keep shifting toward evaluation and verification.

        Agent evals mature

        Standard task formats, containerised environments (Harbor-style), user simulators and pass^k reporting are converging. Expect shared formats for agent tasks and transcripts, like AGENTS.md did for instructions.

        Trained judges and verifiers

        Specialised grading models, process reward models and verifier agents trained on expert labels will replace many prompted judges, especially for high-volume online evaluation.

        Evals inside the loop

        Autonomous agent loops use evals as stop conditions and keep-or-discard rules (see the Loop Engineering guide). The same graders will serve CI, production and the agent's own self-checks.

        Fresh, private benchmarks

        Contamination and saturation push the field toward continuously refreshed and privately held test sets, third-party evaluators, and reporting with cost and error bars.

        Compliance-grade evaluation

        With EU AI Act obligations phasing in (some dates postponed to 2027–2028) and standards like ISO/IEC 42001, versioned eval records and audit trails become required infrastructure for regulated uses.

        Chapter 25Everyone

        Production checklist, glossary and sources

        Tick items as you go. Progress is saved in this browser only.

        Glossary

        TermDefinition
        Air-gappedA system with no network connection to the outside world.
        Catastrophic forgettingA fine-tuned model losing skills it had before fine-tuning.
        DistillationTraining a smaller model on a larger model's outputs to match its quality cheaply.
        DPODirect preference optimisation: fine-tuning on pairs of preferred and rejected responses.
        Fine-tuningContinuing to train a model's weights on your own examples.
        GGUFA file format for quantised models used by llama.cpp and Ollama.
        GRPO / RFTReinforcement fine-tuning methods where a grader's score is the training reward.
        KV cacheStored attention keys and values for tokens in active requests; grows with context × concurrency.
        LoRA / QLoRALow-rank adapters trained on a frozen model; QLoRA uses a 4-bit quantised base to save memory.
        Open-weight modelA model whose weights can be downloaded and run yourself, under a licence.
        Private endpointA managed model reachable only from your own cloud network and region.
        QuantisationStoring weights in fewer bits (e.g. 8 or 4) to cut memory and cost, with some quality risk.
        safetensorsA weight file format that cannot execute code when loaded, unlike pickle files.
        SFTSupervised fine-tuning on input → ideal output examples.
        Zero data retention (ZDR)An API arrangement where the provider does not store your prompts or outputs.
        A/B testRandomly splitting live users between two versions to measure impact on real outcomes.
        Adaptive rubricA rubric the judge generates per prompt (a list of pass/fail tests), then applies to the response.
        Attack success rate (ASR)Share of adversarial attempts that make the system misbehave.
        Axial codingGrouping free-text error notes into a small set of named failure modes.
        BaselineThe current version's scores on the same tasks, used for comparison.
        BenchmarkA public task set used to compare models.
        BootstrapEstimating uncertainty by recomputing a metric on many resamples of the data.
        Capability evalA hard suite with a low pass rate, used to measure progress ("hill to climb").
        Cohen's kappa (κ)Agreement between two graders corrected for chance agreement.
        Confidence intervalA range likely to contain the true value of a metric (e.g. 95% CI).
        ContaminationTest tasks or answers appearing in a model's training data, inflating scores.
        Criteria driftGraders' standards changing as they see more outputs (Shankar et al.).
        Faithfulness / groundednessWhether an answer's claims are supported by the provided context.
        Golden datasetA curated set of tasks with trusted expected behaviour.
        GraderLogic that scores one aspect of a trial (also evaluator, scorer, metric).
        GuardrailA runtime check that blocks or fixes an individual input or output.
        Harness (eval)Infrastructure that runs tasks, records transcripts, grades and aggregates.
        HoldoutA dataset split used rarely, to detect overfitting to dev and test sets.
        LLM-as-judgeUsing a language model with a rubric to grade outputs.
        MRRMean reciprocal rank: average of 1 / rank of the first relevant result.
        nDCGNormalised discounted cumulative gain: ranking quality with graded relevance.
        Non-inferiority testChecking that a new version is not worse than baseline by more than a margin.
        Offline evalEvaluation on a fixed dataset before release.
        Online evalEvaluation of sampled live production traffic.
        Open codingWriting free-text notes on what went wrong in each trace, without a fixed list.
        OutcomeThe final state of the environment after a trial.
        Pairwise comparisonAsking which of two outputs is better.
        Paired analysisComparing two versions per task on the same tasks, removing task-difficulty noise.
        pass@kProbability at least one of k attempts succeeds.
        pass^kProbability all k attempts succeed; a reliability metric.
        Position biasA judge favouring an answer because of its position in a pairwise prompt.
        Recall@kShare of relevant items found in the top k results.
        Red-teamingDeliberately attacking a system to find failures before others do.
        Reference-free evalGrading without a known correct answer (e.g. groundedness, format).
        Regression evalA suite that should pass near 100%; a drop means something broke.
        Rogan–Gladen correctionAdjusting an observed pass rate for a judge's known TPR and TNR.
        SaturationWhen top systems pass nearly all of a benchmark, so it no longer separates them.
        SliceA subset of tasks sharing a property (feature, language, risk) reported separately.
        Standard errorThe typical size of the error in a metric estimate due to sampling.
        TaskOne test: an input plus success criteria (also test case, example, sample).
        Theoretical saturationThe point in error analysis where new traces stop revealing new failure modes.
        TPR / TNRTrue positive rate and true negative rate of a judge versus human labels.
        TrajectoryThe sequence of steps and tool calls an agent took.
        TranscriptThe full record of a trial: messages, tool calls, reasoning, results (also trace).
        TrialOne attempt at a task.
        User simulatorAn LLM playing a user with a hidden goal, to test conversational agents.

        Sources and further reading

        The idea behind it all

        Look at your data. Then measure what you found.

        The Evaluation Guide. Written with research current to October 2026. Tools, benchmarks, cloud services and regulations change monthly: check official docs for anything newer, and treat numbers here as starting points. Companion guides: RAG · Agents · MCP · Prompt Engineering · Context Engineering · Harness Engineering · Loop Engineering.