◆ AI All-in-One

Level 2 Agentic Coding · Building with AI

Evaluating LLM Applications

How to tell whether your prompt, model or agent change made things better or worse. Build a test set from real examples, grade with code where you can and with a calibrated LLM judge where you must, watch the error bars, and run it all on every change.

Level
●●●●● Easy
Reading
13 min
To learn it well
1 hour to read, a day to build your first eval set
↗ Plan a path here

Read first

Using LLM APIs

This leads to

Building AI Products
The full path from zero — 5 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Large Language Models, Explained Simply
  5. Using LLM APIs
  6. Evaluating LLM Applications

Read them roughly in this order. See it on the concept map →

Why it matters

You change one sentence in a prompt and the answer to your test question gets better. Did the app get better? Or did ten other kinds of question quietly get worse? Without measurement you can't know. Most teams building on language models go through a phase of "vibe checks": trying a handful of examples by hand after each change, shipping, and hearing about breakages from users.

An eval (short for evaluation) is an automated test of an AI application's behaviour on a set of examples, with a score you can track. Evals are what let you:

  • swap a model (a newer one, or a cheaper one) with confidence,
  • change a prompt without breaking yesterday's fixes,
  • compare a Retrieval-Augmented Generation pipeline with and without reranking,
  • tell whether an agent actually finishes tasks or only sounds as if it does.

Benchmarks like those in Evaluating LLMs and Benchmarks measure models in general. This chapter is about evaluating your application on your task, which is the only evaluation that tells you whether it works for your users. Practitioners widely regard a good eval set as the most valuable asset an AI product team builds. It outlives every prompt and model you try.

The intuition

Think of a driving examiner. They don't judge a learner by one lap of the car park. They have a fixed route with known hazards (a roundabout, a hill start, a school zone), a checklist for each one, and they mark every candidate the same way. A new driving school's methods can then be compared fairly: same route, same checklist.

An eval has the same three parts:

  1. The route is the eval set: a fixed collection of realistic inputs, including the hard cases you know about.
  2. The checklist is the graders: code, a judge model or a person deciding pass or fail for each output.
  3. The result sheet is the scores: pass rates overall and for each kind of case, compared over time.

Then comes the loop that makes it useful: when a user finds a new failure, you add that case to the route. The eval set grows to cover every mistake you have ever fixed, so none of them can quietly come back.

Eval set inputs + expected, tagged by type App version prompt + model + tools, traced Code graders schema, exact match LLM judge pass/fail on a rubric Human review a sample of outputs calibrates Scores by tag easy 1.00 → 1.00 accents 0.00 → 1.00 lowercase 0.00 → 0.00 gate Ship monitor live traffic new failures from production become new test cases block if any tag drops
Fig. 1 The eval loop. A fixed eval set runs through the application; code graders, an LLM judge and occasional human review score the outputs; scores are compared with the previous version before shipping. Failures found in production are added back to the eval set.

Key idea Start with error analysis on real outputs, turn each failure type into test cases, grade with code wherever possible, and use an LLM judge only for what code can't check, after confirming that it agrees with a human. Then run the eval on every change, like unit tests.

How it works

Step 1: look at real outputs (error analysis)

Don't start by writing metrics. Start by reading. Run your app on 50 to 100 realistic inputs, from real users if you have them, and look at every output. Write a one-line note on each failure: "invented an order number", "ignored the date", "answered in English to a French question". Then group the notes into categories and count them. This is error analysis, and it tells you what to measure. You'll often find that two or three failure types make up most of the problems, and that the metric you planned to track ("helpfulness") isn't one of them.

Step 2: build the eval set

Each case needs an input, and either an expected output or criteria for a good one. Good sources:

  • Real traffic (with personal data removed): the truest picture of what users do.
  • Failure cases from error analysis and user reports. Each fixed bug becomes a permanent test.
  • Hand-written edge cases: empty input, very long input, other languages, attempts at prompt injection, questions the app should refuse.
  • Synthetic cases written by a model when real data is scarce. Have a model vary the dimensions you care about (topic × difficulty × user type), then read the results and discard unrealistic ones. See Synthetic Data.

Tag each case ("lowercase", "two-cities", "refund-request") so you can see where a change helped or hurt. A version that improves the average while breaking all refund requests is not an improvement.

How many cases? Fewer than you fear to start (20 to 50 well-chosen ones beat none), but more than you'd think to compare versions, as the next section shows.

Step 3: choose graders

From cheapest and most reliable to most expensive:

  1. Code-based graders are ordinary functions. Is the output valid JSON matching the schema? Does it equal the expected value? Does it contain the required disclaimer? Is it under 100 words? Does the generated SQL run and return the right rows? Did the agent call issue_refund with the right amount? Use them for everything they can check. They are fast, free and deterministic.
  2. LLM-as-judge: a second model call grades the output against a written rubric. Use it for what code can't check, such as "Is the answer supported by the retrieved documents?", "Is the tone polite?" or "Does the summary miss any key point from the source?"
  3. Human review is the gold standard and the most expensive. Use it to create reference labels, to calibrate the LLM judge, and to spot-check samples of production traffic.

Writing a judge that you can trust

An LLM judge is itself a prompt, so it can be wrong. A few rules make judges far more reliable:

  • Judge one thing at a time. Use one criterion per judge call ("faithful to the sources: yes/no"), not "rate overall quality".
  • Prefer pass/fail to 1–10 scales. Models (and people) are inconsistent about the difference between a 6 and a 7. A binary decision with a written reason is easier to check and to act on.
  • Write the rubric with examples of a pass and a fail, especially borderline ones.
  • Ask for the reason first, then the verdict, so the decision follows from the reasoning.
  • Calibrate against humans. Label 50 to 100 outputs yourself, run the judge on the same outputs, and measure agreement. If the judge passes outputs you failed, fix the rubric and measure again.
  • Know the biases. The MT-Bench study (Zheng et al., 2023) found that LLM judges favour the answer shown first in pairwise comparisons, favour longer answers, and can favour their own model's style. Swap answer order and average, and don't rely on a judge to compare its own outputs with a rival's.

A worked calibration example. You label 100 outputs: 70 good, 30 bad. The judge passes 66 of the good ones and 18 of the bad ones. Its agreement with you is (66+12)/100=78%(66 + 12)/100 = 78\%, but the error that matters is that it passes 18 of 30 bad outputs (60%). A judge that lets most failures through will make every version look fine. Tighten the rubric until it catches most of the bad outputs, then re-check.

Step 4: mind the error bars

A pass rate measured on a sample is an estimate, and with small samples it is a rough one. If kk of nn cases pass, the pass rate is p^=k/n\hat p = k/n and its standard error is approximately

SE=p^ (1−p^)n\text{SE} = \sqrt{\frac{\hat p\,(1-\hat p)}{n}}

A 95% confidence interval is roughly p^±1.96×SE\hat p \pm 1.96 \times \text{SE}. Worked example: 40 of 50 cases pass, so p^=0.8\hat p = 0.8 and SE=0.8×0.2/50=0.057\text{SE} = \sqrt{0.8 \times 0.2 / 50} = 0.057. The interval is about 0.8±0.110.8 \pm 0.11, so anywhere from 69% to 91%. A new prompt scoring 86% on the same 50 cases is not clearly better.

±0 ±5 ±10 ±15 ±20 ±25 10 20 50 100 200 500 1000 ±17.5 ±11.1 ±7.8 ±5.5 ±3.5 ±2.5 number of eval cases n (log scale) 95% interval, ± points pass rate around 80%: ± 1.96·√(0.8·0.2 / n) 4× the cases → half the uncertainty
Fig. 2 Half-width of the 95% confidence interval for a pass rate near 80%, as the eval set grows. With 50 cases the true rate could be 11 points either side. Halving the uncertainty needs four times as many cases.

Two practical consequences. Comparing two versions on the same cases is more sensitive than comparing two independent scores, so look at the cases that flipped from pass to fail and back. And a big eval set is worth having for decisions that matter, such as choosing a model.

Step 5: run it on every change, and in production

  • Offline evaluation runs the eval set before shipping. Put it in continuous integration, like unit tests, and block a change that drops the score on any important tag. This is a regression test for prompts and models.
  • Online evaluation measures live traffic: user feedback (thumbs up or down, edits, retries), code checks on every response, and LLM-judge scoring of a sample.
  • Tracing records every step of every request: the prompt, retrieved documents, each tool call and result, tokens and latency. When a score drops, traces show why. For agents, also check intermediate steps (right tool, right arguments), not only the final answer.

Cost and latency are metrics too. Track tokens per request and response time alongside quality, because a better prompt that doubles the cost is a business decision, not a free win. See Building AI Products.

In code

A complete mini eval harness: an eval set with tags, two versions of an "app", code graders, and a report with error bars and failing tags. The two app versions are regular expressions standing in for "prompt v1" and "prompt v2", so the harness runs offline. In real use, app_v1 would call a model. Runs as written.

import json, math, re

CASES = [  # the eval set: input, expected value, tags for slicing
    {"msg": "My parcel to Leeds hasn't arrived since 3 May", "city": "Leeds", "tags": ["easy"]},
    {"msg": "Order for Paris, France - late!", "city": "Paris", "tags": ["easy"]},
    {"msg": "deliver to new york pls", "city": "New York", "tags": ["lowercase"]},
    {"msg": "Shipping to São Paulo is stuck", "city": "São Paulo", "tags": ["accents"]},
    {"msg": "Where is my order?", "city": None, "tags": ["no-city"]},
    {"msg": "I live in Bath but ship to Bristol", "city": "Bristol", "tags": ["two-cities"]},
]

def app_v1(msg):                        # stand-in for "prompt v1 + model"
    m = re.search(r"\b(?:to|for) ([A-Z][a-z]+)", msg)
    return json.dumps({"city": m.group(1) if m else None})

def app_v2(msg):                        # stand-in for "prompt v2 + model"
    m = re.search(r"\b(?:to|for) ((?:[A-Z]\w*\s?)+)", msg)   # multi-word names, accents
    return json.dumps({"city": m.group(1).strip() if m else None})

def grade(output, case):                # code-based grader
    try:
        city = json.loads(output)["city"]
    except (ValueError, KeyError):
        return {"valid_json": False, "correct": False}
    return {"valid_json": True, "correct": city == case["city"]}

def run_eval(app):
    results = [dict(grade(app(c["msg"]), c), tags=c["tags"]) for c in CASES]
    n, k = len(results), sum(r["correct"] for r in results)
    se = math.sqrt((k / n) * (1 - k / n) / n)
    failed = sorted({t for r in results if not r["correct"] for t in r["tags"]})
    return k / n, se, failed

for name, app in [("v1", app_v1), ("v2", app_v2)]:
    acc, se, failed = run_eval(app)
    print(f"{name}: accuracy {acc:.2f} ± {1.96 * se:.2f}   failing tags: {failed}")
# v1: accuracy 0.67 ± 0.38   failing tags: ['accents', 'lowercase']
# v2: accuracy 0.83 ± 0.30   failing tags: ['lowercase']

The tags tell the real story: v2 fixed accented and multi-word names and still fails lowercase input. The ± column tells the other half. With only six cases, 0.67 against 0.83 is not statistically convincing, so you would add cases before betting on v2.

When code can't decide, add an LLM judge. Here is one written against the Anthropic Python SDK, using structured output so the verdict is always parseable (needs an API key, so it isn't run here):

import json
import anthropic

client = anthropic.Anthropic()
RUBRIC = """You are grading a customer-support answer for FAITHFULNESS only.
PASS if every factual claim in the answer is supported by the provided policy text.
FAIL if the answer states any fact (a date, amount, rule) that the policy does not support.
Ignore tone and length. Give your reasoning first, then the verdict."""

def judge(policy: str, answer: str) -> dict:
    response = client.messages.create(
        model="claude-sonnet-5-5", max_tokens=2000, system=RUBRIC,
        messages=[{"role": "user", "content": f"<policy>{policy}</policy>\n<answer>{answer}</answer>"}],
        output_config={"format": {"type": "json_schema", "schema": {
            "type": "object",
            "properties": {"reasoning": {"type": "string"},
                           "verdict": {"type": "string", "enum": ["PASS", "FAIL"]}},
            "required": ["reasoning", "verdict"], "additionalProperties": False}}},
    )
    return json.loads(next(b.text for b in response.content if b.type == "text"))

Open-source tools such as promptfoo and Inspect (from the UK AI Security Institute), and hosted platforms for tracing and evals, package these pieces with dashboards. Build the twenty-line version first. It teaches you what you need from a tool.

Common pitfalls

  • Metrics before reading. Generic scores such as "helpfulness 4.2/5" or text-overlap scores (BLEU, ROUGE) rarely track what your users care about. Error analysis first.
  • A judge nobody checked. An uncalibrated LLM judge gives you confident numbers that may be meaningless. Measure its agreement with human labels, especially on the failures.
  • Too few cases for the decision. Six cases can catch a crash, but they can't choose between two good prompts. See the error-bar figure.
  • Overfitting the eval. If you tune prompts against the same 30 cases for weeks, you'll fit their quirks. Keep a held-out set you look at rarely, as in Training, Validation and Test Sets.
  • Stale eval sets. Users change, products change. Keep adding fresh production cases.
  • Grading only the final answer of an agent. An agent can reach the right answer by luck or through unsafe actions. Check the trace too.
  • Non-determinism ignored. The same input can give different outputs. For important cases, run them several times and report the pass rate across runs.

Watch out Never let the system under test see its own eval set. If eval cases end up in few-shot examples, retrieval indexes or fine-tuning data, the scores go up and mean nothing. This is the same data leakage that ruins classical ML evaluation, and it is easy to do by accident when everything is "just prompts".

Where it leads

A bit of history

Software testing is old. Machine learning brought the held-out test set and fixed metrics such as accuracy and F1. Language generation was always harder to score: BLEU (2002) and ROUGE (2004) counted word overlap with reference texts and correlate poorly with quality for open-ended answers. Using a strong model as a grader took off in 2023. G-Eval scored text with GPT-4 and a rubric, and the MT-Bench and Chatbot Arena work (Zheng et al.) measured how often GPT-4's judgments agreed with human preferences and catalogued judge biases. In 2024 practitioners, notably Hamel Husain, Shreya Shankar and Eugene Yan, popularised the workflow in this chapter: error analysis first, binary judges calibrated against humans, and evals as the core of iteration. Shankar et al.'s "Who Validates the Validators?" (2024) showed that people's grading criteria themselves shift as they look at more outputs, one more reason to keep reading the data. Most AI platforms now ship eval and tracing tools, and "evals" has become a standard part of the AI engineer's job.

Try it

  1. Add five cases to CASES that break app_v2 (try "to St. Ives", "to Newcastle upon Tyne", "for the Bristol office"). Write an app_v3 that fixes some of them, and check that v3 doesn't regress any old case.
  2. Change run_eval to print a pass rate for each tag, not just the list of failing tags.
  3. Using the SE formula: how many cases do you need for the 95% interval around an 80% pass rate to be ±3 points?

Hint for 3: solve 1.960.16/n=0.031.96\sqrt{0.16/n} = 0.03, so n=0.16×(1.96/0.03)2≈683n = 0.16 \times (1.96/0.03)^2 \approx 683.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You're starting evals for a new support bot. What should you do first?

  2. You need to check that an output is valid JSON with a city field equal to the expected value. Which grader should you use?

  3. You label 100 outputs (70 good, 30 bad). Your LLM judge passes 66 good and 18 bad ones. What is the main problem?

  4. Prompt v1 passes 40 of 50 cases (80%) and prompt v2 scores 86% on the same 50. Is v2 clearly better?

  5. Some of your eval cases accidentally ended up as few-shot examples in the production prompt. What happens?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Article

Your AI Product Needs Evals

Hamel Husain · 2024 · Beginner · Free

The influential practitioner's case for evals as the core of LLM product iteration: unit-test-style assertions, human and model evaluation, and looking at your data.

Article

Using LLM-as-a-Judge For Evaluation: A Complete Guide

Hamel Husain · Intermediate · Free

A step-by-step method for building a judge you can trust: a domain expert's pass/fail labels with critiques, iterating the judge prompt, and measuring its agreement with the expert.

Article

Task-Specific LLM Evals that Do & Don't Work

Eugene Yan · 2024 · Intermediate · Free

Which metrics actually track quality for classification, summarisation, translation, copyright and toxicity, and which popular ones don't.

Paper

Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena

Zheng et al. (LMSYS) · 2023 · Intermediate · Free

Shows strong LLMs agree with human preferences about as often as humans agree with each other, and catalogues judge biases (position, verbosity, self-preference).

Tool

Inspect

UK AI Security Institute · Intermediate · Free

An open-source Python framework for LLM evaluations: datasets, solvers, scorers (including model-graded), agent and tool evals, and a log viewer.

Tool

promptfoo

Promptfoo · Beginner · Free

An open-source command-line tool for testing prompts and models against test cases with assertions and LLM-graded rubrics, plus red-teaming. Runs in CI.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/building/evals-for-apps.md