HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 24 of 25 — Generative AI Fundamentals
intermediate Chapter 24 of 25

LLM Hallucination, Evaluation and Safety: Where GenAI Fails

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

What Is LLM Hallucination?

An LLM hallucination is a generated claim that is false or presented as established without adequate evidence, often in language that sounds plausible. To evaluate one, check the claim against the task’s accepted evidence and distinguish a contradiction from a claim the evidence cannot settle. Retrieval, verification and selective abstention can reduce these errors, but each addresses a different failure mode.

A large language model can invent a circular number for a university policy, cite a real circular that says something different, report an exact statistic with no source, or produce a convincing explanation that gets the cause backwards. The same pattern appears in systems that use tools: an assistant might say a ticket was created when it only prepared a request. In each case, identify the statement that can be checked before deciding how to score it.

Failure typeExampleWhat to check
Contradicted claimThe assistant says there is a filing fee. The applicable policy says there is none.The controlling source, effective date and scope
Unsupported claimAn answer gives an exact survey percentage, but no trusted source establishes it.Whether evidence entails the figure; missing proof alone does not make it false
Misleading citationA real policy is cited for a rule that appears only in a superseded version.Whether the cited passage supports the specific claim and still applies
Fabricated action reportThe assistant reports that a ticket was created after an API timeout.The committed record or a trusted operation status

Factual correctness and grounding can diverge. An answer may guess the right fact without evidence. It may also faithfully summarise an obsolete document and give the wrong advice for the current date. Evaluate both dimensions when the application needs current, authoritative answers. For creative writing, invented details are expected; the same details become a problem if the task asks for a factual report.

Why Do LLMs Hallucinate Even When They Sound Confident?

In an autoregressive language model, the probability of an output sequence is P(y | x) = product over t of P(y_t | x, y_1, ..., y_(t-1)). Here x is the input, and y_t is the token generated at step t. Pretraining rewards predicting tokens from context; instruction tuning can improve the behaviour of the resulting model, but the generation equation contains no independent test that a sentence is true.

Suppose the prompt asks, “What is the deadline for a backlog exam application?” without naming the university, exam session or academic year. A specific date may fit the patterns the model learned, even though the prompt does not identify a unique deadline. Also, an earlier generated token becomes part of the input for the next prediction. Once a model invents a date or document name, it can build a coherent paragraph around that initial mistake.

Training data can be incomplete, inconsistent or stale. At inference time, important instructions or evidence can also fall outside the context window, or the model may give too much weight to a distracting passage. Lowering temperature can reduce variation between outputs, but even greedy decoding can repeatedly select the same wrong continuation. A token probability measures how likely a continuation is under the model, not whether a source supports a claim.

Use the cheapest control that addresses the cause. Ask a clarifying question if an entity or time range is missing. Require applicable sources for facts that change. Use deterministic code to calculate totals or compare dates, then validate the result before presenting it. For a source-based answer, instruct the model to state what is missing rather than fill a gap. Test that instruction on inputs where the answer is genuinely absent.

Why Does RAG Still Produce Hallucinations?

Retrieval-augmented generation (RAG) puts selected evidence in the model’s input. An answer can fail because the pipeline selected the wrong evidence, because the right evidence never entered the index, or because the model misread what it received. Inspect the actual passages sent to the model before deciding whether to change the retriever or the generator.

A RAG pipeline shows how a missing policy condition leads to an unsupported answer claim.
Trace missing evidence through chunking, retrieval and generation before choosing a fix.
  • Coverage and freshness: An index built from last month’s files cannot answer reliably about a policy issued this morning. Current or private information must come from an authorised source, such as an updated index or a live connector. The connector needs appropriate access checks and a way to signal stale or partial results.
  • Chunk boundaries: A chunk might contain a reimbursement amount but omit the sentence defining who qualifies. Keep headings, table labels and relevant conditions together where practical. Fetch adjacent text or a parent section when a match is too narrow to interpret.
  • Relevance and authority: A semantic search can rank an obsolete policy or an informal discussion above the current rule. In the RAG retrieval pipeline, use applicable metadata filters, lexical matching for exact identifiers, and re-ranking when relevant passages exist but appear too low in the results.
  • Ambiguity and reasoning: Two passages may apply to different campuses or employee categories. Even with all the right passages, the model can combine incompatible rules or miscalculate a deadline that depends on holidays. Show the conflict when scope is unresolved; delegate calculations to code with an explicit calendar.

To isolate an error, run the question twice with the same generation configuration: once with normal retrieval and once with human-selected reference passages. If the answer improves with reference passages, audit coverage, chunking or ranking. If it still fails, inspect the generator’s interpretation, citation mapping and any required computation. Increasing k may recover missing evidence, but it might also introduce outdated rules and competing instructions. Measure answer quality along with retrieval recall.

Where Do AI Agents and Multimodal Models Fail?

AI agents make repeated decisions about what to do, which tool to call and whether the result completes a task. A model can choose a tool whose name sounds right, pass an identifier for the wrong record, or continue from an incomplete response. Validate arguments against a schema, then check business constraints in application code. A valid date string or account identifier does not prove the requested operation is appropriate for that record.

Track a tool action using application state: proposed, dispatched, and then confirmed, failed or unknown. An API timeout can mean the response was lost after the operation committed, or that the operation never ran. For supported operations, use an idempotency key and check status before retrying. Build success messages from verified results, such as a committed ticket identifier. If there is no confirmation, say the action is unconfirmed rather than converting uncertainty into success or failure.

Long tasks accumulate errors because later steps depend on earlier outputs. In a simplified workflow with 10 required steps that each succeed independently with probability 0.98, the chance all steps succeed is 0.98^10 = 0.817, about 82 percent. This is a model of error accumulation, not a benchmark; real failures can be correlated, recovered or amplified. Apply step limits, checkpoints and stop conditions. Monitor external API availability and tail latency, because retries and extra model calls can increase both operating cost and response time compared with a single-call system.

Multimodal models can misread a faint decimal point in a scanned invoice, confuse speakers in overlapping audio, or miss a short event between sampled video frames. Preserve evidence that reviewers can inspect: a page region, an audio timestamp or a frame range. For fields such as invoice totals, compare extracted values with independent arithmetic and request review when image quality or conflicting evidence makes the field uncertain.

Worked Example: How Do You Score a Hallucinated Answer?

Consider a synthetic expense policy assistant. The employee asks how to file a domestic travel claim, who approves it, when it is paid, whether there is a fee and when receipts are required. The evaluator marks passages A and B as necessary for a complete answer. The system retrieves A and C.

An expense policy example shows one of two required passages retrieved and three of five claims supported.
Retrieval recall, claim support and citation precision expose different errors in the same answer.
  • A, current domestic policy: Submit in the expense portal. Manager approval is required. Payment is due within five business days of approval. No submission fee applies.
  • B, current receipts appendix: Receipts are required for expenses above INR 2,000.
  • C, unrelated material: The office supplies guide lists approved stationery vendors and contains no travel receipt rule.

The assistant replies: “Submit in the expense portal [A]. Manager approval is required [A]. There is an INR 100 submission fee [A]. Payment is due within five business days of approval. Receipts are required for expenses above INR 2,000 [C].” Split the response into five claims and score each against what the system actually received.

ClaimStatus against retrieved evidenceCitation result
Submit in the expense portalSupportedA supports it
Manager approval is requiredSupportedA supports it
Submission costs INR 100ContradictedA says there is no fee
Payment is due within five business days of approvalSupportedNo citation attached
Receipts are required above INR 2,000Insufficient evidenceC does not establish it

Retrieval recall at two is 1 / 2 = 0.50 because only A of the two required passages was retrieved. Claim support rate is 3 / 5 = 0.60. Citation precision is 2 / 4 = 0.50 when each claim-to-citation link is one scored unit. The uncited payment claim does not reduce citation precision, so also track citation coverage: two of the five claims have a valid citation.

The receipt claim is correct against the full reference set but unsupported at generation time. The fee claim is wrong even with the correct evidence present. These errors call for separate fixes: retrieve the receipts appendix or acknowledge the missing rule, and verify the fee claim against A before publishing. A complete, accurate response needs both fixes.

How Do You Evaluate LLM Hallucination and Task Quality?

Build a versioned test set from representative user requests. Record the expected disposition as well as the answer: respond with evidence, ask for missing details, abstain, or report that a tool operation is unconfirmed. Include answerable and unanswerable cases, stale documents, conflicting sources, API failures and difficult scans. Pin the policy version or evaluation time so a later document update does not silently change the definition of a correct answer.

Score at multiple levels. Claim support detects additions or distortions. Required-fact coverage detects omissions, such as an answer that says only where to apply when the user also asked for the deadline. At the request level, report answer coverage, the fraction of requests answered substantively, and supported accuracy among those answers. A system can improve its support rate by declining difficult questions, so inspect unjustified abstentions on answerable inputs as well as wrong answers on unanswerable inputs.

The Python below calculates the worked example’s metrics from reviewed annotations. Keep annotation separate from aggregation so you can replace manual review with a calibrated judge without changing the metric definitions. An undefined ratio returns None; a response with no citations should not be credited with perfect citation precision.

from dataclasses import dataclass
from typing import Literal

Status = Literal["supported", "contradicted", "insufficient"]

@dataclass(frozen=True)
class Claim:
    status: Status
    # One boolean per claim-to-citation link, reviewed against the passage.
    citation_validity: tuple[bool, ...] = ()

def ratio(n: int, d: int) -> float | None:
    return n / d if d else None

def score(gold, ranked_passages, k, claims):
    retrieved = set(ranked_passages[:k])
    links = [ok for claim in claims for ok in claim.citation_validity]
    return {
        "retrieval_recall_at_k": ratio(len(gold & retrieved), len(gold)),
        "claim_support_rate": ratio(
            sum(c.status == "supported" for c in claims), len(claims)
        ),
        "citation_precision": ratio(sum(links), len(links)),
        "valid_citation_coverage": ratio(
            sum(any(c.citation_validity) for c in claims), len(claims)
        ),
    }

claims = [
    Claim("supported", (True,)),
    Claim("supported", (True,)),
    Claim("contradicted", (False,)),
    Claim("supported"),
    Claim("insufficient", (False,)),
]
print(score({"A", "B"}, ["A", "C"], 2, claims))
# Recall: 0.5, support: 0.6, precision: 0.5, citation coverage: 0.4

For evaluation at scale, an LLM judge can label one atomic claim at a time against supplied passages. Require a structured verdict and a short evidence span. Check that the quoted span exists, then sample the verdicts for human review: an exact quote can still fail to entail the claim. Calibrate against human labels, inspect errors by category, and use manual review for high-impact disagreements. If you average support across questions, each question gets equal weight; pooling all claims gives longer answers more influence. State which you report.

How Do You Make GenAI Systems Safer in Production?

Factuality is one safety dimension. A factually correct answer can still reveal private data, and a correct summary of a tool request does not establish that the user is allowed to carry it out. Decide what the system may read, say and change. Enforce those boundaries in trusted application components rather than relying on the prompt or a model-generated decision.

  • Separate evidence from instructions: Treat retrieved text and tool responses as untrusted data. Text inside a document cannot grant permissions or authorise a new operation. Resolve user identity and data access outside the model, before private evidence is retrieved or shown.
  • Limit side effects: Use narrowly scoped credentials and validate each proposed operation against the current user, target resource and policy. Require explicit approval for sensitive changes, and bind approval to the exact parameters submitted for execution.
  • Handle uncertainty by impact: A low-stakes suggestion can be shown with a caveat. A payment, eligibility decision or formal policy interpretation may need source validation and human review before it is issued or executed.
  • Monitor production failures: Track document versions, tool status and applicable decision codes with minimal sensitive data. Alert on stale sources, rising error rates or writes with unknown status. Keep a regression set and rerun it when the model, index, prompt or tool schema changes.

Write release tests as observable assertions. For an unavailable service, check that the system never reports an unverified success. For an unauthorised operation, check that the backend rejects it and that no state changes. For ambiguous policy evidence, check that the system asks for the missing scope or routes the case for review. A clear response and a correct backend outcome are separate acceptance criteria.

Key Takeaways

  • Separate contradicted claims from claims for which the available evidence is insufficient.
  • Token probabilities and confident wording do not establish factual correctness.
  • Diagnose RAG failures by comparing normal retrieval with human-selected evidence.
  • Verify agent actions from trusted application state, especially after timeouts.
  • Measure retrieval recall, claim support, citation quality and task coverage separately.
  • Enforce permissions outside the model and test safety controls against observable outcomes.

Frequently Asked Questions

Can RAG eliminate LLM hallucination?

No. RAG supplies evidence, but an index can be stale, retrieval can omit a relevant condition, and the model can misinterpret a passage it receives. Test retrieval and answer generation separately. When the system lacks the applicable source, it should state the gap, ask for clarification or route the request for review.

Does setting temperature to zero stop hallucinations?

No. In systems that use greedy decoding at zero temperature, the decoder chooses the highest scoring next token. That token can be part of a false claim, so the setting can make an error more repeatable. Use evidence checks and task-specific validation to verify factual statements rather than treating decoding settings as a factuality control.

How can I detect a hallucinated citation?

Check that the cited source exists, that its version applies to the request, and that the relevant passage supports the exact statement. A real policy document can be cited for a rule it never states. For claims with several conditions or numbers, verify each part instead of accepting a citation based on matching keywords.

Can one LLM evaluate another LLM’s output?

Yes. A judge model can compare short claims against reference passages and produce reviewable labels at scale. It can also overlook qualifications, favour fluent answers or share errors with the generator. Compare its labels with human review on diverse examples and keep manual checks for disputed or high-impact cases.

What should an agent say if a tool call times out?

It should report that the outcome is unconfirmed unless it can verify the final state through a trusted status check. A timeout does not prove failure, because the service may have completed the operation before its response was lost. For writes, check status before retrying and use an idempotency mechanism when the service supports one.

Ready to Master Generative AI Fundamentals?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and Placement Guarantee* — structured interview support until placed.

Explore Course