Sub topic 13
Version and maintain prompts over time
A system prompt is part of your application's behavior, so it needs the same care as code. This chapter covers how to store, identify, change, release, and retire prompt versions. It assumes you have read the earlier chapters on writing prompts and building a small evaluation set. You should be comfortable reading Python and JSON and have called an LLM chat API before.
Why prompts need versions
A prompt edit can change output as much as a code change can, and the effect is harder to predict. Adding one rule to fix a complaint can break the JSON format, shift the tone, or make the model refuse questions it used to answer.
Without versioning, you run into these problems:
- You cannot say which prompt produced a bad reply from last Tuesday.
- You cannot roll back, because nobody kept the old text.
- Two teammates edit the same prompt in a web console and overwrite each other.
- A model upgrade changes behavior, and you cannot tell whether the prompt or the model caused it.
Versioning fixes this by making every prompt change identifiable, reviewable, testable, and reversible.
What counts as "the prompt"
The text of the system message is only one part of what the model sees. Treat the whole bundle as one versioned unit:
- The system prompt text.
- The user-message template, including the delimiters around documents and questions.
- Few-shot examples.
- Tool definitions and their descriptions.
- The output schema or format specification.
- The model name and sampling settings, such as temperature.
If you change the delimiter format in the Python template but leave the system prompt alone, the behavior can still change. Your version should cover that change too.
Store prompts as files in your repository
Keep prompt text in plain files next to your code, not in strings scattered through functions or in a vendor dashboard that nobody reviews. Files give you diffs, pull request review, blame history, and a rollback with git revert.
A simple layout:
prompts/
support_assistant/
v1.txt
v2.txt
v3.txt
CHANGELOG.md
config/
prompts.json
evals/
support_assistant/
cases.jsonlEach version is a separate immutable file. Never edit v2.txt after it has shipped. Copy it to v3.txt and change the copy. Immutable files mean that a version label always points to the same text, which makes logs and bug reports trustworthy.
A small config file pins which version is active and which model it was tested with:
{
"support_assistant": {
"prompt_version": "v3",
"model": "example-model-2025-01",
"temperature": 0
}
}Pin a dated or fixed model identifier where your provider offers one. A floating alias such as "latest" lets the provider change behavior under you with no change in your repository.
Choose a version scheme
Any scheme works if it is consistent. Many teams use simple counters (v1, v2). Others borrow semantic versioning. The useful idea from semantic versioning is that the version number tells downstream code how risky the change is.
| Change | Example | Suggested bump | What to re-check |
|---|---|---|---|
| Output format or schema | Rename `sources` to `citations` | Major | Parsers, validators, every test case |
| New or changed rule | Add "never give tax advice" | Minor | Full evaluation set, with extra cases for the new rule |
| Wording fix with no intended behavior change | Clarify a sentence | Patch | Full evaluation set, to confirm nothing moved |
| Model or temperature change | Switch to a newer model | Treat as minor or major | Full evaluation set, plus a cost and latency check |
Even a patch change needs the evaluation run. "No intended change" is a hope, not a result.
Record the version with every request
When a customer reports a bad answer, you need to know which prompt produced it. Log the prompt name, version, and a short hash of the text with each model call. The hash catches the case where someone edited a file without bumping the version.
import hashlib
import json
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
@dataclass(frozen=True)
class PromptVersion:
name: str
version: str
text: str
@property
def digest(self) -> str:
return hashlib.sha256(self.text.encode("utf-8")).hexdigest()[:12]
def load_prompt(root: Path, name: str, version: str) -> PromptVersion:
path = root / name / f"{version}.txt"
return PromptVersion(name, version, path.read_text(encoding="utf-8"))
def log_call(prompt: PromptVersion, model: str, request_id: str) -> str:
record = {
"ts": time.time(),
"request_id": request_id,
"prompt": prompt.name,
"prompt_version": prompt.version,
"prompt_sha": prompt.digest,
"model": model,
}
return json.dumps(record)
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "support_assistant").mkdir()
(root / "support_assistant" / "v3.txt").write_text(
"You are a support assistant for Acme Billing.", encoding="utf-8"
)
prompt = load_prompt(root, "support_assistant", "v3")
print(log_call(prompt, "example-model-2025-01", "req-001"))The log line from this script contains prompt_version and prompt_sha. With those two fields you can filter production logs to one prompt version, compare error rates between versions, and reproduce a failure by loading the exact text.
A change workflow
Treat each prompt edit as a small release. The steps below match the checks you built in the evaluation chapter.
Gate on regressions, not only on the average
A prompt that raises the overall pass rate can still break a case that used to pass. Compare per-case results and block the change if any previously passing case now fails, unless a reviewer accepts the trade-off.
def new_failures(baseline: dict[str, bool], candidate: dict[str, bool]) -> list[str]:
"""Return case IDs that passed on the baseline but fail on the candidate."""
return sorted(
case_id
for case_id, passed in baseline.items()
if passed and not candidate.get(case_id, False)
)
baseline = {"refund-policy": True, "injection-1": True, "tax-advice": False}
candidate = {"refund-policy": True, "injection-1": False, "tax-advice": True}
regressions = new_failures(baseline, candidate)
print("Regressions:", regressions)
print("OK to promote" if not regressions else "Blocked")Here the candidate fixed tax-advice but broke injection-1. The pass count is unchanged, yet the change should not ship. A missing case counts as a failure, which is the safe default.
Review diffs for intent
In review, read the prompt diff the way you would read a code diff. Ask:
- Does the change address the stated problem and nothing else?
- Does a new rule conflict with an existing one?
- Does the change add a case to the evaluation set that would have caught the original bug?
The last question matters most. Every production failure you fix should leave behind a test case, so the same failure cannot return unnoticed.
Roll out gradually and keep rollback cheap
For applications with real traffic, send a small share of requests to the new version first. Route by a stable key such as a user ID hash so one user does not flip between versions mid-conversation. Compare the canary against the current version on the signals you can measure: format errors, refusal rate, handoff-to-human rate, latency, token cost, and explicit user feedback.
Rollback should be a config change, not a redeploy of rewritten text. Because old version files stay in the repository, rolling back means setting prompt_version to the previous value.
Maintain prompts as models and products change
Prompts drift out of date even when nobody touches them.
- Model upgrades. A new model can read the same prompt differently. Run the full evaluation set against the new model with the current prompt before switching. Fix problems in a new prompt version, and avoid changing the model and the prompt in one step, so you can tell which change caused a difference.
- Provider changes. Hosted models can be updated or retired. Pinned identifiers reduce surprise, but they eventually expire, so track retirement dates.
- Accumulated patches. Each incident tends to add a rule. After many fixes the prompt contains duplicates, contradictions, and rules for problems that no longer occur. Schedule a periodic cleanup. Rewrite the prompt for clarity, then confirm with the evaluation set that behavior held.
- Product changes. When policies, product names, or supported languages change, the prompt and the evaluation cases change with them.
Keep a short CHANGELOG.md per prompt. Each entry needs the version, date, reason, and the evaluation result.
## v3 (2026-03-02)
Reason: Model sometimes gave tax guidance on invoice questions.
Change: Added the rule "Do not give legal or tax advice."
Eval: 48/50 passing (v2: 47/50). New cases: tax-advice-1, tax-advice-2.Name an owner for each prompt. An unowned prompt tends to be edited by whoever last had a complaint, with no testing.
Common mistakes
- Editing a shipped version in place. Logs from that version no longer match its text. Always create a new file.
- Versioning only the system prompt. Template, tool, and schema changes alter behavior too, so include them in the versioned unit.
- Changing the model and the prompt together. You lose the ability to attribute a regression.
- Testing on cases you tuned against. Keep some cases that you never used while editing, so you can detect overfitting to the test set.
- Storing secrets in prompts. Prompt files are committed and logged. Keep API keys, private customer data, and internal credentials out of them.
- No logging of the version. Without it, versioning cannot help you debug production.
Summary of the practice
- Store each prompt version as an immutable file in version control.
- Pin the model and settings alongside the prompt version.
- Log version and hash with every call.
- Gate changes on a per-case regression check.
- Roll out gradually, and keep rollback to a config change.
- Re-test on model changes, and clean up the prompt periodically.
Exercise
A teammate fixes a customer complaint by editing v2.txt directly and deploying. Two days later the support team asks why answers changed on Monday, and your logs show only "prompt_version: v2". List two problems with this process and the change that fixes each.
Show answer
First, editing a shipped file in place makes the label "v2" ambiguous, because logs from before and after the edit point to different text. The fix is to treat version files as immutable and put the change in a new file, v3.txt. Second, the change was deployed without an evaluation run or review, so nobody checked for regressions. The fix is to run the evaluation set on a branch, block on any case that newly fails, and require a reviewed pull request. Logging a short hash of the prompt text (prompt_sha) would also have exposed the silent edit.
Exercise
Your evaluation set has 50 cases. The baseline prompt passes 45 and the candidate passes 46. Why might you still refuse to promote the candidate, and what code-level check would show it?
Show answer
The candidate may fix one or more cases while breaking others that used to pass, and the totals hide this. Comparing per-case results with a function like new_failures(baseline, candidate) lists every case that passed before and fails now. If that list is not empty, the change should be blocked or explicitly accepted by a reviewer.
Exercise
Your provider releases a newer model, and you also want to add a new rule to the prompt. Should you do both in one release? Explain.
Show answer
No. Change one thing at a time. First run the existing evaluation set with the current prompt on the new model and note any differences. Then release the new rule as a new prompt version on the model you have already validated. If both change at once and a case fails, you cannot tell whether the model or the rule caused it.