Sub topic 14
Compare candidates on your own examples
This chapter assumes you can call a model through an SDK or HTTP API, read basic Python, and know what a prompt, a token, and a context window are. It also assumes you have read the earlier chapters on hosted APIs, open-weight models, and model sizes, since those produce your list of candidates.
Why public benchmarks are not enough
Leaderboards score models on tasks someone else chose. Your application has its own inputs, output format, and tolerance for mistakes. A model that ranks first on a general reasoning benchmark can still fail at extracting fields from your invoices. A smaller model that ranks lower can do that job perfectly.
A small evaluation set of your own examples gives you three things leaderboards cannot:
- A like-for-like score for each candidate on your task.
- Evidence for the "smallest model that meets requirements" decision.
- A regression test you can rerun when a provider updates a model or you consider switching.
Build the evaluation set
Start with 30 to 100 cases. Fewer than about 20 is too noisy to separate candidates. More than a few hundred is rarely needed early on and slows iteration.
Draw cases from real or realistic inputs:
- Typical requests, weighted roughly as they appear in production.
- Known hard cases: messy formatting, abbreviations, long inputs, typos.
- Edge cases: empty fields, no valid answer, contradictory input.
- Past failures, once you have any.
Each case needs an input and a way to decide whether the output is acceptable. Write the expected answer before you see any model output. Otherwise you will unconsciously accept whatever the first model produced.
Remove personal or confidential data from your cases unless the candidate you send them to is approved for that data. A hosted API receives every case you run.
Keep a few cases aside as a holdout. Use the main set while you tune prompts. Check the holdout only at the end. If a prompt scores well on the main set but poorly on the holdout, you tuned the prompt to the examples.
Choose a pass check
The check should be as strict as the task requires and no stricter. Common options:
| Check | Use when | Risk |
|---|---|---|
| Exact match | Output is a label or a fixed token | Fails on harmless whitespace or punctuation |
| Contains or regex | Answer is embedded in extra text | Substring matches can be wrong (see below) |
| Parse and compare | Output is JSON or another structured format | Must handle invalid output as a failure, not an error |
| Programmatic rule | Length limits, required fields, banned words | Only covers rules you can state |
| Model as judge | Free-form text such as summaries | The judge has its own biases and costs tokens |
A plain expected in output check has a trap. The expected value INV-17 is "contained" in INV-175, so a wrong answer passes. Anchor the match so it cannot continue into more identifier characters.
For free-form output, use a judge model only after you have checked its verdicts against a sample you graded by hand. Use a judge that is not one of the candidates being scored, to avoid a model favoring its own style.
Run every candidate the same way
A fair comparison holds everything constant except the model:
- Use the same prompts, the same cases, and the same parameters.
- Set
temperature=0for repeatable output. Even then, some hosted models give slightly different results on repeated calls, so run each case two or three times and count a case as passed only by a rule you fix in advance, such as "all runs pass." - Give each model a fair prompt. A prompt written for one model's habits can penalize another. If you adapt prompts per model, say so in your notes and adapt them with equal effort.
- Record the exact model identifier and date. Hosted model names can point to updated versions over time.
The harness below uses the ask(prompt) shape from the portability chapter. It measures pass rate and latency, and it keeps the failures so you can read them. The two candidates here are stand-ins that need no API access. Replace them with real ask functions to run a real comparison.
import re
import statistics
import time
cases = [
{"prompt": "Extract the invoice number: 'Invoice INV-2041, due May 3'", "expected": "INV-2041"},
{"prompt": "Extract the invoice number: 'Ref: INV-17, total $90'", "expected": "INV-17"},
{"prompt": "Extract the invoice number: 'Invoice INV-9 paid'", "expected": "INV-9"},
]
def check(output: str, expected: str) -> bool:
"""Match the expected value as a whole token, not as part of a longer one."""
pattern = r"(?<![\w-])" + re.escape(expected) + r"(?![\w-])"
return re.search(pattern, output) is not None
def evaluate(ask_fn, cases, runs: int = 1) -> dict:
passed_cases = 0
latencies = []
failures = []
for case in cases:
all_passed = True
for _ in range(runs):
start = time.perf_counter()
output = ask_fn(case["prompt"])
latencies.append(time.perf_counter() - start)
if not check(output, case["expected"]):
all_passed = False
failures.append({"prompt": case["prompt"], "got": output})
passed_cases += all_passed
return {
"pass_rate": passed_cases / len(cases),
"median_latency_s": statistics.median(latencies),
"failures": failures,
}
# Stand-ins for real models: replace with functions that call your candidates.
def ask_small(prompt: str) -> str:
match = re.search(r"INV-\d", prompt) # truncates multi-digit numbers
return match.group(0) if match else ""
def ask_large(prompt: str) -> str:
match = re.search(r"INV-\d+", prompt)
return match.group(0) if match else ""
for name, fn in (("small", ask_small), ("large", ask_large)):
result = evaluate(fn, cases, runs=2)
print(f"{name}: pass rate {result['pass_rate']:.2f}, "
f"{len(result['failures'])} failed runs")
# small: pass rate 0.33, 4 failed runs
# large: pass rate 1.00, 0 failed runsThe small stand-in returns INV-2 for INV-2041. A bare in check would accept INV-1 for the expected INV-17, but the anchored check correctly rejects it.
Measure more than accuracy
A pass rate alone does not pick a model. For each candidate, also record:
- Latency. Median and a high percentile such as p95, measured from your own network and region.
- Cost per request. Use the token counts from the responses and the
request_costcalculation from the pricing chapter, then project to monthly volume. - Failure type. Wrong answer, malformed format, refusal, or timeout. Each has a different fix.
- Operational fit. Context window large enough for your longest cases, license acceptable, data handling approved.
Put the results in one table. A typical outcome is a small model at 94% pass rate and a fraction of the cost, against a large model at 98%. Whether 4 points is worth the price is a product decision, and the table lets you make it with numbers.
Read the results with care
With 50 cases, one case is 2 percentage points. A gap of 2 to 4 points between two models is often noise. Before treating a difference as real:
- Rerun and confirm the scores are stable.
- Read the failures of each model. Do they share a pattern, such as long inputs?
- Check whether the check itself is wrong. A correct answer in an unexpected format counts as a failure.
- Add more cases in the area where the models differ.
Reading failures usually teaches more than the score. If a model fails because the prompt was ambiguous, fix the prompt before judging the model.
Common errors
- Tuning on the test set. Keep a holdout and report it separately.
- Lenient checks. Substring matches inflate scores.
- Strict checks. Exact match on free text undercounts good answers.
- Unequal conditions. Different temperature, different prompt effort, or a candidate quantized more aggressively than the one you plan to deploy.
- Unrepresentative cases. A set built only of clean examples hides the failures you will see in production.
- One-time evaluation. Models, prompts, and your data change. Rerun the set when you change any of them.
The evaluation loop
Exercise
Your evaluation uses the check expected in output with the expected value INV-17. A model answers INV-175. What happens, and how do you fix the check?
Show answer
The check passes, because INV-17 is a substring of INV-175, so a wrong answer is counted as correct. Fix it by matching the expected value as a whole token, for example with a regular expression that forbids word characters or hyphens directly before and after the match, as in the check function above.
Exercise
Two candidates score 92% and 96% on a 25-case set, and the larger model costs eight times as much per request. List three things you would do before choosing the larger model.
Show answer
The 4-point gap is one case on 25, so it may be noise. First, add more cases, especially in the area where the models differ, and rerun. Second, read the failed cases of both models to see whether the failures come from the model, an ambiguous prompt, or a faulty check. Third, check the gap on a holdout set and weigh it against the eightfold cost, including whether a prompt fix or a router that sends only hard cases to the large model closes the difference.