Sub topic 16
Online evaluation, user feedback, and monitoring
This chapter assumes you can write the offline harness from earlier chapters (dataset, scorer, pass rate) and compute a bootstrap confidence interval. It also assumes you have deployed, or could deploy, an LLM application behind an API. Online evaluation covers what happens after release: measuring quality on real traffic, collecting user signals, and noticing when quality drops.
Why offline evaluation is not enough
An offline dataset is a snapshot of what you expected users to do. Production differs from it in several ways:
- Input drift. Users ask things you did not anticipate, and their topics and phrasing change over time.
- Upstream changes. A provider updates a hosted model, a document index is re-built, or a tool API changes its response format. None of these touch your code or your test set.
- Long tail. Rare inputs that never made it into a 200-case dataset appear daily at production volume.
- Interaction effects. Latency, truncation, concurrency limits, and retries only show up under real load.
Online evaluation does not replace the offline harness. Offline evaluation is the gate before release. Online evaluation tells you whether the released system still behaves as the gate predicted, and it supplies new failures to add to the dataset.
Signals you can collect
No single online signal is reliable on its own. Combine several.
| Signal | Examples | Strength | Weakness |
|---|---|---|---|
| Explicit feedback | Thumbs up/down, star rating, written comment | Direct statement of satisfaction | Sparse, and skewed toward strong opinions |
| Implicit feedback | Regenerate clicks, copy-to-clipboard, edits to the output, abandoned sessions, follow-up rephrasing | Available for most sessions | Ambiguous: a copy may mean success, a regenerate may mean curiosity |
| Automatic scoring | LLM judge or programmatic checks on sampled traces | Scales, and uses the same criteria as offline | Judge errors and cost, and it needs the logged context |
| Operational metrics | Latency, token counts, error rate, refusal rate, schema-validation failures | Cheap, immediate, objective | Says little about correctness |
Programmatic checks from the earlier chapter are especially useful online. They are cheap enough to run on every response: valid JSON, required fields present, length limits, no leaked system prompt, citations that point to retrieved documents.
Log traces you can replay
Every online method depends on logging. A useful trace records enough to re-run or re-score the request later:
- A unique trace ID and a timestamp.
- The user input and the final output.
- The model name and parameters, and the prompt version.
- For RAG, the retrieved document IDs and the context given to the model.
- For agents, each tool call and its result.
- Latency and token counts.
- Any feedback event, linked by trace ID.
The prompt version matters most. Without it you cannot tell whether a quality change came from your deploy or from outside.
import hashlib
import json
import time
import uuid
def new_trace(user_input, output, model, prompt_version, latency_ms, retrieved_ids=None):
return {
"trace_id": str(uuid.uuid4()),
"ts": time.time(),
"input": user_input,
"output": output,
"model": model,
"prompt_version": prompt_version,
"latency_ms": latency_ms,
"retrieved_ids": retrieved_ids or [],
}
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()).hexdigest()
bucket = int(digest[:8], 16) / 0xFFFFFFFF
return bucket < rate
trace = new_trace("Capital of France?", "Paris", "model-x", "v12", 420)
print(json.dumps({"id": trace["trace_id"][:8], "sampled": should_sample(trace["trace_id"], 0.1)}))Hash-based sampling is deterministic, so a retry or a second worker makes the same decision. That keeps your sampled set unbiased and reproducible.
Scoring sampled traffic automatically
Running a judge on every request is usually too expensive. Instead, score a random sample, for example 1 to 5 percent. You can also oversample risky segments: long conversations, low-confidence retrievals, or sessions with negative feedback.
Reuse the judge prompt and parse_verdict function from the judge chapter, with the same criterion. Using the same rubric offline and online lets you compare the two numbers directly. Keep these rules:
- Count unparseable verdicts separately. A rising unparseable rate is itself a signal that something changed.
- Re-validate the judge against fresh human labels from production samples. Real traffic can differ from your calibration set.
- Store the judge's model and prompt version with each score, so a judge change is not mistaken for an application change.
Reading explicit and implicit feedback
Feedback is biased by who chooses to give it. A thumbs-down rate of 4 percent does not mean 96 percent of users are happy, because most users never click anything. Report the response rate next to the rating, and compare like with like.
def feedback_summary(events):
"""events: dicts with optional 'thumb' ('up' or 'down') and 'regenerated' (bool)."""
total = len(events)
rated = [e for e in events if e.get("thumb") in ("up", "down")]
ups = sum(e["thumb"] == "up" for e in rated)
return {
"responses": total,
"feedback_rate": len(rated) / total if total else 0.0,
"thumbs_up_rate": ups / len(rated) if rated else None,
"regenerate_rate": sum(bool(e.get("regenerated")) for e in events) / total if total else 0.0,
}
events = [
{"thumb": "up"}, {"thumb": "down", "regenerated": True},
{}, {}, {"regenerated": True}, {}, {}, {"thumb": "up"}, {}, {},
]
print(feedback_summary(events))This prints a feedback rate of 0.3, a thumbs-up rate of about 0.67, and a regenerate rate of 0.2. With only three rated responses, the thumbs-up rate carries very little information. Apply the interval methods from the statistics chapter before acting on it.
Common pitfalls:
- Selection bias. Users who are angry or delighted rate more often. Compare trends over time and across versions, not absolute levels.
- Interface effects. Moving the thumbs buttons changes the response rate, which can look like a quality change.
- Ambiguous implicit signals. Validate each one. Take a sample of sessions with regenerate clicks, read them, and check that the signal tracks real dissatisfaction.
- Proxy optimization. If you optimize only for thumbs-up, the model may learn to flatter. Pair feedback with a judge or human audits for correctness.
Monitoring and alerting
Monitoring turns scores into alerts. Track a rolling window of a quality metric, such as the judge pass rate or schema-validation rate, and alert when it falls below a threshold. Require a minimum count before alerting, so a few early failures do not trigger a false alarm.
from collections import deque
class RollingRate:
def __init__(self, window: int, min_count: int, threshold: float):
self.values = deque(maxlen=window)
self.min_count = min_count
self.threshold = threshold
def add(self, passed: bool) -> None:
self.values.append(1 if passed else 0)
def rate(self) -> float:
return sum(self.values) / len(self.values) if self.values else 0.0
def breached(self) -> bool:
return len(self.values) >= self.min_count and self.rate() < self.threshold
mon = RollingRate(window=20, min_count=20, threshold=0.8)
for p in [True] * 18 + [False] * 2:
mon.add(p)
print(mon.rate(), mon.breached()) # 0.9 False
for p in [False] * 6:
mon.add(p)
print(mon.rate(), mon.breached()) # 0.6 TrueA fixed threshold is a starting point. Set it from your offline pass rate and its confidence interval, so normal sampling noise does not page anyone. Break each metric down by prompt version, model, and user segment, because an aggregate can hide a failure in one slice.
Alongside quality metrics, watch these:
- Latency percentiles (p50 and p95), because averages hide slow tails.
- Cost per request and tokens per response.
- Refusal rate and empty-output rate.
- Input distribution shifts, such as average length or the share of new topics.
Comparing versions safely in production
Before you send all traffic to a change, limit its exposure.
- Shadow mode. Run the new version on real inputs, but do not show its output to users. You can score both versions with the same judge and compare. This costs extra compute but carries no user risk.
- Canary release. Send a small share, such as 5 percent, to the new version and watch the monitors. Roll back if a metric breaches.
- A/B test. Randomly assign users, not requests, to variants, so one user sees a consistent experience. Choose the primary metric and the sample size before you start. Report the difference with a confidence interval, as in the statistical rigor chapter, and do not stop the test the first time the result looks good.
Closing the loop
The most valuable output of online evaluation is new test cases. A repeatable process looks like this:
Add failures you reviewed and labeled to the offline set, tagged by failure type. Then the regression suite covers a bug once it has been seen in production. Keep a held-out portion that you never tune against, so improvements measured offline stay trustworthy.
Common errors
- Logging only outputs, so a failure cannot be replayed because the retrieved context or prompt version is missing.
- Treating the thumbs-up rate as accuracy.
- Alerting on raw rates in small windows, which produces constant false alarms.
- Changing the judge, the prompt, and the model in one deploy, so a metric movement cannot be attributed.
- Adding production data to the dataset without redacting it.
Exercise
Your monitor shows the thumbs-down rate rose from 3% to 5% after a release. The feedback rate (the share of responses that received any rating) fell from 10% to 4% in the same period. What should you do before concluding that quality dropped, and which other signals would you check?
Show answer
First treat the change as unconfirmed. The fall in feedback rate suggests the interface or user mix changed, which can shift who rates and make the thumbs-down rate unreliable. Check whether the release or a UI change moved the rating buttons. Compute confidence intervals, since 4% of the traffic gives far fewer rated responses. Then look at signals that do not depend on users choosing to rate: the judge pass rate on a random sample of traces from both versions, programmatic check failures, regenerate rate, and refusal rate. Read a sample of the thumbs-down traces by hand. If these agree, roll back or investigate. If only the thumbs-down rate moved, the cause is likely a change in who gives feedback.
Exercise
Why does should_sample hash the trace ID instead of calling random.random()?
Show answer
Hashing is deterministic: the same trace ID always gets the same decision, regardless of which worker handles it or whether the request is retried or re-processed later. A random call can sample a trace on one pass and skip it on another, which makes the scored set irreproducible and can bias counts when events for one trace are processed more than once.