AI Hallucinations: Why They Happen — Explained with Real Examples

why do AI hallucinations happen
AI Hallucinations: Why They Happen — Explained with Real Examples

Learn · With · Examples

Ask a language model a question and it can answer with total confidence — complete with dates, citations, and code — while being completely wrong. This isn’t a bug that occasional updates will fix. It is a direct consequence of how these models work. This guide breaks down exactly why hallucinations happen, with interactive examples, real cases, and the techniques used to reduce them.

📖 17 min read 🎲 Next-token prediction explorer 🖼️ Hallucination gallery 🌡️ Temperature demo ❓ 6-question quiz

Section 01

What is an AI Hallucination?

An AI hallucination is when a language model generates output that is fluent, confident, and completely wrong — a fabricated fact, a citation to a paper that doesn’t exist, a function that was never in the library, a quote nobody said. The term comes from human perception, where a hallucination is seeing something that isn’t there. The model isn’t “seeing” anything, but the analogy fits: it is generating something that has no basis in reality, with the same fluency as something true.

Think of a brilliant friend who has read almost everything but never admits when they don’t know something. Ask them a question and they will answer instantly and confidently — sometimes correctly, sometimes by smoothly inventing a plausible-sounding answer. They are not lying, because lying requires knowing the truth and hiding it. They genuinely cannot tell the difference between “I recall this” and “this sounds right.” That is a language model.

⚖️ Real Case — Fabricated Legal Citations

In 2023, lawyers in a U.S. federal case submitted a brief containing citations to six court cases — complete with quotes and docket numbers. None of the cases existed. A chatbot had fabricated them entirely, and they read as completely legitimate legal citations. The court sanctioned the lawyers involved.

3–27%
Estimated hallucination rate across leading models on open-domain factual questions
0%
Built-in mechanism for a model to know it’s wrong — confidence is not accuracy
1 token
At a time — the entire generation process, with no global fact-check step
2016
Term first applied to neural network outputs, borrowed from image captioning research

Section 02

Intrinsic vs Extrinsic — The Formal Definition

Researchers split hallucinations into two categories, depending on what the output contradicts:

Intrinsic Hallucination
The output contradicts the source material it was given. Ask it to summarise a document, and it states something the document explicitly says is false.
Extrinsic Hallucination
The output cannot be verified from the given source at all — it adds new “facts” that are neither confirmed nor denied by the source material or reality.
P(next token | previous tokens)
This is all a language model actually computes — a probability distribution over the next token, not a fact-lookup

💡 The Core Insight

A language model is not a database with a retrieval system attached. It is a function that predicts the statistically most likely next word given everything before it. Truth is not a variable in that computation — plausibility is. Most of the time plausible and true are the same thing, because it learned from mostly-true text. But nothing in the mechanism enforces truth. When they diverge, you get a hallucination.

Section 03

Interactive: Next-Token Prediction Explorer

Every word a language model produces is chosen from a probability distribution over its entire vocabulary. Click a prompt below to see simplified next-token probabilities. Notice what happens when no single answer clearly dominates — that flat, spread-out distribution is exactly where hallucinations are born.

  Next-Token Prediction Explorer
Prompt: “The capital of France is ___
Paris
97%
Lyon
1.5%
Marseille
0.8%
(other)
0.7%
✅ Low hallucination risk. One token dominates overwhelmingly — this fact appeared millions of times in training data in exactly this pattern. The model is essentially certain.
Prompt: “The Battle of Hastings took place in the year ___
1066
78%
1067
9%
1086
6%
(other)
7%
⚠️ Moderate risk. The correct answer still leads clearly, but nearby wrong years have real probability mass — with unlucky sampling, a wrong-but-plausible year could get selected.
Prompt: “The third-longest river in Paraguay by tributary count is ___
Río Apa
14%
Río Aquidabán
12%
Río Ypané
11%
Río Tebicuary
10%
(other, spread thin)
53%
🔴 High hallucination risk. No token dominates — this is an obscure, likely under-documented fact. The model will still confidently output ONE of these river names in fluent prose, with no indication of its uncertainty. This is the classic hallucination signature: a flat probability distribution rendered as a confident sentence.

⚠️ The Fluency Trap

Notice that all three answers above would read equally confidently in a generated sentence — “The third-longest river in Paraguay by tributary count is the Río Apa.” Nothing in the grammar or tone signals that this answer had only 14% probability versus the capital-of-France answer’s 97%. Fluency is constant; certainty is invisible.

Section 04

Why They Happen — 6 Root Causes

🎯

1. Next-Token Prediction, Not Fact-Checking

The model’s only job during generation is “what word comes next.” There is no separate module that checks generated claims against a database of true facts.

📚

2. Training Data Gaps and Noise

If a topic was rare, contradictory, or wrong across the training corpus, the model absorbs that gap or error as if it were reliable pattern.

🎲

3. Sampling Randomness

Generation involves randomness (temperature, top-p sampling) by design — to avoid robotic repetitive text. That same randomness can select a low-probability, incorrect token.

🔌

4. No Real-Time Grounding

Without a retrieval or search tool connected, the model only has frozen knowledge from training — it cannot look anything up to double-check itself mid-answer.

📊

5. Miscalibrated Confidence

Models are trained to sound helpful and fluent, not to output calibrated uncertainty. There’s no built-in “I’m only 14% sure” phrasing — everything comes out sounding equally confident.

🗜️

6. Lossy Compression of Knowledge

A model with billions of parameters still compresses trillions of words of training text. Like a JPEG at low quality, fine details blur — and the model fills gaps with its best statistical guess.

🧠 An Analogy: Compression, Not Storage

A language model does not store facts the way a database stores rows. It stores statistical patterns compressed from its training data. Recalling a fact is more like reconstructing a blurry JPEG than reading a row from a spreadsheet — usually accurate, but sometimes the reconstruction fills gaps with a plausible-looking artifact that was never actually there.

Section 06

Interactive: Temperature and Sampling

“Temperature” controls how randomly a model samples from its next-token probability distribution. Lower temperature makes it pick the highest-probability token almost every time. Higher temperature flattens the distribution, giving low-probability (and potentially wrong) tokens a real chance of being chosen. Click through the same prompt at three different temperatures.

  Temperature Comparison — same prompt, three settings
Prompt: “List three lesser-known facts about the founding of the city of Timbuktu.”
temp = 0.0deterministicalways picks top token
1. Timbuktu was founded around the 5th century CE by Tuareg nomads as a seasonal camp.
2. It grew into a major center of trade in salt, gold, and books.
3. The University of Sankore made it a hub of Islamic scholarship by the 14th century.
✅ Lowest hallucination risk — but not zero. At temp 0 the model always picks its single most likely token, giving the most “average” and well-supported answer it has. Repeatable and conservative, though it can still be confidently wrong if the top token itself is incorrect.
temp = 0.7balancedsome randomness
1. Timbuktu’s name may derive from “Tin Abutut,” referring to a well tended by a woman named Buktu.
2. Its libraries once held an estimated 700,000 manuscripts.
3. By the 1300s it briefly rivaled Cairo as a center of Islamic learning in West Africa.
⚠️ Moderate risk — this is the typical default used in chat products. More varied and interesting phrasing, but occasional lower-probability claims slip in (exact manuscript counts and etymology claims are exactly the kind of specific-sounding numbers most likely to be invented).
temp = 1.5highly randomcreative but unstable
1. Timbuktu was reportedly founded in 1204 by the merchant-explorer Amara Keita after a caravan dispute.
2. Its original name, “Tinbouctu,” is said to mean “the place of the hidden well of stars.”
3. Early manuscripts suggest the city briefly minted its own gold currency called the “sanu-tomo.”
🔴 High risk — specific names, dates, and invented terms appear with total fluency and confidence. This is temperature-driven hallucination in its purest form: low-probability, largely fabricated tokens getting selected and then compounding into an entirely invented but very readable narrative.

Section 07

Types of Hallucinations

TypeWhat happensExample
FactualStates something false about the worldWrong birth year for a historical figure
FaithfulnessContradicts a document it was explicitly givenSummarizing a report and stating a conclusion the report actually rejects
CitationInvents sources, papers, or linksA perfectly formatted but nonexistent journal reference
LogicalReasoning steps don’t actually follow from each otherA multi-step math “proof” where step 3 doesn’t follow from step 2
EntityMerges or invents people, places, organizationsAttributing a real quote to the wrong (but plausible) person
TemporalGets timelines or sequences wrongSaying an event happened before its actual cause

Section 08

How Hallucinations Are Measured

Researchers use standardized benchmarks to compare how often different models hallucinate. These typically involve asking models factual questions where a subtly wrong but plausible answer is a common human misconception — deliberately testing the gap between “sounds right” and “is right.”

BenchmarkWhat it testsApproach
TruthfulQACommon misconceptions817 questions designed so a plausible-sounding wrong answer mimics common false beliefs
HaluEvalGeneral hallucination detection35,000 samples across QA, summarization, and dialogue tasks
FActScoreFactual precision of long-form textBreaks generated biography-style text into atomic facts and verifies each one
SelfCheckGPTConsistency-based detectionSamples the same prompt multiple times — inconsistent answers signal likely hallucination

⚠️ No Benchmark is Perfect

Hallucination rates vary wildly depending on domain, question difficulty, and whether the model has retrieval tools available. A single “hallucination rate” percentage for a model is always a simplification — the real rate depends heavily on what you’re asking.

Section 09

Real-World Consequences

⚖️

Legal Filings

Multiple documented cases of lawyers submitting briefs with fabricated case citations generated by chatbots, leading to court sanctions and case dismissals.

🏥

Medical Information

Confidently wrong drug interaction or dosage claims are especially dangerous because the fluent, authoritative tone makes errors hard to spot without independent verification.

🛫

Customer Service Bots

An airline’s chatbot invented a bereavement fare policy that didn’t exist. A tribunal ruled the airline was still bound by what its bot had promised the customer.

💻

Software Supply Chain

Attackers have started publishing malicious packages under names that AI coding assistants commonly hallucinate as real library names — a technique called “slopsquatting.”

📰

News Summarization

AI news summary tools have attributed claims to sources that never made them, misrepresenting the actual reporting underneath.

🎓

Academic Research

Students and researchers citing AI-fabricated sources have had papers rejected or retracted after reviewers discovered the citations don’t exist.

Section 10

Mitigation Techniques

TechniqueHow it worksEffectiveness
RAG (Retrieval-Augmented Generation)Retrieves real documents and grounds the answer in them before generatingHigh — directly addresses the “no grounding” root cause
Lower temperatureReduces randomness in token selection for factual tasksModerate — reduces but doesn’t eliminate risk
Chain-of-thought promptingForces the model to show reasoning steps, making errors easier to catchModerate — helps with logical, not factual, hallucinations
Self-consistency checkingGenerate multiple answers and check if they agreeModerate — inconsistency signals uncertainty
RLHF fine-tuningTrains the model to say “I don’t know” when uncertainModerate — helps but models remain overconfident on edge cases
Citation requirementsForces the model to link every claim to a real retrievable sourceHigh — makes fabrication immediately checkable
Human reviewA person verifies high-stakes outputs before they’re usedHighest — the only currently reliable safeguard for critical use cases

Section 11

Worked Example — Grounding with RAG

Retrieval-Augmented Generation (RAG) is the most effective widely-used mitigation. Instead of relying purely on the model’s compressed training memory, the system first retrieves real, current documents and feeds them into the prompt as context.

❌ Without RAG
Prompt: “What is our company’s current refund policy?”

Model has no access to your company’s actual policy documents — it generates a plausible-sounding generic refund policy based on common patterns from training data, presented as if it were your specific company’s real policy.
✅ With RAG
Prompt: “What is our company’s current refund policy?”

System first retrieves your actual policy document, inserts its real text into the prompt, then asks the model to answer using only that text. The model now has real grounding — reducing (not eliminating) fabrication risk to whether the model accurately reads the provided text.

✅ Why Grounding Helps but Doesn’t Solve It

RAG dramatically reduces factual hallucinations because the model is now paraphrasing real retrieved text instead of reconstructing from compressed memory. But it doesn’t eliminate the risk entirely — the model can still misread, misquote, or blend the retrieved documents with its own memory (an intrinsic hallucination against the very source it was given).

Section 12

Code Example — Sampling Parameters

Here is how temperature and top-p (nucleus sampling) are actually set when calling a language model API — the same parameters demonstrated in the interactive Temperature demo above.

Python
import anthropic

client = anthropic.Anthropic()

# Low temperature — for factual, deterministic tasks
# Minimizes risk of low-probability token selection
response_factual = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=500,
    temperature=0.0,  # deterministic, most-likely token every time
    messages=[{"role": "user", "content": "What year did WWII end?"}]
)

# Higher temperature — for creative, exploratory tasks
# Accepts more hallucination risk in exchange for variety
response_creative = client.messages.create(
    model="claude-sonnet-5",
    max_tokens=500,
    temperature=1.0,
    messages=[{"role": "user", "content": "Write a whimsical short story about rain."}]
)

# RAG pattern — ground the model in real retrieved text
def answer_with_grounding(question, retrieved_docs):
    context = "\n\n".join(retrieved_docs)
    prompt = f"""Answer ONLY using the context below.
If the answer is not in the context, say "I don't have that information."

Context:
{context}

Question: {question}"""

    return client.messages.create(
        model="claude-sonnet-5",
        max_tokens=500,
        temperature=0.0,  # low temp — stick close to retrieved facts
        messages=[{"role": "user", "content": prompt}]
    )

⚠️ Temperature Zero Isn’t a Cure

Setting temperature to 0.0 reduces randomness-driven hallucination, but does nothing for hallucinations that come from a genuinely wrong top-probability token — if the model’s single most confident answer is itself incorrect, temperature 0 will reproduce that error every single time, consistently.

Section 13

Knowledge Quiz

Click a question to expand it, then pick your answer.

A hallucination is fabricated content generated with the same fluency and confidence as accurate content. It’s not intentional deception (the model has no concept of “hiding” the truth) and it’s not simply a matter of opinion — it’s a factual or logical error presented as fact.
Language models compute a probability distribution over the next token and sample from it. There is no built-in fact-verification step in that process — plausibility, not truth, is what’s being optimized during generation. Truth and plausibility usually align, but not always.
Intrinsic hallucinations contradict the provided source — e.g., summarizing a document and stating something the document explicitly denies. This is distinct from extrinsic hallucination, where the model adds unverifiable new claims not confirmed OR denied by the source.
Temperature controls how randomly tokens are sampled from the probability distribution. Higher temperature flattens the distribution, giving unlikely (and often wrong) tokens more chance of selection. But temperature 0 isn’t a fix either — if the single most probable token is itself wrong, temperature 0 will reproduce that error consistently every time.
RAG retrieves real, current documents and inserts them into the prompt as context, letting the model paraphrase actual text instead of reconstructing facts from lossy compressed memory. It significantly reduces — but does not fully eliminate — hallucination risk, since the model can still misread or misquote the retrieved text.
The model has learned the statistical *pattern* of citations extremely well — journal names, volume numbers, page ranges, author formatting — even when the specific paper doesn’t exist. This makes fabricated citations look completely legitimate at a glance, as demonstrated by real legal cases where fake case citations passed initial review.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *