Chapter 4 · Experiments and Evaluation
Python Prompt Experiments: Test Cases, Runners, JSONL Logs and Mock Mode
- Page 15 of 24
- 15 min read
Trying a prompt in a chat window feels like an experiment, but it is not repeatable: you cannot say which wording produced which answer, and you cannot run it again on twenty inputs. A prompt experiment in Python fixes that. You keep the prompt text in a file, the test inputs in another file, run every input through the same function, and write one structured record per run. Then two prompt versions can be compared on exactly the same inputs.
This page builds the first half of a tiny evaluation toolkit, in three small files: runner.py, toys.py and a few data files. The next page, Metrics and Experiment Reports: Accuracy, Precision, Recall, Latency and CSV, adds scoring on top, and the page after it designs the test data. Everything uses the standard library and the promptlab helper from Prompt Chaining: Stages, Fixed Schemas and the promptlab Helper.
What you will learn
- How to keep prompts as strings and template files, apart from the test inputs, and load cases from JSON or CSV.
- How to write one reusable runner that calls an existing client and writes a metadata-rich JSONL record per case.
- How to handle API errors so a failed call becomes a record instead of destroying the log.
- How to practise offline with a mock (toy) provider, run the same test set against two prompt versions and compare them side by side.
Prompts are Python strings
A prompt is text, so a Python string holds it. A triple-quoted string keeps line breaks, and render from promptlab fills the {text} field. render raises an error if a variable is missing or unused, which catches typos before any call is made. Avoid f-strings for prompts you will store and reuse: an f-string fills its fields at the moment the line runs, so the template and the input become mixed together and cannot be saved or versioned separately. If a prompt must contain a literal brace, write it twice ({{ and }}) and let render turn each pair into one brace.
from promptlab import render
V1 = """Classify the support message as billing, delivery or other.
### MESSAGE
{text}"""
print(render(V1, text="Where is my box?"))
print(len(V1), "characters in the template")Classify the support message as billing, delivery or other.
### MESSAGE
Where is my box?
78 characters in the templateThis works for one prompt in one script. As soon as you have two versions and ten inputs, strings inside code become hard to compare and review. The next sections move the template and the inputs into files.
Test cases in JSON or CSV
A test case is one input plus an id. Keep cases in a data file, never inside the code, so a colleague can add one without touching Python. JSON suits records with several fields; CSV suits cases edited in a spreadsheet. The six invented support messages below are the test set for this page.
# file: cases.json
[
{"id": "c1", "text": "I was charged twice for invoice 3318."},
{"id": "c2", "text": "My parcel has not arrived after two weeks."},
{"id": "c3", "text": "Please send me a refund for the broken lamp that I bought last month."},
{"id": "c4", "text": "How do I change my profile photo?"},
{"id": "c5", "text": "Tracking shows nothing for my package."},
{"id": "c6", "text": "The driver left the box outside in the rain, and the invoice total looks wrong too."}
]Loading uses json and csv from the standard library. Use the csv module, not line.split(","): texts contain commas and quotes, and the module handles them. Note that CSV returns every value as a string, so a number column needs converting.
import csv, json
cases = json.load(open("cases.json", encoding="utf-8"))
with open("cases.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["id", "text"])
writer.writeheader()
writer.writerows(cases)
with open("cases.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print(len(cases), len(rows), rows == cases)
print(rows[2])6 6 True
{'id': 'c3', 'text': 'Please send me a refund for the broken lamp that I bought last month.'}Prompt templates apart from test inputs
Two files, two versions of one prompt. Version 2 adds a rule for refunds and asks for the label only. Each file is a template with one field, {text}; the inputs live in cases.json. Now a change to the prompt is a change to one small file, and a new test case never touches the prompt.
# 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}| Keep in the template file | Keep in the cases file | Keep in the code |
|---|---|---|
| Instructions, rules, output format, delimiters | Inputs, ids, later the expected answers | Loading, calling, logging, scoring |
| Changes when you improve the prompt | Changes when you find a new case | Changes rarely |
If a template needs a variable the input does not supply, or the reverse, render says so:
from promptlab import render
v1 = open("prompts/v1.txt", encoding="utf-8").read()
for variables in ({}, {"text": "hi", "extra": 1}):
try:
render(v1, **variables)
except ValueError as error:
print(error)missing variables: ['text']
unused variables: ['extra']One reusable function that calls the client
Now the core file. run_experiment takes any Client (the class from promptlab; it does not matter what provider sits inside), a prompt version, the cases, and a log path. It does not know whether the answer comes from a real model or a toy, so the same function serves practice and real experiments. It also records the metadata you will need later to explain a result: which model, which prompt version, which exact prompt text (a short hash of the template), which settings and which case. Read the file once; its parts are explained after it.
# file: runner.py
"""runner.py: load cases, run one prompt template over them, log one JSONL record per case."""
import csv, hashlib, json
from pathlib import Path
from promptlab import ProviderError, render
def load_cases(path):
"""Read cases from a .json list or a .csv with a header row; every case needs a unique 'id'."""
p = Path(path)
if p.suffix == ".csv":
with p.open(newline="", encoding="utf-8") as f:
cases = list(csv.DictReader(f))
else:
cases = json.loads(p.read_text(encoding="utf-8"))
if len({c["id"] for c in cases}) != len(cases):
raise ValueError("duplicate case ids")
return cases
def load_prompt(version):
return Path("prompts", f"{version}.txt").read_text(encoding="utf-8")
def run_experiment(client, version, cases, log, **settings):
"""Run prompts/<version>.txt over cases. Each record is written to the log at once; an API error
becomes a record with status 'error' instead of stopping the run."""
template = load_prompt(version)
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 records
def read_jsonl(path):
with open(path, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
def side_by_side(cases, a, b):
"""Print case id, text, both outputs and a marker where they differ."""
for case, ra, rb in zip(cases, a, b):
x, y = ra.get("text", "ERROR"), rb.get("text", "ERROR")
print(f"{case['id']:<3}{case['text'][:28]:<30}{x[:24]:<26}{y[:24]:<26}{'' if x == y else '<-- differs'}")- Metadata (the first
rec): case id, prompt version,prompt_sha, model name and settings. Version names are labels people can forget to bump; the hash changes whenever the template text changes, so a record can always be matched to the exact text. (If your file ends with an extra newline, your hash will differ from the one printed here; what matters is that it changes when the text changes.) - JSONL means one JSON object per line. The file is opened in append mode and each record is written and flushed at once, so a crash on case 40 leaves cases 1 to 39 on disk, and two runs can share one file.
sort_keys=Truekeeps the lines stable and easy to compare in a diff. - Two logs: the runner's log has one structured record per case (what you analyse); the client's own
log_pathhas one line per attempt with the full messages (what you read when something looks wrong). - Usage and latency come from the
Response. Here they are rough, fake numbers; the next page treats them honestly.
Mock mode: practising offline with a toy provider
You should be able to develop and test the whole experiment loop without network access, an account or any cost. That is mock mode: the client wraps a toy provider instead of a real one. The toy below is a stand-in, not a model. It classifies by keywords, it reads the prompt (so version 2 really behaves differently), it gets wordy on long messages when the prompt does not say "label only", and, with a temperature above 0, it gives a seeded wrong answer now and then so that later pages can practise on variability. Real models behave less predictably, which is exactly why you test them; what mock mode proves is that your harness works.
# 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 providerOne small factory chooses the provider. In mock mode it returns the toy; a real run would wrap your own SDK call in a function provider(messages, **settings) and put it in the other branch. The runner does not change.
from promptlab import Client
from runner import load_cases, run_experiment, read_jsonl, side_by_side
from toys import make_triage
def make_client(mode="mock", log="logs/calls.jsonl"):
if mode == "mock":
return Client(make_triage(), model="toy-triage", log_path=log)
raise NotImplementedError("wrap your SDK call in provider(messages, **settings) and return a Client")
client = make_client()
cases = load_cases("cases.json")
v1 = run_experiment(client, "v1", cases, "logs/v1.jsonl")
print(v1[0])
print(len(read_jsonl("logs/v1.jsonl")), "records in logs/v1.jsonl;", len(read_jsonl("logs/calls.jsonl")), "lines in logs/calls.jsonl"){'case': 'c1', 'version': 'v1', 'prompt_sha': '55f857e1', 'model': 'toy-triage', 'settings': {}, 'status': 'ok', 'text': 'billing', 'input_tokens': 28, 'output_tokens': 2, 'latency_ms': 60}
6 records in logs/v1.jsonl; 6 lines in logs/calls.jsonlAPI errors without losing the experiment log
Real calls fail: time-outs, rate limits, network drops. If one failure raises an exception through your loop, you lose the rest of the run and, unless you wrote as you went, the results so far. The runner above catches ProviderError (raised by the client after its retries are used up) and stores an error record. The next block makes a provider that always fails on messages about "tracking", with one retry allowed.
def fail_on(word, provider):
"""Stand-in for an unreliable API: raises a time-out whenever the message contains word."""
def wrapped(messages, **settings):
if word in messages[-1]["content"].lower():
raise TimeoutError("provider timed out")
return provider(messages, **settings)
return wrapped
flaky = Client(fail_on("tracking", make_triage()), model="toy-triage", log_path="logs/calls_flaky.jsonl", retries=1)
flaky_recs = run_experiment(flaky, "v2", cases, "logs/v2_flaky.jsonl")
print([r["status"] for r in flaky_recs])
print(flaky_recs[4]["error"])
print(len(read_jsonl("logs/v2_flaky.jsonl")), "experiment records;", len(read_jsonl("logs/calls_flaky.jsonl")), "attempts logged")['ok', 'ok', 'ok', 'ok', 'error', 'ok']
TimeoutError: provider timed out (after 2 attempt(s))
6 experiment records; 7 attempts loggedThe run finished, case c5 is marked as an error with the reason, and the client log shows seven attempts for six cases: the failed case was tried twice. Failed cases are data, not noise: you decide afterwards whether to re-run them, and you never count a missing answer as a wrong or a right one.
The same test set against two prompt versions
A fair comparison changes one thing. Both versions below run through the same client, on the same ordered cases; only the template differs. The assertion checks that the two result lists really cover the same case ids in the same order.
v2 = run_experiment(client, "v2", cases, "logs/v2.jsonl")
assert [r["case"] for r in v1] == [r["case"] for r in v2]
LABELS = {"billing", "delivery", "other"}
for name, records in (("v1", v1), ("v2", v2)):
clean = sum(r["text"] in LABELS for r in records)
print(name, records[0]["prompt_sha"], "bare labels:", clean, "of", len(records))v1 55f857e1 bare labels: 4 of 6
v2 fbece8b2 bare labels: 6 of 6Compare outputs side by side
Numbers hide details; read the rows. side_by_side prints both outputs next to each input and marks the differences.
side_by_side(cases, v1, v2)c1 I was charged twice for invo billing billing
c2 My parcel has not arrived af delivery delivery
c3 Please send me a refund for I think it is other. billing <-- differs
c4 How do I change my profile p other other
c5 Tracking shows nothing for m delivery delivery
c6 The driver left the box outs I think it is billing. billing <-- differsVersion 2 changed two rows. In c3 (the refund request) version 1 said "other" in a sentence ("I think it is other."), and version 2 gives the bare label billing, which is better on both counts. In c6 the message has two problems, a late driver and a wrong invoice; version 1 wraps its answer in a sentence and version 2 gives a bare label, but the label inside is the same, and a person might argue it should be delivery. Reading the rows has just shown you something a count could not: version 2 is cleaner, but you cannot say which is more correct until each case has an expected answer. That is the next page's job.
Where this shows up at work
A support team changes a triage prompt and wants to know whether it is safer than the old one before it replaces it. A data team re-runs the same two hundred inputs every time the model or the prompt changes. A single runner, a folder of versioned templates and a JSONL log are what let someone else repeat the run six months later and understand a surprising row.
Common mistakes
- Mixing prompt and inputs in one string. You cannot reuse the prompt on new cases or diff versions. Keep templates and cases in separate files.
- Logging only at the end. A crash or a stopped run loses everything. Append one record per case as it finishes.
- Letting one API error stop the run, or hiding it. Store an error record with a status, and never score a missing answer as if it were an answer.
- Comparing versions on different inputs. Use the same cases in the same order, and change one thing at a time.
- Treating mock results as evidence about a real model. A toy provider tests your harness. Only runs against the real provider say anything about real behaviour.
Try it yourself
Use the files and the namespace from this page, in one folder with promptlab.py.
- Easy. Add a seventh case
c7with the text "Why was my card debited two times?" and run version 2 on it. Predict the label first, and say whether a person would agree. - Medium. Write
failed_ids(records)that returns the case ids with statuserror, and call it on the flaky run. - Hard. Write
rerun_failed(client, version, cases, records, log)that runs only the failed cases again with a client you pass in and returns the full list of records in the original order. Check it on the flaky run, using the healthyclient.
Answers
Easy. The toy has no keyword for "debited", so it answers other; a person would say billing. This is a missing-keyword failure of the stand-in, and it is the kind of row that becomes a new case in your test set.
c7 = {"id": "c7", "text": "Why was my card debited two times?"}
print([r["text"] for r in run_experiment(client, "v2", [c7], "logs/c7.jsonl")])['other']Medium.
def failed_ids(records):
return [r["case"] for r in records if r["status"] == "error"]
print(failed_ids(flaky_recs))['c5']Hard.
def rerun_failed(client, version, cases, records, log):
bad = {r["case"] for r in records if r["status"] == "error"}
again = {r["case"]: r for r in run_experiment(client, version, [c for c in cases if c["id"] in bad], log)}
return [again.get(r["case"], r) for r in records]
fixed = rerun_failed(client, "v2", cases, flaky_recs, "logs/v2_flaky.jsonl")
print([r["status"] for r in fixed], failed_ids(fixed))['ok', 'ok', 'ok', 'ok', 'ok', 'ok'] []Pass checklist: the easy answer names a reason, not only a label; failed_ids reads a field and never calls a provider; rerun_failed calls the provider only for failed cases, keeps the order of the original list and appends to the same log, so the log now holds the failed record and its repair (do not delete the failure). This revisits the stop-and-name-the-stage habit from Prompt Chaining: Stages, Fixed Schemas and the promptlab Helper.
Summary
- Keep prompt templates, test cases and code in separate files;
rendercatches missing and unused variables. - Write one runner that works with any
Client, and record model, prompt version, prompt hash, settings, status, text, usage and latency per case. - Append JSONL records as you go; turn API errors into error records and keep them out of the scores.
- Use a toy provider as mock mode to test the harness offline; it is a stand-in, not evidence about real models.
- Compare versions on the same cases in the same order, and read the rows side by side.
Next: Metrics and Experiment Reports: Accuracy, Precision, Recall, Latency and CSV, where expected answers turn these outputs into scores and a CSV report.

