Building an Eval Set for Your AI Feature

Learn how to collect real test cases, define expected outputs, and wire up a one-command eval script that tells you exactly whether your AI feature got better or worse.

Why I Finally Stopped Vibes-Testing My AI Features

For a long time, my "eval process" was: run the feature, see if the output seemed okay, ship it. I'd tweak the prompt, re-run it mentally against two or three cases I remembered from last week, and call it done. That worked fine until it didn't. I changed a system prompt to fix a hallucination problem in one scenario, and three days later a user reported that the feature was now refusing to answer completely valid questions. I had no test suite. I had no history. I had no idea what broke.

That's the moment I got serious about evals. And honestly, once I built my first real eval set, I couldn't believe I'd been shipping AI features any other way.

This guide walks you through the whole thing: collecting real cases, defining what "correct" looks like, and writing a script you can run with a single command.

Step 1 — Collect Real Cases (Not Made-Up Ones)

The worst eval sets are written by developers who sat in a room and imagined what users might ask. The best ones are built from actual inputs your feature received — or close approximations of them.

Here's how I collect cases in practice. If I'm building a feature that classifies support tickets, I'll grab 20–30 real tickets from Slack, email threads, or logs. If I'm building a code explainer, I pull actual code snippets from the codebase rather than writing toy examples. If I'm pre-launch, I use Claude itself to generate realistic edge cases by giving it the domain and asking it to produce varied, tricky inputs.

generate-cases.txt (prompt to Claude)
# Prompt to generate realistic test inputs
You are helping me build an eval set for a support ticket classifier.
The classifier categorizes tickets into: billing, technical, account, general.

Generate 10 realistic, varied support ticket inputs — include edge cases,
ambiguous tickets that could fit multiple categories, very short messages,
and tickets written in poor grammar. Output as a JSON array.

Store your cases in a simple cases.json file. Keep it human-readable. You'll be editing it by hand as you discover new failure modes.

cases.json
[
{
"id": "case-001",
"input": "I was charged twice this month",
"expected_category": "billing",
"notes": "Clear billing issue"
},
{
"id": "case-002",
"input": "App keeps crashing when I open settings",
"expected_category": "technical",
"notes": "Straightforward tech"
},
{
"id": "case-003",
"input": "I need to cancel but also the payment didn't go through",
"expected_category": "billing",
"notes": "Ambiguous — billing wins by convention"
}
]

Aim for 20–50 cases minimum

Fewer than 20 cases and you're still vibes-testing with extra steps. You need enough coverage to catch regressions and spot patterns in failures.

Step 2 — Define What "Correct" Actually Means

This is the hard part. For classification tasks it's easy — either the right label came out or it didn't. But a lot of AI features produce open-ended text, and you need to define what good looks like before you can measure it.

I use three approaches depending on the feature type:

1. Exact match — Good for classification, extraction, structured output. The expected output is a specific string, label, or JSON structure. Easy to automate.

2. Contains check — Good for summaries or explanations where you care about specific facts being present. You check that the output contains certain key phrases or data points.

3. LLM-as-judge — Good for quality assessment of free-form text. You write a second prompt that asks Claude to score the response on a rubric. More expensive, but powerful for nuanced evals.

judge-prompt.txt
# LLM-as-judge prompt template
You are evaluating an AI response. Score it 1–5 on these criteria:
- Accuracy: Does it correctly answer the question?
- Conciseness: Is it appropriately brief?
- Safety: Does it avoid harmful content?

Input: {input}
Expected behavior: {expected}
Actual response: {actual}

Respond with JSON: {"accuracy": N, "conciseness": N, "safety": N, "pass": true/false}

Whatever your check type, encode it in your cases.json so the eval script knows how to grade each case.

Step 3 — Write the One-Command Eval Script

Here's where it all comes together. The goal is a script you can run any time you change a prompt, upgrade a model version, or refactor your feature logic. It should give you a pass rate and show you exactly which cases failed.

Here's a complete Python eval runner I've used on real projects:

run_evals.py
#!/usr/bin/env python3
import json, anthropic, sys
from datetime import datetime

# Load your eval cases
with open("cases.json") as f:
cases = json.load(f)

client = anthropic.Anthropic()
results = []
passed = 0

# Your feature's system prompt
SYSTEM = """You classify support tickets into exactly one of:
billing, technical, account, general.
Respond with only the category name, nothing else."""

for case in cases:
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=50,
system=SYSTEM,
messages=[{"role": "user", "content": case["input"]}]
)

actual = response.content[0].text.strip().lower()
expected = case["expected_category"].lower()
ok = actual == expected
if ok: passed += 1

results.append({
"id": case["id"],
"input": case["input"],
"expected": expected,
"actual": actual,
"pass": ok
})

# Print summary
total = len(cases)
print(f"\n{'='*40}")
print(f"EVAL RESULTS — {datetime.now().strftime('%Y-%m-%d %H:%M')}")
print(f"Passed: {passed}/{total} ({100*passed//total}%)")
print(f"{'='*40}")

# Print failures
failures = [r for r in results if not r["pass"]]
if failures:
print("\nFAILURES:")
for f in failures:
print(f" [{f['id']}] expected={f['expected']} got={f['actual']}")
print(f" Input: {f['input'][:60]}...")

# Save results for tracking over time
with open("eval_history.jsonl", "a") as out:
out.write(json.dumps({"timestamp": str(datetime.now()),
"pass_rate": passed/total, "failures": len(failures)}) + "\n")

sys.exit(0 if passed == total else 1)
terminal
python run_evals.py
========================================
EVAL RESULTS — 2025-01-15 09:42
Passed: 27/30 (90%)
========================================

FAILURES:
[case-003] expected=billing got=account
Input: I need to cancel but also the payment didn't go...
[case-017] expected=technical got=general
Input: The API keeps returning 500 errors on Tuesday...

Notice that last line: sys.exit(1) if anything failed. That means you can drop this into a CI pipeline and it'll block deploys when your pass rate drops.

Step 4 — Track Results Over Time

The eval_history.jsonl file the script writes is your paper trail. Every time you run evals, it appends a line. After a few weeks you can see whether your prompt changes are actually moving the needle.

eval_history.jsonl
{"timestamp": "2025-01-10 14:22", "pass_rate": 0.80, "failures": 6}
{"timestamp": "2025-01-12 09:11", "pass_rate": 0.87, "failures": 4}
{"timestamp": "2025-01-15 09:42", "pass_rate": 0.90, "failures": 3}

Keep this file in your repo. Future-you will be very grateful when you need to explain why you changed something.

Add new failures to the case set immediately

Every time a user reports a bad output, add it to cases.json right then. This is how your eval set grows to cover real-world edge cases instead of staying theoretical forever.

Using Claude Code to Build the Eval Faster

When I'm setting up a new eval suite, I lean on Claude Code heavily. I'll open a session with my feature code and prompt, then ask it to scaffold the eval runner based on my cases structure. It's particularly good at writing the grading logic for contains checks and generating the LLM-as-judge prompt templates.

One specific workflow I use: paste in a handful of real failure cases and ask Claude Code to suggest what additions to the system prompt might fix them. Then I run evals again to verify. That feedback loop — change prompt, run eval, check score — is how you actually make AI features better in a disciplined way instead of just guessing.

claude code session
# Tell Claude Code what you're working on
> I have a support ticket classifier that's failing on ambiguous
billing+account tickets. Here are the failing cases [paste cases].
Here's my current system prompt [paste prompt].
Suggest 3 prompt variations and update run_evals.py to test all 3
and report which performs best.

The Mindset Shift That Made This Click For Me

When I stopped thinking of evals as "testing" and started thinking of them as "evidence," everything clicked. Every AI feature is a hypothesis: "I believe this prompt, with this model, produces good outputs for these kinds of inputs." An eval set is just the experiment that proves or disproves it.

Once you have that evidence, you can iterate with confidence. You can upgrade models without fear. You can hand the feature off to a teammate and they'll know exactly what "working" means. You'll stop having that sinking feeling when a user reports something weird and you have no idea how widespread the problem is.

Start small — 20 cases, a simple exact-match check, one script. You can build from there. The hardest part is writing down what "correct" means. Once you've done that, the rest is just plumbing.

Keep going

More tutorials in this category, or explore the full field guide.

More Claude Code Tutorials Official Docs ↗