Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Generative AI & LLM · Chapter 11 / 20

Generative AI & LLM

Evaluation methodology and datasets

An evaluation (eval) is a repeatable measurement of the quality of an LLM feature: a dataset of cases, the system under test, scorers that judge every output, and a rule that turns the scores into a decision. Unit tests with fake models keep the code around the model correct; evaluations measure what the model does inside the product.

Most weak evaluation suites fail before any metric is chosen: they measure generic qualities nobody needs, on cases nobody uses, against labels nobody agreed on. This chapter covers the method that prevents that: success criteria, error analysis, building and maintaining datasets, labels and agreement, overfitting and contamination, running evaluations, frameworks, and reading results. The next chapters cover the instruments: code-based scorers, LLM-as-a-judge and statistics.

Prerequisites: Why LLM testing is different, Testing LLM code without the model.

Tests and evaluations

AspectClassic testEvaluation
Expected resultOne exact oracleA scoring rule: assertion, metric, rubric or human label
OutcomePass or failA verdict per case, aggregated into rates per slice
DeterminismExpected to be stableRun-to-run variation is normal and must be measured
PurposeProve that a requirement holdsMeasure quality, compare versions, catch regressions
SizeOne case per behaviourDozens to thousands of cases per behaviour

Every evaluation has the same five parts:

evaluation = dataset      cases: inputs plus what is needed to judge them (facts, labels, references, tags)
           + task         the system under test, called the same way as in production
           + scorers      code, model judges or people, each returning a verdict with a reason
           + aggregation  pass rates overall and per slice, with their uncertainty
           + decision     a rule fixed in advance that turns results into ship, block or investigate

The evaluation loop

Evaluation is not a phase at the end of a project. It is a loop that starts before the first prompt is written and continues in production:

1. Success criteria    What must be true for users and the business?
        ↓
2. Error analysis      Read real outputs; name and count what goes wrong
        ↓
3. Dataset             Cases that represent real use and the failures found
        ↓
4. Scorers             One check for each criterion and failure category
        ↓
5. Baseline            Run the current version; it is the reference
        ↓
6. Iterate             Change prompts, models or retrieval; compare with the baseline
        ↓
7. Gate and monitor    Run in CI, sample production; new failures return to step 2

Working this way is called eval-driven development. The loop restarts whenever the product, the model or the users change.

Success criteria

A criterion that can be evaluated names what must be true, how it is measured, the threshold and its priority (Why LLM testing is different shows how to derive criteria from risks). For the support assistant used throughout this course:

CriterionMeasured byThreshold
States the return and refund policy correctlyFact scorer on 300 policy questionsAt least 95%
Never invents a policyJudge validated against human labelsAt most 1%
Replies in the language of the customerCode-based scorer on every case100%
Looks up the order when an order number is givenCheck of the tool calls in the traceAt least 98%

Prefer binary criteria, pass or fail, to scores from 1 to 5. Two reviewers rarely agree on whether an answer is a 3 or a 4, a middle score hides what is wrong, and a pass rate is easy to track. If quality has several aspects, write one binary criterion per aspect.

Error analysis

Error analysis is the step most teams skip and the one that decides whether the evaluation measures anything useful. It borrows two techniques from qualitative research:

  1. Collect traces: 100 or more real or realistic inputs, each with the full trace: input, retrieved context, tool calls, output.
  2. Open coding: read each trace and write a short free-text note about the first thing that went wrong. Upstream errors cause downstream ones, so a wrong retrieval is noted, not the wrong answer it produced.
  3. Axial coding: group the notes into a small failure taxonomy with clear, non-overlapping names.
  4. Count and prioritize: how often each category occurs, weighted by how much harm it does.
  5. Act: turn the top categories into scorers and dataset cases.

One domain expert who understands the users should own the judgement; a committee produces inconsistent labels. Keep reading new traces until they stop revealing new categories, which qualitative researchers call saturation.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

19 of 40 traces have a problem
category              traces  severity  priority
invented policy            5         3        15
missing citation           6         2        12
missed order lookup        3         3         9
too long                   4         1         4
wrong language             1         2         2
new categories appeared at traces [2, 3, 5, 8, 13] and none in the last 27

The most frequent problem, missing citations, is not the most important one: invented policies are rarer but more harmful. Every category also suggests its instrument. An invented policy needs a fact scorer or a validated judge; a missed order lookup is a deterministic check of the tool calls in the trace; "too long" is a word count. A generic "helpfulness" score from a framework would have measured none of them.

Building an evaluation dataset

A dataset should represent real use, contain the failures you know about, and cover the slices you care about. Each source contributes something different:

SourceGives youWatch out for
Samples of production trafficThe real mix of requests and wordingsPersonal data; easy, frequent requests dominate
Failures from error analysis and incidentsCases known to breakPast failures only; add them, do not build only from them
Edge casesEmpty, very long, mixed-language, ambiguous inputsCan drift away from real use
Adversarial casesPrompt injection, jailbreaks, off-topic requestsBelong to a separate security suite
Synthetic casesCoverage of rare combinationsUnnatural wording; every case needs review

Store one case per line in a versioned file. Besides the input, a case carries what its scorers need and the tags its results are sliced by:

{"id": "refunds-0042", "input": "Can I return shoes after 40 days?", "expected_facts": ["return-window-30-days", "counted-from-delivery"], "forbidden": ["promises-exception"], "tags": {"lang": "en", "intent": "returns", "difficulty": "policy-boundary"}, "source": "production-2026-09", "added": "2026-10-02"}

The script builds a dataset from a production log in four steps:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

2000 logged messages, 1320 after removing duplicates
delivery           506 in the log,  46 in the sample
refunds            311 in the log,  28 in the sample
returns            424 in the log,  39 in the sample
account deletion    79 in the log,  10 in the sample
123 cases: {'dev': 87, 'test': 36}
scrubbed example: Refund A-7388 to <email> please

Why each step matters:

  • Personal data is removed first, so it never reaches the dataset, its version history or the reports built from it.
  • Duplicates distort results. A third of this log repeats other requests; one wrong answer to a popular question would otherwise count dozens of times. Near-duplicates (the same question with small wording changes) need a similarity check, which the example project implements.
  • A purely proportional sample starves rare slices. Account deletion is about 6% of traffic and would get 7 cases; with a minimum of 10 its pass rate can at least show a collapse. Report slices separately, because the overall rate weights them by their sample size, not by their importance.
  • Hash-based splits are stable. Adding cases or shuffling the file never moves a case between the development set and the test set.

Rules for keeping a dataset useful:

  • Version it next to the prompts and scorers, and store the dataset version with every result.
  • Tag every case by language, intent, difficulty and source, so that results can be sliced.
  • Grow it with every production failure and retire cases that no longer represent the product.
  • Document it: where the cases come from, how they were labelled, and the known gaps, in the spirit of datasheets for datasets.

Synthetic cases with coverage

Production samples miss rare combinations: an angry customer asking two questions in Ukrainian may never appear in a month of logs. Synthetic cases fill such gaps when they are generated systematically: choose the dimensions that change behaviour, choose combinations of their values, generate inputs for each combination with a model, and review every generated case.

All combinations quickly become too many. Combinatorial testing offers a classic answer: many defects are triggered by the interaction of two factors, so a set of cases that covers every pair of values catches them with far fewer cases.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

all combinations: 54, value pairs to cover: 45
cases that cover every pair of values: 9
  new customer | return | en | simple
  new customer | refund | uk | ambiguous
  regular customer | return | uk | two questions
  regular customer | delivery | en | ambiguous
  angry customer | refund | en | two questions

Nine combinations cover every pair that 54 would. Each combination becomes a short instruction for a generator model ("write the message of an angry regular customer asking two questions about a refund, in Ukrainian"), usually with several inputs per combination. A person reviews every generated case before it enters the dataset: generated text tends to be cleaner and more explicit than real messages, and a model should not be the only judge of cases it wrote.

Labels and reference answers

What a case stores as its expected result depends on the task:

Expected resultFitsScored by
Exact labelClassification, routing, extractionExact match, classification metrics
Expected and forbidden factsFree-text answers about known factsFact-based scorers
Reference answerTranslation, rewriting, summarizationOverlap or similarity metrics, with care
Grading notesOpen-ended answersA validated judge or a person

Labels need written guidelines with examples of borderline cases. To find out whether the guidelines work, let two people label the same sample and measure their agreement. Raw agreement is misleading when one label is rare, so the standard measure, Cohen's kappa, subtracts the agreement expected by chance:

observed agreement   p_o = share of cases with the same label
chance agreement     p_e = Σ over labels of (share of reviewer 1) · (share of reviewer 2)
Cohen's kappa        κ = (p_o − p_e) / (1 − p_e)        1 = perfect, 0 = no better than chance
Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

raw agreement 87%, agreement expected by chance 82%, kappa 0.26
failures found: reviewer 1 3, reviewer 2 3, both 1

An 87% agreement sounds good, but two reviewers who mark almost everything as passing agree that often by chance. The kappa of 0.26 shows what matters: of five answers that someone marked as failing, the reviewers agree on one. Before labelling hundreds of cases, discuss exactly these disagreements, sharpen the criterion and its examples, and measure again. The same measure later validates model judges against human labels (LLM-as-a-judge).

Splits, overfitting and contamination

  • Development and test sets. Iterate on prompts against the development set; use the held-out test set for decisions, and look at its individual cases rarely. When the development score rises and the test score does not, the prompt has been fitted to the development cases.
  • Few-shot examples taken from evaluation cases inflate scores: the model has seen the answers. Keep examples in prompts and evaluation cases in disjoint sets, and check the overlap automatically.
  • Contamination. Public benchmarks and their answers can be part of the training data of the model under test, which makes scores on them unreliable. Private cases built from your own product are much less exposed; refresh them over time.
  • A metric that becomes a target stops measuring. When the team optimizes one number, read samples of outputs regularly to confirm that the number still means what it did.

Layers of checks

Checks belong to the cheapest layer that can make them reliably:

            /  production monitoring  \      live traffic, online scorers, user feedback
           /     human review          \     expert labels on samples
          /   model-graded evaluation   \    LLM-as-a-judge validated against people
         /  reference-based metrics      \   facts, overlap, retrieval metrics
        /  deterministic assertions       \  schema, patterns, length, citations, cost, latency
       /  unit tests with a fake model     \ parsing, routing, retries, tool loops

Lower layers are cheap, fast and repeatable; upper layers are expensive and noisy but closer to what users experience. Never ask a model judge whether an output is valid JSON, and never trust a judge that was not compared with human labels.

Running evaluations

An evaluation run is an experiment. Record enough to reproduce it and to explain its results:

Recorded itemWhy
Dataset version and case IDsTo know exactly what was measured
Model ID, prompt version and parametersTo know exactly what was evaluated
Scorer versionsResults are comparable only under the same scorers
Raw outputs and tracesTo re-score without re-running the model, and to read failures
Seeds, timestamps, cost and latencyTo reproduce the run and to watch the budget

Practical rules for the harness:

  • Separate generation from scoring. Store outputs once, then score them as often as scorers change.
  • Cache model calls by model, prompt version, parameters and input, so that unchanged cases cost nothing on the next run.
  • Run cases concurrently within the provider's rate limits, and retry only transient errors (LLM application anatomy and APIs).
  • Keep runs immutable. A run that was re-scored or partly re-generated is a new run.

Evaluation frameworks

Frameworks provide datasets, runners, caching, built-in scorers, reports and CI integration. The concepts in this chapter apply to all of them:

ToolStyleGood fit
promptfooYAML configuration and a command-line runner; assertions from substring checks to custom code and model gradersComparing prompts and models in CI
DeepEvalTest cases and metrics in the style of pytestTeams whose tests already live in pytest
Inspect AIPython tasks made of datasets, solvers and scorers; sandboxes for agentsAgent and capability evaluations
OpenAI EvalsA registry of evaluation templates and benchmarksBenchmark-style evaluations
Platforms such as Braintrust, Langfuse or PhoenixDatasets, experiments and production traces with a review interfaceTeams that need annotation and tracing in one place

A promptfoo configuration for two of the refund cases, comparing two prompt versions:

description: Support assistant, refund policy
prompts:
  - file://prompts/support-answer/v13.txt
  - file://prompts/support-answer/v14.txt
providers:
  - id: anthropic:messages:claude-sonnet-5-5   # pin the exact model you ship
    config:
      temperature: 0
tests:
  - vars:
      question: Can I return shoes after 40 days?
    assert:
      - type: icontains
        value: 30 days
      - type: not-icontains
        value: exception
  - vars:
      question: Чи можна повернути взуття через 40 днів?
    assert:
      - type: icontains
        value: 30 днів
      - type: llm-rubric
        value: Answers in Ukrainian and says that the 30 days start at delivery

The same check as an Inspect AI task:

# Run on your own machine: pip install inspect-ai
# then: inspect eval refunds.py --model anthropic/claude-sonnet-5-5
from inspect_ai import Task, task
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import generate, system_message


@task
def refunds():
    return Task(
        dataset=[Sample(input="Can I return shoes after 40 days?", target="30 days")],
        solver=[system_message("You are the support assistant of an online shoe store."), generate()],
        scorer=includes(),
    )

Choose one framework for offline evaluations, keep custom scorers as plain functions that you can test on their own, and avoid built-in metrics whose definition you cannot explain.

Reading results: scorecards and flipped cases

A result is a comparison with the baseline, not a single number. The aggregate is the least informative part of it:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

pass rate: baseline 75%, candidate 75%, change +0%
fixed (fail to pass): ['c02', 'c04']
broken (pass to fail): ['c09', 'c11']
lang=en: baseline 5/8, candidate 7/8
lang=uk: baseline 4/4, candidate 2/4

"No change" hides two fixes and two new failures, both in Ukrainian. Read every flipped case before approving a change: flips show what the change really did, and a cluster of flips in one slice is a regression even when the average is flat. Whether a difference is larger than noise is a statistical question (Statistics for evaluation).

Example project

The method of this chapter is implemented and tested in examples/llm-testing/08-evaluation-methodology: an error-analysis report with priorities and saturation, a dataset builder that scrubs personal data, removes duplicates and near-duplicates, samples by slice and splits by hash, a dataset validator that finds schema errors, duplicate IDs, leakage between splits and thin slices, a pairwise generator for synthetic case specifications, an agreement report for labels, and an evaluation runner with a response cache, a run manifest and a scorecard of flipped cases. All tests run offline, without a model or API keys:

uv sync --project examples/llm-testing
uv run --project examples/llm-testing pytest examples/llm-testing/08-evaluation-methodology

Common mistakes

  • Choosing metrics before reading outputs, which produces generic scores that miss the real failures.
  • Scales from 1 to 5 without anchors instead of binary criteria with examples.
  • A dataset of easy, frequent cases that reports a high pass rate and says nothing about rare slices.
  • Duplicates and personal data in the dataset.
  • Synthetic cases that nobody reviewed.
  • Labels without guidelines or an agreement check.
  • Tuning prompts on the test set, or few-shot examples copied from evaluation cases.
  • Unrecorded runs: no dataset, prompt, model or scorer version stored with the results.
  • Approving a change from the average without reading the flipped cases.

Summary

  • An evaluation is a dataset, a task, scorers, aggregation and a decision rule fixed in advance.
  • Start from success criteria and error analysis: read traces, code the failures, count them, prioritize by frequency and severity, and read until saturation.
  • Build datasets from production samples, known failures, edge cases and reviewed synthetic cases; scrub personal data, remove duplicates, stratify by slice and split by hash.
  • Generate synthetic cases from dimensions; pairwise coverage keeps their number small.
  • Store the expected result that fits the task, write labelling guidelines, and check agreement with Cohen's kappa.
  • Keep a held-out test set, keep few-shot examples out of the evaluation, and prefer private cases to public benchmarks.
  • Record every run fully, separate generation from scoring, and read flipped cases and slices, not just the average.

Source registry

17 chapter references
Your AI Product Needs Evals

Practitioner account of evaluation-driven development, error analysis and the levels of LLM evaluation.

Hamel Husain · article
Source ↗
AI Evals: Everything You Need to Know

Error analysis with open and axial coding, theoretical saturation, binary pass/fail criteria and one domain expert as the owner of quality.

Hamel Husain and Shreya Shankar · article
Source ↗
A Field Guide to Rapidly Improving AI Products

Looking at data, simple annotation tools and making evaluation part of everyday product work.

Hamel Husain · article
Source ↗
Who Validates the Validators? Aligning LLM-Assisted Evaluation of LLM Outputs with Human Preferences

Criteria drift: evaluation criteria become clear while grading outputs, so criteria, labels and scorers evolve together.

Shankar et al. — arXiv / UIST 2024 · paper
Source ↗
Define success criteria and build evaluations

Compares code-based, human and model-based grading and shows when exact and string matching are enough.

Anthropic · official docs
Source ↗
Datasheets for Datasets

Documenting how a dataset was collected, labelled and should be used.

Gebru et al. — arXiv / Communications of the ACM 2021 · paper
Source ↗
Holistic Evaluation of Language Models

Evaluation as a matrix of scenarios and metrics, reported per scenario instead of as one number.

Liang et al. — arXiv / TMLR 2023 · paper
Source ↗
NLP Evaluation in trouble: On the Need to Measure LLM Data Contamination for each Benchmark

Benchmark data in the training data of a model makes its scores unreliable; contamination has to be measured.

Sainz et al. — arXiv / Findings of EMNLP 2023 · paper
Source ↗
A Coefficient of Agreement for Nominal Scales

Cohen's kappa: agreement between two raters corrected for the agreement expected by chance.

Jacob Cohen — Educational and Psychological Measurement 1960 · paper
Source ↗
The Measurement of Observer Agreement for Categorical Data

The conventional verbal scale for kappa values, from slight to almost perfect agreement.

Landis and Koch — Biometrics 1977 · paper
Source ↗
Practical Combinatorial Testing (SP 800-142)

Pairwise and t-way combinatorial testing; most failures are triggered by interactions of few factors.

NIST · official docs
Source ↗
Intro

Configuration-driven evaluation of prompts and models with a command-line runner suited to CI.

promptfoo · tool
Source ↗
Assertions and metrics

Deterministic assertions such as contains, regex and is-json, plus custom JavaScript and Python assertions.

promptfoo · tool
Source ↗
DeepEval

LLM test cases and metrics in the style of pytest.

Confident AI · tool
Source ↗
Inspect

Evaluation tasks made of datasets, solvers and scorers, with sandboxes for agent evaluations.

UK AI Security Institute · tool
Source ↗
openai/evals

A framework and registry of evaluation templates and benchmarks.

OpenAI · tool
Source ↗
Patterns for Building LLM-based Systems & Products

Evaluations as the first pattern of LLM products and their relation to the other patterns.

Eugene Yan · article
Source ↗