Sub topic 4
Protect quality with a small evaluation set
Every lever in this tutorial trades something for lower cost or latency. Shorter prompts, smaller models, output limits, and cached answers can all make responses worse. A small evaluation set (an "eval set") is how you find out whether a change broke something. This chapter shows how to build one, score it, and use it as a gate before you ship a change.
This chapter assumes you can call an LLM API, write basic Python, and read JSON. You also need the baseline numbers from the previous chapter on measurement. Quality is the third number beside cost and latency.
Why you need a guardrail
Cost and latency are easy to see. Each request has a token count, a price, and a timer. Quality is harder to see. If you cut a prompt by 40% and the answers get slightly worse, nothing crashes. Users notice weeks later, or never complain and just leave.
An eval set turns "seems fine" into a number you can compare before and after. It answers one question: does the cheaper or faster version still meet the bar?
What an eval set is
An eval set is a fixed list of example inputs, each paired with something you can check the output against. You run the same set through the current system and through a changed system, then compare scores.
A useful set for this purpose is small. Between 30 and 100 examples is a reasonable start. It is meant to catch large regressions cheaply, not to produce a precise benchmark. Because you will run it many times, a large set makes every experiment slow and expensive.
Each example usually has:
- An
id, so you can trace failures. - The
input, the same shape you send in production. - An expected answer, a reference answer, or a list of rules the answer must satisfy.
- Optional tags, such as
easy,edge_case, orrefund_policy.
Choosing examples
How you pick examples matters more than how many you have.
- Sample from real traffic. Pull requests from your logs. Invented examples tend to be cleaner and easier than real ones.
- Cover the categories you serve. If 20% of traffic is billing questions, include billing questions. Tag them so you can see per-category scores.
- Include hard cases on purpose. Add ambiguous inputs, very long inputs, inputs in other languages, and inputs that should be refused.
- Add every bug you fix. When a user reports a bad answer, add that input. The set grows from real failures.
- Remove sensitive data. Strip personal information before saving examples.
Keep the set frozen between comparisons. If you change examples and the system at the same time, you cannot tell which change moved the score.
Three ways to score
Pick the cheapest scoring method that still reflects what you care about.
| Method | How it works | Good for | Weakness |
|---|---|---|---|
| Programmatic check | Code tests the output: exact match, regex, valid JSON, required fields, length limit | Classification, extraction, formats | Cannot judge open-ended text |
| Reference comparison | Compare to a reference answer by overlap or by embedding similarity | Short factual answers | Penalizes correct answers worded differently |
| LLM as judge | A model grades the output against a rubric | Summaries, tone, helpfulness | Costs tokens, can be biased, needs its own checking |
Prefer programmatic checks wherever you can. They are free, fast, and repeatable. Use an LLM judge only for the parts that code cannot test.
Using an LLM as judge safely
A judge is another model call, so it adds cost and has its own errors. Reduce the risk:
- Write a short rubric with a fixed scale, such as pass or fail with a one-line reason.
- Set temperature to 0 for the judge to keep scores stable.
- Use a stronger model for judging than the one you are testing, when you can.
- Check the judge by hand on 10 to 20 examples. If you disagree with it often, fix the rubric before trusting it.
- Judges tend to prefer longer answers. When you are testing a change that shortens output, add a rubric line that does not reward length.
A minimal eval harness
The harness below stores examples as dictionaries, runs a system function over them, scores each with a check function, and reports the pass rate by tag. The system argument is any function that takes an input string and returns an output string, so you can plug in a different prompt or model for each comparison.
import json
from collections import defaultdict
EVAL_SET = [
{"id": "t1", "tag": "extraction", "input": "Order #4821 shipped on May 3.",
"expected": {"order_id": "4821"}},
{"id": "t2", "tag": "extraction", "input": "Please cancel order 977.",
"expected": {"order_id": "977"}},
{"id": "t3", "tag": "edge_case", "input": "Hello, no order here.",
"expected": {"order_id": None}},
]
def check(output: str, expected: dict) -> bool:
"""Programmatic check: output must be JSON with the expected order_id."""
try:
data = json.loads(output)
except json.JSONDecodeError:
return False
return data.get("order_id") == expected["order_id"]
def run_eval(system, eval_set=EVAL_SET):
results = []
for ex in eval_set:
output = system(ex["input"])
results.append({"id": ex["id"], "tag": ex["tag"],
"passed": check(output, ex["expected"])})
by_tag = defaultdict(list)
for r in results:
by_tag[r["tag"]].append(r["passed"])
summary = {tag: sum(v) / len(v) for tag, v in by_tag.items()}
summary["overall"] = sum(r["passed"] for r in results) / len(results)
return summary, results
def fake_system(text: str) -> str:
# Stand-in for a real model call, so the harness runs without an API key.
digits = "".join(c if c.isdigit() else " " for c in text).split()
return json.dumps({"order_id": digits[0] if digits else None})
summary, results = run_eval(fake_system)
print(summary)Replace fake_system with a function that calls your model. Save results to a file, so you can diff per-example outcomes between runs and not only look at the overall number.
Comparing a candidate to the baseline
Run the eval set against the current system, record the scores, then run it against the candidate. The comparison needs three things.
- Same examples, same checks. Only the system under test changes.
- A threshold defined in advance. For example: "overall pass rate must stay within 2 points of baseline, and no tag may drop more than 5 points." Writing the rule before you see results prevents rationalizing a bad result.
- Cost and latency next to quality. Report all three together. A change that saves 30% on cost and loses 1 point of quality may be a good trade. One that loses 15 points is not.
Handling noise and small samples
With a small set, one example is a large share of the score. On 40 examples, a single flip moves the pass rate by 2.5 points. Keep these effects in mind.
- Model output varies. Even at low temperature, outputs can differ between runs. If a borderline result matters, run the set two or three times and compare the averages.
- Look at flips, not only totals. A score that stays at 90% might hide five examples that newly fail and five that newly pass. Read the newly failing ones.
- Small gaps are not evidence. A 1-point difference on 40 examples is within noise. Treat only larger or consistent differences as real.
- Per-tag drops matter. An overall score can hold steady while one category collapses. This often happens when a trimmed prompt removes instructions that only one category needed.
Common errors
- Testing on the examples you tuned the prompt against. The score then overstates quality. Keep a held-out portion that you never use while editing prompts.
- Checks that are too strict. An exact-match check fails a correct answer that has extra whitespace. Normalize outputs before comparing.
- Checks that are too loose. A check that only tests "output is not empty" passes almost anything.
- A set that never changes. Traffic shifts over time. Review and refresh the set every few months, adding recent real cases.
- Skipping the eval because the change looks harmless. Small prompt edits and model version bumps can both change behavior.
- Ignoring the judge's cost. An LLM judge on 100 examples is 100 more calls per run. Budget for it.
Where this fits in the rest of the tutorial
Later chapters depend on this gate. Choosing a smaller model, trimming prompts, limiting output, caching responses, and routing between models all need a quality check before and after the change. Keep the harness in your repository and run it as part of each experiment.
Exercise
You trim a prompt and the overall pass rate on a 40-example eval set goes from 92.5% to 90.0%. The tag "refusal" went from 5 of 5 passing to 2 of 5 passing. Should you accept the change, and why?
Show answer
Do not accept it yet. The overall drop is one example, which is within noise for a set this size. The refusal category lost three of five examples, which is a large per-tag regression. The trimmed prompt probably removed instructions the refusal cases relied on. Read the three newly failing examples, restore the missing instructions, and rerun. Setting a per-tag threshold in advance, such as "no tag drops more than 5 points", would have flagged this automatically.
Exercise
You want to evaluate a summarization feature. Name one programmatic check and one check that needs an LLM judge.
Show answer
A programmatic check can verify that the summary is under a set word limit, or that it contains required names or numbers from the source. A judge is needed to decide whether the summary is faithful to the source and covers the main points, because code cannot test meaning reliably.