Sub topic 3
Building an evaluation dataset
An evaluation dataset is the set of inputs, with expected outputs or grading criteria, that you run your application against. Every metric later in this tutorial is computed over it, so a weak dataset gives you precise-looking numbers that mean little.
This chapter assumes you can write basic Python, have called an LLM API, and have read the previous chapter on defining success criteria. You should already have a written list of what "good" means and the failure modes you care about.
What a case contains
A case is one unit of evaluation. At minimum it has a stable ID, an input, and something to grade against. Add metadata early, because you will want to slice results by it later.
| Field | Purpose |
|---|---|
| `id` | Stable identifier, so results can be compared across runs |
| `input` | What the application receives (a question, a document, a conversation) |
| `expected` | A reference answer, or `null` if grading uses criteria instead |
| `criteria` | Optional rubric text for a judge or human reviewer |
| `tags` | Category, difficulty, language, or other slicing attributes |
| `source` | Where the case came from: production log, hand-written, synthetic |
Not every task has a single correct answer. For summarization or open-ended advice, store the criteria that a good answer must satisfy, such as "mentions the refund deadline" or "does not promise a specific date". For classification and extraction, store the exact label or fields.
Store cases as JSON Lines, one object per line. The format is diff-friendly in version control, and appending a case never rewrites the file.
{"id": "refund-001", "input": "Can I return a laptop after 45 days?", "expected": null, "criteria": "States the 30-day window. Does not offer an exception.", "tags": ["refunds", "easy"], "source": "support-log"}Where cases come from
Use several sources, because each one covers different gaps.
- Production logs are the most realistic. They show how users actually phrase things, including typos and vague requests. Remove personal data before storing them.
- Hand-written cases let you target a specific failure mode from your success criteria. They tend to be cleaner and more polite than real traffic.
- Synthetic cases are generated by an LLM from your documents or from seed examples. They are cheap and good for coverage, but they inherit the generator's style and blind spots. Review every one by hand before it enters the set.
- Bug reports are cases you add each time the application fails in the field. Over time, this is the most valuable source.
flowchart TDIgnore the line above. The actual diagram follows.
How big and how broad
There is no universal size. Use these rules of thumb instead.
- Start with 30 to 50 carefully chosen cases. That is enough to expose obvious failures and small enough to read every output.
- Grow toward a few hundred when you need to detect small differences. With 50 cases, one case changes the pass rate by 2 points, and sampling noise alone can be 10 points or more. The statistics chapter covers this.
- Make every slice you care about large enough to read. If "refund questions" is 4 of 200 cases, you cannot say anything about refund questions.
Coverage matters more than raw count. List the dimensions that change behavior: topic, input length, language, user intent, and the failure modes from your success criteria. Then check that each combination you care about has cases.
Include these categories deliberately:
- Typical cases that represent most real traffic.
- Edge cases such as empty input, very long input, mixed languages, and ambiguous requests.
- Known failures from earlier versions.
- Should-refuse or should-abstain cases, where the right behavior is to decline or say "I don't know". Without these, a model that always answers confidently scores well.
Match the real distribution of traffic for your headline number, and oversample rare but costly cases in separate tagged slices. Report them separately so the oversampling does not distort the overall score.
Labeling and quality control
Wrong labels cap your measurable accuracy and produce misleading failures. A "failing" case where the label is wrong sends you to fix a bug that does not exist.
- Write down labeling guidelines before labeling. Ambiguity in the guidelines becomes disagreement between labelers.
- Have two people label a sample and compare. If they disagree often, the task definition is unclear, and no metric will be reliable until you fix that.
- When a model fails a case, read the case before changing the model. A meaningful share of early "failures" turn out to be label errors.
- Prefer criteria over a single reference string where several answers are valid. "The capital is Paris" and "Paris" should both pass.
A basic loader catches structural errors before they waste an evaluation run.
import json
REQUIRED = {"id", "input", "tags"}
def load_cases(path):
cases, seen = [], set()
with open(path, encoding="utf-8") as f:
for line_no, line in enumerate(f, start=1):
if not line.strip():
continue
case = json.loads(line)
missing = REQUIRED - case.keys()
if missing:
raise ValueError(f"line {line_no}: missing {sorted(missing)}")
if "expected" not in case and "criteria" not in case:
raise ValueError(f"line {line_no}: needs expected or criteria")
if case["id"] in seen:
raise ValueError(f"line {line_no}: duplicate id {case['id']}")
seen.add(case["id"])
cases.append(case)
return casesSplitting: development and held-out sets
If you tune prompts against the same cases you report on, the score rises partly because you fit those cases. This is overfitting to the evaluation set, and it is the most common dataset error.
Split the data into two parts:
- A development set you read, debug against, and tune on freely.
- A held-out test set you run rarely and do not inspect case by case while iterating.
The split must respect groups. If five cases are paraphrases of the same question, or all come from the same source document, they must land on the same side. Otherwise the test set contains near-copies of development cases and the score is inflated.
import random
from collections import defaultdict
def split_by_group(cases, group_key, dev_fraction=0.5, seed=0):
groups = defaultdict(list)
for case in cases:
groups[case[group_key]].append(case)
keys = sorted(groups)
random.Random(seed).shuffle(keys)
n_dev = max(1, int(len(keys) * dev_fraction))
dev = [c for k in keys[:n_dev] for c in groups[k]]
test = [c for k in keys[n_dev:] for c in groups[k]]
return dev, test
cases = [
{"id": "a1", "doc": "policy-A"}, {"id": "a2", "doc": "policy-A"},
{"id": "b1", "doc": "policy-B"}, {"id": "c1", "doc": "policy-C"},
]
dev, test = split_by_group(cases, "doc")
print(len(dev), len(test))The fixed seed makes the split reproducible. Save the resulting IDs rather than re-splitting later, because adding cases would otherwise reshuffle which side each case falls on.
Common errors
- Contamination. If cases appear in your prompt's few-shot examples, in fine-tuning data, or in public benchmarks the model may have seen, scores overstate real quality. Keep few-shot examples out of the evaluation set.
- Synthetic-only data. A set generated by one LLM favors outputs that look like that LLM's. Mix in real traffic.
- Stale data. Products, policies, and user behavior change. Review the set regularly and retire cases whose expected answer is no longer correct.
- Silent edits. Changing a case or label changes scores without any change in the application. Version the dataset, and record the dataset version with every run.
- Only easy cases. If the application scores 98% from day one, the set cannot show improvement and will not catch regressions.
Exercises
Exercise
You have 300 support questions drawn from 40 policy documents, with several paraphrased questions per document. You randomly assign individual questions to a development set (200) and a test set (100). The test score is 12 points higher than any real-world result. What is the likely cause, and how do you fix it?
Show answer
Paraphrases of the same question and questions about the same document appear on both sides, so the test set contains near-copies of development cases that you tuned against. Split by document (the group key) so that all questions from one document go to the same set, then re-measure.
Exercise
Your dataset has 500 cases, all of which have a correct answer in the provided documents. Production traffic sometimes asks questions the documents cannot answer. What should you add, and why?
Show answer
Add should-abstain cases where the right behavior is to say the answer is not available, tagged as their own slice. Without them, a system that always produces a confident answer scores perfectly on the dataset while hallucinating in production.