Zero Labs
Industry News / AI

Why AI Makes Things Up: A Complete Guide to LLM Hallucination

Source · Towards AI By Sanjana Dubey

From the publisher’s feed, collected in the ZeroLabs newsroom.

A complete 2026 guide to LLM hallucination: what it is, the types, how to detect it, how industry reduces it, and a working code example.Source: Image by Sanjana Dubey1. What is a hallucination, in plain wordsImagine asking a very well read friend a question they do not know the answer to. A good friend says “I am not sure.” A bad friend, who hates looking clueless, invents a smooth answer on the spot, in the same calm tone they use when they are right.A large language model (LLM) is the second kind of friend by default. A hallucination is output that sounds fluent and confident but is false, invented, or not supported by the material the model was supposed to rely on.Three quick examples:You ask for sources on a topic and get five neat citations. Two of the papers do not exist.You paste a contract and ask for a summary. The summary says the notice period is 60 days. The contract says 30.A support bot tells a customer a refund policy exists. It does not.Note what these share: nothing in the tone warns you. The wrong answer looks identical to the right one.2. Why It Happens: The Mathematics of Confident WrongnessThe model only predicts the next tokenAn LLM does not store facts the way a database does. It does not look anything up. At every single step of generation, it does one thing: it looks at all the text so far and asks, what is the most probable next token?The model takes your input and produces a vector of raw numbers called logits. GPT-2, for example, has a vocabulary of 50,257 tokens, so at each step the model outputs 50,257 numbers, one score for each possible next token. These raw scores are then passed through a function called softmax:P(token_i | context) = exp(logit_i) / sum of exp(logit_j) over all tokensSmall example (numbers made up for illustration): Say there are only three candidate tokens with logits 4.0, 2.0 and 1.0. Softmax gives:Token A: 0.84Token B: 0.11Token C: 0.04The model then picks a token. It either takes the highest one (greedy decoding) or samples from the distribution. It adds that token to the text and repeats the whole process. A full answer is just this loop run many times.Nothing in this loop checks whether the output is true.Probability is not truthA hallucination is a case where a false continuation gets a higher probability than the true one:P(false answer | context) > P(true answer | context)Nothing in the decoding process breaks this tie by checking reality. The model picks whatever has the highest score. If the pattern of your question resembles questions whose true answers it saw many times during training, it is likely to be correct. If the question is about something rare, ambiguous, or poorly represented in training data, the model still produces a confident answer, because the softmax always outputs a distribution. There is no “I do not know” token built into the mechanism. The probability mass has to go somewhere.Example:Prompt: “The capital of France is”Paris 0.97Lyon 0.01Other 0.02The model saw this fact thousands of times, so the right token wins easily.Prompt: “The 2021 Meridian Prize for poetry was won by” (a prize that does not exist)Name 1 0.09Name 2 0.07Name 3 0.05... thousands of other names with small valuesThe probabilities are spread thin, but they still add up to 1, so one name still comes out on top. The model writes it in the same confident tone as “Name 1”. You cannot tell the difference from the text alone.Errors build on errorsEach token is generated conditioned on everything that came before it, including any errors already committed. If the model makes a wrong claim at position t, every token at position t+1, t+2, t+3 is now generated to be consistent with that wrong claim. This is called exposure bias in the research literature. The model was trained on clean human text and never learned to recover from its own mistakes mid-generation.Example: The model says a bridge was built in 1847, but it was really built in 1883. The next sentences about the architect, the materials and the opening ceremony are now written to fit 1847. The final paragraph is detailed and consistent with itself, but it stands on one wrong token.Training rewards plausible text, not true textPretraining uses cross entropy loss. At each position, the model is penalized when it gives a low probability to the token that actually came next in the training text:Loss = - log P(actual next token | tokens before it)This teaches the model to produce text that looks like its training data. It does not teach the model to produce text that is true. Training data also has errors and gaps, and facts are stored in the model’s parameters in a compressed and imperfect way. Rare facts can get blurred together.After pretraining, many models are tuned with human feedback (RLHF). This can reward answers that sound complete and confident over answers that admit doubt, so the most rewarded answer is not always the most honest one.The incentive problem: models learn to bluffThere is a second cause that gets less attention. It is about how models are graded.Researchers at OpenAI, including Adam Tauman Kalai and Santosh Vempala, argue that standard training and evaluation reward guessing over admitting uncertainty. Most benchmarks give 1 point for a correct answer and 0 points for a wrong answer. An answer like “I do not know” also gets 0 points. So a guess can only help the score, and it never hurts.Think of a multiple choice exam with no penalty for wrong answers. The student who always guesses scores higher than the student who leaves blanks. If AI benchmarks work the same way, models learn that bluffing pays.Example: A model faces 300 four option questions it is unsure about. If it abstains on all of them, it scores 0. If it guesses, it gets about 75 right by chance (25 percent). The guessing model gets the higher benchmark score. Across millions of training steps, that signal teaches the model to always answer.The researchers suggest changing the scoring so that confident wrong answers cost more than abstaining, and so that models get credit for knowing what they do not know. This would need coordinated changes across major benchmarks, and it has not been widely adopted yet.The full pictureSource: Image by Sanjana Dubey3. The Types of HallucinationNot every hallucination is the same, and the right fix depends on which kind you are facing. Researchers use two simple questions to sort them.Question 1: Is the answer wrong about the world, or wrong about what you told the model? This gives two types: factuality and faithfulness.Question 2: When you gave the model a document, did it go against that document, or add things the document never said? This gives two types: intrinsic and extrinsic.These are two separate ways of sorting, from two different bodies of research. The intrinsic and extrinsic labels are the older pair. The factuality and faithfulness labels come from a 2023 survey of LLM hallucination. In real projects you will often use both labels together.The diagram shows the four classic labels.Source: Image by Sanjana DubeyType 1: Factuality hallucinationWhat it is: The model says something that is wrong about the real world. The prompt does not matter. The claim is simply false or cannot be verified.Example: “Napoleon won the Battle of Waterloo.” He lost it.It comes in two flavors:Wrong fact. A real fact is mixed up. For example, saying Thomas Edison invented the telephone, when it was Alexander Graham Bell.Made up fact. The model invents something that does not exist, such as a research paper, a quote or a court case.Fix to reach for: Give the model a trusted source to read from (retrieval, covered in Section 5), or let it say “I do not know”.Type 2: Faithfulness hallucinationWhat it is: The model does not follow what you gave it. This can mean your instructions, your document, or even its own earlier steps. The claim may even be true, but the model did not do what you asked.Example: You write “Answer only from this document.” The model quietly adds facts from its own memory.Example: You ask for a Spanish translation of a question, and the model answers the question instead.Fix to reach for: Clear instructions, structured output, and a check in code that the answer really comes from your document. You will build this check in the project at the end of this post.Type 3: Intrinsic hallucinationWhat it is: The model contradicts the text you gave it. The truth was right there in front of it.Example: Your document says “The meeting is on Tuesday.” The model’s summary says “The meeting is on Wednesday.”Fix to reach for: Compare the answer against the source. A simple check in code, or a second model acting as a judge, can catch this.Type 4: Extrinsic hallucinationWhat it is: The model adds details that are not in your source. They are not contradicted by it either. They are just unsupported. They might even be true, but you cannot prove them from the document.Example: A company report is summarized as showing “record growth in Asia”. The report never said that.Fix to reach for: Ask the model to quote the exact sentence behind every claim, and remove any claim that has no quote.Quick comparisonFactuality: Wrong about the world. Example: Napoleon won Waterloo.Faithfulness: Did not follow your instructions or context. Example: Used outside knowledge when told not to.Intrinsic: Contradicts your source. Example: Says Wednesday when the source says Tuesday.Extrinsic: Adds what your source never said. Example: Adds “record growth in Asia”.Source: Image by Sanjana DubeyThe newer types you will hear about in 2026As companies move from chatbots to AI agents that call tools and act on their own, three more categories matter.Tool hallucination. The agent invents a function that does not exist, claims it ran a tool it never ran, or uses an irrelevant tool instead of admitting it cannot do the task. It has four subtypes.Invented tool: it calls a function that does not exist, such as update_user when only create_user and delete_user are available.Wrong tool: the tool exists but does not fit the task, like calling a reporting function to check stock.Wrong arguments: the tool is real, but the agent adds an option it does not accept or skips one it requires.Pretend run: the agent never calls the tool and writes a realistic looking result as if it did.2. Silent hallucination. The agent forms a false belief inside its own work and acts on it without ever stating it, so there is no wrong sentence for you to spot. For example, it assumes a price column is in dollars when it is in cents, and every refund it calculates is wrong.3. Cascading hallucination. In a system of several agents, one fabricates a number, the next treats it as verified, and a third acts on it. Each step looks consistent, yet the whole chain rests on an invention.Even more typesResearchers have also sorted agent hallucinations by the stage of the agent loop. A 2025 survey lists five:Reasoning: the agent misunderstands the goal or makes a bad plan.Execution: the agent fails when turning a plan into actions, usually through tools.Perception: the agent misreads what it sees in its environment.Memory: the agent saves wrong information, or retrieves the wrong thing later.Communication: wrong messages spread between agents.4. The twist: smarter models can hallucinate moreFor two years the working assumption was that teaching models to reason makes them more reliable. A paper at ACL 2026, “The Reasoning Trap: How Enhancing LLM Reasoning Amplifies Tool Hallucination” by Chenlong Yin, Zeyang Sha, Shiwen Cui, Changhua Meng and Zechao Li, challenged that for tool use.The authors built a diagnostic called SimpleToolHalluBench with two traps, using 296 tools. In one, the task needs a tool but that tool is removed. In the other, only an irrelevant tool is provided. An honest model should say “I cannot do this.” A hallucinating model fakes it.What they reported:Strengthening reasoning through reinforcement learning raised tool hallucination in step with task gains.Training on math alone, with no tools involved, still increased tool hallucination. The authors argue this means the problem is not just overfitting to tool tasks.The effect also appeared when reasoning was added by fine tuning, or simply switched on at inference.Example: Qwen3 8B hallucinated in 36.2 percent of the irrelevant tool trap with thinking off, and 56.8 percent with thinking on.Prompting helped only a little. Preference tuning (DPO) cut hallucination a lot, but it also lowered tool use performance.The tests used small and mid size open models, so the results do not automatically apply to every frontier model.A similar pattern shows up in OpenAI’s own report. On its PersonQA test of facts about people, o3 hallucinated on 33 percent of questions against 16 percent for o1, and o4 mini reached 48 percent. This is a different kind of test, and OpenAI said more research is needed to explain it. The lesson for readers: a stronger model is not automatically a more honest one, so verification matters more, not less.5. How to detect hallucinationsDetection methods fall into four families, from cheap to expensive.1. Check against the source (deterministic)If the answer should come from a document, test in code that every quote really appears in it. This is fast, free and very strong. It proves the quote exists, not that the model understood it correctly, so pair it with a judge. The project below uses this check.2. Check for consistencyAsk the same question several times with some randomness. A model that knows the answer repeats it. A model that is guessing drifts.SelfCheckGPT (EMNLP 2023) does this without any outside database and without access to model internals.Semantic entropy (Oxford researchers, Nature, 2024) groups the sampled answers by meaning, not exact wording, and measures how scattered the meanings are. It costs roughly 10 times the compute of one call.A minimal version in Python. Use a temperature above zero, otherwise every answer is identical:from collections import Counterdef consistency_score(ask, prompt, n=5): answers = [ask(prompt).strip().lower() for _ in range(n)] top, count = Counter(answers).most_common(1)[0] return top, count / n # low ratio means a likely guessExact string matching is too strict for long answers, so real systems compare meaning with embeddings or an entailment model. The blind spot: a model that gives the same wrong answer every time looks confident.3. Check each claim against evidenceBreak a long answer into single facts and check each one.SAFE (Google DeepMind, 2024) splits an answer into individual facts, searches Google for each, and rates it as supported or not. On about 16,000 facts it agreed with human raters 72 percent of the time, and cost about $0.19 per response against about $4 for human raters.Cloud guardrails do a similar job in production. Amazon Bedrock’s contextual grounding check scores an answer for grounding (is it based on the source?) and relevance (does it answer the question?), and blocks answers below a threshold you set. It supports summarization, paraphrasing and question answering, but not chatbot conversations.5. Look inside the modelResearch on probing internal activations can spot some hallucinations the text does not reveal. It needs access to the model’s internals, so it only works with open weight models, and probes often do not transfer well between tasks. This is mostly for model builders.6. Test before and after you shipKeep a set of questions with known answers and track the hallucination rate each time you change the model, the prompt or the documents. For agents, log every tool call and check it against the list of real tools.7. How industry reduces hallucinationNo serious team claims to eliminate it. They stack layers, as in the table.Source: Image by Sanjana DubeyThe pattern behind all of them is the same: never let the model be the only judge of its own answer, and make “I do not know” a valid, safe outcome.8. Hands on: fix a real hallucination problem with Python and GroqThe problem. The Air Canada story is the perfect test. A customer support bot gets asked about refund policy. A naive bot answers from vague memory and may invent a policy. We will build a bot that only answers from the company’s own policy text, proves its answer with exact quotes, double checks itself, and otherwise hands off to a human.The design, shown below, has five gates between the question and the customer:Retrieve the relevant policy snippets. If none match, escalate immediately without calling the model.Ask the model for a JSON answer that must include exact quotes.Check in plain code that each quote appears word for word in the cited snippet.Ask a second, cheaper model whether every claim in the answer is supported.Only then answer. Any failed gate triggers escalation to a human.Source: Image by Sanjana DubeyHere is the working code, followed by what I did and did not verify.The codeInstall and set your key (get one at console.groq.com/keys):pip install groqexport GROQ_API_KEY="your key here"Save this as support_bot.py:import jsonimport osimport reGEN_MODEL = "llama-3.3-70b-versatile"JUDGE_MODEL = "llama-3.1-8b-instant"# Demo policy text written for this tutorial. It is NOT a real airline policy.POLICY = [ {"id": "P1", "text": "Bereavement fares: Discounts must be requested before the ticket is booked. Refunds for bereavement fares cannot be claimed after travel is completed."}, {"id": "P2", "text": "Cancellations: Tickets cancelled within 24 hours of booking are fully refundable. After 24 hours a cancellation fee of 100 dollars applies."}, {"id": "P3", "text": "Checked baggage: The first checked bag is free on international flights. Domestic flights charge 30 dollars for the first bag."}, {"id": "P4", "text": "Pets: Small pets in approved carriers may travel in the cabin for a fee of 75 dollars each way."},]STOPWORDS = {"the", "a", "an", "is", "are", "can", "i", "my", "to", "for", "of", "on", "in", "do", "does", "how", "what", "and", "or", "it", "if", "after", "before"}def tokenize(text): return [w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOPWORDS]def retrieve(question, k=3): q = set(tokenize(question)) scored = [] for chunk in POLICY: score = len(q & set(tokenize(chunk["text"]))) if score > 0: scored.append((score, chunk)) scored.sort(key=lambda s: s[0], reverse=True) return [c for _, c in scored[:k]]def get_client(): from groq import Groq return Groq(api_key=os.environ["GROQ_API_KEY"])def parse_json(text): try: return json.loads(text) except (json.JSONDecodeError, TypeError): match = re.search(r"\{.*\}", text or "", re.DOTALL) if match: try: return json.loads(match.group(0)) except json.JSONDecodeError: return None return Nonedef call_llm(client, model, system, user, json_mode=True): kwargs = {"response_format": {"type": "json_object"}} if json_mode else {} resp = client.chat.completions.create( model=model, temperature=0, messages=[{"role": "system", "content": system}, {"role": "user", "content": user}], **kwargs, ) return resp.choices[0].message.contentdef naive_answer(client, question): return call_llm(client, GEN_MODEL, "You are an airline support agent.", question, json_mode=False)GEN_SYSTEM = ( "You are an airline support agent. Answer ONLY using the SOURCES provided. " "If the sources do not contain the answer, set can_answer to false. " 'Reply as JSON: {"can_answer": bool, "answer": str, ' '"citations": [{"source_id": str, "quote": str}]}. ' "Each quote must be copied exactly from the source text.")JUDGE_SYSTEM = ( "You are a strict fact checker. Given SOURCES and an ANSWER, decide whether every claim " "in the answer is directly supported by the sources. " 'Reply as JSON: {"supported": bool, "unsupported_claims": [str]}.')def norm(s): return re.sub(r"\s+", " ", s.lower()).strip()def verify_citations(result, chunks): by_id = {c["id"]: norm(c["text"]) for c in chunks} cites = result.get("citations") or [] if not cites: return False, "no citations given" for c in cites: source = by_id.get(c.get("source_id")) if source is None: return False, "cited a source that was not retrieved" if norm(c.get("quote", "")) not in source: return False, "quote not found verbatim in source" return True, "ok"def escalate(reason): return {"status": "escalated", "reason": reason, "reply": "I am not able to confirm that. I am passing you to a human agent."}def grounded_answer(client, question): chunks = retrieve(question) if not chunks: return escalate("no relevant policy found") sources = "\n".join(f"[{c['id']}] {c['text']}" for c in chunks) raw = call_llm(client, GEN_MODEL, GEN_SYSTEM, f"SOURCES:\n{sources}\n\nQUESTION: {question}") result = parse_json(raw) if not result: return escalate("model did not return valid JSON") if not result.get("can_answer"): return escalate("model said sources do not contain the answer") ok, why = verify_citations(result, chunks) if not ok: return escalate(f"citation check failed: {why}") judge_raw = call_llm(client, JUDGE_MODEL, JUDGE_SYSTEM, f"SOURCES:\n{sources}\n\nANSWER: {result['answer']}") verdict = parse_json(judge_raw) if not verdict or not verdict.get("supported"): return escalate("judge found unsupported claims") return {"status": "answered", "reply": result["answer"], "citations": result["citations"]}if __name__ == "__main__": client = get_client() for q in ["Can I claim a bereavement discount after my trip?", "Does the plane have wifi?"]: print("Q:", q) print("NAIVE:", naive_answer(client, q)) print("GROUNDED:", grounded_answer(client, q)) print()Run it with python support_bot.py.What you should seeFor the bereavement question, the naive bot answers from general knowledge and may well say something helpful sounding that does not match your policy. The grounded bot should reply that the discount must be requested before booking, with a quote from P1 attached. For the wifi question, the policy has nothing about wifi, so the grounded bot escalates before it even calls the model, while the naive bot will happily say something. That second case is the whole point: the safe behavior is a handoff, not a guess. I have not run this against the live Groq API, so treat those outputs as the intended behavior, not recorded results.Key TakeawaysHallucination comes from how models are trained and tested, so plan for it. A model learns to write the most likely next word, not to check facts. OpenAI researchers also argue that many tests give zero points for “I do not know”, so guessing pays. Expect some wrong answers and build checks around them.A confident tone is not evidence. A wrong answer is written in the same style as a right one, so you cannot judge truth from how an answer sounds.Know what kind of error you are facing. Some answers are wrong about the world (factuality), some ignore your instructions or source (faithfulness), and some add things your document never said (extrinsic). Each needs a different fix.Agents bring new errors. They can invent tools, claim they ran a tool when they did not, act on false assumptions they never state, and pass one mistake down a chain of agents. Check every tool call against the list of real tools, and add checks between agents.A newer, smarter model is not automatically more honest. The Reasoning Trap research found that training models to reason better also made them more likely to invent or misuse tools, at least in the open models it tested. Do not skip verification just because you upgraded.No single detector catches everything. Combine a source check, a consistency check, a claim by claim check, a judge model, and a test set of questions with known answers.Every check has a blind spot. An exact quote check proves a quote exists, not that the model understood it. A consistency check misses a model that gives the same wrong answer every time. A judge can itself be wrong.Use several layers of defense. Give the model trusted sources, make it show the exact evidence, check that evidence in code, add a judge model, and make “I do not know” a safe answer that hands off to a human.Measure it and keep humans in the loop. Track the hallucination rate each time you change the model, prompt or documents, and review high stakes answers by hand. No method removes hallucination completely.Frequently Asked QuestionsWhat is an LLM hallucination?It is a confident answer that is false, not supported by your documents, or does not follow your instructions.Why do models hallucinate?A model always picks a most likely next word, even when it does not know the answer, and nothing in that process checks if the answer is true. Tests that reward guessing over admitting doubt make this worse.Can hallucinations be removed completely?Not in practice. Every method reduces them, and Anthropic’s own guidance says important information should still be checked.What is the difference between factuality and faithfulness errors?A factuality error is wrong about the real world, like saying Napoleon won Waterloo. A faithfulness error does not follow what you gave the model, like using outside knowledge when you said to answer only from the document.Do bigger or reasoning models hallucinate less?Not always. On OpenAI’s PersonQA test, o3 hallucinated on 33 percent of questions against 16 percent for o1. The Reasoning Trap paper found a similar pattern for tool use in the open models it tested.Does RAG fix the problem?It helps a lot, but the model can still misread or add to the documents it is given. Check its quotes in code.Does a lower temperature help?It reduces random guesses, but it does not fix wrong knowledge.How can I detect hallucinations?Use layers. Check quotes against the source in code, ask the same question several times and see if the answers drift, check each claim against evidence, and use a judge model. Keep a test set so you can track the rate over time.What is semantic entropy?It is a method from Oxford researchers, published in Nature in 2024. It samples several answers, groups them by meaning, and measures how scattered the meanings are. Scattered meanings suggest the model is guessing. It costs roughly 10 times the compute of one call.Is a judge model enough on its own?No. A judge is flexible, but it can be wrong too, so use it together with code checks.What should an agent do when it has no suitable tool?It should say it cannot do the task. Inventing a tool, or using an irrelevant one, is exactly the tool hallucination the Reasoning Trap benchmark tests for.What is the easiest check to start with?If the answer should come from a document, check in code that every quote really appears in it. It is fast and free.Is saying “I do not know” bad for users?It is safer than a confident wrong answer. Pair it with a hand off to a human so the user still gets help.Is this only a chatbot problem?No. Agents that use tools and pass work to other agents can spread one mistake through a whole chain, though a 2026 study found this depends on how the system is designed.ReferencesAI Hallucinations Are a Test Taking Problem, Says OpenAIA Survey on Hallucination in Large Language ModelsLLM based Agents Suffer from Hallucinations: A Survey of Taxonomy, Methods, and DirectionsThe Reasoning Trap (ACL 2026)Detecting hallucinations using semantic entropy (Oxford, Nature 2024)Anthropic: Reduce hallucinationsWhy AI Makes Things Up: A Complete Guide to LLM Hallucination was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.