Sub topic 6
Evaluation: Golden Sets, Programmatic Checks, and Model-Graded Scoring
This chapter assumes you know the classic ML lifecycle (train, validate, deploy), can write Python, and have called an LLM API. It also assumes you have read the earlier chapters on versioned prompts and non-deterministic output. Here you will build an offline evaluation: a fixed set of inputs, checks that score the outputs, and a pass rate you can compare between versions.
Why evaluation changes for LLM apps
In classic MLOps you hold out a labeled test set and compute a metric such as accuracy or F1. The model's output is a label or a number, so scoring is a comparison against ground truth.
LLM output is free text. Many different answers can be correct, and the same input can produce different text on each run. Three consequences follow:
- Exact-match comparison fails on correct answers that are worded differently.
- A single run says little, because the next run may differ.
- Quality has several dimensions at once: correctness, tone, length, format, and safety.
Evaluation therefore becomes a layered set of checks, run several times per case, reported as rates.
The three building blocks
| Building block | What it is | Strength | Weakness |
|---|---|---|---|
| Golden set | A curated list of inputs with expectations | Repeatable, comparable across versions | Costs effort to build and keep current |
| Programmatic check | Code that tests one property of an output | Cheap, fast, deterministic | Can only test what you can express in code |
| Model-graded scoring | A second LLM call that scores the output against a rubric | Handles fuzzy qualities such as helpfulness | Noisy, costs tokens, has its own biases |
Use them together. Programmatic checks catch hard failures. Model grading covers what code cannot express. The golden set holds both.
Building a golden set
A golden set is a versioned collection of cases. Each case has an ID, an input, and the expectations for a good output. Expectations are usually not a single reference answer. They are properties: "mentions the duplicate charge", "under 60 words", "valid JSON with a category field".
Sources for cases, in rough order of value:
- Real production inputs, with personal data removed.
- Past failures. Every bug report becomes a case so it cannot return unnoticed.
- Edge cases you invent: empty input, very long input, another language, hostile text.
- A few typical "happy path" examples.
Keep the set small enough to run on every change, often 30 to 200 cases, and tag cases by category so you can see which area regressed. Store the set in the repository next to the prompt, so a prompt change and its evaluation data are reviewed together.
Edge cases in building sets
- Leakage. If you paste golden-set examples into the prompt as few-shot examples, the set no longer measures generalization. Keep them separate.
- Staleness. Real traffic shifts over time. Refresh the set from recent traces on a schedule, and keep a stable core so scores stay comparable.
- Imbalance. If 90% of cases are easy, a high pass rate hides weak spots. Report per-tag rates, not only the overall number.
Programmatic checks
A programmatic check is a function that takes the output and returns true or false. Good targets:
- Format: parses as JSON, matches a schema, contains required sections.
- Length: within word or character limits.
- Content rules: includes or excludes specific terms, no email addresses or card numbers leaked.
- Structure: a cited ID exists in the retrieved context.
Write checks to test properties, not exact strings. "charge" in out.lower() survives rewording. out == "The customer was charged twice." does not.
The example below runs each case several times and reports a pass rate. A case passes a run only if all its checks pass. A threshold function then turns the report into a yes or no decision.
def run_eval(generate, cases, runs=3):
"""generate(text) -> str. Each case has an id, an input, and a list of check functions."""
report = []
for case in cases:
passes = 0
for _ in range(runs):
output = generate(case["input"])
if all(check(output) for check in case["checks"]):
passes += 1
report.append({"id": case["id"], "pass_rate": passes / runs})
return report
def gate(report, min_pass_rate=0.9):
failing = [r["id"] for r in report if r["pass_rate"] < min_pass_rate]
return len(failing) == 0, failing
cases = [
{
"id": "duplicate_charge",
"input": "My invoice shows a duplicate charge.",
"checks": [
lambda out: "charge" in out.lower(),
lambda out: len(out.split()) <= 60,
],
},
]To try it without an API key, pass a stub as generate:
def fake_generate(text):
return "The customer reports a duplicate charge on their invoice."
report = run_eval(fake_generate, cases, runs=3)
print(report)
print(gate(report))With the stub, both checks pass on every run, so the report shows a pass rate of 1.0 and gate returns (True, []). In real use, generate calls your model with a specific prompt version, as defined in the chapter on versioned prompts.
Why repeat runs
Because output varies, one pass proves little. Three runs on a case that fails one time in five will pass all three about half the time (0.8 cubed is about 0.51). If a case matters, use more runs. If the budget is tight, spend repeats on the cases that have shown flakiness. Where your provider allows it, a low temperature reduces variance but does not remove it, so you still need repeats.
Model-graded scoring
Some properties resist code: "the summary is faithful to the ticket", "the tone is polite", "the answer addresses the question". For these you can ask another model to act as a judge.
A judge prompt needs:
- A rubric with concrete criteria, not "rate the quality".
- A small, fixed scale or a pass/fail decision.
- A required output format that you can parse.
- The input and the output being graded, and a reference answer when you have one.
import json
JUDGE_TEMPLATE = """You are grading a support-ticket summary.
Ticket:
{ticket}
Summary:
{summary}
Criteria:
1. Every claim in the summary appears in the ticket.
2. The summary names the customer's main problem.
Reply with JSON only: {{"faithful": true or false, "names_problem": true or false, "reason": "one sentence"}}"""
def judge(call_judge_model, ticket, summary):
"""call_judge_model(prompt) -> str. Returns a parsed verdict, or None if unparseable."""
prompt = JUDGE_TEMPLATE.format(ticket=ticket, summary=summary)
raw = call_judge_model(prompt)
try:
verdict = json.loads(raw)
except json.JSONDecodeError:
return None
return verdict if {"faithful", "names_problem"} <= verdict.keys() else NoneTreat an unparseable judge reply as its own outcome. Count it and look at it, since silently scoring it as a pass or a fail distorts the rate.
Known judge problems
- Self-preference. A model can score text from its own family higher. Use a different model as judge when you can.
- Position and length bias. When comparing two outputs, judges often favor the first one shown or the longer one. Randomize the order and control for length.
- Rubric drift. Changing the judge model or the rubric changes every score. Version the judge prompt and judge model exactly like the app's prompt, and re-run baselines when either changes.
- Overconfidence. Judge scores are estimates. Validate the judge by hand-labeling 30 to 50 cases and measuring how often the judge agrees with you. If agreement is low, fix the rubric before trusting the numbers.
How the pieces fit
Choosing thresholds and reading results
A threshold is a decision, not a fact. Some guidance:
- Set per-case or per-tag thresholds for critical behavior, such as refusing unsafe requests, in addition to an overall rate.
- Compare against a baseline: run the current production version on the same set and look at differences, not only absolute numbers.
- Small sets give coarse rates. With 20 cases, one case is 5 points. Do not read a 2-point change as a signal.
- Always read the failing outputs. A number tells you that something failed, and the text tells you why.
Common mistakes
- Using a single run and trusting the result.
- Writing checks that match exact wording, then rejecting good outputs.
- Evaluating only happy-path inputs.
- Changing the golden set and the prompt in the same commit, so you cannot tell which moved the score.
- Letting the judge and the app share the same model and the same blind spots.
- Treating a passing offline score as proof of production quality. Offline sets cover only what you thought to include, which is why later chapters add monitoring on live traffic.
Exercise
A prompt change raises the overall pass rate on your 40-case golden set from 0.92 to 0.95, but all 3 cases tagged "refusal" drop from 1.0 to 0.33. The overall gate is 0.9. Should the release go ahead, and what would you change in the evaluation setup?
Show answer
Do not release on the overall number. The overall rate hides a regression in a safety-relevant category, and it passes only because the other 37 cases are easy. Add a per-tag threshold for "refusal" (for example 1.0, or at least 0.9), report pass rates by tag, and read the failing refusal outputs to find the cause. Also consider adding more refusal cases, since 3 cases give very coarse rates.
Exercise
Your judge model gives a faithfulness score to summaries produced by a model from the same vendor. Name two risks and one step to reduce each.
Show answer
Risk 1 is self-preference, where the judge favors text from its own model family. Reduce it by using a judge from a different family or comparing against human labels. Risk 2 is an unvalidated rubric, where the judge's scores do not match what you care about. Reduce it by hand-labeling 30 to 50 cases and measuring agreement between judge and human, then revising the rubric until agreement is acceptable.