Chapter 8 of 8 · Free, no signup

Support Us

Generative AI & LLM Engineering · Chapter 8 · ~20 min · Interactive Visuals

Reducing Hallucinations & Evaluating Answers

Understand why LLMs invent believable confabulations, anchor them with Faithfulness and Chain-of-Verification guardrails, and build automated CI/CD evaluation pipelines using LLM-as-a-Judge.

  • Distinguish factuality failures from faithfulness failures
  • Ground answers with context, citations, and verification
  • Evaluate relevance, faithfulness, and context precision
  • Build golden datasets for repeatable CI checks

1The Anatomy of a Hallucination: Factuality vs. Faithfulness

An LLM is fundamentally a probabilistic token generator. It does not possess a relational database of truth, an active memory of current events, or an internal fact-checking governor. When it predicts the next token, it selects words that are statistically convincing, not necessarily factually true.

In production AI engineering, hallucinations are categorized into two primary forms:

  • Extrinsic Hallucination (Factuality Failure): The model asserts a claim about the real world that cannot be substantiated by verified training data or external reality (e.g., inventing fake case citations, non-existent Python packages, or fictional historical treaties).
  • Intrinsic Hallucination (Faithfulness Failure): The model contradicts or distorts the information directly supplied in its context window (e.g., given a lab result stating "negative for disease", the model summarizes that the patient tested positive).

Interactive Hallucination Inspector

Compare uncalibrated baseline outputs against grounded responses across four failure modes.

User Prompt:

How do I sign RS256 JWTs with high-speed async C-bindings in Python?

Raw LLM Output (Uncalibrated)Hallucinated

You should install the fast-pyjwt-c accelerated engine using pip install fast-pyjwt-c. Then import fast_jwt and call fast_jwt.sign_rs256(payload, private_key).

Grounded & Evaluated OutputFaithful to this context

Standard PyJWT or the cryptography library are the verified standards for RS256 signing. Install them via pip install pyjwt[crypto] and use jwt.encode(payload, private_key, algorithm='RS256'). No official package named 'fast-pyjwt-c' exists.

Root Cause Under the Hood

Subword token probability favors plausible-sounding package names when no strict tool-lookup or verified catalog is provided.

Production Countermeasure

Require models to call registry search tools (e.g., PyPI API) or enforce standard library fallbacks instead of generating package names from pure recall.

The Slopsquatting Attack: Research has shown that when LLMs are asked to recommend software libraries, they frequently invent plausible package names like flask-auth-secure. Malicious actors scan LLM outputs, register those hallucinated package names on PyPI/npm, and inject malware into automated build pipelines!

What is the difference between an Intrinsic and an Extrinsic hallucination?

2Root Causes & Confabulation Dynamics

Why do models hallucinate? These architectural and training factors can contribute to confabulations:

  1. Greedy Next-Token Pressure: Without an explicit permission to refuse or say "I don't know", the model may be more likely to produce a plausible-sounding guess instead of abstaining.
  2. Sycophancy & Human Feedback Bias: RLHF (Reinforcement Learning from Human Feedback) often rewards agreeable, helpful-sounding assistants. If a user asks a leading or mistaken question, models frequently corroborate the falsehood to appear polite.
  3. Attention Dilution & Needle-in-a-Haystack Limits: When context windows exceed tens of thousands of tokens, attention heads can lose track of subtle negative qualifiers (such as "not", "except", or "never").

The Hallucination Risk Simulator

See how sampling temperature, context availability, domain rarity, and prompt constraints alter confabulation odds.

Sampling Temperature:0.70
0.0 (Deterministic)0.7 (Standard)1.2 (Creative / Wild)
Estimated Confabulation Risk
63%
High Risk (Critical)
Recommended Countermeasure:

⚠️ Higher-risk configuration. The model may invent details rather than admit uncertainty. Use lower sampling randomness where supported, provide reliable context, and offer a clear refusal path.

Why can instructing an LLM to reply 'Insufficient Information' when context is missing reduce unsupported answers?

3Mitigation: Grounding, Citations & Chain-of-Verification

Relying on prompt wording alone ("please be 100% accurate") is insufficient for enterprise workflows. Production systems deploy structured architectural defenses:

1. Citation Anchoring

Require the model to return verbatim quote spans before generating synthesis: [Quote: "..."].

2. Negative Constraints

Enforce strict boundaries: "Use ONLY information from <context>. Do not infer facts not stated."

3. Verification Loops (CoVe)

Plan targeted questions to fact-check the draft independently, then revise before delivering to the user.

Chain-of-Verification (CoVe) in Action

Watch an AI detect its own factual mistake by planning and executing independent verification queries.

1. Baseline Draft GenerationDrafting

The LLM responds to the user's initial prompt, generating a plausible-sounding but unverified draft.

Query: 'Tell me about Marie Curie and her Nobel Prizes.' Draft Answer: Marie Curie was a Polish physicist who won two Nobel Prizes: the 1903 Nobel Prize in Physics for her work on radioactivity, and the 1911 Nobel Prize in Medicine for developing mobile X-ray radiography units during World War I.
Note the subtle error: 1911 Nobel Prize in Medicine (she actually won in Chemistry!).
Why Independent Execution Matters in CoVe: If the model fact-checks its draft within the same generation pass, its review can be biased by the draft. Generating independent verification questions and answering them in isolated sessions can reduce that influence, but the checks still need reliable sources.

4The LLM Evaluation Hierarchy

How do you know if a prompt change, new embedding model, or fine-tuned checkpoint actually improved your system? Traditional software uses deterministic unit tests. But LLMs produce unstructured natural language where traditional metrics fall short:

Evaluation MethodSpeed & CostSemantic NuancePrimary Use Case
Deterministic / Regex / SchemaInstant & FreeNone (Syntax only)JSON validity, status codes, prohibited keywords
BLEU / ROUGE n-gram OverlapFast & Low CostPoor (Word matches)Outdated; misses inverted semantics ("not bad" vs "bad")
Semantic Embedding DistanceFast & CheapModerateCosine similarity against reference gold answers
LLM-as-a-Judge (G-Eval / Ragas)Moderate ($0.01/eval)ExceptionalFaithfulness, Tone, Complex reasoning, Hallucination checks
Human Evaluation (SME Review)Slow & ExpensiveGold StandardCalibrating automated judges and high-stakes audits

Why have modern AI teams largely abandoned BLEU and ROUGE for evaluating conversational LLM answers?

5The RAG Triad & LLM-as-a-Judge in Practice

For Retrieval-Augmented Generation, the industry standard evaluation taxonomy is the RAG Triad (popularized by TruLens and Ragas):

1. Faithfulness

Are all claims in the answer grounded in the retrieved context? Prevents hallucinations.

2. Answer Relevance

Does the answer directly address the user's prompt without evasive padding?

3. Context Precision

Did the retriever pull relevant signal rather than noisy distractors?

The Ragas Triad & LLM-as-a-Judge Arena

Test how automated evaluation frameworks break answers into atomic claims to compute mathematical Faithfulness and Relevance.

Faithfulness Score100%

Measures if every statement is substantiated by context. Formula: |Grounded Claims| / |Total Claims|

Answer Relevance98%

Measures semantic alignment with the user's prompt, ignoring irrelevant padding.

Atomic Claim Decomposition by LLM-Judge:2/2 Supported
Defective hardware is eligible for immediate exchange/refund within 30 days.
Verified in provided context
After 30 days, customers can file a warranty repair claim for up to 12 months.
Verified in provided context
Judge Verdict: PASS (High Confidence) — All atomic claims are grounded in Section 4.1 with zero extraneous fluff.
LLM-as-a-Judge Biases to Guard Against: When using models like GPT-4o as an automated judge, watch out for Position Bias (favoring the first answer in pairwise comparisons), Length Bias (favoring longer, wordier answers), and Self-Enhancement Bias (favoring answers generated by its own model family).

6CI/CD Golden Datasets: Testing AI Before Shipping

Never deploy a prompt change or swap a model checkpoint without running an automated regression benchmark. A Golden Dataset is a curated collection of 50 to 500 test cases containing:

  • Representative Queries: Standard user inputs covering your core product features.
  • Adversarial & Edge Cases: Out-of-domain questions, sycophancy traps, and negative refusal tests.
  • Ground-Truth Reference Contexts: Exact document chunks or database states against which faithfulness is evaluated.

Automated CI/CD Golden Eval Runner

Run real-time regression suites against prompt iterations before deploying AI to production.

Golden Pass Rate
75%
Avg Latency
318 ms
Est. Cost / 1k
$0.65
Test CaseResultLatency
Known Entity QueryAccurate + Cited310ms
Out-of-Context Negative RefusalGraceful Refusal290ms
Sycophancy TrapPolite Correction330ms
Adversarial SlopsquattingUnverified Guess340ms

7Chapter Challenge

Production Hallucination & Evaluation Architect

Answer all four engineering questions correctly to prove your mastery of hallucination defense and evaluation.

0 / 4 correct
  1. 1You run an LLM-as-a-Judge evaluator on a customer support bot. The bot scores highly on Faithfulness but low on Answer Relevance. What does this mean?

  2. 2A financial app asks an LLM: 'What were Apple's Q4 2030 revenues?'. Why is giving the model an explicit refusal protocol ('If data is unavailable, state insufficient information') critical?

  3. 3What is 'Slopsquatting' in AI software engineering?

  4. 4In Meta's Chain-of-Verification (CoVe) framework, why must verification questions be answered independently of the initial draft?

8Recap

  • Hallucinations are Inherent to Next-Token Prediction: Models optimize for statistical plausibility, not verified objective truth.
  • Distinguish Intrinsic from Extrinsic: Intrinsic contradicts your supplied context; Extrinsic fabricates external world facts.
  • Calibrate Uncertainty: Provide explicit refusal options ("State insufficient data") to give the model a high-probability truth escape hatch.
  • Use Verification Loops: Techniques like Chain-of-Verification (CoVe) detect and correct errors before outputs reach end users.
  • Deploy Automated Judges (Ragas Triad): Measure Faithfulness, Answer Relevance, and Context Precision in CI/CD with Golden Datasets.

Solve the challenge above to complete the chapter, or

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us