GOAT EngineerPreparing your learning space…

AI Engineering · Concept Library · Free article

LLM Hallucination

A hallucination is a fluent, confident, wrong answer, and it is what a next-token predictor does when it has no grounds to answer and no way to stop. That makes it structural rather than a bug you can patch, so the honest target is a bounded rate and never zero.

A hallucination is a fluent, confident, wrong answer, and it is not a glitch. A model is built to produce the most plausible next token, not the most true one, with no fact database to check against and no built-in “I don’t know.” So when it lacks the knowledge, its only move is to invent something that sounds right. You do not eliminate this; you design against it, with grounding, an honest abstain path, detection signals, verification, and measurement. This page is the mental model plus the practical toolbox: what it is, the kinds, how to detect it, the defense ladder, how the field measures it, and the code you write.

A customer asks Wrenlet whether their refund covers currency conversion. It answers warmly and precisely, quoting “section 7.4 of the refund policy”: a section that has never existed. The wording is confident, the format is professional, and the fact is fabricated. No exception was thrown, no log line went red. This is the failure mode that will hurt you most in production, because it looks exactly like success.

To handle it you first have to accept an uncomfortable truth: this is the model working as designed. Watch it happen, then we will unpack why, and build the toolbox that bounds it.

The interactive version of this example is available when JavaScript loads.

Two things in that panel are the whole page in miniature. Press it again and the invented section changes: a different cap, a different settlement window, a different confirmation prefix, each delivered in the same even, professional register. Nothing in the tone marks any of them as invented, because nothing in the model distinguishes them from a real answer. Then flip the abstain switch and the same question gets an honest refusal instead. Nothing about the model's knowledge changed between those two outputs. What changed is whether stopping was an option it was given, which is why the fixes later on this page are about the system around the model rather than about the model.

Why do LLMs hallucinate?

Because a model has no grounds to refuse and no facts to check against, so the most plausible continuation is a confident sentence. Recall the one thing a model does: predict the most plausible next token (see how LLMs work). It has no lookup table of facts, no notion of a source of truth, and, unless you build one, no default option to stop and say “I don’t know.” Ask it about something it never learned well (a niche policy, a post-cutoff event, an obscure entity) and it cannot return nothing. The most probable continuation is a confident, well-formed sentence, so that is what it produces. The fabrication is not a short-circuit; it is the machine doing its job on a question it has no grounds to answer.

Where does a hallucination come from?

From one of three places, and which one decides which fix works: the pretraining data never held the fact, the training objective rewarded a guess over a shrug, or the decoding committed to a wrong token early and stayed consistent with it. “Structural” is not hand-waving. You can point at exactly where in the pipeline the falsehood enters. Surveys of the field (Huang et al., 2023/2025) split the causes into three, and each one points at a different lever:

Where falsehoods enter, and the lever each one hands you
SourceWhat goes wrongThe lever it points to
Data (pretraining)Facts that appeared rarely or never, a one-off policy, a fact past the training cutoff, were never learned. There is a floor here: for facts seen once or not at all, the base model has nothing to recall.Bring the fact in at request time (retrieval / grounding).
Training (objective)The model is optimized to produce plausible, helpful-sounding text, and, as you will see, practically rewarded for guessing over admitting doubt.Reward abstention; tune and prompt for “I don’t know.”
Inference (decoding)Sampling can commit to a wrong early token, and everything after has to stay consistent with it, so one slip cascades into a confident wrong paragraph.Verify the output; detect low-consistency answers before trusting them.

What kinds of hallucination are there?

Four that matter, along two independent axes: false about the world, false about the source you handed it, a fabricated citation, or an invented instruction. “Hallucination” is a bucket. Two independent questions carve it into the pieces that actually change your engineering. First: is it false about the world, or false about the source you handed it? That is factuality vs faithfulness, the distinction that decides whether retrieval even helps.

Four kinds, and why the split matters
KindWhat it looks likeThe fix it points to
Factuality errorFree-floating false fact, untrue of the world: “your plan includes 24/7 phone support” when it does not.Ground the model in real data (retrieval); it can’t invent what it’s given.
Faithfulness errorContradicts the source you provided: the retrieved doc says 100 req/min, the answer says 1,000.Verification against the source; grounding alone does not guarantee it.
Citation fabricationReal-sounding but nonexistent doc sections, URLs, API methods, or ticket numbers.Make it cite retrievable sources and verify the citation resolves.
Instruction hallucinationInvents or ignores constraints: answers a question you didn’t ask, or makes up a policy rule.Tighter prompts + checks that the output obeys the stated constraints.

The second question is orthogonal: is the output inconsistent with the source it was given, or does it add things the source never mentioned? That is the older intrinsic vs extrinsic split (Ji et al., 2023): intrinsic = it contradicts the provided text; extrinsic = it adds ungrounded content that may or may not happen to be true. Intrinsic errors are always faithfulness failures; extrinsic ones straddle: ungrounded, but not necessarily false.

Why models are practically trained to bluff

There is a second, sharper reason models fabricate: for years we have rewarded them for it. Most benchmarks score an answer as right or wrong and give an “I don’t know” the same zero as a confident mistake. Under that scoring, guessing is free, a blind guess sometimes lands, an abstention never scores, so the behavior that maximizes the benchmark is to always answer, never abstain. A 2025 analysis from OpenAI, Why Language Models Hallucinate, makes the argument precisely: hallucination starts as an unavoidable statistical floor in pretraining (you cannot generate only true statements if you cannot perfectly tell true from false), and it survives post-training because the evaluations we optimize on almost never reward calibrated uncertainty. Drag the dial and feel the incentive for yourself.

The interactive version of this example is available when JavaScript loads.

The engineering lesson is not “wait for better models.” It is that abstention has to be a first-class, rewarded output in your system, and in your evals. When you build an internal test set, score a confident wrong answer as worse than an honest “I can’t find that,” and measure the model’s answer rate alongside its accuracy. One published comparison shows the whole problem in three numbers. In the GPT-5 system card's SimpleQA table, a model that abstained on 52% of that hard short-fact test was wrong on 26% of the questions, against 75% for a model that answered nearly everything. Now look at what a leaderboard would print. Its headline accuracy is the lower of the two, 22% against 24%, because every abstention scores the same as a wrong answer. Divide by what each model actually attempted and the ranking flips: about 46% against 24% on the questions it was willing to answer. Two cautions, though. Those are two different models, one a generation older, not one model under two settings. And that 46% is arithmetic on the published table, 22 over the 48 it attempted, rather than a figure anybody published.

You cannot trust the model’s confidence

The instinctive fix, “only answer when the model is confident”, runs into a wall: a model’s expressed confidence is poorly calibrated, meaning its certainty does not reliably track its correctness. And it gets worse after tuning. OpenAI’s own GPT-4 technical report (2023) showed the pretrained model was well-calibrated, and the preference-tuning that makes it pleasant and assertive measurably degraded that calibration. Its Figure 8 says so in one line: “The post-training hurts calibration significantly.” It learned to sound sure. So the fluent, self-assured tone that reads as “this one’s solid” is exactly the signal you cannot lean on. Watch the gap open up:

The interactive version of this example is available when JavaScript loads.

Because the model’s own certainty is untrustworthy, most untrustworthy precisely when it is wrong, you reach for external checks instead of the model’s vibe. Those checks are the next section.

How do you detect a hallucination?

You will never catch every fabrication, but several signals are far more reliable than the model’s self-assurance, and the cheapest one is almost free. The reliable pattern is a ladder: run the cheap structural check first, escalate to sampling-based signals for open-ended generation, and reserve the expensive judge for what’s left.

The detection ladder

  • Citation-resolves check (nearly free). Make the model cite the passage it used, then programmatically confirm the citation exists and the quoted span is a real substring of a document you actually retrieved. This catches the classic fabricated-reference with almost no machine learning: a made-up “section 7.4” fails the check instantly.
  • Self-consistency (a few extra calls). Ask the same question several times and compare. When the model is standing on something real the samples agree; when it is inventing, each run makes up different details, so wide disagreement is a strong fabrication smell (the self-check idea, Manakul et al., 2023). Agreement is only weak evidence of truth, a model can be consistently wrong, but its absence is a loud alarm.
  • Semantic-entropy signal. A refinement of self-consistency: sample several answers, cluster them by meaning (not wording, using an entailment check), and measure the spread across meaning-clusters. High spread means the model is scattering probability over mutually contradictory answers: a well-validated fabrication signal (Farquhar et al., Nature 2024). Raw token-probabilities alone are weak, because there are many correct ways to phrase a true answer.
  • Grounding / entailment check (a judge call). For grounded answers, decompose the output into atomic claims and verify each is entailed by the retrieved source: via a trained entailment model or a strict LLM-judge that sees only the source. This is the backbone of faithfulness scoring and the direct measure of intrinsic errors.

The interactive version of this example is available when JavaScript loads.

How do you reduce hallucinations?

You layer six defenses, roughly in order of how much each removes: do not ask it to know, ground it, constrain the shape, make it cite and let it abstain, verify before trusting, and escalate by blast radius. No single trick removes hallucination, so production systems layer several, each catching what the last let through. Roughly in order of how much of the problem each one removes, rather than how cheap it is to build:

The defense ladder

  1. Don’t ask it to know. If the fact is computable or queryable, make the model call the tool and return the tool’s value: a price, a balance, a policy section, a row count. This removes the fabrication surface instead of policing it, and for the refund question this page opened on it is the whole answer. The model routes; your systems answer.
  2. Ground it. Retrieve real, relevant text and instruct the model to answer only from it. This is RAG: the single biggest lever for factuality (it gets its own deep dive later in the course). Its own failure mode: if retrieval misses, or the model favors its memory over the passage, you get a faithfulness error anyway.
  3. Constrain the shape. Where the output is structured, force it into a schema, enum, or function-call arguments. This makes an invalid value (a made-up status code, an out-of-set category) impossible, though a well-formed value can still be factually wrong, so this polices structure, not truth.
  4. Make it cite, and abstain. Require the answer to quote the sentence it relied on, and give it an explicit, rewarded path to say “that isn’t in the provided material.” Then verify the citation actually resolves.
  5. Verify before trusting. Run a claim-check, self-consistency, or a plan-then-check pass on high-stakes answers; block or downgrade the ones that fail. A useful pattern is to have the model independently answer verification questions about its own draft: kept separate from the draft so its errors don’t bias the check (chain-of-verification, Dhuliawala et al., 2023).
  6. Escalate by blast radius. For anything costly to get wrong, money, legal, medical, an irreversible action, route to a human or require confirmation. Cheap, low-stakes drafts can tolerate more.

The interactive version of this example is available when JavaScript loads.

When is a hallucination actually acceptable? Decide by blast radius
Use caseTolerancePosture
Brainstorming, first-draft copyHighLet it run; a human edits. Speed beats precision.
Support answers, internal searchMediumGround + cite + abstain; sample-check quality offline.
Money, legal, medical, agent actionsNear zeroGrounding + verification + human-in-the-loop or confirmation. Never ship raw model output.

How is hallucination measured?

You will meet a shelf of hallucination benchmarks, and the single most important skill is reading what each one actually measures, because a faithfulness number and a world-factuality number measure different things entirely, and get quoted interchangeably. Models are dramatically more reliable summarising a document you hand them than answering from memory, and the two are measured by separate benchmarks that cannot be divided into one another: one of them is adversarially collected against a specific model, so its error rate is not a base rate for anybody.

The benchmarks you’ll hear cited, and what each really tests
BenchmarkWhat it measuresRead it as
HHEM / grounded-summary leaderboardsFaithfulness: is a summary consistent with the short source doc it was given?Best models land in the low single-digit %, but only on short-doc summary faithfulness, not general truth.
TruthfulQAWhether the model repeats common human misconceptions.Famous for an inverse-scaling result: bigger models were sometimes less truthful.
FActScoreLong-form factual precision: what fraction of atomic claims are supported by a reference.Good for essays/bios; instruction-tuned models often land only in the middling range.
SimpleQAShort fact-seeking QA graded correct / incorrect / not-attempted.The three-way grade lets it measure abstention and overconfidence, not just accuracy.
RAGAS (metric suite, not a leaderboard)Splits a RAG answer into faithfulness, answer-relevancy, context precision/recall.Reference-free; lets you blame a failure on retrieval vs generation.

Measure it: on your task, not a leaderboard

A leaderboard number is not your rate on your data and task. You reduce hallucination the way you reduce any defect: you measure it and set a target. Build a small labeled evaluation set (include adversarial and deliberately unanswerable questions to test whether the model abstains), and score three numbers together: faithfulness/groundedness (does each claim follow from the source?), hallucination rate (share of answers with an unsupported claim), and answer rate (how often it chose to answer at all). Splitting a RAG failure into retrieval-quality vs generation-faithfulness (the RAGAS decomposition) tells you which half to fix. Then sample live traffic to catch drift. The full machinery, golden sets, LLM-as-judge, regression suites, is the evaluation topic later in the course; here, the point is simply: put a number on it, then drive the number down.

The checks in code

Every defense above is a small function you wrap around the model call. None needs a framework: the point is to see how little code turns a fragile answer into a bounded one.

Four guards: plus the router that ties them together

  • Self-consistency. sampleAndAgree(prompt, n = 5): call the model n times at temperature ≈ 0.8, normalize each answer, and return the modal answer plus an agreement ratio (largest matching cluster ÷ n). Below a threshold, abstain or escalate instead of returning. For free-form text, cluster by a cheap “do these two say the same thing?” judge call rather than exact match.
  • Faithfulness / grounding check. isFaithful(answer, context): split answer into atomic claims with one model call, then for each claim ask a low-temperature judge, passing only the context, to reply with a constrained ENTAILED / NOT_ENTAILED / UNSURE. Any NOT_ENTAILED flags the answer. Forcing the verdict into an enum (structured output) stops the judge itself from waffling.
  • Confidence signal. On OpenAI-style APIs, request logprobs and read per-token probabilities to compute an answer-span confidence: remembering it’s a weak signal. Anthropic doesn’t expose token log-probs, so the native pattern is a structured confidence field plus a self-consistency cross-check; never trust the self-reported number alone.
  • Citation-resolves check. After generation, for each cited claim assert the documentId is one you actually retrieved (resolves) and the quoted span is a real substring of that document (not fabricated), then run the entailment check that the span supports the claim. Anthropic’s Citations feature makes “resolves” a structural guarantee by returning claims tied to exact source spans.
  • Wrap it in a router. Behind one answerWithGuards(request), map the action the answer feeds, display-only → cite-and-abstain → writes-or-acts, to which guards must pass before the answer is allowed through. That router is this whole page turned into ten lines.

What to unlearn, and what to do instead

These are the seven beliefs that produce bad designs, each next to the habit that follows once you drop it. Every habit is the same move: stop trying to make the model truthful, and start bounding what an untruthful answer can do.

The seven that decide whether your system is honest
Drop this beliefBuild this habit
“A bigger or better model will fix it.”Pick the defence by blast radius, per feature. Decide whether an answer is display-only, cited-and-abstainable, or acting on the world, and require grounding, verification and human confirmation in proportion.
“It is lying.”Treat it as a property rather than a character flaw, and design for a rate rather than for a culprit.
“Temperature 0 stops it.”Remember what temperature touches. It shrinks the decoding-origin share and leaves the data and training shares untouched, which is why it feels like it helps and never fixes it. The single most likely continuation can be a confident fabrication.
“A ‘don’t hallucinate’ prompt fixes it.”Make abstention a first-class, rewarded output instead. Give the model an explicit “not in the provided material” path, and in your evals score a confident wrong answer as worse than an honest decline.
“RAG eliminates it.”Ground with retrieval, then verify the grounding. Retrieval attacks factuality, and a claim-level entailment check attacks the faithfulness errors retrieval leaves behind. You need both.
“High confidence means it is probably right.”Never gate on the model’s self-confidence. Use external signals, citation-resolves, self-consistency, semantic spread, a verifier, because calibration is poor and preference-tuning degrades it further.
“A benchmark score is our hallucination rate.”Measure on your own labelled eval, with unanswerable questions in it, and set an SLO. A faithfulness score on short documents and a world-factuality score on open questions are not the same measurement and cannot be converted.

Interview cheat-sheet: intern to principal

Why do LLMs hallucinate?
They’re trained to produce the most plausible next token, not the most true one, with no fact store to check against and no default ‘I don’t know.’ On a question they can’t answer well, the most probable continuation is a confident, well-formed sentence, so they generate one. It’s structural, not a bug.
What’s the difference between a factuality and a faithfulness error?
Factuality (extrinsic): the claim is false against the world. Faithfulness (intrinsic): the claim contradicts the source you actually provided. Grounding/retrieval targets factuality; faithfulness needs verification against the source, and grounding can even worsen faithfulness if the model overrides or misreads the retrieved text. Note the two are independent: an answer can be faithful to a wrong source (faithful but false) or add a true fact that wasn’t in the source (true but unfaithful).
Why can’t you just gate answers on the model’s confidence?
Because model confidence is poorly calibrated, it doesn’t reliably track correctness, and preference-tuning makes models sound more certain, degrading calibration further (OpenAI’s GPT-4 report showed exactly this). Use external signals instead: self-consistency across samples, semantic spread, claim-level verification against the source, or a verifier model.
How would you detect hallucinations at inference time?
Cheap-first: verify cited passages resolve and are real substrings; run self-consistency (sample N, low agreement = fabrication smell); for open generation use a semantic-spread/entropy signal that clusters answers by meaning; for grounded answers, decompose into claims and check each is entailed by the source with a strict judge. No single signal is trustworthy alone, self-consistency misses confidently-memorized falsehoods, judges inherit biases, so stack them and escalate by stakes.
Design a support assistant that minimizes harmful hallucinations.
Ground answers in retrieved policy docs and instruct answer-only-from-context; require citations and give a rewarded ‘not in the provided material’ abstain path; verify citations resolve and run a claim-check or self-consistency pass on the answer; gate anything touching money or account changes behind a verifier and human confirmation. Measure faithfulness, hallucination rate, and answer rate on a labeled eval that includes unanswerable questions, and set an SLO.
Your evals show the model rarely says ‘I don’t know.’ Why, and is that good?
It’s usually because the training (and many benchmarks) reward guessing: a wrong answer and an abstention score the same zero, so always-answer maximizes the score (OpenAI’s 2025 analysis makes this precise). It’s not good for a trustworthy product: you want abstention to be a first-class, rewarded output, and to score confident wrong answers as worse than honest abstentions. In one published comparison, the model that abstained on about half the questions made errors on 26% of them against 75%, and was more accurate on what it did attempt.
Does adding RAG solve hallucination?
It’s the biggest single lever for factuality but not a solution. RAG can’t ground what retrieval misses, and it introduces its own faithfulness failures: the model ignoring the passage for its memory, over-trusting a wrong passage, or blending sources wrong. Measure retrieval quality and generation faithfulness separately, and keep verification on top.
Why can reasoning models hallucinate more than plainer ones?
On grounded tasks like summarization and person-factuality, several reasoning models score worse: OpenAI’s o3/o4-mini system card reported roughly double the person-factuality hallucination of the prior model. A longer chain of generated claims is more surface area to fabricate on; chain-of-thought helps math and code, not automatically faithfulness. Choose the model per task and measure.
Someone quotes ‘this model has a 3% hallucination rate.’ What do you ask?
‘On what task?’ A ~1 to 5% figure is typically short-document summary faithfulness (e.g. HHEM-style), which is a very different thing from world-factuality on open questions, where rates are far higher. Faithfulness and factuality numbers measure different things and get conflated constantly, and you cannot convert one into the other. A benchmark ranks models; it isn’t your rate on your data.
Can you get hallucination to zero?
No. It’s a structural consequence of how the model generates, with a statistical floor from pretraining. The honest goal is a measured, bounded rate with detection and human review on high-stakes paths. Distrust anyone claiming they eliminated it; trust ‘we hold it under X% and gate the dangerous flows.’

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.