Example: Pinning and Rolling Back Model and Prompt Versions
Treat the model id and the prompt as versioned dependencies of a release: allow only model and prompt pairs that passed evaluation, refuse to start on anything else or on a prompt edited in place, tag every model call with the pair that made it, and roll back a prompt with a configuration change.
Contentsand lesson path
On this page
- The problem
- Step 1: Record what was evaluated
- Step 2: Refuse unevaluated pairs at start-up
- Step 3: Tag every model call
- Step 4: See what the check stops
- Step 5: Roll back the prompt
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of App Deployment
- From Source to Deployable Artifact Concept · 15 min
- Configuration and Secrets Across Environments Worked example · 20 min
- Lab: Deploy Behind a Custom Domain with HTTPS and Health Checks Lab · 30 min
- Lab: Preview Deploys, Zero-Downtime Release and Rollback Lab · 30 min
- Example: Pinning and Rolling Back Model and Prompt Versions Worked example · 10 min
- Check: Production Readiness Review Knowledge check · 8 questions
What you will learn
- Expose health and readiness checks and release a new version with zero downtime (rolling, blue-green or canary), then roll back a bad release.
Prerequisites: Containerization
01. The problem
The notes API is gaining a summary endpoint that calls a model. Its behaviour now also depends on the model, the prompt and the generation settings, none of which is Python code, and lesson 1's rules apply to them: know exactly what runs, never let it change underneath you, be able to go back. They drift in three ways:
- Moving model ids. Some ids are aliases that a provider points at newer versions. Earlier Claude models had an alias such as
claude-haiku-4-5next to a dated snapshot id,claude-haiku-4-5-20251001; newer ones have a single id per version, such asclaude-sonnet-5-5. Check your provider's documentation and pin an id that names one fixed version. - Retirement. Providers deprecate model versions and later retire them on announced dates, after which a pinned id stops working. Plan each upgrade as a release with its own evaluation.
- Prompts edited in place, in a dashboard, a database row or a file changed without a new version name.
The plan: model id and prompt version become runtime configuration, but only pairs that passed evaluation may run, and every model call is logged with its pair. The example runs on its own in a folder called pin-demo, with Python 3.12 or later and pydantic-settings; in the notes API, the two settings would join lesson 2's Settings class.
02. Step 1: Record what was evaluated
The image ships both prompt versions, as plain text files:
Summarise the note below in one sentence of at most 25 words.
Keep names, numbers and dates exactly as written. Do not add facts.Summarise the note below in one sentence of at most 20 words.
Keep names, numbers and dates exactly as written. Do not add facts.
Start with the action the reader must take, if there is one.Next to them sits a record of every pair that passed the evaluation gate from the AI evaluation skill. The gate appends an entry when a run passes, including a hash of the exact prompt bytes it evaluated:
[
{"model": "claude-sonnet-5-5", "prompt": "v3", "prompt_hash": "8275c2e788fdcdaf",
"eval": "summaries-dev 2026-10-02: 48/50, all must-pass cases"},
{"model": "claude-sonnet-5-5", "prompt": "v4", "prompt_hash": "57488a8b8a305a3a",
"eval": "summaries-dev 2026-10-16: 49/50, all must-pass cases"}
]for f in prompts/summarise/*.txt; do echo "$(sha256sum < "$f" | cut -c1-16) $f"; done8275c2e788fdcdaf prompts/summarise/v3.txt
57488a8b8a305a3a prompts/summarise/v4.txtThe first 16 hex digits of SHA-256 are plenty to notice a changed file. If you use different generation settings, such as the output limit or the effort level, put them in the record too: a pair evaluated with one setting says little about another.
03. Step 2: Refuse unevaluated pairs at start-up
Load and check both settings in one settings class:
"""Load the model and prompt this process will use, and refuse unevaluated pairs."""
import hashlib
import json
from pathlib import Path
from pydantic import model_validator
from pydantic_settings import BaseSettings
PROMPT_DIR = Path("prompts/summarise")
EVALUATED = json.loads(Path("evaluated.json").read_text(encoding="utf-8"))
class AIPins(BaseSettings):
llm_model: str # an exact model id, e.g. claude-sonnet-5-5
prompt_version: str # a file name in prompts/summarise/, e.g. v4
prompt_text: str = ""
prompt_hash: str = ""
@model_validator(mode="after")
def check_evaluated(self) -> "AIPins":
path = PROMPT_DIR / f"{self.prompt_version}.txt"
if not path.is_file():
raise ValueError(f"no prompt file {path}")
self.prompt_text = path.read_text(encoding="utf-8")
self.prompt_hash = hashlib.sha256(path.read_bytes()).hexdigest()[:16]
pair = (self.llm_model, self.prompt_version)
for record in EVALUATED:
if (record["model"], record["prompt"]) != pair:
continue
if record["prompt_hash"] != self.prompt_hash:
raise ValueError(f"{path} was edited after evaluation")
return self
raise ValueError(f"no passing evaluation for {pair[0]} + {pair[1]}")LLM_MODEL and PROMPT_VERSION come from the environment, like any other setting. After the fields validate, check_evaluated loads the prompt file, hashes it and looks for a record with the same model and prompt version. A pair without a record, or a file whose hash differs from the evaluated one, raises ValueError, which pydantic turns into a validation error. As in lesson 2, the process then stops at start-up and the platform keeps the previous version serving.
04. Step 3: Tag every model call
A stand-in for the service loads the pins once and logs them with every call. It needs no API key: the model call is replaced by a line that keeps the first sentence of the note.
"""Stand-in for the API process: load the pins once, then tag every call with them."""
import logging
import sys
from pydantic import ValidationError
from ai_pins import AIPins
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
log = logging.getLogger("notes")
try:
pins = AIPins()
except ValidationError as error:
log.error("not starting: %s", error.errors()[0]["msg"])
sys.exit(1)
def summarise(note: str) -> str:
# The real service sends pins.prompt_text and the note to pins.llm_model here.
reply = note.split(".")[0]
log.info("llm_call model=%s prompt=%s prompt_hash=%s",
pins.llm_model, pins.prompt_version, pins.prompt_hash)
return reply
log.info("serving with model=%s prompt=%s", pins.llm_model, pins.prompt_version)
print(summarise("Rotate the staging key before Friday. The old one leaked in a log."))LLM_MODEL=claude-sonnet-5-5 PROMPT_VERSION=v4 python serve.pyINFO serving with model=claude-sonnet-5-5 prompt=v4
INFO llm_call model=claude-sonnet-5-5 prompt=v4 prompt_hash=57488a8b8a305a3a
Rotate the staging key before FridayWith these fields on every call, the go/no-go check from lab 4 can split error rates, latency, cost and user feedback by model and prompt, just as it split them by X-App-Version. That also lets you canary a prompt change: run two instances with different PROMPT_VERSION values behind a weighted split, and compare.
05. Step 4: See what the check stops
Try a model that was never evaluated with this prompt, then edit v4.txt in place, as someone might do to make a quick fix:
LLM_MODEL=claude-haiku-5-5 PROMPT_VERSION=v4 python serve.py
cp prompts/summarise/v4.txt v4.bak
sed -i 's/at most 20 words/at most 15 words/' prompts/summarise/v4.txt
LLM_MODEL=claude-sonnet-5-5 PROMPT_VERSION=v4 python serve.py
mv v4.bak prompts/summarise/v4.txtERROR not starting: Value error, no passing evaluation for claude-haiku-5-5 + v4
ERROR not starting: Value error, prompts/summarise/v4.txt was edited after evaluationBoth stop before serving a single request. The right way to make the quick fix is a new file, v5.txt, that goes through the evaluation gate and gets its own record. Moving to a cheaper or newer model works the same way: evaluate the pair, add the record, release.
06. Step 5: Roll back the prompt
Suppose v4 passed its evaluation but users report worse summaries, and the per-version metrics agree. Because v3 still ships in the same image and still has its record, rolling back is a configuration change followed by a restart:
LLM_MODEL=claude-sonnet-5-5 PROMPT_VERSION=v3 python serve.pyINFO serving with model=claude-sonnet-5-5 prompt=v3
INFO llm_call model=claude-sonnet-5-5 prompt=v3 prompt_hash=8275c2e788fdcdaf
Rotate the staging key before FridayOn a platform, change the variable and let it do a rolling restart, or start a slot with the old value and switch to it as in lab 4; the image stays the same. A model rollback works the same way, as long as the provider still serves the previous version. Two habits keep rollback possible: keep the previous prompt file and its record for at least one release, and put the model id and prompt hash into the key of any response cache, so the bad version's answers are not served afterwards.
07. Common mistakes
08. Check your understanding
09. Apply it
If your practice project calls a model, add this pattern to it: pin a model id that names one fixed version, keep each prompt version as a file, have your evaluation gate write evaluated.json, check the pair at start-up and add model, prompt version and prompt hash to every log line about a model call. Then release a new prompt version, roll it back with a configuration change, and add both events to your rollback write-up. If your project does not call a model, apply the same idea to another runtime dependency you do not control, such as an external API version.
10. Review prompt
Without looking back, answer:
- In which three ways can the model and prompt behind a release change without a code change?
- What does the start-up check compare, and why does it hash the prompt file?
- Which fields go on every model-call log line, and what do they let the go/no-go check do?
- What has to be true for a prompt rollback to be a configuration change rather than a rebuild?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.