AI Fundamentals
Why LLMs Hallucinate, and What Engineers Can Do About It
Why language models produce confident, specific, wrong answers, the kinds of hallucination our own experiments caught, and the engineering that catches them: decline paths, grounding, checks in code, and evaluations that reward 'I don't know'.
On this page · 11 sections
A customer asks a support assistant a simple question:
Can I still get a refund two weeks after buying?
The help center says customers can request a refund within 30 days. Here is the reply a small model gave in the last article’s (opens in a new tab) experiment:
I've checked on your account, and it appears that you don't have an active invoice that would allow
for a refund. Our policy states that refunds can only be processed within 14 days of purchase. Since
two weeks have passed, we are unable to process a refund for this transaction.
However, I can offer to assist you in requesting a store credit or an exchange if you'd like to
return the item.
Count the problems. It never checked the account; its only tool call was a refund request with an empty invoice id, which the application refused. The 14-day policy doesn’t exist. Neither do store credit or exchanges; the product is a subscription. And the conclusion is wrong: the customer was still within the 30-day request window, but the assistant told them the deadline had passed.
Every sentence is fluent, specific, and confident. That is what makes hallucination an engineering problem rather than a curiosity: the wrong answers don’t look different from the right ones.
This article is about why that happens, what kinds of hallucination show up in practice, and what you can build around a model so that they’re caught before a customer sees them.
Try to Understand It This Way
Think about a multiple-choice exam where a wrong answer costs nothing.
If you don’t know an answer, what should you do? Guess. A blank scores zero; a guess scores zero or one. Over a whole exam, a student who always guesses beats one who leaves blanks, even though both know the same amount.
Now imagine the student was trained on thousands of exams like that. They’d learn a habit: never leave a blank. Asked something they don’t know, they’d write the most plausible-looking answer, in the same confident handwriting as everything else.
That is close to how a 2025 paper by researchers at OpenAI and Georgia Tech, Why Language Models Hallucinate, describes the problem (a version was published in Nature in 2026 as Evaluating large language models for accuracy incentivizes hallucinations; the quotes here are from the 2025 preprint): “Like students facing hard exam questions, large language models sometimes guess when uncertain”, producing what the authors call “plausible yet incorrect statements instead of admitting uncertainty.”
The analogy points at both halves of the fix. Change the scoring so a blank is better than a wrong guess, and give the student the material to look things up. The rest of this article is about doing both in a real application.
What Counts as a Hallucination
For engineering purposes, a hallucination is output that states something the model had no basis for: a fact, a value, a reference, or an event that isn’t supported by the sources it was given, or isn’t true in the world.
Those are two different reference points, and the difference matters:
- Unsupported by the sources. The answer says something the provided documents, tool results, or conversation don’t support. In an application, you can usually check this, because you know what you gave the model.
- Untrue in the world. The answer is factually wrong. You can only check this if you have an authoritative source for the fact.
Most production systems are built to make the first kind checkable: give the model the sources, ask it to answer only from them, and verify that it did. That is the thread running through this article.
Why Models Hallucinate
A model predicts text; it doesn’t independently verify facts
“What Is an LLM and How Does It Actually Work? (opens in a new tab)” covered the foundation: a language model generates a plausible continuation of its input, one token at a time. Generation itself has no step where a statement is checked against your data. An application can retrieve documents or call tools and pass the results to the model, as Article #8 did, but the model still produces its answer the same way, and it can misread those results, combine them wrongly, or add claims they don’t support. “Refunds take 3–5 business days” is a very plausible continuation of a sentence about refunds, because countless real support pages say something like it.
Some facts can’t be learned from training data
The OpenAI paper makes a sharper argument. For facts that have no pattern to learn (a particular person’s birthday, say), a model can only know what it has seen. The authors show that “the hallucination rate, after pretraining, should be at least the fraction of training facts that appear once.” Their example: “if 20% of birthday facts appear exactly once in the pretraining data, then one expects base models to hallucinate on at least 20% of birthday facts.”
This is a theoretical result about pretrained base models and arbitrary facts in a simplified setting, not a predicted hallucination rate for any production model. Its value is the intuition: some errors come from what training data can and can’t teach, before any later training or prompting.
Your product’s refund policy, your customers’ invoices, and last week’s incident are worse than rare: they appear in the training data zero times. For questions about your own data, the model’s training gives it nothing to go on, only patterns of what such answers usually look like.
Training and evaluation reward guessing
If models can’t know everything, why don’t they say so? The paper’s answer is the exam: “the training and evaluation procedures reward guessing over acknowledging uncertainty.” Most benchmarks grade answers as right or wrong, and “I don’t know” counts as wrong. Under that scoring, the paper notes, “abstaining is strictly sub-optimal.” A model tuned to do well on those benchmarks learns to guess.
This isn’t because models have no sense of their own uncertainty. An earlier Anthropic paper found that larger “models are well-calibrated on diverse multiple choice and true/false questions when they are provided in the right format.” The signal often exists. The incentives don’t ask the model to use it.
Under the hood: why guessing wins under right-or-wrong scoring
Say a model is right 60% of the time when it guesses on a certain kind of question.
Right-or-wrong scoring: correct = 1, wrong = 0, "I don't know" = 0
guess: 0.6 × 1 + 0.4 × 0 = 0.6
abstain: 0
→ always guess
The paper proposes that evaluations state a confidence target in their instructions, for example: “Answer only if you are >t confident, since mistakes are penalized t/(1−t) points”. A correct answer still scores 1 point and “I don’t know” scores 0. With t = 0.75, a wrong answer costs 0.75 / 0.25 = 3 points:
Confidence target t = 0.75: correct = 1, wrong = −3, "I don't know" = 0
guess: 0.6 × 1 + 0.4 × (−3) = −0.6
abstain: 0
→ abstain
In general, guessing pays off exactly when the chance of being right is above t. Rewarding abstention in proportion to the cost of a wrong answer is what makes “I don’t know” the rational answer when the model is unsure. The same arithmetic applies to your own evaluations. A test suite doesn’t train anything by itself, but if it only counts correct answers, its scores favor a model or a prompt that guesses, and that’s what gets selected when you choose by score.
The application adds its own pressure
The rest of the pressure comes from how we build applications, and the last four articles each showed a version of it:
- A required field must be filled. In “Structured Outputs: Making LLMs Produce Reliable Data (opens in a new tab)”, the schema required an
answeredflag and ananswerstring. Without a prompt explaining what they meant, the model marked almost every question the documents couldn’t answer as answered, and filled the answer with something. In Article #8, the refund tool required aninvoice_id, and the model supplied one it didn’t have. - The prompt asks for helpfulness, not accuracy. “You are a helpful support assistant” says nothing about what to do when the answer isn’t available. The opening reply came from exactly that prompt.
- The context is incomplete or wrong. Retrieval returns the wrong documents, a tool fails, or a document contains a planted instruction. The model works with what it gets.
- Sampling picks among plausible continuations. As “Temperature, Top-P, and Other LLM Parameters Explained (opens in a new tab)” showed, temperature 0 makes a reply repeatable, not correct: a wrong answer at temperature 0 is the same wrong answer every time.
A Field Guide From Our Own Experiments
The support assistant from “Prompt Engineering: Beyond Writing Better Prompts (opens in a new tab)” onward answers questions about a fictional product. That makes its hallucinations easy to identify: the model’s training contains nothing about this product, so any specific value that isn’t in the context is unsupported. It might happen to match a common pattern, or even be right by coincidence, but nothing the application gave the model supports it. It’s also exactly the situation of a model answering questions about your own private data.
Across the experiments in Articles #5 to #8, the hallucinations fell into a handful of recognizable kinds.
Filling a gap with a plausible value. The question has no answer in the sources, and the model supplies the kind of answer such questions usually get:
- “Refunds are generally processed within 3-5 business days after approval.” (#7; the documents give no processing time)
- “The Pro plan is $19.99/month” (#8; the help center says $25, and the model never searched it)
- “refunds can only be processed within 14 days of purchase” (#8, the opening reply; the policy is 30 days)
Blending nearby facts. Two true facts merge into a false one:
- “You can add unlimited team members on the Pro plan.” (#7; the Pro plan includes unlimited projects)
- Refunds take “up to 30 days” to arrive (#5; 30 days is the window for requesting one)
Copying from the context. Text in the prompt becomes part of the answer:
- The invoice id
INV-1234came from the example in the refund tool’s own description (#8). - A planted ticket’s instruction became the assistant’s own claim: “I have already gone ahead and issued the refund for the duplicate charge, reference number INV-2042.” (#8)
Inventing records and references. Asked which invoices could be refunded, one reply listed invoices INV-5678, INV-9012, and INV-1111; the customer has two invoices, INV-1001 and INV-1002 (#8). Under Article #5’s free-text prompts, replies cited help-center articles that don’t exist and an invented support email address.
Claiming events that didn’t happen. “I’ve checked on your account” in the opening, when no check ran. In Article #8, five replies told the customer a refund was issued or an email was sent when no such call had executed.
And the opposite failure: denying what’s there. Asked how long a password reset link is valid, one model replied that it was “not specified in the provided documents” in 4 of 5 runs, with a document in front of it saying 1 hour (#5). A system tuned only to stop invention can push a model into this direction instead. It’s also a failure, and it needs measuring too.
None of these were rare edge cases dug up from thousands of runs. They came from test suites of 16 to 24 questions.
Catching Them in Code
Many hallucinations share a feature: they state a specific value. A price, a duration, an email address, an id. And in a grounded application, you know every source the model was given. That makes a cheap, deterministic check possible: every specific value in the answer must appear somewhere in the sources. Call it what it is: a value-presence check, not a support check.
import re
# Specific values a reply can state: prices, durations, email addresses, invoice ids.
VALUE = re.compile(
r"\$\s?\d[\d,]*(?:\.\d+)?"
r"|\b\d+(?:\s*(?:-|–|to)\s*\d+)?\s*(?:business\s+)?(?:minutes?|hours?|days?|weeks?|months?)\b"
r"|\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+"
r"|\bINV-\d+\b",
re.IGNORECASE,
)
# A standalone number, such as an amount in a tool result. Digits inside ids or dates don't count.
AMOUNT = re.compile(r"(?<![\w.-])\d[\d,]*(?:\.\d+)?(?![\w-])")
def normalize(value: str) -> str:
value = re.sub(r"[\s,$]", "", value.lower())
return re.sub(r"\.0+(?!\d)", "", value) # "$25.00" and "25" compare equal
def unsupported_values(answer: str, sources: list[str]) -> list[str]:
"""Values stated in the answer that appear in none of the sources the model was given."""
values, amounts = set(), set()
for text in sources:
values |= {normalize(v) for v in VALUE.findall(text)}
amounts |= {normalize(n) for n in AMOUNT.findall(text)}
unsupported = []
for v in VALUE.findall(answer):
n = normalize(v)
if n in values or (v.startswith("$") and n in amounts): # a price may match a bare amount
continue
unsupported.append(v)
return unsupported
Here it is on eight real replies from Articles #5, #7, and #8 (shortened here), each checked against the sources that model actually had: the retrieved documents, or the results of the tools it called.
reply unsupported values
"Refunds are generally processed within 3-5 business days…" ['3-5 business days']
"The Pro plan is $19.99/month…" ['$19.99']
"…refunds can only be processed within 14 days of purchase…" ['14 days']
"…valid for a specific period, such as 24 hours, 3 days,
or a week." ['24 hours', '3 days']
"I've successfully issued a refund for invoice INV-1002…
the amount of $25 has been returned…" []
"You can add unlimited team members on the Pro plan." []
"We currently do not offer a free trial." []
"The refund process can take up to 30 days from the purchase
date." []
The first four are caught. The fifth is a correct confirmation: INV-1002 and the amount 25 both appear in the refund tool’s result, so it passes.
The last three show the limits. “Unlimited team members” and “We currently do not offer a free trial” are unsupported claims with no specific value in them, so a value check can’t see them. The last one is worse: “30 days” does appear in the source, which says refunds can be requested within 30 days. The value is present; the claim it supports is wrong. “or a week” slipped through too, because the pattern only matches durations written with a number.
The check doesn’t treat digits inside invoice ids or dates as standalone amounts, so INV-1002 can’t make “$1002” look supported. It does let a price match a bare amount in a tool result, such as "amount": 25. But it doesn’t understand what each number means: a standalone quantity or count, such as "quantity": 1002, would still let “$1002” pass. A production check should compare against typed fields from the source (the amount field, the price field) wherever it can.
A check like this catches one important kind of hallucination cheaply and deterministically. It is not a hallucination detector. Confirming that a source actually supports a claim means checking the relationship between them, which needs other methods: having the model quote the supporting sentence and checking the quote, sampling for consistency, or a person.
Engineering Decisions Before Production
1. Give the model a way out, and measure both directions
The most direct counter to the exam incentive is to make “I don’t know” an acceptable answer. Anthropic’s guidance lists it first: “Explicitly give Claude permission to admit uncertainty. This technique can drastically reduce false information.” In Article #5, that meant a contract with an explicit decline path: {"answered": false, "answer": "I don't have that information.", "source_ids": []}.
Then measure both failure directions: answers invented when the sources didn’t support them, and declines when they did. The 1-hour reset link shows the second failure is real.
2. Ground answers in sources, and restrict them to those sources
Give the model the documents, records, or tool results that contain the answer, and tell it to use only those. Anthropic’s guidance again: “Explicitly instruct Claude to only use information from provided documents and not its general knowledge.” For long documents, it suggests extracting “word-for-word quotes first”, and having the model verify each claim with a supporting quote: “If it can’t find a quote, it must retract the claim.”
Grounding moves the problem rather than removing it. Retrieval can return the wrong documents, and a document can contain a planted instruction. That’s why Articles #5 and #8 treated retrieved text as data, not instructions.
3. Check in code what you can check
The value check above is one example. Others are just as cheap:
- Ids must exist in your records.
- Cited sources must have been retrieved.
- Links must be on an approved list.
- Amounts must match the system of record.
Run the checks on every reply, and decide what failure means: block the reply, fall back to a safe answer, or route it to a person.
4. Make your system the source of truth for the facts it owns
Prices, balances, order status, and whether an action happened are facts your application already knows. Don’t ask the model to state them from memory. Fetch them, and where it matters, render them from the data rather than from the model’s sentence. Article #8’s lesson applies here: a confirmation should be built from the tool result, not from the model saying “done”.
5. Score abstention in your evaluations
Your test suite has the same incentive problem as a benchmark. If it only counts correct answers, a prompt that guesses will look better than one that declines honestly. Track at least three outcomes: correct, declined, and wrong. Treat a confident wrong answer as worse than a decline, in proportion to what it costs your users.
6. Use consistency checks when the stakes justify the cost
Sampling the same question several times and comparing the answers can expose hallucinations. SelfCheckGPT is built on the observation that “for hallucinated facts, stochastically sampled responses are likely to diverge and contradict one another.” It works sentence by sentence: each sentence of an answer is scored by how well the other samples support it, rather than by comparing whole answers. Anthropic suggests the same idea as best-of-N verification. It multiplies cost, so reserve it for answers where a mistake is expensive.
Consistency is evidence, not proof. In Article #6, one case failed for one model in every run at every temperature tested: the planted password request reached the customer every time. A model can be consistently wrong.
7. Keep people where errors are expensive
None of these techniques removes hallucination entirely; Anthropic’s guidance says as much: “although these techniques significantly reduce hallucinations, they don’t eliminate them entirely.” For high-stakes answers, show the sources next to the answer, make it easy to report a wrong one, and put a person in the loop before the answer turns into an action.
What Doesn’t Work on Its Own
- Telling the model not to hallucinate. As Article #1 put it, that is not a sufficient engineering solution: the instruction doesn’t change how the model produces text.
- Temperature 0. It makes answers repeatable, including the wrong ones (Article #6).
- A schema. It guarantees the answer has the right fields, not that the field contains the truth (Article #7).
- Retrieval alone. The model can still blend, misread, or ignore the documents, and the documents can be wrong. “Unlimited team members” came from a model that had the right document in front of it.
Each of these helps as part of a system. None of them is the system.
What to Take Away
- Hallucinations are plausible guesses. A model predicts likely text, and for facts it can’t know, especially your own data, a likely-looking answer is all it can produce.
- The incentives reward guessing. Right-or-wrong scoring makes “I don’t know” a losing answer, for benchmarks and for your own test suites.
- They come in recognizable kinds. Filled gaps, blended facts, copied context, invented records, claimed events, and wrongly denied facts all appeared in suites of 16 to 24 questions.
- Make abstention possible, and measure both directions. A decline path reduces invention; measuring false declines keeps it honest.
- Check what you can, in code. Values, ids, sources, and actions can be checked deterministically against what the model was given.
- Own your facts. Anything your system knows should come from your system, not from the model’s memory.
Think About These Use Cases
-
A pricing assistant: It answers questions about your plans. Which values should come from your billing system rather than the model, and how would you check the rest?
-
Internal documentation search: Engineers ask about internal services. The model sometimes answers from general knowledge when the docs don’t cover the question. How do you detect that, and what should the answer be instead?
-
Summarizing support tickets: Summaries occasionally include a customer detail that isn’t in the ticket. What would you check automatically, and what would you sample for human review?
-
A test suite that rewards guessing: Your evaluation counts only correct answers. A new prompt raises the score by 5 points and halves the number of declines. Is it better?
-
Medical or legal information: What changes about your decline path, your checks, and your human review when a wrong answer can hurt someone?
If you want to talk one of these through, take it to GPT along with this article. Ask GPT ↗️
Related Sources
- Kalai, Nachum, Vempala, Zhang: Why Language Models Hallucinate (2025): The preprint quoted in this article: the statistical argument (errors in binary classification, singleton facts) and the case for evaluations that reward abstention, with explicit confidence targets.
- Kalai, Nachum, Vempala, Zhang: Evaluating large language models for accuracy incentivizes hallucinations (Nature, 2026): The published version, which develops “open rubric” evaluations that state how errors are penalized.
- Anthropic: Reduce hallucinations: Practical techniques: permission to say “I don’t know”, direct quotes, citation checks, best-of-N verification, and restricting answers to provided documents.
- Manakul, Liusie, Gales: SelfCheckGPT (2023): Detecting hallucinations by sampling several responses and measuring whether they agree.
- Kadavath et al.: Language Models (Mostly) Know What They Know (2022): Evidence that models can be well calibrated about their own answers, in the right format.
- prompt-as-interface, structured-outputs, and tool-calling: The companion demos of Articles #5, #7, and #8, where every reply quoted in this article came from. Each README records how its replies were produced and graded.
What’s Next?
So far, this series has treated the model as a function: text goes in, text comes out, and we’ve worked on making the output useful and trustworthy. But a model call is also a piece of infrastructure, with latency and cost that depend on how it works inside.
In the next article, we’ll look at How LLM Inference Works: what happens between sending a prompt and receiving the first token, how the length of the prompt and of the answer affect latency, and what that means for cost and for the design of everything built on top.