AI and machine learning · Intermediate · 22 min
Keep prompts in files and test them like code
By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · anthropic 2.14.0 · pytest 9.2.0 · PyYAML 6.0.4
You will move an LLM prompt out of a Python string into a versioned file, load it with a small module that logs the prompt version on every call, and guard changes with snapshot tests, a pytest regression set and a changelog entry.
On this page
A prompt written as a string literal inside a Python function changes whenever someone edits that function. Nobody reviews it as a prompt, no test notices, and when replies get worse a week later the logs cannot tell you which wording produced them. Treat the prompt like any other part of the code: give it a file, a version and an owner, test it, and record why it changed.
You will build this for a small ticket-triage feature for Greenbasket, a made-up online grocery shop. The model reads a customer message and returns a category and an urgency flag as JSON. By the end you have:
- a prompt file with front matter (
id,version,model,ownerand call settings) promptlib.py, which loads and checks prompt files and fills in their variables- a call that logs
triage-ticket@v1and a content hash with every request - snapshot tests that fail when a rendered prompt changes, and say whether you forgot to bump the version
- a regression set that runs in pytest against a local stub by default and against the real API when you ask for it
- a changelog entry for a prompt change
The tests need no API key and no network, so they can run on every pull request. That matters if you pay for data by the megabyte: the whole suite runs offline.
Step 1 · Create the project
Make a throwaway project and add the SDK, a YAML parser for the front matter, and pytest as a development dependency. The exact pins mean a new release cannot change behaviour under your tests:
mkdir -p ~/prompts-demo
cd ~/prompts-demo
uv init --no-package
uv add "anthropic==2.14.0" "pyyaml==6.0.4"
uv add --dev "pytest==9.2.0"
rm main.py
mkdir -p prompts tests/fixturesTell pytest to import modules from the project folder, where to find tests, and about a regression marker you will use later. This appends a new table to the pyproject.toml that uv init made:
cat >> pyproject.toml <<'TOML'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
markers = ["regression: runs prompt cases through the model (a stub unless PROMPT_TESTS_LIVE=1)"]
TOMLCheck it worked
uv run python -c "import anthropic, yaml; print(anthropic.__version__, yaml.__version__)"The output is 2.14.0 6.0.4.
Step 2 · Write the prompt as a file with front matter
Each prompt gets one Markdown file in prompts/, named after its id. The front matter says what the prompt is and how to call it. The body has a # system section and a # user section. Variables are written $name, Python's string.Template syntax. It was picked over str.format because the prompt contains JSON, and { and } would otherwise need escaping. A literal dollar sign is written $$.
cat > prompts/triage-ticket.md <<'MD'
---
id: triage-ticket
version: 1
model: claude-opus-5-5
owner: support-tools
max_tokens: 4000
effort: low
variables: [shop_name, ticket]
---
# system
You sort customer support messages for $shop_name, an online grocery shop.
Customers write in any language, including Nigerian Pidgin and French.
Reply with one JSON object and nothing else, with no code fence:
{"category": "<billing|delivery|account|other>", "urgent": <true|false>}
Categories:
- billing: charges, refunds, payment failures
- delivery: late, missing, damaged or spoiled items
- account: signing in, passwords, profile details
- other: anything else
Set urgent to true only when the customer cannot get food they paid for today,
or reports food that may be unsafe to eat.
# user
<ticket>
$ticket
</ticket>
MDWhat the fields are for:
idandversionname the exact wording. Bumpversionon every change to the text or the settings.model,max_tokensandefforttravel with the prompt, because a prompt tuned for one model and effort level is a different prompt on another. Claude Opus 5.5 always thinks before it answers, and thinking tokens count towardmax_tokens, so the limit is set well above the few tokens of JSON the reply needs.effort: lowkeeps that thinking short for a simple sorting task.owneris who reviews changes. Use a team name, never a personal email address.variableslists every value the code must supply.
Check it worked
head -n 9 prompts/triage-ticket.mdYou see the front matter between two --- lines, ending with variables: [shop_name, ticket].
Step 3 · Load and render prompts with a small module
promptlib.py reads a prompt file, checks the front matter, and refuses to load a file whose $variables do not match its variables list, so a typo fails at load time instead of reaching the model. It also hashes the file, so the logs can show if someone edited the text without bumping the version.
cat > promptlib.py <<'PY'
"""Load prompt files from prompts/ and fill in their variables."""
import hashlib
from dataclasses import dataclass
from pathlib import Path
from string import Template
import yaml
PROMPT_DIR = Path(__file__).parent / "prompts"
REQUIRED = ("id", "version", "model", "owner", "max_tokens", "effort", "variables")
class PromptError(Exception):
pass
@dataclass(frozen=True)
class Prompt:
id: str
version: int
model: str
owner: str
max_tokens: int
effort: str
variables: tuple
system: str
user: str
sha: str
@property
def ref(self):
return f"{self.id}@v{self.version}"
def render(self, **values):
if set(values) != set(self.variables):
raise PromptError(f"{self.ref} needs {sorted(self.variables)}, got {sorted(values)}")
return Template(self.system).substitute(values), Template(self.user).substitute(values)
def load(prompt_id):
path = PROMPT_DIR / f"{prompt_id}.md"
text = path.read_text(encoding="utf-8")
if not text.startswith("---\n"):
raise PromptError(f"{path.name}: no front matter")
head, found, body = text[4:].partition("\n---\n")
if not found:
raise PromptError(f"{path.name}: front matter is not closed with ---")
meta = yaml.safe_load(head) or {}
missing = [key for key in REQUIRED if key not in meta]
if missing:
raise PromptError(f"{path.name}: missing {', '.join(missing)}")
if meta["id"] != prompt_id:
raise PromptError(f"{path.name}: id is {meta['id']!r}, expected {prompt_id!r}")
system, found, user = body.partition("\n# user\n")
system = system.strip()
if not found or not system.startswith("# system\n"):
raise PromptError(f"{path.name}: needs a '# system' and a '# user' section")
system = system.removeprefix("# system\n").strip()
user = user.strip()
used = set(Template(system).get_identifiers()) | set(Template(user).get_identifiers())
if used != set(meta["variables"]):
raise PromptError(f"{path.name}: body uses {sorted(used)}, front matter lists {sorted(meta['variables'])}")
return Prompt(
id=meta["id"],
version=int(meta["version"]),
model=meta["model"],
owner=meta["owner"],
max_tokens=int(meta["max_tokens"]),
effort=meta["effort"],
variables=tuple(meta["variables"]),
system=system,
user=user,
sha=hashlib.sha256(text.encode("utf-8")).hexdigest()[:12],
)
PYread_text turns Windows line endings into \n, so a file saved on Windows loads and hashes the same as on Linux or macOS.
Check it worked
Load the prompt, render it, then try to render it with a variable missing:
uv run python - <<'PY'
from promptlib import PromptError, load
prompt = load("triage-ticket")
print(prompt.ref, prompt.model, prompt.owner)
system, user = prompt.render(shop_name="Greenbasket", ticket="Where is my order #4410?")
print(system.splitlines()[0])
print(user)
try:
prompt.render(shop_name="Greenbasket")
except PromptError as error:
print("refused:", error)
PYThe output is:
triage-ticket@v1 claude-opus-5-5 support-tools
You sort customer support messages for Greenbasket, an online grocery shop.
<ticket>
Where is my order #4410?
</ticket>
refused: triage-ticket@v1 needs ['shop_name', 'ticket'], got ['shop_name']Step 4 · Add snapshot tests for the rendered prompt
A snapshot test renders each prompt with fixed example values and compares the result with a saved copy in tests/snapshots/. Any change to the wording, however small, fails the test until a person looks at the difference and accepts it. The first line of each snapshot is the prompt's ref, so the test can also tell you when the text changed but the version did not.
cat > tests/test_snapshots.py <<'PY'
import os
from pathlib import Path
import pytest
from promptlib import PROMPT_DIR, load
SNAPSHOTS = Path(__file__).parent / "snapshots"
UPDATE = "UPDATE_SNAPSHOTS=1 uv run pytest tests/test_snapshots.py"
# One set of example values per prompt file.
EXAMPLES = {
"triage-ticket": {"shop_name": "Greenbasket", "ticket": "My order #4411 arrived without the rice."},
}
def test_every_prompt_has_an_example():
assert sorted(path.stem for path in PROMPT_DIR.glob("*.md")) == sorted(EXAMPLES)
@pytest.mark.parametrize("prompt_id", sorted(EXAMPLES))
def test_rendered_prompt_matches_snapshot(prompt_id):
prompt = load(prompt_id)
system, user = prompt.render(**EXAMPLES[prompt_id])
current = f"{prompt.ref}\n=== system ===\n{system}\n=== user ===\n{user}\n"
path = SNAPSHOTS / f"{prompt_id}.txt"
if os.environ.get("UPDATE_SNAPSHOTS") == "1":
SNAPSHOTS.mkdir(exist_ok=True)
path.write_text(current, encoding="utf-8")
return
assert path.exists(), f"no snapshot for {prompt_id}: run {UPDATE}, read it and commit it"
saved = path.read_text(encoding="utf-8")
if saved != current and saved.split("\n", 1)[0] == prompt.ref:
pytest.fail(f"{prompt_id} renders differently but is still {prompt.ref}: bump version in prompts/{prompt_id}.md")
assert saved == current, f"rendered prompt changed (now {prompt.ref}): review the diff, then run {UPDATE}"
PYThe first test fails if someone adds a prompt file without example values, so no prompt can skip the snapshot. Write the first snapshots, then read what was saved:
UPDATE_SNAPSHOTS=1 uv run pytest tests/test_snapshots.py -q
head -n 3 tests/snapshots/triage-ticket.txtThe snapshot starts with triage-ticket@v1, then === system === and the first line of the system prompt with Greenbasket filled in. Commit the snapshots folder with the code: a reviewer then sees prompt changes in the pull request as a plain text diff.
Check it worked
Run the tests without the update flag:
uv run pytest tests/test_snapshots.py -qThe summary line is 2 passed.
Step 5 · Call the model through the prompt file and log its version
triage.py is the feature. It loads the prompt, renders it, sends the model and settings named in the front matter, and logs one JSON line per call with the prompt's ref and hash. When a customer complains about a wrong answer, that line tells you exactly which prompt produced it.
cat > triage.py <<'PY'
import json
import logging
import anthropic
from promptlib import load
SHOP_NAME = "Greenbasket"
CATEGORIES = {"billing", "delivery", "account", "other"}
log = logging.getLogger("triage")
class TriageError(Exception):
pass
def triage(ticket, client=None):
prompt = load("triage-ticket")
system, user = prompt.render(shop_name=SHOP_NAME, ticket=ticket)
client = client or anthropic.Anthropic()
message = client.messages.create(
model=prompt.model,
max_tokens=prompt.max_tokens,
output_config={"effort": prompt.effort},
system=system,
messages=[{"role": "user", "content": user}],
)
log.info(json.dumps({
"event": "llm_call",
"prompt": prompt.ref,
"prompt_sha": prompt.sha,
"model": message.model,
"message_id": message.id,
"stop_reason": message.stop_reason,
"input_tokens": message.usage.input_tokens,
"output_tokens": message.usage.output_tokens,
}))
text = "".join(block.text for block in message.content if block.type == "text").strip()
if not text:
raise TriageError(f"{prompt.ref}: no text in the reply (stop_reason={message.stop_reason})")
try:
result = json.loads(text)
except json.JSONDecodeError:
raise TriageError(f"{prompt.ref}: reply is not JSON: {text[:80]!r}") from None
if result.get("category") not in CATEGORIES or not isinstance(result.get("urgent"), bool):
raise TriageError(f"{prompt.ref}: unexpected reply {result!r}")
return result
PYThe reply can hold thinking blocks before the text, so the code joins only the text blocks. If the model spends the whole max_tokens budget thinking, or declines (stop_reason of refusal), there is no text, and the function raises an error that names the prompt version instead of returning a guess.
To test this without a key, the tests start a small stand-in for the Messages API inside pytest. It answers POST /v1/messages with the response shape from the API reference: a thinking block (empty, as Opus 5.5 returns by default), a text block, stop_reason and usage. Replies come from recorded examples keyed by ticket text, and a ticket it has no reply for gets a 400 error, so a missing recording fails loudly. The tutorial /tutorials/test-llm-code-offline-with-a-stub-messages-api builds a fuller stub; this one is the minimum the prompt tests need.
cat > tests/fixtures/stub_replies.json <<'JSON'
{
"Can I change the card I pay with?": "{\"category\": \"billing\", \"urgent\": false}",
"Please explain every charge on my account since 2024, line by line.": null
}
JSON
cat > tests/conftest.py <<'PY'
import json
import os
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import anthropic
import pytest
HERE = Path(__file__).parent
LIVE = os.environ.get("PROMPT_TESTS_LIVE") == "1"
def recorded_replies():
"""Ticket text -> reply text. None means the reply was cut off by max_tokens."""
replies = json.loads((HERE / "fixtures" / "stub_replies.json").read_text(encoding="utf-8"))
cases = HERE / "regression.jsonl"
if cases.exists():
for line in cases.read_text(encoding="utf-8").splitlines():
if line.strip():
case = json.loads(line)
replies[case["ticket"]] = case["recorded"]
return replies
class StubMessages(BaseHTTPRequestHandler):
seen = []
def send_json(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
request = json.loads(self.rfile.read(int(self.headers["content-length"])))
StubMessages.seen.append(request)
user = request["messages"][-1]["content"]
ticket = user.split("<ticket>", 1)[-1].split("</ticket>", 1)[0].strip()
replies = recorded_replies()
if ticket not in replies:
return self.send_json(400, {"type": "error", "error": {
"type": "invalid_request_error", "message": f"stub has no recorded reply for {ticket!r}"}})
content = [{"type": "thinking", "thinking": "", "signature": "stub"}]
stop_reason = "max_tokens"
if replies[ticket] is not None:
content.append({"type": "text", "text": replies[ticket]})
stop_reason = "end_turn"
self.send_json(200, {
"id": f"msg_stub_{len(StubMessages.seen)}", "type": "message", "role": "assistant",
"model": request["model"], "content": content, "stop_reason": stop_reason,
"stop_sequence": None, "usage": {"input_tokens": 180, "output_tokens": 40},
})
def log_message(self, *args):
pass
@pytest.fixture(scope="session")
def stub_url():
server = ThreadingHTTPServer(("127.0.0.1", 0), StubMessages)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield f"http://127.0.0.1:{server.server_port}"
server.shutdown()
@pytest.fixture
def client(stub_url):
if LIVE:
return anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
StubMessages.seen.clear()
return anthropic.Anthropic(api_key="stub-key", base_url=stub_url, max_retries=0)
@pytest.fixture
def stub_only():
if LIVE:
pytest.skip("checks the stub's records, not the real model")
return StubMessages.seen
PYNow the tests for triage.py. They check what your code sends and logs, which is the part you own:
cat > tests/test_triage.py <<'PY'
import json
import logging
import pytest
from promptlib import load
from triage import SHOP_NAME, TriageError, triage
TICKET = "Can I change the card I pay with?"
def test_request_comes_from_the_prompt_file(client, stub_only):
assert triage(TICKET, client=client) == {"category": "billing", "urgent": False}
prompt = load("triage-ticket")
system, user = prompt.render(shop_name=SHOP_NAME, ticket=TICKET)
sent = stub_only[-1]
assert sent["model"] == prompt.model
assert sent["max_tokens"] == prompt.max_tokens
assert sent["output_config"] == {"effort": prompt.effort}
assert sent["system"] == system
assert sent["messages"] == [{"role": "user", "content": user}]
def test_every_call_logs_the_prompt_version(client, caplog):
caplog.set_level(logging.INFO, logger="triage")
triage(TICKET, client=client)
record = json.loads(caplog.records[-1].getMessage())
prompt = load("triage-ticket")
assert record["prompt"] == prompt.ref
assert record["prompt_sha"] == prompt.sha
def test_reply_cut_off_by_max_tokens_raises(client, stub_only):
with pytest.raises(TriageError, match="stop_reason=max_tokens"):
triage("Please explain every charge on my account since 2024, line by line.", client=client)
PYCheck it worked
Run the tests with live logging on, so you can see the line each call writes:
uv run pytest tests/test_triage.py -o log_cli=true --log-cli-level=INFOAll three tests pass, and among the log output you see lines like {"event": "llm_call", "prompt": "triage-ticket@v1", "prompt_sha": "...", "model": "claude-opus-5-5", ...}. In production, send the same line to your log store so you can search by prompt.
Step 6 · Run a regression set before a prompt change merges
The regression set is a short list of real-looking tickets with the answer you expect, kept next to the tests in JSON Lines (one JSON object per line). Include the messages your customers really send: Pidgin, French, a food safety report, something off-topic. Each case also stores recorded, the reply the model gave on the last live run you accepted. The stub plays that reply back.
cat > tests/regression.jsonl <<'JSONL'
{"id": "refund-late", "ticket": "I returned the spoiled milk last week and still have no refund.", "category": "billing", "urgent": false, "recorded": "{\"category\": \"billing\", \"urgent\": false}"}
{"id": "missing-item", "ticket": "My order #4411 arrived without the rice.", "category": "delivery", "urgent": false, "recorded": "{\"category\": \"delivery\", \"urgent\": false}"}
{"id": "pidgin-no-delivery", "ticket": "Abeg, the rider never bring my tomatoes and I don pay since morning.", "category": "delivery", "urgent": true, "recorded": "{\"category\": \"delivery\", \"urgent\": true}"}
{"id": "french-sign-in", "ticket": "Je n'arrive plus à me connecter à mon compte depuis hier.", "category": "account", "urgent": false, "recorded": "{\"category\": \"account\", \"urgent\": false}"}
{"id": "unsafe-food", "ticket": "The chicken I got today smells bad and my son already ate some.", "category": "delivery", "urgent": true, "recorded": "{\"category\": \"delivery\", \"urgent\": true}"}
{"id": "off-topic", "ticket": "Do you sell gift cards?", "category": "other", "urgent": false, "recorded": "{\"category\": \"other\", \"urgent\": false}"}
JSONL
cat > tests/test_regression.py <<'PY'
import json
from pathlib import Path
import pytest
from triage import triage
LINES = (Path(__file__).parent / "regression.jsonl").read_text(encoding="utf-8").splitlines()
CASES = [json.loads(line) for line in LINES if line.strip()]
@pytest.mark.regression
@pytest.mark.parametrize("case", CASES, ids=[case["id"] for case in CASES])
def test_regression_case(case, client):
result = triage(case["ticket"], client=client)
assert result["category"] == case["category"]
assert result["urgent"] is case["urgent"]
PYAgainst the stub, these tests prove the plumbing: every case renders, the request is well formed, and your parser accepts each recorded reply. They do not prove the model is right; only a live run does that. That split keeps continuous integration free and offline, while a person who changes a prompt runs the live set before merging.
Run the regression cases against the stub:
uv run pytest -m regression -vWhen you are ready to test the wording against the real model, load your key and turn on live mode. This sends one request per case and is billed to your account:
set -a; . ~/.config/llm-demo/env; set +a
PROMPT_TESTS_LIVE=1 uv run pytest -m regression -vIf a live case fails, read the reply before you touch anything. Either the prompt needs work, or the expected answer was wrong. When you accept a new reply, paste it into that case's recorded field so the stub stays in step with the model. For deciding which cases belong in the set, and how many, see /tutorials/build-a-golden-set-to-test-an-llm-feature.
Check it worked
The stub run lists six test_regression_case[...] lines, one per id, each PASSED, and ends with 6 passed, 5 deselected. The deselected five are the snapshot and triage tests, which -m regression leaves out.
Step 7 · Change the prompt and ship version 2
Support staff ask for double charges to be marked urgent. Edit the prompt's urgency rule, but leave version: 1 for now, as people often do:
cat > prompts/triage-ticket.md <<'MD'
---
id: triage-ticket
version: 1
model: claude-opus-5-5
owner: support-tools
max_tokens: 4000
effort: low
variables: [shop_name, ticket]
---
# system
You sort customer support messages for $shop_name, an online grocery shop.
Customers write in any language, including Nigerian Pidgin and French.
Reply with one JSON object and nothing else, with no code fence:
{"category": "<billing|delivery|account|other>", "urgent": <true|false>}
Categories:
- billing: charges, refunds, payment failures
- delivery: late, missing, damaged or spoiled items
- account: signing in, passwords, profile details
- other: anything else
Set urgent to true only when the customer cannot get food they paid for today,
reports food that may be unsafe to eat, or has been charged more than once
for the same order.
# user
<ticket>
$ticket
</ticket>
MDRun the snapshot tests:
uv run pytest tests/test_snapshots.pyThe test fails with triage-ticket renders differently but is still triage-ticket@v1: bump version in prompts/triage-ticket.md. Bump the version. This rewrites the one version: line in the front matter:
uv run python - <<'PY'
from pathlib import Path
path = Path("prompts/triage-ticket.md")
text = path.read_text(encoding="utf-8")
assert text.count("\nversion: 1\n") == 1
path.write_text(text.replace("\nversion: 1\n", "\nversion: 2\n"), encoding="utf-8")
PYRun the snapshot tests again with -vv, which makes pytest print the full difference between the saved and the new text:
uv run pytest tests/test_snapshots.py -vvIt still fails, now with rendered prompt changed (now triage-ticket@v2), and the diff shows the new urgency lines and the new first line. That is the review step: read the diff as the reviewer of your pull request will. When it says what you meant, accept it:
UPDATE_SNAPSHOTS=1 uv run pytest tests/test_snapshots.py -qAdd a regression case for the new rule. It appends one line, so the existing cases are untouched:
cat >> tests/regression.jsonl <<'JSONL'
{"id": "charged-twice", "ticket": "You charged me twice for order #4420.", "category": "billing", "urgent": true, "recorded": "{\"category\": \"billing\", \"urgent\": true}"}
JSONLThe recorded reply here is what you expect; replace it with the real reply after your live run. Then record the change for the people who read logs and review prompts. A changelog entry says what changed, why, and how it was checked:
cat > CHANGELOG.md <<'MD'
# Prompt changelog
## triage-ticket v2
- Date: 2026-11-18 (replace this with the day you merge)
- Owner: support-tools
- Change: urgent is now also true when a customer has been charged more than once for the same order.
- Why: support staff asked for double charges to reach the urgent queue.
- Checked: snapshot diff reviewed; new regression case charged-twice; regression set passed against the stub and in a live run.
## triage-ticket v1
- Owner: support-tools
- First version: four categories and an urgent flag for unpaid-for or unsafe food.
MDBefore you merge, run the live set from the previous step once more, and only keep "in a live run" in the entry if it passed.
Check it worked
Run the whole suite:
uv run pytest -qThe summary is 12 passed: two snapshot tests, three triage tests and seven regression cases. Your logs now show triage-ticket@v2 for every new call, and git log CHANGELOG.md tests/snapshots/ tells the story of every prompt change.
When you have finished with the demo, delete it:
rm -rf ~/prompts-demoNext steps
- Write the prompt itself with clear roles, rules and an output format: /tutorials/write-a-system-prompt-with-role-rules-and-format
- Brush up on fixtures, parametrize and reading failures: /tutorials/test-python-code-with-pytest
Related tutorials
- Write a system prompt that sets the role, the rules and the output formatYou will turn a one-line prompt into a structured system prompt for a solar installer's support assistant, keep it in a template file that Python renders, and prove with deterministic tests that it is built correctly, stays cacheable and has a format your code can parse.
- How to Write and Run Tests in Python with pytestYou will install pytest 9.2 in a uv project, write tests for a small price-parsing module, run many cases from one test with parametrize, read a failure and fix the code, and use a fixture that gives each test its own temporary folder.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials