404human Projects Writing Build logs Learning Books Progress
Rust · Zola
zsh · 404human@dev:~ Tab complete · ↑↓ history · type help

LLM evaluation and metrics: a practical guide

How to build an honest LLM evaluation suite—held-out cases, deterministic graders vs LLM-as-judge, decoy traps, and a runnable Python eval harness.

Published
Read time
4 min read
Kind
guide
Topics

Most teams “evaluate” an LLM change the same way: edit the prompt, try three favorite examples in a playground, think “looks better,” and ship to production. Two days later, a silent regression breaks JSON tool arguments or makes the model claim it finished a task it never ran.

LLM evaluation is just applying standard software testing discipline to a probabilistic component: freeze a realistic set of inputs, run your actual prompt + model + harness against them, grade outcomes automatically, and block regressions before they ship.

The hard part isn’t picking a fancy evaluation framework. The hard part is designing evals that cannot flatter you. Here is the practical framework and runnable Python harness we use, grounded in what we learned running hidden-test Rust exams (I made an AI read the entire Rust Book) and held-out safety checks on Personal Voice Agent.

Four rules for LLM evaluations that don’t lie

1. Keep a held-out set the prompt author never tunes on

If you tweak your prompt until all 20 examples in your test file pass, you haven’t measured generalization—you memorized those 20 examples. Split your dataset into a dev set (used while iterating) and a held-out set (opened only to score a candidate release).

On our Personal Voice Agent, automated unit tests were green after four review rounds—yet running a held-out set of 70 sentences revealed that 7% of completion claims (5 of 70) still lacked required disclosure, all of them in answers to plain questions. Only held-out cases catch blind spots like that.

2. Include decoys, impossible tasks, and negative cases

Happy-path evals hide the worst production bugs. Every serious eval suite needs:

  • Unknown / missing inputs: Ask about a record that does not exist and grade whether the model returns not_found instead of hallucinating or picking the closest enum value.
  • Decoys: In our final hidden-test Rust exam (59/59), we packed questions with plausible-looking decoys—like method names that collide with Iterator::count or retired compiler error codes—because real codebases are full of look-alike traps.
  • Untrusted / adversarial inputs: Include prompt-injection snippets inside retrieved text to verify the harness refuses unauthorized tool calls.

3. Grade with deterministic code first, LLM-as-judge second

Grader typeBest forReliabilityCost & speed
Deterministic assertions (JSON schema, exact tool name, SQL/compiler check, regex, refusal check)Tool calling, code generation, extraction, safety gatesHigh (reproducible)Free, milliseconds
Execution-based tests (run generated code against hidden unit tests)Coding agents, SQL generation, config generationHighestCheap, seconds
LLM-as-judge (rubric scoring with a separate strong model)Tone, summary faithfulness, open-ended helpfulnessMedium (calibrate against humans)Extra API tokens

Never use an LLM judge for something Python or a compiler can check deterministically. When you do use an LLM judge, require binary pass/fail criteria with explicit reasons rather than vague 1–5 star ratings, and calibrate it on 30 human-labeled examples first.

4. Track cost per acceptable result, not just accuracy

A cheaper 8B model that passes 75% of tasks on the first try and needs two retries or human cleanup can cost more than a stronger model that passes 97% cleanly. Record four LLM evaluation metrics on every run:

  1. Task pass rate (overall and broken down by slice: happy path, missing data, adversarial).
  2. Tool / schema validity rate (valid JSON + allowed tool + valid arguments).
  3. Faithfulness / ground-truth match (did the prose match the execution ledger?).
  4. Latency (p50, p95) and total tokens/cost per passing task.

A minimal, runnable LLM eval harness in Python

You don’t need a heavy vendor SDK to start running CI-gated evals. This 55-line standard-library runner grades structured outputs deterministically, computes pass rate and p95 latency, and exits non-zero if a candidate drops below your threshold:

import json
import math
import time
from typing import Callable


def percentile(values: list[float], pct: float) -> float:
    if not values:
        return 0.0
    ordered = sorted(values)
    idx = min(len(ordered) - 1, max(0, math.ceil((pct / 100.0) * len(ordered)) - 1))
    return ordered[idx]


def grade_case(case: dict, output: dict) -> tuple[bool, list[str]]:
    """Deterministic checks: expected tool, forbidden strings, and required keys."""
    reasons = []
    if "expected_tool" in case and output.get("tool") != case["expected_tool"]:
        reasons.append(f"tool={output.get('tool')} expected={case['expected_tool']}")
    text = output.get("text", "")
    for must in case.get("must_contain", []):
        if must.lower() not in text.lower():
            reasons.append(f"missing:{must}")
    for forbid in case.get("must_not_contain", []):
        if forbid.lower() in text.lower():
            reasons.append(f"forbidden:{forbid}")
    return len(reasons) == 0, reasons


def run_eval(cases: list[dict], runner: Callable[[str], dict], min_pass_rate: float = 0.90) -> dict:
    passed = 0
    latencies_ms = []
    failures = []

    for case in cases:
        t0 = time.monotonic()
        output = runner(case["input"])
        latencies_ms.append((time.monotonic() - t0) * 1000.0)
        ok, reasons = grade_case(case, output)
        if ok:
            passed += 1
        else:
            failures.append({"id": case["id"], "reasons": reasons})

    rate = passed / len(cases) if cases else 0.0
    return {
        "total": len(cases),
        "passed": passed,
        "pass_rate": round(rate, 4),
        "p95_ms": round(percentile(latencies_ms, 95), 2),
        "gate_passed": rate >= min_pass_rate,
        "failures": failures,
    }

Wire that into CI so every prompt edit, model upgrade, or tool-schema change prints the exact diff in pass rate, p95_ms, and failing case IDs before merging.

Where evals meet production observability

Offline evals catch regressions before deploy; production traffic reveals the weird edge cases you never imagined. Close the loop by pulling real failed or uncertain operations out of your AI observability timeline (with secrets redacted), turning each real bug into a permanent regression case in your eval dataset, and watching the new case fail once before fixing it.

Frequently asked questions

How many test cases do I need to start an LLM evaluation suite? Start with 30 to 50 real cases: 20 typical user requests, 10 edge/missing-data cases, 10 adversarial/refusal cases, and 10 held-out cases you don’t tune against. Grow the suite every time a real production failure occurs.

Why shouldn’t I use the same model to grade its own answers? Self-grading suffers from the same confirmation bias we see in code reviews: a model often shares the same blind spots and style preferences as the output it just produced. Prefer deterministic checks or hidden execution tests first; if you need an LLM judge, use an independent rubric calibrated against human labels.

Do I need a dedicated LLM evaluation framework? Not at the start. A JSONL file of cases plus a small Python or Rust runner in Git gives you versioned diffs, zero vendor lock-in, and fast CI runs. Add an external UI only when non-engineers (domain experts or PMs) need to label hundreds of outputs collaboratively.

Related reading