Sub topic 14
Putting it together: the LLMOps loop
This chapter assumes you have read the earlier chapters on versioned prompts, evaluation, tracing, monitoring, cost, and safety. It also assumes you can read Python and know the classic train, validate, deploy cycle. Here you will connect those pieces into one operating loop and run a small skeleton of it.
The loop in one picture
Classic MLOps loops around a trained model: new data leads to retraining, validation, deployment, and drift monitoring. In an LLM application the model is usually a dependency you do not retrain. The loop turns around the artifacts you do control: the prompt, the model identifier, the sampling settings, the retrieval configuration, and the guardrails.
Every arrow in the diagram corresponds to something concrete: a version ID, a report, a pass or fail result, a trace record, or a new test case. If a step produces no record you can inspect, the loop has a gap there.
Stage by stage
Each stage produces an artifact and a signal, and each signal can send you back to an earlier stage.
| Stage | Artifact it produces | Signal it relies on | What sends you back |
|---|---|---|---|
| Change | A proposed prompt, model, or config edit | A defect, cost target, or feature request | Nothing; this is the entry point |
| Version | A version ID from a content hash | Identical inputs produce identical IDs | An unversioned setting found in a trace |
| Offline eval | A report of per-case pass rates | Golden set results over repeated runs | Failing or regressed cases |
| Release gate | A pass or fail decision | Thresholds and comparison with the baseline | Any failing gate |
| Production tracing | One structured record per call | Prompt version, tokens, latency, status | Missing fields in records |
| Monitoring | Dashboards and alerts | Quality proxies, cost per request, p95 latency, guardrail hits | An alert, a drift in scores, or user complaints |
| Feedback | New golden cases and labeled examples | Reviewed traces and user ratings | A failure that no existing case covers |
Two stages deserve extra attention because they join the others.
Versioning is the join key
A version ID is what lets a trace in production point back to the exact eval report that approved it. Without that link you can see that quality dropped on Tuesday but not which change caused it. Hash everything that can change behavior: template, model identifier, temperature, and also retrieval settings such as chunk size, number of results, and the embedding model. If a setting lives in an environment variable and is not part of the hash, it is an unversioned change waiting to happen.
Feedback is the step classic MLOps teams skip
In classic MLOps, ground-truth labels often arrive later and retraining consumes them. In an LLM app, the equivalent is a human or model-graded review of sampled traces. Each confirmed failure should become a golden case, so the same failure cannot ship twice. The golden set grows from production, not only from what you imagined at design time.
A runnable skeleton of the loop
The code below combines three pieces from earlier chapters: a versioned prompt, a traced call, and an eval harness with a gate. It adds a regression check against the baseline version. The model is a stub so the script runs without credentials. Replace fake_model with an adapter around your real client.
import hashlib
import json
import time
import uuid
from dataclasses import dataclass
@dataclass(frozen=True)
class PromptVersion:
name: str
template: str
model: str
temperature: float
@property
def version_id(self) -> str:
raw = f"{self.name}|{self.model}|{self.temperature}|{self.template}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:12]
def render(self, **values: str) -> str:
return self.template.format(**values)
def traced_call(call_model, prompt_version, user_input, log):
start = time.perf_counter()
status = "ok"
result = {}
try:
result = call_model(prompt_version, user_input)
return result
except Exception:
status = "error"
raise
finally:
log(json.dumps({
"trace_id": str(uuid.uuid4()),
"prompt_version": prompt_version.version_id,
"model": prompt_version.model,
"latency_ms": round((time.perf_counter() - start) * 1000, 1),
"input_tokens": result.get("input_tokens"),
"output_tokens": result.get("output_tokens"),
"status": status,
}))
def run_eval(generate, cases, runs=3):
report = []
for case in cases:
passes = 0
for _ in range(runs):
output = generate(case["input"])
if all(check(output) for check in case["checks"]):
passes += 1
report.append({"id": case["id"], "pass_rate": passes / runs})
return report
def gate(report, min_pass_rate=0.9):
failing = [r["id"] for r in report if r["pass_rate"] < min_pass_rate]
return len(failing) == 0, failing
def regressions(candidate, baseline, tolerance=0.05):
base = {r["id"]: r["pass_rate"] for r in baseline}
return [
r["id"] for r in candidate
if r["id"] in base and r["pass_rate"] < base[r["id"]] - tolerance
]
def fake_model(prompt_version, user_input):
prompt = prompt_version.render(ticket_text=user_input)
text = "Customer reports: " + user_input
return {
"text": text,
"input_tokens": len(prompt.split()),
"output_tokens": len(text.split()),
}
def make_generate(call_model, prompt_version, log):
def generate(text):
return traced_call(call_model, prompt_version, text, log)["text"]
return generate
cases = [
{
"id": "duplicate_charge",
"input": "My invoice shows a duplicate charge.",
"checks": [
lambda out: "charge" in out.lower(),
lambda out: len(out.split()) <= 60,
],
},
]
baseline = PromptVersion(
name="summarize_ticket",
template="Summarize this support ticket in two sentences:\n\n{ticket_text}",
model="example-model-2026-01",
temperature=0.2,
)
candidate = PromptVersion(
name="summarize_ticket",
template="Summarize this support ticket in one sentence:\n\n{ticket_text}",
model="example-model-2026-01",
temperature=0.2,
)
traces = []
base_report = run_eval(make_generate(fake_model, baseline, traces.append), cases)
cand_report = run_eval(make_generate(fake_model, candidate, traces.append), cases)
passed, failing = gate(cand_report)
regressed = regressions(cand_report, base_report)
print("baseline:", baseline.version_id, "candidate:", candidate.version_id)
print("gate passed:", passed, "failing:", failing, "regressed:", regressed)
print("trace lines written:", len(traces))
release = passed and not regressed
print("RELEASE" if release else "HOLD")The script prints two different version IDs, because the template changed. The gate and the regression check are separate questions. The gate asks whether the candidate is good enough in absolute terms. The regression check asks whether it is worse than what is running now on any case, which can happen even when every case still clears the threshold.
Note that the eval calls also go through traced_call. That is deliberate. Offline runs produce traces tagged with the candidate's version ID, so you can compare their token counts and latency with production later.
How the loop differs from the classic one
- The trigger changes. Classic retraining fires on data drift or a schedule. LLM changes fire on prompt edits, provider model updates, retrieval index changes, and new failure reports. A provider that retires or silently updates a model identifier can start a turn of the loop without any change on your side.
- Evaluation is the center, not validation. A held-out metric such as AUC does not exist for open-ended text. Your golden set, programmatic checks, and model-graded scoring carry that role, and repeated runs measure the spread that sampling adds.
- Cost and latency are release criteria. A candidate prompt that passes quality checks but doubles the input tokens should be judged on that too. Record tokens and latency in the eval report next to pass rates.
- Safety belongs inside the loop. Prompt-injection cases and data-handling checks should be golden cases like any other, so each release is tested against them.
Failure modes of the loop
- Unversioned inputs. A retrieval index rebuilt overnight changes outputs while the prompt version stays the same. Include an index or corpus identifier in traces, even if it is not in the hash.
- A golden set that never changes. Pass rates stay at 100% while real users hit failures the set does not cover. Schedule a review that moves confirmed production failures into the set.
- Gate thresholds that drift upward in tolerance. Teams lower
min_pass_rateto get a release through. Treat a threshold change as a reviewed change with its own record. - Judge drift. If a model grades outputs, a change to the grader model shifts scores without any change to the app. Version the grader prompt and model like any other artifact, and re-score a fixed sample when it changes.
- Traces without privacy controls. Logging full inputs helps debugging but may store personal data. Decide what to redact or sample before turning full logging on.
- Alerts on averages only. Mean latency hides slow tails. Alert on p95 or p99, and on per-version cost per request.
Decision checklist for a change
Before shipping any change, you should be able to answer these from records, not from memory:
- What exactly changed, and what is the new version ID?
- Which cases did it improve, and which did it regress?
- What happened to tokens per request and latency compared with the baseline?
- Did the safety and injection cases still pass?
- Which trace field or alert will show within a day that the change misbehaves?
- How do we roll back?
Exercises
Exercise
A candidate prompt passes the gate with every case at a pass rate of at least 0.9, but the baseline scored 1.0 on three of those cases and the candidate scores 0.9 on them. Which function in the skeleton catches this, and why is a separate check needed?
Show answer
The regressions function catches it. The gate function only compares each case with a fixed threshold, so 0.9 passes. regressions compares each case with the baseline's pass rate minus a tolerance (0.05 by default), so a drop from 1.0 to 0.9 is reported. Without it, a release can make the application worse on cases that were previously solid while still looking acceptable in absolute terms.
Exercise
Quality metrics in production look stable, but your monthly bill rose 40% after a release. Using the loop, name the artifact that should have exposed this before release and the trace fields you would use to investigate after the fact.
Show answer
The offline eval report should have recorded tokens per request (and latency) for the candidate next to the baseline, and the release criteria should have included a cost limit. After the fact, group trace records by prompt_version and compare input_tokens and output_tokens per request between the old and new version IDs. A longer template, extra retrieved context, or a more verbose output style would show up as higher token counts under the new version.