Chapter 4 · Experiments and Evaluation
Metrics and Experiment Reports: Accuracy, Precision, Recall, Latency and CSV
- Page 16 of 24
- 20 min read
Last page you could run two prompt versions on the same cases and read the rows. Reading six rows works; reading sixty does not, and "version 2 looks cleaner" is not a result you can put in a report. This page adds the numbers: the share of answers that are right, which kinds of mistakes a prompt makes, how long and how costly a run is, how much a repeated test varies, and a CSV that a colleague can open in a spreadsheet.
We keep building the small toolkit. The new file is metrics.py; the files from Python Prompt Experiments: Test Cases, Runners, JSONL Logs and Mock Mode are needed again because each page runs in a fresh folder. Everything uses toy providers, so every number below is a repeatable stand-in that tests your scoring code. It says nothing about how a real model would score.
What you will learn
- How to add a human-written expected answer or rubric to a test case, and when exact match is the right check.
- How to compute accuracy, field-level extraction accuracy, and precision and recall with a small confusion matrix, from scratch.
- How to use human review for quality that code cannot judge, with a blind review sheet in CSV.
- How to record latency, usage and estimated cost honestly, repeat a test to see variability and export an experiment report to CSV.
Files from the previous page, again
The two prompt templates, the toy provider and a shortened runner.py (the same logic as before, without the CSV loader and the side-by-side printer) are repeated here so this page runs on its own.
# file: prompts/v1.txt
Classify the support message as billing, delivery or other.
### MESSAGE
{text}# file: prompts/v2.txt
Classify the support message as billing, delivery or other.
A refund request is billing. Reply with the label only.
### MESSAGE
{text}# file: toys.py
"""toys.py: stand-in providers (NOT real models) so experiments can be repeated exactly."""
import random
BILLING = ["invoice", "charged", "payment"]
DELIVERY = ["parcel", "package", "delivery", "arrived", "tracking", "driver"]
def make_triage(seed=7, noise=0.3):
"""Toy classifier. It reads the prompt: a 'refund' hint adds a billing word, 'label only' stops wordy
replies on long messages. With temperature above 0 it sometimes answers 'other' (seeded)."""
rng = random.Random(seed)
def provider(messages, temperature=0, **settings):
head, text = messages[-1]["content"].lower().split("### message", 1)
billing = BILLING + (["refund"] if "refund" in head else [])
label = ("billing" if any(w in text for w in billing)
else "delivery" if any(w in text for w in DELIVERY) else "other")
if temperature > 0 and rng.random() < noise:
label = "other"
if "label only" not in head and len(text.split()) > 9:
return f"I think it is {label}."
return label
return provider# file: runner.py
"""runner.py (shortened from the previous page): load cases, run one prompt version, log JSONL."""
import hashlib, json
from pathlib import Path
from promptlab import ProviderError, render
def load_cases(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def run_experiment(client, version, cases, log, **settings):
template = Path("prompts", f"{version}.txt").read_text(encoding="utf-8")
sha = hashlib.sha256(template.encode()).hexdigest()[:8]
records = []
Path(log).parent.mkdir(parents=True, exist_ok=True)
with open(log, "a", encoding="utf-8") as out:
for case in cases:
rec = {"case": case["id"], "version": version, "prompt_sha": sha,
"model": client.model, "settings": settings}
try:
r = client.complete([{"role": "user", "content": render(template, text=case["text"])}], **settings)
rec.update(status="ok", text=r.text.strip(), input_tokens=r.usage.input_tokens,
output_tokens=r.usage.output_tokens, latency_ms=r.latency_ms)
except ProviderError as exc:
rec.update(status="error", error=str(exc))
out.write(json.dumps(rec, sort_keys=True) + "\n")
out.flush()
records.append(rec)
return recordsExpected answers and rubrics
A score needs something to compare with. Write the expected answer yourself, before you look at any output, and store it with the case. If you write it after reading the model's answer you will find yourself agreeing with it. The cases are now twelve invented support messages, each with a human-written label in expected. Two of them are deliberately hard: c6 contains two problems and c9 uses a word ("ship") the toy does not know.
# file: cases.json
[
{"id": "c1", "text": "I was charged twice for invoice 3318.", "expected": "billing"},
{"id": "c2", "text": "My parcel has not arrived after two weeks.", "expected": "delivery"},
{"id": "c3", "text": "Please send me a refund for the broken lamp that I bought last month.", "expected": "billing"},
{"id": "c4", "text": "How do I change my profile photo?", "expected": "other"},
{"id": "c5", "text": "Tracking shows nothing for my package.", "expected": "delivery"},
{"id": "c6", "text": "The driver left the box outside in the rain, and the invoice total looks wrong too.", "expected": "delivery"},
{"id": "c7", "text": "Why was my card debited two times?", "expected": "billing"},
{"id": "c8", "text": "The payment page crashed and I think I was charged.", "expected": "billing"},
{"id": "c9", "text": "Can you ship to a post office box?", "expected": "delivery"},
{"id": "c10", "text": "Where can I download the mobile app?", "expected": "other"},
{"id": "c11", "text": "The package arrived damaged and I want a refund.", "expected": "billing"},
{"id": "c12", "text": "Thanks, the invoice is correct now and everything is fine.", "expected": "other"}
]Not every task has one right string. For free text such as a reply draft, write a rubric: a short list of yes/no checks, written before the run, that two people could apply and mostly agree on.
| Task type | Expected answer | Check |
|---|---|---|
| Label, id, yes/no | The exact value | Exact match (next section) |
| Extraction to fields | The record with true values | Field-by-field comparison |
| Reply draft | A rubric: names the order id; apologises once; states the next step; at most 60 words; promises nothing that was not given | Code for the countable items, a person for the rest |
Exact-match accuracy
Accuracy is the share of cases where the output equals the expected answer. Exact match is the right check when the task has a small closed set of answers (labels, yes/no, ids), because it is cheap, repeatable and needs no judgement. It is the wrong check for summaries or advice. Here is the scoring file; it only uses the standard library.
# file: metrics.py
"""metrics.py: small scoring functions (standard library only)."""
import csv
from collections import Counter
def norm(value):
"""Lowercase, trim and collapse spaces, so 'Billing.' and 'billing' match."""
return " ".join(str(value).lower().split()).strip(".!")
def accuracy(pairs):
"""Share of (predicted, expected) pairs that match exactly after norm()."""
return sum(norm(p) == norm(g) for p, g in pairs) / len(pairs) if pairs else 0.0
def first_label(text, labels):
"""Lenient reading of a wordy answer: the label that appears earliest in text, else 'none'."""
found = [(text.lower().find(l), l) for l in labels if l in text.lower()]
return min(found)[1] if found else "none"
def field_accuracy(preds, golds, fields):
"""Accuracy per field, plus 'all' = share of records where every field is right."""
n = len(golds)
result = {f: sum(norm(p.get(f)) == norm(g[f]) for p, g in zip(preds, golds)) / n for f in fields}
result["all"] = sum(all(norm(p.get(f)) == norm(g[f]) for f in fields) for p, g in zip(preds, golds)) / n
return result
def confusion(pairs):
"""Counter of (expected, predicted) -> count."""
return Counter((g, p) for p, g in pairs)
def precision_recall(pairs, labels):
"""Per label: precision = tp/(tp+fp), recall = tp/(tp+fn), f1 = their harmonic mean (0.0 if undefined)."""
cm, out = confusion(pairs), {}
for label in labels:
tp = cm[(label, label)]
fp = sum(c for (g, p), c in cm.items() if p == label and g != label)
fn = sum(c for (g, p), c in cm.items() if g == label and p != label)
pr = tp / (tp + fp) if tp + fp else 0.0
rc = tp / (tp + fn) if tp + fn else 0.0
out[label] = {"precision": round(pr, 2), "recall": round(rc, 2),
"f1": round(2 * pr * rc / (pr + rc), 2) if pr + rc else 0.0}
return out
def show_confusion(pairs, labels):
cm, cols = confusion(pairs), labels + ["none"]
print(f"{'expected/predicted':<20}" + "".join(f"{c:>10}" for c in cols))
for g in labels:
print(f"{g:<20}" + "".join(f"{cm[(g, c)]:>10}" for c in cols))
def write_csv(path, rows):
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)Now run both versions and score them twice. Strict accuracy compares the whole output with the expected label. Lenient accuracy first looks for the label word inside the output. The gap between the two is the part of the failure that is about format, not about the decision.
from promptlab import Client
from runner import load_cases, run_experiment
from metrics import *
from toys import make_triage
LABELS = ["billing", "delivery", "other"]
cases = load_cases("cases.json")
gold = {c["id"]: c["expected"] for c in cases}
def pairs(records, lenient=False):
"""(predicted, expected) for the cases that returned an answer; error records are left out."""
return [(first_label(r["text"], LABELS) if lenient else r["text"], gold[r["case"]])
for r in records if r["status"] == "ok"]
client = Client(make_triage(), model="toy-triage")
runs = {v: run_experiment(client, v, cases, f"logs/{v}.jsonl") for v in ("v1", "v2")}
for v, records in runs.items():
print(v, "strict", round(accuracy(pairs(records)), 3), "lenient", round(accuracy(pairs(records, True)), 3))v1 strict 0.417 lenient 0.5
v2 strict 0.667 lenient 0.667Version 1 loses on format (strict is lower than lenient) and on the decision (lenient is still only half). Version 2 closes the format gap, and its two numbers are equal. Report both when answers can be wordy, and remember that twelve cases give very coarse numbers: one case moves accuracy by about eight points.
Field-level extraction accuracy
When the task is extraction, one number for "the record" hides which field fails. Compare field by field and also count records that are fully right. The five invoices below are invented; the "predicted" side is what an extraction prompt returned.
golds = [{"vendor": "Nile Tools", "total": "120.50", "currency": "USD"},
{"vendor": "Aiko Print", "total": "89.00", "currency": "JPY"},
{"vendor": "Lena GmbH", "total": "1205.00", "currency": "EUR"},
{"vendor": "Mateo SAS", "total": "40.00", "currency": "COP"},
{"vendor": "Priya Foods", "total": "15.75", "currency": "INR"}]
preds = [{"vendor": "Nile Tools", "total": "120.50", "currency": "USD"},
{"vendor": "Aiko Print", "total": "89.00", "currency": None},
{"vendor": "Lena GMBH", "total": "1,205.00", "currency": "EUR"},
{"vendor": "Mateo", "total": "40.00", "currency": "COP"},
{"vendor": "Priya Foods", "total": "15.75", "currency": "INR"}]
print({k: round(v, 2) for k, v in field_accuracy(preds, golds, ["vendor", "total", "currency"]).items()}){'vendor': 0.8, 'total': 0.8, 'currency': 0.8, 'all': 0.4}Every field scores 0.8, yet only 2 of 5 whole records are fully right (all is 0.4), because the errors fall in different records. Look at the per-field numbers to find which field to fix, and at all to see what a user gets. Two misses deserve thought: Lena GMBH differs only in case, which norm forgives, and 1,205.00 versus 1205.00 is a format difference that exact comparison counts as wrong. Decide such rules on purpose (compare numbers as numbers, ignore thousands separators) and write them down, because they change the score.
Classification precision and recall
Accuracy treats all mistakes alike. Precision for a label answers "when the prompt said billing, how often was it right?" (true positives divided by true positives plus false positives). Recall answers "of the real billing messages, how many did it find?" (true positives divided by true positives plus false negatives). A confusion matrix counts each (expected, predicted) pair, so you see which labels are mixed up. Both functions are in metrics.py; the lines below score version 2.
show_confusion(pairs(runs["v2"], True), LABELS)
for label, scores in precision_recall(pairs(runs["v2"], True), LABELS).items():
print(label, scores)expected/predicted billing delivery other none
billing 4 0 1 0
delivery 1 2 1 0
other 1 0 2 0
billing {'precision': 0.67, 'recall': 0.8, 'f1': 0.73}
delivery {'precision': 1.0, 'recall': 0.5, 'f1': 0.67}
other {'precision': 0.5, 'recall': 0.67, 'f1': 0.57}Read the matrix by rows: of five expected billing messages, four were found and one went to other (recall 0.8). Of the four expected delivery messages, delivery was predicted for two (recall 0.5), and delivery precision is 1.0 because nothing else was wrongly called delivery. The costly error depends on the product: if a missed billing message is serious, watch billing recall; if a wrongly-flagged message wastes an agent's time, watch precision. Both are worth a look before a single accuracy figure.
Semantic quality with human review
Some quality has no exact answer: is a reply polite, clear, appropriate? Use a person, and make the review fair. The sheet below hides which prompt version wrote each reply (a blind sheet) and shuffles the order with a fixed seed, so the reviewer is not influenced by the version name or by position. The six replies are invented stand-ins for logged outputs.
import csv, json, random
replies = {"t1": {"v1": "Sorry. Refund started.",
"v2": "Hello Kwame, I am sorry your order 48213 arrived damaged. We will start your refund today."},
"t2": {"v1": "Your parcel is late, we know.",
"v2": "Hello Lena, I am sorry order 51877 is late. A colleague will check its location and write to you."},
"t3": {"v1": "Hello Mateo, thank you for writing. We will send the right item.",
"v2": "Hello Mateo, sorry about the wrong item in order 60412. We will send the correct one."}}
items = [(case, v, text) for case, d in replies.items() for v, text in d.items()]
random.Random(3).shuffle(items)
key = {f"r{i}": (case, v) for i, (case, v, _) in enumerate(items, 1)}
with open("review_sheet.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["item", "reply", "score_1_to_5", "comment"])
writer.writerows([f"r{i}", text, "", ""] for i, (_, _, text) in enumerate(items, 1))
json.dump(key, open("review_key.json", "w"))
print(open("review_sheet.csv", encoding="utf-8").read().splitlines()[0])
print(len(key), "items; first two:", list(key.items())[:2])item,reply,score_1_to_5,comment
6 items; first two: [('r1', ('t1', 'v1')), ('r2', ('t2', 'v1'))]In real work you send review_sheet.csv (not the key) to one or two reviewers with the rubric. Below, a small table of invented scores stands in for a reviewer: after the sheet comes back, join the scores to the key and average per version.
invented = {("t1", "v1"): 2, ("t1", "v2"): 5, ("t2", "v1"): 1, ("t2", "v2"): 4, ("t3", "v1"): 3, ("t3", "v2"): 5}
by_version = {"v1": [], "v2": []}
for item, (case, v) in key.items():
by_version[v].append(invented[(case, v)])
print({v: round(sum(s) / len(s), 2) for v, s in by_version.items()}, "n per version:", len(by_version["v1"])){'v1': 2.0, 'v2': 4.67} n per version: 3Three replies per version is far too few to claim a difference; it only shows the procedure. With real reviewers, use at least two, write down the rubric, and measure how often they agree (the next page, Evaluation Dataset Design: Metrics, Edge Cases, Held-Out Sets and Baselines, shows how).
Latency and available usage metrics
Each record already holds latency_ms, input_tokens and output_tokens. In this tutorial the latency is a deterministic fake computed inside promptlab from the output length and a call counter, so tests are repeatable. It is not a measurement. Real latency is measured on the client: time the call yourself with time.perf_counter(), which is what Client(real_timing=True) does. Token counts are also the rough four-characters estimate, not a tokenizer.
Provider note (as of 2026-10-12): the providers' response objects carry token usage (for example reasoning-token counts, cache read and write counts, or thought-token counts), but latency is not a response field in the documentation checked, so measure it client-side. Field names differ by provider and change; check the current documentation before relying on one.
fake = [r["latency_ms"] for r in runs["v2"]]
print("fake latency, v2: mean", round(sum(fake) / len(fake)), "ms, max", max(fake), "ms")
real = Client(make_triage(), real_timing=True).complete([{"role": "user", "content": "### MESSAGE\nhello"}])
print("real timing is an int >= 0:", isinstance(real.latency_ms, int) and real.latency_ms >= 0)fake latency, v2: mean 58 ms, max 70 ms
real timing is an int >= 0: TrueWhen you report latency from real runs, give the median and the slowest few, not only the mean, and say how many calls and from where you measured. A single slow call is common.
Cost estimates from a price sheet
Cost is tokens times price. Keep prices in a small table in your code or in a file, never inside the formula, so one edit updates every estimate. The numbers below are example prices, not real. Real prices come from the provider's current price page, differ by model and kind of token, and change; copy them in with the date. Treat the result as an estimate: token counts here are rough, and cached input, reasoning tokens and discounts (see Prompt Caching and Cost: Stable Prefixes, Usage Data and Estimates) are priced differently.
PRICES = {"input_per_million": 1.00, "output_per_million": 4.00} # EXAMPLE numbers, not real prices
def cost(records, prices=PRICES):
ok = [r for r in records if r["status"] == "ok"]
tokens_in, tokens_out = sum(r["input_tokens"] for r in ok), sum(r["output_tokens"] for r in ok)
return (tokens_in * prices["input_per_million"] + tokens_out * prices["output_per_million"]) / 1_000_000
for v, records in runs.items():
per_call = cost(records) / len(records)
print(v, "per call", f"{per_call:.7f}", "| per 10,000 calls", round(per_call * 10_000, 3), "(example currency units)")v1 per call 0.0000418 | per 10,000 calls 0.418 (example currency units)
v2 per call 0.0000507 | per 10,000 calls 0.507 (example currency units)Version 2 costs about a fifth more per call here, because its prompt has an extra line of instructions; a prompt that adds 400 tokens would show in this table at once. Cost matters next to quality: a cheaper version that loses accuracy is rarely cheaper in total.
Repeating tests to observe variability
One run is one sample. A real model may answer differently each time, especially when a sampling setting such as temperature is above zero, and a temperature of zero does not guarantee identical answers either. The toy provider imitates this with a seeded random wrong answer when temperature is above 0. Repeat the same test several times and look at the spread, not at the best run.
noisy = Client(make_triage(seed=11), model="toy-triage")
hot = [round(accuracy(pairs(run_experiment(noisy, "v2", cases, f"logs/hot{i}.jsonl", temperature=0.7), True)), 2) for i in range(5)]
cold = [round(accuracy(pairs(run_experiment(noisy, "v2", cases, f"logs/cold{i}.jsonl", temperature=0), True)), 2) for i in range(3)]
print("temperature 0.7, five runs:", hot, "min", min(hot), "max", max(hot))
print("temperature 0, three runs :", cold)temperature 0.7, five runs: [0.58, 0.67, 0.5, 0.58, 0.67] min 0.5 max 0.67
temperature 0, three runs : [0.67, 0.67, 0.67]If two prompt versions differ by less than the spread between repeats of the same version, you have not shown that one is better. The toy's temperature-0 runs are identical because it is a toy; do not assume that of a real model without testing.
Export an experiment report to CSV
A report is one row per prompt version with the same columns every time, written as CSV so it opens in any spreadsheet and can be committed next to the prompts.
def summarise(records):
ok = [r for r in records if r["status"] == "ok"]
return {"version": records[0]["version"], "prompt_sha": records[0]["prompt_sha"], "cases": len(records), "ok": len(ok),
"strict_accuracy": round(accuracy(pairs(records)), 3), "lenient_accuracy": round(accuracy(pairs(records, True)), 3),
"mean_latency_ms_fake": round(sum(r["latency_ms"] for r in ok) / len(ok)),
"cost_per_10k_example": round(cost(records) / len(records) * 10_000, 3)}
write_csv("report.csv", [summarise(r) for r in runs.values()])
print(open("report.csv", encoding="utf-8").read().strip())version,prompt_sha,cases,ok,strict_accuracy,lenient_accuracy,mean_latency_ms_fake,cost_per_10k_example
v1,55f857e1,12,12,0.417,0.5,65,0.418
v2,fbece8b2,12,12,0.667,0.667,58,0.507Exercise: a small prompt-comparison script
The last point of this page is a small notebook-style script: plain Python with # %% markers, so an editor can run it cell by cell and a terminal can run it top to bottom. The Hard task below asks you to write it; one model answer is in the answers.
Where this shows up at work
Before a prompt change ships, a team compares the old and new versions on a fixed test set and attaches the CSV to the change request. A reviewer looks at accuracy, at the per-label recall that matters for the product, at cost per thousand calls and at the rows that got worse.
Common mistakes
- Writing the expected answer after seeing the output. You will agree with the model. Write expectations first.
- Using accuracy alone. A prompt can score well overall and still miss the one label that matters. Check recall and precision per label.
- Counting errors as wrong answers, or dropping them silently. Report how many cases returned an answer next to the score.
- Calling a fake latency or a rough price a measurement. Label the source and the date, and measure real latency on the client.
- Believing one run. Repeat, and compare differences with the spread.
Try it yourself
Use the page's files and namespace in one folder with promptlab.py.
- Easy. Compute the per-label recall of version 1 with lenient reading, and say which label it misses most.
- Medium. Add the invoice
{"vendor": "Omar Traders", "total": "75.00", "currency": "EGP"}as gold and a prediction with a wrong total, and report all four numbers fromfield_accuracy. - Hard. Write the notebook-style comparison script: cells for setup, run, score and a final cell that prints a one-line verdict ("v2 is ahead by N points" or "no clear difference"), and writes the CSV report.
Answers
Easy.
for label, s in precision_recall(pairs(runs["v1"], True), LABELS).items():
print(label, "recall", s["recall"])billing recall 0.4
delivery recall 0.5
other recall 0.67Billing recall is lowest (0.4): version 1 has no refund rule, so the refund messages c3 and c11 went elsewhere, and c7 uses a word the toy does not know. Pass checklist: it used the lenient pairs, it printed recall per label, and it named the label with the lowest value.
Medium.
golds2 = golds + [{"vendor": "Omar Traders", "total": "75.00", "currency": "EGP"}]
preds2 = preds + [{"vendor": "Omar Traders", "total": "57.00", "currency": "EGP"}]
print({k: round(v, 2) for k, v in field_accuracy(preds2, golds2, ["vendor", "total", "currency"]).items()}){'vendor': 0.83, 'total': 0.67, 'currency': 0.83, 'all': 0.33}Pass checklist: four keys (three fields and all); every value is now out of six records; total falls to 0.67 because the new total is wrong, and all falls to 0.33.
Hard. The three cells run in order; the final one compares only the two versions it was given and refuses to claim a difference smaller than one case.
# %% setup
versions = ["v1", "v2"]
client = Client(make_triage(), model="toy-triage")
# %% run
results = {v: run_experiment(client, v, cases, f"logs/nb_{v}.jsonl") for v in versions}
# %% score
rows = [summarise(results[v]) for v in versions]
for row in rows:
print(row["version"], row["strict_accuracy"], row["lenient_accuracy"])
# %% verdict and report
gap = round((rows[1]["strict_accuracy"] - rows[0]["strict_accuracy"]) * 100)
one_case = round(100 / len(cases))
print(f"v2 is ahead by {gap} points" if gap >= one_case else "no clear difference")
write_csv("nb_report.csv", rows)v1 0.417 0.5
v2 0.667 0.667
v2 is ahead by 25 pointsPass checklist: one cell per step, so a failure shows where it happened; the same cases and order for both versions; the verdict has a threshold written in code rather than decided by eye (one case is a very low bar; with twelve cases treat any verdict as a hint, not proof); the CSV is written last. This revisits the error records from the previous page: summarise counts only answered cases for accuracy and still reports ok next to cases.
Summary
- Write expected answers or a rubric before looking at outputs; use exact match for closed answer sets and report strict and lenient scores when answers can be wordy.
- For extraction compare field by field; for classification read the confusion matrix and per-label precision and recall, not accuracy alone.
- Use blind, shuffled human review for quality that code cannot judge, with a rubric and more than one reviewer.
- Fake latency and rough token counts test your code only; measure real latency on the client and take prices from the provider's current price page.
- Repeat tests to see variability, and export one CSV row per prompt version.
Next: Evaluation Dataset Design: Metrics, Edge Cases, Held-Out Sets and Baselines, where you decide what to measure, build a larger labelled dataset and keep part of it hidden.

