Introduction
In enterprise environments, particularly in regulated industries like healthcare, finance, and manufacturing, hallucinations-where an AI model generates plausible but factually incorrect information-are not just errors; they are liabilities. While Retrieval-Augmented Generation (RAG) significantly reduces hallucinations by grounding responses in external data, it does not eliminate them entirely. Models may still ignore retrieved context, misinterpret data, or fabricate connections between unrelated documents.
This article presents a robust, enterprise-grade solution using LangGraph to build a multi-agent RAG system that actively detects and fixes hallucinations. We implement a "Verify-Then-Trust" workflow where a dedicated agent acts as a factual auditor, ensuring every claim in the generated response is supported by retrieved evidence before it reaches the user.
Step-by-Step Implementation
1. State Schema with Verification Tracking
from typing import List, Dict, Any, TypedDict, Optional
from langgraph.graph import StateGraph, END
from langchain_core.messages import HumanMessage, AIMessage
class VerificationState(TypedDict):
messages: List
retrieved_documents: List[Dict] # Contains content and metadata
initial_draft: str
verified_answer: str
hallucination_detected: bool
verification_feedback: str
confidence_score: float
citations: List[str]
2. Retrieval Agent with Source Tracking
from langchain_community.vectorstores import PGVector
from langchain_huggingface import HuggingFaceEmbeddings
class RetrievalAgent:
def __init__(self, vector_store: PGVector):
self.vector_store = vector_store
def retrieve(self, state: VerificationState) -> VerificationState:
"""Retrieve relevant documents and store them with IDs"""
query = state["messages"][-1].content
docs = self.vector_store.similarity_search_with_score(query, k=5)
retrieved = []
for doc, score in docs:
retrieved.append({
"id": doc.metadata.get("doc_id"),
"content": doc.page_content,
"source": doc.metadata.get("source"),
"relevance_score": score
})
state["retrieved_documents"] = retrieved
return state
3. Initial Generation Agent
from langchain_openai import ChatOpenAI
class GeneratorAgent:
def __init__(self):
self.llm = ChatOpenAI(model="gpt-4", temperature=0.1)
def generate_draft(self, state: VerificationState) -> VerificationState:
"""Generate an initial answer based on retrieved context"""
context = "\n".join([doc["content"] for doc in state["retrieved_documents"]])
query = state["messages"][-1].content
prompt = f"""
Answer the question based ONLY on the following context.
If the answer is not in the context, state "Information not found".
Context:
{context}
Question: {query}
"""
response = self.llm.invoke(prompt)
state["initial_draft"] = response.content
return state
4. Hallucination Detector Agent (LLM-as-a-Judge)
class VerifierAgent:
def __init__(self):
self.judge_llm = ChatOpenAI(model="gpt-4", temperature=0.0)
def verify_facts(self, state: VerificationState) -> VerificationState:
"""Check if the draft answer is supported by the retrieved documents"""
draft = state["initial_draft"]
docs = state["retrieved_documents"]
context_text = "\n".join([f"[Doc {i+1}]: {d['content']}" for i, d in enumerate(docs)])
prompt = f"""
You are a factual auditor. Your job is to detect hallucinations.
Retrieved Context:
{context_text}
Draft Answer:
{draft}
Instructions:
1. Identify every claim in the Draft Answer.
2. Check if each claim is explicitly supported by the Retrieved Context.
3. If any claim is unsupported or contradicted, mark as HALLUCINATION.
4. Provide specific feedback on which parts are unsupported.
Output Format (JSON):
{{
"hallucination_detected": true/false,
"confidence_score": 0.0-1.0,
"feedback": "Specific details on unsupported claims...",
"supported_citations": ["Doc 1", "Doc 3"]
}}
"""
response = self.judge_llm.invoke(prompt)
# In production, parse JSON properly
result = {
"hallucination_detected": False, # Placeholder parsing
"confidence_score": 0.9,
"feedback": "",
"supported_citations": ["Doc 1"]
}
state["hallucination_detected"] = result["hallucination_detected"]
state["verification_feedback"] = result["feedback"]
state["confidence_score"] = result["confidence_score"]
state["citations"] = result["supported_citations"]
return state

Join the conversation! Your thoughts help the community grow.