Learning path: Prompt and Context Engineering · Step 6 of 8
Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
Treat prompts like code: one file per version, a registry.json that names the live one, a hash logged with every answer, a 12-ticket golden set (v1 0/12, v2 12/12) and 8 pytest tests that catch a careless label edit before review.
What you will learn
- Keep each prompt version in its own file and name the live one in a registry
- Log a short hash of the prompt with every answer
- Score every version on a golden set and review the change as a diff
- Catch a careless prompt edit with millisecond prompt-file tests and a 90% gate
Before you start
- Few-Shot Prompting Done Right
- Basic pytest
- Basic git
Most prompts live as one string inside a Python file, edited in place. Nobody can see when it changed, or why, or which version wrote last week's good answers. In this article we treat prompts the way we treat code: files in a repo, with diffs, tests and review.
The example is a small help desk that sorts support tickets into four labels: billing, bug, feature and other. The code runs with a stand-in test model, so you can run all of it without a key. Set your model and key in .env and the same code calls a real model.
A sticky note, or a recipe book
Picture a family recipe on a sticky note. People change it with a pencil. There's no date and no copy. When dinner tasted great last week, nobody knows which version made it. That is how most prompts live.
A recipe book does four things differently:
- File: each version is a file of its own.
- Diff: you can see exactly what changed.
- Test: a test tells you if the new version is better.
- Review: someone else checks it before it goes live.
Prompts live in files
The project is laid out like this:
prompts/
registry.json
classify_ticket/
v1.txt
v2.txt
CHANGELOG.md
app/
prompts.py load a prompt by name and version
model.py stand-in test model, or a real one from .env
classifier.py classify one ticket, parse the label strictly
evals/
golden.jsonl 12 tickets with the right label
run_evals.py
tests/
test_prompts.py
test_evals.py
The loader in app/prompts.py is small on purpose:
import hashlib
import json
from dataclasses import dataclass
from pathlib import Path
PROMPTS = Path(__file__).resolve().parent.parent / "prompts"
@dataclass(frozen=True)
class Prompt:
name: str
version: str
text: str
@property
def sha(self) -> str:
"""Short content hash: log it with every call so you know which prompt produced an answer."""
return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:8]
def render(self, **values: str) -> str:
return self.text.format(**values)
def live_version(name: str) -> str:
return json.loads((PROMPTS / "registry.json").read_text(encoding="utf-8"))[name]
def load_prompt(name: str, version: str | None = None) -> Prompt:
version = version or live_version(name)
text = (PROMPTS / name / f"{version}.txt").read_text(encoding="utf-8")
return Prompt(name, version, text)
- sha is a short hash of the prompt text. Log it with every answer and you can always tell which prompt produced it.
- registry.json names the live version of each prompt.
- load_prompt uses the live version when you don't ask for one.
- Each version is a plain text file:
prompts/<name>/<version>.txt. Nothing clever, and that is the point.
v1 gives a sentence, not a label
Most teams start here. Version one is a single line, with no labels and no output format:
Classify this support ticket:
{ticket}
Our code needs a label it can use, so the parser in app/classifier.py is strict. The reply must be exactly one of the four labels; anything else becomes None:
LABELS = ("billing", "bug", "feature", "other")
def parse_label(reply: str) -> str | None:
word = reply.strip().lower().rstrip(".")
return word if word in LABELS else None
def classify(ticket: str, version: str | None = None, model=None) -> Result:
prompt = load_prompt("classify_ticket", version)
reply = (model or get_model()).invoke(prompt.render(ticket=ticket)).content
return Result(parse_label(reply), reply, prompt.version, prompt.sha)
Ask it about a card charged twice:
python demo.py ask
ticket : My card was charged twice for one order.
label : None
prompt : classify_ticket v1 (80c99f45)
The model answered in a friendly sentence, so the label is None. The prompt version and its hash are printed too.
Score every version on a golden set
One ticket is a vibe. We want a number. The project has a golden set: twelve tickets in evals/golden.jsonl, three per label, each with the right answer.
{"ticket": "I was charged twice for order 4417.", "label": "billing"}
{"ticket": "The checkout page is blank after I press Pay.", "label": "bug"}
{"ticket": "Could you add dark mode to the app?", "label": "feature"}
{"ticket": "hello?", "label": "other"}
(Four of the twelve lines.) This set is only for testing; none of it goes into the prompt. How to build a bigger one, with a schema and coverage checks, is in Building a Golden Dataset for LLM Evals.
python demo.py evals runs every version over all twelve:
python demo.py evals
classify_ticket v1 (80c99f45): 0/12 correct
expected billing got None reply: This looks like a billing issue. Let me know if
expected billing got None reply: This looks like a billing issue. Let me know if
expected billing got None reply: This looks like a billing issue. Let me know if
... and 9 more
classify_ticket v2 (5556148f): 12/12 correct
Version one gets zero out of twelve: every reply is a sentence, so nothing can be parsed. Version two, which we look at next, gets twelve out of twelve. Twelve tickets with the right answer, written once, and now every change gets a score.
v2 is a new file, not an edit
Version two sits next to version one in prompts/classify_ticket/v2.txt. We did not edit the old file.
You sort support tickets for an online shop.
Labels: billing, bug, feature, other
Reply with the label only, in lower case.
Ticket: I was charged twice this month.
Label: billing
Ticket: The export button spins forever, I need my invoice.
Label: bug
Ticket: hi
Label: other
Ticket: Can you email me invoices every month?
Label: feature
Ticket: {ticket}
Label:
- One line lists the four labels the code accepts.
- "Reply with the label only, in lower case" gives the parser something it can read.
- Four examples: an easy one, a hard one, an edge case ("hi") and a near miss that mentions an invoice but asks for a feature. Why those four is in Few-Shot Prompting Done Right.
- One slot for the ticket at the end.
A diff for the prompt, one line to go live
Now the review. python demo.py diff shows exactly what changed between v1 and v2. This is what a reviewer reads in a pull request:
python demo.py diff
--- v1.txt
+++ v2.txt
@@ -1,3 +1,15 @@
-Classify this support ticket:
+You sort support tickets for an online shop.
+Labels: billing, bug, feature, other
+Reply with the label only, in lower case.
-{ticket}
+Ticket: I was charged twice this month.
+Label: billing
+Ticket: The export button spins forever, I need my invoice.
+Label: bug
+Ticket: hi
+Label: other
+Ticket: Can you email me invoices every month?
+Label: feature
+
+Ticket: {ticket}
+Label:
Going live is one line in registry.json:
git diff prompts/registry.json
@@ -1,3 +1,3 @@
{
- "classify_ticket": "v1"
+ "classify_ticket": "v2"
}
Ask the same ticket again:
ticket : My card was charged twice for one order.
label : billing
prompt : classify_ticket v2 (5556148f)
The label is now billing, and the answer carries v2 and its hash, so every log line says which prompt wrote it. Next to the files, a CHANGELOG.md says in plain words what v2 changed and why.
A test decides, not a feeling
Before anything goes live, a test decides. tests/test_evals.py holds the quality gate:
from app.model import StandInModel
from app.prompts import live_version
from evals.run_evals import GOLDEN, evaluate
def test_golden_set_covers_every_label():
assert {c["label"] for c in GOLDEN} == {"billing", "bug", "feature", "other"}
def test_live_prompt_passes_the_gate():
res = evaluate(live_version("classify_ticket"), StandInModel())
assert res["accuracy"] >= 0.9, f"{res['correct']}/{res['total']} correct"
The first test checks that the golden set covers all four labels. The second is the gate: the live prompt must get at least 90% of the golden tickets right, or the test fails.
tests/test_prompts.py checks the prompt files themselves. They take milliseconds and need no model:
import re
import pytest
from app.classifier import LABELS
from app.prompts import live_version, load_prompt, versions
ALL = versions("classify_ticket")
def test_live_version_exists():
assert live_version("classify_ticket") in ALL
@pytest.mark.parametrize("version", ALL)
def test_has_exactly_one_ticket_slot(version):
assert re.findall(r"\{(\w+)\}", load_prompt("classify_ticket", version).text) == ["ticket"]
def test_live_prompt_lists_the_labels_the_code_accepts():
text = load_prompt("classify_ticket").text
line = next(l for l in text.splitlines() if l.startswith("Labels:"))
assert tuple(x.strip() for x in line.removeprefix("Labels:").split(",")) == LABELS
def test_live_prompt_asks_for_a_parseable_reply():
assert "label only" in load_prompt("classify_ticket").text.lower()
def test_examples_use_known_labels():
text = load_prompt("classify_ticket").text
assert set(re.findall(r"^Label: (\w+)$", text, re.M)) <= set(LABELS)
That is five test functions, and the ticket-slot test runs once per version (v1 and v2), so six tests here plus two in the gate file. Run them all:
python -m pytest -q
........ [100%]
8 passed in 0.33s
Eight passed, in well under a second. Then commit the prompt, the registry and the changelog together:
git log --oneline
18f3fa5 classify_ticket v2: labels, label only, 4 examples (12/12)
ec82b61 classify_ticket v1
Break it: the test catches a bad edit
Someone adds refund to the labels line. It looks harmless.
git diff -U0 prompts
-Labels: billing, bug, feature, other
+Labels: billing, bug, feature, refund, other
python -m pytest -q --tb=line
At index 3 diff: 'refund' != 'other'
FAILED tests/test_prompts.py::test_live_prompt_lists_the_labels_the_code_accepts
1 failed, 7 passed in 0.31s
The labels line of the live prompt must match the labels the code accepts, and it doesn't. The message points at index 3: refund instead of other. Without this test, the model could start replying "refund", and the parser would quietly turn every one of those into None. The test stopped it before any model call and before review.
Undo it with git and you're back to green:
git checkout -- prompts
python -m pytest -q
8 passed in 0.13s
The same habits, for prompts
| Habit | For code | For prompts |
|---|---|---|
| Version | A file in git | prompts/<name>/v2.txt plus registry.json |
| Review | A diff in a pull request | demo.py diff and the changelog |
| Test | Unit tests | Prompt-file tests: milliseconds, no model |
| Gate | CI must pass | Golden set: at least 90% before it goes live |
| Trace | A version in the logs | The prompt hash with every answer |
None of this needs a new tool. Files, git and pytest are enough. To run these tests on every pull request in GitHub Actions, and to grade saved answers from a real model, see Regression Testing an LLM Bot in CI.
Try it yourself
- Add a
v3.txtwith one more example and runpython demo.py evals. - Add two tickets to
evals/golden.jsonlthat v2 gets wrong. - Break the
{ticket}slot in v2 and see which test fails.
Related course on Udemy
Become an AI Engineer: LLMs, RAG, Agents and MCP
Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)Related posts
The AI Stack in One Picture: Six Layers Every AI Product Is Built From
Every AI product is built from six layers: data, model, retrieval, orchestration, serving and ops, with evals and security across all of them. A restaurant analogy, one request traced through all six, and what an AI engineer actually builds around the model call.
Tokenization: What an LLM Actually Sees When You Type
A language model never sees letters, only token ids. Use tiktoken to watch strawberry become three ids, see a space or a capital change them, fix the letter-counting problem, and compare English, German and Hindi token counts.
LLM Tokens, Context Windows and Cost: What One Question Really Costs
Follow one four-word help desk question that becomes 911 input tokens. Learn what fills the context window, why chat memory grows every turn, how max_tokens cuts a reply, and how to price a call.
What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
A large language model predicts the next token, over and over. That one loop makes it strong at drafting, summarising and classifying, and weak at fresh facts, exact maths, memory and guaranteed truth. See why with a three-line tiktoken script, and learn the fix for each gap.