Hallucination Detection: Spotting Confabulation
Confidently wrong by construction
A language model has no internal fact database to consult. It samples the next token from a distribution shaped by statistical patterns in training text, which means it produces the most plausible continuation, not the most verified one. When the plausible continuation happens to be true, we call it knowledge. When it is not, we call it a hallucination â and from the model's side there is no difference in the process, and often no difference in confidence either.
That is what makes confabulation dangerous in production: fluency and reliability are uncorrelated. A fabricated citation reads exactly like a real one, and a wrong dosage is delivered in the same calm, well-structured prose as a correct one. Detection therefore cannot rely on the model's own tone. You need external checks â against a knowledge base, against retrieved documents, against the model's own consistency under resampling â positioned in the request path where a bad answer can still be stopped before a user acts on it.
Five failure modes worth testing separately
Not all confabulation is the same, and separating them tells you which fix applies.
| Type | Example | Typical cause | Best detector |
|---|---|---|---|
| Factual error | Wrong founding date | Training-data gaps | Knowledge lookup |
| Fabricated citation | Invented paper and authors | Pattern completion of citation style | DOI or library lookup |
| Internal inconsistency | Two contradictory figures in one answer | Long generation with no plan | Cross-sentence entailment |
| Temporal confusion | Correct fact, wrong year attached | Date drift in training data | Field extraction and checks |
| Unfaithful reasoning | Right answer, unsupported working | Pattern matching on answer style | Step-by-step verification |
The last row is the subtle one. A model can reach a correct answer through invented reasoning, and if your product shows users its working, that reasoning becomes a hallucination of its own â one they are more likely to trust precisely because it looks rigorous.
Extracting claims and verifying them
Detection starts by turning prose into checkable statements. A claim extractor pulls the factual sentences, then each claim is checked against a source you trust: your own document store, a structured database, or a search index restricted to domains you have vetted.
import re
from dataclasses import dataclass
NUMBER = re.compile(r"\b\d[\d,.]*%?\b")
YEAR = re.compile(r"\b(?:19|20)\d{2}\b")
@dataclass
class Claim:
text: str
kind: str # date | number | assertion
supported: bool = False
confidence: float = 0.0
def extract_claims(response: str) -> list:
claims = []
for sentence in re.split(r"(?<=[.!?])\s+", response.strip()):
if YEAR.search(sentence):
claims.append(Claim(sentence, "date"))
elif NUMBER.search(sentence):
claims.append(Claim(sentence, "number"))
elif re.search(r"\b(according to|study|report|research)\b", sentence, re.I):
claims.append(Claim(sentence, "assertion"))
return claims
def verify_against_context(claim: Claim, context: str) -> Claim:
"""Grounding test: is most of the claim's content present in context?"""
tokens = set(re.findall(r"[a-z0-9]+", claim.text.lower()))
ctx = set(re.findall(r"[a-z0-9]+", context.lower()))
overlap = len(tokens & ctx) / max(len(tokens), 1)
claim.supported = overlap >= 0.6
claim.confidence = overlap
return claim
Lexical overlap is a blunt instrument â it misses paraphrase â but it catches the highest-severity class cheaply: answers that assert something with no grounding in the documents you retrieved. When the stakes justify the cost, replace the overlap test with a natural-language inference model that returns entailment, contradiction, or neutral.
Reading model confidence as a weak signal
Token log-probabilities give you a free, noisy signal. Text with consistently low likelihood is more often drifting into invention, because the model is sampling from the thin tail of its distribution rather than the confident head.
import torch
def mean_logprob(model, tokenizer, prompt: str, completion: str) -> float:
prompt_ids = tokenizer(prompt, return_tensors="pt").input_ids
full_ids = tokenizer(prompt + completion, return_tensors="pt").input_ids
labels = full_ids.clone()
labels[:, :prompt_ids.shape[1]] = -100 # score only the completion
with torch.no_grad():
logits = model(full_ids).logits
logprobs = torch.log_softmax(logits[:, :-1, :], dim=-1)
token_lp = logprobs.gather(-1, labels[:, 1:].unsqueeze(-1)).squeeze(-1)
mask = labels[:, 1:] != -100
return (token_lp * mask).sum().item() / mask.sum().item()
def should_review(model, tokenizer, prompt, answer, threshold=-1.8) -> bool:
return mean_logprob(model, tokenizer, prompt, answer) < threshold
Two caveats keep this honest. Calibration is model-specific, so set thresholds from a labelled set of correct and hallucinated answers rather than picking a round number. Low likelihood also flags unusual but correct phrasing â rare names, technical jargon â so treat the signal as a routing rule that escalates answers to review, never as an automatic rejection.
Grounding answers with retrieval
The strongest practical mitigation is to make the model answer from provided documents and then check that it actually did. Retrieval narrows the surface where invention can happen, and a post-hoc grounding check verifies the result.
class GroundedGenerator:
def __init__(self, retriever, llm, min_support=0.6):
self.retriever = retriever
self.llm = llm
self.min_support = min_support
def answer(self, question: str) -> dict:
docs = self.retriever.search(question, k=5)
context = "\n\n".join(d.text for d in docs)
prompt = (
"Answer using only this context. If the context does not contain "
"the answer, reply exactly: INSUFFICIENT CONTEXT\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
answer = self.llm.generate(prompt, temperature=0.0)
if answer.strip() == "INSUFFICIENT CONTEXT":
return {"answer": None, "status": "abstained"}
claims = extract_claims(answer)
checked = [verify_against_context(c, context) for c in claims]
support = sum(c.supported for c in checked) / max(len(checked), 1)
return {
"answer": answer,
"support": support,
"status": "grounded" if support >= self.min_support else "needs_review",
"unsupported": [c.text for c in checked if not c.supported],
}
The abstention branch matters as much as the check. A system allowed to say it does not know converts an unverifiable answer into an honest one, which is the better user experience and always the better audit trail.
Sampling for self-consistency
Ask the same question several times at a nonzero temperature and compare the answers. Genuine facts repeat; invented details flicker between samples â one run names Berlin, another Vienna. Agreement across samples is not proof of truth, but disagreement is a reliable red flag, especially for dates, quantities, and proper nouns.
In practice, run three to five samples, extract the structured facts from each, and compare them. If the numbers agree, ship the first answer. If they diverge, either retrieve better context or route the query to human review. This costs extra inference, so reserve it for high-value queries: medical, legal, financial, or anything a user might act on without checking.
Deciding what the system does when detection fires
A detector that raises a flag but has nowhere to send it is theatre, so the routing policy must be designed alongside the checks themselves. Every signal lands somewhere on a spectrum from silent accept to hard block, and the right position depends on consequence rather than on how easy the flag was to build.
Consider three products with identical detectors. A brainstorming assistant can accept a low-confidence answer and let the user filter it, because a wrong suggestion costs nothing. An internal knowledge search should append the retrieved sources and mark unsupported sentences, because the user is making decisions with the output. A medication or billing answer must abstain and escalate, because the cost of silence is severe. The same detector output, routed three different ways, produces three completely different risk profiles.
| Signal strength | Cheap product | Medium stakes | High stakes |
|---|---|---|---|
| Fully grounded | Show answer | Show answer with sources | Show answer with sources |
| Low support | Show with caveat | Rewrite or abstain | Abstain and escalate |
| Contradictory samples | Show best sample | Hold for review | Block and notify |
| Blocked category | Refuse politely | Refuse and log | Refuse, log, alert owner |
Write the routing table down before launch and version it with the rest of the system. When a false negative reaches a user, the question you want answered is not only why the detector missed it, but why the policy let that class of output through unreviewed.
Assembling a detection pipeline that holds up
Each detector has blind spots, and pretending otherwise recreates the original problem. Entailment models over-accept fluent nonsense. Overlap checks cannot judge a claim that contradicts the world while sharing its vocabulary with the context. Log-probabilities are opaque and shift between checkpoints. All of them degrade silently when your prompt or model version changes.
| Layer | Catches | Cost | Placement |
|---|---|---|---|
| Retrieval grounding | Invented facts absent from sources | Retrieval latency | Before the answer is shown |
| Self-consistency | Unstable details under resampling | 3 to 5 times inference | High-value queries only |
| Claim verification | Unsupported assertions in prose | One extra model call | On flagged answers |
| Human review | Everything the models miss | Analyst time | Sampled plus escalations |
Measure the false-negative rate of the whole stack on known-bad answers drawn from your own logs. A detector that never fires feels reassuring while catching almost nothing, and only replaying real failures tells you which layer is dead.
Common Mistakes
Treating the model's stated confidence as a probability of being right
Fix: Calibrate against labelled examples; verbal confidence is stylistic and barely correlated with accuracy.
Checking only the final answer, not the reasoning shown to users
Fix: Verify intermediate claims too â unfaithful reasoning misleads even when the conclusion is correct.
Assuming retrieval alone eliminates hallucination
Fix: Add a grounding check: models blend retrieved facts with prior beliefs whenever context is thin.
Rejecting answers on low log-probability without calibration
Fix: Derive thresholds from your own correct and incorrect samples, and escalate rather than block.
Best Practices
- Allow abstention and design the interface for it; users trust a system that admits gaps more than one that never does.
- Log every flagged answer together with its retrieved context so detector quality can be measured over time.
- Split hallucination metrics by claim type, because a fix for wrong dates does nothing for invented citations.
- Replay a sampled slice of live traffic through the detectors weekly to catch drift before users report it.
Key Takeaways
- Hallucination is a property of the generation process, not a mistake the model notices; fluency says nothing about truth.
- Separate failure types first, because wrong dates, fabricated citations, and contradictions need different detectors.
- Claim extraction plus context verification is the cheapest detector that meaningfully reduces unsupported assertions.
- Log-probability and self-consistency signals are good for routing to review but must be calibrated before use.
- Retrieval grounding, an explicit abstention path, and layered checks give the only production arrangement that holds up.