1. Home
  2. Blog
  3. Artificial Intelligence

Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

A language model can give a confident, well-written answer that is simply false. Learn why this happens, the forms it takes, and practical ways to reduce and detect it in your own AI features.

8 min read
AI hallucinations explained: why language models make things up and how to reduce it

Key takeaways

  • An AI hallucination is output that sounds plausible but is false or unsupported.
  • Models predict likely text. They have no built-in way of knowing what is true.
  • Grounding answers in trusted sources, clear prompts and automated checks reduce hallucinations.
  • No current technique removes them completely, so important outputs still need verification.

A support chatbot tells a customer that refunds take 14 days. The real policy says 7. The answer was fluent, polite and wrong. This is an AI hallucination, and it is one of the main reasons AI features need careful design and testing.

This guide explains the causes in plain terms and focuses on practical prevention. The automated check near the end is a small Python script we ran against example answers we wrote ourselves. It was not run against a live AI model.

What is an AI hallucination?

A hallucination is when a generative AI system produces content that is factually wrong, made up, or not supported by the information it was given, while presenting it as true. The term is a metaphor. The model is not seeing things. It is generating text that fits the pattern of a good answer without being tied to facts.

The dangerous part is the confidence. A hallucinated answer usually looks exactly like a correct one, with the same tone, structure and detail.

Why language models hallucinate

A large language model is trained to predict the next piece of text, a token, based on patterns in a huge amount of training data. Several things follow from that:

  • Plausible is not the same as true. The model learns what answers tend to look like. When it lacks the facts, the most likely-looking continuation can still be invented.
  • Gaps and cut-offs. Training data has gaps and ends at a certain date. The model may fill in missing facts rather than say it does not know.
  • Training rewards answering. Research, including a 2025 OpenAI paper on why models hallucinate, argues that common training and evaluation methods reward guessing over admitting uncertainty, much like a multiple-choice test with no penalty for wrong answers.
  • Ambiguous prompts. Vague questions invite the model to assume details.
  • Long or messy context. Important facts can be overlooked when buried in long inputs.

Common types of hallucination

Type Example
Invented facts A wrong date, number or statistic
Fake sources Citations, papers or URLs that do not exist
Unfaithful summaries A summary that adds claims not in the document
Made-up code Calls to functions or packages that do not exist
Wrong reasoning Each step looks fine, but the conclusion does not follow
False confidence Answering a question that has no reliable answer

Researchers often split these into factuality errors, which contradict the real world, and faithfulness errors, which contradict the source material the model was given. For business apps built on your own documents, faithfulness is usually what you can test most directly.

Made-up code deserves a special warning. If an assistant suggests installing a package that does not exist, an attacker can publish a malicious package under that name. Check that every suggested dependency is real and trusted before installing it.

Where it matters most

A hallucinated movie fact is harmless. A hallucinated drug dose, legal citation, refund policy or financial figure is not. There have been well-reported cases of lawyers submitting court filings with case citations invented by AI tools. Rank your use cases by the cost of a wrong answer, and apply the strongest controls where that cost is high.

How to reduce hallucinations

  1. Ground the answer in trusted data. Give the model the relevant facts rather than relying on its memory.
  2. Allow “I don’t know”. Tell the model explicitly to say when the information is not available, and treat that as a good outcome.
  3. Be specific. Clear, narrow questions leave less room for invention. Our prompt engineering guide covers this in detail.
  4. Ask for quotes or citations from the provided sources, then verify them automatically.
  5. Use structured output, such as JSON with fixed fields, so answers are easier to validate.
  6. Use tools for things models are weak at, like calculations, dates and live data lookups.
  7. Keep a human in the loop for high-stakes decisions.

Grounding with your own data

Retrieval-augmented generation (RAG) is the most common grounding pattern. The system searches your documents for passages relevant to the question and includes them in the prompt, with instructions to answer only from those passages. It sharply reduces invented facts, but it is not a cure. The model can still misread a passage, combine passages wrongly, or fall back on its own knowledge, and the search step can return the wrong documents. So grounded systems still need checks.

Tip: Log the retrieved passages alongside each answer. When a wrong answer is reported, you can quickly tell whether retrieval failed or the model ignored good context. The fix is different for each.

A simple automated check

Here is one cheap guard we built: flag any number in an answer that does not appear in the source text. It is crude, but numbers like prices, days and limits are exactly where costly hallucinations show up.

import re

SOURCE = """Refunds are paid within 7 days to the original payment method.
Orders over 1000 rupees ship free. Standard delivery takes 3 to 5 working days."""

def unsupported_numbers(answer, source):
    found = set(re.findall(r"\d+", answer))
    allowed = set(re.findall(r"\d+", source))
    return sorted(found - allowed, key=int)

We tested three answers written to imitate typical model output:

grounded     -> no unsupported numbers
hallucinated -> ['14', '500']
partly       -> ['1']

The “hallucinated” answer claimed 14-day refunds and free shipping over 500 rupees, and both numbers were caught. The “partly” answer had correct delivery times but added “or 1 day with express”, which the policy never mentions, and that was caught too. A second check verifies that quoted phrases really appear in the source:

{'paid within 7 days': True, 'no questions asked': False}

These checks have obvious limits. They miss wrong words, units and unsupported claims without numbers, and they would wrongly flag a correct calculation. Many teams add an “LLM as a judge” step, where a second model checks each claim against the sources. That catches more, but it can be wrong too, so measure it.

Testing for hallucinations

Treat hallucination rate as a quality metric you measure, not a feeling. A practical approach:

  • Build a test set of real questions with known correct answers and sources.
  • Include questions the system should refuse, because the answer is not in the data.
  • Score answers for correctness, faithfulness to sources and appropriate refusals.
  • Run the set on every change to prompts, models or retrieval settings.
  • Sample production conversations for human review.

The discipline of regression testing applies here too: a fixed set of cases, run on every change, with results compared over time. When choosing how to ground a system, our comparison of RAG vs fine-tuning vs prompt engineering explains the trade-offs.

Advice for everyday users

  • Verify facts, figures, quotes and citations from the original source.
  • Be especially careful with medical, legal and financial information.
  • Paste the source text in and ask the assistant to answer only from it.
  • Ask “how confident are you, and what is this based on?”, but remember the answer can also be wrong.

Can hallucinations be eliminated?

Not with current technology. Newer models and better training have reduced hallucination rates on many benchmarks, and grounding helps a great deal, but every system still makes mistakes. The realistic goal is to make errors rare, easy to detect and low in impact through system design, testing and clear signals to users.

Hallucinations in AI coding tools

Developers meet hallucinations daily in coding assistants: a method that does not exist on a class, an outdated configuration option, or a confident explanation of an error that is really caused by something else. The defences are the ones you already use for human code. Compile or type-check the result, run the tests, and read the official documentation for any API you have not used before. Take extra care with security-sensitive code, such as authentication, cryptography and input validation, where plausible-looking code can be subtly unsafe. Treat AI suggestions as a draft from a fast but unreliable colleague: often useful, never automatically correct.

Final thoughts

Hallucinations come from how language models work: they generate likely text, not checked facts. You cannot switch them off, but you can design around them. Ground answers in trusted data, let the model say “I don’t know”, add automatic checks for the details that matter, and measure the results continuously.

Frequently asked questions

What is an AI hallucination?

It is when an AI system produces false or unsupported information and presents it as true, such as an invented statistic, citation or policy detail.

Why do AI models hallucinate?

Language models predict likely text based on patterns, not verified facts. Gaps in training data, vague prompts and training that rewards guessing all make hallucinations more likely.

Does RAG stop hallucinations?

It reduces them by giving the model trusted information, but it does not stop them. The model can still misread sources, and retrieval can return the wrong documents.

How can you detect AI hallucinations?

Compare answers against source documents, check numbers and quotes automatically, use a second model to verify claims, and review samples with people.

Will AI hallucinations ever go away?

Rates are falling as models improve, but no current method removes them entirely. Important outputs still need checks and human review.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →