AI & Machine Learning 6 min read 68 viewsReviewed

Build a Tiny Eval Harness Before You Touch That Prompt Again

Changing an LLM system prompt and eyeballing a few outputs is a sampling trap. Here's how to build a small Python eval harness that catches regressions before you deploy.

Build a Tiny Eval Harness Before You Touch That Prompt Again

Changing an LLM system prompt and eyeballing a few outputs is a sampling trap. Here's how to build a small Python eval harness that catches regressions before you deploy.

In this article (9)Expand โ†“

The prompt change that looked fine

You edit the system prompt behind a support bot. You try five examples in a notebook. The answers look better. You deploy.

Two days later, a different class of requests is broken. Users asking about refunds get answers about shipping. The five examples you checked were all shipping questions. This is the sampling trap: your eyeballs only see the cases you happened to try. Real Python's tutorial on LLM evaluation in Python makes the same point: manual inspection is useful while experimenting, but it doesn't give you a repeatable regression signal.

A regression is a case that worked before and fails now. To catch one, you need to run the same inputs against the old prompt and the new prompt and compare. That's an eval harness. It's smaller than you think.

What an eval harness actually is

An eval harness is a script that does four things:

  1. Loads a fixed set of test cases (inputs plus expected properties).
  2. Calls your LLM with each case, using a given prompt.
  3. Scores each output against the expected properties.
  4. Prints a pass/fail report you can diff between prompt versions.

An "oracle" is a source of truth for correctness. For many LLM tasks you don't have one. You can't write a unit test that says the exact string a model should return, because the model is stochastic (it can return different valid outputs for the same input). So you score properties instead of exact matches.

Properties are things like: the output is valid JSON, it mentions the order ID, it doesn't mention a competitor, it's under 300 characters. Each property is a small function that returns true or false.

Write the case set first

Before you touch the prompt again, write down what the feature is supposed to do. Turn each expectation into a case. A case is a dict with an input and a list of checks.

Keep the first version small. Ten to thirty cases is enough to catch obvious regressions. Group them by request class so a failure tells you which class broke. If you only have shipping cases, you'll never see the refund regression.

๐ŸPython
# cases.py
CASES = [
    {
        "id": "refund-001",
        "input": "I was charged twice for order A123. Can I get a refund?",
        "checks": [
            ("mentions_order", lambda out: "A123" in out),
            ("mentions_refund", lambda out: "refund" in out.lower()),
            ("no_shipping_talk", lambda out: "shipping" not in out.lower()),
        ],
    },
    {
        "id": "json-001",
        "input": "Return the ticket as JSON with keys id and priority.",
        "checks": [
            ("valid_json", lambda out: _is_json(out)),
        ],
    },
]

def _is_json(text: str) -> bool:
    import json
    try:
        json.loads(text)
        return True
    except json.JSONDecodeError:
        return False

That's the whole idea. Each check is a plain Python function. You can add checks as you learn what breaks.

Run the harness and score outputs

The harness calls your model, applies the checks, and records results. Keep the model call behind a function so you can swap providers or mock it in tests.

๐ŸPython
# harness.py
import json
from dataclasses import dataclass, field
from cases import CASES

def call_llm(system_prompt: str, user_input: str) -> str:
    # Replace with your provider's SDK call.
    # This stub keeps the harness runnable without network access.
    return f"Echo: {user_input}"

@dataclass
class CaseResult:
    case_id: str
    passed: bool
    failed_checks: list[str] = field(default_factory=list)
    output: str = ""

def run(prompt: str) -> list[CaseResult]:
    results = []
    for case in CASES:
        try:
            output = call_llm(prompt, case["input"])
        except Exception as exc:
            results.append(CaseResult(case["id"], False, [f"error: {exc}"], ""))
            continue
        failed = [name for name, check in case["checks"] if not check(output)]
        results.append(CaseResult(case["id"], not failed, failed, output))
    return results

def report(results: list[CaseResult]) -> None:
    total = len(results)
    passed = sum(r.passed for r in results)
    print(f"{passed}/{total} cases passed")
    for r in results:
        if not r.passed:
            print(f"  FAIL {r.case_id}: {', '.join(r.failed_checks)}")

if __name__ == "__main__":
    report(run("You are a helpful support agent."))

Run it. You'll see something like 1/2 cases passed with the failing case listed. That's your baseline.

Compare old and new prompts

The point of the harness is the diff. Run both prompts, then compare per case. A regression is a case that passed under the old prompt and fails under the new one. A fix is the reverse.

๐ŸPython
# compare.py
from harness import run

OLD_PROMPT = "You are a helpful support agent."
NEW_PROMPT = "You are a support agent. Always mention the order ID."

old = {r.case_id: r for r in run(OLD_PROMPT)}
new = {r.case_id: r for r in run(NEW_PROMPT)}

regressions = [cid for cid in old if old[cid].passed and not new[cid].passed]
fixes = [cid for cid in old if not old[cid].passed and new[cid].passed]

print(f"regressions: {regressions}")
print(f"fixes: {fixes}")

This is the signal you were missing. It tells you which cases got worse, not just whether the average improved. Averages hide regressions: a prompt can improve ten cases and break two, and the average still goes up.

If you want a longer walkthrough of structuring this loop, see our guide on building a repeatable LLM eval harness.

Scoring without a perfect oracle

Most checks fall into three buckets. Pick the cheapest one that catches your failure.

Check type โ€” Catches โ€” Cost โ€” Flakiness ยท Exact match โ€” Fixed outputs (classification labels, IDs) โ€” Low โ€” Low ยท Property check โ€” Format, required fields, forbidden phrases โ€” Low โ€” Low ยท LLM-as-a-judge โ€” Tone, helpfulness, factual consistency โ€” High โ€” High

An LLM-as-a-judge is a second model call that reads the output and scores it. It's useful when you can't write a property check. But it's flaky: the judge can disagree with itself across runs, and it costs money per case. Real Python's tutorial covers judge-based scoring as one option; treat judge scores as a signal, not ground truth.

Start with property checks. Add a judge only for the cases where properties can't express what you need. When you do, pin the judge model version and log its raw output so you can audit disagreements later.

Failure modes you will hit

Stochastic variation. The same prompt can pass one run and fail the next. If a case flips between runs, your check is too strict or the task is genuinely nondeterministic. Run the case a few times and require a majority pass, or loosen the check.

Overfitting to the eval set. If you tune the prompt against the same cases repeatedly, you'll pass the eval and fail in production. Keep a held-out set you don't look at while tuning. Rotate new cases in from real traffic.

Cost and latency. Every case is a model call. Thirty cases times two prompts is sixty calls per comparison. That's fine locally, but don't run it on every commit without a budget. Run it before merging prompt changes, not on every push.

Checks that lie. A check that passes for the wrong reason is worse than no check. If a check tests "refund" in output, a model that says "we cannot refund" passes. Read the outputs when a check is new.

Silent model changes. Providers update models. Your harness passing today doesn't mean it passes next month. Re-run the baseline when you upgrade.

Where this stops being enough

A tiny harness catches format breaks, missing fields, and forbidden phrases. It does not measure whether answers are correct in the world. It does not catch slow degradation in tone across thousands of interactions. It does not replace human review of a sample of real traffic.

For deeper failure patterns, our post on why the model forgot a rule that was in the prompt is a useful companion. And if you're wiring this into a CI loop, the same discipline as testing that actually tells you what happened applies: a green check is only as good as the check.

Build the harness before the next prompt edit. Ten cases and fifty lines of Python will save you a bad deploy.

Sources

Share

About the Author

Comments (0)

Loading comments...