Hallucinations
A hallucination is output that sounds confident and fluent but is false or unsupported: an invented citation, a non-existent API function, a wrong date, a "quote" nobody said. It is one of the most important limitations to understand, because the errors look exactly like correct answers.
Why it happens
A language model generates likely text, not verified text. Several factors make false continuations likely:
- No knowledge, no abstention — when a fact is missing or rare in the training data, the model still produces something shaped like an answer.
- Pattern completion — a citation "looks like"
Author (Year). Title. Journal., so the model can produce a perfectly formatted, fictional reference. - Outdated knowledge — anything after the training cutoff is unknown.
- Pressure from the prompt — leading questions ("Which paper proved X?") presuppose an answer exists.
- Sampling — randomness occasionally picks a lower-probability, wrong token, and later tokens build on it.
Fluent but false: a toy demonstration
A bigram model trained on a few true sentences can recombine them into fluent false ones, because each word pair it uses is plausible on its own:
import random
facts = [
"marie curie won the nobel prize in physics",
"albert einstein won the nobel prize in physics",
"marie curie was born in warsaw",
"albert einstein was born in ulm",
]
follows = {}
for sentence in facts:
words = sentence.split()
for a, b in zip(words, words[1:]):
follows.setdefault(a, []).append(b)
rng = random.Random(4)
for _ in range(4):
word, out = "albert", ["albert"]
while word in follows:
word = follows[word][int(rng.random() * len(follows[word]))]
out.append(word)
sentence = " ".join(out)
print(f"{'TRUE ' if sentence in facts else 'FALSE'} {sentence}")FALSE albert einstein won the nobel prize in ulm
FALSE albert einstein was born in physics
FALSE albert einstein won the nobel prize in ulm
TRUE albert einstein won the nobel prize in physics
Every generated sentence is grammatical and every word pair occurred in true training text — yet some sentences combine them wrongly. Real LLMs are vastly better than this toy, but the underlying risk is the same: local plausibility is not truth.
Detecting unsupported claims
When you have source documents (RAG), you can check each sentence of an answer against them. Production systems use an LLM or a trained entailment model for this; the toy below uses word overlap to flag sentences with little support:
import re
source = ("The X200 kettle holds 1.7 litres. It switches off automatically when the water boils. "
"The warranty lasts two years.")
answer = ("The X200 holds 1.7 litres. It switches off automatically when the water boils. "
"It has a five-year warranty and a built-in water filter.")
STOP = {"the", "it", "a", "an", "and", "has", "when", "is"}
def content_words(text):
return {w for w in re.findall(r"[a-z0-9.]+", text.lower()) if w not in STOP}
source_words = content_words(source)
for sentence in re.split(r"(?<=\.)\s+", answer):
words = content_words(sentence)
support = len(words & source_words) / len(words)
flag = "ok " if support >= 0.6 else "CHECK "
print(f"{flag} {support:.0%} {sentence}")ok 100% The X200 holds 1.7 litres.
ok 100% It switches off automatically when the water boils.
CHECK 29% It has a five-year warranty and a built-in water filter.
The third sentence mixes a wrong warranty period with an invented feature — exactly the kind of claim to flag for review or remove.
Reducing hallucinations
| Technique | How it helps |
|---|---|
| Ground with sources (RAG) | the answer can be copied from text rather than recalled |
| "Answer only from the sources; otherwise say you don't know" | gives the model a legitimate way out |
| Ask for citations or quotes | unsupported claims become visible and checkable |
| Use tools for facts and maths | search, databases and calculators beat memory |
| Lower temperature for factual tasks | fewer low-probability detours |
| Verify in code | check that cited IDs, URLs or function names actually exist |
| Self-consistency | disagreement between samples signals uncertainty |
| Human review for high stakes | medical, legal, financial and safety-relevant content |
Verifying things that can be checked mechanically is cheap and very effective — for example, that every package or function the model mentions really exists:
import math
suggested = ["math.sqrt", "math.isqrt", "math.cuberoot", "math.prod", "math.average"]
for name in suggested:
attr = name.split(".", 1)[1]
exists = hasattr(math, attr)
print(f"{name:<14} {'exists' if exists else 'DOES NOT EXIST'}")math.sqrt exists
math.isqrt exists
math.cuberoot DOES NOT EXIST
math.prod exists
math.average DOES NOT EXIST
math.cuberoot and math.average sound plausible but are not part of Python's math module (Python 3.11 added math.cbrt for cube roots). Code assistants can invent names like these; running, linting and testing generated code catches them.
Tip: Design your product for the possibility of errors: show sources, make it easy to report mistakes, and never present model output as verified fact unless it was verified.
Test yourself
What is the root cause of hallucinations?
- Bugs in the tokenizer
- Models generate likely-sounding text without a built-in check that it is true
- Too much training data
- Using JSON output
Which technique gives the model a legitimate alternative to inventing an answer?
- Raising the temperature
- Instructing it to say 'I don't know' when the sources don't contain the answer
- Removing the system prompt
- Asking leading questions
A code assistant suggests calling math.average. What's the best response?
- Trust it; it sounds right
- Verify it exists (run, lint or check the docs) before relying on it
- Raise the temperature and ask again
- Rename your module to math