LLMOps and monitoring
LLMOps is how you keep an AI feature working after launch: version prompts like code, log every request safely, watch quality and cost, and block releases that make things worse.
1. Why it matters
- Quality changes without a code change: new documents, new user questions, a provider model update.
- Without logs you cannot answer "why did it say that?" for a complaint.
- Without a release gate a prompt tweak that fixes one case breaks ten others.
2. Key ideas
3. How it works, step by step
- Move prompts out of code strings into a versioned file or registry.
- Log each request as structured JSON with PII redacted; keep logs for a fixed period.
- Build a daily summary: volume, refusal rate, latency p95, cost, top failing topics.
- Run the golden set in CI on every change to prompts, retrieval or model; fail the build if the gate fails.
- Sample live conversations every week, label them, and add the failures to the golden set.
- Set alerts: cost per day, error rate, refusal rate outside a normal band.
- Release behind a flag to a small share of users first; roll back if online metrics drop.
4. Code you can run
Run it from the starter project folder: python examples/l4_llmops.py. It runs offline for free; add an API key in .env to use Claude.
"""Lesson 4: request logs with personal data removed, prompt versions and a release gate.
Run: python examples/l4_llmops.py"""
import collections, os, sys, tempfile
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from starter.ops import get_prompt, log_request, read_log, release_gate
log_path = os.path.join(tempfile.mkdtemp(), "requests.jsonl")
print("1) Structured log lines (personal data removed)")
log_request(log_path, question="My email is [email protected], how many leave days?", prompt_version="rag-answer@v2", latency_ms=420, tokens={"input": 1650, "output": 60}, refused=False)
log_request(log_path, question="What is the dress code?", prompt_version="rag-answer@v2", latency_ms=95, tokens=None, refused=True)
log_request(log_path, question="Expense deadline?", prompt_version="rag-answer@v1", latency_ms=610, tokens={"input": 1700, "output": 90}, refused=False)
for rec in read_log(log_path):
print(" ", {k: rec[k] for k in ("question", "prompt_version", "latency_ms", "refused")})
print("\n2) A daily summary from the log")
rows = read_log(log_path)
lat = sorted(r["latency_ms"] for r in rows)
print(f" requests={len(rows)} refusal rate={sum(r['refused'] for r in rows) / len(rows):.0%} max latency={lat[-1]} ms")
print(" by prompt version:", dict(collections.Counter(r["prompt_version"] for r in rows)))
print("\n3) Prompt versions are stored like code")
for v in ("rag-answer@v1", "rag-answer@v2"):
print(f" {v}: {get_prompt(v)[:70]}...")
print("\n4) Release gate: compare the new version with the last release")
bars = {"accuracy": (0.90, 0.02), "refusal_correct": (0.95, 0.0)}
last = {"accuracy": 0.93, "refusal_correct": 1.00}
for label, new in [("candidate A", {"accuracy": 0.94, "refusal_correct": 1.00}), ("candidate B", {"accuracy": 0.95, "refusal_correct": 0.75})]:
ok, problems = release_gate(new, last, bars)
print(f" {label}: {'RELEASE' if ok else 'BLOCKED'} {problems if problems else ''}")1) Structured log lines (personal data removed)
{'question': 'My email is [EMAIL REMOVED], how many leave days?', 'prompt_version': 'rag-answer@v2', 'latency_ms': 420, 'refused': False}
{'question': 'What is the dress code?', 'prompt_version': 'rag-answer@v2', 'latency_ms': 95, 'refused': True}
{'question': 'Expense deadline?', 'prompt_version': 'rag-answer@v1', 'latency_ms': 610, 'refused': False}
2) A daily summary from the log
requests=3 refusal rate=33% max latency=610 ms
by prompt version: {'rag-answer@v2': 2, 'rag-answer@v1': 1}
3) Prompt versions are stored like code
rag-answer@v1: Answer only from the sources. Cite the source tag for each claim. If t...
rag-answer@v2: You answer questions about company documents. Use only the numbered so...
4) Release gate: compare the new version with the last release
candidate A: RELEASE
candidate B: BLOCKED ['refusal_correct 0.75 is below the bar 0.95', 'refusal_correct fell from 1.00 to 0.75']5. What the code does
- log_request writes JSON lines and redacts personal data, so the email in the first question never reaches the log.
- The daily summary is a few lines of Python over the log; dashboards do the same at scale.
- Prompt versions live in one dictionary; production systems keep them in files under version control.
- release_gate blocks candidate B even though its accuracy is higher, because refusals got worse. That is the point of gating on several metrics.
6. Common mistakes and fixes
| Problem | Fix |
|---|---|
| Prompts edited directly in production | Every change goes through the repository, the eval and the gate. |
| Only accuracy is gated | Gate refusal correctness, safety and cost too, or one will quietly get worse. |
| Logs hold raw personal data | Redact before writing, restrict access and set retention. |
| Golden set never grows | Add every real failure you find; the set should grow every month. |
| No way to roll back quickly | Keep the previous prompt and model ID in configuration so a rollback is a flag change. |
7. Product manager view
- Own the release bar: which metrics, what minimum, how much drop is allowed.
- Review the weekly failure sample with the team; it is the best source of roadmap items.
- Agree an incident process for harmful or wrong answers: who switches the feature off, who tells users.
8. Assignment
Check your work against the model answer for Subject 16.
9. Interview questions
What would you monitor for an LLM feature in production?
Volume, latency p50 and p95, errors, cost per day and per task, refusal and escalation rates, user feedback, and quality on a weekly labelled sample, all split by prompt and model version.
How do you version prompts?
Store them in the repository with an ID and version, log the version with every request, test every change with the eval and release through the gate.
What is a release gate?
An automatic check in CI that compares a candidate with the bars and the last release and blocks the release if any metric fails.
A provider updates the model and quality drops. How would you notice and respond?
Pin model versions where possible, run the eval on the new version before switching, watch online metrics after, and roll back by configuration if they drop.