AI 客服機械人如何把 RAG 幻覺比例由 18% 降至 3%
Our AI Support Bot Invented a Refund Policy: How We Cut RAG Hallucinations From 18% to 3% in Production (Real Code)
作者重建其 RAG 客服機械人的處理流程,將含至少一項無來源支持主張的答案比例由 18% 降至 3%。改動包括加入相關度門檻及文件時效篩選、強制引用與拒答路徑、逐字引文檢查,以及由另一個小模型執行的忠實度評估。8 週後,忠實度評分為 0.96,政策風險事件降至 0,另有 9% 的問題轉交人工處理。
AI in Production: War Stories, Scenario #1. One real production incident: the alert, the triage (dead ends included), the root cause, the fix with runnable code, the measured result — and how to tell it in a senior interview. This is the hallucination incident.
Full original (canonical) on PrepStack: https://prepstack.co.in/blog/ai-production-scenario-1-rag-hallucinations
The incident
Our RAG-powered support bot answers ~520 tickets/month against a knowledge base of product docs, billing policies, and runbooks. Three weeks after launch, a CSM forwarded a screenshot: "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 a draft, not an old version. The model invented it, fluently and confidently.
We hand-labeled 200 recent answers with the support team. 18% contained at least one claim not supported by the retrieved documents. An airline famously lost a tribunal case because its chatbot invented a bereavement-fare policy and the court held the company to it. A hallucinating support bot is not a quality problem; it is a contract-writing machine.
Where it broke — four failure points, all live at once
question -> embed -> vector search (k=8, NO score floor [F1], NO freshness filter [F2])
-> PROMPT: "answer using the context" (no "I don't know", no citations [F3])
-> LLM answer -> user (NO verification [F4])
The refund question hit all four: it asked about annual plans, our docs only covered monthly, retrieval returned 8 weakly-related chunks [F1], one a deprecated 2023 promo doc [F2], the prompt demanded an answer [F3], and nothing stood between the model's guess and the customer [F4].
Triage — including the dead ends
- "Is the model bad?" We swapped in a larger model. 18% → 16%. Bigger models hallucinate more fluently, not less often, on bad context.
- "Temperature too high?" Changed the wording of hallucinations, not the rate. The problem was upstream of generation.
- "Is retrieval returning the right docs?" First real signal: the refund question's top chunk scored 0.61 cosine — well below the ~0.75 we saw on good answers. Retrieval was failing quietly.
- "Is the KB clean?" 11% of indexed chunks came from superseded docs.
Root cause: 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 wasn't a model defect — it was the designed behavior of a pipeline with no abstention path.
The broken pipeline — a POC you can run
# broken_rag.py - reproduces the failure. Do NOT ship this.
import anthropic
client = anthropic.Anthropic()
DOCS = [
"Refunds: monthly plans may be refunded within 14 days of purchase "
"if usage is below 1,000 API calls.",
"Billing cycles run from the 1st of each month.",
]
def answer(question: str) -> str:
context = "\n\n".join(DOCS) # [F1] no relevance check
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, # [F3]
messages=[{"role": "user", "content": question}],
)
return next(b.text for b in response.content if b.type == "text") # [F4] straight to user
print(answer("What is the refund policy for annual plans?"))
# Typical output: a fluent, invented policy for annual plans - the docs only cover monthly.
The fix — five layers, each catching what the last misses
Principle: every claim must be traceable to a retrieved source, and "I don't know" must be a first-class answer.
# Layer 1 + 2: retrieval gate (relevance floor + freshness filter)
def gate_retrieval(chunks: list[Chunk]) -> list[Chunk]:
fresh = [c for c in chunks if not c.superseded] # layer 2
strong = [c for c in fresh if c.score >= MIN_RELEVANCE] # layer 1 (e.g. 0.72)
return strong # an EMPTY result is VALID -> routes to abstention, not generation
# Layer 3: citation-forced generation with an explicit out
class Citation(BaseModel):
doc_id: str
quote: str # verbatim sentence from the source supporting the claim
class GroundedAnswer(BaseModel):
can_answer: bool # False when the context does not contain the answer
answer: str
citations: list[Citation]
SYSTEM = """Use ONLY the provided context. Every factual claim must carry a
verbatim citation. If the context does not contain the answer, set
can_answer=false - that is a GOOD outcome. Do not generalize from a
similar-but-different case (e.g. monthly vs annual)."""
# Layer 4: faithfulness judge - a SEPARATE, cheap model that never sees the question,
# so it can't be charmed into agreeing the answer is "helpful" - only that it's SUPPORTED.
def judge_faithfulness(answer, chunks) -> float:
# ... returns supported_claims / total_claims via a small model (Haiku-class) ...
...
# Layer 5: the pipeline, with abstention as a first-class path
def answer_question(question, retrieved) -> str:
chunks = gate_retrieval(retrieved)
if not chunks: return ABSTAIN # escalate to a human ticket
result = generate(question, chunks)
if not result.can_answer: return ABSTAIN
source_text = " ".join(c.text for c in chunks)
for cit in result.citations: # deterministic, no LLM
if cit.quote not in source_text: return ABSTAIN # fabricated citation -> abstain
if judge_faithfulness(result, chunks) < MIN_FAITHFULNESS: return ABSTAIN
return result.answer
Four things matter more than any prompt wording:
-
The empty result is valid.
gate_retrievalreturning[]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's its virtue. An LLM cannot talk its way past it. Catches fabricated citations with zero model calls. - The judge has a different job, not just a different model. It never sees the question, so "it's a reasonable answer" is not an escape hatch.
-
Every abstention logs a reason. Three weeks of
abstainlogs became our knowledge-base content roadmap.
"Hallucination" is 6 failure modes wearing one name
| # | Case | Caught by |
|---|---|---|
| 1 | Pure fabrication (the 60-day policy) | Judge (claims unsupported) |
| 2 | Wrong-source citation | Verbatim citation check |
| 3 | Stale truth (superseded promo doc) | Freshness filter (layer 2) |
| 4 | Near-miss generalization (monthly → annual) | Prompt rule + judge |
| 5 | Partial truth (real window, invented "no questions asked") | Judge (per-claim split) |
| 6 | Confident answer on garbage retrieval (0.61) | Relevance gate (layer 1) |
A fix that handles only one of these will look done and still burn you.
What it cost — and how we got the latency back
| Addition | Latency | Cost |
|---|---|---|
| Citation-forced structured output | ~0 | +15% output tokens |
| Verbatim citation check | <1 ms | $0 |
| Faithfulness judge (small model) | +400-600 ms | ~$0.0004/query |
We clawed the judge's latency back three ways: model tiering (judge on a 20x-cheaper small model; verification is narrower than generation), running the judge on the stream while the UI shows "checking sources" (~300 ms perceived, not 600), and prompt caching on the byte-stable system prompt + context (repeat-turn input cost −85%). Net: roughly cost-neutral per query, p95 +under 300 ms.
Results (8 weeks, same 200-answer protocol)
| Metric | Before | After |
|---|---|---|
| Answers with ≥1 unsupported claim | 18% | 3% |
| Faithfulness (judge-scored) | not measured | 0.96 |
| Policy-risk incidents reaching customers | ~2/month | 0 in 8 weeks |
| Abstention rate | 0% (by design!) | 9%, all escalated to humans |
The 9% abstention is the number stakeholders questioned — "the bot refuses one in eleven?" Yes. Before, those eleven got confident answers and two were wrong in ways a human had to clean up. An honest escalation beats a confident lie on every support metric we track, including CSAT. The remaining 3% is dominated by near-miss generalization — the hardest class. Zero isn't the target; zero undetected is.
In the interview
STAR, 60 seconds: "Our RAG bot was inventing policies — 18% unsupported claims, including a refund policy that didn't exist. Instead of swapping models, I rebuilt the pipeline around evidence: a retrieval gate with a relevance floor + freshness filter, citation-forced generation with an abstention path, a deterministic verbatim-quote check, and a cheap second-model faithfulness judge gating every answer. 18% → 3%, faithfulness 0.96, policy incidents to zero, and the 9% we escalate became our KB roadmap."
Follow-ups you'll get: why not a better model? (tried; 18%→16% — it's a pipeline problem). Who judges the judge? (a 150-pair golden set; 95% agreement with humans before any threshold ships). How'd you pick 0.72 / 0.85? (from labeled data, not vibes). What does it cost? (have the table). What still gets through? (near-miss generalization, ~3% — name your residual).
Originally published on PrepStack.
來源:DEV Community · dev.to