Sub topic 4
Writing a repeatable evaluation harness
This chapter assumes you can write Python functions and call an LLM through an SDK. It also assumes you have a small dataset of cases like the one from the previous chapter, with an id, an input, and an expected value. Here you build the loop that runs your application over those cases and records scores. Later chapters add better scorers and statistics on top of it.
What the harness is for
An evaluation harness is a program that takes three things: the application, a dataset, and a scorer. It runs them and produces a score plus enough detail to explain the score. It matters because every other decision in this tutorial, such as changing a prompt, swapping a model, or tuning retrieval, is judged by comparing harness runs. A harness you can't repeat gives you numbers you can't compare.
"Repeatable" means a later run of the same inputs, on the same settings, gives results you can compare to an earlier run. LLMs are nondeterministic, so identical scores are not the goal. The goal is that any difference between two runs comes from the change you made and not from a hidden change in the harness.
The minimal harness
Start with the smallest version that works. It loops over cases, calls the application, scores the output, and returns the pass rate along with the per-case results.
def exact_match(output: str, expected: str) -> bool:
return output.strip().lower() == expected.strip().lower()
def run_eval(app, cases, scorer):
results = []
for case in cases:
output = app(case["input"])
passed = scorer(output, case["expected"])
results.append({"id": case["id"], "output": output, "passed": passed})
pass_rate = sum(r["passed"] for r in results) / len(results)
return pass_rate, results
cases = [
{"id": "c1", "input": "Capital of France?", "expected": "Paris"},
{"id": "c2", "input": "Capital of Japan?", "expected": "Tokyo"},
]
def fake_app(question: str) -> str:
return "Paris" if "France" in question else "Kyoto"
rate, results = run_eval(fake_app, cases, exact_match)
print(rate) # 0.5Three design choices in this code are worth keeping.
- The application is a plain function from input to output. Any system can be wrapped this way: a single prompt, a RAG pipeline, or an agent. The harness doesn't need to know what is inside.
- The scorer is a parameter. It takes the output and the expected value and returns a pass or fail. You can later pass a regex check, a judge call, or a similarity function without touching the loop.
- Per-case results are returned, not only the average. A pass rate tells you that something changed. The per-case records tell you what.
Where the minimal version breaks
The minimal harness has gaps that show up as soon as you run it against a real model.
- One exception ends the run. A rate limit or timeout on case 47 loses the results for cases 1 to 46.
- Errors and wrong answers are mixed up. If you catch exceptions and score them as failures, an outage looks like a quality drop.
- Nothing records what was run. Two weeks later you can't tell which prompt, model, or dataset version produced a number.
- Results vanish when the process exits. You can't diff two runs or look at failures later.
- It is slow. Model calls are mostly waiting on the network, so running one at a time wastes time.
A harness you can trust
The version below fixes each gap. It catches errors per case and stores them separately from failures. It records the configuration and a hash of the dataset. It runs cases in a thread pool, which suits I/O-bound API calls. It writes one JSON line per case to a file.
import hashlib
import json
import time
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
def exact_match(output: str, expected: str) -> bool:
return output.strip().lower() == expected.strip().lower()
def dataset_hash(cases) -> str:
blob = json.dumps(cases, sort_keys=True).encode("utf-8")
return hashlib.sha256(blob).hexdigest()[:12]
def run_case(app, case, scorer):
start = time.perf_counter()
output, passed, error = None, None, None
try:
output = app(case["input"])
passed = bool(scorer(output, case["expected"]))
except Exception as exc:
error = repr(exc)
return {
"id": case["id"],
"output": output,
"passed": passed,
"error": error,
"latency_s": round(time.perf_counter() - start, 4),
}
def run_eval(app, cases, scorer, config, workers=4, out_path=None):
with ThreadPoolExecutor(max_workers=workers) as pool:
results = list(pool.map(lambda c: run_case(app, c, scorer), cases))
scored = [r for r in results if r["error"] is None]
n_passed = sum(r["passed"] for r in scored)
summary = {
"run_at": datetime.now(timezone.utc).isoformat(),
"config": config,
"dataset_hash": dataset_hash(cases),
"n_cases": len(results),
"n_errors": len(results) - len(scored),
"pass_rate": round(n_passed / len(scored), 3) if scored else None,
"strict_pass_rate": round(n_passed / len(results), 3),
"mean_latency_s": round(sum(r["latency_s"] for r in results) / len(results), 4),
}
if out_path:
with open(out_path, "w", encoding="utf-8") as f:
f.write(json.dumps({"summary": summary}) + "\n")
for r in results:
f.write(json.dumps(r) + "\n")
return summary, results
cases = [
{"id": "c1", "input": "Capital of France?", "expected": "Paris"},
{"id": "c2", "input": "Capital of Japan?", "expected": "Tokyo"},
{"id": "c3", "input": "Capital of Brazil?", "expected": "Brasilia"},
]
def fake_app(question: str) -> str:
if "Brazil" in question:
raise TimeoutError("simulated timeout")
return "Paris" if "France" in question else "Kyoto"
config = {"model": "fake", "prompt_version": "v1", "temperature": 0}
summary, results = run_eval(fake_app, cases, exact_match, config, out_path="run_v1.jsonl")
print(summary["pass_rate"], summary["strict_pass_rate"], summary["n_errors"])
# 0.5 0.333 1The two rates answer different questions. pass_rate is quality among cases that produced an output. strict_pass_rate counts an error as a failure, which is what a user would experience. Report both, and treat a nonzero n_errors as something to fix before you trust either.
Making runs repeatable
Several practices keep two runs comparable.
- Freeze the dataset. The dataset hash in the summary tells you whether two runs used the same cases. If the hashes differ, the scores are not directly comparable. Version dataset files the way you version code.
- Record the full configuration. Store the model name, prompt version, temperature, retrieval settings, and any other parameter that changes behavior. A run with no config is just a number.
- Pin what you can. Set temperature to 0 for evaluation runs where you want the least variation. Where the API supports a seed, pass it. Be aware that even then, providers do not guarantee identical outputs across calls, which is why the statistics chapter covers repeated runs and confidence intervals.
- Keep scorers deterministic and versioned. If you change
exact_matchto strip punctuation, old and new scores are no longer comparable. Treat scorer changes like dataset changes: record them and re-run the baseline. - Save raw outputs. Scoring can be redone later with a better scorer only if the model outputs were kept. Calling the model again costs money and returns different text.
Common errors
| Error | Symptom | Fix |
|---|---|---|
| Averaging over a different number of cases | Scores jump when a few calls fail | Report `n_cases` and `n_errors` with every score |
| Comparing runs on different datasets | A "gain" appears right after the dataset was edited | Compare `dataset_hash` values first |
| Scoring in the same call as generation, with no saved output | A scorer bug forces a full re-run | Save outputs, then score them |
| Unbounded concurrency | Rate-limit errors rise with `workers` | Keep `workers` low, and add retries with backoff inside the app function |
| Mutating cases inside the app | Later cases see changed data | Treat cases as read-only; pass copies if the app edits them |
| Order-dependent results | Results differ when the dataset is shuffled | Key results by `id`, never by position |
Thread pools also have a limit. They help with network-bound calls, but a CPU-heavy scorer, such as a large embedding computation done locally, won't speed up under threads in standard CPython. For that, score in a separate pass using a process pool.
Using the harness day to day
Run the harness first to get a baseline, before you change anything. Make one change, run again with a new config label, and compare the two summary lines and the per-case records. The cases that flipped from pass to fail, or the reverse, are the most informative output, because they show exactly what your change affected. With a small dataset, a few flips can come from nondeterminism alone, so treat small differences with caution until you have the interval estimates covered later in this tutorial.
Exercise
Your harness reports passrate 0.90 for prompt v1 and 0.93 for prompt v2. Looking at the summaries, v1 has nerrors 0 and v2 has n_errors 12 out of 100 cases. What should you conclude, and what two numbers would you check next?
Show answer
Do not conclude that v2 is better. Its passrate is computed over only 88 cases, and the 12 errored cases may be the hard ones. Compare strictpassrate, which counts errors as failures, and the datasethash of both runs to confirm they used the same cases. Then investigate why 12 calls errored (timeouts, rate limits, or a bug in v2's code path) and re-run until n_errors is near zero.
Exercise
Why does the harness store raw outputs in the results file instead of only the pass or fail result?
Show answer
Raw outputs let you re-score the same outputs with a revised or different scorer, such as a stricter regex or an LLM judge, without calling the model again. Calling again costs money and, because outputs are nondeterministic, would return different text, so the new scores would not be comparable to the old ones.