Chapter 5 · Security and Operations
Prompt Operations: Owners, Versions, Acceptance Criteria and Rollback
- Page 21 of 24
- 19 min read
A prompt that matters to a product becomes an asset: other people depend on it, it changes over time, and a change can quietly make things worse. Git, APIs and Backend for AI: Advanced showed how a backend tracks which prompt and model version produced an answer; this page does not repeat that. It follows the prompt asset through its life: who owns it, how versions are named and explained, what "better" means before you edit, how a change is compared with the last one, and how to undo it.
You build a small toolkit, promptops.py, for one invented asset: a ticket-triage prompt that labels support tickets billing, bug or other. You need Python 3.12+ and promptlab.py in your folder. Blocks whose first line says file: are files you create; the other blocks run in order and share variables. The only "model" is a toy provider, a deterministic stand-in so the toolkit can be tested repeatably. Real models are less predictable, which is why you test; toy results say nothing about them.
What you will learn
- How to define a prompt asset with an owner, store it apart from experiment outputs, and give each version a readable identifier and a recorded reason.
- How to keep test inputs and acceptance criteria with the prompt, and write the criteria before you edit.
- How to compare a change with the previous version on a fixed regression set, and accept or reject it by the criteria.
- How to record assumptions, quality by language and use case, and the latency and cost trade-off of each version.
The toolkit in one file
Create this module first; each section uses a part of it. The toy provider inside is a stand-in: it reads only the languages the prompt names and breaks ties as the prompt says, so a prompt edit visibly changes its answers.
# file: promptops.py
"""promptops: a tiny prompt registry (prompts/registry.json plus prompts/<name>/ files)."""
import difflib, hashlib, json
from pathlib import Path
from promptlab import Client, estimate_tokens, render
ROOT = Path("prompts")
PRICE_PER_1K_TOKENS = 1.0 # placeholder units, not a real price
def _read(path):
return json.loads(Path(path).read_text(encoding="utf-8"))
def _save(reg):
text = json.dumps(reg, indent=1, sort_keys=True, ensure_ascii=False)
(ROOT / "registry.json").write_text(text + "\n", encoding="utf-8")
def load(name, version=None):
"""Prompt text plus metadata; no version means the 'current' pointer."""
asset = _read(ROOT / "registry.json")[name]
version = version or asset["current"]
entry = asset["versions"][version]
return {"version": version, "entry": entry, "asset": asset,
"text": (ROOT / name / entry["file"]).read_text(encoding="utf-8")}
def lint(name):
"""What a teammate needs before touching an asset. Empty list = complete."""
asset, folder = _read(ROOT / "registry.json").get(name, {}), ROOT / name
problems = [f"no {key}" for key in ("purpose", "owner", "assumptions", "current") if not asset.get(key)]
problems += [f"missing file {f}" for f in ("cases.json", "criteria.json") if not (folder / f).exists()]
entry = asset.get("versions", {}).get(asset.get("current"))
if entry is None or not (folder / entry["file"]).exists():
problems.append("the current version has no file")
return problems
def next_version(name, breaking=False):
major, minor = max(tuple(int(n) for n in v[1:].split(".")) for v in load(name)["asset"]["versions"])
return f"v{major + 1}.0" if breaking else f"v{major}.{minor + 1}"
def add_version(name, text, reason, date, breaking=False):
"""Write the next version file and register it; no reason, no version."""
if not reason.strip():
raise ValueError("a new version needs a change reason")
reg, version = _read(ROOT / "registry.json"), next_version(name, breaking)
(ROOT / name / f"{version}.txt").write_text(text, encoding="utf-8")
reg[name]["versions"][version] = {"file": f"{version}.txt", "reason": reason, "date": date, "status": "candidate"}
_save(reg)
return version
def set_status(name, version, status):
reg = _read(ROOT / "registry.json")
reg[name]["versions"][version]["status"] = status
_save(reg)
def set_current(name, version, date, why):
"""Move the pointer (files never change) and record the move."""
reg = _read(ROOT / "registry.json")
asset = reg[name]
asset.setdefault("pointer_history", []).append(
{"from": asset["current"], "to": version, "date": date, "why": why})
asset["current"] = version
asset["versions"][version]["status"] = "released"
_save(reg)
def diff(name, a, b):
old, new = (load(name, v)["text"].splitlines() for v in (a, b))
return "\n".join(difflib.unified_diff(old, new, a, b, lineterm="", n=0))
KEYWORDS = {"en": {"billing": ("charged", "invoice", "refund"), "bug": ("crash", "error")},
"es": {"billing": ("cobr", "factura"), "bug": ("falla", "falló", "error")},
"bn": {"billing": ("চার্জ",), "bug": ("ক্র্যাশ",)}}
LANGUAGES = {"en": "English", "es": "Spanish", "bn": "Bangla"}
def toy_triage(messages, **settings):
"""STAND-IN, not a model: reads only the languages the prompt names; breaks ties as told.
Planted weakness: without the context line, it loses tickets longer than 12 words."""
rules, ticket = messages[-1]["content"].split("Ticket:\n", 1)
if "software shop" not in rules and len(ticket.split()) > 12:
return "other"
langs = [code for code, word in LANGUAGES.items() if word in rules]
hits = [label for label in ("billing", "bug")
if any(w in ticket.lower() for c in langs for w in KEYWORDS[c][label])]
if len(hits) > 1 and "choose bug" in rules:
return "bug"
return hits[0] if hits else "other"
def run_set(name, version, provider=toy_triage, text=None):
"""Run the fixed regression set. `text` tries an unsaved draft instead."""
raw = (ROOT / name / "cases.json").read_bytes()
prompt, cases = text or load(name, version)["text"], json.loads(raw)
client, rows = Client(provider, model="toy"), []
for c in cases:
reply = client.complete([{"role": "user", "content": render(prompt, ticket=c["ticket"])}])
rows.append({**{k: c[k] for k in ("id", "language", "use_case")}, "ok": reply.text.strip() == c["expected"],
"tokens": reply.usage.input_tokens, "ms": reply.latency_ms})
def by(key):
groups = {}
for r in rows:
groups.setdefault(r[key], []).append(r["ok"])
return {k: round(sum(v) / len(v), 2) for k, v in sorted(groups.items())}
n, tokens = len(rows), sum(r["tokens"] for r in rows) / len(rows)
report = {"name": name, "version": version, "cases": hashlib.sha256(raw).hexdigest()[:8],
"accuracy": round(sum(r["ok"] for r in rows) / n, 3), "by_language": by("language"),
"by_use_case": by("use_case"), "failed": [r["id"] for r in rows if not r["ok"]],
"mean_input_tokens": round(tokens, 1), "mean_latency_ms": round(sum(r["ms"] for r in rows) / n, 1),
"cost_per_1000_calls": round(tokens * PRICE_PER_1K_TOKENS, 1)}
if version: # experiment output goes to runs/, never to prompts/
out = Path("runs") / name
out.mkdir(parents=True, exist_ok=True)
(out / f"{version}.json").write_text(json.dumps(report, indent=1, sort_keys=True) + "\n")
return report
def check(report, baseline, criteria):
"""Judge a run by criteria written BEFORE the edit. Empty list = accepted."""
if baseline["cases"] != report["cases"]:
return [f"different case set ({baseline['cases']} vs {report['cases']}): results are not comparable"]
problems = []
if report["accuracy"] < criteria["min_accuracy"]:
problems.append(f"accuracy {report['accuracy']} is below {criteria['min_accuracy']}")
for lang, acc in report["by_language"].items():
if acc < criteria["min_accuracy_per_language"]:
problems.append(f"{lang} accuracy {acc} is below {criteria['min_accuracy_per_language']}")
new = sorted(set(report["failed"]) - set(baseline["failed"]))
if len(new) > criteria["max_new_failures"]:
problems.append(f"new failures: {new}")
if report["mean_input_tokens"] > criteria["max_mean_input_tokens"]:
problems.append(f"mean input {report['mean_input_tokens']} tokens is above {criteria['max_mean_input_tokens']}")
return problemsDefine a prompt asset and its owner
A prompt becomes an asset when someone depends on it. Then it needs more than its text. The registry file records the facts a teammate needs before touching it:
| Part | Where it lives | Why |
|---|---|---|
| Prompt text, one file per version | prompts/ticket-triage/v1.0.txt | The thing that ships |
| Purpose, owner, reviewer, assumptions | registry.json | A named person decides and answers questions |
| Representative test inputs | cases.json | Evidence beside the text |
| Acceptance criteria | criteria.json | What "better" means |
The owner is a named person who accepts or rejects changes, not a team alias nobody reads; the reviewer is a second pair of eyes. Start with the registry and the first version:
// file: prompts/registry.json
{
"ticket-triage": {
"purpose": "Label an incoming support ticket as billing, bug or other, so it reaches the right queue.",
"owner": "Nadia Rahman, support tools team (Dhaka)",
"reviewer": "Mateo Silva, support operations (Bogotá)",
"current": "v1.0",
"assumptions": {
"model": "any chat model that follows a one-word output instruction (a toy stand-in in this tutorial)",
"provider": "none here; write your provider and model name, and the date you checked them",
"settings": "default sampling settings; the reply is one word",
"input": "one ticket, up to a few hundred words, in English, Spanish or Bangla"
},
"versions": {
"v1.0": {"file": "v1.0.txt", "reason": "First release: labels only.", "date": "2026-09-01", "status": "released"}
}
}
}# file: prompts/ticket-triage/v1.0.txt
You label customer support tickets for a software shop.
Tickets are written in English.
Labels: billing, bug, other.
Reply with the label only.
Ticket:
{ticket}The asset is incomplete on purpose; lint says what is missing.
from promptops import *
print(lint("ticket-triage"))['missing file cases.json', 'missing file criteria.json']Store prompts apart from experiment outputs
Replies, logs and scores pile up fast. Keep two places with two rules:
prompts/ small, reviewed; every change has a reason
registry.json owner, purpose, assumptions, versions, pointer
ticket-triage/
v1.0.txt v1.1.txt one file per version; released files never change
cases.json criteria.json
runs/ outputs: many, regenerated, safe to delete
ticket-triage/v1.0.json one report per run (run_set writes it)Everything in prompts/ is reviewed by a person. Everything in runs/ can be rebuilt by running the set again, so it normally stays out of version control. Mixing them hides the prompt change among dozens of output files. The backend side of this (which version served which request) is in Git, APIs and Backend for AI: Advanced.
Give each version a readable identifier and a reason
An identifier must tell a human what kind of change this is. One scheme that works; avoid names like final2:
| Change | Identifier | Example |
|---|---|---|
| Wording or rules; same output format and variables | Minor: v1.1, v1.2 | Add a tie rule |
| Output format, labels or variables change, so callers must change | Major: v2.0 | Reply as JSON instead of one word |
The rule that keeps the system honest: an identifier changes only when the text changes, and a released file never changes. Each version also records why it exists. The diff shows what changed; only the reason says why. add_version picks the next identifier and refuses an empty reason. Here is the first real edit. Nadia's team found that Spanish and Bangla tickets were labelled other and that a mixed ticket went to billing, so the new prompt names all three languages and adds a tie rule.
V11 = """You label customer support tickets for a software shop.
Tickets may be written in English, Spanish or Bangla.
Labels: billing, bug, other.
If a ticket fits more than one label, choose bug.
Reply with the label only.
Ticket:
{ticket}
"""
reason = "Spanish and Bangla tickets were labelled other; mixed tickets went to billing."
print(add_version("ticket-triage", V11, reason, "2026-09-14"))
print(diff("ticket-triage", "v1.0", "v1.1"))
try:
add_version("ticket-triage", V11, " ", "2026-09-14")
except ValueError as exc:
print("refused:", exc)v1.1
--- v1.0
+++ v1.1
@@ -2 +2 @@
-Tickets are written in English.
+Tickets may be written in English, Spanish or Bangla.
@@ -3,0 +4 @@
+If a ticket fits more than one label, choose bug.
refused: a new version needs a change reasonThe refusal shows the habit enforced by code. The new version is a candidate: the current pointer still names v1.0.
Keep representative test inputs with each prompt
A version is only as trustworthy as the inputs it was tried on. cases.json lives in the prompt's folder, so whoever changes the prompt sees the evidence. Cover every language you support, every label and the awkward mixed tickets; real sets are larger. Invent or anonymise the text; Team Handover: Prompt Libraries, Change Logs, Handover Documents and Readiness returns to personal data.
// file: prompts/ticket-triage/cases.json
[
{"id": "en-billing", "language": "en", "use_case": "billing", "expected": "billing", "ticket": "I was charged twice for my March invoice."},
{"id": "en-bug", "language": "en", "use_case": "bug", "expected": "bug", "ticket": "The app crashes when I upload a photo."},
{"id": "en-other", "language": "en", "use_case": "other", "expected": "other", "ticket": "How do I change my account email?"},
{"id": "en-mixed", "language": "en", "use_case": "mixed", "expected": "bug", "ticket": "Charged twice and then the app crashed."},
{"id": "es-billing", "language": "es", "use_case": "billing", "expected": "billing", "ticket": "Me cobraron dos veces la factura de marzo."},
{"id": "es-bug", "language": "es", "use_case": "bug", "expected": "bug", "ticket": "La aplicación falla al subir una foto."},
{"id": "es-other", "language": "es", "use_case": "other", "expected": "other", "ticket": "¿Cómo cambio mi correo?"},
{"id": "es-mixed", "language": "es", "use_case": "mixed", "expected": "bug", "ticket": "Me cobraron dos veces y luego la app falló."},
{"id": "bn-billing", "language": "bn", "use_case": "billing", "expected": "billing", "ticket": "আমার কার্ডে দুইবার চার্জ করা হয়েছে।"},
{"id": "bn-bug", "language": "bn", "use_case": "bug", "expected": "bug", "ticket": "অ্যাপটি বারবার বন্ধ হয়ে যায়।"},
{"id": "bn-other", "language": "bn", "use_case": "other", "expected": "other", "ticket": "আমার পাসওয়ার্ড কীভাবে বদলাব?"},
{"id": "bn-mixed", "language": "bn", "use_case": "mixed", "expected": "bug", "ticket": "দুইবার চার্জ হয়েছে আর অ্যাপ ক্র্যাশ করেছে।"}
]| Case | English gloss of the ticket |
|---|---|
es-billing | "They charged me twice for the March invoice." |
es-bug | "The application fails when uploading a photo." |
es-other | "How do I change my email?" |
es-mixed | "They charged me twice and then the app failed." |
bn-billing | "My card was charged twice." |
bn-bug | "The app keeps closing." |
bn-other | "How do I change my password?" |
bn-mixed | "I was charged twice and the app crashed." |
Define acceptance criteria before editing
Decide what "good enough" means before you see the new results; afterwards almost any result can be explained as acceptable. Write criteria as numbers and let code apply them:
// file: prompts/ticket-triage/criteria.json
{"written_before": "v1.1", "min_accuracy": 0.85, "min_accuracy_per_language": 0.75,
"max_new_failures": 0, "max_mean_input_tokens": 70}min_accuracy_per_language: no language may be left behind, even if the average looks fine.max_new_failures: a case the previous version answered correctly must not start failing, even if the total improves.max_mean_input_tokens: a size budget, from the helper's rough estimate (one token per four characters): good for comparing versions, not for predicting a bill.
Now the asset is complete:
print(lint("ticket-triage") or "asset complete")asset completeCompare changes against a fixed regression set
A regression set is a fixed list of cases every candidate must pass. If the cases change between runs, a score change might come from the cases, not the prompt. run_set stores a short digest of cases.json in each report, and check refuses to compare reports with different digests. Run the baseline v1.0, then the candidate, and apply the criteria. A second candidate, v1.2, tries to save tokens by dropping the tie rule.
crit = json.loads(Path("prompts/ticket-triage/criteria.json").read_text())
r0 = run_set("ticket-triage", "v1.0")
r1 = run_set("ticket-triage", "v1.1")
V12 = V11.replace("If a ticket fits more than one label, choose bug.\n", "")
add_version("ticket-triage", V12, "Shorter prompt to cut input tokens.", "2026-09-20")
r2 = run_set("ticket-triage", "v1.2")
for r in (r0, r1, r2):
print(r["version"], r["accuracy"], r["failed"])
print("v1.1 against v1.0:", check(r1, r0, crit) or "accepted")
print("v1.2 against v1.1:", check(r2, r1, crit) or "accepted")v1.0 0.417 ['en-mixed', 'es-billing', 'es-bug', 'es-mixed', 'bn-billing', 'bn-bug', 'bn-mixed']
v1.1 0.917 ['bn-bug']
v1.2 0.667 ['en-mixed', 'es-mixed', 'bn-bug', 'bn-mixed']
v1.1 against v1.0: accepted
v1.2 against v1.1: ['accuracy 0.667 is below 0.85', 'bn accuracy 0.5 is below 0.75', "new failures: ['bn-mixed', 'en-mixed', 'es-mixed']"]Read it as a reviewer. v1.1 fixes six of the seven failures of v1.0 and breaks nothing; bn-bug still fails, now a known failure. v1.2 is cheaper but loses the three mixed tickets: it fails three criteria at once. The decision does not depend on who argues best. Release the first, mark the second rejected; only the pointer moves, and the rejected file stays. Rollback works the same way: move the pointer back to an earlier released version (the next page rehearses it).
set_current("ticket-triage", "v1.1", "2026-09-21", "Passed all criteria on the 12-case set.")
set_status("ticket-triage", "v1.2", "rejected")
asset = load("ticket-triage")["asset"]
print(asset["current"], {v: e["status"] for v, e in asset["versions"].items()})
print(asset["pointer_history"])v1.1 {'v1.0': 'released', 'v1.1': 'released', 'v1.2': 'rejected'}
[{'date': '2026-09-21', 'from': 'v1.0', 'to': 'v1.1', 'why': 'Passed all criteria on the 12-case set.'}]With a real model, one run per case is a weak signal; replies vary even at a low temperature. Repeat borderline cases, as Sampling and Reasoning Controls: Temperature, Top-p, Effort and Repeatability shows. The toy provider is deterministic, so one run is enough here.
Document model and provider assumptions
A prompt is written for a model, with certain settings, for a certain kind of input. When any of these changes, old test results stop being evidence. The assumptions block records the exact model name you tested, the provider, the settings that matter, the input (languages, length), the expected output and the date you checked, so a reviewer can find affected prompts when a provider announces a model change or retirement. Here the model is a stand-in and the entry says so; in your registry put real names.
Provider note (as of 2026-10-12): a prompt-registry or versioning feature at any provider was not confirmed in this tutorial's fact-check. Check whether your platform offers one, and what it versions (text only, or also model, settings and test data). Plain files work on any platform. Check the current documentation.
Track quality by language and use case
One accuracy number hides who is hurt. The report breaks results down by the language and use_case fields of each case:
for r in (r0, r1, r2):
print(r["version"], "language", r["by_language"], "use case", r["by_use_case"])v1.0 language {'bn': 0.25, 'en': 0.75, 'es': 0.25} use case {'billing': 0.33, 'bug': 0.33, 'mixed': 0.0, 'other': 1.0}
v1.1 language {'bn': 0.75, 'en': 1.0, 'es': 1.0} use case {'billing': 1.0, 'bug': 0.67, 'mixed': 1.0, 'other': 1.0}
v1.2 language {'bn': 0.5, 'en': 0.75, 'es': 0.75} use case {'billing': 1.0, 'bug': 0.67, 'mixed': 0.0, 'other': 1.0}Version v1.0 manages English (0.75) and fails Spanish and Bangla. Version v1.2 scores 0.667 overall but zero on mixed tickets. Neither fact is visible in the average. Two cautions. Four cases per language only demonstrate the method: one case moves a language by 0.25. And token counts differ by language: many non-Latin scripts need more tokens per sentence than English, so the helper's rough rule may understate the cost for scripts such as Bangla. Measure with your provider's own counter, per language.
Record latency and cost trade-offs
Every version has a price. Record it next to quality, so a trade-off is a visible decision. run_set keeps mean input tokens, mean latency and a cost figure using the placeholder PRICE_PER_1K_TOKENS; set it from your provider's current price sheet.
for r in (r0, r1, r2):
print(r["version"], r["accuracy"], r["mean_input_tokens"], r["mean_latency_ms"], r["cost_per_1000_calls"])v1.0 0.417 47.6 55.8 47.6
v1.1 0.917 65.6 56.2 65.6
v1.2 0.667 53.2 57.5 53.2The toy latency is the helper's fake number and depends on reply length, not the prompt, so it cannot show a real trade-off here; the cost column is a placeholder unit, not money. The table shows the shape of the decision: v1.1 costs roughly 40 percent more estimated input than v1.0 for a large quality gain, usually worth it; v1.2 saves about a fifth and gives up the mixed tickets, which is not. With a real model, run with real timing, and remember that output tokens and any hidden reasoning tokens also cost time and money (see Prompt Caching and Cost: Stable Prefixes, Usage Data and Estimates).
Where this shows up at work
Teams keep a registry like this beside the application and gate releases on a regression run. Newcomers read the owner, assumptions, criteria and last report first.
Common mistakes
- No named owner. Everyone may edit and nobody decides. Fix: one owner and one reviewer, recorded in the registry.
- Editing a released file. History becomes a guess. Fix: a new version with a reason; move the pointer.
- Setting criteria after seeing results. The numbers then justify whatever happened. Fix: commit
criteria.jsonbefore the edit. - Judging by the average. One language or case type can collapse while the total rises. Fix: report by language and use case; count new failures.
- Changing the test set and the prompt together. You cannot tell which moved the score. Fix: one change at a time; compare digests.
Try it yourself
- Easy. Register a second asset,
reply-draft, with only a purpose and a current versionv1.0, and runlinton it. Read what it reports. - Medium. Write
v1.3, shorter thanv1.1but keeping the three languages and the tie rule. Run it and compare it withv1.1by the criteria. - Hard. Add a thirteenth case (Spanish,
"Aparece un error al iniciar sesión.", "An error appears when signing in", expectedbug). Re-runv1.3and check it against the oldv1.1report. What happens, and what is the correct next step?
Answers
Easy. The report should name the missing owner, assumptions, the two files and the missing version file.
reg = json.loads(Path("prompts/registry.json").read_text(encoding="utf-8"))
reg["reply-draft"] = {"purpose": "Draft a reply to a customer.", "current": "v1.0"}
Path("prompts/registry.json").write_text(json.dumps(reg), encoding="utf-8")
print(lint("reply-draft"))['no owner', 'no assumptions', 'missing file cases.json', 'missing file criteria.json', 'the current version has no file']Pass checklist: each problem names what is missing; the fix is to fill it in, not to change lint.
Medium.
V13 = """You label customer support tickets for a software shop.
Tickets may be in English, Spanish or Bangla.
Labels: billing, bug, other. Mixed ticket: choose bug.
Reply with the label only.
Ticket:
{ticket}
"""
add_version("ticket-triage", V13, "Same behaviour as v1.1 in fewer tokens.", "2026-09-28")
r3 = run_set("ticket-triage", "v1.3")
print(r3["accuracy"], r3["failed"], r3["mean_input_tokens"])
print(check(r3, r1, crit) or "accepted")0.917 ['bn-bug'] 57.6
acceptedPass checklist: the version has a reason; it ran on the same fixed set; it was compared with the current version, not the oldest; "accepted" comes from the criteria.
Hard.
path = Path("prompts/ticket-triage/cases.json")
cases = json.loads(path.read_text(encoding="utf-8"))
cases.append({"id": "es-bug2", "language": "es", "use_case": "bug", "expected": "bug",
"ticket": "Aparece un error al iniciar sesión."})
path.write_text(json.dumps(cases, ensure_ascii=False, indent=1), encoding="utf-8")
r3b = run_set("ticket-triage", "v1.3")
print(check(r3b, r1, crit))
r1b = run_set("ticket-triage", "v1.1")
print(check(r3b, r1b, crit) or "accepted on the new set")['different case set (f125750a vs 80efc886): results are not comparable']
accepted on the new setPass checklist: check refuses because the digest changed; the next step is to re-run the baseline on the new set. Adding a case is legitimate, but it is a separate change from editing the prompt.
Summary
- A prompt asset has an owner, purpose, assumptions, test cases and criteria, stored with it.
- Keep reviewed prompts apart from regenerated experiment outputs.
- Identifiers describe the kind of change, released files never change, and every version records a reason.
- Write acceptance criteria before editing, then compare each candidate with the previous version on a fixed regression set.
- Report quality by language and use case, with latency and cost beside it; release by moving the
currentpointer.
Next: Team Handover: Prompt Libraries, Change Logs, Handover Documents and Readiness, where you add model variants, a review gate, rollback, a change log and a handover document.

