03.13 A Minimal Eval Harness

Understand LLMsLesson 13 of 134,447 words7 parts
Module 03 · 0 of 13 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13

You can now call a model, parse its answer, retry its errors and trace what it did. One question is left, and it decides whether your app is any good: how do you know the answers are right? Reading a few outputs by eye does not scale, and it does not tell you whether yesterday's prompt change made things better or worse. This lesson builds the smallest honest answer: a list of test cases, a function that grades each answer, a pass rate, a log of every run, and a check that compares two runs and tells you what got worse. It is about 130 lines of plain Python with no framework and no key, and it is the seed of evalkit, the harness that 10A.1 builds and Module 10A grows.

What you'll learn

  • What an eval case, a grader, a pass rate and a regression are, in plain words
  • How to write four kinds of grader: exact match, contains, regex and a simple rubric scored by a fake judge
  • How to run cases against a model client that is a plain function, so the same harness runs against a scripted fake (free, offline) and against OpenAI or Anthropic (needs a key)
  • How to log every run as JSONL, one line per case, so a run is a file you can open, diff and keep
  • How to compare two runs and name the cases that regressed (passed before, fail now) and the ones that were fixed
  • How cost tracking from 03.7 carries over: every eval request writes a per-request cost record, so you know what an eval run costs
  • How each case run emits a span with 03.12's tracer, so a failing case can be opened as a trace
  • Why a harness this small is worth having, and what it deliberately leaves out

What you don't need

  • API keys. The model in every runnable sample is a scripted fake with canned answers and token counts, so every code block runs offline with real output. The OpenAI and Anthropic client functions need a key and are labelled illustrative.
  • Any framework, database or hosted service. The only storage is text files.
  • Statistics. The lesson reports a plain pass rate. Confidence intervals, repeats and judge calibration belong to Module 10A.
  • A finished 03.12. The harness works without the tracer; with tracer.py in the same folder it adds spans.

Setup

Python 3.11 or newer and the standard library. As of 2 December 2026 nothing here needs an install; to try the provider functions in Part 6 you would add openai and anthropic (package names only; you get the newest release). Make one folder. Save each code block under the file name in its first comment, and run it with python3. If you did 03.12, copy its tracer.py and show_trace.py into the same folder.


What you must be able to do after this lesson#

  • Write an eval case list
  • Build a harness that runs cases against a model
  • Write graders and compute a pass rate
  • Log every run with its cost
  • Compare two runs

Why this matters for an AI engineer#

LLM apps change all the time: you edit a prompt, swap a model, add a tool. Each change can fix one thing and silently break another, and nothing throws an error when it does. A small set of cases that you re-run after every change is the cheapest safety net there is. It is also how teams argue less: "the new prompt is better" becomes "the new prompt passes 5 of 6 cases and broke one".

You'll hear... You'll understand it after...
"Did that prompt change break anything?" Part 5: Comparing two runs
"What's our pass rate?" Part 3: Graders and a pass rate
"Add that bug to the test set." Part 1: Cases
"Is it an exact match or an LLM judge?" 3.3 The rubric and the fake judge
"What does one eval run cost?" Part 4: Logging every run
"Where does evalkit come from?" Part 7: Where this goes next

Part 1: What an eval is, and the case list#

1.1 An eval in one sentence#

An eval (short for evaluation) is a repeatable test for model behaviour: a fixed list of inputs, a rule that decides whether each answer is acceptable, and a number that summarises how many were. A normal unit test checks that code gives one exact output. A model gives different words each time, so an eval usually checks a property of the answer ("contains the refund window", "matches an order-id pattern") rather than the exact string.

The whole harness has four moving parts:

text
cases  ->  client (the model)  ->  grader  ->  score  ->  pass rate + JSONL log

1.2 One case#

A case is one input plus what a good answer looks like. We use a small dataclass with the same core fields as evalkit's Example (id, input, reference, metadata), plus a grader that names how to judge it:

Field Meaning
id A stable name, so you can talk about "the order-id case" across runs
input The prompt sent to the model
reference What a good answer equals, contains, matches, or must mention (its meaning depends on the grader)
grader exact, contains, regex or rubric
metadata Free tags (for example {"feature": "support"}) for slicing results later

Keep cases few and real. Six to twenty cases that came from real failures beat two hundred invented ones. When a bug is reported in production, the first thing to do is add it here as a case.


Part 2: The harness#

2.1 minieval.py#

Everything lives in one file. Read it top to bottom once; the next parts explain each piece.

python
# minieval.py  (standard library only; the seed of evalkit)
"""A minimal eval harness: cases, graders, a pass rate, JSONL logs, a regression check."""
import contextlib
import json
import re
import time
import uuid
from dataclasses import dataclass, field, asdict
from datetime import datetime, timezone

try:                                   # optional: 03.12's tracer. No tracer.py, no spans.
    import tracer
except ImportError:
    tracer = None

# Made-up demo prices in USD per million tokens. Real prices: see 03.7.
PRICE_PER_MTOK = {"demo-model": {"input": 1.00, "output": 4.00}}


# ---------------------------------------------------------------- cases and scores
@dataclass(frozen=True)
class Example:
    """One eval case. Same four core fields as evalkit's Example, plus `grader`."""
    id: str
    input: str
    reference: str = ""                 # what a good answer contains or equals
    grader: str = "exact"               # exact | contains | regex | rubric
    metadata: dict = field(default_factory=dict)


@dataclass
class Score:
    name: str
    value: float                        # 0.0 to 1.0
    passed: bool
    detail: str = ""


# ---------------------------------------------------------------- graders
def grade_exact(ex, output):
    ok = output.strip().lower() == ex.reference.strip().lower()
    return Score("exact", float(ok), ok, "" if ok else f"expected {ex.reference!r}")


def grade_contains(ex, output):
    ok = ex.reference.lower() in output.lower()
    return Score("contains", float(ok), ok, "" if ok else f"missing {ex.reference!r}")


def grade_regex(ex, output):
    ok = re.search(ex.reference, output) is not None
    return Score("regex", float(ok), ok, "" if ok else f"no match for /{ex.reference}/")


def fake_judge(rubric_items, output):
    """Stands in for an LLM judge: one point per rubric item whose keyword appears.
    A real judge is a model call (Module 10A); this one is deterministic so you can test the harness."""
    hits = [kw for kw in rubric_items if kw.lower() in output.lower()]
    return len(hits), len(rubric_items)


def grade_rubric(ex, output):
    items = [p.strip() for p in ex.reference.split(";") if p.strip()]
    got, total = fake_judge(items, output)
    value = got / total
    return Score("rubric", round(value, 2), got == total, f"{got}/{total} rubric items")  # all items to pass; the value keeps the partial credit


GRADERS = {"exact": grade_exact, "contains": grade_contains,
           "regex": grade_regex, "rubric": grade_rubric}


# ---------------------------------------------------------------- the run
def cost_usd(model, input_tokens, output_tokens):
    p = PRICE_PER_MTOK[model]
    return round((input_tokens * p["input"] + output_tokens * p["output"]) / 1_000_000, 8)


def append_jsonl(path, record):
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(record) + "\n")


def run_eval(examples, client, *, model, run_name, results_path, cost_path):
    """client(prompt) -> {"text": str, "usage": {"input_tokens": int, "output_tokens": int}}"""
    rows = []
    run_span = tracer.span("eval.run", run=run_name, model=model) if tracer else contextlib.nullcontext({})
    with run_span:                                      # one trace per run, one child span per case
        for ex in examples:
            case_span = tracer.span("eval.case", case_id=ex.id) if tracer else contextlib.nullcontext({})
            with case_span as attrs:
                start = time.perf_counter()
                status, output, usage, cost = "ok", "", {"input_tokens": 0, "output_tokens": 0}, 0.0
                try:
                    reply = client(ex.input)
                    output, usage = reply["text"], reply["usage"]
                    cost = cost_usd(model, usage["input_tokens"], usage["output_tokens"])
                except Exception as exc:                # a failed call is a failed case, not a crash
                    status = f"error:{type(exc).__name__}"
                latency_ms = round((time.perf_counter() - start) * 1000, 1)
                score = GRADERS[ex.grader](ex, output) if status == "ok" else Score(ex.grader, 0.0, False, status)
                attrs.update(input_tokens=usage["input_tokens"], output_tokens=usage["output_tokens"],
                             cost_usd=cost, passed=score.passed)
            # 03.7-shaped cost record: one line per model request
            append_jsonl(cost_path, {
                "ts": datetime.now(timezone.utc).isoformat(timespec="seconds"),
                "call_id": uuid.uuid4().hex, "env": "eval", "feature": f"eval:{run_name}",
                "provider": "demo", "model": model,
                "uncached_input_tokens": usage["input_tokens"], "output_tokens": usage["output_tokens"],
                "cost_usd": cost, "cost_source": "computed", "price_version": "demo-1",
                "latency_ms": latency_ms, "status": status})
            row = {"run": run_name, "example_id": ex.id, "grader": ex.grader, "output": output,
                   "score": score.value, "passed": score.passed, "detail": score.detail,
                   "cost_usd": cost, "latency_ms": latency_ms, "metadata": ex.metadata}
            append_jsonl(results_path, row)
            rows.append(row)
    return rows


def pass_rate(rows):
    return sum(r["passed"] for r in rows) / len(rows)


# ---------------------------------------------------------------- regression check
def compare(old_rows, new_rows):
    old = {r["example_id"]: r for r in old_rows}
    new = {r["example_id"]: r for r in new_rows}
    regressions = [i for i in new if i in old and old[i]["passed"] and not new[i]["passed"]]
    fixes = [i for i in new if i in old and not old[i]["passed"] and new[i]["passed"]]
    return {"old_rate": pass_rate(old_rows), "new_rate": pass_rate(new_rows),
            "regressions": regressions, "fixes": fixes}

The design choices worth noticing:

  • The model is a function. client(prompt) returns {"text": ..., "usage": {...}}. Nothing in the harness knows about OpenAI or Anthropic. That seam is the same one 03.10 uses for fake clients, and the same one evalkit uses (there the callable returns just the text; the one-line adapter is lambda p: client(p)["text"]).
  • A failed call is a failed case, not a crash. An exception from client becomes status = "error:TimeoutError" and a score of zero, and the run continues. Only the exception's class name is kept, for the same privacy reasons as 03.12, Part 5.
  • Every request writes a cost record. More on that in Part 4.
  • The tracer is optional. If tracer.py imports, every run becomes one trace with one child span per case (4.3).

2.2 The cases and a scripted model#

Now six cases, and two scripted "model versions". Version v1 stands for your current prompt. Version v2 stands for a change you made. Both are fakes with canned text and token counts so the lesson runs offline.

python
# demo_run.py  (standard library only; the model is a scripted fake)
import time

from minieval import Example, run_eval, pass_rate

CASES = [
    Example("capital", "What is the capital of France? One word.", "paris", "exact"),
    Example("refund-window", "How many days do customers have to request a refund?", "30 days", "contains"),
    Example("order-id", "Extract the order id from: 'Order A-4471 is late.'", r"A-\d{4}", "regex"),
    Example("tone", "Reply to an angry customer whose parcel is late.", "sorry; refund; tracking", "rubric"),
    Example("shipping", "Which carrier ships express orders?", "DHL", "contains"),
    Example("json-ok", "Reply with exactly the word: ready", "ready", "exact"),
]

# Scripted answers for two versions of the same prompt. Token counts are canned too.
SCRIPT = {
    "v1": {
        "What is the capital of France? One word.": "Paris",
        "How many days do customers have to request a refund?": "Customers have 30 days to ask for a refund.",
        "Extract the order id from: 'Order A-4471 is late.'": "The order id is A-4471.",
        "Reply to an angry customer whose parcel is late.": "We are sorry. Here is your tracking link.",
        "Which carrier ships express orders?": "Express orders go with UPS.",
        "Reply with exactly the word: ready": "ready",
    },
    "v2": {
        "What is the capital of France? One word.": "Paris",
        "How many days do customers have to request a refund?": "Customers have 30 days to ask for a refund.",
        "Extract the order id from: 'Order A-4471 is late.'": "The order id is A4471.",
        "Reply to an angry customer whose parcel is late.": "We are sorry. We offer a refund and a tracking link.",
        "Which carrier ships express orders?": "Express orders go with DHL.",
        "Reply with exactly the word: ready": "ready",
    },
}


def fake_client(version):
    def client(prompt):
        time.sleep(0.01)
        text = SCRIPT[version][prompt]
        return {"text": text, "usage": {"input_tokens": 20 + len(prompt) // 4,
                                        "output_tokens": max(1, len(text) // 4)}}
    return client


if __name__ == "__main__":
    for version in ("v1", "v2"):
        rows = run_eval(CASES, fake_client(version), model="demo-model", run_name=version,
                        results_path="results.jsonl", cost_path="calls.jsonl")
        print(f"{version}: {sum(r['passed'] for r in rows)}/{len(rows)} passed, pass rate {pass_rate(rows):.0%}")
        for r in rows:
            if not r["passed"]:
                print(f"   FAIL {r['example_id']:<14} {r['detail']}")

Run it:

bash
python3 demo_run.py

Real output:

text
v1: 4/6 passed, pass rate 67%
   FAIL tone           2/3 rubric items
   FAIL shipping       missing 'DHL'
v2: 5/6 passed, pass rate 83%
   FAIL order-id       no match for /A-\d{4}/

Version v2 has the higher pass rate, and that is the number most people would stop at. Part 5 shows why that is not enough.


Part 3: Graders and a pass rate#

3.1 Exact, contains and regex#

The first three graders are plain string tests, and they are deterministic: the same output always gets the same verdict, which is why you reach for them first.

Grader Passes when Good for Weakness
exact the answer equals the reference (ignoring case and surrounding whitespace) one-word answers, labels, yes or no "Paris." with a full stop fails if you forgot to normalise
contains the reference text appears inside the answer a fact that must be stated the answer can contain it and still be wrong overall
regex a pattern matches anywhere ids, dates, formats a too-loose pattern passes bad answers; a too-strict one rejects good ones

In the run above, order-id is a regex case. Version v2 answered A4471 without the hyphen, so A-\d{4} found no match. The detail field says why, which is what you read first when a case fails.

3.2 The score and the pass rate#

A grader returns a Score: a value between 0 and 1 (partial credit), a passed flag (the yes-or-no gate) and a short detail. The pass rate is the share of cases that passed:

text
pass rate = cases passed / cases run

Report it as both a fraction and a percentage ("5/6, 83%"). With only six cases, one case is 17 points of pass rate, so treat small differences with care. That is a measurement-noise question that Module 10A handles properly; for now, never celebrate a one-case change.

3.3 The rubric and the fake judge#

Some answers cannot be checked with a string test: "Is the reply to an angry customer polite and does it offer a fix?" A rubric turns that into a short checklist of required points, and a judge scores the answer against it. In production the judge is usually another model call (an LLM judge), which Module 10A covers properly because judges are themselves unreliable and need checking.

For this lesson the judge is a fake: a function that gives one point for each rubric item whose keyword appears in the answer. It is deterministic, so you can test the harness itself without a key or a flaky judge:

python
def fake_judge(rubric_items, output):
    hits = [kw for kw in rubric_items if kw.lower() in output.lower()]
    return len(hits), len(rubric_items)

The tone case uses the rubric sorry; refund; tracking. Version v1 mentioned sorry and tracking but not a refund, so it scored 2/3 (value 0.67) and failed, because this harness requires every item to pass. The partial value is still logged, so you can see "nearly".

3.4 Test the graders themselves#

A grader is code, and code can be wrong. A wrong grader makes every number meaningless, so give the graders their own small test with known answers. It needs no model:

python
# test_graders.py  (standard library only; run with python3 test_graders.py)
from minieval import Example, GRADERS, compare


def grade(kind, reference, output):
    return GRADERS[kind](Example("t", "q", reference, kind), output)


assert grade("exact", "paris", " Paris\n").passed
assert not grade("exact", "paris", "It is Paris.").passed
assert grade("contains", "30 days", "You have 30 days.").passed
assert grade("regex", r"A-\d{4}", "id A-4471").passed
assert not grade("regex", r"A-\d{4}", "id A4471").passed
assert grade("rubric", "sorry; refund", "Sorry, we will refund you.").passed
r = grade("rubric", "sorry; refund", "Sorry about that.")
assert not r.passed and r.value == 0.5       # partial credit, but not a pass
print("all grader tests passed")
text
all grader tests passed

Part 4: Logging every run, and what it cost#

4.1 One line per case#

run_eval appends one JSON line per case to results.jsonl. A line is the whole story of one case in one run. Real output of the first line for v1:

json
{"run": "v1", "example_id": "capital", "grader": "exact", "output": "Paris", "score": 1.0, "passed": true, "detail": "", "cost_usd": 3.4e-05, "latency_ms": 12.5, "metadata": {}}

Append, never overwrite: the file is a history. Because every line carries its run name, two runs can live in one file and be compared later, and you can open the file in any editor or load it with json.loads line by line.

4.2 The per-request cost record#

Eval runs spend real money once the model is real, and a cost nobody tracks becomes a surprise. So each model request also writes a record in the shape that 03.7, 5.1 defines for its cost tracker, in a separate calls.jsonl. This harness fills a small subset of that record (ts, call_id, env, feature, provider, model, uncached_input_tokens, output_tokens, cost_usd, cost_source, price_version, latency_ms, status) and leaves the rest out. Real output of one line:

json
{"ts": "2026-12-02T02:59:34+00:00", "call_id": "4387085738a84e9c8e5c80400b017cac", "env": "eval", "feature": "eval:v1", "provider": "demo", "model": "demo-model", "uncached_input_tokens": 32, "output_tokens": 10, "cost_usd": 7.2e-05, "cost_source": "computed", "price_version": "demo-1", "latency_ms": 12.5, "status": "ok"}

Two choices matter here. The env is eval, and the feature is eval:<run name>, so eval spend never mixes with production spend in one total. And the prices are made-up demo numbers (demo-model); a real harness would use the dated price table from 03.7, Part 4. That is how cost tracking starts in Module 03 and carries through the whole path: the same record shape for an app call and an eval call.

Answering "what do my eval runs cost?" is a short loop over that file:

python
# cost_report.py  (standard library only)
import json
from collections import defaultdict

spend, calls = defaultdict(float), defaultdict(int)
for line in open("calls.jsonl", encoding="utf-8"):
    r = json.loads(line)
    spend[r["feature"]] += r["cost_usd"]
    calls[r["feature"]] += 1
for feature in sorted(spend):
    print(f"{feature:<10} calls={calls[feature]}  cost=${spend[feature]:.6f}")
print(f"{'total':<10} calls={sum(calls.values())}  cost=${sum(spend.values()):.6f}")

Real output after running both versions:

text
eval:v1    calls=6  cost=$0.000315
eval:v2    calls=6  cost=$0.000327
total      calls=12  cost=$0.000642

4.3 One span per case#

If tracer.py from 03.12 is in the folder, run_eval wraps the run in an eval.run span and each case in an eval.case child span, carrying token counts, cost and whether the case passed. Open the trace file with 03.12's viewer:

bash
python3 show_trace.py trace.jsonl

Real output (the two eval.run roots are the v1 and v2 runs; times will differ):

text
trace 79cf64fe2b4f44eaa2df8591f198c33c
eval.run      72.9 ms  ok
  eval.case     12.5 ms  ok  in=30 out=1 cost=$0.000034
  eval.case     11.4 ms  ok  in=33 out=10 cost=$0.000073
  eval.case     12.1 ms  ok  in=32 out=5 cost=$0.000052
  eval.case     12.5 ms  ok  in=32 out=10 cost=$0.000072
  eval.case     12.5 ms  ok  in=28 out=6 cost=$0.000052
  eval.case     10.1 ms  ok  in=28 out=1 cost=$0.000032
eval.run      75.6 ms  ok
  eval.case     12.5 ms  ok  in=30 out=1 cost=$0.000034
  eval.case     12.5 ms  ok  in=33 out=10 cost=$0.000073
  eval.case     12.5 ms  ok  in=32 out=5 cost=$0.000052
  eval.case     11.3 ms  ok  in=32 out=13 cost=$0.000084
  eval.case     12.5 ms  ok  in=28 out=6 cost=$0.000052
  eval.case     12.5 ms  ok  in=28 out=1 cost=$0.000032

The case id and the passed flag are stored on each span, so a failing case in the results file can be found in the trace file by id. When the model call inside a case is a real provider call, the span is also the place where a provider request id would go (03.12, Part 3).

4.4 When the model call itself fails#

A timeout, a rate limit or a refusal should be a failed case you can see, not a run that dies halfway. Here the fake client raises a TimeoutError for the refund case:

python
# flaky_demo.py  (standard library only)
from demo_run import CASES, fake_client
from minieval import run_eval, pass_rate

good = fake_client("v2")


def flaky(prompt):
    if "refund" in prompt:
        raise TimeoutError("read timed out")        # the model call itself fails
    return good(prompt)


rows = run_eval(CASES, flaky, model="demo-model", run_name="flaky",
                results_path="flaky_results.jsonl", cost_path="flaky_calls.jsonl")
print(f"pass rate {pass_rate(rows):.0%}")
for r in rows:
    if not r["passed"]:
        print(r["example_id"], "|", r["detail"], "| cost", r["cost_usd"])

Real output:

text
pass rate 67%
refund-window | error:TimeoutError | cost 0.0
order-id | no match for /A-\d{4}/ | cost 5.2e-05

The errored case is counted as failed, costs nothing in the demo (no tokens came back), and says why. In real use a timeout may still be billed (03.8, 6.6), and a fuller harness would retry transient errors with the rules from 03.8 before counting a failure.


Part 5: Comparing two runs#

5.1 Why the pass rate is not enough#

In 2.2 the pass rate went from 67% to 83%. That looks like a win. But two cases were fixed and one case that used to pass now fails. A single number hides that. A user who relied on order-id extraction just got a worse product, and nobody saw it.

A regression is a case that passed in the old run and fails in the new one. The question to ask after every change is "what regressed?", before "did the pass rate go up?".

5.2 The comparison#

compare() (in minieval.py) lines up two runs by case id and returns the two pass rates, the cases that regressed and the cases that were fixed. A tiny command-line wrapper reads both runs from the log:

python
# compare_runs.py  (standard library only)
import json
import sys

from minieval import compare

rows = [json.loads(line) for line in open("results.jsonl", encoding="utf-8")]
old = [r for r in rows if r["run"] == sys.argv[1]]
new = [r for r in rows if r["run"] == sys.argv[2]]
c = compare(old, new)
print(f"{sys.argv[1]} -> {sys.argv[2]}: pass rate {c['old_rate']:.0%} -> {c['new_rate']:.0%}")
print("fixed:     ", c["fixes"] or "none")
print("regressed: ", c["regressions"] or "none")
cost = sum(r["cost_usd"] for r in new)
print(f"cost of the {sys.argv[2]} run: ${cost:.6f}")
sys.exit(1 if c["regressions"] else 0)     # a non-zero exit code can fail a CI job
bash
python3 compare_runs.py v1 v2

Real output:

text
v1 -> v2: pass rate 67% -> 83%
fixed:      ['tone', 'shipping']
regressed:  ['order-id']
cost of the v2 run: $0.000327

The script exits with code 1 when anything regressed, and 0 otherwise. A non-zero exit code is exactly what makes a CI job fail (03.10, Part 12 shows how to run key-free checks in CI). So a prompt change that breaks an old case can be stopped before it ships.


Part 6: Swapping in a real client#

Deep-dive

The harness only needs a function that takes a prompt and returns {"text", "usage"}. Here is that function for the two main providers. It needs keys, so no output is shown and it is illustrative. The usage fields were checked against the providers' prompt-caching documentation on 2 December 2026:

  • OpenAI Responses: usage.input_tokens is the total input and includes cached tokens (usage.input_tokens_details.cached_tokens is the cached part); usage.output_tokens is the output.
  • Anthropic Messages: usage.input_tokens counts only tokens after the last cache breakpoint; cache_read_input_tokens and cache_creation_input_tokens are reported separately; usage.output_tokens is the output.
python
# real_clients.py  (illustrative: needs OPENAI_API_KEY and ANTHROPIC_API_KEY; not run)
from openai import OpenAI
from anthropic import Anthropic

openai_client, anthropic_client = OpenAI(), Anthropic()


def openai_call(prompt):
    resp = openai_client.responses.create(model="gpt-6-luna", input=prompt, max_output_tokens=300)
    cached = resp.usage.input_tokens_details.cached_tokens        # part of input_tokens
    return {"text": resp.output_text,
            "usage": {"input_tokens": resp.usage.input_tokens - cached,   # uncached input only
                      "output_tokens": resp.usage.output_tokens}}


def anthropic_call(prompt):
    msg = anthropic_client.messages.create(
        model="claude-haiku-5-5", max_tokens=300,
        messages=[{"role": "user", "content": prompt}])
    return {"text": msg.content[0].text,
            "usage": {"input_tokens": msg.usage.input_tokens,          # already excludes cache reads and writes
                      "output_tokens": msg.usage.output_tokens}}

Each function converts to the same convention as 03.7: input_tokens here means uncached input. With caching off, the two conversions are trivial; with caching on, they are why 03.7 insists on one convention.

To use one, pass it as the client and give the run the matching model name and a real price row:

python
# illustrative: needs a key and a price row for the model
from real_clients import openai_call
rows = run_eval(CASES, openai_call, model="gpt-6-luna", run_name="gpt-v1",
                results_path="results.jsonl", cost_path="calls.jsonl")

Three things change when the client is real:

  1. Answers vary between runs. The same case may pass once and fail once. With a real model, run each case a few times and look at the share that pass. 04.9, Part 1 and Module 10A cover this properly.
  2. Calls cost money and take time. Keep the set small, cap max_output_tokens, and run the cheap model first. 03.9 shows how to run cases concurrently or through a Batch API.
  3. Tests that call a real model are not unit tests. Keep the fake-client run in your normal test suite, and run the real one on demand or on a schedule (03.10, 7.8).

Part 7: Where this goes next#

Deep-dive

This harness is deliberately small. Here is what it leaves out, and where each piece comes from:

Missing piece Where it arrives
Scorers as separate objects, metadata slices, a report class 10A.1, Part 6 builds evalkit/core.py with Example, Score, Scorer and run_eval
Datasets from files, splits, validation 10A.2
More graders and metrics 10A.3
A real LLM judge, and checking the judge 10A.4
Repeats, caching, parallel runs, CI 10A.8
Evaluating the prompt itself, not only the app 04.9

The names in this lesson (Example, Score, a client callable, a JSONL result log) were chosen so that moving to evalkit is a rename, not a rewrite. The one deliberate difference is that here the client returns tokens as well as text, because cost tracking starts now.


Common misconceptions#

  • "I need a framework before I can evaluate." Six cases, a grader function and a loop are an eval. Frameworks add datasets, judges, dashboards and CI integration. They do not replace the habit.
  • "A higher pass rate means the change is better." Not if it broke a case that used to pass. Read the regressions first.
  • "Evals need a key and cost money." The harness runs free against a fake, which tests your grading code. You only spend money when you measure a real model, and the cost log tells you how much.
  • "An LLM judge is more accurate than string checks." A judge is more flexible, not more accurate. It can be wrong and biased, and it costs tokens. Use deterministic graders wherever they are good enough.
  • "If a case fails, the model is wrong." The grader, the reference or the case itself can be wrong. Read the failing output before you change the prompt.
  • "More cases is always better." A few cases drawn from real failures beat many invented ones. Add a case when something breaks.

Key takeaways#

  • An eval is a fixed list of cases, a rule that decides whether each answer is acceptable, and a number that summarises the result.
  • The model is a plain function (client(prompt) returns text and usage), so the same harness runs against a fake and against OpenAI or Anthropic.
  • Use deterministic graders (exact, contains, regex) first, a rubric with a judge when you must, and test the graders themselves.
  • Log every run as JSONL, one line per case, and append so history is kept.
  • Compare runs by case id and read the regressions before the pass rate. Exit non-zero on a regression so CI can stop a bad change.
  • Cost tracking starts in Module 03: every eval request writes a record in the shape of 03.7's cost log, and every case can emit a span with 03.12's tracer.
  • This harness is the seed of evalkit. Modules 10A and 10B grow it into evalkit, then DeepEval (10B.2 onward).

Terms introduced in this lesson#

Term Meaning
Eval A repeatable test for model behaviour: cases, a grading rule and a summary number
Eval case One input plus what a good answer looks like (reference) and which grader to use
Grader A function that turns one model answer into a score and a pass or fail
Exact match / contains / regex Three deterministic string graders, from strictest to most flexible
Rubric A short checklist of points a good answer must cover
Judge (LLM judge) A model, or here a fake function, that scores an answer against a rubric
Pass rate The share of cases that passed
Client (as a function) client(prompt) returning text and token usage; the seam that lets a fake or a real model plug in
Regression A case that passed in the old run and fails in the new one
Run One pass of all cases against one model and prompt version, logged under a run name
JSONL A text file with one JSON object per line, appended to over time
evalkit The shared eval package that Module 10A builds; this harness is its seed

Exercises#

  1. Add a case from a bug. A customer reports that the bot says "returns accepted within 14 days". Add a refund-window-14 case that catches an answer containing 14 days. Hint: the contains grader checks that text is present, so you need either a regex that fails on 14 days, or a new not_contains grader. Write the second and add it to GRADERS.
  2. A not_contains grader. Implement grade_not_contains, register it, and add a unit test for it in test_graders.py. Hint: copy grade_contains and invert the check. Test both a passing and a failing answer.
  3. A pass-rate threshold. Make compare_runs.py also exit with code 1 when the new pass rate is below 80%, even if nothing regressed. Hint: c["new_rate"] < 0.8. Decide whether the threshold should be a command-line argument.
  4. Slice by metadata. Tag each case with {"feature": "support"} or {"feature": "extraction"}, then print the pass rate per feature for one run. Hint: group rows by r["metadata"]["feature"]. A pass rate for each feature is what tells you where a prompt change hurt.
  5. Spend by run. Run v1 three times, then use cost_report.py to see the total. Which line would you check to find a run that suddenly cost double? Hint: calls= should stay equal across runs of the same cases; if calls is the same and cost doubled, output tokens grew. Compare output_tokens in calls.jsonl.
  6. Open a failing case as a trace. With 03.12's tracer.py in the folder, find the eval.case span for the shipping case in v1 and read its attributes. Hint: spans store case_id and passed. Write a three-line filter over trace.jsonl.

Check yourself#

  1. What are the four parts of the harness, in order?
  2. Why is the model passed in as a plain function?
  3. Why use exact, contains or regex before a judge?
  4. What is a pass rate, and why is one-case movement not meaningful on six cases?
  5. What is a regression, and why read the regressions before the pass rate?
  6. Why does a failed model call count as a failed case instead of crashing the run?
  7. Why does each eval request write a cost record, and why is env set to eval?
  8. How do OpenAI's and Anthropic's input_tokens differ when prompt caching is used?
  9. Why does the script that compares runs exit with a non-zero code on a regression?
  10. What does Module 10A add to this harness?

Further resources#


← 03.12 — Minimal Tracing for LLM Calls | Module 04: Prompt & Context Engineering →

Modules 10A and 10B grow this into evalkit, then DeepEval (10B.2 onward).

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close