04.9 Iterating, Debugging and Porting Prompts
The first draft of a prompt is a hypothesis, not an answer. This lesson is about what you do after that: how to define "better" before you change anything, how to build a small set of labelled cases that tells you whether a change helped, how to read a model's failures and fix the right layer, how to keep prompts from silently regressing, and how to move a prompt that works on one model to another without starting over. It ends with the honest economics of prompt work — iteration costs tokens and engineer time, and the best prompt is the cheapest one that is good enough.
Everything in this lesson runs against a fake model — a small deterministic Python stand-in — so you can learn the whole loop with no API key, no network and no cost. The same harness runs unchanged against OpenAI, Anthropic, Gemini or OpenRouter; only the model callable differs. Where a sample needs a real provider, it is labelled illustrative.
What you'll learn
- The prompt development loop: define success, build a dev set, change one thing at a time, measure, keep a changelog
- How to measure honestly: repeats for variance, confidence intervals in plain English, paired comparisons (McNemar's test), and why "it looked better" is not evidence
- A complete pure-Python harness (
promptlab.py) for running prompts over labelled cases, scoring outputs, comparing versions and logging changes - A symptom → cause → fix table for the failures prompts actually produce, and when the fix is not in the prompt at all
- How to read what the model is doing: echo-back prompts, seeds and sampling, logprobs, and token-level inspection
- Prompt regression: golden sets, assertions, snapshot diffs, canary cases, and a minimal runner you can put in CI
- How to port a prompt across models and providers: why prompts don't transfer 1:1, a migration checklist, and the verified state of provider prompt tools as of November 2026
- Prompt optimization with an LLM in the loop — DSPy, GEPA, TextGrad and the manual critique loop — and when it's worth the tokens
- Cost and latency tuning: shortening prompts without losing quality, cache-friendly layout, model ladders and batching
- Debugging prompts in production: what to log, sampling failures, feedback loops, A/B tests and the incident playbook
- An anti-patterns catalogue and three worked case studies from broken prompt to fixed prompt
What you don't need
- API keys. Every runnable sample uses the fake model or pure Python. Provider samples are short and labelled; the mechanics of calling each API are Module 03's job, not this lesson's.
- A large dataset. The whole method works on 10–30 labelled cases; this lesson uses 12 plus a 5-case hold-out set.
- Any machine-learning background. The statistics here are two formulas explained in plain English, implemented for you.
Setup
No packages are required for the core of this lesson — promptlab.py, fake_model.py and the demo scripts use only the Python standard library (Python 3.11+). If you want the optional pytest-based regression runner in Part 3, add pytest:
uv init prompt-lab --bare --python 3.13 && cd prompt-lab # first time only; see lesson 03.1, Part 4
uv add pytest # or: pip install pytestCopy promptlab.py, fake_model.py and s1_dev_loop.py from this lesson into the project folder (each is given in full below), then:
python3 s1_dev_loop.pyThe provider glue in 1.8 and the porting checklist in Part 4 need the Module 03 SDKs (openai, anthropic, google-genai, python-dotenv; checked against the major versions named in lesson 04.1's Setup) and the .env keys described in lesson 03.1, Part 4. Everything else — including every number in this lesson — runs with none of it.
What you must be able to do after this lesson#
- Run the prompt development loop with a dev set and a changelog
- Compare two prompt versions with repeats and a paired test
- Diagnose a failure from its symptom to a likely cause
- Write a small regression suite for prompts
- Port a prompt to another model with a checklist
Why this matters for an AI engineer#
Prompt work is the part of AI engineering that looks like art and behaves like engineering. Teams that treat it as art ship prompts that can't be explained, can't be tested and can't be rolled back. Teams that treat it as engineering ship prompts with a changelog, a regression suite and a migration plan — and when the model provider ships a new snapshot on a Tuesday, they find out from their own tests, not from users.
| You'll hear... | You'll understand it after... |
|---|---|
| "The prompt worked yesterday, why is it broken today?" | 1.7 Variance and non-determinism, 7.5 The incident playbook |
| "I tweaked the prompt and it got better." | 1.4 A minimal harness, 1.7 |
| "We need to support GPT and Claude." | Part 4: Porting prompts |
| "The model ignores the format instruction." | 2.2 The symptom → cause → fix table |
| "Should we fine-tune instead?" | 2.3 Prompt fixes vs non-prompt fixes |
| "Can we auto-optimize the prompt?" | Part 5: LLM in the loop |
| "How do we stop prompt changes breaking prod?" | Part 3: Prompt regression |
| "Prompt iteration is burning tokens." | 1.8 Iterating cheaply, Part 6 |
| "The provider deprecated the model / changed the API." | 4.4 Model versions and deprecations |
Part 1: The prompt development loop#
1.1 Define success before you touch the prompt#
Every provider's prompt-engineering documentation now starts from the same advice, and it's worth stating plainly because it's the step everyone skips. Anthropic's prompt-engineering overview says you need "a clear definition of the success criteria for your use case", "some ways to empirically test against those criteria" and "a first draft prompt you want to improve" — in that order (source, verified November 2026). OpenAI's guide advises "Pinning your production applications to specific model snapshots" and "Building tests and evaluation suites that measure prompt behavior so you can monitor performance as you iterate, or when you change and upgrade model versions" (source, verified November 2026).
Translating that into practice:
- Write down what "good" looks like — not "the output should be good" but concrete, checkable properties. For the triage task in this lesson: output is exactly one line
category | urgency; category is one of five labels; urgency follows the written rules; the label matches what a human agent would choose. - Collect examples of good and bad outputs — real failures from logs, or outputs you generate and reject. These become your dev set (1.2) and, later, your regression suite (Part 3).
- Write a scorer — a function that turns "looks right" into a number in [0, 1]. It can be exact match, a set of assertions, a rubric judged by another model, or a human label. The scorer is your definition of success, made executable.
1.2 Build a small dev set#
A dev set is a small, fixed collection of labelled cases you iterate against. It does not need to be big:
- 10–30 cases is the sweet spot for prompt iteration. Big enough to cover your failure modes, small enough to run on every change in seconds-to-minutes.
- Cover the space, not the volume. Include: typical cases, each known edge case (negation, multiple issues, unusual phrasing), each output-format requirement, and a few adversarial cases (input that looks like it should break the prompt). Tag each case (
edge,two-issue,hedged) so you can see where failures cluster, not just how many. - Label with the same rubric a human reviewer would use. If two engineers would disagree on the label, the case is ambiguous — fix the task definition or drop the case.
- Never iterate against production traffic directly. Sample failures into the dev set; iterate offline.
1.3 The loop: one change at a time, with a changelog#
The development loop is deliberately boring:
flowchart LR
A["Define success<br/>(rubric + scorer)"] --> B["Build dev set<br/>(10–30 labelled cases)"]
B --> C["Write v1 prompt"]
C --> D["Run dev set, score"]
D --> E{"Failure<br/>analysis"}
E -->|"one hypothesis"| F["Change ONE thing"]
F --> G["Re-run, compare"]
G --> H{"Improved<br/>and no<br/>regressions?"}
H -->|yes| I["Record in changelog<br/>keep version"]
H -->|no| J["Revert or rethink"]
I --> D
J --> E
D --> K["Hold-out check<br/>before shipping"]Three rules make it work:
- Change one thing at a time. If you add a format spec and three examples and a role in one edit, you cannot attribute the result. When it improves you won't know which change did it; when it regresses you won't know which to blame. One variable per iteration is slower per step and faster overall.
- Keep a changelog. Every kept version gets an entry: version id, what changed, why, and the dev-set score before and after. This lesson's harness writes it as JSONL; 04.10 covers versioning the prompts themselves properly. The changelog answers "what did we change before it broke?" six months later.
- Compare against the previous version on the same cases. Never compare a new run to a remembered number, a different dev set, or a different model — those comparisons are meaningless (see 1.7).
And one habit upstream of the loop itself: start simple. The first prompt should be the simplest thing that could possibly satisfy the contract — v1 here is deliberately minimal — and complexity gets added only when the dev set demands it, one measured failure at a time. Every rule you write before measuring is a rule you can't attribute.
1.4 A minimal harness: promptlab.py#
Everything the loop needs is about 350 lines of pure Python. The design decisions that matter:
- A model is a callable,
(system_prompt, rendered_prompt, case) -> str. Not an SDK client — a callable. That seam is what lets the same harness drive a fake model in CI, a provider SDK in production, or a replay of logged calls when debugging (03.10 builds the same seam for API debugging). - A scorer is a callable,
(case, output) -> float in [0, 1]. Deterministic scorers are preferred; an LLM judge is allowed but then it needs its own dev set (Module 10A owns judge design). repeats> 1 for real models. Non-determinism means one run is a sample, not a measurement (1.7).- Statistics you can explain. The harness reports a mean, a pass rate with a Wilson interval, and McNemar's exact test for paired comparisons — no scipy, no black boxes.
One relationship worth stating up front: 04.1, 7.3–7.4 ships triage_loop.py, a compact sketch of the same loop (run(cases, build_prompt, call_model) → report()) for the same task family. promptlab.py is the measurement-grade version this lesson builds on — the same callable-model seam, plus repeats, confidence intervals, paired statistics, snapshots and the changelog that Parts 3–5 need. If you wrote 04.1's loop, read this as its grown-up sibling, not a replacement to unlearn.
Here is the complete file. Save it as promptlab.py:
"""promptlab.py — a minimal harness for the prompt development loop.
Pure Python, no dependencies, no network. A "model" is just a callable
(system_prompt, rendered_prompt, case) -> output text, so the same harness runs
against a fake model, a provider SDK call, or a replay wrapper. Scores are
floats in [0.0, 1.0]; 1.0 means "perfect on this case".
"""
from __future__ import annotations
import hashlib
import json
import math
import statistics
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Iterable
# ---------------------------------------------------------------- cases
@dataclass(frozen=True)
class Case:
"""One labelled example.
`input` is the text that goes into the prompt's {input} slot.
`expected` is whatever ground truth your scorer needs; leave it "" when
scoring needs a rubric or an LLM judge instead.
`tags` ("edge", "long", "ambiguous"...) let you slice results afterwards.
"""
id: str
input: str
expected: str = ""
tags: tuple[str, ...] = ()
# A scorer maps (case, model output) -> score in [0.0, 1.0].
Scorer = Callable[[Case, str], float]
# A "model" is any callable (system_prompt, rendered_prompt, case) -> str.
# Keeping it a plain callable — not an SDK client — is what makes the harness
# testable with fakes and replayable in CI.
ModelFn = Callable[[str, str, "Case"], str]
# ---------------------------------------------------------------- statistics
def wilson_interval(successes: int, n: int, z: float = 1.96) -> tuple[float, float]:
"""95% Wilson score interval for a binomial proportion.
Honest even for small n, unlike the normal approximation which produces
intervals outside [0, 1] when p is near 0 or 1.
"""
if n == 0:
return (0.0, 0.0)
p = successes / n
denom = 1 + z * z / n
centre = (p + z * z / (2 * n)) / denom
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
return (max(0.0, centre - half), min(1.0, centre + half))
def mcnemar_exact(b: int, c: int) -> tuple[float, bool]:
"""Two-sided exact McNemar p-value for paired pass/fail counts.
Comparing two prompts on the SAME cases is a paired design: what matters
is the discordant pairs — cases where exactly one prompt passed.
Under the null (the prompts are equally good) those split 50/50, so
min(b, c) ~ Binomial(b + c, 0.5). Returns (p_value, significant at 5%).
"""
n = b + c
if n == 0:
return 1.0, False
k = min(b, c)
tail = sum(math.comb(n, i) for i in range(k + 1)) / (2**n)
p = min(1.0, 2 * tail)
return p, p < 0.05
# ---------------------------------------------------------------- results
@dataclass
class RunResult:
"""The outcome of running one prompt version over a set of cases."""
name: str
prompt: str
model: str
repeats: int
scores: list[list[float]] # scores[case_index][repeat_index]
outputs: list[list[str]] # outputs[case_index][repeat_index]
case_ids: list[str]
tags: list[tuple[str, ...]]
elapsed_s: float = 0.0
@property
def prompt_hash(self) -> str:
return hashlib.sha256(self.prompt.encode("utf-8")).hexdigest()[:12]
def case_means(self) -> list[float]:
"""Mean score per case across repeats — the unit of comparison."""
return [statistics.fmean(row) for row in self.scores]
def overall(self) -> float:
"""Mean of the per-case means (cases are the independent units)."""
return statistics.fmean(self.case_means())
def pass_rate(self, threshold: float = 0.999) -> tuple[float, tuple[float, float]]:
"""Fraction of individual calls scoring >= threshold, with a 95%
Wilson interval. threshold=1.0 means 'only perfect counts'."""
flat = [s for row in self.scores for s in row]
k = sum(1 for s in flat if s >= threshold)
return k / len(flat), wilson_interval(k, len(flat))
def by_tag(self, tag: str) -> float:
idx = [i for i, t in enumerate(self.tags) if tag in t]
if not idx:
return float("nan")
return statistics.fmean(statistics.fmean(self.scores[i]) for i in idx)
@dataclass
class Comparison:
"""Two runs over the same cases, compared case by case."""
a_name: str
b_name: str
mean_delta: float # b.overall() - a.overall()
improved: list[str]
regressed: list[str]
mcnemar_b: int # cases only B passed
mcnemar_c: int # cases only A passed
mcnemar_p: float
mcnemar_significant: bool
def render(prompt: str, case: Case) -> str:
"""Fill the prompt's {input} slot. If there is no slot the prompt is sent
as-is and model_fn can still read case.input itself."""
return prompt.replace("{input}", case.input)
def run(
cases: Iterable[Case],
prompt: str,
model_fn: ModelFn,
scorer: Scorer,
*,
name: str = "run",
model: str = "unknown",
system: str = "",
repeats: int = 1,
) -> RunResult:
"""Run `prompt` over `cases`, score every output, return a RunResult.
`repeats` runs each case N times: the only honest way to see variance on
a non-deterministic model (lesson 02.5, Part 7).
"""
cases = list(cases)
scores: list[list[float]] = []
outputs: list[list[str]] = []
t0 = time.perf_counter()
for case in cases:
rendered = render(prompt, case)
srow: list[float] = []
orow: list[str] = []
for _ in range(repeats):
out = model_fn(system, rendered, case)
srow.append(max(0.0, min(1.0, scorer(case, out))))
orow.append(out)
scores.append(srow)
outputs.append(orow)
return RunResult(
name=name,
prompt=prompt,
model=model,
repeats=repeats,
scores=scores,
outputs=outputs,
case_ids=[c.id for c in cases],
tags=[c.tags for c in cases],
elapsed_s=time.perf_counter() - t0,
)
def compare(a: RunResult, b: RunResult, *, pass_threshold: float = 0.999) -> Comparison:
"""Compare two runs case by case. Same cases, same order — a paired design,
which is far more sensitive than comparing two independent averages."""
if a.case_ids != b.case_ids:
raise ValueError("compare() needs the same cases in the same order")
am, bm = a.case_means(), b.case_means()
eps = 1e-9
improved = [cid for cid, x, y in zip(a.case_ids, am, bm) if y > x + eps]
regressed = [cid for cid, x, y in zip(a.case_ids, am, bm) if y < x - eps]
b_only = sum(1 for x, y in zip(am, bm) if x < pass_threshold <= y)
a_only = sum(1 for x, y in zip(am, bm) if y < pass_threshold <= x)
p, sig = mcnemar_exact(b_only, a_only)
return Comparison(
a_name=a.name,
b_name=b.name,
mean_delta=b.overall() - a.overall(),
improved=improved,
regressed=regressed,
mcnemar_b=b_only,
mcnemar_c=a_only,
mcnemar_p=p,
mcnemar_significant=sig,
)
# ---------------------------------------------------------------- changelog
@dataclass
class ChangelogEntry:
ts: str
prompt_name: str
version: str
prompt_hash: str
change: str
score_before: float | None
score_after: float | None
notes: str = ""
class Changelog:
"""An append-only JSONL history of prompt changes — the prompt's git log.
One line per change: what changed, why, and what the dev set said before
and after. When a regression appears in production, this is where you look
first.
"""
def __init__(self, path: str | Path):
self.path = Path(path)
def record(
self,
run_result: RunResult,
*,
prompt_name: str,
version: str,
change: str,
score_before: float | None = None,
notes: str = "",
) -> None:
entry = ChangelogEntry(
ts=time.strftime("%Y-%m-%dT%H:%M:%S"),
prompt_name=prompt_name,
version=version,
prompt_hash=run_result.prompt_hash,
change=change,
score_before=score_before,
score_after=run_result.overall(),
notes=notes,
)
with self.path.open("a", encoding="utf-8") as f:
f.write(json.dumps(entry.__dict__) + "\n")
@classmethod
def load(cls, path: str | Path) -> "Changelog":
return cls(path)
def entries(self) -> list[dict]:
if not self.path.exists():
return []
return [json.loads(line) for line in self.path.read_text().splitlines() if line.strip()]
def table(self) -> str:
rows = ["| when | version | hash | before → after | change |", "|---|---|---|---|---|"]
for e in self.entries():
before = "—" if e["score_before"] is None else f"{e['score_before']:.3f}"
rows.append(
f"| {e['ts']} | {e['version']} | `{e['prompt_hash']}` | "
f"{before} → **{e['score_after']:.3f}** | {e['change']} |"
)
return "\n".join(rows)
# ---------------------------------------------------------------- snapshots
def save_snapshot(run: RunResult, path: str | Path) -> None:
"""Freeze a run's per-case outputs and mean score.
For prompt regression you snapshot *outputs*, not just scores: a prompt
change that keeps the score but alters every answer is still a change you
want to see in review.
"""
snap = {
"name": run.name,
"prompt_hash": run.prompt_hash,
"model": run.model,
"cases": {
cid: {
"mean": statistics.fmean(row),
"outputs": outs,
}
for cid, row, outs in zip(run.case_ids, run.scores, run.outputs)
},
}
Path(path).write_text(json.dumps(snap, indent=2))
def load_snapshot(path: str | Path) -> dict:
return json.loads(Path(path).read_text())
def diff_snapshots(old: dict, new: dict) -> list[dict]:
"""Cases whose output text or mean score changed between two snapshots."""
changes = []
for cid, old_case in old["cases"].items():
new_case = new["cases"].get(cid)
if new_case is None:
changes.append({"case": cid, "kind": "removed"})
continue
if old_case["outputs"] != new_case["outputs"] or abs(old_case["mean"] - new_case["mean"]) > 1e-9:
changes.append(
{
"case": cid,
"kind": "changed",
"old_mean": old_case["mean"],
"new_mean": new_case["mean"],
}
)
for cid in new["cases"]:
if cid not in old["cases"]:
changes.append({"case": cid, "kind": "added"})
return changes
# ---------------------------------------------------------------- reporting
def markdown_table(runs: list[RunResult], *, pass_threshold: float = 0.999) -> str:
"""One row per run: overall score, pass rate with CI, per-tag slices."""
tags = sorted({t for r in runs for tags in r.tags for t in tags})
header = "| run | hash | overall | pass rate (95% CI) | " + " | ".join(f"{t}" for t in tags) + " |"
sep = "|" + "---|" * (4 + len(tags))
rows = [header, sep]
for r in runs:
pr, (lo, hi) = r.pass_rate(pass_threshold)
cells = " | ".join(f"{r.by_tag(t):.2f}" for t in tags)
rows.append(
f"| {r.name} | `{r.prompt_hash}` | {r.overall():.3f} | "
f"{pr:.1%} ({lo:.0%}–{hi:.0%}) | {cells} |"
)
return "\n".join(rows)
def failing_cases(run: RunResult, *, pass_threshold: float = 0.999) -> list[tuple[str, float, str]]:
"""(case_id, mean_score, first_output) for every case below threshold —
the list you take into the debugging loop."""
out = []
for cid, mean, outs in zip(run.case_ids, run.case_means(), run.outputs):
if mean < pass_threshold:
out.append((cid, mean, outs[0]))
return outTwo statistics in there are worth understanding because you'll meet them again:
- The Wilson interval answers "how precise is this pass rate?" A pass rate of 50% on 12 cases has a 95% interval of roughly 25–75% — the honest statement is "somewhere between a quarter and three-quarters of calls pass", not "50%". As your dev set grows the interval narrows; that is the mathematical reason small dev sets can't detect small improvements.
- McNemar's exact test answers "did B really beat A?" When you run two prompts on the same cases, only the cases where they disagree matter — the concordant cases (both pass or both fail) carry no information about which is better. If B passes 3 cases A failed and A passes 0 that B failed, the exact two-sided p-value is
2 × (1/2)³ = 0.25: not significant. You need six discordant cases all favouring one side before p dips under 0.05 — five gives p = 0.0625, still noise. This is why "the new prompt fixed 2 cases" proves nothing on a 12-case dev set — and why you either grow the set or accept the uncertainty.
1.5 Try it: the triage loop, v1 → v4#
The running example is support-ticket triage: given a ticket, output category | urgency. Categories: billing, technical, account, shipping, other. Urgency: low, normal, high, urgent. It's the same task family 04.1 uses for its worked rewrite — same domain, mostly the same categories, but a different contract (04.1's is JSON priority/category/summary; this one is two labels on a single line). Where 04.1's triage_loop.py is the compact sketch, promptlab.py is the measurement-grade harness this lesson builds on — see 1.4. Here we watch the process rather than the anatomy.
First, the "model". fake_model.py is a deterministic stand-in for a small chat model: it reads the prompt for a fixed set of instruction signals and applies keyword rules. It exists so every sample runs offline; a real model is far less predictable, which is the entire point of measuring.
"""fake_model.py — a deterministic stand-in for a small chat model.
The triage task: read a support ticket, output `CATEGORY | URGENCY`.
Categories: billing, technical, account, shipping, other.
Urgency: low, normal, high, urgent.
FakeTriager 'reads' the rendered prompt for a fixed set of instruction
signals (documented below) and then applies keyword rules. It exists so every
sample in lesson 04.9 runs offline, for free and reproducibly. A real model is
far less predictable — which is exactly why the lesson insists on measuring
on your own model and dev set.
"""
from __future__ import annotations
import json
import re
CATEGORIES = ("billing", "technical", "account", "shipping")
URGENCIES = ("low", "normal", "high", "urgent")
# Keyword -> category. First match wins unless the prompt asks for the
# 'primary issue' rule below. Keywords are matched as plain substrings —
# deliberately naive, like a real small model's keyword-ish behaviour.
CATEGORY_KEYWORDS = {
"billing": ("invoice", "charge", "refund", "payment", "card", "billing", "charged"),
"technical": ("error", "crash", "bug report", "500", "timeout", "times out",
"timed out", "broken", "login fails", "checkout", "outage",
"site is down", "can't work", "cannot work", "blank screen",
"won't load"),
"account": ("password", "account", "email", "2fa", "locked out"),
"shipping": ("deliver", "tracking", "package", "order", "shipment", "courier"),
}
# Urgency rules the 'model' applies when the prompt supplies them, in order.
# Note the phrases, not bare substrings: "down" alone would match "download".
URGENCY_RULES = [
("urgent", ("is down", "are down", "site down", "went down", "down for",
"outage", "data loss", "security breach", "can't work", "cannot work")),
("high", ("deadline", "today", "asap", "production", "launch")),
("low", ("no rush", "low priority", "not urgent", "when you have time")),
]
class FakeTriager:
"""A callable with the ModelFn signature: (system, prompt, case) -> str.
Instruction signals it recognises in the prompt text (all case-insensitive):
- `CATEGORIES:` line -> restricts the category vocabulary
- 'urgency rules' -> applies the ordered keyword rules below
- 'hedge' -> polite hedges score low, not normal
- 'negation' -> 'not a billing issue' is not billing
- 'primary issue' -> first-mentioned problem wins
(without it, the LAST matching keyword wins — a real-model-like quirk)
- 'output format:' -> emits `cat | urg`; otherwise prose
"""
NEGATION_RE = re.compile(
r"\b(?:not|no|isn'?t|never)\s+(?:a\s+|an\s+|the\s+)?"
r"(?:billing|technical|account|shipping)[a-z ]{0,25}?"
r"(?:issue|problem|matter|question|request)?"
)
def __call__(self, system: str, prompt: str, case) -> str:
text = case.input.lower()
p = prompt.lower()
if "negation" in p:
text = self.NEGATION_RE.sub(" ", text)
# --- category -----------------------------------------------------
cats = self._categories(prompt)
matches = [
c for c in cats
if c in CATEGORY_KEYWORDS and any(k in text for k in CATEGORY_KEYWORDS[c])
]
if not matches:
category = "other"
elif "primary issue" in p:
category = self._first_mentioned(text, matches)
else:
category = self._last_mentioned(text, matches)
# --- urgency ------------------------------------------------------
urgency = self._urgency(p, text)
# --- format -------------------------------------------------------
if "output format:" in p:
return f"{category} | {urgency}"
return (
f"Thanks for reaching out! I've reviewed your ticket and it looks like "
f"a {category} matter. Regarding urgency, I would rate this as {urgency}. "
f"We'll get back to you shortly."
)
# -- helpers ---------------------------------------------------------
@staticmethod
def _categories(prompt: str) -> list[str]:
m = re.search(r"CATEGORIES:\s*([a-z, |]+)", prompt)
if not m:
return list(CATEGORIES) + ["other"]
return [c.strip() for c in m.group(1).split(",") if c.strip()]
@staticmethod
def _first_mentioned(text: str, matches: list[str]) -> str:
pos = {c: min(text.find(k) for k in CATEGORY_KEYWORDS[c] if k in text) for c in matches}
return min(matches, key=lambda c: pos[c])
@staticmethod
def _last_mentioned(text: str, matches: list[str]) -> str:
pos = {c: max(text.rfind(k) for k in CATEGORY_KEYWORDS[c] if k in text) for c in matches}
return min(matches, key=lambda c: -pos[c])
@classmethod
def _urgency(cls, p: str, text: str) -> str:
hedge_low = "hedge" in p
has_rules = "urgency rules" in p
for level, keywords in URGENCY_RULES:
if level == "low" and not (has_rules or hedge_low):
# The 'low' rule only exists when the prompt supplies the rules
# block or the explicit hedge instruction.
continue
if any(k in text for k in keywords):
return level
if hedge_low and any(k in text for k in ("whenever", "no rush", "when you have time", "get a chance")):
return "low"
return "normal"Now the dev set, four prompt versions and the loop itself, as s1_dev_loop.py:
"""s1_dev_loop.py — the prompt development loop, end to end, on the triage task.
Everything runs against FakeTriager (fake_model.py): deterministic, offline,
free. Swap `model` for a real provider call (call_llm.py) and the same code
measures your actual model — the numbers will differ, the loop won't.
"""
from __future__ import annotations
import re
from pathlib import Path
from promptlab import (
Case,
Changelog,
compare,
failing_cases,
markdown_table,
run,
)
from fake_model import FakeTriager
# ------------------------------------------------------------- the task
# Input: a support ticket. Output contract: one line `category | urgency`.
# Categories: billing, technical, account, shipping, other.
# Urgency: low, normal, high, urgent.
DEV_SET = [
Case("t01", "Hi, I was charged twice for my subscription this month. Invoice #4471 "
"shows two payments of $29. Can you refund the duplicate?",
"billing | normal"),
Case("t02", "The app crashes every time I open the reports page. Error 500 since "
"this morning. This is blocking our board meeting TODAY.",
"technical | high", tags=("edge",)),
Case("t03", "I can't log in — it says my password is wrong but I'm sure it's right. "
"Also my billing email is wrong so invoices go to my old address.",
"account | normal", tags=("two-issue",)),
Case("t04", "Quick note — this is not a billing question. Just wanted to say the "
"new dashboard looks great, thanks!",
"other | normal", tags=("negation",)),
Case("t05", "Hey — whenever you get a chance, could someone check why my "
"invoice total looks wrong? It's been bugging me for a while.",
"billing | low", tags=("hedged",)),
Case("t06", "URGENT: our entire checkout is down, customers can't complete orders. "
"We're losing sales every minute.",
"technical | urgent", tags=("two-issue", "urgent")),
Case("t07", "Where is my order? Tracking says delivered but nothing arrived. "
"Package was supposed to come Tuesday.",
"shipping | normal"),
Case("t08", "I need to update the card on file before the renewal charge hits "
"tomorrow. Also the invoice PDF won't download — error when I click it.",
"billing | normal", tags=("two-issue",)),
Case("t09", "My password reset email never arrives. I've checked spam. Account "
"recovery link is expired too.",
"account | normal"),
Case("t10", "The export feature times out on datasets over 10k rows. Error 500 "
"every time. This blocks our weekly report for the board.",
"technical | normal"),
Case("t11", "Hi team! Loving the product. Quick question — can invoices be "
"exported as CSV? No rush whenever you have time.",
"billing | low", tags=("hedged",)),
Case("t12", "Security concern: I think someone else has access to my account. I "
"didn't make the charges on my card and my password was changed "
"without me.",
"account | normal", tags=("two-issue",)),
]
# Cases the loop NEVER sees during iteration. They answer one question:
# did the prompt learn the task, or did it memorise the dev set?
HOLDOUT_SET = [
Case("h01", "Our invoice from March is wrong — we were billed for 12 seats but "
"only have 8. Also can't download the PDF, getting a 403.",
"billing | normal"),
Case("h02", "Delivery driver marked my package delivered but it's not here. "
"I've waited 2 weeks.",
"shipping | normal"),
Case("h03", "Is it possible to get an invoice in PDF format for our accountant? "
"Whenever works.",
"billing | low", tags=("hedged",)),
Case("h04", "Two things: first, the mobile app crashes on startup (error on "
"startup). Second, unrelated — I need to update my billing email.",
"technical | normal", tags=("two-issue",)),
Case("h05", "Bonjour, je n'arrive pas à me connecter, mon mot de passe ne "
"fonctionne plus.",
"account | normal", tags=("multilingual",)),
]
# ------------------------------------------------------------- the prompts
PROMPT_V1 = """You are a support triage assistant. Read the customer's ticket and work out \
what it is about and how urgently it needs attention. Think carefully and explain \
your reasoning.
Ticket:
{input}"""
PROMPT_V2 = """You are a support triage assistant. Read the ticket and decide its category \
and urgency.
CATEGORIES: billing, technical, account, shipping, other
Ticket:
{input}
Output format: exactly one line — `category | urgency`, where urgency is one of \
low, normal, high, urgent. Nothing else."""
PROMPT_V3 = """You are a support triage assistant. Read the ticket and decide its category \
and urgency.
CATEGORIES: billing, technical, account, shipping, other
URGENCY RULES (apply in order, first match wins):
- urgent if the ticket mentions an outage, data loss, security breach, or the \
customer can't work
- high if there's a deadline, "today", "asap", or a production/launch blocker
- low if the customer says "no rush", "low priority", "not urgent", or "when \
you have time"
Other rules:
- Watch for negation: "not a billing issue" means it is NOT billing.
- When a ticket raises two problems, label the primary issue — the one the \
customer leads with.
Ticket:
{input}
Output format: exactly one line — `category | urgency`, where urgency is one of \
low, normal, high, urgent. Nothing else."""
PROMPT_V4 = """You are a support triage assistant. Read the ticket and decide its category \
and urgency.
CATEGORIES: billing, technical, account, shipping, other
URGENCY RULES (apply in order, first match wins):
- urgent if the ticket mentions an outage, data loss, security breach, or the \
customer can't work
- high if there's a deadline, "today", "asap", or a production/launch blocker
- low if the customer says "no rush", "low priority", "not urgent", or "when \
you have time"
- Treat polite hedges like "whenever you get a chance" or "whenever works" \
as low urgency
Other rules:
- Watch for negation: "not a billing issue" means it is NOT billing.
- When a ticket raises two problems, label the primary issue — the one the \
customer leads with.
Ticket:
{input}
Output format: exactly one line — `category | urgency`, where urgency is one of \
low, normal, high, urgent. Nothing else."""
VERSIONS = [
("v1", PROMPT_V1, "first draft: role + task, no contract"),
("v2", PROMPT_V2, "added category list and output format"),
("v3", PROMPT_V3, "added urgency rules, negation, primary-issue rule"),
("v4", PROMPT_V4, "added polite-hedge rule for low urgency"),
]
# ------------------------------------------------------------- the scorer
_PAIR_RE = re.compile(r"^\s*([a-z]+)\s*\|\s*([a-z]+)\s*$")
def triage_scorer(case: Case, output: str) -> float:
"""Score one triage reply against `category | urgency`.
Both fields right: 1.0. One field right: 0.5. Unparseable: 0.0.
"""
exp_cat, exp_urg = case.expected.split(" | ")
lines = [ln for ln in output.strip().splitlines() if ln.strip()]
m = _PAIR_RE.match(lines[-1]) if lines else None
if not m:
return 0.0
got_cat, got_urg = m.group(1), m.group(2)
return (got_cat == exp_cat) / 2 + (got_urg == exp_urg) / 2
def print_comparison(cmp) -> None:
print(f" {cmp.a_name} -> {cmp.b_name}: mean {cmp.mean_delta:+.3f} | "
f"improved {cmp.improved} | regressed {cmp.regressed} | "
f"McNemar p={cmp.mcnemar_p:.3f} {'(significant)' if cmp.mcnemar_significant else '(noise)'}")
def main() -> None:
model = FakeTriager()
workdir = Path(__file__).parent
log = Changelog(workdir / "changelog.jsonl")
if log.path.exists():
log.path.unlink()
results = []
prev = None
for name, prompt, change in VERSIONS:
r = run(DEV_SET, prompt, model, triage_scorer,
name=name, model="fake-triager", repeats=1)
results.append(r)
if prev is not None:
print_comparison(compare(prev, r))
log.record(r, prompt_name="ticket-triage", version=name, change=change,
score_before=prev.overall() if prev else None)
prev = r
print("\nDev set (12 cases):")
print(markdown_table(results))
# The hold-out set decides whether v4 is a real improvement or dev-set memorisation.
hr = run(HOLDOUT_SET, PROMPT_V4, model, triage_scorer,
name="v4-holdout", model="fake-triager", repeats=1)
print("\nHold-out set (5 cases, never iterated on):")
print(markdown_table([hr]))
for cid, score, out in failing_cases(hr):
print(f" FAIL {cid} score={score:.2f} output={out!r}")
# What did the dev loop actually learn? Show the failing cases at each stage.
print("\nFailures at v2 (the version most teams would have shipped):")
for cid, score, out in failing_cases(results[1]):
print(f" {cid} score={score:.2f} output={out!r}")
print("\nChangelog:")
print(log.table())
if __name__ == "__main__":
main()Run it — the fake model is deterministic, so every score, hash and p-value below reproduces exactly; only the timestamps differ:
python3 s1_dev_loop.py v1 -> v2: mean +0.750 | improved ['t01', 't02', 't03', 't04', 't05', 't06', 't07', 't08', 't09', 't10', 't11', 't12'] | regressed [] | McNemar p=0.031 (significant)
v2 -> v3: mean +0.208 | improved ['t03', 't04', 't06', 't08', 't11'] | regressed [] | McNemar p=0.062 (noise)
v3 -> v4: mean +0.042 | improved ['t05'] | regressed [] | McNemar p=1.000 (noise)
Dev set (12 cases):
| run | hash | overall | pass rate (95% CI) | edge | hedged | negation | two-issue | urgent |
|---|---|---|---|---|---|---|---|---|
| v1 | `99d1c555fbb2` | 0.000 | 0.0% (0%–24%) | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 |
| v2 | `84d142503cd6` | 0.750 | 50.0% (25%–75%) | 1.00 | 0.50 | 0.50 | 0.62 | 0.50 |
| v3 | `649eaed45384` | 0.958 | 91.7% (65%–99%) | 1.00 | 0.75 | 1.00 | 1.00 | 1.00 |
| v4 | `44fd920d3e1b` | 1.000 | 100.0% (76%–100%) | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 |
Hold-out set (5 cases, never iterated on):
| run | hash | overall | pass rate (95% CI) | hedged | multilingual | two-issue |
|---|---|---|---|---|---|---|
| v4-holdout | `44fd920d3e1b` | 0.900 | 80.0% (38%–96%) | 1.00 | 0.50 | 1.00 |
FAIL h05 score=0.50 output='other | normal'
Failures at v2 (the version most teams would have shipped):
t03 score=0.50 output='billing | normal'
t04 score=0.50 output='billing | normal'
t05 score=0.50 output='billing | normal'
t06 score=0.50 output='shipping | urgent'
t08 score=0.50 output='technical | normal'
t11 score=0.50 output='billing | normal'
Changelog:
| when | version | hash | before → after | change |
|---|---|---|---|---|
| 2026-11-05T20:20:30 | v1 | `99d1c555fbb2` | — → **0.000** | first draft: role + task, no contract |
| 2026-11-05T20:20:30 | v2 | `84d142503cd6` | 0.000 → **0.750** | added category list and output format |
| 2026-11-05T20:20:30 | v3 | `649eaed45384` | 0.750 → **0.958** | added urgency rules, negation, primary-issue rule |
| 2026-11-05T20:20:30 | v4 | `44fd920d3e1b` | 0.958 → **1.000** | added polite-hedge rule for low urgency |Read what just happened, because it is the lesson:
- v1 scored 0.000 — not because the "model" is bad but because the prompt never said what shape the answer should take. Prose sympathy is not a triage label. This is the most common first-draft failure: the prompt describes the task but not the contract.
- v2 jumped to 0.750 — adding the category list and the
category | urgencyformat fixed ten cases at once. Format and vocabulary are the highest-leverage prompt changes; get them before anything subtle. - v3 → 0.958 — the rules block fixed negation (t04), two-issue tickets (t03, t06, t08) and hedged phrasing that the rules already covered (t11). The remaining failure, t05, needed one more rule.
- v3 → v4 is "noise" — one case flipped on a 12-case set; McNemar p = 1.0. Keeping v4 is still right (the hedge rule is a real generalisation, as h03 confirms), but the dev set alone cannot prove it. This is the statistical reality of small dev sets, and the reason 1.6 exists.
- The hold-out set earned its keep: h05 — a French ticket — fails at 0.5 because the keyword machinery is English-only. No amount of English prompt tuning fixes that; it's a task coverage gap, which is a non-prompt problem (2.3). Meanwhile h03 and h04 confirm the hedge and primary-issue rules generalise beyond the dev cases that motivated them.
1.6 Overfitting prompts to the dev set#
A prompt can score 100% on the dev set and be worse in production. The mechanisms:
- Memorisation via examples. If your dev set leaks into the prompt (few-shot examples that are near-duplicates of dev cases, or rules that name specific inputs — "when the ticket mentions invoice #4471..."), the model learns the answers, not the task. The hold-out set is the detector: it contains the same kinds of cases written differently.
- Rule-stacking. Each dev failure tempts a new rule. Twenty special-case rules make the prompt long, contradictory and brittle — the model starts satisfying the letter of rule 17 while violating rule 3 (02.10, Part 8 shows compliance degrades as constraint count grows). The fix is generalisation: rewrite the specific rule as the principle it instances ("polite hedges mean low urgency" covers a whole class, not one ticket).
- Scorer overfitting. If the scorer is an LLM judge, the prompt can drift toward what the judge rewards rather than what users need. Keep deterministic assertions for anything checkable; reserve judges for genuinely fuzzy qualities, and audit the judge itself (Module 10A).
- Dev-set staleness. Production inputs drift (new products, new phrasing, new languages — h05 is already drifting). Schedule hold-out re-runs and refresh the dev set from production failures; a dev set untouched for a quarter measures last quarter's product.
The practical protocol: iterate on dev, gate on hold-out. Ship a version only if hold-out doesn't regress. When dev and hold-out disagree, believe hold-out — it is the less contaminated estimate. For anything you ship to real traffic, the honest final check is a small online measurement, which is Module 11C's A/B machinery (7.4).
1.7 Variance, repeats and honest comparisons#
02.5, Part 7 established that API calls are not deterministic even at temperature 0 — batching, floating-point non-associativity and provider-side changes all contribute. For prompt iteration this means:
- One run is an anecdote. A prompt that passes 11/12 cases once might pass 9/12 on the next run. Set
repeats=3–5for real models on your dev set; the harness averages per case first, so the comparison unit stays honest. - Report intervals, not points. "92% ± noise" is not a result; "91.7%, 95% CI 65–99%" is. The Wilson interval in
promptlab.pyis the cheap version; for pass/fail comparisons between two prompt versions,compare()'s McNemar test is the right tool. - Compare paired, never pooled. Running prompt A on Monday and prompt B on Tuesday and comparing averages invites drift (the provider may have changed something). Run both on the same cases, interleaved if you can, and diff per case.
- Watch the tags.
markdown_table()slices by tag — a change that liftsoverallwhile tankingnegationis a trade, not a win. Real improvements usually show up as "fixed the target tag, broke nothing". - Seeds where supported. Some providers accept a
seedparameter (02.5, 3.10); it reduces but does not eliminate variance (02.9's caveats apply — pinning and evals beat seeds). Where seeds exist, fix one for dev-set runs so week-over-week numbers are comparable; vary it when you specifically want the variance estimate.
1.8 Iterating cheaply: cost-aware by default#
Prompt iteration burns tokens in three places: running the dev set, running hold-out/regression checks, and (for LLM-in-the-loop methods, Part 5) the optimiser itself. The levers, roughly in order of impact:
- Iterate on the cheapest model that shows the behaviour. A prompt that fixes format and instruction-following on
gpt-6-lunaorclaude-haiku-5-5usually transfers upward; verify the winner on your production model before shipping (Part 4 is about exactly this gap). Model prices differ by an order of magnitude between tiers (02.9, Part 6). - Keep the dev set small and the scorer cheap. Deterministic scorers cost zero tokens. An LLM judge multiplies every run's cost — use it only where no deterministic check exists.
- Cache-aware prompt layout. If your prompt has a stable prefix (system prompt, rules, examples), provider prompt caching makes repeated dev-set runs dramatically cheaper (02.7, 7.4, 03.7, Part 6). Put the volatile
{input}last — whichrender()already does. - Batch offline runs. Dev-set and hold-out evaluation is offline, embarrassingly parallel work: the Batch APIs cut cost ~50% for jobs that can wait hours (03.9, Part 6).
- Don't re-run what didn't change.
prompt_hashin the changelog tells you whether two runs even tested the same prompt. Cache run results keyed by (prompt hash, case id, model, repeats) and reuse them.
For the provider call itself, the harness needs only a ModelFn. Here is call_llm.py — illustrative glue, one function per provider in the Module 03 order. It returns the model's text; wire it into run() exactly like FakeTriager:
"""call_llm.py — ModelFn adapters for the four providers (ILLUSTRATIVE).
Each factory returns a callable with the signature
model_fn(system_prompt, rendered_prompt, case) -> str
so it drops straight into promptlab.run(). Needs the Module 03 SDKs and a
.env with OPENAI_API_KEY / ANTHROPIC_API_KEY / GEMINI_API_KEY / OPENROUTER_API_KEY.
Mechanics of each API are Module 03's job; this file only shows the seam.
"""
from __future__ import annotations
import os
from dotenv import load_dotenv
load_dotenv()
def openai_model(model: str = "gpt-6-luna"):
from openai import OpenAI
client = OpenAI()
def call(system: str, prompt: str, case) -> str:
# Responses API is primary (Module 03); `instructions` carries the
# system prompt, `input` the rendered user prompt.
resp = client.responses.create(
model=model,
instructions=system or "You are a helpful assistant.",
input=prompt,
)
return resp.output_text
return call
def anthropic_model(model: str = "claude-haiku-5-5"):
from anthropic import Anthropic
client = Anthropic()
def call(system: str, prompt: str, case) -> str:
# Messages API. No sampling parameters: the 2026-10-21 API version
# removed temperature/top_p/top_k (Module 03, lesson 03.2).
resp = client.messages.create(
model=model,
max_tokens=1024,
system=system or "You are a helpful assistant.",
messages=[{"role": "user", "content": prompt}],
)
return "".join(b.text for b in resp.content if b.type == "text")
return call
def gemini_model(model: str = "gemini-3.8-flash"):
from google import genai
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
def call(system: str, prompt: str, case) -> str:
# generate_content is primary (Module 03). System instruction goes in
# config; the rendered prompt is the user turn.
cfg = genai.types.GenerateContentConfig(
system_instruction=system or "You are a helpful assistant."
)
resp = client.models.generate_content(model=model, contents=prompt, config=cfg)
return resp.text or ""
return call
def openrouter_model(model: str = "openai/gpt-6-luna"):
from openai import OpenAI
# OpenRouter speaks Chat Completions through the openai SDK.
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"])
def call(system: str, prompt: str, case) -> str:
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": prompt})
resp = client.chat.completions.create(model=model, messages=messages)
return resp.choices[0].message.content or ""
return callPart 2: Diagnosing failures#
2.1 A failure taxonomy#
Before fixing anything, name what kind of failure you're looking at. Prompt debugging fails most often because people treat every bad output as a wording problem. The taxonomy:
| Failure class | What it looks like | Where the fix usually lives |
|---|---|---|
| Contract failures | Wrong format, prose instead of JSON/labels, extra commentary, missing fields | Prompt (output spec), or schema/API (03.4) |
| Instruction failures | Ignores a stated rule, violates a constraint, answers a different question | Prompt wording, context, or model capability |
| Comprehension failures | Misunderstands the task, misses negation/ambiguity, picks wrong category | Prompt (examples, rules), context, or data quality |
| Knowledge failures | Hallucinates facts, stale info, invents fields/entities | Context/RAG (Module 07), tools, or abstention rules — rarely more prompt |
| Reasoning failures | Right format, wrong logic; confident wrong chains | Prompt (CoT structure — 04.3), reasoning effort, or a stronger model |
| Consistency failures | Same input, different answers across runs; label drift | Sampling controls, prompt determinism aids, scoring with repeats |
| Context failures | Breaks on long inputs, loses early constraints, misses buried facts | Context selection/ordering (04.6, 04.7) |
| Capability failures | Task is beyond the model (arithmetic, counting, obscure knowledge, vision detail) | Different model, tools/code execution, or task redesign |
02.10 is the deep reference for why models fail; this part is about what to do next when your dev set shows a failure.
2.2 The symptom → cause → fix table#
The most-used artifact in this lesson. Work top-down: match the symptom, check the likely causes in order, apply the cheapest fix that the evidence supports.
| Symptom | Likely cause (in order) | Fix |
|---|---|---|
| Output format drifts (prose, extra keys, markdown fences) | No explicit output contract; contract buried mid-prompt; schema not enforced | Put the format spec last and make it exact; use structured output / strict schema (03.4); add a parser + retry (04.4) |
| Ignores an instruction that "obviously" applies | Instruction conflicts with another; too many constraints; negative phrasing; instruction too far from the data | Resolve contradictions; state the rule positively; move key rules next to the input or repeat at the end; reduce constraint count |
| Wrong label/category on edge cases | Label definitions ambiguous; no examples of the edge case; similar labels not distinguished | Sharpen label definitions with boundaries and examples; add 1–2 hard examples (04.2); add an explicit "other/unknown" escape |
| Hallucinates fields or facts | Asked for data not in the input; no grounding instruction; model fills gaps | Add "use only the provided text; say null/unknown when absent"; quote evidence; retrieval for real knowledge (Module 07) |
| Too verbose / ignores length limit | Soft length request; no counting mechanism; reasoning model over-explaining | Hard constraint + format; max_tokens/verbosity controls (02.5, 6.4); ask for the answer first |
| Refuses or over-refuses | Safety training on ambiguous phrasing; task looks like a restricted domain | Rephrase neutrally; clarify legitimate purpose; check provider refusal docs; route to a different model only as last resort |
| Inconsistent across runs | Temperature/sampling; borderline cases; genuine ambiguity | repeats to measure; tighten the decision rule; accept and score probabilistically |
| Breaks on long inputs | Lost-in-the-middle; context rot; instructions buried before data | Long data first, question last; re-state critical rules at the end (02.7, 5.5); shrink context (04.6) |
| Copies examples verbatim / anchors on them | Examples too similar to inputs; too few varied examples | Diversify examples; use placeholders for volatile fields; fewer, more distinct shots (04.2) |
| Loses constraints midway (multi-step) | Long instruction list; constraint–data distance grows | Group related rules; repeat the checklist at the end; split into chained steps (04.8) |
| Perfect on dev, wrong on production inputs | Overfit prompt; dev set unrepresentative; distribution drift | Hold-out gate (1.6); refresh dev set from prod failures; resist rule-stacking |
| Works on model A, fails on model B | Different instruction-following, format habits, reasoning defaults | Port deliberately — Part 4 |
2.3 Prompt fixes vs non-prompt fixes#
The most expensive debugging mistake is tuning a prompt to compensate for a problem that lives somewhere else. Before editing the prompt, ask which layer owns the failure:
| If the failure is... | The fix is... | Not... |
|---|---|---|
| Missing or wrong data (account state, doc content, order details) | Better context: retrieval, tool calls, database lookups (04.6, Module 07, Module 08A) | A longer prompt describing what the data would say |
| Wrong shape needed (nested JSON, enums, dates) | Schema/structured output, parsing, validation (03.4) | Begging in prose for "valid JSON" |
| Needs computation (sums, dates, regex, code) | Tools/code execution — models are unreliable calculators (02.10, Part 5, Module 08A) | Asking it to "be careful with numbers" |
| Needs current information | Search tools, fresh context injection, knowledge cutoff handling (02.10, Part 3) | Prompting harder about "recent" events |
| Systematically wrong on a class of inputs | Task redesign, better label taxonomy, human-in-the-loop, or (last resort) fine-tuning (02.1, 7.4) | A 40th special-case rule |
| Only wrong sometimes, borderline | Accept the uncertainty; calibrate the threshold; collect more data | Chasing 100% on an ambiguous task |
| Wrong on one model only | Port the prompt or pick the model that fits (Part 4) | Assuming the prompt is model-neutral |
2.4 Reading the model's behaviour#
When the dev set says "6 cases fail" you need to see why, not just that. Techniques, cheapest first:
- Show the failing case with the full prompt.
failing_cases()gives you(case_id, score, output); print the rendered prompt alongside — half of all "model misunderstandings" are prompt bugs (a stray example, a contradictory line, the{input}slot in the wrong place). 03.10, Part 3 is the API-level checklist for "what did we actually send". - Ask the model to explain its interpretation. Before asking for the answer, ask "restate the task in your own words" or "what rules apply here?" (the echo-back technique). If the restatement is wrong, the prompt is ambiguous — fix the prompt, not the output. If it's right but the answer is wrong, the failure is reasoning, not comprehension — different fix (04.3).
- Vary one sampling knob at a time. Where the provider supports it, compare outputs at different seeds/temperatures (02.5, Part 3). If answers swing wildly, the case is ambiguous or the prompt under-specified; if they're stable-but-wrong, it's systematic — a wording or context problem.
- Use logprobs where available. For classification/routing tasks, token logprobs expose the model's confidence distribution over labels (02.5, Part 5, provider support in 5.4). A label chosen at 0.51 vs 0.99 probability is a different debugging problem: the first wants a better decision rule, the second wants a different prompt or model.
- Inspect at token level when format breaks. If the model emits almost-right JSON, look at where it diverges — a missing comma, an unescaped quote, a truncated tail (02.2 covers what a token is and why errors cluster at token boundaries). That localises whether the problem is the schema (too complex — 03.4), the token budget (truncation — check finish reasons, 02.5, 4.5), or the prompt's format instructions.
- Diff two prompts.
diff_snapshots()(Part 3) shows exactly which cases changed output between versions — often the fastest way to see what a "tiny" edit actually did.
2.5 A debugging workflow that scales#
For a single failing case: reproduce → isolate → hypothesise → fix → verify (the verify step is a dev-set re-run, not a vibe). For a class of failures — which is what production gives you — work the loop in 1.3 but feed it from the taxonomy: cluster failures by class first (the tags column exists for this), fix the biggest cluster, re-measure. Never fix failures one-at-a-time in production order; you'll chase the same root cause five times.
Part 3: Prompt regression#
3.1 What a prompt regression suite is#
A regression suite is the dev set promoted to a gate: a fixed set of cases with scorers/assertions that must keep passing as prompts, models and context evolve. Without it, every prompt edit is a leap of faith and every model upgrade is a potential outage. With it, "did this change break anything?" is a command, not a meeting.
The components, all of which you already have:
- Golden set — the labelled cases (your dev set, frozen at ship time; optionally extended with hold-out cases once the prompt stabilises).
- Scorers/assertions — deterministic checks per case: exact match, contains, regex, JSON-schema validity, field-level comparisons, score thresholds.
- Snapshots — recorded outputs for diffing ("the prompt changed every answer" is information even when scores hold).
- A runner — executes the suite and reports pass/fail per case plus the aggregate.
- A threshold/gate — the rule for "acceptable": e.g. overall ≥ baseline − 0.02 and zero regressions on
critical-tagged cases.
3.2 Assertions, snapshots and canary cases#
Three complementary check styles:
- Assertions check properties: "output parses as JSON", "category ∈ allowed set", "urgency matches the rules table", "no PII pattern in output". Prefer them — they survive harmless wording changes.
- Snapshots check identity: the exact output text (or its hash) for cases where the output should be stable. Powerful but brittle — every legitimate prompt improvement breaks snapshots, so use them for invariants (a disclaimer line, a citation format) not for prose answers.
- Canary cases are a handful of high-value, high-visibility cases run on every change and watched in production-like conditions — the triage ticket that caused the last outage, the extraction that must never miss the total. They cost almost nothing and catch the regressions users actually feel.
3.3 The minimal runner#
promptlab.py already has the pieces; the regression runner adds a gate and a snapshot diff. Save as s3_regression.py (imports the triage task from s1_dev_loop.py — keep all files in one folder):
"""s3_regression.py — the minimal prompt regression runner (stdlib only).
Runs the golden set against the current prompt, diffs outputs against the
saved snapshot, and exits non-zero if the gate fails. CI without keys: swap
FakeTriager for a replay of recorded outputs (Part 3.4).
"""
from __future__ import annotations
import sys
from pathlib import Path
from promptlab import (
diff_snapshots,
failing_cases,
load_snapshot,
markdown_table,
run,
save_snapshot,
)
from fake_model import FakeTriager
from s1_dev_loop import DEV_SET, PROMPT_V4, triage_scorer
SNAPSHOT = Path(__file__).parent / "snapshots" / "triage_v4.json"
GATE_OVERALL = 0.95 # ship gate: overall score must stay >= this
GATE_CRITICAL_TAG = "critical" # no case with this tag may regress
def main() -> int:
model = FakeTriager()
result = run(DEV_SET, PROMPT_V4, model, triage_scorer,
name="triage-v4", model="fake-triager", repeats=1)
print(markdown_table([result]))
# 1. Score gate
ok = result.overall() >= GATE_OVERALL
print(f"score gate: {result.overall():.3f} >= {GATE_OVERALL} -> {'PASS' if ok else 'FAIL'}")
# 2. Snapshot diff: which cases changed output vs the recorded baseline?
if SNAPSHOT.exists():
old = load_snapshot(SNAPSHOT)
save_snapshot(result, SNAPSHOT.with_suffix(".new.json"))
new = load_snapshot(SNAPSHOT.with_suffix(".new.json"))
changes = diff_snapshots(old, new)
for ch in changes:
print(f" snapshot {'~' if ch['kind'] == 'changed' else ch['kind'].upper()}: {ch['case']}")
if not changes:
print(" snapshot: no output changes")
else:
SNAPSHOT.parent.mkdir(exist_ok=True)
save_snapshot(result, SNAPSHOT)
print(f" snapshot: created {SNAPSHOT}")
# 3. Critical cases must not fail
crit_fail = [cid for cid, s, _ in failing_cases(result) if GATE_CRITICAL_TAG in dict((c.id, c.tags) for c in DEV_SET)[cid]]
if crit_fail:
ok = False
print(f"critical gate: FAIL on {crit_fail}")
else:
print("critical gate: PASS")
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())And the pytest version for teams that want it in their test suite — test_prompt_regression.py:
"""test_prompt_regression.py — run with: pytest -q
The same golden set as a pytest module: fast, CI-friendly, and it fails the
build exactly like a broken unit test would.
"""
from promptlab import run
from fake_model import FakeTriager
from s1_dev_loop import DEV_SET, PROMPT_V4, triage_scorer
def test_triage_prompt_regression():
result = run(DEV_SET, PROMPT_V4, FakeTriager(), triage_scorer,
name="triage-v4", model="fake-triager", repeats=1)
assert result.overall() >= 0.95, f"triage score dropped to {result.overall():.3f}"
def test_no_case_scores_zero():
result = run(DEV_SET, PROMPT_V4, FakeTriager(), triage_scorer,
name="triage-v4", model="fake-triager", repeats=1)
zeros = [cid for cid, mean, _ in
((c, m, o) for c, m, o in zip(result.case_ids, result.case_means(), result.outputs))
if mean == 0.0]
assert not zeros, f"cases scoring zero: {zeros}"Running python3 s3_regression.py for the first time (deterministic — the snapshot path is abbreviated):
| run | hash | overall | pass rate (95% CI) | edge | hedged | negation | two-issue | urgent |
|---|---|---|---|---|---|---|---|---|
| triage-v4 | `44fd920d3e1b` | 1.000 | 100.0% (76%–100%) | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 |
score gate: 1.000 >= 0.95 -> PASS
snapshot: created .../snapshots/triage_v4.json
critical gate: PASSThe critical gate passes vacuously here because no case in DEV_SET carries the tag critical. In your own suite, tag the few cases that must never fail (the outage ticket, the must-not-miss total) so the gate has something to check.
3.4 Running it in CI, and the handoff#
Three cadences, three honest costs:
- Every PR (no keys): unit-test the rendering and run the suite against a fake/replay client — 03.10, Part 7 builds exactly this fake-client machinery. This catches prompt-text accidents (a deleted rule, a broken
{input}slot) but cannot catch model-behaviour regressions. - On merge / nightly (with keys, small set): run the golden set against the pinned production model. This is where real regressions surface. Use the cheapest tier that matches production behaviour,
repeats=3, and alert on gate failure — 03.9 for cheap bulk runs, 03.8 for flaky-infrastructure handling. - On model-version bumps (scheduled): providers retire snapshots and ship new ones with notice periods (02.9, Part 8); run the full suite on the new snapshot before switching the pin, and keep the old snapshot's results for diffing.
You will outgrow this minimal runner quickly — and that's the signal to move to the real evaluation stack. Module 10A owns eval datasets, metrics, LLM-as-judge design and statistical rigour; Module 11A and Module 11C own CI/CD for prompts, tracing and alerting. Mentioned here only because you'll meet them: promptfoo (open-source eval/red-team CLI under the MIT licence; OpenAI announced on 9 March 2026 that it would acquire the company, and as of November 2026 the repository README says it is now part of OpenAI and remains open source and MIT licensed; see the company update) is the most common off-the-shelf answer for exactly this golden-set workflow.
Part 4: Porting prompts across models and providers#
Deep-dive
4.1 Why prompts don't transfer 1:1#
A prompt is not a specification — it's a suggestion to a particular trained behaviour. Two models trained on different data, with different chat templates, different instruction hierarchies and different post-training will read the same words differently. The evidence is already in this module: 02.10, Part 7 shows small phrasing changes swing accuracy, and 04.1 covers how model classes (reasoning vs non-reasoning, frontier vs small) respond to different habits.
Practically, a port fails in five recurring ways:
- Format habits differ. One model wraps JSON in markdown fences unless forbidden; another emits a preamble ("Sure! Here's..."); a third truncates at the first closing brace. The fix is provider-appropriate output control — response formats, stop sequences and, where the provider still supports it, prefill (Anthropic no longer accepts prefilled assistant turns from Claude 4.6 onward) — not more prose pleading (03.4, 03.2).
- Instruction weight differs. Some models follow the system prompt almost literally; others blend it with user-turn enthusiasm. Rules that were "obvious" on model A get negotiated on model B.
- Reasoning defaults differ. Reasoning models think before answering and want goals + constraints, not step-by-step scripts (02.8, Part 7); non-reasoning models need the structure spelled out. A CoT-heavy prompt can hurt on a reasoning model (over-thinking, format breaks) and help on a standard one.
- Vocabulary and culture differ. Training data mixes differ: one model knows your internal acronym, another doesn't; one is chattier by default, one terser. "Be concise" means different lengths to different models.
- Provider plumbing differs. Where instructions go (system vs developer vs user role), what parameters exist (effort vs temperature vs thinking budget), and how tools/schemas are expressed all vary (03.2, 02.8, Part 3).
4.2 What differs per provider — verified and reported#
The table separates documented differences (provider docs, verified November 2026) from reported ones (community observation — treat as hypotheses to test on your model, not facts).
| Area | OpenAI | Anthropic | Gemini | OpenRouter |
|---|---|---|---|---|
| Instruction placement | instructions param / system-ish role on Responses; developer role on Chat Completions (03.2) |
system param, top of Messages request |
system_instruction in config |
Chat Completions system message |
| Reasoning control | reasoning.effort on reasoning models (02.8, 3.1) |
adaptive thinking + effort (02.8, 3.2) | thinking_level / thinking config (02.8, 3.3) |
one reasoning param translated per provider (02.8, 3.4) |
| Sampling knobs | temperature/top_p exist but frontier models increasingly ignore or reject them (02.5, 6.2) |
removed entirely in API version 2026-10-21 | model-dependent | depends on routed endpoint |
| Documented prompt guidance | Prompt engineering guide: pin snapshots, build eval suites, iterate; prompting guide: treat prompts as code | Prompting best practices: organised per model — model-specific guidance first; overview: success criteria + tests first | Prompting strategies: iterative by design; Gemini 3 prompting guide: thinking levels, place critical constraints last, split-step verification | inherits whichever model you route to; see that model's docs |
| Reported habits (test on your model) | Literal instruction-following post-GPT-4.1 (GPT-4.1 prompting guide, archived); verbose unless told otherwise | Responds well to XML-structured prompts and examples (Anthropic docs) | Gemini 3 defaults to less verbose, more direct answers; may over-index on "do not infer" (Gemini 3 prompting guide) | Behaviour varies by endpoint, not just model — routing can change results for identical prompts |
| Prompt tooling (Nov 2026) | Prompt optimiser in dashboard (chat interface; dataset-backed optimiser deprecated with Evals, shutdown Nov 30 2026 — docs); reusable prompt objects v1/prompts also shutting down Nov 30 2026 (deprecations) |
Experimental prompt-tool APIs (generate_prompt, improve_prompt, templatize_prompt) retired Aug 17 2026 with the legacy Workbench (the old prompt-improver docs page now redirects to the best-practices page); Playground (Aug 18) runs requests but stores no prompts/evals (release notes) |
Vertex AI / Gemini Enterprise Agent Platform: zero-shot and few-shot prompt optimizers via the Agent Platform SDK, plus a Studio AI prompt assistant (refine/generate) — zero-shot, few-shot, assistant; all Vertex-side — recheck which surface your Gemini access uses | Presets exist (see 04.10) |
4.3 The migration checklist#
When a prompt must move (new provider, new model family, model deprecation, or a "the old one is cheaper" decision), run this in order:
- Freeze the source of truth. Export the exact prompt text + version + the model ID it was tuned on + its dev-set score. You are porting a measured artefact, not a vibe.
- Run the unchanged prompt on the target first. Baseline before editing — you need to know how much is "the model differs" vs "the port broke it".
- Check the mechanics, not the wording. Instruction placement, parameter names, output-format features, reasoning controls (03.2, 02.8, Part 3). A prompt can be word-perfect and still fail because
temperature400s or the system role doesn't exist. - Adapt the prompt to the target's documented habits. XML vs Markdown structure, verbosity defaults, reasoning-model prompting style (02.8, Part 7). Change the form, keep the contract.
- Re-run the full dev set + hold-out on the target. Same cases, same scorer,
repeatsmatched. Compare per-case, not just the aggregate. - Iterate on the target with the same loop (1.3) — but expect a different optimum. The best prompt for Claude is not the best prompt for GPT; don't force symmetry.
- Record the port in the changelog: source model → target model, score before/after, what you changed and why. Future-you will need it when the target model also gets deprecated.
- Keep both versions alive during transition. Route by capability or A/B until the new path proves itself in production metrics (7.4).
4.4 Model versions and deprecations#
Prompts are tested against model snapshots, and snapshots die. 02.9, Part 8 covers aliases vs snapshots, lifecycle stages and pinning; the prompt-engineering consequence:
- A prompt version and a model version are one unit. Your regression suite must record which model produced the baseline. "triage-v4 @ claude-haiku-5-5 scored 0.958" is a fact; "triage-v4 scored 0.958" is not.
- Deprecation notices are your migration trigger. Providers announce shutdowns weeks-to-months ahead (02.9, 8.2); treat each notice as a scheduled porting task, not an emergency. The checklist in 4.3 is the runbook.
- Silent behaviour drift happens without deprecation. Providers update serving infrastructure; identical prompts can shift (02.5, Part 7). The regression suite on a schedule is the only detector — which is why 3.4 matters more than any single prompt trick.
- Provider prompt tooling is volatile too. As of November 2026: OpenAI's dataset-backed prompt optimiser is being deprecated with the Evals platform (read-only Oct 31, shutdown Nov 30 — prompt optimizer docs, deprecations); Anthropic's prompt improver and the experimental
improve_prompt/generate_prompt/templatize_promptAPIs were retired August 17, 2026 with the legacy Workbench, and the replacement Playground stores no prompts or evals (release notes). Build your own loop (Part 1) — it outlives any vendor's tool.
4.5 Automatic prompt optimization tools#
"Automatic prompt optimization" (APO) is the name for tools that search prompt space for you: generate variants, score them, keep the best. Three honest categories as of November 2026:
| Tool | What it does | When it's worth it | Limits |
|---|---|---|---|
| DSPy (dspy.ai, PyPI — v3.5.0 as of 11 November 2026) | Programming model: you declare a Signature (typed inputs/outputs) and Module; optimizers (GEPA, MIPROv2, BootstrapFewShot) mutate instructions and/or demos against your metric + trainset |
You have a measurable metric, a trainset, and a pipeline worth optimising systematically; GEPA's reflection loop is the newest of these optimisers (GEPA docs, paper arXiv:2507.19457) | Costs many LM calls; needs a good metric (garbage metric → optimised garbage); optimises for the trainset — hold-out discipline still yours; framework learning curve |
| TextGrad (GitHub, textgrad.com) | "Autograd for text": an LLM critiques outputs in natural language and that critique is backpropagated to rewrite prompts/variables (published in Nature, 2025) | When you have judgment but no labels — a critic LM can score what a metric can't | Noisier, pricier gradient signal; inherits every quirk of LLM-as-judge; less turnkey than DSPy for pure prompt search |
| Provider/console tools | OpenAI dashboard prompt optimiser (chat-based; dataset-backed version deprecated Nov 2026); Anthropic improver (retired Aug 2026) | Quick first-draft improvement, adapting a prompt written for another model | Black-box, no versioned artefact, no regression suite — a starting point, not a system |
The meta-lesson regardless of tool: optimisers amplify your eval, they don't replace it. A tool that searches 500 prompt variants against a 12-case dev set will find the variant that overfits those 12 cases. Give it a trainset and a hold-out, keep the human-readable prompt as the artefact you ship, and read the diff it produces — auto-optimised prompts are often weird, effective, and worth understanding before you deploy them.
Part 5: Optimization with an LLM in the loop#
Deep-dive
5.1 The generate–critique–select loop#
The simplest APO doesn't need a framework — it's the dev loop with an LLM playing "failure analyst". The loop:
- Run the current prompt on the dev set; collect the failures (
failing_cases()). - Show the LLM the prompt + the failing cases + their wrong outputs + the expected labels.
- Ask for a revised prompt (or a list of candidate revisions) — the critic.
- Run each candidate on the dev set; keep the best that doesn't regress.
- Log everything; repeat until the hold-out stops improving.
This is meta-prompting applied to prompt engineering — 04.8 covers the general technique; the gallery prompt G3 is a ready-made critic. Its advantage over hand-tuning: the critic sees patterns across failures a human skims past ("three of the six failures share negation phrasing"). Its risk: the critic proposes rule #18 for a problem that wants a schema fix (2.3) — always diagnose before accepting a proposal.
5.2 A minimal tournament harness#
promptlab.py already supports the mechanics; what's missing is the candidate generator and the selection rule. Here's s5_tournament.py — pure-local, works with any ModelFn as both actor and critic:
"""s5_tournament.py — LLM-in-the-loop prompt tournament (pure-local demo).
Actor = the model under test. Critic = an LLM (or fake) that proposes prompt
variants from observed failures. Selection = best train score with a
no-regression constraint, verified on a hold-out split. Overfitting is the risk
to watch: a candidate can win on `train` and still lose on the hold-out.
"""
from __future__ import annotations
from promptlab import compare, failing_cases, markdown_table, run
from fake_model import FakeTriager
from s1_dev_loop import DEV_SET, HOLDOUT_SET, PROMPT_V3, triage_scorer
# A fake "critic": deterministic rules that turn observed failures into prompt
# edits — stands in for an LLM reading the same failures. In production this
# function is an LLM call (see the illustrative version below).
def fake_critic(prompt: str, failures: list[tuple[str, float, str]]) -> list[str]:
variants = [prompt + "\n\nRemember: answer with exactly one line."]
# The hedge failure class shows up in the failing INPUTS, not the outputs —
# a real critic reads the cases; this stub proposes the fix unconditionally.
variants.append(prompt.replace(
"Output format:",
"Polite hedges like 'whenever you can' mean low urgency.\n\nOutput format:"))
return variants
def llm_critic(system: str, prompt: str, case) -> str: # placeholder signature
raise NotImplementedError("swap in a real ModelFn that returns revised prompts")
def main() -> None:
actor = FakeTriager()
train, holdout = DEV_SET[:9], DEV_SET[9:] + HOLDOUT_SET # split, not the real hold-out
# Baseline: v3 still misses the hedge case (t05), so the critic has work to do.
base = run(train, PROMPT_V3, actor, triage_scorer, name="v3", model="fake")
print("baseline:", f"{base.overall():.3f}")
# Generate candidates from observed failures
fails = failing_cases(base)
candidates = fake_critic(PROMPT_V3, fails)
print(f"{len(candidates)} candidate(s) from critic")
results = [base]
comparisons = []
for i, cand in enumerate(candidates):
r = run(train, cand, actor, triage_scorer, name=f"cand-{i}", model="fake")
results.append(r)
c = compare(base, r)
comparisons.append(c)
print(f" cand-{i}: train {r.overall():.3f} (delta {c.mean_delta:+.3f}, "
f"regressions {c.regressed})")
# Selection rule: best train score AND no case-level regressions vs baseline.
# A candidate is eligible only when compare() reports zero regressed cases;
# the baseline itself is always eligible, so a bad tournament keeps v3.
eligible = [base] + [r for r, c in zip(results[1:], comparisons) if not c.regressed]
best = max(eligible, key=lambda r: r.overall())
verdict = "baseline kept" if best is base else f"{best.name} selected"
print(f"selection: {verdict} — train {best.overall():.3f}")
print(markdown_table(results))
# Verify winner on hold-out — the overfitting check
hr = run(holdout, best.prompt, actor, triage_scorer, name="winner-holdout", model="fake")
print("\nhold-out verification of winner:")
print(markdown_table([hr]))
if __name__ == "__main__":
main()Run it with python3 s5_tournament.py (it needs promptlab.py, fake_model.py and s1_dev_loop.py in the same folder). The fake model is deterministic, so this is real output:
baseline: 0.944
2 candidate(s) from critic
cand-0: train 0.944 (delta +0.000, regressions [])
cand-1: train 1.000 (delta +0.056, regressions [])
selection: cand-1 selected — train 1.000
| run | hash | overall | pass rate (95% CI) | edge | hedged | negation | two-issue | urgent |
|---|---|---|---|---|---|---|---|---|
| v3 | `649eaed45384` | 0.944 | 88.9% (56%–98%) | 1.00 | 0.50 | 1.00 | 1.00 | 1.00 |
| cand-0 | `0f37fb8499c3` | 0.944 | 88.9% (56%–98%) | 1.00 | 0.50 | 1.00 | 1.00 | 1.00 |
| cand-1 | `f35b82c6c495` | 1.000 | 100.0% (70%–100%) | 1.00 | 1.00 | 1.00 | 1.00 | 1.00 |
hold-out verification of winner:
| run | hash | overall | pass rate (95% CI) | hedged | multilingual | two-issue |
|---|---|---|---|---|---|---|
| winner-holdout | `f35b82c6c495` | 0.938 | 87.5% (53%–98%) | 1.00 | 0.50 | 1.00 |Read it as the protocol working: cand-0 adds nothing, cand-1 fixes the hedge failure with no regressions and is selected, and the hold-out split (the last three dev cases plus the five real hold-out cases) scores 0.938 — lower than the 1.000 on train, and the lost points are the French ticket, a coverage gap no prompt edit in this tournament addresses.
For a real critic, fake_critic becomes a ModelFn call with a prompt like gallery item G3: give it the current prompt, the failing (input, expected, actual) triples, and ask for a revised prompt — then validate the reply (it must still contain the output contract) before it enters the tournament. The validation step matters: critics occasionally delete the format spec while "improving" reasoning, and an unvalidated candidate poisons the whole run.
The price is arithmetic, and it's worth doing before you scale the tournament up: every candidate costs one full dev-set run (cases × repeats actor calls) plus the critic calls that proposed it, and the loop repeats until the hold-out stops improving. On this lesson's 12-case set with repeats=3 and ten candidates that's ~360 actor calls plus the critic overhead — trivial on a small model, real money on a frontier one. This is why the knobs that matter are budget-shaped: DSPy's GEPA takes exactly one of auto (light/medium/heavy), max_full_evals or max_metric_calls to cap total metric invocations (GEPA in depth, verified November 2026), small dev sets keep each evaluation cheap, and the critic can run on a cheaper model than the actor. Cost-aware iteration (1.8) applies to the optimiser exactly as it does to your hands.
Part 6: Cost and latency tuning of prompts#
Deep-dive
Prompt work has a price tag in two currencies: tokens (money) and wall-clock (latency). Both are tunable through the prompt — which is why this belongs in an iteration lesson, not just a billing one.
6.1 Shorten without losing quality: the ablation method#
The disciplined way to shrink a prompt: remove one section at a time and measure — the same ablation 04.6 uses for context sources. For each candidate deletion (an example, a rule block, a persona paragraph, a repeated instruction), run the dev set and compare. Keep what earns its tokens; cut what doesn't. Two rules of thumb that survive contact with production:
- The last instruction is the most expensive real estate. Critical rules belong near the end (or repeated there) because position effects are real (02.7, 5.5) — but a rule stated twice is two tokens' worth of insurance, not four.
- Examples cost tokens per call, every call. Three few-shot examples might be 600 tokens × every request × every user. If the task works zero-shot on your model, the examples are overhead; if they fix a real failure class, they're the cheapest fix available. Measure, don't guess (04.2 covers the trade-off).
6.2 Caching-friendly structure#
Every prompt token you send is billed as input — unless it hits the provider's prompt cache. The cache economics are 03.7's subject; the prompt-design consequence is one rule: stable content first, volatile content last. System prompt → rules → examples → retrieved context → the actual question/input that changes per call. Put the {input} slot and any per-request data at the very end (02.7, 7.4). Reordering a prompt to improve cache hits is a measured change like any other — verify on your dev set that the reorder didn't move the answer.
6.3 The model ladder: better prompts on smaller models#
The cheapest latency and cost win is often not a shorter prompt but a smaller model — if the prompt is good enough to close the capability gap. The workflow:
- Develop the prompt on the cheapest tier that shows the target behaviour (iteration is typically several-fold cheaper there — the gap between tiers is an order of magnitude and drifts; verify current prices in 02.9, Part 6).
- Verify on your production model; if it passes, consider whether the production model can be downgraded too — run the same dev set on the smaller model and compare.
- A prompt that rescues a small model is a reusable asset: keep the "small-model prompt variant" in your library (04.10) for cost-sensitive traffic paths.
6.4 Output tokens, reasoning tokens and batching#
- Output is the expensive direction (02.5, 1.4): reasoning tokens bill as output too (02.8, 5.1). Cap
max_output_tokens/max_tokensto what the contract needs; ask for the answer before the explanation when the explanation isn't consumed; use verbosity controls where offered (02.5, 6.4). - Reasoning effort is a prompt-cost knob. On reasoning models, effort/thinking level trades quality for tokens and latency (02.8, Part 3). Tune it on the dev set like any other variable — higher isn't always better, and "medium" often beats "high" on cost-adjusted quality.
- Batch what can wait. Dev-set runs, regression suites, backfills and LLM-judge scoring are offline work: the Batch APIs roughly halve cost at the price of latency (03.9, Part 6). Never batch a user-facing call; always batch an eval.
Part 7: Debugging prompts in production#
Deep-dive
7.1 What to log — the prompt-regression fields#
03.10, Part 4 owns logging mechanics (redaction, correlation IDs, OTel); the prompt-specific fields a debugging log needs on top:
{
"ts": "2026-11-05T14:22:11Z",
"trace_id": "req_8f3a…",
"prompt_name": "ticket-triage",
"prompt_version": "v4",
"prompt_hash": "44fd920d3e1b",
"model": "claude-haiku-5-5",
"model_snapshot": "claude-haiku-5-5",
"case_id": null,
"input": "<the ticket text>",
"output": "billing | normal",
"score": null,
"latency_ms": 812,
"usage": {"input_tokens": 410, "output_tokens": 8}
}The non-obvious ones: prompt_version + prompt_hash (which prompt produced this — the changelog join key), model_snapshot (which weights — some providers alias moving snapshots; Anthropic's dateless IDs such as claude-haiku-5-5 are each a fixed snapshot, so the ID itself is the value, while for an alias such as an OpenAI or Gemini latest name you log the exact model string the response reports back; 02.9, 8.1), score when a cheap scorer exists (lets you alert on quality, not just errors), and case_id when the input came from a known dataset row. Log the rendered prompt or enough to reconstruct it — "what did the model actually see" is 03.10's first debugging question, and for prompts the answer includes template variables.
7.2 Sampling failures: trace sampling for prompts#
You cannot read every production prompt I/O — volume and privacy both say no. The pattern that works:
- 100% of failures — scorer failures, user-reported bad outputs, parse errors, refusals, guardrail trips. These are your dev-set feedstock.
- A random sample of successes — 1–5% depending on volume — to catch silent regressions (the prompt got subtly worse but nothing "failed"). This is also your A/B measurement substrate.
- All canary/critical-path calls — the small set of high-stakes flows get full logging always.
- Never log secrets or unredacted PII — 03.10, 4.5 covers redaction; prompt inputs are user data and inherit every rule.
7.3 Closing the loop: feedback → dev set → fix#
Production debugging only works if failures flow back into the lab:
- Thumbs-down / "bad answer" buttons and support escalations land in a review queue.
- A human (or the dev-set labeller prompt — gallery G4) labels each: real failure vs user error vs ambiguous.
- Confirmed failures become new dev-set cases — this is how the dev set stays representative as the product drifts (1.6).
- Fixes go through the normal loop: reproduce on the dev set → diagnose → change one thing → verify → changelog → ship.
The failure mode to avoid: "fixing" production prompts from anecdotes. One angry user's ticket is a hypothesis, not a spec — it becomes a dev-set case first, and only ships if it doesn't regress the suite.
7.4 A/B tests, canaries and rollouts#
For changes too risky for the dev set alone — tone shifts, big restructures, model swaps — measure on real traffic:
- Offline A/B first: run both prompt versions over a larger labelled sample (hundreds of cases, not 12) before touching production. This catches what the dev set can't.
- Online A/B: split traffic by user/request hash, measure the same metrics you'd put in the dev set (task success, format validity, downstream action rate) plus guardrails (latency, cost, escalation rate). The statistics are Module 10A's subject; the prompt-level rule is decide the metric before you start and pre-register the minimum detectable effect — with LLM variance, small samples lie (1.7).
- Canary rollout: ship the new prompt to 1–5% of traffic first, watch the golden metrics, then ramp. A prompt regression at 100% is an outage; at 2% it's a ticket. Shadow traffic (run the new prompt, log but don't serve) is the zero-risk variant for high-stakes flows.
7.5 The incident playbook#
When "the prompt broke in prod":
- Freeze. Pause prompt rollouts and model-version bumps until you know what changed.
- Identify the change. Compare
prompt_hash/prompt_version/model_snapshotin logs before vs after the regression started — the changelog and deploy log usually name the culprit immediately. - Reproduce offline. Pull the failing logged inputs into a mini dev set; run current vs previous prompt version. If it reproduces, you have a dev-set case and a fix path. If it doesn't reproduce, suspect the input distribution (a new kind of ticket arrived) or provider-side drift — widen the sample.
- Fix forward or roll back. Prompts are config: rollback = redeploy the previous version (your changelog makes this a lookup, not an archaeology project). Fix forward only if the fix is measured.
- Add the case to the regression suite. Every production incident becomes a permanent canary case — that's how the suite earns its keep.
- Postmortem the process. Did the dev set lack this case class? Did the gate threshold sit too low? Did the rollout skip the canary? Fix the process hole, not just the prompt.
Part 8: Anti-patterns catalogue#
Reference
The recurring ways prompt work goes wrong — each with the fix:
| Anti-pattern | Why it fails | The fix |
|---|---|---|
| Prompt spaghetti — one undifferentiated 4,000-word blob | No structure → the model can't tell rules from data; contradictions hide; nobody can review it | Sections, tags, a template (04.4, 04.10) |
| Contradictory instructions — "be concise" + "explain everything thoroughly" | Models resolve conflicts unpredictably; compliance degrades with constraint count | One priority order; resolve conflicts explicitly; fewer, sharper rules |
| Hidden assumptions — "use the usual format", "as discussed" | The model has no "usual"; it invents one | Write the contract explicitly every time |
| Example leakage — real customer data, PII, or near-duplicate dev cases inside prompts | Privacy breach + the model copies example content into outputs | Synthetic examples; placeholders; Module 12 for the security rules |
| Prompt-as-database — cramming reference tables, catalogues, policies into the prompt | Bloats every call, goes stale, hurts attention | Retrieval/tools for data; prompt for behaviour (04.6) |
| Unbounded context — "here's everything we have, figure it out" | Context rot, cost, lost-in-the-middle | Select and budget context deliberately (04.6) |
| Copy-pasted internet prompts — "You are DAN", "take a deep breath", "$200 tip", ALL CAPS | 2023-era folklore; current models don't need it and some patterns actively hurt | Provider docs + your own dev set; this module's evidence-minded approach |
| Overfitting to the dev set — rules that name test cases | 100% dev, drift in prod | Hold-out gate, generalised rules (1.6) |
| Changing five things at once | Can't attribute the result; can't roll back cleanly | One variable per iteration (1.3) |
| No version, no changelog | "What changed before it broke?" is unanswerable | Changelog + versioned prompts (04.10) |
| Iterating on production | Real users become your dev set; no control, no measurement | Offline dev set → canary → A/B (Part 7) |
| Treating prompts as model-neutral | Works on GPT, silently fails on Claude | Per-model ports + regression per model (Part 4) |
| Optimising without a metric | "Looks better" isn't a metric; auto-optimisers amplify whatever you give them | Scorer first, always (1.1) |
Part 9: Worked case studies#
Deep-dive
Three failures taken from broken prompt to fixed prompt — the reasoning and the changelog entry, not just the diff. (The triage case reuses the Part 1 demo data, so its numbers are real output you can reproduce. Cases B and C are constructed illustrations of the method on new tasks: the incidents, the model behaviours they describe, and every score, hash and timing are invented to show the shape of a changelog and are not measurements of any model.)
Case study A: the triage prompt that couldn't decide (contract + rules)#
Broken (v2-equivalent): role + task + category list + format line — scored 0.750 on the dev set. Six failures: two-issue tickets labelled by whichever keyword appeared last (t03, t06, t08), a negated category taken literally (t04), hedged urgency read as normal (t05, t11).
Diagnosis: not a comprehension failure — the model understood the task; it lacked decision rules for ambiguous inputs. Symptom table row: "wrong label on edge cases → label definitions ambiguous; add boundary rules and examples".
Fix (v3→v4): added the URGENCY RULES block, the negation rule, the primary-issue rule, and the hedge rule — each targeting a class of failure, not a case. Dev 1.000, hold-out 0.900 with only the multilingual case failing.
Changelog:
v3 | 649eaed45384 | 0.750 → 0.958 | added urgency rules, negation, primary-issue rule
v4 | 44fd920d3e1b | 0.958 → 1.000 | added polite-hedge rule for low urgencyLesson: the wins came from rules that generalise, applied one class at a time — and the hold-out immediately showed the remaining gap was coverage (non-English tickets), not wording.
Case study B: invoice extraction that invented a field#
Broken prompt: "Extract the invoice details as JSON: vendor, invoice_number, date, total, line_items, payment_terms, currency." On real invoices the model returned "payment_terms": "Net 30" even when the invoice never stated terms — it inferred the most common value. Dev set (hand-picked clean invoices) never caught it because every dev invoice had terms.
Diagnosis: hallucinated fields — the prompt asked for data not guaranteed present, with no abstention path. Symptom table: "hallucinates fields → asked for data not in input; add null/unknown rule + grounding". This is also a dev-set failure: the set didn't cover the missing-field case.
Fix — three layers, not one:
- Prompt: added "If a field is not stated in the invoice, output
null. Never infer or assume values." plus "quote the source text fortotal". - Schema: made
payment_termsexplicitly nullable in the structured-output schema (03.4) sonullis a first-class answer, not a failure. - Validation: a semantic check that flags any non-null extracted value not found in the source text (grounding check — 03.4, 6.3).
Dev-set fix: added five invoices without payment terms and two with ambiguous totals. Score before: 0.71 → after: 0.94, and the residual failures were genuinely ambiguous scans (a data problem, routed to OCR review — a non-prompt fix).
Changelog:
v1 | 7c2e91a4f0d3 | — → 0.710 | first draft: extract fields as JSON
v2 | e58b03d71c96 | 0.710 → 0.940 | null/abstention rule + source quote for total; nullable schema + grounding validator; +7 dev cases covering missing fieldsLesson: the prompt fix alone would have reduced hallucination but the schema + validator is what makes it enforceable. When a field can be absent, the contract must say so — in the prompt, the schema, and the check.
Case study C: porting a summariser from GPT to Claude (and Gemini)#
Starting point: a meeting-notes summariser tuned on gpt-6-luna: Markdown headings, "be concise but comprehensive", bullet actions, ~150 words. Dev set: 14 labelled meetings, score 0.89.
Port attempt 1 — unchanged: Claude returned XML-tagged sections and noticeably longer outputs; Gemini returned terse prose ignoring the heading structure. Dev scores: Claude 0.71, Gemini 0.64. Classic format-habit and verbosity drift (4.1).
Fix per provider (form changes, contract kept):
- Claude: kept the structure but switched section markers to the XML-ish tags Anthropic's docs favour, and tightened the length rule to a hard "≤150 words" with an example. Score → 0.86.
- Gemini: its default is less verbose (Gemini 3 prompting guide) — the "comprehensive" instruction was producing shorter outputs than wanted, so the prompt added explicit coverage requirements ("every decision and every action item must appear") rather than length words. Score → 0.85.
- OpenRouter: to check whether the gateway matters, route the same Claude model through it (
anthropic/claude-sonnet-5.5) and re-run the dev set. If the scores match the direct-API run, the model (not the gateway) drives the difference; if they don't, you have an endpoint-level difference to log, which is the reported OpenRouter habit in 4.2.
Changelog:
v1 @ gpt-6-luna | 4a91f2c7e0b5 | — → 0.890 | tuned on gpt-6-luna: markdown headings, ~150 words
v1 @ claude | 4a91f2c7e0b5 | — → 0.710 | unchanged prompt baseline on claude-sonnet-5-5 (port attempt 1)
claude-v2 @ claude | 9d03be61a7f2 | 0.710 → 0.860 | XML-ish section tags + hard ≤150-word rule + worked example
v1 @ gemini | 4a91f2c7e0b5 | — → 0.640 | unchanged prompt baseline on gemini-3.8-flash (port attempt 1)
gemini-v2 @ gemini | c6f84a20d9e1 | 0.640 → 0.850 | explicit coverage requirements instead of length wordsOne entry per port with source→target model, before/after scores, and the specific habit that changed. In a real port the effort is mostly dev-set runs, and it is cheap compared with discovering the drift in production.
Lesson: the contract (what a good summary contains) ported unchanged; the form (tags, length words, coverage phrasing) had to be re-tuned per model. That's the whole porting philosophy: preserve the spec, re-earn the wording.
Prompt gallery#
Reusable prompts for the jobs this lesson covers. Each is complete; drop into your {input} convention or adapt.
G1 — Failure-triage prompt (classify a bad output before you fix anything):
You are a debugging assistant for LLM prompts. I will give you a prompt, a failing
input, the model's output, and the expected output. Diagnose the failure class —
choose exactly one: contract, instruction, comprehension, knowledge, reasoning,
consistency, context, or capability — then explain the most likely cause and the
cheapest fix (prompt wording, context/data, schema/API, tools, model change, or
task redesign). Do not rewrite the prompt yet.
PROMPT:
{input}G2 — Echo-back / interpretation check (run before asking for the answer on ambiguous cases):
Before you answer, restate the task in your own words: what is being asked, what
the output format must be, and which rules apply to THIS input. Then answer.
{input}G3 — Prompt critic (the LLM-in-the-loop proposer; feed it failures, get a revision):
You are a prompt engineer reviewing a failing prompt. Below is the current prompt,
then cases where it failed: each shows the input, the expected output, and the
actual output.
CURRENT PROMPT:
{prompt}
FAILURES:
{failures}
Propose ONE revised prompt that fixes the failure pattern without breaking what
already works. Rules: keep the output contract identical; prefer general rules
over special cases; do not add more than ~150 words; output only the revised
prompt text, no commentary.G4 — Dev-set labeller (turn raw production failures into labelled cases):
You are labelling examples for a prompt regression suite. For each input below,
produce the CORRECT expected output according to this rubric: {rubric}. If the
input is genuinely ambiguous or the correct answer depends on information not
provided, mark it AMBIGUOUS instead of guessing.
INPUTS:
{inputs}G5 — Regression-triage prompt (after a model/prompt bump, explain what changed):
A prompt regression suite shows these cases changed after a model version bump.
For each, compare the old and new outputs and hypothesise whether the change is
a prompt problem (wording no longer lands), a model-behaviour change (new default
habits), or a legitimate improvement. Group the cases by likely cause.
CASES:
{cases}G6 — Porting reviewer (check a prompt for provider portability):
Review this prompt for portability across model providers. Flag: instructions
that assume a specific chat-template role, output-format habits that may differ,
reasoning-style instructions that could conflict with built-in reasoning, and
wording that relies on one provider's documented prompting guidance. For each
flag, say whether it's a hard blocker or a test-on-target item.
PROMPT:
{prompt}Common misconceptions#
| Misconception | Reality |
|---|---|
| "A better prompt is just a longer/more detailed prompt" | Detail helps until constraints conflict; after ~a handful of rules, compliance degrades and cost rises. Measure additions like any other change. |
| "If it works on my model it'll work on theirs" | Prompts are model-specific artefacts; port deliberately with a dev set per model. |
| "Temperature 0 makes runs reproducible" | API non-determinism persists (batching, FP non-associativity, provider changes); use repeats and intervals, not single runs. |
| "The dev score is the truth" | The dev set is a sample; hold-out and production metrics are the less-contaminated estimates. |
| "Auto-optimisers find the best prompt" | They find the best prompt for your metric and trainset — including the one that overfits both. |
| "Prompt regressions are rare" | Every prompt edit, model bump and provider infra change can regress; without a suite you find out from users. |
| "Fine-tuning fixes bad prompts" | Fine-tuning is for behaviour prompts can't reach; it needs data, money and evals — and a good prompt is the baseline it builds on. |
| "More examples always help" | Examples fix format/style/edge decisions but cost tokens every call and can anchor/copy; zero-shot often wins on strong models. |
| "The provider's prompt tool knows best" | Vendor tools are conveniences that come and go (Anthropic's improver already retired); your own measured loop is the durable asset. |
Key takeaways#
- Define success before you write: a rubric, a scorer, and a small labelled dev set are the preconditions for iteration — every provider's docs now say so.
- The loop is boring on purpose: one change at a time, measure on the same cases, keep a changelog, gate on hold-out.
- Measure honestly: repeats for variance, intervals for uncertainty, paired (McNemar) comparisons for "did B beat A" — small dev sets can't detect small wins.
- Diagnose by class: contract vs instruction vs comprehension vs knowledge vs reasoning vs context vs capability failures have different owners; the symptom → cause → fix table routes you to the cheapest correct layer — which is often not the prompt.
- Regression is a suite, not a hope: golden cases + assertions + snapshots + canaries, run on every change and every model bump.
- Porting is a checklist, not a copy-paste: freeze the artefact, baseline on target, adapt form not contract, re-earn the wording per model, log the port.
- LLM-in-the-loop amplifies your eval: critics, tournaments and DSPy/GEPA are force multipliers for a good dev set — and overfitting engines for a bad one.
- Cost is a prompt property: shorter prompts, cache-friendly order, smaller models with better prompts, output caps and batching all compound.
- Production debugging closes the loop: log prompt version + model snapshot + score, sample failures, feed confirmed failures back into the dev set, and treat every incident as a new canary case.
Terms introduced in this lesson#
| Term | Meaning |
|---|---|
| Dev set | A small fixed set of labelled cases used to iterate a prompt against |
| Hold-out set | Labelled cases never used during iteration, reserved to detect overfitting |
| Golden set | The dev set frozen at ship time and promoted into the regression suite |
| Regression suite | Golden cases + scorers/assertions + snapshots run as a gate on every prompt or model change |
| Canary case/prompt | A small set of high-value cases run on every change and watched in production-like conditions |
| Prompt changelog | An append-only record of prompt versions: what changed, why, and the dev score before/after |
| Prompt hash | A short hash of the exact prompt text, used to prove which version produced a result |
| Scorer | A function mapping (case, output) to a score in [0,1]; the executable definition of success |
| ModelFn | The callable seam (system, prompt, case) -> str that lets one harness drive fake, provider or replay models |
| Paired comparison | Comparing two prompt versions on the same cases, which controls for case difficulty |
| McNemar's test | Exact test on discordant pass/fail pairs between two paired versions |
| Wilson interval | A confidence interval for a pass rate that stays honest at small n |
| Trace sampling | Logging all failures plus a random sample of successes for production prompt debugging |
| Prompt porting / migration | Adapting a prompt across models or providers while preserving its contract |
| Prompt optimiser | A tool that searches prompt variants against a metric (DSPy/GEPA, TextGrad, vendor tools) |
| DSPy | Framework for programming (not prompting) LM pipelines; ships GEPA/MIPROv2/BootstrapFewShot optimisers |
| GEPA | DSPy's reflective prompt optimizer: mutates instructions from execution-trace feedback on a Pareto frontier |
| Reflection LM | The LM an optimizer uses to critique traces and propose prompt revisions |
| Textual gradient | TextGrad's natural-language critique treated as a gradient for rewriting text variables |
| Ablation | Removing one prompt/context element at a time and measuring the effect |
| Model ladder | Developing on a cheap model, verifying on the production model, possibly downgrading production |
| Snapshot diff | Comparing recorded per-case outputs between two runs to see what a change actually did |
| Echo-back check | Asking the model to restate the task before answering, to separate comprehension from reasoning failures |
| Shadow traffic | Running a new prompt on real requests without serving its output, for zero-risk measurement |
All terms are also collected in the glossary.
Exercises#
- The loop by hand (1.3–1.5): run
s1_dev_loop.py, then write aPROMPT_V5that fixes the h05 multilingual failure (e.g. an explicit "tickets may be in any language; classify by meaning" rule). Run it on dev and hold-out. Did the dev score move? Did hold-out? What does that tell you about rule-stacking? - Statistics (1.4, 1.7): run the dev set with
repeats=5on the fake model — identical outputs, so the intervals collapse. Now write aNoisyTriagerwrapper that randomly flips the urgency label 20% of the time (seededrandom.Random). Compare v3 vs v4 withrepeats=5: does McNemar still call the one-case difference noise? At what discordant count does it turn significant? - Diagnosis (2.2): take three new failing outputs you invent for the triage task and classify each by the failure taxonomy — which layer owns the fix?
- Regression gate (3.3): modify
PROMPT_V4trivially (change "support triage assistant" to "customer triage assistant") and runs3_regression.py. Which gate fires — score, snapshot, or critical? What does that tell you about which check catches wording-only changes? - Porting (4.3): pick one provider pair (e.g. OpenAI→Anthropic) and walk the migration checklist on the triage prompt. Which steps change the form vs the contract?
- LLM-in-the-loop (5.1): implement
llm_criticas a realModelFn(any provider fromcall_llm.py) using gallery prompt G3. Feed it the v2 failures and inspect the proposed prompt — does it preserve the output contract? - Cost (6.1): ablate
PROMPT_V4— remove one block at a time (each urgency rule, the negation rule, the primary-issue rule, theCATEGORIESline) — and find the smallest prompt that still scores ≥0.95 on dev and hold-out. - Production logging (7.1): extend
CallLogger(write it: wrap aModelFn, emit the JSON fields listed in 7.1) and add trace sampling — 100% of scorer failures, 5% of successes. Test it againstFakeTriageron the dev set. - Anti-patterns (Part 8): take a real prompt from your own project (or invent one) and score it against the anti-pattern table — which patterns does it commit?
- Case study (Part 9): reproduce case study B's fix on a different extraction task (e.g. resume parsing): write the broken prompt, the three-layer fix, and the new dev cases.
Hints. (1) A rule written for French may fix h05 but the fake model's keyword machinery is English-only, so expect the score not to move — that is the lesson: some gaps are not prompt gaps. (2) Seed the wrapper (random.Random(7)) so your own run is reproducible; read mcnemar_b and mcnemar_c from the Comparison — noise turns some per-case means below the pass threshold, so the discordant count changes — and compare it with the rule of thumb of about six discordant cases on one side for p < 0.05. (3) Ask first which layer could have prevented the failure: prompt, context, schema, tools or model. (4) Predict first: the fake model reacts to instruction keywords, not to the role sentence, so its outputs stay identical and none of the three gates should fire. Then ask what you would have to compare (the prompt_hash stored in the snapshot) to notice a wording-only edit at all. (5) Step 3 (mechanics) is where most ports break; steps 4 and 6 change only the form. (6) Validate the critic's reply with "| urgency" in reply or similar before running it. (7) Cut a block, re-run dev and hold-out, restore it if either drops. (8) Wrap ModelFn as a function returning a function; write one JSON line per call. (9) Count only patterns you can point to in the text. (10) The key move is a nullable schema plus a grounding check, not only a stronger instruction.
Check yourself#
- What three things does Anthropic's prompt-engineering overview say you need before prompt engineering?A clear definition of success criteria, ways to empirically test against them, and a first-draft prompt to improve — in that order.
- Why is a dev set of 12 cases unable to prove that a one-case improvement is real?One flipped case is a single discordant pair; the exact two-sided p-value only drops under 0.05 once about six discordant cases all favour one side, so small sets can't distinguish signal from noise.
- What does McNemar's test actually compare, and why are concordant cases ignored?It compares the discordant pairs — cases where exactly one of the two versions passed — because concordant cases carry no information about which version is better; under the null they split 50/50.
- A prompt scores 0.95 on dev but 0.60 on hold-out. What are the two most likely explanations and what do you do?Either the prompt memorised dev-set specifics (rules naming test cases, leaked examples) or the dev set isn't representative of real inputs; re-generalise the rules and refresh the dev set from production failures.
- Your model ignores a format instruction that "obviously" applies. Name three causes in order of likelihood and the fix for each.Conflicting instructions; too many constraints (compliance degrades with count); negative phrasing or instruction buried far from the data — resolve the conflict, reduce constraints, restate positively near the input.
- When is fine-tuning the right fix for a prompt failure, and when is it the wrong one?Right when you have hundreds of labelled examples and a measured gap no prompt/context/schema/tool closes; wrong as a first response — it costs money, freezes knowledge and still needs evals.
- What is the difference between an assertion, a snapshot and a canary case in a regression suite?Assertions check properties (parse, membership, thresholds) and survive wording changes; snapshots check exact output identity and are brittle but catch invariant drift; canaries are a few high-value cases watched continuously in production-like conditions.
- Why must a prompt version and a model snapshot be recorded together?Because a prompt's behaviour is a function of (prompt text, model weights); "v4 scored 0.958" is meaningless without knowing which snapshot produced it, and providers alias moving snapshots.
- Name two verified facts about provider prompt tooling as of November 2026 that should change how you build your iteration workflow.OpenAI's dataset-backed prompt optimiser is deprecated with Evals (shutdown Nov 30 2026) and
v1/promptsreusable objects are also shutting down; Anthropic's prompt improver and experimental prompt APIs were retired Aug 17 2026 with no saved-prompt/eval replacement in Playground. - What are the four protections against overfitting in an LLM-in-the-loop optimiser?A hold-out set the optimiser never sees; a no-regression constraint per case (not just aggregate); limited candidate count / selection pressure; human review of the winning diff before shipping.
- Why does putting
{input}last in a prompt save money, and which lesson owns the full caching mechanics? - What are the three cadences for running a prompt regression suite, and what does each catch that the others can't?Every PR without keys (fake/replay — catches prompt-text accidents), on merge/nightly with keys on the small golden set (catches real model regressions), and on model-version bumps before switching pins (catches snapshot drift).
- In production debugging, why do you log
prompt_hashandmodel_snapshotrather than just the prompt name?Because names are reused across edits; the hash proves exactly which text produced a logged output, and the snapshot proves which weights — together they make a production failure reproducible offline. - Which anti-pattern does "here's everything we have, figure it out" commit, and what's the fix?Unbounded context / prompt-as-database — cramming reference data into the prompt; the fix is retrieval or tools for data and prompts for behaviour (04.6).
Further resources#
- OpenAI, Prompt engineering guide and Prompting guide: pin snapshots, build eval suites, treat prompts as code.
- OpenAI, Prompt optimizer: the dashboard optimiser and its deprecation timeline; the deprecations page tracks
v1/promptsand Evals shutdowns. - Anthropic, Prompt engineering overview and Prompting best practices: success criteria first; per-model guidance.
- Anthropic, Claude Platform release notes: Workbench retirement, Playground, experimental prompt-API shutdowns.
- Google, Prompting strategies and the Gemini 3 prompting guide; Vertex AI prompt optimizers: zero-shot, few-shot, and the Studio prompt assistant.
- DSPy, GEPA optimizer docs and GEPA paper (arXiv:2507.19457); TextGrad.
- promptfoo: open-source prompt evals and red-teaming (MIT licensed; OpenAI announced its acquisition on 9 March 2026 and, as of November 2026, the repository README says it is now part of OpenAI and remains open source).
- Module 03: 03.10 debugging and testing, 03.7 cost and caching, 03.9 async and batch, 03.11 provider-agnostic client.
- Module 02: 02.5 determinism, 02.7 context windows, 02.8 reasoning models, 02.9 model landscape, 02.10 failure modes.
- Module 10A (evaluation) and Modules 11A to 11C (production and LLMOps) for the full eval and deployment stack this lesson previews.
← 04.8 — Prompt Patterns for Common Tasks | Module 04 overview | 04.10 — Prompt Templates, Versioning and a Prompt Library →