Why LLMs Confidently Make Things Up: Understanding and Catching Hallucination
Last time, Rae stuck with RAG for her support bot instead of jumping to a long-context model. The cost math was simple: fractions of a cent per query with RAG, keeping her runway intact. Long-context would run $0.30–2.10 per customer query. She figured RAG was the right call—for now.
1. The ‘Confident Liar’ Problem
Then the “burrito refund” incident happened. A customer named Marco emailed Rae’s support bot: “I bought a burrito warmer from your store last month and it stopped heating. Can I get a refund?” The bot replied with a detailed, professional, utterly fabricated refund policy: “Per our 90-day burrito warmer guarantee, you are eligible for a full refund plus a $15 inconvenience credit. Please ship the item to our returns center at 142 Fake Street, Springfield.”
There was no 90-day burrito warmer guarantee. No $15 inconvenience credit. No 142 Fake Street. Rae checked the retrieved context—the answer wasn’t in it. The bot had simply made it up, and it sounded certain.
Ever asked an AI a question and gotten back an answer that looked perfect—only to realize it was completely invented?
It’s a strange feeling. The grammar is flawless, the tone is professional, and it might even cite sources that look real. But the facts are pure fiction. We call this a “hallucination.”
Think of it this way: if you ask a human about the “Great Martian War of 1924,” they’ll likely say, “That never happened.” An LLM, though, might tell you about the brave soldiers who fought in the trenches of the Red Planet.
The first thing to understand is that LLMs don’t have a “truth” database. No small encyclopedia sits inside them that they consult before speaking. Instead, they have a “probability map.” They aren’t trying to be right; they are trying to be likely.
Watching a model fabricate history
Let’s see what happens when we push a model to lie. In this example, we’ll ask about a historical event that never occurred.
import os
import openai
def trigger_hallucination():
prompt = "Tell me about the signing of the Treaty of New York in 1752 between France and the Aztec Empire."
print(f"Prompt: {prompt}\n")
# There was no Aztec Empire in 1752, and no such treaty.
# If OPENAI_API_KEY is set, this makes a real call — but a live LLM's
# wording is NOT deterministic, so don't expect an exact match run to run.
if os.getenv("OPENAI_API_KEY"):
client = openai.OpenAI()
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
)
response = completion.choices[0].message.content
else:
# No API key set — this is a representative example of the kind of
# confident, fabricated answer a model produced when we asked it.
# A real call won't reproduce this exact wording; it's illustrative,
# not a guaranteed transcript.
response = "The Treaty of New York (1752) was a landmark agreement that ended the border disputes..."
print(f"AI Response: {response}")
trigger_hallucination()
prompt— a question about the “Treaty of New York in 1752 between France and the Aztec Empire,” an event that never happened (the Aztec Empire fell to the Spanish in the 1500s, and there was no such treaty in 1752).print(f"Prompt: {prompt}\n")— displays the fabricated question.if os.getenv("OPENAI_API_KEY")— checks whether a real key is configured. If so, the code makes an actual call viaclient.chat.completions.create(...)and uses whatever the model returns.response(no-key branch) — a representative example of the kind of confident, fabricated answer a model produced when we asked it. It’s illustrative, not a guaranteed transcript: a live call to the same prompt won’t reproduce this exact wording, since LLM sampling is stochastic.print(f"AI Response: {response}")— shows the model’s fabricated answer.- Key insight: the model doesn’t fact-check the premise of the question. It sees “Treaty,” “New York,” and “France” and generates text that sounds like a history book—prioritizing the vibe of a factual answer over actual facts. This is exactly what happened with Rae’s burrito refund incident: the customer’s question contained assumptions about a refund policy, and the bot played along instead of pushing back.
In the code above, the model doesn’t stop to object, “Wait, the Aztecs were conquered centuries before 1752.” It sees “Treaty,” “New York,” and “France” and starts building a sentence that sounds like a history book. The vibe of a factual answer wins out over the actual facts. That’s the core issue: a world-class mimic, not a librarian.
2. Think of it as a Super-Powered Autocomplete
To understand why the AI lies, you have to realize it isn’t “thinking” in the way we do. It’s your phone’s autocomplete, scaled up.
Type “How are” on your phone and it suggests “you” — because “you” is the most statistically likely next word. LLMs do the same thing, just with billions of parameters and much better grammar. This is next-token prediction.
The model looks at the words you’ve typed, checks its massive map of how words usually follow each other, and rolls a set of weighted dice to pick the next one.
Sampling one token
Picture how a model sees a sentence. It doesn’t see “Truth”; it sees a list of candidates with percentages.
import random
def simulate_next_token(context):
# This is a simplified version of what happens inside a transformer
candidates = {
"the": 0.45, # 45% chance
"a": 0.30, # 30% chance
"yesterday": 0.05,
"Mars": 0.20 # A 'creative' but potentially wrong choice
}
# The model picks based on these weights
next_word = random.choices(list(candidates.keys()), weights=candidates.values())[0]
return next_word
print(f"Next word chosen: {simulate_next_token('The explorer went to ')}")
candidates— a dictionary mapping possible next words to their probabilities, standing in for the model’s learned distribution over the vocabulary."the","a","yesterday","Mars"— four candidate continuations, with"the"at 45% and"Mars"at 20%.random.choices(list(candidates.keys()), weights=candidates.values())— performs weighted random sampling: it picks one word from the candidate list, with each word’s probability proportional to its weight.[0]— extracts the single chosen word from the list thatrandom.choicesreturns.- Return value — the chosen word, simulating one step of next-token prediction.
- Key insight: if the model picks
"Mars", it isn’t because the explorer actually went there—it’s because"Mars"had a high enough probability in the model’s training data to be a valid grammatical continuation. This is the core mechanism behind both creative writing and hallucination: the model is rolling weighted dice, not consulting a fact database.
The math behind the guess
The core mechanism of an LLM is next-token prediction: given the tokens seen so far (the context), the model computes a probability distribution over the entire vocabulary, then samples (or greedily picks) the next token.
where is the raw logit (unnormalized score) the model assigns to token , and is the vocabulary size. This is the softmax function — it converts raw scores into a probability distribution that sums to 1.
The log-prob of a chosen token is the natural log of that probability:
A log-prob near 0 (e.g., -0.01) means the model assigned near-100% probability to that token — very confident. A log-prob of -4.50 means the probability was roughly , or about 1.1% — the model was essentially guessing.
| Plain English | Statistical symbol | Python equivalent |
|---|---|---|
| Probability of next token given context | probs[i] | |
| Raw logit score for token | logits[i] | |
| Softmax over vocabulary | torch.softmax(logits, dim=-1) | |
| Log-probability of chosen token | torch.log_softmax(logits, dim=-1)[i] | |
| Confidence threshold for flagging | threshold = -1.0 |
If the model picks “Mars,” it isn’t because it knows the explorer went there. It’s because “Mars” had a high enough probability in its training data to be a valid grammatical choice. So researchers sometimes call LLMs “Stochastic Parrots” — they repeat the patterns of the internet without understanding what the words mean.
3. The Hardest Part: The ‘Confabulation’ Gap
The hardest part of causal inference and AI behavior: telling a “creative” choice from a “factual” error.
When an LLM writes a poem about a blue cat, we call it creative. When it writes a legal brief about a blue law that doesn’t exist, we call it a hallucination. Same math, both times.
What this means is that the model lacks grounding. It has no “world model.” It doesn’t know that gravity makes things fall — it only knows that the word “fall” frequently appears near the word “gravity.”
Here’s the catch. If the training data contains a lot of fiction or common misconceptions, the model will confabulate (make things up) based on those biases. If 1,000 internet forum posts say that eating silica gel is safe (it’s not), the model’s probability map will reflect that lie as a “truth.”
4. Measuring the Lie: Log-Probs and Uncertainty
Here’s the interesting part: we can peek under the hood and check whether the model is “nervous” about what it’s saying.
When a model generates a word, it assigns that word a probability. We call these log-probs (logarithmic probabilities). If the model is 99% sure the next word is “Paris,” the log-prob sits high. If it’s torn between five different names because it doesn’t really know the answer, the log-probs stay low.
That lets us catch lies. A factual statement full of low-probability words is a red flag.
# Using a hypothetical output from an API that provides logprobs
response_data = [
{"token": "The", "logprob": -0.01}, # Very confident
{"token": "capital", "logprob": -0.02},
{"token": "of", "logprob": -0.01},
{"token": "France", "logprob": -0.05},
{"token": "is", "logprob": -0.01},
{"token": "Limoges", "logprob": -4.50} # VERY LOW confidence!
]
for item in response_data:
if item['logprob'] < -1.0:
print(f"Warning: The model is unsure about the word '{item['token']}'")
response_data— a list of dictionaries, each holding atokenand itslogprob(the natural log of the probability the model assigned to that token when it was generated)."The","capital","of","France","is"— the first five tokens, with log-probs near 0 (e.g., -0.01, -0.02, -0.05), meaning the model was nearly 100% confident in each. These are common words with high probability in almost any context."Limoges"— the final token, with a log-prob of -4.50, which corresponds to a probability of roughly (about 1.1%). The model was essentially guessing.for item in response_data— iterates through each token inresponse_data.if item['logprob'] < -1.0— flags any token whose log-prob falls below -1.0 (roughly 37% confidence — ).- Warning print — when the condition triggers, it prints a warning identifying the uncertain token.
- Key insight: this is the basis of a “BS detector” — if a factual claim is built from low-probability tokens, the model is likely fabricating. The catch: most production APIs (like OpenAI’s) don’t expose per-token log-probs by default, so this technique requires an API that supports it or running an open-source model locally.
In this example, the model said “Limoges” instead of “Paris.” It printed the word, but its internal score was -4.50 — very low. The model was guessing. Check these numbers across your outputs and you’ve got a “BS detector” for your AI applications.
5. The Solution: Self-Reflection and RAG
So what does that mean for us? We can’t easily change how the model thinks, but we can change how we use it.
Two methods work well here: Self-Consistency and RAG (Retrieval-Augmented Generation).
Self-Consistency is like asking three different people the same question. If the AI gives three different answers, it’s hallucinating.
RAG is the “Open Book” method. Instead of asking the AI to recall a fact from its training, we hand it a specific document and say, “Only use this text to answer.”
Grounding the answer in a real document
Here’s how RAG fixes our Treaty of New York problem:
# The 'Truth' source
knowledge_base = {
"Treaty of New York": "A 1790 agreement between the US and the Creek people."
}
def rag_answer(query):
# 1. Search our 'truth' database
context = knowledge_base.get("Treaty of New York", "No data found.")
# 2. Give the AI the context so it doesn't have to guess
prompt = f"Using only this info: {context}, answer this: {query}"
# Now the AI has no reason to invent Aztecs
return "The Treaty of New York actually happened in 1790 with the Creek people."
print(rag_answer("Tell me about the Treaty of New York."))
knowledge_base— a dictionary holding the ground truth about the Treaty of New York: it was a 1790 agreement between the US and the Creek people (a real historical fact).rag_answer(query)— takes a query string and performs two steps.context = knowledge_base.get("Treaty of New York", "No data found.")— looks up the relevant context, simulating the retrieval step of RAG (in production, this would be a vector database search returning the most semantically similar chunk). If no data is found, it falls back to the string"No data found."prompt = f"Using only this info: {context}, answer this: {query}"— embeds the retrieved context directly into the prompt, constraining the model to answer only from the provided context.- Return value — the correct answer, grounded in the retrieved fact.
- Key insight: by giving the model the truth upfront, we move the task from “remembering” (where it fails) to “summarizing” (where it excels). For Rae’s support bot, this is exactly what she needs: instead of letting the bot invent a refund policy, she retrieves the actual policy text and instructs the model to use only that.
By giving the model the “truth” upfront, we move the task from “remembering” (where it fails) to “summarizing” (where it excels).
Hallucination Mitigation Strategies: When Each Helps and When It Falls Short
Rae tried several approaches after the burrito refund incident. Here’s what works, what partially works, and what doesn’t fully solve the problem:
RAG (Grounding via retrieval):
- When it helps: When the answer exists in the retrieved context and the question is about a specific fact (e.g., “What’s the return policy for the burrito warmer?”). The model reads the answer and summarizes it — moving from “remembering” to “reading comprehension.”
- When it doesn’t fully solve: When the model ignores the retrieved context and hallucinates anyway (a “context adherence” failure — the model sees the context but generates something else). Also when the retrieval step fetches the wrong chunk — garbage in, garbage out. RAG reduces hallucination but doesn’t eliminate it.
Lower temperature:
- When it helps: Temperature controls how “creative” the token sampling is. Setting temperature to 0 (greedy decoding) makes the model always pick the single highest-probability token, reducing random creative leaps. Good for factual QA where you want the most probable answer, not the most inventive one.
- When it doesn’t fully solve: Low temperature reduces random hallucinations but not systematic ones. If the model’s probability map is wrong (e.g., it learned a common misconception from training data), temperature 0 will confidently output the wrong answer every time — consistently and confidently wrong.
Confidence / log-prob thresholds:
- When it helps: When you can access the model’s per-token log-probs. Tokens with very low log-probs signal the model is guessing — you can flag or reject responses where key factual tokens fall below a threshold (e.g., log-prob < -1.0).
- When it doesn’t fully solve: Log-probs measure the model’s confidence, not its correctness. A model can be very confident and very wrong — high probability does not equal true. Also, most production APIs (OpenAI, Anthropic) don’t expose per-token log-probs by default, making this impractical for many deployments without running an open-source model locally.
Refusal prompting (system prompts that say “If you don’t know, say you don’t know”):
- When it helps: For questions clearly outside the model’s knowledge or the retrieved context. A strong system prompt like “Answer only using the provided context. If the answer is not in the context, say ‘I don’t know’” can reduce fabrication by giving the model permission to abstain.
- When it doesn’t fully solve: Models still hallucinate within the guardrails — they may find a plausible-sounding answer in the context that isn’t actually there, or subtly misread it. Refusal prompting reduces the surface area but doesn’t close the gap entirely.
Rae’s takeaway: No single technique eliminates hallucination. She needs RAG for grounding, a low temperature for consistency, refusal prompts for guardrails — and critically, a way to measure whether these fixes are actually working. Which is exactly what she’ll build next.
Summary Checklist
- LLMs are not databases: They predict the next likely word, not the next true fact.
- Fluency is not accuracy: A well-crafted sentence can still be wrong.
- Check the log-probs: If you can access the model’s confidence scores, use them to flag shaky answers.
- Use RAG: Don’t let the AI guess. Give it the data it needs.
Rae patches the burrito refund incident with a RAG fix, a lower temperature, and a stronger system prompt. A week later, another fabricated answer slips through. Then another. She can’t eyeball every response the bot generates to see if it “looks right.” She needs a systematic way to measure whether her fixes are working—and to catch hallucinations before her customers do. Next article, she’ll learn how to evaluate LLM output beyond just checking whether it “looks right.”
Check Your Understanding
Questions below move from simple recall up to open-ended design, roughly following Bloom’s Taxonomy.
Remember What is next-token prediction, and why does the article say it means an LLM has a “probability map” rather than a “truth database”?
Understand Explain in your own words why the article calls an LLM a “world-class mimic, not a librarian.” What is the difference between the two when a question asks about the Treaty of New York?
Apply
Using the logprob thresholds from Section 4, a model outputs the sentence “The capital of France is Limoges” with the token Limoges scored at -4.50. Write out the loop condition from the code that would flag Limoges, and state what the warning would tell you about the model’s confidence.
Analyze The article says the model does “the exact same math” when writing a poem about a blue cat and when writing a legal brief about a law that doesn’t exist. Walk through why one output is labeled “creative” and the other “hallucination,” given that the underlying mechanism is identical.
Evaluate Section 5 proposes Self-Consistency as a hallucination detector: ask the same question multiple times, and treat disagreement as a sign of fabrication. Critique that approach—describe a realistic scenario where three confident, consistent answers could all still be wrong, and explain why agreement alone isn’t proof of truth.
Create Design one additional detection or prevention technique beyond log-probs, self-consistency, and RAG that a production system could use to catch confident hallucinations. Describe how it would work, what failure mode it targets, and one limitation it would still have.
Related articles
References & Further reading
- Ji, Z., Lee, N., Frieske, R., Yu, T., Su, D., Xu, Y., Ishii, E., Bang, S.J., Madotto, A., & Fung, P. (2023). Survey of Hallucination in Natural Language Generation. arXiv:2202.03629
- Bender, E.M., Gebru, T., McMillan-Major, A., & Shmitchell, S. (2021). On the Dangers of Stochastic Parrots: Can Language Models Be Too Big? FAccT ‘21. doi:10.1145/3442188.3445922
- OpenAI. (2024). Logprobs API documentation. platform.openai.com/docs/api-reference/chat
Apply What You Learned is for Supporter and Insider subscribers.
Subscribe to unlock the exercises on this post.
See plansRelated articles
- LLMs & GenAI Under review
Why LLMs Forget the Middle: Understanding Context Windows and Lost in the Middle
Discover why LLMs ignore information in the middle of long prompts, how the Lost in the Middle phenomenon hurts RAG, and how reordering and reranking fix it.
- LLMs & GenAI Under review
Fine-Tuning vs. RAG: How to Actually Decide
Stop LLM hallucination: learn when to fine-tune vs. use RAG, with a decision framework, code examples, and a practical readiness checklist for your project.
- LLMs & GenAI Under review
RAG vs. Long-Context Models: Which Wins in 2026?
Should you use RAG or Long-Context LLMs in 2026? Compare cost, accuracy, and Lost-in-the-Middle trade-offs to see why a hybrid retrieval approach wins.
- LLMs & GenAI Under review
Building Your First RAG Pipeline: Chunking, Embedding, and Retrieval
Learn to build a complete RAG pipeline from scratch: chunk your documents, embed text into searchable vectors, and retrieve the right passages for your LLM.
Looking for something else?
Search every article by title, summary or topic.