Forward Deployed EngineeringAI EngineeringLLM Reliability
Why do LLMs hallucinate?
Question 16 of 73 · Updated
On this page
- Interview-ready answer
- 1. What counts as a hallucination?
- 2. Why hallucinations occur
- Training objective and learned knowledge
- Ambiguity and missing context
- Failure to use available evidence
- Autoregressive generation and reasoning errors
- 3. Two useful distinctions: factuality and faithfulness
- 4. Why temperature zero does not guarantee accuracy
- 5. Why RAG does not eliminate hallucinations
- 6. A production mitigation strategy
- Ground the answer in trusted information
- Constrain generation appropriately
- Validate important claims and actions
- Allow uncertainty and escalation
- 7. How to evaluate hallucinations
- Python example: aggregate human-labeled claim support
- 8. Debugging a hallucination in an enterprise workflow
- 9. Practical FDE engineering trade-offs
- Likely interviewer follow-ups
Interview-ready answer#
LLMs hallucinate because they are trained primarily to predict plausible tokens from context, not to independently verify that every generated claim is true. They learn statistical patterns from training data, which can be incomplete, outdated, inconsistent, or incorrect. When the model lacks reliable information, misunderstands a question, or fails to use the supplied evidence, it can still generate a fluent and confident-looking answer.
There is no single cause. Hallucinations can arise from the model's learned knowledge, the prompt, retrieval failures, reasoning mistakes, or the generation process. Instruction tuning and factuality-oriented training can reduce the problem, but they do not guarantee correctness.
As an FDE, I would treat hallucination as an end-to-end reliability problem. I would ground answers in authorized, current sources, use deterministic tools for exact facts and calculations, require evidence for important claims, validate outputs, and allow the system to abstain or escalate when evidence is insufficient. I would evaluate factual correctness and evidence support separately, with particular attention to high-risk customer workflows.
1. What counts as a hallucination?#
A hallucination is generated content that is presented as factual but is false, fabricated, or unsupported under the relevant grounding requirements. Terminology varies across research and applications, so define the failure precisely for the task.
| Failure type | Example |
|---|---|
| Factual error | Giving an incorrect date for a documented event |
| Fabricated entity or citation | Inventing a research paper, policy section or API method |
| Contradiction of supplied evidence | Saying the refund period is 60 days when the applicable policy says 30 |
| Unsupported elaboration | Adding an eligibility exception not present in the policy |
| False tool or action claim | Reporting that a refund was completed when no successful transaction was recorded |
A factually correct statement can still be unsupported by the provided documents. Conversely, a statement faithfully copied from an outdated document can be grounded in that document but factually incorrect today.
Creative fiction, explicitly labeled speculation, and justified uncertainty should not automatically be classified as hallucinations.
2. Why hallucinations occur#
Training objective and learned knowledge#
Autoregressive language models estimate the probability of the next token given previous tokens. A likely continuation is not necessarily a true statement. Pretraining learns useful factual associations, but it does not provide a built-in database of independently verified facts or a universal truth-checking mechanism.
Training data can contain outdated information, conflicting accounts, misinformation, or few examples of a specialized domain. Facts stored implicitly in parameters may also be difficult to retrieve reliably through prompting.
Post-training can improve instruction following, factuality and uncertainty behavior. Nevertheless, systems optimized for helpful, complete answers may sometimes produce unsupported responses instead of admitting insufficient evidence. This is a possible contributing factor, not a claim that every training method rewards hallucination.
Ambiguity and missing context#
A vague user question may refer to several entities, locations, policy versions or time periods. If the model assumes the wrong interpretation, it can generate an answer that sounds relevant but is incorrect for the user's actual situation.
For example, asking "What is our travel allowance?" without specifying employee category, destination or policy date may not provide enough information to identify the applicable rule.
Failure to use available evidence#
Even when correct information is included in the prompt, the model may overlook an exception, confuse similar entities, misread a table, or combine facts incorrectly. Long contexts, conflicting passages and irrelevant information can worsen this problem.
Autoregressive generation and reasoning errors#
Each generated token conditions later predictions. An early mistaken assumption can lead to a coherent but incorrect continuation. Errors may also arise in arithmetic, multi-step reasoning, entity resolution and temporal reasoning.
Sampling can change which continuation is produced, but sampling randomness is not the fundamental cause of hallucinations.
3. Two useful distinctions: factuality and faithfulness#
Factuality asks whether a claim is correct in the relevant real-world or authoritative domain.
Faithfulness or groundedness asks whether a claim is supported by the source evidence available to the system.
For a source-grounded assistant, classify individual claims as:
- Supported: The authorized, applicable evidence establishes the claim.
- Contradicted: The applicable evidence establishes an incompatible claim.
- Insufficient: The evidence does not establish either conclusion.
Insufficient evidence is not proof that a claim is false. If conflicting sources cannot be resolved, record the conflict separately or treat the claim as unresolved under the chosen evaluation rubric.
This distinction helps determine whether to repair retrieval, fix source data, improve generation, or change the system's uncertainty policy.
4. Why temperature zero does not guarantee accuracy#
Temperature changes the distribution used for token selection. For positive temperature, lower values make high-scoring tokens relatively more likely; many APIs implement temperature zero through greedy or near-greedy decoding.
Suppose a model assigns its highest score to an incorrect continuation. Greedy decoding will still select it. Making an answer more repeatable does not make the underlying information correct.
Even nominally deterministic generation can vary because of serving implementations, numerical precision, batching, model updates and other configuration details.
Use low temperature when consistency is useful, such as extraction or classification. Evaluate factual accuracy separately. Do not use temperature zero as a truthfulness control.
5. Why RAG does not eliminate hallucinations#
Retrieval-augmented generation supplies external evidence to the model, reducing reliance on implicit knowledge. It is particularly useful for changing or customer-specific information. But every stage can fail.
| Stage | Example failure | Mitigation |
|---|---|---|
| Ingestion | Current policy not indexed | Check synchronization, versions, parsing and deletion handling |
| Retrieval | Wrong policy or entity retrieved | Evaluate evidence recall, filters, hybrid search and reranking |
| Context assembly | Relevant exception omitted or truncated | Preserve complete evidence and inspect final context |
| Generation | Model misreads a correct passage | Test gold-context generation and constrain unsupported claims |
| Citation | Citation exists but does not support the claim | Verify source identity, applicability and claim-level entailment |
| Source quality | Retrieved policy is itself incorrect or outdated | Resolve authoritative versions with domain owners |
RAG increases access to evidence; it does not force the model to reason correctly or establish that the evidence itself is true.
6. A production mitigation strategy#
Ground the answer in trusted information#
Retrieve relevant, authorized and current records. Preserve source identifiers, effective dates, versions and scope. Enforce tenant and document permissions in trusted application services, not through instructions to the model.
Use structured queries or validated API calls for exact balances, order states, inventory and other transactional facts. Prefer deterministic calculations for arithmetic and rules with known inputs.
Constrain generation appropriately#
Specify which evidence the model may rely on and require it to identify uncertainty, conflicts and missing information. Structured outputs can enforce a response schema, but syntactic validity does not establish semantic correctness.
For source-grounded questions, request citations to supporting passages and verify the cited source is actually available and applicable. Treat retrieved text as untrusted input; it must not override application policy.
Validate important claims and actions#
Use task-specific validation. A numeric value can be checked against a trusted API response, a policy claim against an applicable source, and an action-completion claim against an authoritative transaction receipt.
An independent model or natural language inference classifier can help screen unsupported statements, but it can also make mistakes. Calibrate automated judgments against human-reviewed examples and use deterministic validation wherever possible.
For high-risk operations, apply risk-based human review or require explicit confirmation before executing an action. Never present a proposed tool call as a completed operation.
Allow uncertainty and escalation#
A reliable system must be able to say that it cannot establish an answer. Ask a clarifying question if the request is ambiguous, retrieve additional evidence when useful, or escalate to a domain owner when the stakes justify it.
Avoid relying solely on the model's self-reported confidence or token probabilities as factual confidence. Use measured calibration, available evidence and domain-specific validation.
7. How to evaluate hallucinations#
Build a representative, human-reviewed dataset of customer questions with applicable evidence and expected answers. Include unanswerable questions, ambiguous requests, stale documents, conflicting policies, multi-hop queries and adversarially misleading inputs.
| Metric | What it measures |
|---|---|
| Claim support rate | Fraction of evaluated claims supported by the applicable evidence |
| Contradiction rate | Fraction contradicted by that evidence |
| Insufficient-evidence rate | Fraction not established or contradicted by available evidence |
| Factual accuracy | Correctness against trusted ground truth, independently of source support |
| Citation precision and coverage | Whether citations support associated claims and important claims are cited |
| Answer completeness | Whether all required information is present |
| Appropriate abstention | Whether the system declines or escalates when it cannot establish an answer |
| Answer coverage | Proportion of requests answered rather than declined |
| Risk-weighted error rate | Severity-adjusted failures according to customer-defined consequences |
Define the evaluation unit and denominator. Claim-level micro-averages can favor long responses; report per-answer results as well when appropriate. An empty or abstained answer should not receive perfect claim support just because it contains no claims. Measure accuracy at a given coverage level to prevent gaming through excessive abstention.
Python example: aggregate human-labeled claim support#
This example aggregates labels supplied by reviewers or an independently evaluated verifier. It does not determine whether natural-language claims are true.
PYTHONdef support_metrics(labels: list[str]) -> dict[str, float | int | None]: allowed = {'supported', 'contradicted', 'insufficient'} if any(label not in allowed for label in labels): raise ValueError('Unknown claim label') n = len(labels) supported = labels.count('supported') contradicted = labels.count('contradicted') return {'claims': n, 'support_rate': supported / n if n else None, 'contradiction_rate': contradicted / n if n else None, 'insufficient_rate': (n - supported - contradicted) / n if n else None}
For labels ['supported', 'supported', 'contradicted', 'insufficient'], the support rate is 0.50, contradiction rate is 0.25 and insufficient-evidence rate is 0.25. Empty input returns None for the rates rather than silently reporting perfect performance.
Local verification: 9,844 test cases passed using Python: all 9,841 label sequences of lengths zero through eight, two invalid-label cases, and one explicit example. The checks verified claim counts, expected rates, empty-input handling, rate totals and invalid-label rejection. These tests validate aggregation, not the accuracy of a claim-labeling model.
The implementation takes O(n) time and O(1) auxiliary space for a list of n labels, excluding the input.
8. Debugging a hallucination in an enterprise workflow#
Imagine a customer assistant claims that a cancelled order has already been refunded, even though the payment system has not confirmed a refund.
I would first establish the correct business state with the payment system. Then trace the request through the retrieval or tool-call layer, tool response, final model context and generated answer.
If the refund-status tool was never called, improve tool-routing requirements. If the tool returned an error, handle that error explicitly. If the model received the correct pending status but reported success, validate the response against the trusted status and prevent unsupported completion claims.
For this workflow, I would design the application to derive transaction status directly from the authoritative tool result. The model may explain that status, but it should not be the source of truth for whether the transaction succeeded.
Before rollout, I would test pending, completed, failed, timed-out and unknown states, including repeated requests and stale responses. Track false success claims separately because their operational consequences can be much more severe than minor wording errors.
This is a hypothetical scenario, not a claimed customer incident.
9. Practical FDE engineering trade-offs#
- Retrieval versus larger prompts: More evidence may improve coverage but can introduce distractors and latency. Measure the evidence actually used in the answer.
- Verification versus latency: Additional validation costs time and compute. Apply rigorous checks to consequential claims and use cheaper deterministic checks where available.
- Abstention versus coverage: A lower error rate achieved by rejecting most requests may not deliver useful customer outcomes. Evaluate the accuracy-coverage trade-off.
- Fine-tuning versus external knowledge: Fine-tuning can improve behavior or specialized capabilities, but is not a reliable mechanism for continuously updating exact facts. Use authoritative sources for mutable information.
- Model choice versus system design: A stronger model may improve reasoning, but cannot repair inaccessible data, wrong permissions or an unreliable source of truth.
- Monitoring versus privacy: Record evidence identifiers, model versions, validation outcomes and risk categories while avoiding unnecessary retention of sensitive customer content.
Agree on risk-specific acceptance thresholds with the customer, compare alternatives on a held-out evaluation set, and monitor production regressions. Do not promise zero hallucinations for an unconstrained generative system.
Likely interviewer follow-ups#
Can you completely eliminate hallucinations? Not generally for open-ended LLM generation. For a narrowly specified task, deterministic components and strong validation can prevent particular classes of unsupported output.
Is every incorrect answer a hallucination? Not under every definition. Distinguish false factual assertions, reasoning errors, unsupported claims and legitimate uncertainty according to the evaluation rubric.
Is RAG better than fine-tuning for hallucinations? It depends on the failure. RAG is useful for supplying missing or changing knowledge. Fine-tuning can improve task behavior. Neither alone guarantees truthfulness.
How do you isolate a retrieval failure from a generation failure? Supply the known correct evidence directly to the same generator. If the answer improves, inspect upstream evidence selection; otherwise investigate generation, source interpretation and the evaluation labels.
What would you tell a customer who asks for 100% accurate answers? Define the tasks and risks, identify claims that can be deterministically verified, agree on escalation behavior and measurable reliability targets, and avoid unsupported guarantees.
References
- 1.
- 2.
- 3.
- 4.
- 5.
Related questions
Explore other topics:AI AgentsAI System DesignLarge Language Models