Format
Deep Engineering
Written for
For engineers and technical leads
Thread
AI Without the Hype
AI & Machine Learning

Evaluate First: Building the LLM Evaluation Set Before You Build the Feature

Most LLM features are tuned by trying a handful of prompts until the demo looks right. This issue builds the evaluation set and harness that should exist before the first prompt is written.

Khalid Aboubakr
9 min read
Under the HoodLlmArtificial IntelligenceTesting

An LLM feature without an evaluation set has no working definition of "better". The usual workflow, adjusting a prompt in a playground against a handful of inputs until the output looks right, produces a feature that ships and then cannot be changed safely. When the provider releases a cheaper model, a retrieval setting is tweaked or a template gains a sentence, nobody can say whether quality went up, went down, or went down only for one kind of input, because the only test set that ever existed was a few examples in somebody's head. LLM evaluation closes that gap with a versioned set of cases, graders that score them and a harness that runs on every change. The cheapest time to build it is before the feature, because writing the cases also shows whether the feature is defined well enough to build. The running example below is a feature that summarises support tickets.

Define what correct means before writing a prompt

An evaluation set is only as useful as the definition of success it encodes. "The summary should be good" cannot be tested. "The summary states the customer's request in the first sentence, mentions every product named in the ticket, contains no information absent from the ticket, and stays under 80 words" can be tested, most of it automatically.

Write the success criteria as separate, checkable properties rather than one overall judgement. Typical properties fall into a few families: format (valid JSON, required fields present, length limits), faithfulness (no claims that are not supported by the input or the retrieved sources), coverage (the facts that must appear do appear), behaviour (refuses out-of-scope requests, asks for clarification when the input is ambiguous, does not follow instructions embedded in user content), and tone or policy constraints. Each property becomes a grader later, and each one can fail independently, which is what makes regressions diagnosable.

This step also forces a product conversation that many AI projects skip. If the team cannot agree on what a correct answer looks like for twenty real inputs, the problem is not the model; it is that the feature is not yet defined. Many of the patterns in why AI projects fail in production trace back to exactly this gap.

Building the LLM evaluation set

Where the cases come from

The best source is real inputs: actual tickets, documents, messages or queries, with personal data removed or the use approved. If the product does not exist yet, use the closest real material the business has, such as emails that will later arrive through the feature. Domain experts then write the expected properties for each case, and, where it helps, a reference answer. Synthetic cases generated by a model are useful for volume and for edge cases that are rare in real data, but they should be labelled as synthetic and reviewed, because a model tends to generate inputs that another model finds easy.

What the set must cover

A set that only contains typical inputs measures the happy path. Deliberately stratify it, and tag each case so results can be broken down:

  • common cases in roughly the proportions you expect in production;
  • edge cases: very long or very short inputs, mixed languages, poor formatting, missing information;
  • out-of-scope inputs the feature should decline or route elsewhere;
  • adversarial inputs, including instructions hidden in user content that try to override the system prompt;
  • ambiguous cases where even human experts disagree, so you know where the ceiling is.

Anthropic's documentation on building evaluations makes a point that runs against intuition: more cases with slightly lower-signal automated grading are better than a few cases with careful human grading. Start with dozens of cases, not thousands, and grow the set every week the feature exists.

How a case is stored

Store cases as data under version control, next to the code, in a format any script can read. JSON Lines works well:

{"id": "tkt-0142", "tags": ["billing", "arabic"], "input": "…ticket text…", "expected": {"must_mention": ["refund", "invoice 4471"], "max_words": 80, "language": "ar"}} {"id": "tkt-0187", "tags": ["out-of-scope"], "input": "…ticket text…", "expected": {"must_decline": true}}

Two rules protect the set's value. Keep a held-out portion that is never looked at while tuning prompts, otherwise the prompt is gradually fitted to the test set and the scores stop meaning anything. And never copy evaluation cases into the prompt as few-shot examples; that guarantees a good score on those cases and tells you nothing.

Graders: code first, models where judgement is needed

Every property should be graded by the cheapest reliable method. Code-based graders, such as schema validation, exact or normalised match, regular expressions, length checks and "does every cited ID exist in the retrieved documents", are fast, deterministic and free. They should cover as much as possible.

import json def parse(output): try: data = json.loads(output) except json.JSONDecodeError: return None return data if isinstance(data, dict) else None def summary_of(output): summary = (parse(output) or {}).get("summary") return summary if isinstance(summary, str) else "" def valid_output(case, output): data = parse(output) return data is not None and {"summary", "category"} <= data.keys() def mentions_required(case, output): text = summary_of(output).lower() return all(term.lower() in text for term in case["expected"].get("must_mention", [])) def within_length(case, output): limit = case["expected"].get("max_words") return limit is None or len(summary_of(output).split()) <= limit

Properties such as faithfulness or whether a refusal was appropriate need judgement, and that is where a model used as a grader earns its place. LLM judges are useful and biased in measurable ways. The MT-Bench study by Zheng and colleagues documented position bias (preferring whichever answer is shown first in a comparison), verbosity bias (preferring longer answers) and self-enhancement bias (favouring answers the judge model generated itself). The mitigations are practical. Give the judge a specific rubric per property and ask for a constrained verdict, pass or fail, rather than a score out of ten. In pairwise comparisons, run both orders and only count consistent verdicts. Use a different model from the one being evaluated where possible. And before trusting a judge, grade a sample of cases by hand and measure how often the judge agrees with the humans. A judge that agrees with your experts on most cases is a scalable instrument; one that does not is noise with a confident tone.

Human review remains part of the loop, but as calibration and as the final check on a sample, not as the main grading mechanism.

Nondeterminism and small numbers

The same input can produce different outputs from the same model, especially at non-zero temperature. Run each case several times and record a pass rate per case, not a single pass or fail. A case that passes two runs out of three is a different problem from one that always fails.

Be careful with differences between variants. On a set of 50 cases, a single case changing outcome moves the overall pass rate by two percentage points, so a prompt that scores 84% against a baseline of 82% has not demonstrably improved anything. Compare variants on the same cases, look at which cases changed, and read them. Breaking results down by tag usually tells you more than the headline number: a change that improves common cases while breaking every out-of-scope case is a regression, whatever the average says.

Pin the model version in configuration. Most providers offer dated or versioned model identifiers alongside aliases that move. Evaluation results only describe the exact model, prompt and parameters they were produced with, and a moving alias silently invalidates them. If you want to understand why the same model can vary between runs and how context length affects behaviour, how large language models actually work covers sampling and context windows in more depth.

The harness

The harness is small. It loads cases, calls the feature exactly as production does, through the same prompt templates, retrieval and post-processing, runs the graders, and aggregates.

import json from collections import defaultdict def load_cases(path): with open(path, encoding="utf-8") as f: return [json.loads(line) for line in f if line.strip()] def run_eval(cases, generate, graders, samples=3): results = [] for case in cases: for i in range(samples): output = generate(case["input"]) checks = {name: grade(case, output) for name, grade in graders.items()} results.append({"id": case["id"], "tags": case["tags"], "sample": i, "passed": all(checks.values()), "checks": checks}) return results def pass_rate_by_tag(results): by_tag = defaultdict(list) for r in results: for tag in r["tags"]: by_tag[tag].append(r["passed"]) return {tag: (sum(v) / len(v), len(v)) for tag, v in by_tag.items()} MUST_PASS = {"out-of-scope", "prompt-injection"} def gate(results): for tag, (rate, n) in pass_rate_by_tag(results).items(): if tag in MUST_PASS and rate < 1.0: raise SystemExit(f"{tag}: {rate:.0%} over {n} runs; release blocked")

The essential design choice is that generate is the real feature, not a bare model call. Many regressions come from changes to retrieval, templating or output parsing, and an evaluation that bypasses them will not see those regressions. Store every run's outputs alongside the scores, so that when a number moves you can read what actually changed.

Run the harness in continuous integration whenever the prompt, the model identifier, retrieval settings or post-processing change. Treat a small set of tags as hard gates, typically safety, refusal and injection cases, and report the rest as trends for a human to review. Open-source frameworks such as OpenAI's Evals, or holistic benchmark efforts such as Stanford's HELM, are worth reading for structure, but a feature-specific harness of a hundred lines that runs on every change is usually worth more than a general benchmark that runs once.

After launch, the set keeps growing

Production is where the evaluation set learns. Every reported failure becomes a new case, tagged, with the expected properties written down, before the fix is attempted. That way the fix is proven and the failure cannot quietly return. Online signals, such as users editing generated text, thumbs-down ratings or escalations, are valuable for finding new failure types, but they are not a substitute for the offline set, because they arrive late and cannot be rerun against a candidate model.

When a provider releases a new model, the set turns a risky migration into a measured one: run both, compare by tag, read the cases that changed, and decide with evidence. NIST's AI Risk Management Framework makes measurement one of its four core functions, alongside govern, map and manage, so the same habit also serves whoever has to account for the system's risks.

Before the first prompt: a checklist

  1. Success criteria are written as separate, checkable properties, agreed with the people who own the outcome.
  2. The evaluation set contains real or realistic inputs, stratified and tagged, with a held-out portion.
  3. Code graders cover every property that can be checked mechanically.
  4. Model graders have rubrics, constrained verdicts and a measured agreement rate with human graders.
  5. Each case runs several times; results are reported per tag with case counts.
  6. The model version, prompt and parameters are pinned and recorded with each run.
  7. The harness exercises the real feature path and runs in CI on every relevant change.
  8. Every production failure becomes a test case before it is fixed.

If the team cannot complete the first two items, the feature is not ready to build. That conclusion, reached in a week, is far cheaper than reaching it after launch. If you are commissioning an AI feature, ask to see the evaluation set and its latest per-tag results before you approve a model or provider change; evaluation first is how we approach AI application development. Later issues of Under the Hood build on it for retrieval and model failover.

References

Related Articles

AI & Machine Learning28 min read

Large Language Model Architecture: How LLMs Actually Work

A technical deep dive into LLM architecture: tokenization, embeddings, transformer blocks, attention mechanisms, and why these systems behave the way they do—including hallucinations and limitations.