Sub topic 6
Why and how to version prompts
This chapter assumes you can render a template with named variables and keep it in a file outside your code, as covered in the earlier chapters. It also assumes you know basic Git and read YAML comfortably. Here you will see why prompts need versions, what counts as a change, and which numbering scheme to choose. You will also see how to keep released versions from being edited by accident.
Why prompts need versions
A prompt is a program that runs on a model. Changing one sentence can change the output format, the tone, the length, or how the model handles edge cases. Unlike code, a prompt change rarely produces an error. The application keeps running and the output quietly gets worse for some inputs.
Without versions, you run into these problems:
- You cannot say which prompt produced a bad answer from last Tuesday.
- You cannot reproduce a result, because the prompt has since been edited.
- Two services use "the summarize prompt" but have copied slightly different text.
- You cannot roll back, because the old text only exists in someone's memory.
- A fix for one input type breaks another, and nobody notices for days.
Git history alone does not solve this. Git records every commit, but your application needs a stable name for "the text that was in production". A commit hash is accurate but gives no hint of how big the change was. It also ties the prompt to the whole repository state. A version identifier is a label on one prompt that the application, the logs, and the tests can all refer to.
What counts as a change
Treat the following as part of the prompt version, because each can change model behavior:
- The instruction text, including punctuation and example wording.
- The few-shot examples, if the template includes them.
- The set of variables and how they are placed in the text.
- The output format you ask for (JSON keys, headings, length limits).
- The system or role message, if it is stored with the template.
Model settings such as temperature and model name are not part of the template text. They still matter, because a prompt tuned for one model may behave differently on another. Later chapters record them as metadata and log them with every call. For now, remember that a version identifies the text, not the whole behavior.
A whitespace change can alter tokenization and sometimes the output. In practice most teams treat trailing whitespace as noise and normalize it before comparing or hashing, as shown later in this chapter.
Choosing a versioning scheme
Four schemes are common. None is universally best. The right choice depends on how many consumers depend on the prompt and how much a version number needs to tell them.
| Scheme | Example | Strengths | Weaknesses |
|---|---|---|---|
| Incrementing integer | `v7` | Simple, easy to order | Says nothing about the size of the change |
| Semantic version | `1.2.0` | Signals whether the change is safe to adopt | Requires judgment and discipline |
| Date based | `2026-11-27` | Shows when it was released | Ambiguous when two releases happen in a day |
| Content hash | `a3f9c01b7d2e` | Cannot drift from the text, assigned automatically | Not human-ordered, no meaning in the value |
Many teams combine two of these. A human-chosen version such as 1.2.0 is what the application pins. A content hash computed automatically verifies that the text behind that version has not changed.
This tutorial uses semantic versions, matching the YAML examples from the storage chapter. If only one team uses the prompt and it changes weekly, plain integers are a reasonable choice and cost less effort.
Applying semantic versioning to prompts
Semantic versioning has three numbers: MAJOR.MINOR.PATCH. For code, the numbers describe API compatibility. For prompts, the "API" is what the calling code expects: the variables it supplies and the output shape it parses. A workable rule set:
- Major: the contract changes. A variable is added, removed, or renamed. The output format changes, for example from free text to JSON, or a JSON key is renamed. Calling code or parsers must change too.
- Minor: new behavior that keeps the contract. You add an instruction, a new example, or handle a new case, and existing parsers still work.
- Patch: a wording fix not intended to change behavior. Typos, clearer phrasing, or tighter formatting.
The patch category needs care. Because a model reacts to wording, a "harmless" rewrite can shift outputs. Treat patch as "intended not to change behavior", and let the regression tests from a later chapter confirm it. If a patch fails the tests, bump it to minor and describe what moved.
The decision flow looks like this:
Here is a small helper that applies the rule. It rejects anything that is not a three-part numeric version, so a typo fails immediately.
def bump(version: str, level: str) -> str:
parts = version.split(".")
if len(parts) != 3 or not all(p.isdigit() for p in parts):
raise ValueError(f"not a MAJOR.MINOR.PATCH version: {version!r}")
major, minor, patch = (int(p) for p in parts)
if level == "major":
return f"{major + 1}.0.0"
if level == "minor":
return f"{major}.{minor + 1}.0"
if level == "patch":
return f"{major}.{minor}.{patch + 1}"
raise ValueError(f"unknown level: {level!r}")
print(bump("1.2.0", "minor")) # 1.3.0
print(bump("1.2.0", "major")) # 2.0.0Laying out versions on disk
A simple layout keeps one file per version, grouped by prompt name. This matches the loader from the storage chapter, which reads prompts/<name>/<version>.yaml.
prompts/
summarize/
1.0.0.yaml
1.1.0.yaml
1.2.0.yaml
classify_ticket/
1.0.0.yaml
2.0.0.yamlKeeping every version as its own file has trade-offs.
- Benefit: you can load any old version by name without checking out an old commit. This makes rollback and side-by-side comparison easy.
- Cost: the directory grows, and reviewers must diff two files to see a change.
The alternative is a single file per prompt, with versions living only in Git tags. That keeps the tree small. It makes it harder for the application to load two versions in the same process, which you need for comparison tests and gradual rollouts.
Each version file should state its own version, as in this example:
name: summarize
version: 1.3.0
changelog: Add an instruction to keep names and dates unchanged.
variables: [style, text]
template: |
Summarize the following text in $style style.
If the text is under 50 words, answer in one sentence.
Keep names and dates exactly as written.
$textThe loader should check that the version field matches the file name. A copied file with a forgotten edit would otherwise report the wrong version in your logs.
import yaml
from pathlib import Path
def load_prompt(name: str, version: str, root: str = "prompts") -> dict:
path = Path(root) / name / f"{version}.yaml"
data = yaml.safe_load(path.read_text())
if data["name"] != name or str(data["version"]) != version:
raise ValueError(
f"{path} declares {data['name']} {data['version']}, expected {name} {version}"
)
return dataThe str() call matters. YAML parses an unquoted 1.2 as a number, and a value like 1.10 becomes 1.1. Three-part versions such as 1.2.0 stay strings, but quoting the value in the file is a safe habit.
Making released versions immutable
The most important rule of versioning is that a released version never changes. If 1.2.0 is edited in place, every log line that says "1.2.0" becomes unreliable, and tests that passed against it no longer describe what is deployed. To change a prompt, create 1.2.1 or 1.3.0.
Git does not enforce this, so add a check. The script below records a content hash for each version in a lock file and fails if a recorded version's text has changed. Normalizing whitespace first avoids false alarms from editors that strip trailing spaces.
import hashlib
import json
import sys
from pathlib import Path
import yaml
def content_hash(template_text: str) -> str:
lines = [line.rstrip() for line in template_text.strip().splitlines()]
return hashlib.sha256("\n".join(lines).encode("utf-8")).hexdigest()[:12]
def check_immutable(root: str = "prompts", lock_file: str = "prompts.lock.json") -> list:
lock_path = Path(lock_file)
lock = json.loads(lock_path.read_text()) if lock_path.exists() else {}
problems = []
for path in sorted(Path(root).glob("*/*.yaml")):
data = yaml.safe_load(path.read_text())
key = f"{path.parent.name}/{path.stem}"
digest = content_hash(data["template"])
if key in lock and lock[key] != digest:
problems.append(f"{key} changed after it was recorded")
lock.setdefault(key, digest)
lock_path.write_text(json.dumps(lock, indent=2, sort_keys=True))
return problems
if __name__ == "__main__":
found = check_immutable()
for message in found:
print(message)
sys.exit(1 if found else 0)Commit prompts.lock.json alongside the prompts and run the script in continuous integration. A change to an old version then shows up as a failed check instead of a mystery in production.
Common errors
- Editing a released version. The fix feels small, so people skip the new file. The immutability check above prevents it.
- Under-bumping. Renaming a variable as a patch breaks callers that still pass the old name. Variable and output-format changes are always major.
- Over-bumping everything. If every change is major, the number carries no information and consumers stop trusting it.
- Version in the file name only. Without the
versionfield inside the file, a copied file keeps its old identity in logs. Validate that both agree. - Mixing text and settings. If changing temperature does not bump anything, two runs with the same "version" can differ. Record settings separately, as the next chapters show.
- No note on why. A version with no
changelogforces reviewers to diff the text and guess the intent.
Exercises
Exercise
A template currently uses the variables style and text. You rename text to document so the name is clearer, and the wording of the instructions is unchanged. The current version is 1.4.2. What is the next version, and why?
Show answer
2.0.0. Renaming a variable changes the contract, because calling code that passes text will now fail to render. Any variable or output-format change is a major bump, and the minor and patch numbers reset to zero.
Exercise
Your immutability check stores a hash of the template text. A teammate fixes a typo in the released version 1.2.0 and the check fails. What should they do instead of editing the lock file?
Show answer
Revert the edit to 1.2.0 and create a new version file, 1.2.1, containing the typo fix with a changelog line. Add the new version to the lock file through the normal run of the check. The released 1.2.0 must stay exactly as it was, so logs and tests that mention it remain accurate.