CONTENTS
CHAPTER 8

Evals — The Skill That Separates Professionals from Tinkerers

6 MIN READ

If you take one chapter from this book seriously, make it this one.

Anyone can build an impressive AI demo in a weekend. The hard part, and the thing companies pay for, is knowing whether it works, on real inputs, across thousands of cases, and whether your latest change made it better or worse. That knowledge comes from evaluations (evals).

“You can’t improve what you can’t measure” is a cliché everywhere. In AI engineering it’s the whole job. Without evals, every prompt change, model upgrade, and new tool is a guess.

8.1 Why evals are different from tests

Traditional tests are deterministic: expect(add(2, 2)).toBe(4). Pass or fail.

AI evals differ in fundamental ways:

Unit tests AI evals
Deterministic Stochastic: the same input can give different outputs
Binary pass/fail Often graded, partial, or subjective
One correct output Many acceptable outputs
100% pass expected 92% might be excellent; 99% might be required for some slices
Test the code Test the system: model + prompt + tools + retrieval + data
Written once Continuously evolving as you discover new failure modes

You need both. Keep unit tests for deterministic code (parsers, tools, validators), and use evals for model behavior.

8.2 The eval-driven development loop

   ┌──────────────────────────────────────────────────────────┐
   │                                                          │
   ▼                                                          │
 Look at data ──► Find failure modes ──► Build evals ──► Change system ──► Measure
 (real outputs)   (error analysis)       for them        (prompt/tools/     (vs baseline)
                                                          model/retrieval)

This is the same loop as test-driven development, adapted for statistical systems. The most important (and most skipped) step is the first one.

8.3 Error analysis: look at your data

Practitioners like Hamel Husain and Shreya Shankar have championed this point, and it’s correct: the highest-ROI activity in AI engineering is reading outputs. Not dashboards. Actual traces.

The process:

  1. Collect 50–100 real (or realistic) traces: full inputs, intermediate steps, tool calls, outputs.
  2. Read each one and write a free-form note on what went wrong, if anything. (“Ignored the user’s timezone.” “Retrieved the wrong product version.” “Too verbose for mobile.” “Hallucinated a feature we don’t have.”)
  3. Cluster the notes into failure categories (“open coding” and then “axial coding,” borrowing from qualitative research).
  4. Count. Now you have a prioritized list: “38% timezone errors, 22% wrong doc version, 9% verbosity…”
  5. Fix the biggest categories and build automated evals for each.

This takes a few hours and routinely reveals that the problem isn’t what you assumed. Teams that skip it end up building generic metrics (“helpfulness score: 4.2/5”) that don’t correspond to anything actionable.

Build a simple trace viewer. This is a perfect task for a frontend engineer: a small internal web app that shows traces cleanly (conversation, tool calls, retrieved docs) with buttons to label good/bad and add notes. Teams that make looking at data easy look at data more. Your skills directly improve the team’s AI quality here.

8.4 Types of evals

1. Code-based (deterministic) checks

Fast, cheap, reliable. Use them wherever possible.

  • Output parses as valid JSON matching the schema.
  • Required fields present; values in allowed ranges.
  • Exact match or regex for classification labels, extracted IDs, dates.
  • The right tool was called with the right arguments.
  • Generated code compiles, and tests pass (the gold standard for coding tasks).
  • Response length under a limit; no banned phrases; contains a citation.

2. LLM-as-judge

For subjective or open-ended qualities (faithfulness, tone, helpfulness, policy compliance), use a model to grade outputs.

JUDGE_PROMPT = """You are evaluating a fitness-app assistant's response for FAITHFULNESS.

<training_data>{tool_results}</training_data>
<response>{response}</response>

A response is FAITHFUL if every factual claim about the user's training is directly
supported by the training data. General advice (not about their data) doesn't count.

First, list each claim about the user's data and whether it is supported.
Then output a verdict: PASS if all claims are supported, otherwise FAIL.

Output JSON: {{"claims": [{{"claim": str, "supported": bool}}], "verdict": "PASS"|"FAIL"}}"""

Making LLM judges trustworthy:

  • Binary or low-cardinality judgments (pass/fail, or a small rubric) beat 1–10 scales. Models, like humans, are inconsistent on fine-grained scales.
  • One criterion per judge. Separate judges for faithfulness, tone, and completeness, rather than a single “quality” score.
  • Ask for reasoning before the verdict.
  • Validate the judge against human labels. Hand-label 100+ examples, and measure agreement (true positive and true negative rates, not just accuracy). Iterate on the judge prompt until agreement is high. An unvalidated judge is just another unverified model.
  • Watch for known biases: position bias in pairwise comparisons (swap the order and average), verbosity bias (preferring longer answers), and self-preference (favoring outputs from the same model family).

3. Human evaluation

The ground truth, and expensive. Use it to build labeled datasets, validate LLM judges, and periodically audit production. Domain experts beat generic annotators for anything specialized: a physiotherapist for injury advice, a lawyer for contracts.

4. Pairwise / preference evals

“Is output A or B better?” is often easier and more reliable to judge than absolute scoring. Useful for comparing prompt versions or models.

8.5 Building your eval dataset

Your dataset is your most valuable AI asset. Treat it like production code.

Sources:

  • Production traffic (with privacy safeguards): the most representative. Sample across user types, features, and edge cases.
  • Failure cases from error analysis and user reports. Every bug becomes a regression test.
  • Synthetic data: use a strong model to generate varied inputs. Do it systematically: define dimensions (user persona × query type × difficulty × edge condition) and generate combinations, rather than asking for “50 test questions,” which yields bland, homogeneous data.
  • Adversarial cases: prompt injections, out-of-scope requests, ambiguous inputs, hostile users.

Structure:

{"id": "tz-001", "input": {...}, "expected": {...}, "tags": ["timezone", "edge"], "source": "prod-2026-10"}
{"id": "inj-004", "input": {...}, "expected": {"refuses_injection": true}, "tags": ["security"]}

Tag everything so you can measure performance by slice. An overall 94% can hide 60% on Android users or on non-English queries.

Size: start with 50–100 high-quality cases. Grow to hundreds or thousands as you find new failure modes. Quality and coverage matter more than volume.

Keep a held-out set. If you iterate on prompts against the same examples endlessly, you’ll overfit to them. Keep a separate set you check only occasionally.

8.6 Evaluating agents

Agents are harder to evaluate because the path varies and tasks are long. Approaches:

  • Outcome-based: Did the end state match the goal? (Tests pass, the file has the right content, the database row exists, the booking was made.) Prefer this. Agents may find valid paths you didn’t anticipate.
  • Trajectory-based: Were the steps reasonable? (Didn’t delete things unnecessarily, didn’t take 40 turns for a 5-turn task, called tools correctly.) Use these as secondary metrics and safety checks.
  • Environment-based: Build sandboxed, resettable environments (a fake company’s database, a mock email inbox, a repo snapshot) where the agent can act freely and you can check the outcome automatically. Benchmarks like SWE-bench (real GitHub issues verified by tests), τ-bench (customer-service agents with simulated users), and Terminal-Bench follow this pattern.
  • Run multiple trials. Agent performance varies run to run. Report pass rates over several attempts. “pass@k” (succeeds in at least one of k tries) and “pass^k” (succeeds in all k tries) answer different questions. For a production agent users rely on, consistency (pass^k) often matters more.
  • Track cost and latency alongside success. An agent that succeeds 2% more often at 3× the cost may be a regression.

8.7 Evals in your workflow

  • CI integration: run a fast eval subset on every PR that touches prompts, tools, or model config. Run the full suite nightly or before releases.
  • Compare against baseline, not absolute numbers. Show per-case diffs: which cases newly pass, which newly fail.
  • Model upgrades: when a new model drops, your eval suite tells you within hours whether to switch, and which prompts need adjusting. Teams without evals spend weeks on vibes-based testing or upgrade blindly.
  • Production monitoring: run cheap automated checks and sampled LLM judges on live traffic. Track user signals (thumbs, edits, retries, abandonment). Feed failures back into the dataset.

Tooling: Braintrust, Langfuse, LangSmith, Arize Phoenix, promptfoo, Inspect (from the UK AI Security Institute, popular for research-style evals), or a homegrown setup: a JSONL dataset, a Python runner, and a results table. Start simple; the discipline matters more than the tool.

8.8 A minimal eval harness

import json, asyncio
from statistics import mean

async def run_case(case, system):
    output = await system(case["input"])
    results = {
        "schema_valid": check_schema(output),
        "label_correct": output.get("label") == case["expected"]["label"],
        "faithful": (await judge_faithfulness(case, output))["verdict"] == "PASS",
    }
    return {"id": case["id"], "tags": case["tags"], **results, "output": output}

async def run_eval(path, system, trials=3):
    cases = [json.loads(l) for l in open(path)]
    runs = await asyncio.gather(*[run_case(c, system) for c in cases for _ in range(trials)])
    for metric in ["schema_valid", "label_correct", "faithful"]:
        print(f"{metric:15s} {mean(r[metric] for r in runs):.1%}")
    # also: breakdown by tag, diff against the last baseline run, save all outputs for review
    return runs

Fifty lines of code and a well-curated dataset put you ahead of a surprising number of teams shipping AI features.

Key takeaways

  • Evals are the core professional skill in applied AI. They turn guessing into engineering.
  • Start with error analysis: read real traces, categorize failures, count them. Build tooling that makes this easy (a great frontend contribution).
  • Prefer deterministic code checks; use LLM judges for subjective criteria, with binary verdicts, one criterion each, and validation against human labels.
  • Your dataset is a core asset: real traffic, failures, systematic synthetic data, adversarial cases, all tagged by slice.
  • Evaluate agents by outcome first, over multiple trials, tracking cost and latency.
  • Wire evals into CI, model-upgrade decisions, and production monitoring.

Exercises

  1. Take an AI feature you’ve built (or the RAG system from Chapter 6). Collect 50 outputs and do a full error-analysis pass. Produce a ranked failure-category table.
  2. Build a trace viewer in React that loads a JSONL file of traces and lets you label each pass/fail with notes.
  3. Write an LLM judge for one subjective criterion. Hand-label 60 examples, measure judge–human agreement, and iterate on the judge until it agrees on at least 90% of cases.
  4. Set up a GitHub Action that runs your eval suite on PRs touching prompts/ and posts a summary comment with metric diffs against main.