Our AI Support Bot Invented a Refund Policy — How We Cut RAG Hallucinations From 18% to 3% in Production
Our production RAG bot invented a refund policy. The broken pipeline, the real fix, every hallucination case, 18% to 3% — plus the interview answers.
- Author
- Randhir Jassal
- Published
- Reading time
- 22 min read
- Views
- 5 views
AI in Production: War Stories, Scenario #1. Every post in this series is one real production incident: the alert, the triage (dead ends included), the root cause, the fix with runnable code, the measured result — and then how to tell the story in a senior interview, with the follow-up questions you will actually get. No toy examples. This is the hallucination incident.
The incident
Mattrx Help is the RAG-powered support assistant inside Mattrx, our marketing SaaS. It answers roughly 520 support tickets a month against a knowledge base of product docs, billing policies, and runbooks. Three weeks after launch, a customer success manager forwarded a screenshot with the subject line "did we change the refund policy??"
The bot had told a customer:
"You are eligible for a full refund within 60 days of purchase, no questions asked."
Our actual policy was 14 days, conditional. There was no 60-day policy anywhere in the knowledge base — not in a draft, not in an old version. The model had invented it, fluently, politely, and with total confidence.
We pulled a sample of 200 recent answers and hand-labeled them with the support team. 18% contained at least one claim not supported by the retrieved documents. Most were harmless paraphrase drift. Some, like the refund answer, were liabilities. If that number sounds familiar, it should — an airline famously lost a tribunal case because its chatbot invented a bereavement-fare policy, and the court held the company to what the bot said. A hallucinating support bot is not a quality problem; it is a contract-writing machine.
Architecture: where it broke
This was the pipeline on the day of the incident. The failure points are marked [F1] to [F4] — all four were live at once.
MATTRX HELP - RAG PIPELINE (BEFORE)
User question
|
v
+----------------+ +---------------------+ +------------------+
| Embed question |---->| Vector search |---->| Top-k chunks |
| (embedding API)| | (pgvector, k=8) | | NO score floor |
+----------------+ +---------------------+ | NO freshness |
| filter [F1][F2] |
+--------+---------+
|
v
+-----------------------------------------------------------------+
| PROMPT: "Answer the user's question using the context below." |
| - no instruction for what to do when context is insufficient |
| - no requirement to cite sources [F3] |
+--------------------------------+--------------------------------+
|
v
+-----------------------+
| LLM generates answer |
+-----------+-----------+
|
v
+-----------------------+
| Answer sent to user |
| NO verification [F4] |
+-----------------------+
[F1] Retrieval has no relevance floor: k=8 chunks returned even when
the best match is garbage.
[F2] No freshness filter: superseded policy docs still retrievable.
[F3] Prompt neither forces citations nor allows "I don't know."
[F4] Nothing checks the answer against the sources before it ships.
The refund question hit all four: the customer asked about refunds for an annual plan, our docs only covered monthly plans, retrieval returned eight weakly-related chunks about billing [F1], one of them was a deprecated 2023 promo doc [F2], the prompt demanded an answer anyway [F3], and nothing stood between the model's best guess and the customer [F4].
Triage: what we checked first (including the dead ends)
- "Is the model bad?" — dead end. We swapped the generation model for a larger one. Hallucination rate moved from 18% to 16%. Bigger models hallucinate more fluently, not less often, when the pipeline feeds them bad context.
- "Is the temperature too high?" — dead end. Sampling settings changed the wording of hallucinations, not the rate. The problem was upstream of generation.
- "Is retrieval returning the right docs?" — first real signal. For the refund question, the top chunk's cosine similarity was 0.61 — well below the ~0.75 we saw on good answers. Retrieval was failing quietly and the prompt forced the model to improvise.
- "Is the knowledge base clean?" — second real signal. 11% of chunks in the index came from superseded documents. The embedding pipeline indexed everything and forgot nothing.
Root cause, stated plainly: the pipeline had no concept of "not enough evidence." Every question got k chunks and every set of k chunks got a confident answer. Hallucination was not a model defect; it was the designed behavior of a pipeline with no abstention path.
The broken pipeline — a POC you can run
This is a faithful miniature of the before-state. Run it and you can watch it hallucinate: ask it anything adjacent to, but not covered by, its documents.
# broken_rag.py - reproduces the failure. Do NOT ship this.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
DOCS = [
"Refunds: monthly plans may be refunded within 14 days of purchase "
"if usage is below 1,000 API calls. Contact billing@mattrx.example.",
"Billing cycles run from the 1st of each month. Invoices are emailed "
"within 3 business days of cycle close.",
]
def answer(question: str) -> str:
# [F1] no relevance check: we ALWAYS stuff everything we have
context = "\n\n".join(DOCS)
# [F3] prompt demands an answer, forbids nothing
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system="Answer the user's question using the context below.\n\n" + context,
messages=[{"role": "user", "content": question}],
)
# [F4] straight to the user, no verification
return next(b.text for b in response.content if b.type == "text")
print(answer("What is the refund policy for annual plans?"))
# Typical output: a fluent, invented policy for annual plans - the docs
# only cover monthly. Nothing in this code can even notice that.
The model is doing exactly what it was asked: be helpful using whatever it has. The bug is the pipeline's, not the model's.
The fix, layer by layer
We rebuilt the pipeline around one principle: every claim must be traceable to a retrieved source, and "I don't know" must be a first-class answer. Five layers, each catching what the previous one misses. This is the production code, trimmed only of company-internal imports.
# grounded_rag.py - the production pipeline. Python 3.11+, pip install anthropic pydantic
import json
import logging
import os
import time
from dataclasses import dataclass
from datetime import datetime, timezone
import anthropic
from pydantic import BaseModel, Field
log = logging.getLogger("mattrx.help.rag")
GENERATION_MODEL = os.getenv("RAG_GENERATION_MODEL", "claude-sonnet-5-5")
JUDGE_MODEL = os.getenv("RAG_JUDGE_MODEL", "claude-haiku-5-5")
MIN_RELEVANCE = float(os.getenv("RAG_MIN_RELEVANCE", "0.72")) # layer 1
MIN_FAITHFULNESS = float(os.getenv("RAG_MIN_FAITHFULNESS", "0.85")) # layer 4
client = anthropic.Anthropic(max_retries=3, timeout=30.0)
@dataclass(frozen=True)
class Chunk:
doc_id: str
text: str
score: float # cosine similarity from vector search
superseded: bool # layer 2: set by the ingestion pipeline
updated_at: datetime
# ---- Layer 1 + 2: retrieval gate (relevance floor + freshness filter) ----
def gate_retrieval(chunks: list[Chunk]) -> list[Chunk]:
"""Drop stale chunks, then drop weak matches. An empty result is a
VALID result - it routes to the abstention path, not to generation."""
fresh = [c for c in chunks if not c.superseded]
strong = [c for c in fresh if c.score >= MIN_RELEVANCE]
log.info("retrieval_gate", extra={
"in": len(chunks), "fresh": len(fresh), "strong": len(strong),
"top_score": max((c.score for c in chunks), default=0.0),
})
return strong
# ---- Layer 3: citation-forced generation with an explicit out ----
class Citation(BaseModel):
doc_id: str = Field(description="ID of the source chunk")
quote: str = Field(description="Verbatim sentence from that chunk supporting the claim")
class GroundedAnswer(BaseModel):
can_answer: bool = Field(description="False when the context does not contain the answer")
answer: str = Field(description="The answer, or empty string when can_answer is false")
citations: list[Citation]
SYSTEM = """You are Mattrx Help, a support assistant.
Rules, in priority order:
1. Use ONLY the provided context. Never use outside knowledge for policy,
pricing, or billing claims.
2. Every factual claim must carry a citation quoting the source verbatim.
3. If the context does not contain the answer, set can_answer=false. That
is a GOOD outcome, not a failure. Do not guess, extrapolate, or
generalize from a similar-but-different case (e.g., monthly vs annual).
"""
def generate(question: str, chunks: list[Chunk]) -> GroundedAnswer:
context = "\n\n".join(f"[{c.doc_id}] {c.text}" for c in chunks)
response = client.messages.parse(
model=GENERATION_MODEL,
max_tokens=2048,
system=SYSTEM + "\n\nContext:\n" + context,
messages=[{"role": "user", "content": question}],
output_format=GroundedAnswer, # schema-validated by the API
)
return response.parsed_output
# ---- Layer 4: faithfulness judge (cheap model, different job) ----
def judge_faithfulness(answer: GroundedAnswer, chunks: list[Chunk]) -> float:
"""Second model verifies the first. The judge sees ONLY answer + sources
(not the question), so it cannot be charmed into agreeing the answer is
'helpful' - it can only check that it is SUPPORTED."""
sources = "\n\n".join(f"[{c.doc_id}] {c.text}" for c in chunks)
response = client.messages.create(
model=JUDGE_MODEL,
max_tokens=256,
output_config={"format": {"type": "json_schema", "schema": {
"type": "object",
"properties": {
"supported_claims": {"type": "integer"},
"total_claims": {"type": "integer"},
"unsupported": {"type": "array", "items": {"type": "string"}},
},
"required": ["supported_claims", "total_claims", "unsupported"],
"additionalProperties": False,
}}},
messages=[{"role": "user", "content":
"Sources:\n" + sources +
"\n\nAnswer to verify:\n" + answer.answer +
"\n\nSplit the answer into factual claims. Count how many are "
"directly supported by the sources. List every unsupported claim."
}],
)
data = json.loads(next(b.text for b in response.content if b.type == "text"))
if data["total_claims"] == 0:
return 1.0
score = data["supported_claims"] / data["total_claims"]
if data["unsupported"]:
log.warning("unsupported_claims", extra={"claims": data["unsupported"]})
return score
# ---- Layer 5: the pipeline, with abstention as a first-class path ----
ABSTAIN = ("I don't have enough information to answer that reliably. "
"I've flagged this for our support team - you'll hear from a "
"human within one business day.")
def answer_question(question: str, retrieved: list[Chunk]) -> str:
t0 = time.monotonic()
chunks = gate_retrieval(retrieved)
if not chunks:
log.info("abstain", extra={"reason": "retrieval_gate"})
return ABSTAIN # escalates to a human ticket
result = generate(question, chunks)
if not result.can_answer:
log.info("abstain", extra={"reason": "model_declined"})
return ABSTAIN
# Citations must actually quote the sources - verbatim check, no LLM.
source_text = " ".join(c.text for c in chunks)
for cit in result.citations:
if cit.quote not in source_text:
log.warning("abstain", extra={"reason": "fabricated_citation",
"quote": cit.quote[:80]})
return ABSTAIN
score = judge_faithfulness(result, chunks)
if score < MIN_FAITHFULNESS:
log.warning("abstain", extra={"reason": "judge_rejected", "score": score})
return ABSTAIN
log.info("answered", extra={"faithfulness": score,
"latency_ms": int((time.monotonic() - t0) * 1000)})
return result.answer
Four things in this code matter more than any of the prompt wording:
- The empty result is valid.
gate_retrievalreturning[]is not an error branch; it is the system saying "escalate to a human." Before the fix, that state was unrepresentable. - The citation check is deterministic.
cit.quote not in source_textis dumb string containment, and that is its virtue — an LLM cannot talk its way past it. We catch fabricated citations (the sneakiest hallucination class) with zero model calls. - The judge has a different job, not just a different model. It never sees the question, so "well, it's a reasonable answer" is not an escape hatch. Supported or not supported, per claim.
- Every abstention logs a reason. Three weeks of
abstainlogs told us exactly which knowledge-base gaps to fill — abstention became our content roadmap.
MATTRX HELP - RAG PIPELINE (AFTER)
question -> embed -> vector search
|
[gate: score >= 0.72, not superseded]
| |
chunks empty
| |
v v
[generate: citations forced, ESCALATE TO HUMAN
can_answer=false allowed] (logged, ticketed)
| |
can_answer declined ----> ESCALATE
|
v
[verbatim citation check] --fail--> ESCALATE
|
v
[faithfulness judge >= 0.85] --fail--> ESCALATE
|
v
ANSWER SHIPS (with sources shown to the user)
Every hallucination case — and which layer catches it
"Hallucination" is six different failure modes wearing one name. A fix that only handles one of them will look done and still burn you. This is the full matrix we test against:
| # | Case | Example from our logs | Detection signal | Layer that catches it |
|---|---|---|---|---|
| 1 | Pure fabrication | The 60-day refund policy | No supporting source exists | Judge (claims unsupported) |
| 2 | Wrong-source citation | Correct-sounding claim, cites an unrelated doc | Quote not found in cited chunk | Verbatim citation check |
| 3 | Stale truth | Quotes a real but superseded promo doc | Doc marked superseded at ingestion | Freshness filter (layer 2) |
| 4 | Near-miss generalization | Monthly-plan policy applied to annual plans | Model told not to extrapolate; judge flags the leap | Prompt rule 3 + judge |
| 5 | Partial truth | Real 14-day window, invented "no questions asked" | One claim supported, one not | Judge (per-claim split) |
| 6 | Confident answer on garbage retrieval | Best chunk similarity 0.61, answers anyway | Top score below floor | Relevance gate (layer 1) |
The decision table we keep in the runbook: symptom on the left, first layer to check on the right. When hallucinations resurface (they do — every knowledge-base migration shifts score distributions), this table turns a vague "the bot is lying again" into a 10-minute diagnosis.
What the guardrails cost — and how we got the latency back
Nothing here is free. Honest numbers from our traces, per answered question:
| Addition | Latency added | Cost added |
|---|---|---|
| Citation-forced structured output | ~0 (same call) | ~15% more output tokens |
| Verbatim citation check | <1 ms | $0 |
| Faithfulness judge (Haiku-class model) | +400-600 ms | ~$0.0004/query |
| Retrieval gate + freshness filter | <5 ms | $0 |
The judge's 400-600 ms mattered — p95 was already under pressure. Three changes clawed it back:
- Model tiering. The judge runs on a small fast model (
claude-haiku-5-5); verification is a narrower task than generation, and a 20x cheaper model does it reliably. Using the generation model as its own judge would have doubled cost and been less trustworthy (models grade their own work generously). - Judge runs on the stream, not after it. We stream the generated answer into the judge call as soon as generation completes, while the UI renders a "checking sources" state. Perceived latency added: ~300 ms, not 600.
- Prompt caching on the system prompt + context. The system rules are byte-stable and cached; for multi-turn tickets the context chunks are cached too. Repeat-turn input cost dropped ~85%, which more than paid for the judge.
Net: the fully-guarded pipeline costs about the same per query as the naive one did, and p95 grew by under 300 ms.
Results
Eight weeks after rollout, on the same 200-answer hand-labeling protocol:
| Metric | Before | After |
|---|---|---|
| Answers with at least one unsupported claim | 18% | 3% |
| Faithfulness (automated, judge-scored) | not measured | 0.96 |
| Retrieval relevance (top-chunk mean) | not measured | 0.91 |
| Policy-risk incidents reaching customers | ~2/month | 0 in 8 weeks |
| Abstention rate | 0% (by design!) | 9%, all escalated to humans |
That 9% abstention rate is the number stakeholders questioned — "the bot refuses one in eleven questions?" Yes. Before, those eleven questions got confident answers and two of them were wrong in ways a human had to clean up later. An honest escalation beats a confident lie on every support metric we track, including CSAT.
The remaining 3% is dominated by case #4 (near-miss generalization) — the hardest class, because the claims are individually supported and the leap happens between them. We're attacking it with harder negatives in the judge's few-shot examples. Zero is not the target; zero undetected is.
In the interview
This incident is a complete senior-interview story. Here's how to tell it and what you'll be asked next.
The 60-second STAR version: "Our RAG support bot was inventing policies — 18% of answers contained unsupported claims, including a refund policy that didn't exist (Situation). I owned getting that to a safe level without killing answer coverage (Task). Instead of swapping models, I rebuilt the pipeline around evidence: a retrieval gate with a relevance floor and freshness filter, citation-forced generation with an explicit abstention path, a deterministic verbatim-quote check, and a cheap second-model faithfulness judge gating every answer (Action). Hallucinations went from 18% to 3% with faithfulness at 0.96, policy incidents went to zero over eight weeks, and the 9% of questions we now escalate to humans became our roadmap for knowledge-base gaps (Result)."
The five follow-ups you will get — and senior answers:
- "Why not just use a better model?" — We tried; 18% to 16%. Hallucination under weak retrieval is pipeline-designed behavior, not model weakness. The senior signal is attacking the system, not the model.
- "Your judge is also an LLM — who judges the judge?" — A golden set: ~150 hand-labeled answer/source pairs, half with planted unsupported claims. The judge must hit 95% agreement with human labels before any threshold or prompt change ships. Deterministic checks (verbatim quotes) carry what they can so the judge carries less.
- "How did you pick 0.72 and 0.85?" — From data, not vibes: we plotted similarity scores for the hand-labeled good/bad answers and picked the floor that excluded 90% of bad-retrieval cases while keeping 97% of good ones. Thresholds live in env vars because they're knowledge-base-dependent and will need retuning after every migration.
- "What does this cost you in latency and money?" — Have the table ready: ~300 ms perceived, roughly cost-neutral after caching and tiering. Knowing your guardrails' price is a strong senior signal; "we added a judge" without numbers is a junior one.
- "What still gets through?" — Near-miss generalization, ~3%. Naming your residual failure mode — and your plan for it — beats claiming victory. Interviewers probe for honesty at the boundary.
Senior signals in this story: you measured before fixing (the 200-answer labeling), you made abstention a feature with an owner (escalation to humans), you put a deterministic check before a probabilistic one, and you can state the cost of every safeguard.
Pitfalls
- Asking the generator to self-verify. "Double-check your answer" in the same prompt is nearly free and nearly useless — the model that made the error re-makes it. Verification needs a separate call with separate information.
- Forcing citations without checking them. Citation formats are easy for a model to produce and easy to fabricate. The verbatim containment check is the teeth; the citation format alone is decoration.
- Treating abstention as an error metric. If "I don't know" counts against the bot, someone will tune it away and you'll be back at 18%. Pair abstention rate with escalation outcomes instead.
- One global relevance threshold forever. Every re-embedding, chunking change, or KB migration shifts the score distribution. Re-derive thresholds from labeled data after each one.
- Shipping the judge without a budget. A judge on every token of a long answer can cost more than generation. Cap judged claims, use a small model, cache sources.
Continue the series
This is Scenario #1 of AI in Production: War Stories. Next: the morning our agent bill hit $0.90 per run — cost explosions, runaway loops, and model tiering. The series hub with all 12 incidents is coming; these deep dives pair with our interview question banks:
- Generative AI Interview Questions for Senior Engineers — 55 Deep Answers
- AI Agents Interview Questions — 50 Deep Answers on Agentic Workflows, Multi-Agent & MCP
- Build Reliable AI Agents: Loop, Planning, Tools, Memory, Guardrails
Further reading
- RAGAS faithfulness metrics — the formal version of our judge's claim-splitting approach
- The Moffatt v. Air Canada tribunal decision — the legal case for why hallucinated policies are company statements
- Anthropic's docs on structured outputs — the schema-enforcement mechanism used in
generate()
Questions about this incident, or fighting a hallucinating bot of your own? Email me at randhir.jassal@gmail.com — I read everything.
Get the next issue
A short, curated email with the newest posts and questions.