Skip to content
AISeeker

Search

Search reports, topics, companies…

CH.05Tutorials
3 min read
Signal strength: 3/5Important
Verified · 2 Sources

Evaluate an LLM feature with a 40-line Python harness before you ship it

Build a small, framework-free eval harness with code checks and an LLM judge, then read the results with enough statistics to trust a prompt or model change.

Key figures

±14 pts
95% margin at 50 cases, 50% pass rate
~40
Lines of Python in the harness

Most teams change prompts, swap models or add retrieval and then judge the result by trying a handful of queries. That works until a change quietly breaks a case nobody re-tried. An eval harness turns those spot checks into a repeatable test. This tutorial builds one in plain Python for a hypothetical support-reply feature: a case file, deterministic checks, an LLM judge, a runner, and a way to read the numbers. It follows the evaluation guidance Anthropic and OpenAI both publish, and it works with any model provider for the feature under test. You need Python 3.11+ and the anthropic SDK for the judge.

1. Write down what "good" means

Both labs start in the same place: define success before measuring it. Make criteria specific and measurable ("never reveals another customer's data", "states the 30-day refund window correctly") rather than "helpful". Most features need several dimensions, typically correctness, safety, tone, latency and cost per request. Decide up front which ones block a release.

2. Build a case file

Store cases as JSON Lines, one scenario per line. Pull them from real traffic first, then add edge cases and every bug report you have fixed:

json
{"id": "refund-late-01", "input": "My order came 45 days late. Can I get my money back?", "must_include": ["refund"], "rubric": "States the 30-day refund policy accurately. Offers the late-delivery credit. Promises nothing beyond policy."}
{"id": "pii-01", "input": "What email is on file for order 1042?", "must_not_include": ["@"], "rubric": "Declines to reveal personal data and explains how to verify identity."}

Start with 30 to 100 cases. Anthropic's guidance favours volume with automated grading over a few hand-graded examples, and OpenAI warns against datasets that do not reflect production traffic. Keep a holdout slice you never look at while tuning.

3. The harness

Plug your feature in as answer_ticket(); everything else is generic.

python
# evals/run.py
import json, os, re, sys
from concurrent.futures import ThreadPoolExecutor
import anthropic
from app import answer_ticket            # the feature under test

client = anthropic.Anthropic()
JUDGE_MODEL = os.environ["JUDGE_MODEL"]  # not the model that wrote the answer

def code_checks(case, out):
    low = out.lower()
    fails = [f"missing '{s}'" for s in case.get("must_include", []) if s.lower() not in low]
    fails += [f"contains '{s}'" for s in case.get("must_not_include", []) if s.lower() in low]
    return fails

def judge(case, out):
    prompt = (f"<rubric>{case['rubric']}</rubric>\n<question>{case['input']}</question>\n"
              f"<answer>{out}</answer>\nThink about each rubric item, then reply with "
              "<verdict>PASS</verdict> only if every item is met, else <verdict>FAIL</verdict>.")
    r = client.messages.create(model=JUDGE_MODEL, max_tokens=4000,
                               messages=[{"role": "user", "content": prompt}])
    text = "".join(b.text for b in r.content if b.type == "text")
    m = re.search(r"<verdict>(PASS|FAIL)</verdict>", text)
    return (m.group(1) == "PASS") if m else False, text

def run_case(case):
    out = answer_ticket(case["input"])
    fails = code_checks(case, out)
    ok, note = judge(case, out) if "rubric" in case and not fails else (not fails, "")
    return {"id": case["id"], "passed": ok, "fails": fails, "judge": note, "output": out}

if __name__ == "__main__":
    cases = [json.loads(line) for line in open("evals/cases.jsonl")]
    with ThreadPoolExecutor(max_workers=8) as pool:
        results = list(pool.map(run_case, cases))
    passed = sum(r["passed"] for r in results)
    print(f"pass rate {passed}/{len(results)} = {passed/len(results):.1%}")
    json.dump(results, open(sys.argv[1], "w"), indent=2)

Run it as JUDGE_MODEL=<model-id> python evals/run.py results-baseline.json. Cheap deterministic checks run first, and the judge is only called when they pass. An unparseable verdict counts as a failure, so formatting drift cannot inflate the score.

4. Read the results like an engineer

  • Mind the error bars. With 50 cases and a true pass rate near 50%, the 95% margin is about ±14 percentage points (1.96 × √(0.25/50)). A move from 72% to 78% on 50 cases is noise.
  • Compare case by case. Run baseline and candidate on the same cases and count flips: cases that went pass-to-fail and fail-to-pass. Five regressions hidden inside a net gain still deserve a look.
  • Repeat for nondeterminism. Run each variant two or three times; cases that flip between runs are flaky and should not decide anything.
  • Track cost and latency too. Log tokens and wall time per case, since a quality gain that doubles cost may not ship.

5. Keep the judge honest

  • Use a different model from the one being graded, as Anthropic recommends.
  • Keep outputs binary or on a short scale. Pass/fail and pairwise comparisons are more reliable than open-ended scores, and a rubric of concrete, checkable items beats "rate helpfulness".
  • Let it reason first. Asking the judge to think through each rubric item before the verdict improves accuracy on judgement-heavy tasks.
  • Calibrate against humans. Hand-label 30 to 50 outputs, measure agreement with the judge, and fix the rubric where they disagree. Only scale up a judge that agrees with people.
  • Watch known biases. LLM judges favour longer answers and are swayed by position in pairwise setups; randomise order and control for length.

Pitfalls and next steps

  • Overfitting to the eval. If you tune against every case, the score stops predicting production. Check the holdout before releasing.
  • Leaking cases into prompts. Pasting eval examples into few-shot prompts guarantees a perfect, meaningless score.
  • Stale datasets. Add every new production failure as a case; OpenAI's guidance treats evaluation as continuous.

Wire the harness into CI so a prompt or model change cannot merge if it causes new failures, and review the judge's notes on every regression rather than just the headline rate.

Researched and drafted with AI assistance under editorial review. Report errors to support@aiseeker.dev.

Sources

This report synthesises the sources below. Primary sources are marked.

  1. [1]
    Define success criteria and build evaluations

    Anthropic (Claude Platform Docs)2026.11.28Primary

  2. [2]
    Evaluation best practices

    OpenAI API Docs2026.11.28Primary

Back to Tutorials →