Sub topic 14
Monitoring and maintaining the router
This chapter assumes you have built the pipeline from the earlier chapters: classify, route, and evaluate, with a label set that includes an other fallback. You should also be comfortable with Python's logging module and JSON. The goal here is to keep that router accurate after it ships.
Why a router degrades
A router that scored 92% on your labeled set in March can score much lower by autumn without any code change. The causes are usually one of these:
- Input drift. Customers start writing about a new product, a new outage, or a new kind of fraud. The labels no longer describe the traffic.
- Model changes. A provider updates or retires the model behind an alias. The same prompt now produces slightly different labels or confidence values.
- Prompt edits. Someone adds an instruction to fix one case and breaks three others.
- Downstream changes. A team is renamed or merged, so a queue in
QUEUESno longer exists or no longer owns that label.
Offline evaluation only measures the past. Monitoring tells you when production has moved away from it.
What to record for every item
Log one structured record per routed item. You cannot diagnose a problem you did not record.
| Field | Why you need it |
|---|---|
| `item_id` or text hash | Join to human corrections later without storing raw text |
| `label`, `confidence` | Track label mix and confidence distribution |
| `queue` | See where items end up, including `human-triage` |
| `attempts`, `fallback` | Detect rising parse failures |
| `latency_ms` | Detect slowdowns and retry storms |
| `prompt_version`, `model_id` | Attribute a change in behavior to a change in configuration |
Support messages often contain names, emails, and card fragments. Log a hash and the text length, not the text. If you need raw text for error analysis, store it in a separate, access-controlled place with a retention limit.
The classify function from earlier returns ("other", 0.0) after failed attempts. A model that genuinely answers other with low confidence looks identical. To tell them apart, the wrapper below records the confidence value and flags the exact fallback signature. For a cleaner signal, you can change classify to return a third value indicating whether parsing succeeded.
import hashlib
import json
import logging
import time
logger = logging.getLogger("router")
PROMPT_VERSION = "2026-11-v3"
MODEL_ID = "example-model-2026-10"
def route_and_log(text, call_llm, threshold=0.7):
start = time.perf_counter()
label, confidence = classify(text, call_llm)
latency_ms = round((time.perf_counter() - start) * 1000)
if confidence < threshold:
queue = "human-triage"
else:
queue = QUEUES.get(label, "human-triage")
record = {
"item": hashlib.sha256(text.encode("utf-8")).hexdigest()[:16],
"chars": len(text),
"label": label,
"confidence": confidence,
"queue": queue,
"parse_fallback": label == "other" and confidence == 0.0,
"latency_ms": latency_ms,
"prompt_version": PROMPT_VERSION,
"model_id": MODEL_ID,
}
logger.info(json.dumps(record))
return queuePin MODEL_ID to a dated model version where your provider offers one. An alias such as "latest" changes under you, and your logs will then show a behavior change with no matching configuration change.
Signals worth watching
Compute these over a rolling window, such as the last 24 hours, and compare them to a baseline period you trust.
- Label distribution. The share of each label. A jump in
otheroften means a new topic has appeared. - Human-triage rate. The share of items below the confidence threshold or without a mapped queue. If it climbs, either confidence has shifted or inputs are harder.
- Parse-fallback and retry rate. A rise points to format problems, such as a model update that adds prose around the JSON.
- Confidence distribution. Watch the median and the 10th percentile. Models can become more or less confident without becoming more accurate, so a stable accuracy with shifted confidence means your threshold needs re-tuning.
- Latency and cost per item. Retries multiply both.
- Human override rate. How often a person in a queue reroutes an item. This is the closest thing to live accuracy you get for free.
Detecting a shift in label mix
A simple way to compare two label distributions is total variation distance: half the sum of the absolute differences in share per label. It ranges from 0 (identical) to 1 (disjoint).
from collections import Counter
def distribution(counts):
total = sum(counts.values())
if total == 0:
raise ValueError("counts must not be empty")
return {label: n / total for label, n in counts.items()}
def total_variation(baseline, current):
labels = set(baseline) | set(current)
return 0.5 * sum(
abs(baseline.get(label, 0.0) - current.get(label, 0.0))
for label in labels
)
baseline = distribution(Counter(billing=300, technical=450, account=150, other=100))
current = distribution(Counter(billing=280, technical=350, account=120, other=250))
shift = total_variation(baseline, current)
print(f"shift = {shift:.2f}")
if shift > 0.10:
print("ALERT: label mix has drifted; review recent 'other' items")This prints shift = 0.15 followed by the alert. The other share rose from 10% to 25% while technical fell, which is the typical signature of a new topic that the labels do not cover.
Pick the alert threshold from history. Compute the distance between consecutive normal weeks and set the alert above the largest ordinary value. Small windows are noisy: with 40 items per day, a 0.10 shift can be chance. Use windows with at least a few hundred items, or alert only when the shift persists for several windows.
A shift is a prompt to investigate, not proof of error. A marketing campaign can legitimately change the mix while accuracy stays the same.
Sampling for ground truth
Distribution checks cannot tell you whether labels are correct. For that you need people.
- Audit a random sample. Each week, have a reviewer label 50 to 100 randomly chosen items without seeing the model's answer. Compare to the model and track accuracy over time.
- Review the edges deliberately. Also sample items just above the confidence threshold. These are the ones most likely to be silently misrouted, since nothing sends them to a person.
- Capture overrides. When someone moves an item from one queue to another, store the corrected label next to the original prediction.
- Feed corrections back. Add reviewed items to your labeled set, including the hard ones. Keep a frozen "golden" subset that you never edit, so scores remain comparable across months.
Random samples and overrides are biased in different ways. Overrides only cover items a human happened to look at. Use the random audit for the accuracy number and the overrides for finding new failure patterns.
Changing the router safely
Every change to the prompt, labels, threshold, or model should pass a regression gate before it reaches production. The evaluate function from the evaluation chapter already does the work.
def passes_gate(golden, call_llm, baseline_accuracy, tolerance=0.02):
accuracy, confusion = evaluate(golden, call_llm)
return accuracy >= baseline_accuracy - tolerance, accuracy, confusionA gate on overall accuracy can hide a damaged label. If account drops from 90% to 60% while technical improves, the total barely moves. Also compare per-label recall from the confusion counts, and fail the gate if any label falls by more than a set margin.
Further practices:
- Version everything. Increment
PROMPT_VERSIONon every edit and keep old prompts in source control. - Shadow first. Run the new configuration on live traffic without acting on its output, and compare it to the current one. Disagreements are a cheap, targeted review list.
- Roll out gradually. Send 5% of traffic to the new version and watch the signals above before widening.
- Keep a rollback. Switching back to the previous prompt and model should be a one-line configuration change.
- Change one thing at a time. If you change the model and the prompt together, a regression cannot be attributed.
Maintaining the label set
Labels need upkeep like any other schema. Watch for these triggers:
- A growing
otherbucket. Ifotherexceeds roughly 10 to 15% of traffic, read a sample. If one theme makes up a large part of it, add a label with a clear definition. - Two labels that humans keep swapping. Merge them, or sharpen their definitions and add few-shot examples that sit on the boundary.
- A label nobody receives. Remove it or check that the definition is not misleading the model.
- Queue changes. Whenever
QUEUESchanges, rerun the golden set and test that every label has a destination. An unmapped label silently falls tohuman-triage, which looks safe but can bury your reviewers.
Adding or renaming a label invalidates old comparisons. Relabel the golden set under the new scheme and record a new baseline, noting the date.
Failure modes to plan for
- Provider outage or timeouts. Decide in advance whether to send items to
human-triage, queue them for retry, or use a rule-based fallback. Alert on error rate, not only on label mix. - Silent model deprecation. Subscribe to your provider's deprecation notices and schedule a re-evaluation before the retirement date.
- Feedback loops. If you train or choose examples from the router's own unreviewed output, you reinforce its mistakes. Use only human-confirmed labels.
- Alert fatigue. Too many alerts get ignored. Start with two or three signals (human-triage rate, parse-fallback rate, label shift) and add more only when a real incident would have been missed.
Exercise
Over a week, your router's overall accuracy on the weekly audit sample stays at 91%, but the share of items labeled other rises from 8% to 22%, and the human-triage rate doubles. Name two plausible causes and one next step for each.
Show answer
One cause is input drift: a new topic that the labels do not cover. The next step is to read a sample of the other items and, if a theme dominates, add a label with a definition and examples, then re-baseline the golden set. A second cause is a model or prompt change that lowered confidence or made the model more cautious. The next step is to check model_id and prompt_version in the logs for a change on the date of the shift, and rerun the golden set on the old and new configurations to compare per-label results. Accuracy can stay flat because the audit sample reflects the whole traffic mix and many other and triage items are still handled correctly by humans.
Exercise
Why should a regression gate check per-label recall as well as overall accuracy?
Show answer
Overall accuracy is dominated by the common labels. A change can badly hurt a rare label, such as account, while slightly improving a common one, and the total will barely move. Per-label recall from the confusion counts exposes that loss before deployment.