Introduction
In our previous lesson, we established a crucial first line of defense for our agent by tackling prompt injection, securing the input to prevent malicious instruction hijacking. Now, we turn our attention to an equally critical aspect of agent reliability: the trustworthiness of the output. This lesson focuses on hallucinations, the phenomenon where LLMs generate plausible but factually incorrect or unsupported information.
For the customer-facing service agents you aim to build, a single hallucinated fact—a wrong policy detail, a non-existent feature, an incorrect price—can erode user trust and cause significant real-world problems. Our objective is to implement a robust system for validation-based hallucination detection. We will design a process to systematically check an LLM's generated response against a known source of truth, such as retrieved documents in a RAG pipeline or a set of business rules. This moves beyond simple hope and into systematic verification, a cornerstone of production-grade engineering.
1. Understanding Hallucinations in Agentic Systems
At a fundamental level, LLMs are not databases of facts; they are sophisticated statistical models that generate sequences of tokens based on probability. A "hallucination" occurs when the most probable sequence of tokens does not align with reality.
A well-known example illustrates the danger: Air Canada's chatbot confidently invented a bereavement travel policy, promising a customer a refund that the airline's actual policy did not permit. The airline was later forced to honor the hallucinated policy. For autonomous agents, the risk is even greater, as these outputs can trigger further actions.
To effectively combat this, we need to be precise about what we're detecting. The following video provides a clear introduction to hallucinations and frames the problem in the context of RAG systems, which are central to our agent's ability to use knowledge.
LLM Chronicles #6.6: Hallucination Detection and Evaluation for RAG systems (RAGAS, Lynx)
This video from the "LLM Chronicles" series provides an excellent conceptual grounding for hallucination detection.
Watch the initial segments to understand the core problem: by hallucinations: This part explains what hallucinations are from a first-principles perspective, moving beyond anthropomorphism. ground the llm answer: This is a key segment that introduces the idea of using retrieved context as a "ground truth" to evaluate and mitigate hallucinations. This concept of faithfulness or groundedness will be the foundation of our detection system.
In RAG and other agentic workflows, we can narrow the broad problem of "hallucination" to a more constrained and solvable one: ensuring the LLM's answer is faithful to the provided context. We treat the retrieved documents or tool outputs as the ground truth for a given task and verify that the agent's response does not contradict or invent information beyond what that context supports.
2. The "LLM-as-a-Judge" Architectural Pattern
How can we programmatically check if a natural language response is faithful to a source text? The dominant architectural pattern for this is known as LLM-as-a-Judge. The core idea is to use a second, independent LLM call—the "judge"—to evaluate the output of the first LLM—the "generator."
This pattern is powerful because it leverages the LLM's own language understanding capabilities to perform the validation. Instead of complex, brittle parsing logic, we can simply ask the judge: "Does the answer contradict the context?"
The following resources provide a comprehensive overview of this pattern.
Stanford CME295 Transformers & LLMs | Autumn 2025 | Lecture 8 - LLM Evaluation
This lecture from Stanford's "Transformers & LLMs" course introduces the LLM-as-a-Judge concept from an academic and practical perspective.
Watch the segment from before giving the score. Focus on the core setup: the judge LLM takes the original prompt, the response, and evaluation criteria as input, and outputs both a score and a rationale. The idea of forcing the model to produce a rationale before a score is a key technique to improve the quality of the judgment.
The LLM-as-a-Judge pattern turns a difficult validation problem into a structured prompting task. We can design a prompt that guides the judge LLM through a rigorous evaluation process.
3. Implementing a Validation-Based Hallucination Detector
Let's build a hallucination detector from scratch using this pattern. A naive approach might be to just ask a judge LLM, "Is this response faithful to the context?" However, a more robust method involves a multi-step process, which is beautifully illustrated in the diagram below.

This process can be broken down into two main steps:
- Decomposition: Break the agent's generated answer down into a list of individual, verifiable factual claims.
- Verification: For each claim, instruct the judge LLM to verify it against the provided context.
The following lecture segment explains this decomposition-then-verification process in detail.
Stanford CME295 Transformers & LLMs | Autumn 2025 | Lecture 8 - LLM Evaluation
Returning to the Stanford lecture, this section details a practical, multi-step method for quantifying factuality.
Please watch the segment from we have nowadays. Pay close attention to the sequence: An LLM call transforms the original text into a list of atomic facts. Each fact is checked individually against a knowledge source (in our case, the RAG context). The results are aggregated into a final factuality score.
3.1 Designing the Validation Rubric
To make the verification step rigorous, we'll design a "rubric" that the judge LLM must complete for each claim. This turns the process into a guided summarization and comparison task, which LLMs excel at. By using structured output (which you implemented in Module 1), we can ensure the judge's response is machine-parsable.
The following article from Datadog provides an excellent, production-focused design for such a rubric.
Detecting hallucinations with LLM-as-a-judge: Prompt ... - Datadog
This article details a battle-tested approach to building a hallucination detection rubric.
Please read the section titled Creating a rubric. Focus on these key design choices: The task is framed as finding disagreements between the answer and the context. The rubric requires direct quotes from both the answer and the context to ground the judgment. It distinguishes between Contradictions (claims that directly oppose the context) and Unsupported Claims (claims that add new information not found in the context). This distinction is vital for configurability, as some use cases might allow for external knowledge while others demand strict adherence to the provided context.
3.2 Putting It All Together in Code
Now, let's synthesize these concepts into a Python implementation. We'll create a HallucinationDetector class that encapsulates the decomposition and verification logic. This implementation is inspired by the GroundingVerifier from the OneUptime article but incorporates the more advanced, multi-step rubric-based approach we've just discussed.
import openai
import json
from typing import List, Dict, Any, Tuple
# Assume you have your OpenAI client configured
# client = openai.OpenAI(api_key="YOUR_API_KEY")
class HallucinationDetector:
def __init__(self, model: str = "gpt-4-turbo"):
"""
Initializes the detector with a specific model for judging.
For production, this should be a powerful and reliable model.
"""
self.model = model
self.client = openai.OpenAI()
def _decompose_into_claims(self, response: str) -> List[str]:
"""
Step 1: Decompose the LLM's response into a list of atomic, verifiable claims.
"""
prompt = f"""
Decompose the following text into a numbered list of simple, factual claims.
Each claim should be a self-contained statement that can be independently verified.
Text:
"{response}"
Return a JSON object with a single key "claims" containing a list of strings.
Example:
Text: "The sky is blue and the grass is green."
{{
"claims": ["The sky is blue.", "The grass is green."]
}}
"""
try:
completion = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": "You are a helpful assistant that extracts factual claims from text."},
{"role": "user", "content": prompt}
],
response_format={"type": "json_object"},
temperature=0.0
)
data = json.loads(completion.choices[0].message.content)
return data.get("claims", [])
except (json.JSONDecodeError, KeyError) as e:
print(f"Error decomposing response: {e}")
return []
def _verify_claim(self, claim: str, context: str) -> Dict[str, Any]:
"""
Step 2: Verify a single claim against the context using a structured rubric.
"""
prompt = f"""
You are an expert fact-checker. Your task is to verify a given claim against a provided context.
You must complete the following JSON rubric. Do not add any extra commentary.
1. **Analyze the Claim**: Is the claim supported by the context?
2. **Find Evidence**: Quote the exact part of the context that supports or refutes the claim.
3. **Classify Disagreement**: If there is a disagreement, classify it.
**Context**:
---
{context}
---
**Claim to Verify**: "{claim}"
**JSON Rubric to Complete**:
{{
"claim": "{claim}",
"is_supported": <true or false>,
"evidence_quote": "<Direct quote from context or 'No supporting evidence found.'>",
"disagreement_type": "<'Contradiction', 'Unsupported', or 'None'>"
}}
**Instructions for Classification**:
- 'Contradiction': The claim directly contradicts information in the context.
- 'Unsupported': The claim contains information not present in the context.
- 'None': The claim is fully supported by the context.
"""
try:
completion = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": "You are a meticulous fact-checker that fills out JSON rubrics."},
{"role": "user", "content": prompt}
],
response_format={"type": "json_object"},
temperature=0.0
)
return json.loads(completion.choices[0].message.content)
except (json.JSONDecodeError, KeyError) as e:
print(f"Error verifying claim '{claim}': {e}")
return {
"claim": claim,
"is_supported": False,
"evidence_quote": "Verification failed due to system error.",
"disagreement_type": "Unsupported"
}
def validate_response(self, response: str, context: str) -> Tuple[bool, List[Dict[str, Any]]]:
"""
Validates an entire response by decomposing and verifying each claim.
Returns an overall faithfulness status and a list of detailed verification results.
"""
print("--- Starting Hallucination Detection ---")
claims = self._decompose_into_claims(response)
if not claims:
print("Could not decompose response into claims. Assuming it is unfaithful.")
return False, []
print(f"Decomposed into {len(claims)} claims: {claims}")
results = [self._verify_claim(claim, context) for claim in claims]
is_faithful = all(res.get("is_supported", False) for res in results)
print(f"Overall Faithfulness: {'Faithful' if is_faithful else 'Unfaithful'}")
print("--- Detailed Verification Results ---")
for res in results:
status = "SUPPORTED" if res.get('is_supported') else "HALLUCINATED"
print(f" [{status}] Claim: {res.get('claim')}")
if not res.get('is_supported'):
print(f" - Type: {res.get('disagreement_type')}")
print(f" - Evidence Context: {res.get('evidence_quote')}")
print("--- End of Detection ---")
return is_faithful, results
# --- Example Usage ---
detector = HallucinationDetector()
# Example from the OneUptime article
context = """
OneUptime is an open-source observability platform founded in 2019.
It provides monitoring, incident management, and status pages.
The platform supports OpenTelemetry for distributed tracing.
OneUptime is licensed under the MIT license.
"""
# A response with a hallucinated detail ("built on Apache Kafka")
hallucinated_response = """
OneUptime is an observability platform that was founded in 2019.
It uses OpenTelemetry for tracing and is built on Apache Kafka.
The platform is open-source under the MIT license.
"""
faithful_response = """
OneUptime, founded in 2019, is an open-source observability platform
licensed under MIT. It supports OpenTelemetry.
"""
print("\n--- Testing Hallucinated Response ---")
detector.validate_response(hallucinated_response, context)
print("\n--- Testing Faithful Response ---")
detector.validate_response(faithful_response, context)
This implementation provides a clear, step-by-step validation pipeline. It's a reusable component you can integrate after any agent step that generates natural language based on a context, such as after a RAG call or summarizing a tool's output. The pipeline concept is very similar to the "Flow Validation Pipeline" you might design in other software systems.

4. Production Considerations: Biases and Best Practices
Deploying an LLM-as-a-Judge system requires awareness of its potential failure modes. As a systems engineer, you know that every component has limitations. The judge LLM is not infallible and can be subject to several biases.
Stanford CME295 Transformers & LLMs | Autumn 2025 | Lecture 8 - LLM Evaluation
The Stanford lecture continues by discussing critical biases and best practices for using LLM judges in production.
First, watch the segment on for evaluation to understand the common biases: Position Bias: The order of information can affect the outcome. Verbosity Bias: The judge may prefer longer, more detailed answers, even if they are less accurate. Self-Enhancement Bias: A model tends to rate its own output more favorably. This is a strong argument for using a different, often more powerful, model as the judge. Next, review the we should keep in mind on best practices. Key takeaways include using crisp guidelines, a binary scale for easier judgment, and setting a low temperature for reproducible evaluations.
Mitigating these biases is an engineering task. For example, to combat self-enhancement bias, a common practice is to use a more powerful (and potentially more expensive) model like GPT-4 as the judge, even if the agent itself uses a faster, cheaper model for generation. To manage verbosity bias, your rubric prompt can explicitly instruct the judge to ignore length. These are the kinds of details that separate a prototype from a production-ready system.
Conclusion
In this lesson, we have engineered a systematic process for detecting hallucinations in our agent's outputs. By treating the retrieved context in a RAG system as ground truth, we've transformed the vague problem of "hallucination" into the concrete engineering task of verifying "faithfulness."
Key Takeaways:
- Hallucination detection is a validation problem. For RAG and tool-using agents, we can verify the LLM's output against the context it was given.
- The LLM-as-a-Judge pattern is a powerful architecture. It uses an LLM's own capabilities to check the output of another LLM, avoiding brittle, rule-based text parsing.
- A robust implementation uses a multi-step process:
- Decompose the response into atomic claims.
- Verify each claim against the context using a structured "rubric."
- Production systems must account for judge bias. Using a more powerful, separate model for the judge, designing clear prompts, and setting a low temperature are crucial best practices for reliable and reproducible validation.
Preview of the Next Lesson:
We now have a mechanism to detect when our agent is hallucinating or otherwise violating content policies. But what should the agent do with that information? Simply flagging an error might not be enough. In the next lesson, we will implement output guardrails, which are rules and actions that enforce constraints on the final output. This will allow us to filter, re-generate, or escalate responses that our new hallucination detector has flagged, completing the safety loop from detection to enforcement.