Sub topic 9
Monitoring quality in production and closing the feedback loop
This chapter assumes you have read the earlier chapters on prompt versioning, evaluation, and tracing. You should be comfortable with Python and structured logs. It builds on the version_id hash and the traced_call wrapper from those chapters.
Offline evaluation tells you whether a change looks safe before release. Production monitoring tells you whether the application is still behaving well after release. Real traffic differs from your golden set, providers change models, and your documents change. A passing evaluation run does not guarantee good behavior next month.
Why quality monitoring is harder for LLM apps
In classic MLOps you often get ground truth eventually. A fraud label arrives when the chargeback does, and you compare it with the prediction. Drift detection then compares feature distributions or accuracy over time.
LLM applications usually lack that label. A summary of a support ticket has no single correct answer, and nobody marks it right or wrong after the fact. You must build quality signals from indirect evidence.
Quality can also change without any deploy on your side:
- Input drift. Users start asking about a new product, a new language, or longer documents.
- Provider drift. A model alias is repointed to a newer snapshot, or the provider changes safety filters.
- Context drift. The retrieval index is rebuilt, a document is deleted, or the chunking changes.
- Your own changes. A prompt edit, temperature change, or model swap.
Every one of these should be traceable. That is why each log line carries prompt_version and model. When a metric moves, the first question is which of these four sources changed.
Four layers of signals
No single signal is reliable, so you combine cheap signals that cover all traffic with expensive signals that cover a sample.
| Layer | Examples | Coverage | Cost | Weakness |
|---|---|---|---|---|
| Operational | Error rate, p95 latency, tokens per request | All traffic | Very low | Says nothing about answer quality |
| Programmatic proxies | Valid JSON, length bounds, refusal phrases, citation present | All traffic | Low | Easy to pass with a bad answer |
| Sampled evaluation | Model-graded score, human review | 1 to 5 percent | Medium to high | Slow, and the judge itself can drift |
| User feedback | Thumbs, edits, regenerate clicks, escalation to a human | Self-selected users | Low | Biased and sparse |
Operational and proxy signals catch breakage quickly. Sampled evaluation and user feedback catch slow quality decay. You need both kinds.
Proxy signals
A proxy is a check you can run on every response without a reference answer. Useful ones:
- The output parses as the expected schema.
- Output length is within the range seen during evaluation.
- The refusal rate (phrases such as "I can't help with that") has not jumped.
- For retrieval apps, the answer cites at least one retrieved document.
- The output language matches the input language.
A jump in any of these usually points to a real change. A flat proxy does not prove quality is fine.
Sampled online evaluation
Run your evaluation checks, including a model-graded scorer, on a random slice of live traces. Sample by hashing the trace ID instead of calling a random number generator. The decision is then reproducible, and a retried request cannot be sampled twice.
import hashlib
def should_sample(trace_id: str, rate: float) -> bool:
"""Deterministic sampling: the same trace_id always gives the same answer."""
digest = hashlib.sha256(trace_id.encode("utf-8")).hexdigest()
bucket = int(digest[:8], 16) / 0xFFFFFFFF
return bucket < rate
ids = [f"trace-{i}" for i in range(10_000)]
sampled = [t for t in ids if should_sample(t, 0.02)]
print(len(sampled), "of", len(ids), "sampled")Two cautions apply to sampled evaluation:
- Uniform sampling hides rare failures. If a failure affects 0.5 percent of requests, a 2 percent sample finds about one case per 10,000 requests. Add targeted sampling on top of the uniform sample. Take all requests that errored, all requests with negative feedback, and all requests with unusually long outputs.
- The judge can drift. If the grader is itself an LLM behind a model alias, its scores can shift when the alias changes. Pin the judge's model identifier and version it like any other prompt. Periodically re-score a fixed set of human-labeled examples to confirm the judge still agrees with people.
Turning logs into metrics
The trace line from the tracing chapter already contains most of what you need. The next step is to aggregate it per prompt version, so a regression is attributed to the change that caused it.
from collections import defaultdict
def summarize(records):
"""Aggregate trace records per prompt_version."""
groups = defaultdict(list)
for r in records:
groups[r["prompt_version"]].append(r)
stats = {}
for version, rs in groups.items():
n = len(rs)
latencies = sorted(r["latency_ms"] for r in rs)
stats[version] = {
"n": n,
"error_rate": sum(r["status"] != "ok" for r in rs) / n,
"p95_latency_ms": latencies[min(n - 1, int(0.95 * n))],
}
return stats
def alerts(current, baseline, min_n=50, max_error_increase=0.02, max_latency_ratio=1.5):
"""Compare a recent window with a baseline window of the same prompt version."""
problems = []
if current["n"] < min_n:
return ["not enough traffic to judge"]
if current["error_rate"] > baseline["error_rate"] + max_error_increase:
problems.append("error rate up")
if current["p95_latency_ms"] > baseline["p95_latency_ms"] * max_latency_ratio:
problems.append("p95 latency up")
return problems
baseline_window = [
{"prompt_version": "a1b2c3", "status": "ok", "latency_ms": 800 + i} for i in range(100)
]
recent_window = (
[{"prompt_version": "a1b2c3", "status": "ok", "latency_ms": 1500 + i} for i in range(90)]
+ [{"prompt_version": "a1b2c3", "status": "error", "latency_ms": 300} for _ in range(10)]
)
base = summarize(baseline_window)["a1b2c3"]
now = summarize(recent_window)["a1b2c3"]
print(alerts(now, base))The min_n guard matters. With 12 requests in a window, a single failure moves the error rate by 8 points. Alerting on that trains the team to ignore alerts.
The same pattern works for quality metrics. Replace error_rate with the mean model-graded score or the proxy pass rate, and compare each window with the score the version received at release time in offline evaluation. A gap between offline and online scores is itself a finding. It means your golden set does not resemble real traffic.
Closing the feedback loop
Monitoring is only useful if its findings change the system. The loop turns production failures into permanent test cases.
The steps in practice:
- Flag. Collect traces with negative feedback, failed proxy checks, low judge scores, or errors. Add a uniform random sample so you also see failures nobody flagged.
- Review. A person reads each flagged trace and decides what went wrong. Typical causes are a prompt gap, missing retrieval context, a model limitation, or a bad input. Label each cause. The label tells you where to fix it.
- Convert. Write the failure as a golden case with an input and one or more check functions, in the same format as the
caseslist from the evaluation chapter. A case that fails today and passes after your fix is a regression test. - Fix and gate. Change the prompt, retrieval, or model, run the full evaluation, and release only if the gate passes.
- Watch. After release, confirm the production metric that flagged the problem has recovered.
Step 3 needs care with data handling. Raw production inputs can contain personal data. Before a trace becomes a golden case, redact or replace sensitive values, and check that your retention policy allows storing it. For the same reason, decide deliberately whether trace logs store full inputs and outputs. The traced_call wrapper logged only metadata. Teams that store content usually do so in a separate, access-controlled store keyed by trace_id.
Pitfalls in feedback data
- Selection bias. Users who click thumbs-down are a small, self-selected group. Most dissatisfied users just leave. Treat the thumbs-down rate as a trend indicator, not an absolute quality measure.
- Implicit signals are ambiguous. A regenerate click may mean the answer was wrong, or only that the user wanted another phrasing. Validate each implicit signal against reviewed samples before alerting on it.
- Overfitting the golden set. If every production failure becomes a case and you tune the prompt until all cases pass, the set stops measuring generalization. Keep a held-out portion that nobody tunes against, and refresh it from new traffic.
- Feedback delay. Some signals, such as a ticket reopened a week later, arrive late. Record the
trace_idwith the outcome so you can join it back to the original request.
Choosing thresholds
Pick starting thresholds from data, not intuition. Run the monitor over a week of healthy traffic and look at how much each metric varies naturally. Set alerts a few multiples of that natural variation away from the baseline. Review the thresholds after each incident. A threshold that fired falsely three times should be loosened, and one that missed a real problem should be tightened.
Exercise
Your online monitor shows that the model-graded score for prompt version a1b2c3 dropped from 4.2 to 3.6 over two days. No deploy happened, and error rate and latency are unchanged. List the checks you would make to locate the cause, in order, and say what each would tell you.
Show answer
First, confirm the drop is real. Check that the window has enough samples and that the judge model and judge prompt did not change, by re-scoring a fixed set of human-labeled examples. Second, check provider drift. Look at the model field in the traces and see whether the alias now points to a different snapshot. Rerun the offline golden set against the current model, and if the score fell there too, the provider change is the cause. Third, check context drift. For a retrieval app, see whether the index was rebuilt or documents changed, and compare retrieval hit rates and citation rates before and after. Fourth, check input drift. Compare the distribution of input length, language, and topic between the two days, and read some low-scoring traces to see whether users are asking something new. The cause decides the fix: pin the model snapshot, repair the index, or add new golden cases and update the prompt.
Exercise
A teammate proposes alerting whenever the thumbs-down rate exceeds 5 percent in any one hour. Give two reasons this will perform poorly and one change that improves it.
Show answer
First, hourly windows at low traffic contain few requests, so one or two thumbs-down clicks can cross the threshold by chance and cause false alarms. Second, thumbs-down is self-selected feedback, so its absolute level depends on who chooses to click, and a fixed 5 percent is arbitrary and may be normal for this app. A better design uses a longer window with a minimum request count. It compares the rate with the app's own baseline for the same prompt version, and it is paired with a sampled review of the flagged traces.