Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 4: AI application systems

Chapter 16Evaluation infrastructure

35 min read, 1 lab, Advanced

A one-line prompt tweak that improves the three examples someone tried by hand can quietly break 8 percent of real queries, and nobody notices until customers do. Evaluation infrastructure is the test suite, CI gate and production monitor that catches that change before it ships, with numbers you can defend.

After this chapter you can

  • Explain why evals replace unit tests for model-driven behaviour, and where they sit in the delivery pipeline
  • Build eval datasets from golden examples, production samples and synthetic generation
  • Write programmatic scorers and validate an LLM judge against human labels
  • Size eval sets and compare variants with confidence intervals instead of single numbers
  • Run offline regression gates in CI and online evaluation on production traffic, including agents

Evals are the test suite of AI systems

A unit test asserts that a function returns an exact value. A model-driven feature returns different text for the same input, and "correct" is often a judgement. An eval is a test for that kind of behaviour: a dataset of inputs, the system under test, and scorers that grade each output, aggregated into metrics such as pass rate or recall.

Every change that can alter behaviour needs an eval run: prompts, models, retrieval settings, chunking, tool schemas, routing rules and gateway fallbacks. That is why evals belong in the delivery pipeline, not in a notebook someone runs before a launch.

The loop matters more than any single run. Failures found in production become new dataset cases, so the suite grows towards the problems your users actually hit.

Building eval datasets

SourceHow you get itStrengthWeakness
Golden setExperts write inputs with reference answers or labelsHigh-quality, covers known requirementsSlow to build, reflects the authors' imagination
Production samplingSample real traffic, stratified by feature and outcome, then labelReal distribution, real phrasingNeeds privacy review, labelling effort
Failure harvestingCases from bug reports, low ratings and escalationsTargets known weaknessesSkews towards hard cases
SyntheticA model generates questions from your documents, or variations of real casesCheap and broad coverageEasier and blander than real traffic; needs spot checks
Public benchmarksDatasets with labels, such as BEIR for retrievalFree, comparableRarely matches your domain

A few practices separate useful datasets from vanity ones:

  • Tag every case with slices such as feature, language, customer tier and difficulty, so you can see that an average held steady while one slice collapsed.
  • Version the dataset and record which version produced each result; comparing scores across dataset versions is meaningless.
  • Keep a held-out set that nobody tunes prompts against, or the suite slowly overfits to itself.
  • Scrub or synthesize personal data before production samples enter a repository.

Scorers: programmatic first, judges where needed

Use the cheapest scorer that measures what you care about.

ScorerExamplesCost and reliability
Exact matchClassification label, extracted field, multiple-choice answerFree, deterministic
ProgrammaticJSON validates against a schema, SQL runs, code passes tests, citations point to retrieved documents, recall@kFree, deterministic, needs code
Reference similarityEmbedding similarity to a reference answerCheap, weakly correlated with quality
LLM-as-judgeA model grades faithfulness, helpfulness or policy compliance against a rubricCosts tokens, must be validated
Human reviewExperts grade a sampleMost expensive; the ground truth for everything else

Making an LLM judge trustworthy

An LLM judge is a model prompted to grade another model's output. Judges are known to prefer longer answers, the first option shown and outputs from their own model family. Design them to be checkable:

  • Ask a binary question per criterion ("is every claim supported by the sources?"), not a 1 to 10 score.
  • Ask for a short rationale before the verdict, and constrain the output to a JSON schema.
  • Give the judge what a human grader would need: sources, reference answers, the rubric.

Then validate it like any classifier, against labels from a human who did not see the judge's verdicts.

  1. Collect labelled examples

    Label 50 to 200 outputs by hand, with both passes and failures. If real failures are rare, create some by injecting known errors into good answers.

  2. Split the labels

    Iterate on the judge prompt using one part and measure the final version on a part you never looked at during iteration.

  3. Measure agreement per class

    Report the true positive rate (judge passes what humans passed) and true negative rate (judge fails what humans failed) separately. Raw agreement hides a judge that passes everything when 90 percent of outputs are good.

  4. Re-validate on change

    A new judge model, prompt or output distribution means a new validation run.

Cohen's kappa summarizes agreement corrected for chance: 0 is chance level, 1 is perfect, and values above about 0.6 are usually considered substantial. If you know a judge's TPR and TNR, you can also correct its observed pass rate: true rate equals (observed rate plus TNR minus 1) divided by (TPR plus TNR minus 1).

Statistical noise and sample size

An eval score is an estimate from a sample, and small samples are noisy. For a pass rate p measured on n independent cases, the standard error is the square root of p times (1 minus p) divided by n, and a 95 percent confidence interval is roughly 2 standard errors either side.

Cases (n)95% interval at an 80% pass rate
50about plus or minus 11 points
100about plus or minus 8 points
400about plus or minus 4 points
1,000about plus or minus 2.5 points

So a change from 78 to 82 percent on 100 cases is indistinguishable from noise. Three techniques give you much more signal per case:

  • Paired comparison. Run both variants on the same cases and analyse the per-case differences. Most variance comes from case difficulty, which pairing cancels out.
  • Bootstrap confidence intervals. Resample the per-case differences thousands of times to get an interval for the mean difference without distributional assumptions.
  • Repeated trials. Run nondeterministic systems several times per case and average, or report pass^k (all k trials succeed) when consistency matters, as with agents.

Offline regression suites in CI

A regression gate runs the eval suite on every pull request that can change behaviour and blocks the merge when a metric drops significantly below the stored baseline.

Design choices that keep the gate fast, cheap and believed:

  • Tier the suite. A smoke set of 50 to 200 cases on every pull request, the full suite nightly and before releases.
  • Cache model outputs keyed by model, prompt and parameters, so unchanged cases cost nothing on reruns.
  • Gate on significance and size together. Fail when the drop exceeds a tolerance and its confidence interval excludes zero; otherwise noise blocks merges and people learn to click override.
  • Pin everything that affects scores: dataset version, judge model, temperature, seeds and the serving environment for the baseline.
  • Publish a report with per-slice metrics and the worst-regressed cases, so a failure is debuggable in minutes.
ToolShapeGood for
promptfooYAML-configured CLI with assertions, CI output and red teamingPrompt and model comparisons in CI; acquired by OpenAI in 2026 and still open source
InspectPython framework from the UK AI Security Institute: tasks, solvers, scorers, sandboxesAgent and capability evals with tool use
DeepEvalpytest-style test cases with built-in metricsPython teams who want evals next to unit tests
Langfuse, Arize PhoenixOpen-source tracing with datasets, experiments and online judgesLinking evals to production traces

Online evaluation and tracing-linked evals

Offline evals predict; production decides. Online evaluation measures behaviour on live traffic.

MethodHow it worksUse it for
A/B testRandomly split users between variants and compare outcome metricsProduct impact: task success, retention, cost per resolved ticket
Shadow trafficSend copies of real requests to the candidate, discard its responses, score them offlineRisk-free comparison on the real distribution
CanaryRoute a small percentage to the candidate with automatic rollback on guardrail breachesSafe rollout of model or prompt changes
Implicit feedbackThumbs, regenerations, copy events, escalations to humans, abandonmentCheap continuous signal, biased towards vocal users
Online judgesRun validated judges on a sample of production tracesQuality monitoring between releases

Shadow traffic needs one precaution: the candidate must never perform real side effects, so agent tools are stubbed or pointed at a sandbox.

Tracing-linked evals connect it all. Every request produces a trace with a stable ID that records retrieval results, prompts, tool calls and outputs, as described in "Observability for AI systems". Online scorers attach their verdicts to traces, low-scoring traces go to a review queue, and reviewed cases are promoted into the offline dataset with one click. The chapter "Model deployment pipelines" covers canary and shadow rollouts as deployment mechanics.

Evaluating agents and controlling eval cost

Outcome, trajectory and efficiency

Agents need more than a final-answer check, because a correct answer can hide a dangerous path and a good path can end in a wrong answer.

DimensionQuestionHow to score
OutcomeDid the world end up in the right state?Inspect the database, ledger or files after the run
TrajectoryWere the right tools called with valid arguments, without forbidden actions?Assertions on the recorded tool-call sequence
EfficiencyHow many steps, tokens and dollars did it take?Read from the trace
RobustnessDoes it succeed consistently?Run k trials per task; report pass^k

Score outcomes by state rather than by text wherever possible: "the ledger has exactly three rows totalling 21.50" is a far better check than asking a judge whether the agent's summary sounds right. Each trial needs a freshly reset environment, ideally a sandbox, so runs do not contaminate each other.

Keeping the eval bill sane

  • Use programmatic scorers wherever they suffice, and the smallest judge model that passes validation.
  • Cache outputs and judgements for unchanged cases.
  • Run the full suite with discounted batch APIs where providers offer them.
  • Sample online traffic for judges rather than scoring everything.

Key terms

Eval
A dataset, a system under test and scorers that grade outputs, aggregated into metrics.
Golden set
Hand-curated inputs with reference answers or labels that define expected behaviour.
LLM-as-judge
Using a model with a rubric to grade another model's output.
True negative rate
The fraction of human-labelled failures that a judge also marks as failures.
Cohen's kappa
Agreement between two raters corrected for the agreement expected by chance.
Paired comparison
Evaluating two variants on the same cases and analysing per-case differences.
Regression gate
A CI check that blocks a merge when eval metrics drop significantly below a baseline.
Shadow traffic
Copies of production requests sent to a candidate whose responses users never see.
Pass^k
The probability that all k independent trials of a task succeed, a measure of consistency.
Lab

Gate the RAG service with an eval harness in CI

Advanced, 150 min

Goal: add an eval harness to the RAG service from "Retrieval and vector databases", with programmatic scorers and a validated LLM judge, and make GitHub Actions block pull requests that regress it.

You need: the finished rag-lab project from that chapter in a GitHub repository, its Docker container and Ollama running, and ollama pull qwen3:4b for the judge. Everything is free; GitHub-hosted runners are free for public repositories.

  1. Make generation reproducible. In rag.py, add fixed options to the ollama.chat call so the same input gives the same answer.
rag.py (the changed call)
reply = ollama.chat(model=CHAT_MODEL, think=False,
                    options={"temperature": 0, "seed": 42}, messages=[
    {"role": "system", "content": PROMPT},
    {"role": "user", "content": f"Sources:\n{sources}\n\nQuestion: {question}"}])
  1. Build the golden set from SciFact's labelled test queries.
evals/make_golden.py
import json
import pandas as pd
 
qrels = pd.read_csv("data/test.tsv", sep="\t", dtype=str)
relevant = qrels.groupby("query-id")["corpus-id"].apply(list).to_dict()
queries = pd.read_parquet("data/queries.parquet").set_index("_id")["text"]
with open("evals/golden.jsonl", "w") as f:
    for qid in sorted(relevant, key=int):
        f.write(json.dumps({"id": qid, "question": queries[qid], "relevant": relevant[qid]}) + "\n")
mkdir -p evals && python -m evals.make_golden && wc -l evals/golden.jsonl   # 300 lines
  1. Write the scorers: retrieval metrics, a citation checker and a faithfulness judge that must answer in a fixed JSON schema.
evals/scorers.py
import json
import os
import re
import ollama
 
JUDGE_MODEL = os.getenv("JUDGE_MODEL", "qwen3:4b")
 
def recall_at_k(got, relevant, k):
    return len(set(got[:k]) & relevant) / len(relevant)
 
def mrr_at_k(got, relevant, k):
    return next((1 / r for r, d in enumerate(got[:k], 1) if d in relevant), 0.0)
 
def citation_scores(answer, retrieved_ids, relevant):
    brackets = " ".join(re.findall(r"\[([^\]]+)\]", answer))
    cited = set(re.findall(r"\d{3,}", brackets))
    return {"has_citation": float(bool(cited)),
            "citations_valid": float(bool(cited) and cited <= set(retrieved_ids)),
            "cites_gold": float(bool(cited & relevant))}
 
SCHEMA = {"type": "object", "required": ["reasoning", "verdict"], "properties": {
    "reasoning": {"type": "string"}, "verdict": {"type": "string", "enum": ["PASS", "FAIL"]}}}
RUBRIC = ("You check whether an answer is faithful to its sources. PASS if every factual "
          "claim in the answer is supported by the sources, or if the answer says the sources "
          "do not contain the answer. FAIL if any claim is missing from or contradicted by "
          "the sources. Give brief reasoning first, then the verdict.")
 
def judge_faithfulness(question, answer, contexts):
    sources = "\n\n".join(f"[{i}] {text}" for i, text in contexts.items())
    reply = ollama.chat(model=JUDGE_MODEL, think=False, format=SCHEMA,
                        options={"temperature": 0, "seed": 42}, messages=[
        {"role": "system", "content": RUBRIC},
        {"role": "user", "content": f"Sources:\n{sources}\n\nQuestion: {question}\n\nAnswer: {answer}"}])
    return json.loads(reply["message"]["content"])["verdict"] == "PASS"
  1. Label data to validate the judge. The script generates answers and, for every other question, a corrupted version with one unsupported claim, so you have failures to test against. Read the sources and label each answer yourself before you ever see what the judge thinks.
evals/label.py
import json
import random
import ollama
from common import connect
from rag import answer
 
golden = [json.loads(line) for line in open("evals/golden.jsonl")]
random.seed(1)
conn = connect()
with open("evals/labels.jsonl", "w") as out:
    for n, g in enumerate(random.sample(golden, 30)):
        res = answer(conn, g["question"])
        candidates = [res["answer"]]
        if n % 2 == 0:
            bad = ollama.chat(model="qwen3:1.7b", think=False, messages=[{"role": "user", "content":
                "Rewrite this answer, keeping its citations, but add one specific, plausible claim "
                "(a number, date or finding) that its sources do not support:\n\n" + res["answer"]}])
            candidates.append(bad["message"]["content"])
        random.shuffle(candidates)
        for text in candidates:
            print("\n" + "=" * 80)
            for doc_id, body in res["contexts"].items():
                print(f"[{doc_id}] {body}\n")
            print("QUESTION:", g["question"], "\n\nANSWER:", text)
            label = ""
            while label not in ("p", "f"):
                label = input("\nEvery claim supported? p = pass, f = fail: ").strip().lower()
            out.write(json.dumps({"question": g["question"], "answer": text,
                                  "contexts": res["contexts"],
                                  "human": "PASS" if label == "p" else "FAIL"}) + "\n")
python -m evals.label    # about 45 judgements; budget 30 to 45 minutes
  1. Validate the judge against your labels.
evals/validate_judge.py
import json
from evals.scorers import judge_faithfulness
 
rows = [json.loads(line) for line in open("evals/labels.jsonl")]
tp = tn = fp = fn = 0
for r in rows:
    judge = judge_faithfulness(r["question"], r["answer"], r["contexts"])
    human = r["human"] == "PASS"
    tp += judge and human
    tn += (not judge) and (not human)
    fp += judge and not human
    fn += (not judge) and human
n = len(rows)
tpr, tnr = tp / max(tp + fn, 1), tn / max(tn + fp, 1)
po = (tp + tn) / n
pe = ((tp + fp) * (tp + fn) + (fn + tn) * (fp + tn)) / n ** 2
kappa = (po - pe) / (1 - pe) if pe < 1 else 0.0
print(f"n={n}  TPR={tpr:.2f}  TNR={tnr:.2f}  agreement={po:.2f}  kappa={kappa:.2f}")
print(f"judge PASS: human PASS={tp} human FAIL={fp} | judge FAIL: human PASS={fn} human FAIL={tn}")
python -m evals.validate_judge

Aim for TPR and TNR both at or above about 0.8. If TNR is low, the judge is lenient: read the false passes, tighten the rubric, and re-measure. Ideally keep a third of your labels aside and check the final rubric on those only. Record the numbers in your README; they are the judge's credentials.

  1. Write the gate. It scores retrieval on 100 questions and full answers on 20, compares each metric to a stored baseline with a paired bootstrap, and fails only on a drop that is both larger than a tolerance and statistically clear.
evals/run_evals.py
import argparse, json, os, random, statistics, sys
from common import connect, hybrid_search
from rag import answer
from evals.scorers import recall_at_k, mrr_at_k, citation_scores, judge_faithfulness
 
N_RETRIEVAL = int(os.getenv("N_RETRIEVAL", "100"))
N_JUDGE = int(os.getenv("N_JUDGE", "20"))
TOLERANCE = {"recall@5": 0.02, "mrr@10": 0.02, "citations_valid": 0.10,
             "cites_gold": 0.10, "faithful": 0.10}
 
def evaluate():
    golden = [json.loads(line) for line in open("evals/golden.jsonl")][:N_RETRIEVAL]
    conn, results = connect(), {}
    for n, g in enumerate(golden):
        relevant = set(g["relevant"])
        got = hybrid_search(conn, g["question"], k=10)
        s = {"recall@5": recall_at_k(got, relevant, 5), "mrr@10": mrr_at_k(got, relevant, 10)}
        if n < N_JUDGE:
            res = answer(conn, g["question"])
            s.update(citation_scores(res["answer"], res["doc_ids"], relevant))
            s["faithful"] = float(judge_faithfulness(g["question"], res["answer"], res["contexts"]))
        results[g["id"]] = s
        print(f"{n + 1}/{len(golden)}", end="\r", file=sys.stderr)
    return results
 
def paired_bootstrap(diffs, iters=5000, seed=0):
    rng = random.Random(seed)
    means = sorted(statistics.fmean(rng.choices(diffs, k=len(diffs))) for _ in range(iters))
    return statistics.fmean(diffs), means[int(0.025 * iters)], means[int(0.975 * iters)]
 
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--baseline", default="evals/baseline.json")
    ap.add_argument("--out", default="results.json")
    ap.add_argument("--update-baseline", action="store_true")
    args = ap.parse_args()
    new = evaluate()
    json.dump(new, open(args.out, "w"), indent=1)
    if args.update_baseline:
        json.dump(new, open(args.baseline, "w"), indent=1)
        print("baseline written"); return
    base, failed = json.load(open(args.baseline)), False
    for metric, tol in TOLERANCE.items():
        ids = [i for i in new if metric in new[i] and metric in base.get(i, {})]
        if not ids:
            continue
        mean, lo, hi = paired_bootstrap([new[i][metric] - base[i][metric] for i in ids])
        regressed = mean < -tol and hi < 0
        failed |= regressed
        print(f"{metric:<16} n={len(ids):<4} new={statistics.fmean(new[i][metric] for i in ids):.3f} "
              f"base={statistics.fmean(base[i][metric] for i in ids):.3f} diff={mean:+.3f} "
              f"95% CI [{lo:+.3f}, {hi:+.3f}]  {'REGRESSION' if regressed else 'ok'}")
    sys.exit(1 if failed else 0)
 
if __name__ == "__main__":
    main()
python -m evals.run_evals --update-baseline   # writes evals/baseline.json
python -m evals.run_evals                     # every metric prints ok, exit code 0
  1. Prove the gate catches a regression locally. In common.py, change hybrid_search to use pool=5, rerun, and confirm at least one retrieval metric prints REGRESSION and echo $? shows 1. Revert the change.

  2. Add a requirements file and the workflow. The runner starts pgvector as a service container, installs Ollama, caches the models and runs the gate. On a CPU runner the whole job takes roughly 20 to 40 minutes, which is why it runs only when relevant files change.

requirements.txt
psycopg[binary]
pgvector
numpy
pandas
pyarrow
ollama
sentence-transformers
fastapi
uvicorn
.github/workflows/evals.yml
name: rag-evals
on:
  pull_request:
    paths: ["*.py", "evals/**", "schema.sql", "requirements.txt"]
  workflow_dispatch:
jobs:
  eval:
    runs-on: ubuntu-latest
    timeout-minutes: 75
    services:
      postgres:
        image: pgvector/pgvector:0.8.7-pg18
        env:
          POSTGRES_PASSWORD: rag
          POSTGRES_DB: rag
        ports: ["5432:5432"]
        options: >-
          --health-cmd "pg_isready -U postgres" --health-interval 5s --health-retries 20
    env:
      N_RETRIEVAL: "100"
      N_JUDGE: "20"
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: pip
      - uses: actions/cache@v4
        with:
          path: ~/.ollama/models
          key: ollama-nomic-qwen3-1.7b-4b
      - name: Start Ollama and pull models
        run: |
          curl -fsSL https://ollama.com/install.sh | sh
          sudo systemctl stop ollama || true
          nohup ollama serve > /tmp/ollama.log 2>&1 &
          for i in $(seq 1 30); do curl -sf localhost:11434/api/version && break; sleep 1; done
          ollama pull nomic-embed-text
          ollama pull qwen3:1.7b
          ollama pull qwen3:4b
      - run: pip install -r requirements.txt
      - name: Load corpus
        run: |
          mkdir -p data
          B=https://huggingface.co/datasets/BeIR
          curl -sL -o data/corpus.parquet $B/scifact/resolve/main/corpus/corpus-00000-of-00001.parquet
          curl -sL -o data/queries.parquet $B/scifact/resolve/main/queries/queries-00000-of-00001.parquet
          curl -sL -o data/test.tsv $B/scifact-qrels/resolve/main/test.tsv
          psql postgresql://postgres:rag@localhost:5432/rag -f schema.sql
          python ingest.py
          psql postgresql://postgres:rag@localhost:5432/rag -c \
            "CREATE INDEX docs_hnsw ON docs USING hnsw (embedding vector_cosine_ops)"
      - name: Eval gate
        run: python -m evals.run_evals --out results.json
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: eval-results
          path: results.json
  1. Commit evals/, requirements.txt, the workflow and evals/baseline.json (keep labels.jsonl too; it is your judge's validation set). Open a pull request that changes nothing behavioural, such as a comment edit in rag.py, and watch the check pass. Then open one with the pool=5 change and watch it fail.

If the unchanged pull request flags regressions, your laptop and the runner produce different outputs. Download the eval-results artifact from a run on main, commit it as the new baseline, and note in your README that baselines come from CI. Treating the environment as part of the eval configuration is the real lesson here.

Check your work: your repository shows a green eval check on a harmless pull request and a red one on the regression pull request, the failing log names the regressed metric with its confidence interval, and your README records the judge's TPR, TNR and kappa.

Stretch: add slices. Tag golden cases by query length or by whether keyword or vector search found the gold document, and make the gate report and enforce metrics per slice. Then add a nightly scheduled run on all 300 questions with N_JUDGE=100.

Check yourself

Variant B scores 81 percent and variant A 78 percent on the same 100 test cases. What is the right conclusion?

An LLM judge agrees with human labels 92 percent of the time. Ninety percent of the labelled outputs are passes. Why is this not yet evidence of a good judge?

Your CI eval gate blocks about one in five harmless pull requests, and engineers have started overriding it. What change best restores trust?

An agent eval asks a judge whether the agent's final message says the order was recorded correctly. What is the weakness?

You want to compare a new model on real production traffic without any user seeing its responses. Which method fits, and what must you guard against?

Recap

  • Evals are the test suite for model-driven behaviour and must run on every change to prompts, models, retrieval or routing.
  • Build datasets from golden cases, sampled and harvested production traffic and checked synthetic data, tagged by slice and versioned.
  • Prefer programmatic scorers; validate any LLM judge against blind human labels using TPR, TNR and kappa.
  • Small eval sets are noisy, so compare variants with paired differences and confidence intervals.
  • Gate CI on drops that are both large and significant, with everything that affects scores pinned.
  • Online, combine A/B tests, shadow traffic and judges on sampled traces, and grade agents on outcome state, trajectory and consistency.

Go deeper