OOD Guardrails for a Domain-Restricted Financial Chatbot
Machine LearningModel answerLast updated
Design a low-latency pipeline that classifies chatbot queries as in-domain or out-of-domain, routes them safely, and stays calibrated as traffic drifts.
Context
A customer-facing assistant answers questions about personal finance, grounded in a curated corpus of corporate documents. Traffic has outgrown the corpus: users now ask about medical symptoms, legal disputes, and everyday small talk. You must design the guardrail that decides, for each incoming query, whether it is answerable from the corpus, adjacent-but-unsupported, or clearly outside scope — and what the system does with each verdict.
What to deliver
- An end-to-end architecture for the real-time decision path, plus any secondary check placed around generation.
- The signals you would compute and why each one earns its latency.
- A routing policy for each verdict class, including refusals and handoffs.
- How thresholds are set given that error costs are asymmetric, and how humans keep the thresholds honest over time.
- A monitoring plan that distinguishes "users are phrasing things differently" from "users are asking about new topics."
- How the system accommodates a new domain or an expanded corpus without retraining a large model.
Constraints
- Sustained load of roughly 5,000 queries per second; size for a few times peak.
- Detection latency must stay under 50 ms at p99 on the synchronous path.
- New domains and corpus updates must be absorbed without full model retraining.
Edge cases to address
- The query is financial in topic but not covered by the corpus (a knowledge gap, not a scope violation).
- The query is in-domain but written in another language, filled with slang, or misspelled.
- The query starts benign and drifts into a prohibited topic partway through the generated answer.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing the problem
This is a guardrail design question. The interviewer is looking for four things: which detection signals actually fit the latency budget, how you reason about asymmetric error costs, how the system absorbs new domains cheaply, and how human feedback keeps it from silently degrading. Lead with clarification, then architecture, then policy, then the loop.
1. Clarify before designing
Pin down the taxonomy first, because it drives everything downstream:
- In-domain and covered — answerable from the corpus.
- In-domain but uncovered — a legitimate finance question the corpus doesn't address. This is a knowledge gap, not a scope violation, and deserves a different message ("I don't have that") than a refusal.
- High-risk out-of-scope — medical, legal, tax advice the product is not licensed to give. Treat a mishandled one as a compliance incident.
- Benign out-of-scope — chit-chat; a wrong routing decision here is a minor UX cost.
- Abuse / prompt injection — separate classifier, but the same routing layer.
Also confirm scale: 5k QPS sustained, plan for ~15k at peak (~400M+ queries/day). The 50 ms budget applies to the pre-generation detector; the post-generation check overlaps decoding and doesn't count against it.
2. Request path
- Normalize (~1 ms): language ID, PII scrubbing.
- Encode (5–10 ms): a frozen small sentence encoder (20–100M parameters) on GPU with short dynamic batching. At a few thousand short queries per GPU per second, budget roughly 6–8 GPUs at peak with N+2 redundancy.
- Score (≤5 ms, in parallel):
- kNN distance to the nearest indexed corpus chunks in an approximate index — the core "is this covered" signal.
- Class-conditional distance to per-topic Gaussians fit on in-domain queries, which catches topical proximity that raw nearest-neighbor distance misses.
- A small classifier head on the frozen embedding, trained on in-domain queries plus curated out-of-scope exemplars, producing an energy-style score and a predicted category.
- Cheap lexical features: length, finance-term density, presence of medical/legal vocabulary.
- Fuse with a logistic combiner, calibrated (isotonic or Platt) into a probability. Calibration matters more than raw accuracy because the thresholds are expressed as probabilities.
- Route per the policy below.
- Post-generation check, overlapping decoding: maximum retrieval similarity of the context actually used, an entailment check that the answer is supported by retrieved chunks, and a topic classifier over the generated text. This is what catches an answer that starts on-topic and slides into medical advice.
Total budget lands around 15–25 ms p99, leaving headroom.
3. Semantic OOD versus covariate shift
This distinction is the most common place candidates lose points. Two queries both far from the corpus in embedding space can mean opposite things:
- Semantic OOD: "what dose of ibuprofen should I take" — genuinely out of scope.
- Covariate shift: a Spanish-language or slang-heavy version of "how do I roll over a 401k" — in scope, phrased unusually.
A distance-only detector refuses both. Mitigations: use a multilingual, typo-robust encoder; augment in-domain exemplars with paraphrases, translations, and noisy variants; and monitor the two phenomena with different metrics (a p_ood shift among human-labeled in-domain traffic signals covariate shift; new dense clusters among rejected traffic signals semantic shift).
Why not inline perplexity? An in-domain language model's perplexity is a decent style-shift signal but is expensive and noisy on short text — it punishes typos and slang, which are exactly the cases you want to accept. Compute it asynchronously for monitoring instead.
Adapting without retraining: the encoder stays frozen. kNN and Gaussian statistics are non-parametric — adding a domain means inserting embeddings and recomputing means/covariances in minutes. Only the tiny head and combiner need refitting, both cheap.
4. Routing policy
| Verdict | Action |
|---|---|
| In-domain, covered | Normal retrieval + primary model |
| Gray zone | Conservative prompt + mandatory post-check, or a clarifying question |
| Benign out-of-scope | Small general model with a hard "no advice" instruction, or a template |
| High-risk out-of-scope | Polite refusal + referral; never generate an answer |
| In-domain, uncovered | "I don't have that information" + optional human handoff |
| Abuse | Refuse and rate-limit |
Note that humans cannot sit synchronously in the path at this volume — even 1% of traffic is 50 QPS. Reserve live human routing for authenticated high-value sessions; everything else goes to human labelers asynchronously.
5. Thresholds and asymmetric costs
Define the positive class as out-of-scope. A false negative (serving advice on an unauthorized topic) is a regulatory and liability event. A false positive (refusing a valid question) is churn and a support ticket. These costs differ by category, so set thresholds per category rather than one global number:
threshold_c minimizes C_FN,c · FN_c(t) + C_FP · FP(t)
In practice: high-risk categories target 98–99% recall and tolerate extra false positives; chit-chat favors precision; the global constraint is keeping the in-domain refusal rate at roughly 1–2%. Defense in depth is why the pre-filter doesn't need to be maximally paranoid — the post-generation check cleans up borderline cases.
6. Closing the loop
Log per request: signals, fused probability, decision, route, corpus and detector versions, and a downstream outcome (rephrase after refusal, thumbs-down, appeal). Keep scalar features for all traffic plus full embeddings for a 5–10% sample and for every gray/refused case.
Monitor input drift (distributional distance on embedding projections vs. a reference window, language mix, topic-cluster occupancy), score drift (reject and gray rates sliced by locale, channel, corpus version), and outcome proxies (rephrase rate, post-check failure rate — a pre-filter miss caught downstream). Run a clustering pass daily over gray and refused embeddings; a large coherent new cluster is either legitimate demand you should add to the corpus or a policy gap you should block explicitly.
Finally, sample adjudicated gray-zone cases weekly, re-estimate the thresholds and combiner on them, and track a reliability curve — not just the score histogram. A detector whose scores drift but whose calibration holds is healthy; one whose calibration silently degrades is the failure mode that burns you in production.
Common mistakes to avoid: treating knowledge gaps as scope violations, using a single global threshold, measuring only distance-to-corpus without handling style shift, putting perplexity or a second LLM in the synchronous path, and monitoring score distributions without ever re-labeling the gray zone.