Sub topic 7
Releasing prompt and model changes behind evaluation gates
This chapter assumes you have read the earlier chapters on versioned prompt artifacts and on evaluation (golden sets, programmatic checks, repeated runs). You should be comfortable with Python and with CI pipelines at the level of "a check passes or blocks a merge".
Why releases need their own process
In classic MLOps, a release usually means a newly trained model that passed validation on a held-out set. In an LLM application, the thing that changes behavior is often not a trained model. A one-line edit to a prompt template can change every response your product produces. A model identifier bump, a temperature change, or a new retrieval configuration can do the same.
Three properties make these changes risky:
- They look small in review. A diff that rewords an instruction is easy to approve, yet it can break output format or tone across all inputs.
- They ship without a code deploy. If prompts live in a config store or database, a change can reach production with no pipeline run at all.
- The model underneath can change without your involvement. A provider can retire a model or move an alias such as
latestto a new snapshot. Your code and prompt are unchanged, but behavior is not.
The answer is the same discipline you apply to code, adapted to non-deterministic output: every behavior-affecting change becomes a release candidate, the candidate is measured against the current production version, and only a passing candidate is promoted.
What counts as a release candidate
Treat the full tuple as one unit. In the versioning chapter, the PromptVersion dataclass hashes the name, model, temperature, and template into a version_id. The same idea extends to anything else that shapes output:
- The prompt template and any few-shot examples.
- The model identifier, pinned to a dated snapshot rather than a moving alias.
- Sampling settings such as temperature and maximum output tokens.
- Retrieval settings, such as chunk size, number of chunks, and the embedding model.
- Output parsing and validation code that sits after the model call.
If two of these change in one release and quality drops, you cannot tell which change caused it. Prefer one logical change per candidate, or at least keep the eval report detailed enough to compare.
The gate: compare candidate against baseline
An evaluation gate is an automated step that runs the golden set against the candidate and the current production version, then returns approve or block. Comparing against the baseline matters as much as the absolute threshold. A candidate can clear a 0.9 floor and still be a clear regression on a case that used to pass every time.
Use two rules together:
- Floor: each case's pass rate must be at least a minimum (for example 0.9).
- No regression: each case's pass rate must not fall more than a tolerance below the baseline.
Because output varies between runs, each case runs several times and you work with pass rates, not single results. The code below is self-contained. The two generators are stand-ins for real model calls.
def run_eval(generate, cases, runs=5):
"""Return {case_id: pass_rate}. generate(text) -> str."""
report = {}
for case in cases:
passes = sum(
all(check(generate(case["input"])) for check in case["checks"])
for _ in range(runs)
)
report[case["id"]] = passes / runs
return report
def release_decision(baseline, candidate, min_pass=0.9, max_drop=0.1):
"""Return (approved, reasons). Both arguments are {case_id: pass_rate}."""
reasons = []
for case_id, base_rate in baseline.items():
cand_rate = candidate.get(case_id, 0.0) # a missing case counts as failed
if cand_rate < min_pass:
reasons.append(
f"{case_id}: pass rate {cand_rate:.2f} is below the floor of {min_pass:.2f}"
)
if base_rate - cand_rate > max_drop:
reasons.append(f"{case_id}: fell from {base_rate:.2f} to {cand_rate:.2f}")
return len(reasons) == 0, reasons
cases = [
{
"id": "duplicate_charge",
"input": "My invoice shows a duplicate charge.",
"checks": [
lambda out: "charge" in out.lower(),
lambda out: len(out.split()) <= 60,
],
},
{
"id": "login_failure",
"input": "I cannot log in after the password reset.",
"checks": [
lambda out: "log in" in out.lower(),
lambda out: len(out.split()) <= 60,
],
},
]
def baseline_generate(text):
return f"Summary: {text}"
def candidate_generate(text):
if "log in" in text:
return f"Summary: {text}"
return "The customer has a billing question."
baseline_report = run_eval(baseline_generate, cases)
candidate_report = run_eval(candidate_generate, cases)
approved, reasons = release_decision(baseline_report, candidate_report)
print("approved" if approved else "blocked")
for reason in reasons:
print(reason)Running this prints:
blocked
duplicate_charge: pass rate 0.00 is below the floor of 0.90
duplicate_charge: fell from 1.00 to 0.00The candidate handles the login case but loses the word "charge" on the billing case. An average over both cases would be 0.5, which hides which case broke. The per-case reasons tell the author where to look.
Choosing thresholds
- Set the floor from what you can tolerate, not from what you currently achieve. If a case matters for safety or contract compliance (for example, "never output a card number"), require 1.0.
- Set
max_dropabove the noise level of your suite. Run the baseline against itself a few times and look at how much pass rates move. If they swing by 0.2 between identical runs, a 0.1 tolerance will block good releases at random. - Increase
runsfor cases that sit near the boundary. With 5 runs, one flaky failure moves a pass rate by 0.2. - Keep the golden set stable between baseline and candidate runs. Compare both versions on the same cases in the same job.
Model-graded scores in the gate
If part of your suite uses a model as judge, pin the judge's model identifier and prompt too, and version them like any other artifact. Changing the judge changes every score. When you must change it, re-run the baseline with the new judge before comparing, so both sides are scored by the same one. Use programmatic checks for hard requirements (format, length, forbidden strings) and keep judge scores for softer qualities, with a looser tolerance.
Staged rollout after the gate
Offline evaluation covers the inputs you thought of. Production has inputs you did not. A gate is therefore the first of several steps.
The stages work as follows:
- Shadow: the candidate processes real requests, but its output is logged and not shown to users. You compare it with the stable version's output offline. This costs extra tokens and adds no user risk.
- Canary: a small share of users receive the candidate's output. Watch error rate, latency, token usage, and any quality signals from your traces and feedback.
- Full rollout: the candidate becomes the stable version and the next baseline.
For canary routing, assign users to a version deterministically. A random choice per request would give one user inconsistent behavior within a session.
import hashlib
def pick_version(user_id, stable, candidate, canary_percent):
"""Same user always gets the same version for a given canary_percent."""
digest = hashlib.sha256(user_id.encode("utf-8")).hexdigest()
bucket = int(digest, 16) % 100
return candidate if bucket < canary_percent else stable
users = [f"user-{i}" for i in range(1000)]
chosen = [pick_version(u, "v_stable", "v_candidate", 10) for u in users]
print(chosen.count("v_candidate")) # roughly 100Raising canary_percent from 10 to 25 keeps the original 10% in the canary group, because their buckets are still below the new cutoff.
Rollback
Rollback is only fast if the stable version is still available and selecting it takes one change. Keep the prior version's artifact (template, model ID, settings) addressable by its version_id, and have production read "which version is live" from a pointer you can change without a code deploy. Log the version_id on every request, as covered in the tracing chapter, so you can tell which responses came from which version after the fact.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Gate on an average score across all cases | One broken case is hidden by many easy ones | Report and gate per case, as `release_decision` does |
| Single run per case | Flaky results cause random blocks or random approvals | Run each case several times and use pass rates |
| Tolerance below the noise level | Good candidates are blocked at random | Measure baseline-versus-baseline variation first |
| Baseline measured last week | Provider or data changes make the comparison unfair | Run baseline and candidate in the same job |
| Prompts editable in a UI with no gate | Changes reach users with no evaluation | Route all edits through the same candidate pipeline |
| Golden set never updated | Gate passes while real failures grow | Add failing production cases to the set after each incident |
| Bundling several changes | A regression cannot be attributed | Release one logical change at a time |
Keeping the gate useful over time
A gate protects only against the failures it knows about. After each production incident, add the offending input to the golden set with a check that would have caught it. Then confirm the check fails on the version that caused the incident. Review the suite periodically: remove cases that no longer reflect real traffic, and keep an eye on suite runtime, since a gate that takes an hour tends to get skipped.
Exercise
A candidate prompt gets an average pass rate of 0.95 across 40 golden cases, which is above your 0.9 floor, but the baseline averaged 0.96. A reviewer wants to approve it. What additional information do you need from the gate before deciding, and what would make you block it?
Show answer
You need the per-case pass rates for both versions, not just the averages. Block the candidate if any case falls below its own floor (especially a safety or compliance case that requires 1.0), or if any case dropped by more than the tolerance compared with the baseline, because a few large regressions can hide inside a small drop in the average. Also confirm that the baseline and candidate were run in the same job on the same cases with enough runs per case, and that the difference exceeds the noise measured when the baseline is run against itself.
Exercise
Your canary routing picks a random version on every request. Name two problems this causes and describe a fix.
Show answer
A single user can see different behavior within one session, which makes feedback and bug reports hard to interpret. Metrics for the two groups also mix, because the same user contributes to both. The fix is deterministic assignment: hash the user ID into a bucket from 0 to 99 and send the user to the candidate when the bucket is below the canary percentage, as pick_version does.