The Enterprise RAG Hallucination Wall #
Basic Retrieval-Augmented Generation (RAG)—where queries are embedded, searched via top-k cosine similarity, and dumped into an LLM context prompt—fails catastrophically on enterprise legal contracts, financial audits, and technical compliance manuals.
Common failure points include: 1. **Context Fragmentation:** The relevant answer spans multiple non-contiguous table paragraphs. 2. **Missing Negative Confirmation:** The model invents plausible facts when the documentation does not state the answer. 3. **Stale Semantic Retrieval:** Pure vector search misses exact SKU codes, clause numbers, and acronyms.
---
LangGraph Cyclical State Machine Architecture #
To guarantee deterministic, auditable responses, we model the AI workflow as a **cyclical directed graph** with state validation checkpoints:
import { StateGraph, END } from "@langchain/langgraph";
interface AgentGraphState {
userQuery: string;
retrievedDocuments: Array<{ id: string; text: string; score: number }>;
isContextSufficient: boolean;
refinedQuery?: string;
generatedAnswer?: string;
hallucinationScore: number;
}
// Instantiate Cyclical Workflow Graph
const workflow = new StateGraph<AgentGraphState>({
channels: {
userQuery: null,
retrievedDocuments: null,
isContextSufficient: null,
refinedQuery: null,
generatedAnswer: null,
hallucinationScore: null,
}
});
// Define Autonomous Nodes
workflow.addNode("retrieve_hybrid", retrieveHybridDocumentsNode);
workflow.addNode("grade_relevance", gradeDocumentRelevanceNode);
workflow.addNode("rewrite_query", rewriteAmbiguousQueryNode);
workflow.addNode("synthesize_answer", synthesizeVerifiedAnswerNode);
workflow.addNode("hallucination_guard", auditHallucinationScoreNode);
// Define Conditional Routing
workflow.addConditionalEdges("grade_relevance", (state) => {
return state.isContextSufficient ? "synthesize_answer" : "rewrite_query";
});
workflow.addEdge("rewrite_query", "retrieve_hybrid");
workflow.addConditionalEdges("hallucination_guard", (state) => {
return state.hallucinationScore < 0.05 ? END : "synthesize_answer";
});
---
Hybrid Search with Reciprocal Rank Fusion (RRF) in PostgreSQL pgvector #
We combine dense HNSW vector embeddings (OpenAI `text-embedding-3-large`) with sparse full-text BM25 indexes using PostgreSQL `pgvector` and Reciprocal Rank Fusion (RRF):
-- Hybrid Vector + Full-Text RRF Query
WITH semantic_search AS (
SELECT id, content, RANK() OVER (ORDER BY embedding <=> $1) as rank
FROM enterprise_knowledge_chunks
WHERE tenant_id = $2
LIMIT 20
),
keyword_search AS (
SELECT id, content, RANK() OVER (ORDER BY ts_rank(text_search_vector, plainto_tsquery('english', $3)) DESC) as rank
FROM enterprise_knowledge_chunks
WHERE tenant_id = $2 AND text_search_vector @@ plainto_tsquery('english', $3)
LIMIT 20
)
SELECT
COALESCE(s.id, k.id) as chunk_id,
COALESCE(s.content, k.content) as content,
(COALESCE(1.0 / (60 + s.rank), 0.0) + COALESCE(1.0 / (60 + k.rank), 0.0)) as rrf_score
FROM semantic_search s
FULL OUTER JOIN keyword_search k ON s.id = k.id
ORDER BY rrf_score DESC
LIMIT 8;
This guarantees sub-second, 100% cited answers backed by mathematical clause references.