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.
Pick where you are starting
Every chapter is tagged with a level. Choosing a path highlights the chapters to read first. Nothing is hidden.
What evaluation actually is
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
| Term | What it answers | Who runs it | Typical output |
|---|---|---|---|
| Benchmark | How good is a model at a general skill? | Model labs, researchers, leaderboards | One score per model on a public task set |
| Offline eval | Is version B of my system better than version A on my tasks? | Your team, in development and CI | Scores per metric and slice, with confidence intervals |
| Online eval | Is quality holding up on real traffic right now? | Your team, on sampled production traces | Pass rates over time, alerts, new failure examples |
| Guardrail | Should this one response be blocked or fixed before the user sees it? | Runtime, on every request | Allow, block, redact or retry |
| A/B test | Does the change improve what users and the business care about? | Product and data teams | Lift in task success, retention, conversion, with significance |
| Red-team | Can someone make the system misbehave on purpose? | Security and safety teams, tools | Attack success rate, list of working exploits |
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
| When | What happened | Why it matters |
|---|---|---|
| 2002–2004 | BLEU (machine translation) and ROUGE (summarisation) | First automatic text-overlap metrics; still used, often misused for open-ended generation |
| 2018–2019 | GLUE and SuperGLUE | Shared benchmark suites; saturated within about two years, a pattern that keeps repeating |
| 2019–2020 | BERTScore; MMLU (57 subjects) | Semantic similarity metrics; knowledge benchmarks for large models |
| 2021 | HumanEval and pass@k | Code graded by running unit tests; the unbiased pass@k estimator |
| Nov 2022 | Stanford HELM | Many metrics (accuracy, calibration, robustness, bias, toxicity) per scenario instead of one number |
| 2023 | Chatbot Arena (crowd pairwise votes, Elo); MT-Bench "Judging LLM-as-a-Judge"; G-Eval; RAGAS; SWE-bench; GPQA | LLM judges become mainstream; biases documented; RAG and agentic coding get their own evals |
| Mar 2024 | Hamel Husain, "Your AI Product Needs Evals" | Moves the focus from benchmarks to product evals built from your own traces |
| Apr 2024 | Shankar et al., "Who Validates the Validators?" (EvalGen) | Shows that criteria change as people grade ("criteria drift"); judges must be aligned with humans |
| 2024 | UK 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 2025 | Humanity's Last Exam (HLE) | A hard expert benchmark launched with top scores under 10% |
| Jan 9, 2026 | Anthropic, "Demystifying evals for AI agents" | Shared vocabulary for agent evals: tasks, trials, graders, transcripts, outcomes, harness |
| Feb 2026 | OpenAI stops reporting SWE-bench Verified, citing contamination | Benchmark leakage becomes a mainstream concern; harder successors (SWE-bench Pro) take over |
| Mar 9, 2026 | OpenAI announces it will acquire Promptfoo | Evals and red-teaming become part of the core agent platform stack |
| 2026 | Stanford AI Index reports about half of widely cited benchmarks saturated; cloud eval services for agents go GA | The value moves from public scores to private, task-specific evals |
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.
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.
Which evals you need, and when
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
- 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.
- 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).
- 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).
- 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).
- Do you have users?Sample production traces, run the same graders online, collect feedback, and feed new failures back into the dataset (Ch).
- 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
| Stage | Dataset | Graders | Where it runs | Time per week |
|---|---|---|---|---|
| Prototype | 20–50 hand-written and real examples in a spreadsheet | You, reading outputs; a few assertions | Notebook | 1–2 h |
| Pre-launch | 100–300 examples covering main features, edge cases and known failures | Code checks + 2–5 calibrated binary judges | Script or eval framework; run before each change | 3–6 h |
| Launched | 300–2,000 examples, refreshed from production monthly | Full suite; human review of samples | CI gate on every PR; nightly full run | A part-time owner |
| Scaling | Several suites per feature, plus holdouts and safety sets | Judges with tracked agreement; online evaluators | CI + production sampling + dashboards + alerts | A dedicated person or team |
| Regulated / high stakes | Documented, versioned datasets with expert labels | Expert review, audit trail, bias and safety evals | Formal release process | A team, plus domain experts |
Good uses and bad uses
| Situation | Verdict | Why |
|---|---|---|
| Deciding whether to switch to a new or cheaper model | Must have | Without a suite, model choice is a guess; with one, it's a 1-hour job |
| Changing a prompt that serves real users | Must have | Prompt edits silently break cases you didn't look at |
| Checking that structured output is valid JSON | Code check | Deterministic and free; no judge needed |
| Grading tone or faithfulness | Judge + human calibration | Needs judgement; judge must agree with a person first |
| Generic "helpfulness 1–5" across all outputs | Rewrite | Vague, unactionable and noisy; split into specific binary checks |
| Building a 30-metric dashboard on day one | Don't | Metrics before error analysis measure things nobody cares about |
| Trusting a public leaderboard to pick a model for your task | Don't | Benchmarks measure general skill, often with contamination; test on your own data |
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.
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
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.
Anatomy of an eval, and the flywheel
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
| Part | What it is | Also called | Key decision |
|---|---|---|---|
| Task | One test: an input plus what success means | Test case, example, sample, row, problem | Unambiguous criteria; a reference answer or a rule |
| Trial | One attempt at a task | Run, rollout, sample | How many trials per task (1 for cheap checks, 3–10 for agents) |
| Transcript | Everything that happened: messages, tool calls, reasoning, intermediate results | Trace, trajectory, log | Store it all; you'll need it for debugging and re-grading |
| Outcome | The final state of the world after the trial | End state, result | Grade what actually happened (the booking exists), not what the agent said |
| Grader | Logic that scores one aspect of a trial | Evaluator, scorer, metric, judge, assertion | Code first, model second, human to calibrate |
| Metric | An aggregate of grader scores | Score, KPI | Mean pass rate per slice, with a confidence interval |
| Harness | Infrastructure that runs tasks, records transcripts, grades and aggregates | Eval runner, framework | Isolated, reproducible trials; parallel; cached |
| Suite | A group of tasks for one capability or feature | Eval set, benchmark | Capability suite (hard, low pass rate) or regression suite (near 100%) |
| Baseline | Scores of the current version on the same suite | Control | Always compare paired, on the same tasks |
Capability evals vs regression evals
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.
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 evals | Online evals | |
|---|---|---|
| Inputs | Fixed, curated dataset | Live traffic, sampled |
| Reference answers | Often available | Rarely; reference-free graders only |
| When | Before release, on every change | After release, continuously |
| Catches | Regressions, model and prompt comparisons | Drift, new user behaviour, unknown failure modes |
| Weakness | Dataset goes stale; misses new inputs | No ground truth; privacy limits; delayed signal |
The smallest useful 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 resultsParts 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.
Error analysis: look at your data
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.
- 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.
- 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.
- 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.
- Count and prioritiseTally traces per mode. A few modes usually cover most failures (a Pareto pattern). Weigh frequency by severity.
- Fix or measureSome failures are obvious bugs: fix them, no eval needed. For the rest, write a specific grader for each mode (Ch, Ch).
- 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 note | Strong note | Why |
|---|---|---|
| "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 |
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.
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.
Datasets and golden sets
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
| Source | Strength | Weakness | Use for |
|---|---|---|---|
| Production traces (sampled) | Real distribution and phrasing | Needs PII handling; few reference answers | Main regression and capability sets |
| Bug reports, support tickets, thumbs-down | Known high-impact failures | Biased toward loud failures | Regression tests ("never again") |
| Domain experts writing tasks | Hard, realistic, correct references | Slow, expensive | Capability sets, high-stakes slices |
| Synthetic (dimension-based, LLM-written) | Fast coverage of rare combinations; pre-launch | Can be bland or unrealistic; needs review | Edge cases, cold start, stress tests |
| Adversarial / red-team | Finds safety and robustness gaps | Not representative of normal use | Safety suites (Ch) |
| Public benchmarks | Free, comparable | Generic, often contaminated | Sanity checks only (Ch) |
What a task record should hold
{"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
| Split | Used for | Rule |
|---|---|---|
| Dev | Iterating on prompts, debugging, reading failures | Look at it as much as you like |
| Test | Deciding whether a change ships | Run it, report it, don't tune to individual cases |
| Holdout | Checking you haven't overfit dev and test over months of tuning | Run rarely (monthly, before big releases); never read individual failures |
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.
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.
Code graders and metrics
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
| Grader | How it works | Good for | Watch out |
|---|---|---|---|
| Exact / normalised match | Compare after lower-casing, trimming, removing punctuation | Classification labels, short answers, IDs, numbers | Fails valid paraphrases |
| Numeric tolerance | |answer − reference| ≤ tolerance | Maths, finance, measurements | Parse numbers robustly ("1,200", "1.2k") |
| Contains / regex / must-not | Required or forbidden substrings or patterns | Policy phrases, disclaimers, banned words, leaked secrets | Easy to game; brittle wording |
| Schema validation | Parse JSON; validate with JSON Schema / Pydantic | Structured output, tool arguments | Valid shape ≠ correct values |
| Execution | Run generated code, SQL or commands; check results or tests | Code generation, text-to-SQL, data analysis | Sandbox it; tests can be weak |
| Tool-call check | Was the right tool called, with valid args, in an allowed order? | Agents, function calling | Don't over-constrain the path (Ch) |
| State / outcome check | Query the environment after the trial (DB row, file, API state) | Agents that change things | Needs an isolated environment |
| Classification metrics | Precision, recall, F1, confusion matrix against labels | Routing, intent detection, moderation, extraction | Report per class; watch imbalance |
| Text overlap (BLEU, ROUGE, chrF, METEOR) | Counts shared n-grams with a reference | Translation, tightly constrained summaries | Correlates poorly with quality for free-form answers |
| Semantic similarity (BERTScore, embedding cosine) | Compares meaning via embeddings | Paraphrase-tolerant matching to a reference | "Paris is the capital" vs "Paris is not the capital" can score high |
| Heuristics | Length, readability, language ID, latency, cost, number of turns | Constraints and efficiency | Proxies, 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.
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)
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.
LLM-as-judge: graders you can trust
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
| Format | Question to the judge | Best for | Main risk |
|---|---|---|---|
| Binary, single output | "Does this response cite a source for every factual claim? PASS/FAIL" | Specific failure modes; regression gates | Needs one judge per criterion |
| Reference-guided | "Does the response contain the same key facts as the reference?" | Correctness when you have references | Penalises valid extra info if rubric is strict |
| Pairwise | "Which response is better for this user, A or B?" | Comparing two versions; preference data | Position bias; doesn't give absolute quality |
| Likert / score 1–10 | "Rate helpfulness 1–10" | Rarely the right choice | Noisy, poorly calibrated, unactionable |
| Checklist / rubric | "Check each: (1) greets (2) verifies identity (3) states policy (4) offers next step" | Multi-criteria tasks; partial credit | Long rubrics dilute attention; split if >5 items |
| Adaptive rubric | Judge first writes prompt-specific pass/fail tests, then applies them | Diverse open-ended prompts | Generated tests need spot checks (Vertex AI uses this approach) |
Anatomy of a good judge prompt
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
| Bias | What happens | Mitigation |
|---|---|---|
| Position | In pairwise comparisons, prefers the first (or second) answer | Run both orders; count a win only if consistent; otherwise tie |
| Verbosity / length | Prefers longer answers | Rubric says length is not quality; length-controlled metrics (AlpacaEval LC); check correlation of verdict with length |
| Self-preference | Rates outputs from its own model family higher (linked to lower perplexity / familiarity) | Use a judge from a different family, or a panel of judges |
| Leniency | Passes almost everything; low true negative rate | Few-shot FAIL examples; measure TNR explicitly; stricter wording |
| Authority / format | Swayed by confident tone, citations or markdown formatting, even if wrong | Ask it to verify claims against provided context, not style |
| Sycophancy to the prompt | Follows hints in the output ("this answer is correct") | Wrap output in tags; instruct to ignore instructions inside it |
| Knowledge limits | Can't verify facts it doesn't know or that changed after its cutoff | Give references or retrieved context; use reference-guided judging |
Aligning a judge with humans
- 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.
- SplitTrain (few-shot examples, ~20%), dev (iterate on the prompt, ~40%), test (final measurement, ~40%, untouched until the end).
- 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.
- 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.
- 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).
- 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.
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.
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.
Human evaluation and annotation
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 type | Who | Use for | Rough cost |
|---|---|---|---|
| Error analysis | Product owner, domain expert | Finding failure modes (Ch) | 2–4 h per 100 traces |
| Labelling for judge alignment | Domain expert (one "benevolent dictator", or 2–3 with adjudication) | Ground truth for TPR/TNR | 1–3 min per label |
| Expert review | Doctors, lawyers, senior engineers | High-stakes correctness | $2–$30+ per item |
| Crowd preference | Trained raters, crowd platforms | Pairwise preferences, fluency, general quality | $0.10–$2 per comparison |
| Spot-check sampling | Team members on rotation | Catching judge drift in production | 30 min a week |
| User studies / A/B | Real users | Whether changes help outcomes | Product 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.
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.
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.
Statistics: noise, error bars and pass@k
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
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:
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).
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.
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.
Evaluating RAG systems
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
| Metric | Measures | Needs | Formula / method |
|---|---|---|---|
| Hit rate / recall@k | Did any (or what share of) relevant chunks appear in the top k? | Labelled relevant chunk IDs | |relevant ∩ top-k| / |relevant| |
| Precision@k | How much of the top k is relevant? | Labels | |relevant ∩ top-k| / k |
| MRR | How high is the first relevant result? | Labels | mean of 1 / rank of first relevant |
| nDCG@k | Ranking quality with graded relevance | Graded 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 context | Reference answer (LLM-judged) | LLM checks each chunk or each reference claim |
| Faithfulness / groundedness | Are the answer's claims supported by the retrieved context? | Context + answer | Split answer into claims; judge each as supported or not; supported / total |
| Answer relevance | Does the answer address the question? | Question + answer | Judge, or similarity of questions regenerated from the answer |
| Answer correctness | Is it actually right? | Reference answer or key facts | Reference-guided judge; fact recall |
| Citation accuracy | Do citations point to chunks that support the sentence? | Answer with citations | Judge per citation; code check that cited IDs exist |
| Abstention quality | Says "I don't know" when the answer isn't in the corpus | Unanswerable test questions | Pass 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.
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.
Evaluating agents
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.
| Level | Question | Graders | Example |
|---|---|---|---|
| Outcome | Is the world in the right state? | State checks (DB, files, API), unit tests | The refund row exists, amount ≤ $100, status "approved" |
| Final response | Did it tell the user the right thing? | Judge, reference match | Confirmation message states the correct amount and date |
| Trajectory constraints | Did it follow the rules on the way? | Transcript code checks, judge | Verified identity before refunding; never called delete_account |
| Tool use | Right tools, valid arguments? | Schema checks, tool-call match, judge | search_flights called with ISO dates; no hallucinated tool names |
| Step quality | Were individual decisions reasonable? | Judge on selected steps | Plan was sensible; recovered from a tool error instead of repeating it |
| Efficiency | At what cost? | Counters | Turns, tool calls, tokens, latency, $ per task |
| Reliability | Does it work every time? | Repeated trials | pass^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.
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.
Safety, red-teaming and robustness
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".
| Risk | What to test | Metric | Typical tools / sets |
|---|---|---|---|
| Jailbreaks | Role-play, encoding, many-shot, multi-turn escalation to bypass policies | Attack success rate (ASR) | Promptfoo red team, PyRIT, garak, HarmBench |
| Direct prompt injection | "Ignore previous instructions…" in user input | ASR; system prompt leakage rate | Promptfoo, garak, custom suites |
| Indirect prompt injection | Instructions hidden in retrieved docs, web pages, emails, tool output | ASR on agent actions | AgentDojo, InjecAgent, custom canaries |
| Data leakage | PII, secrets, other users' data, system prompt in output | Leak rate | Regex/PII detectors, canary tokens |
| Harmful content | Violence, self-harm, hate, sexual, illegal advice | Unsafe response rate by category | Cloud content-safety evaluators, Llama Guard, HarmBench |
| Over-refusal | Safe requests that look risky ("how do I kill a Python process?") | False refusal rate | XSTest, OR-Bench, your own borderline set |
| Hallucination | Made-up facts, citations, tool results | Unsupported claim rate | Groundedness judges, SimpleQA-style sets |
| Bias and fairness | Different quality or tone by name, gender, dialect, region | Score gap between counterfactual pairs | Counterfactual templates, BBQ |
| Excessive agency | Agent takes destructive or unapproved actions | Unsafe action rate | Sandboxed agent suites, policy checks on transcripts |
| Robustness | Typos, paraphrases, other languages, long or weird inputs | Score drop vs clean inputs | Metamorphic / perturbation tests |
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
- 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.
- Automated scanRun a generator of attacks across categories (Promptfoo, PyRIT, garak) against a staging endpoint. Grade with judges tuned for each harm category.
- Manual red-teamingHumans find creative multi-turn and domain-specific attacks that tools miss. Budget a few days before launch and after major changes.
- Turn findings into regression testsEvery successful attack becomes a test that must keep failing to work.
- 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.
- Monitor in productionLog blocked and flagged requests, sample them for review, and watch for new attack patterns.
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.
Public benchmarks and leaderboards
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.
| Benchmark | Measures | Graded by | Status (Oct 2026) |
|---|---|---|---|
| MMLU / MMLU-Pro | Broad knowledge, multiple choice (57 subjects; Pro: 10 options, harder) | Exact match | MMLU saturated Pro near saturation |
| GPQA Diamond | Graduate-level "Google-proof" science questions | Exact match | Near saturation |
| Humanity's Last Exam (HLE) | ~2,500 expert-written questions across fields | Exact match / judge | Active reported top scores roughly 40–60%, sources disagree |
| AIME / FrontierMath | Competition and research-level maths | Exact answer | AIME mostly saturated; FrontierMath active |
| HumanEval / MBPP | Short Python functions | Unit tests (pass@k) | Saturated |
| LiveCodeBench | Recent contest problems, refreshed to avoid contamination | Unit tests | Active |
| SWE-bench Verified | Real GitHub issues, human-validated subset | Repo tests | Contaminated treat with caution |
| SWE-bench Pro | Harder, contamination-resistant software tasks | Repo tests | Active |
| Terminal-Bench 2.0 | End-to-end terminal tasks in containers | Tests on final state | Active |
| τ-bench / τ²-bench | Tool-using customer-service agents with simulated users | DB state, pass^k | Active |
| BFCL | Function / tool calling accuracy | AST and execution checks | Active |
| BrowseComp | Finding hard-to-locate facts on the web | Exact answer | Active |
| OSWorld / WebArena | Computer and browser use | Environment state | Active |
| ARC-AGI-2 | Novel abstract reasoning puzzles | Exact grid match | Active |
| IFEval | Following verifiable formatting instructions | Code checks | Near saturation |
| SimpleQA | Short factual questions; hallucination tendency | Judge vs reference | Active |
| MTEB | Embedding models across retrieval and other tasks | Task metrics (nDCG etc.) | Active; check retrieval subsets |
| LMArena (Chatbot Arena) | Crowd pairwise preferences | Bradley–Terry / Elo | Active; style and sampling concerns (below) |
| HELM | Many metrics across scenarios | Mixed | Active; good for multi-metric views |
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.
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
- Shortlist 3–5 models using benchmarks relevant to your task type plus price and latency.
- Run your full offline suite on each, with several trials and error bars.
- Compare cost per successful task and p95 latency, not just pass rate.
- Shadow-test the winner on production traffic with online evaluators before switching.
Types of evals, in one place
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.
Tools, platforms and frameworks
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.
| Tool | Type | Strength | Consider when |
|---|---|---|---|
| Promptfoo | Open-source CLI, YAML config | Fast prompt/model comparisons, CI-friendly, strong red-teaming | You want a quick CI gate and red-team scans. OpenAI announced its acquisition in March 2026; it says the open-source project continues |
| DeepEval | Open-source Python, pytest-style | Many ready metrics (G-Eval, RAG, agent), test-like workflow | Your team lives in pytest; mind judge cost per metric |
| RAGAS | Open-source Python | RAG metrics, test-set generation | Evaluating retrieval and grounding |
| Inspect (UK AISI) | Open-source Python framework | Agent evals with sandboxes, large eval library, used by safety institutes | Agentic or safety evals; rigorous research-style runs |
| OpenAI Evals / Evals API | Open-source + hosted | Graders tied to OpenAI models and fine-tuning | You're on the OpenAI platform |
| lm-eval-harness · lighteval · HELM | Open-source benchmark runners | Standard academic benchmarks at scale | Comparing base or open models |
| MLflow (GenAI evaluate) | Open-source platform | Eval runs tracked with experiments and models | You already use MLflow / Databricks |
| Braintrust | Hosted platform (SaaS) | Experiments, datasets, scorers (autoevals), online scoring, release gating | You want one managed eval workflow from dev to production |
| LangSmith | Hosted platform | Tracing, datasets, offline/online evals, annotation queues | You build on LangChain / LangGraph |
| Langfuse | Open-source, self-hostable platform | Tracing, prompt management, evals, annotation | You need self-hosting or open source |
| Arize Phoenix / AX | Source-available (Phoenix) + SaaS (AX) | OpenTelemetry-native tracing, evals, drift | OTel-first observability |
| W&B Weave · Opik (Comet) · Galileo · Patronus · HoneyHive · Confident AI | Platforms | Varied: tracing, judges, hallucination models, dashboards | Compare against your workflow; many have free tiers |
| Microsoft Foundry evaluations | Cloud service + SDK | Built-in quality, safety and agent evaluators (task adherence, intent resolution, tool-call accuracy), red-teaming agent | You deploy on Azure |
| Amazon Bedrock evaluations · AgentCore Evaluations | Cloud service | Model and RAG evaluation jobs; built-in LLM-judge evaluators for agents (session, trace and tool level), online and on-demand | You deploy on AWS |
| Vertex AI Gen AI evaluation service | Cloud service + SDK | Adaptive rubrics, agent metrics (tool use quality, hallucination), pairwise | You deploy on Google Cloud |
| PyRIT · garak | Open-source red-team | Automated attack generation (Microsoft, NVIDIA) | Security testing (Ch) |
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
| Criterion | Questions to ask |
|---|---|
| Trace viewing | Can a domain expert read one of our traces comfortably, including tool calls and retrieved docs? |
| Custom graders | Can we write our own code graders and judges easily, or are we pushed to generic metrics? |
| Datasets | Versioning, slices, adding production traces to datasets in one click? |
| Experiments | Side-by-side diffs of two runs per task, with confidence intervals? |
| CI integration | CLI or API to run a suite and fail a build on thresholds? |
| Online evals | Sample production traces and run the same graders? Alerts? |
| Data control | Self-hosting, region, retention, PII redaction, SSO? |
| Lock-in | OpenTelemetry support; export of traces, datasets and results? |
| Cost | Per seat, per trace, per judge call? What does 1M traces a month cost? |
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.
Build an eval suite end to end
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.
- Collect tracesLog every request with input, retrieved chunks, tool calls, output, model, prompt version, latency and cost. Pull 100 recent traces.
- 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%).
- DatasetTurn failing and representative traces into 220 tasks with slices, must/must-not facts and expected tool calls (Ch).
- Code gradersTool-argument schema, identity-check-before-change order, must-not phrases, citation IDs exist.
- LLM judgeOne binary judge for policy faithfulness, aligned on 150 expert labels: TPR 94%, TNR 88% on the test split.
- Runner3 trials per task, parallel, cached by (task, system version, trial).
- ReportPass rate per grader and slice with CIs; paired comparison with baseline.
- CI gateBlock merges on regression-suite drops beyond noise.
- OnlineSample 5% of production traces, run the same graders, alert on drift, feed failures back to step 2.
Step 4 · Code graders
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
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 humanModel 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
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
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
| Grader | Baseline | Candidate | Paired diff [95% CI] | Verdict |
|---|---|---|---|---|
| policy_faithful (corrected) | 81.2% | 88.9% | +7.7 [+4.1, +11.2] | Improved |
| identity_before_change | 97.0% | 96.4% | −0.6 [−2.3, +1.1] | No change |
| tool_args_valid | 94.5% | 99.1% | +4.6 [+2.2, +7.0] | Improved |
| refund slice · policy_faithful | 78.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.
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.
Evals in CI/CD and release gates
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
Designing the gate
| Gate type | Rule | Use for |
|---|---|---|
| Hard threshold | Pass rate ≥ 99% on must-never-break tasks | Regression suite, safety-critical checks |
| Non-inferiority | Lower CI bound of (candidate − baseline) > −2 points | Most quality metrics: "not meaningfully worse" |
| Superiority | Lower CI bound of difference > 0 | Changes justified by an improvement claim |
| Slice guard | No slice drops by more than X with significance | Catching hidden regressions |
| Budget guard | Cost per task and p95 latency within limits | Preventing silent cost creep |
| Human sign-off | Expert reviews diff of 30 changed outputs | Releases in high-stakes domains |
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.mdModel-upgrade playbook
- 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.
- Read diffsLook at tasks that flipped in either direction. Judge-flagged improvements should be confirmed by a human sample.
- Adjust promptsFix regressions, re-run, check the holdout to confirm you haven't overfit.
- Re-align judgesIf the judge model changes too, re-measure TPR/TNR first. Never change the system and the judge in the same comparison.
- Shadow and canaryRun the new model on a copy of live traffic (shadow) or a small share (canary) with online evaluators, then roll out.
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.
Online evaluation and production monitoring
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.
| Signal | Examples | Strength | Weakness |
|---|---|---|---|
| Online graders | Code checks and judges on sampled traces (groundedness, policy, format) | Consistent with offline suite | Reference-free only; judge cost |
| Explicit feedback | Thumbs up/down, ratings, comments | Direct user voice | Rare (often <1–2% of sessions), biased to extremes |
| Implicit feedback | Regenerate, copy, edit, abandon, rephrase, escalate to human, follow-up "that's wrong" | Plentiful | Ambiguous; needs validation against labels |
| Business outcomes | Resolution rate, conversion, ticket deflection, retention | What actually matters | Slow, noisy, many causes |
| Operational | Latency, errors, token usage, cost, tool failure rate | Cheap, immediate | Not quality |
| Guardrail events | Blocked inputs/outputs, PII redactions, refusals | Safety visibility | Classifier 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 type | Example | Detect with |
|---|---|---|
| Input drift | New product launch brings a new kind of question | Embedding clusters over time; topic classifier shares; "unknown intent" rate |
| Output / quality drift | Groundedness pass rate slides from 93% to 87% over two weeks | Control charts on online grader rates with CI bands |
| Model drift | Provider updates a model alias; behaviour shifts | Pin versions; daily canary suite on the live endpoint |
| Data drift | Policy documents updated; index stale | Freshness checks; RAG retrieval metrics on a fixed probe set |
| Judge drift | Judge model changed; scores jump overnight | Weekly human spot-check of judge verdicts; pinned judge versions |
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.
Fine-tuning LLMs, measured
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
- 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.
- 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.
- 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.
- 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.
- 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 show | Best first fix | Fine-tune? |
|---|---|---|
| Answers miss company facts or use outdated info | RAG, better retrieval | No facts in weights go stale and can't be cited |
| Output format breaks 3% of the time | Structured outputs / constrained decoding | Rarely |
| Tone or style inconsistent despite good prompts | Few-shot examples, style guide in prompt | Yes SFT on approved examples |
| Narrow classification / extraction at high volume | Prompted large model | Yes fine-tune a small model to match it (distillation) |
| Domain jargon (medical, legal, internal codes) misunderstood | Glossary in context | Maybe SFT, or continued pre-training on domain text |
| Model picks the wrong tool or reasons poorly on a checkable task | Better tool descriptions, examples | Yes reinforcement fine-tuning with a grader |
| Data can't leave your network and API models are banned | Self-hosted open-weight model (Ch) | Maybe fine-tune the open model to close the quality gap |
The fine-tuning methods
| Method | What it does | Data | Use for |
|---|---|---|---|
| Supervised fine-tuning (SFT) | Train on input → ideal output pairs | 500–50k examples | Format, style, narrow tasks, distillation |
| Full fine-tuning | Update every weight | Large, clean sets | Maximum change; big budgets; usually unnecessary |
| LoRA (low-rank adaptation) | Freeze the model; train small adapter matrices (~0.1–1% of parameters) | Same as SFT | The default: cheap, fast, swappable adapters |
| QLoRA | LoRA on a 4-bit quantised base model | Same as SFT | Large models on limited GPU memory |
| DPO / preference tuning | Train on pairs of (preferred, rejected) responses | 1k–10k pairs | Tone, helpfulness, "prefer this over that" |
| Reinforcement fine-tuning (RFT, GRPO) | Model generates attempts; a grader scores them; training rewards high scores | Hundreds of tasks + a reliable grader | Reasoning and tool use on checkable tasks |
| Distillation | Train a small model on outputs of a large one | Thousands of large-model outputs | Same quality, much lower cost and latency |
| Continued pre-training | Keep training on raw domain text | Millions+ tokens | Very specialised vocabularies; rarely needed |
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.
{"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.
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
| Check | Why | How |
|---|---|---|
| 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 suite | Did it break what used to work? | Full product regression suite, all slices |
| General capability | Catastrophic forgetting: losing general skills | A small set of general tasks (reasoning, instruction following, maths, your other features) |
| Safety and refusal | Fine-tuning can erode safety training | Red-team and over-refusal suites (Ch) before and after |
| Overfitting during training | Memorising examples instead of learning the pattern | Validation loss and a small eval run at each checkpoint; pick the best checkpoint by eval, not loss |
| Cost and latency | Was the goal a cheaper model? | Cost per successful task, p95 latency on the serving stack |
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.
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).
Local and private deployment for data and security
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
| Option | Data leaves your control? | Model quality | You manage | Typical fit |
|---|---|---|---|---|
| Public API, default terms | Yes; retained for a period for abuse monitoring | Frontier | Nothing | Non-sensitive data |
| API with zero data retention (ZDR) and a data processing agreement | Processed by provider, not stored | Frontier | Contracts, redaction | Most business data, with legal sign-off |
| Private cloud endpoint (Azure OpenAI / Foundry, Amazon Bedrock, Vertex AI) with private networking | Stays in your cloud tenant and chosen region | Frontier + open models | Network, identity, region choice | Regulated industries already in that cloud |
| Self-hosted open weights in your cloud | No | Open-weight (close to frontier on many tasks) | GPUs, serving, scaling, security, upgrades | Strict residency, custom fine-tunes, very high volume |
| On-premises | No | Open-weight | Everything, including hardware | Data-centre-bound or sovereign requirements |
| Air-gapped | No network path at all | Open-weight, often smaller | Everything, plus offline update process | Defence, classified, critical infrastructure |
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
| Consider | Why it matters |
|---|---|
| Your eval results | The only reliable signal. Run your suite on 3–5 candidates at the quantisation you'll deploy (Ch). |
| Size and architecture | Dense 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). |
| Licence | Apache 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 use | Check real performance at your context lengths and with your tool-calling format, not just the advertised maximum. |
| Languages and domain | Quality varies widely by language; test the ones your users speak. |
| Ecosystem | Support 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
| Precision | Bytes / parameter | 70B weights | Quality impact (typical) | Formats |
|---|---|---|---|---|
| BF16 / FP16 | 2 | ~140 GB | Reference | safetensors |
| FP8 / INT8 | 1 | ~70 GB | Usually negligible on modern GPUs | FP8, SmoothQuant, GPTQ-8 |
| INT4 (4-bit) | ~0.5–0.6 | ~38 GB | Small but measurable; varies by task | AWQ, GPTQ, GGUF Q4_K_M |
| 2–3 bit | ~0.3–0.4 | ~25 GB | Often significant; test carefully | GGUF Q2/Q3, research formats |
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.
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
| Engine | Best for | Notes |
|---|---|---|
| vLLM | Production GPU serving, high concurrency | PagedAttention, continuous batching, OpenAI-compatible API, multi-LoRA, tensor parallelism |
| SGLang | Production serving, prefix-heavy and agent workloads | RadixAttention prefix caching; performance close to or above vLLM in many benchmarks |
| TensorRT-LLM / NVIDIA NIM / Triton | Maximum NVIDIA performance, enterprise support | Compiled engines; NIM packages models as containers |
| llama.cpp | CPU, Apple silicon, edge, air-gapped | GGUF quantised models; no Python stack needed |
| Ollama · LM Studio | Developer laptops, prototypes, personal private use | Easy model management; not designed as hardened multi-user servers |
| Hugging Face TGI | Existing deployments | Reported in maintenance mode since late 2025; prefer vLLM or SGLang for new projects |
| Kubernetes: KServe, llm-d, Ray Serve | Scaling many models on a cluster | Autoscaling, routing, multi-tenant serving |
Security: what self-hosting makes your job
| Area | Risk | Control |
|---|---|---|
| Exposed endpoints | Model 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.1 | Bind to localhost or a private subnet; put an authenticating gateway in front; firewall; patch promptly |
| Model supply chain | Malicious or tampered weights; pickle-based files can run code when loaded | Download from official orgs; prefer safetensors; verify hashes or signatures; scan; mirror into an internal registry |
| Licence compliance | Use outside licence terms | Legal review; record model, version and licence in a model inventory |
| Data in logs | Prompts and outputs with personal data stored in plain text | Redact, encrypt, restrict access, set retention; same rules as production data |
| Egress | Exfiltration via tools, or the server calling home | Default-deny outbound network; allow-list only what tools need |
| Prompt injection | Still applies: local models read untrusted documents too | Same defences and red-team suite as for API models (Ch) |
| Weaker built-in safety | Open models may have less safety tuning, and it can be removed | Add your own input/output guardrails (e.g. Llama Guard-style classifiers); safety evals |
| Multi-tenant leakage | Shared prefix/KV caches or adapters leaking between customers | Isolate tenants; review cache-sharing settings; per-tenant adapters evaluated separately |
| Access control | Anyone on the network can call the model | SSO / service identity at the gateway; per-team keys, quotas and audit logs |
# 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.
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.
System design: an eval platform
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
| Component | Job | Key design choices |
|---|---|---|
| Instrumentation | Capture every model call, tool call, retrieval and output | OTel GenAI conventions; prompt and model version on every span; sampling at ingest for very high volume |
| Trace store | Searchable traces for debugging and sampling | Columnar store (ClickHouse, BigQuery, Snowflake) or a platform; PII redaction; retention policy |
| Dataset registry | Versioned tasks with slices and splits | Immutable versions; changelog; one-click "add trace to dataset"; holdout access control |
| Experiment runner | Run a system version over a dataset with k trials | Isolated environments; output cache; concurrency limits; batch APIs for nightly runs |
| Eval queue + workers | Apply graders to outputs | Idempotent jobs keyed by (output hash, grader version); retries; priority for CI jobs |
| Judge gateway | Central access to judge models | Verdict cache; per-team budgets; pinned model versions; fallback models; logging of judge reasoning |
| Human queue | Route items to annotators | Routing rules (disagreement, UNKNOWN, high risk, random calibration sample); guidelines versioned |
| Results warehouse | Every verdict, queryable | Row per (task/trace, trial, grader, version); joins to traces and datasets |
| Gates, alerts, dashboards | Turn results into decisions | Noise-aware rules; slice views; run-to-run diffs; links to example traces |
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.
Cost and latency of evals
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.
Cost levers, in order
| Lever | Typical saving | Trade-off |
|---|---|---|
| Replace judges with code checks where possible | 100% of that grader's model cost | Engineering time; brittleness if done carelessly |
| Smaller judge model, re-aligned | 5–20× per call | Must re-measure TPR/TNR; may fail on hard criteria |
| Cache verdicts and baseline outputs | 30–60% of calls in CI | Cache invalidation by version |
| Batch APIs for nightly runs | ~50% on those calls | Results in hours, not minutes |
| Prompt caching of judge instructions | Large share of judge input cost | Stable prefix order needed |
| Tiered suites (smoke on PR, full nightly) | 70–90% of CI cost | Some regressions found a day later |
| Lower online sample rate, stratified | Linear | Wider intervals on small slices |
| Route humans only to disagreements | 50–80% of human cost | Keep a random slice for calibration |
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.
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
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.
Scaling evals from 1 user to 1,000,000
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
The failure catalog: technical and functional problems
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.
Every trade-off, side by side
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.
Alternatives to evals, and what's next
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… | Use | When |
|---|---|---|
| LLM judge for output format | Schema validation, structured outputs / constrained decoding | Always for format; make bad formats impossible, not just detected |
| Eval suite for a deterministic function | Unit tests | The code around the model (parsers, routing rules, tools) |
| Offline suite to predict user impact | A/B test | Tone, UX, engagement, business outcomes |
| Monthly eval for a dangerous output | Runtime guardrail | Each bad output must be stopped, not just counted |
| Metrics to understand why users leave | User interviews, session replays | You don't yet know what "good" means |
| Building a suite for a throwaway prototype | Reading 20 outputs | Days-old projects; build the suite once it has users |
| Generic benchmark to choose a model | Your own suite on 3–5 shortlisted models | Always, 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.
Production checklist, glossary and sources
Tick items as you go. Progress is saved in this browser only.
Glossary
| Term | Definition |
|---|---|
| Air-gapped | A system with no network connection to the outside world. |
| Catastrophic forgetting | A fine-tuned model losing skills it had before fine-tuning. |
| Distillation | Training a smaller model on a larger model's outputs to match its quality cheaply. |
| DPO | Direct preference optimisation: fine-tuning on pairs of preferred and rejected responses. |
| Fine-tuning | Continuing to train a model's weights on your own examples. |
| GGUF | A file format for quantised models used by llama.cpp and Ollama. |
| GRPO / RFT | Reinforcement fine-tuning methods where a grader's score is the training reward. |
| KV cache | Stored attention keys and values for tokens in active requests; grows with context × concurrency. |
| LoRA / QLoRA | Low-rank adapters trained on a frozen model; QLoRA uses a 4-bit quantised base to save memory. |
| Open-weight model | A model whose weights can be downloaded and run yourself, under a licence. |
| Private endpoint | A managed model reachable only from your own cloud network and region. |
| Quantisation | Storing weights in fewer bits (e.g. 8 or 4) to cut memory and cost, with some quality risk. |
| safetensors | A weight file format that cannot execute code when loaded, unlike pickle files. |
| SFT | Supervised 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 test | Randomly splitting live users between two versions to measure impact on real outcomes. |
| Adaptive rubric | A 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 coding | Grouping free-text error notes into a small set of named failure modes. |
| Baseline | The current version's scores on the same tasks, used for comparison. |
| Benchmark | A public task set used to compare models. |
| Bootstrap | Estimating uncertainty by recomputing a metric on many resamples of the data. |
| Capability eval | A 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 interval | A range likely to contain the true value of a metric (e.g. 95% CI). |
| Contamination | Test tasks or answers appearing in a model's training data, inflating scores. |
| Criteria drift | Graders' standards changing as they see more outputs (Shankar et al.). |
| Faithfulness / groundedness | Whether an answer's claims are supported by the provided context. |
| Golden dataset | A curated set of tasks with trusted expected behaviour. |
| Grader | Logic that scores one aspect of a trial (also evaluator, scorer, metric). |
| Guardrail | A runtime check that blocks or fixes an individual input or output. |
| Harness (eval) | Infrastructure that runs tasks, records transcripts, grades and aggregates. |
| Holdout | A dataset split used rarely, to detect overfitting to dev and test sets. |
| LLM-as-judge | Using a language model with a rubric to grade outputs. |
| MRR | Mean reciprocal rank: average of 1 / rank of the first relevant result. |
| nDCG | Normalised discounted cumulative gain: ranking quality with graded relevance. |
| Non-inferiority test | Checking that a new version is not worse than baseline by more than a margin. |
| Offline eval | Evaluation on a fixed dataset before release. |
| Online eval | Evaluation of sampled live production traffic. |
| Open coding | Writing free-text notes on what went wrong in each trace, without a fixed list. |
| Outcome | The final state of the environment after a trial. |
| Pairwise comparison | Asking which of two outputs is better. |
| Paired analysis | Comparing two versions per task on the same tasks, removing task-difficulty noise. |
| pass@k | Probability at least one of k attempts succeeds. |
| pass^k | Probability all k attempts succeed; a reliability metric. |
| Position bias | A judge favouring an answer because of its position in a pairwise prompt. |
| Recall@k | Share of relevant items found in the top k results. |
| Red-teaming | Deliberately attacking a system to find failures before others do. |
| Reference-free eval | Grading without a known correct answer (e.g. groundedness, format). |
| Regression eval | A suite that should pass near 100%; a drop means something broke. |
| Rogan–Gladen correction | Adjusting an observed pass rate for a judge's known TPR and TNR. |
| Saturation | When top systems pass nearly all of a benchmark, so it no longer separates them. |
| Slice | A subset of tasks sharing a property (feature, language, risk) reported separately. |
| Standard error | The typical size of the error in a metric estimate due to sampling. |
| Task | One test: an input plus success criteria (also test case, example, sample). |
| Theoretical saturation | The point in error analysis where new traces stop revealing new failure modes. |
| TPR / TNR | True positive rate and true negative rate of a judge versus human labels. |
| Trajectory | The sequence of steps and tool calls an agent took. |
| Transcript | The full record of a trial: messages, tool calls, reasoning, results (also trace). |
| Trial | One attempt at a task. |
| User simulator | An LLM playing a user with a hidden goal, to test conversational agents. |
Sources and further reading
Practice guides
- Anthropic: Demystifying evals for AI agents (Jan 2026)
- Anthropic: A statistical approach to model evaluations (error bars)
- Hamel Husain: Your AI product needs evals
- Hamel Husain & Shreya Shankar: LLM evals FAQ
- Langfuse: Error analysis to evaluate LLM applications
- OpenAI: Evals guide
- Eugene Yan: Evaluating the effectiveness of LLM-evaluators
Papers
- Zheng et al.: Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena (2023)
- Shankar et al.: Who Validates the Validators? (2024)
- Miller: Adding Error Bars to Evals (2024)
- Liu et al.: G-Eval (2023) · Verga et al.: Replacing Judges with Juries (2024)
- Wataoka et al.: Self-Preference Bias in LLM-as-a-Judge · A Survey on LLM-as-a-Judge
- Es et al.: RAGAS (2023) · Chen et al.: HumanEval and pass@k (2021)
- Yao et al.: τ-bench and pass^k (2024) · Liang et al.: HELM (2022)
Tools and cloud docs (verify current details)
Benchmarks, safety and news
- Stanford HAI: AI Index (benchmark saturation)
- Humanity's Last Exam · SWE-bench · LMArena
- Benchmark saturation and SWE-bench Verified contamination (2026 summary)
- OpenAI acquires Promptfoo (Mar 2026)
- OWASP Top 10 for LLM Applications · MITRE ATLAS
- Simon Willison: The lethal trifecta
- Gibson Dunn: EU AI Act omnibus agreement (2026)
Fine-tuning and private deployment
- Hu et al.: LoRA (2021) · Dettmers et al.: QLoRA (2023) · Rafailov et al.: DPO (2023)
- Qi et al.: Fine-tuning aligned language models compromises safety (2023)
- Re-emergent misalignment: narrow fine-tuning erodes safety alignment
- OpenAI fine-tuning page (May 2026 wind-down notice) · Tessl coverage
- Amazon Bedrock reinforcement fine-tuning for open-weight models (Feb 2026)
- Hugging Face TRL · PEFT · Unsloth
- vLLM · SGLang · llama.cpp
- CSA: Exposed self-hosted AI infrastructure (2026) · LeakIX: exposed Ollama instances
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.