AI Operations: Running GenAI Systems in Production
A model that scores 92% in a notebook is not a product. Somewhere between the Jupyter demo and paying customers sits a chain of unglamorous problems: which weights are live, who changed the prompt, why did latency triple overnight, and how much did last Tuesday's traffic cost. AI operations â MLOps for traditional models, LLMOps for language models â is the discipline of answering those questions with systems instead of heroics.
Generative AI makes operations harder than classic ML in three specific ways. Outputs are free-form text, so quality cannot be reduced to a single accuracy number. Inference cost scales directly with usage, so a traffic spike is a financial event, not just a capacity one. And the prompt â a plain-text artifact â becomes a production dependency as real as any model weight, yet most teams keep it in a string literal.
This lesson covers the operational backbone for a generative AI service: versioning models and prompts, tracking token spend, monitoring quality on non-deterministic outputs, and the feedback loop that ties production signals back into training data.
What actually breaks when a demo becomes a service
Before designing systems, it helps to name the failure modes that catch teams off guard. The first is silent drift: the upstream model provider updates a version behind the scenes, or your retrieval index goes stale, and output quality degrades a few percent per week until support tickets spike. The second is uncontrolled spend â one looping client or a retry storm multiplies token bills overnight because nobody tagged usage per endpoint or per customer. The third is prompt entropy: five engineers edit the same prompt string in different branches, nobody can reproduce last month's behavior, and an incident review turns into archaeology.
All three failures share a root cause: the artifacts of an AI system â weights, prompts, data slices, evaluation results â were treated as code byproducts rather than first-class, versioned objects. Operations is the work of fixing that.
Versioning every artifact, not just the weights
Model registries solve half the problem. A minimal registry records each version with its metrics and metadata so deployments can reference an immutable identifier instead of a file path:
import json, hashlib, os
from dataclasses import dataclass, asdict
from datetime import datetime
from typing import Dict, Optional
@dataclass
class ModelVersion:
version_id: str
name: str
artifact_path: str
metrics: Dict
metadata: Dict
created_at: str
status: str = "registered"
class ModelRegistry:
def __init__(self, root: str):
self.root = root
os.makedirs(root, exist_ok=True)
def register(self, name: str, artifact_path: str, metrics: Dict,
metadata: Optional[Dict] = None) -> ModelVersion:
version_id = hashlib.sha256(
f"{name}-{datetime.now().isoformat()}".encode()
).hexdigest()[:12]
version = ModelVersion(
version_id=version_id, name=name, artifact_path=artifact_path,
metrics=metrics, metadata=metadata or {},
created_at=datetime.now().isoformat(),
)
with open(os.path.join(self.root, f"{name}_{version_id}.json"), "w") as f:
json.dump(asdict(version), f, indent=2)
return version
def latest(self, name: str) -> Optional[ModelVersion]:
files = [f for f in os.listdir(self.root) if f.startswith(f"{name}_")]
if not files:
return None
newest = max(files, key=lambda f: os.path.getmtime(os.path.join(self.root, f)))
with open(os.path.join(self.root, newest)) as f:
return ModelVersion(**json.load(f))
The same idea applies to prompts. Treat a prompt template as a versioned artifact with named variables, not a string buried in application code. A prompt manager that stamps each revision with a version number lets you roll back a bad change in seconds and correlate quality regressions with specific prompt diffs â exactly the workflow you already expect from git, applied to the text that steers the model.
Tracking tokens, latency and spend
Language model APIs bill by token, which means cost is a runtime metric you can observe directly. Instrument every call: record prompt tokens, completion tokens, the model identifier, and the request context (endpoint, user tier, feature flag). With pricing tables in place, cost becomes a derived field you can aggregate per feature and per customer.
from dataclasses import dataclass
from typing import Dict, List
@dataclass
class UsageRecord:
model: str
prompt_tokens: int
completion_tokens: int
cost_usd: float
endpoint: str
class TokenTracker:
PRICING = {
"gpt-4": {"input": 0.03, "output": 0.06},
"gpt-4o-mini": {"input": 0.00015, "output": 0.0006},
}
def __init__(self):
self.log: List[UsageRecord] = []
def record(self, model: str, prompt_tokens: int, completion_tokens: int,
endpoint: str) -> UsageRecord:
rates = self.PRICING[model]
cost = (prompt_tokens * rates["input"]
+ completion_tokens * rates["output"]) / 1000
rec = UsageRecord(model, prompt_tokens, completion_tokens, cost, endpoint)
self.log.append(rec)
return rec
def summary_by_endpoint(self) -> Dict[str, Dict[str, float]]:
out: Dict[str, Dict[str, float]] = {}
for r in self.log:
bucket = out.setdefault(r.endpoint, {"cost": 0.0, "tokens": 0, "calls": 0})
bucket["cost"] += r.cost_usd
bucket["tokens"] += r.prompt_tokens + r.completion_tokens
bucket["calls"] += 1
return out
Teams that install this kind of tracker usually discover two things within a week. A surprising share of spend comes from a single low-value feature that was quietly calling a frontier model. And streaming responses â where users abandon mid-generation â burn completion tokens nobody ever reads. Both findings are actionable only if usage is logged per endpoint from day one.
Monitoring quality when outputs are free-form
Classic ML monitoring watches a scalar metric drift from a baseline. Generative systems need something richer because a response is not a number. The practical approach combines three layers.
First, cheap automatic signals: response length distribution, refusal rate, format-compliance rate (does the JSON actually parse?), tool-call failure rate, and latency percentiles. These catch gross breakage in minutes. Second, sampled human review: a small random slice of production traffic is scored weekly against a rubric, producing a slow but trustworthy quality trend. Third, LLM-as-judge evaluation on a fixed golden set that runs on every prompt or model change, giving a fast pre-deployment gate.
The three layers differ in what they cost and how quickly they speak, which is why none of them substitutes for the others:
| Layer | What it catches | Signal delay | Ongoing cost |
|---|---|---|---|
| Automatic signals | Gross breakage: parse failures, refusals, latency spikes, tool errors | Minutes | Near zero â computed from logs you already emit |
| Sampled human review | Slow quality drift and rubric-level regressions | Days to a week | Reviewer time on a small traffic slice |
| LLM-as-judge on a golden set | Regressions from a prompt or model change before it ships | Per release | Judge tokens over a fixed, versioned set |
from collections import deque
import statistics
class ProductionMonitor:
def __init__(self, window: int = 1000):
self.latency_ms = deque(maxlen=window)
self.format_errors = deque(maxlen=window)
self.judge_scores = deque(maxlen=window)
def observe(self, latency_ms: float, parsed_ok: bool, judge: float = None):
self.latency_ms.append(latency_ms)
self.format_errors.append(0 if parsed_ok else 1)
if judge is not None:
self.judge_scores.append(judge)
def health(self) -> Dict:
p95 = sorted(self.latency_ms)[int(len(self.latency_ms) * 0.95)] if self.latency_ms else 0
err_rate = statistics.mean(self.format_errors) if self.format_errors else 0
judge_mean = statistics.mean(self.judge_scores) if self.judge_scores else None
alerts = []
if p95 > 4000:
alerts.append("p95 latency above 4s")
if err_rate > 0.02:
alerts.append("format error rate above 2%")
if judge_mean is not None and judge_mean < 0.7:
alerts.append("judge score below threshold")
return {"p95_latency_ms": p95, "format_error_rate": err_rate,
"judge_mean": judge_mean, "alerts": alerts}
The judge score deserves a caveat: automated judges drift and inherit the biases of the model doing the scoring. Anchor them with a weekly human-labeled batch and re-calibrate whenever you change the judge model itself.
Shipping changes without incidents
Prompts and model versions need the same release discipline as code. A practical pipeline stages every change: an author writes the new prompt or selects a candidate model version, CI runs the golden evaluation set plus a regression suite covering past failures, and the result is compared against the currently live version with a stated acceptance threshold. Only then does the change move to a canary deployment, where a small slice of traffic is served by the new version while quality, latency, and cost metrics are compared side by side against the control.
Canary analysis for generative systems has one extra wrinkle: outputs are stochastic, so single-request comparisons are meaningless. You need aggregate metrics over hundreds or thousands of requests per arm, with identical sampling parameters, before the difference between versions is distinguishable from noise. Teams that skip this step routinely promote a version that looked better on a handful of manual spot checks and then discover on day three that its format-compliance rate is worse.
Rollback is the other half of the loop, and it is where versioning pays off. If the live prompt and model identifiers are configuration values rather than baked into application code, reverting a bad release is a config change that completes in seconds. The incident review that follows should ask two questions: why the evaluation set did not catch the regression (an eval gap that must be closed before the next change), and why the canary metric did not alert fast enough (a monitoring gap). Each answer becomes a concrete addition to the pipeline, which is the mechanism that makes releases progressively safer rather than merely more documented.
The LLMOps loop
Everything above feeds one loop. Production logs become evaluation sets; evaluation failures become prompt or fine-tuning candidates; candidates are tested against the golden set in CI; approved versions are promoted through the registry; the registry pins the deployment. The loop is what converts a static model into a system that improves â and the versioning is what makes each iteration auditable when a regulator, a customer, or an incident review asks what changed and when.
Best Practices
- Version prompts in a manager with named variables â never edit a production prompt in application code.
- Tag every token-usage record with endpoint, feature and customer tier; cost attribution is the foundation of cost control.
- Combine three monitoring layers: cheap automatic signals, sampled human review, and LLM-as-judge on golden sets.
- Run every prompt or model change through the same evaluation gate before promotion; no manual hotfixes around it.
- Keep an immutable registry entry for every deployed artifact so rollback is a config change, not a redeploy.
- Feed production failures back into the eval set so the same regression cannot ship twice.
Key Takeaways
- LLMOps extends MLOps with prompts, tokens and free-form quality â the three things classic pipelines do not model.
- Version models and prompts as first-class artifacts; unversioned prompts make incidents unreproducible.
- Token tracking turns an API bill into per-endpoint, per-customer signals you can act on.
- Quality monitoring for generative AI needs automatic signals plus human sampling plus judge models â no single layer is enough.
- The production-to-evaluation feedback loop is the mechanism that keeps a generative system improving after launch.