Prompt Evaluation and Improvement
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
You've probably done this: change a prompt, try it on one example, think "much better", and ship it. Two weeks later someone notices that a different kind of input now fails. The problem isn't the change. It's that "it seems better" was based on one data point. This lesson is about replacing that feeling with a small, honest test you can run in a minute.
What you'll learn
- How to write success criteria you can actually measure.
- How to build a test set, and what to put in it.
- The three kinds of grader and when to use each.
- How to compare two prompt versions and spot regressions.
Before you start
Start with what "good" means
Anthropic's testing guide begins before any code: define success criteria, and make them specific, measurable, achievable and relevant. "The model does well" isn't a criterion. "At least 95 percent of tickets get the same label a human gave them" is. "Replies sound warm" can become "a grader scores tone at 4 or above on a 1 to 5 scale". Most real features need more than one criterion: accuracy, but also tone, latency and cost.
It's also worth deciding in advance what you'll do with the result. If the score is below the bar, do you change the prompt, switch model, or add a human step? A test without a decision attached tends to be ignored.
Build the test set
The guide gives three principles for designing evaluations:
- Be task-specific. Mirror the real distribution of inputs and include the awkward ones: irrelevant input, very long input, ambiguous cases, and harmful or hostile input.
- Automate when you can. Prefer formats you can grade with code (an exact label, a required phrase, valid JSON) or with another model, so you can rerun everything in seconds.
- Volume over polish. Many automatically graded cases with somewhat noisy scores beat a few perfect hand-graded ones.
A practical start is 20 to 50 real inputs with the answers you want. Tag them (core, edge, adversarial) so you can see where failures cluster. And every time a real input goes wrong in production, add it to the set before you fix the prompt. Over a few months the set becomes the most valuable asset in the project.
Three ways to grade
- Exact match. Normalise case and whitespace, then compare to a known label. Perfect for classification.
- Rules in code. Required phrases present, valid JSON, length in range, no banned words. Cheap, fast, and deterministic.
- Model-graded. A second model scores the output against a rubric, say 1 to 5 for tone. Good for qualities you can't write a rule for. Anthropic's guide recommends, as general good practice, using a different model for grading than the one that produced the output. Keep the rubric narrow, ask for a number only, and spot-check the grader against a few human judgements so you know it's measuring what you think.
The guide also lists similarity-based scoring (for example embedding similarity for consistency) for cases where there's no single right wording. Start with the simplest grader that works. Exact match and a few rules cover more than people expect.
The harness
This is the grown-up version of the small harness from lesson 1.7. It runs any prompt producer over your cases with any grader, keeps every output so you can read it, and compares two runs so a regression doesn't hide inside an average:
import json
import re
from dataclasses import dataclass, field
from typing import Callable
# A grader takes (model_output, case) and returns a score from 0 to 1.
Grader = Callable[[str, "Case"], float]
@dataclass
class Case:
id: str
input: str
expected: str = ""
must_include: list[str] = field(default_factory=list)
tags: list[str] = field(default_factory=list)
def exact(output: str, case: Case) -> float:
"""Code-graded: normalise case and whitespace, then compare to a known label."""
return float(" ".join(output.lower().split()) == " ".join(case.expected.lower().split()))
def includes_all(output: str, case: Case) -> float:
hits = sum(1 for needle in case.must_include if needle.lower() in output.lower())
return hits / len(case.must_include) if case.must_include else 1.0
def valid_json(output: str, case: Case) -> float:
try:
json.loads(output)
return 1.0
except ValueError:
return 0.0
def llm_judge(ask_judge: Callable[[str], str], rubric: str) -> Grader:
"""LLM-graded: a second model scores against a rubric. Anthropic suggests grading with a different
model from the one that wrote the output. Keep the rubric narrow and ask for a number only."""
def grade(output: str, case: Case) -> float:
prompt = (
f"Rate the response on a scale of 1 to 5 against this rubric: {rubric}\n"
f"<response>{output}</response>\nOutput only the number."
)
match = re.search(r"[1-5]", ask_judge(prompt))
return (int(match.group()) - 1) / 4 if match else 0.0
return grade
def run(prompt_version: str, produce: Callable[[Case], str], cases: list[Case], grader: Grader) -> dict:
rows = []
for case in cases:
output = produce(case)
rows.append({"id": case.id, "score": grader(output, case), "output": output, "tags": case.tags})
mean = sum(r["score"] for r in rows) / len(rows)
return {"version": prompt_version, "mean": mean, "rows": rows}
def compare(a: dict, b: dict) -> str:
"""Show regressions explicitly. An average can go up while an important case gets worse."""
by_id = {r["id"]: r for r in a["rows"]}
lines = [f"{a['version']}: {a['mean']:.0%} {b['version']}: {b['mean']:.0%}"]
for r in b["rows"]:
before = by_id[r["id"]]["score"]
if r["score"] < before:
lines.append(f" REGRESSION {r['id']}: {before:.2f} -> {r['score']:.2f}")
elif r["score"] > before:
lines.append(f" fixed {r['id']}: {before:.2f} -> {r['score']:.2f}")
return "\n".join(lines)
Pieces worth noticing:
run takes a plain function that turns a case into model output. In production that function calls the API with your template; in tests it can be a fake. The harness doesn't care.
llm_judge builds a grader from any function that asks a model. The score is mapped from the 1 to 5 scale onto 0 to 1, and a reply with no digit scores 0 rather than crashing.
compare prints regressions and fixes per case. An average can improve from 60 to 70 percent while the one case you care about gets worse, and only a per-case diff shows it.
We tested the scoring with scripted outputs. Version 1 scored 33 percent and version 2 scored 67 percent, and the comparison flagged one regression (c1 went from correct to wrong) and two fixes, one of them the adversarial case. That's the situation the per-case view exists for: version 2 is better overall but broke something, and you want to know before shipping.
A loop you can repeat
- Run the current prompt over the set and save the result as the baseline, with the template version and fingerprint (lesson 3.7).
- Read the failures. Don't just look at the score.
- Change one thing: an instruction, an example, a tag, the model or the effort.
- Run again and
compare against the baseline.
- Keep the change only if the score improves and nothing important regresses. Save the new baseline.
Model outputs can vary from run to run, so for borderline cases it's worth running each case a few times and looking at how often it passes, instead of trusting one run. And if you change the model, rerun everything. Prompts tuned on one model don't always carry over, which Anthropic's own guide says plainly.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A team maintains a prompt that classifies tickets, with a saved set of sixty cases, five of them adversarial. A teammate rewrites the prompt to be friendlier. The overall score goes up a little, but the comparison shows two adversarial cases flipping from correct to wrong: the friendlier wording made the model more willing to follow instructions inside the ticket. Without the per-case view the change would have shipped. With it, they add a sentence saying ticket text is data, rerun, and keep both the friendliness and the safety.
Mistakes to avoid
- Grading on one or two examples.
- A test set made only of easy, typical inputs.
- Looking at the average and ignoring individual regressions.
- Having the same model grade its own output without a spot-check.
- Letting the test set go stale. Add real failures as they appear.
- Changing three things at once, so you can't tell what helped.
Security notes
Test data often comes from real tickets and emails. Remove names, emails, order numbers and anything personal before it goes into a repository or a prompt. And include hostile inputs deliberately: injection attempts, instructions hidden in documents, attempts to extract the system prompt. Those cases are what tell you whether your defences from lesson 3.3 actually hold.
Cost and speed
An evaluation run costs real tokens: cases times prompt size, plus the grader if it's model-based. Sixty short cases on a small model are cheap; thousands of long cases on a large model are not. Use a small, fast model while iterating, run the full set before shipping, and print the token usage of each run (lesson 2.9) so you know what a test costs.
Key takeaways
- Write specific, measurable success criteria first.
- Build a task-specific test set with edge and adversarial cases, and grow it from real failures.
- Use the simplest grader that works: exact match, code rules, then a model with a narrow rubric.
- Compare per case, change one thing at a time, and rerun when the model changes.
Lesson recap: measure, change one thing, compare case by case.
Quick quiz
- Name three properties Anthropic recommends for success criteria.
- Why does Anthropic favour volume over polish in evals?
- What is the guidance on which model should grade the output?
- Why compare cases one by one instead of only comparing averages?
- What should you do with a real input that failed in production?
Answers and explanations
- Any three of: specific, measurable, achievable, relevant.
- Many automatically graded cases give you more coverage and let you rerun quickly, even if each score is a bit noisy.
- Generally use a different model for grading than the one that generated the output.
- An average can rise while an important case gets worse, and only a per-case comparison shows the regression.
- Remove personal data, add it to the test set, and then fix the prompt so the fix is proven.
Official references and further reading
Related tutorials