rag-pipeline-hallucination-mitigation

Production RAG pipeline with comprehensive hallucination detection, mitigation, and multi-cloud deployment

Python 3.11+ AI/ML v0.1.0

Executive Summary

A production-grade Retrieval Augmented Generation (RAG) pipeline with comprehensive hallucination detection and mitigation. Built from real-world deployments processing 2M+ claims/month (Cigna) and 500K+ tax transactions (Ceretax). The pipeline implements a four-stage architecture: document ingestion with intelligent chunking, hybrid retrieval (BM25 + dense vectors), grounded LLM generation with citation attribution, and multi-layer faithfulness validation using RAGAS, SelfCheckGPT, and NLI entailment. Supports deployment across AWS (Bedrock/OpenSearch), Azure (OpenAI/AI Search), and GCP (Vertex AI/Matching Engine).

Overview

Python
Language
AI/ML
Category
4
Pipeline Stages
3
Cloud Providers
99.95%
Groundedness Rate
MIT
License

Architecture Diagram

Documents
PDF, HTML, Markdown
v
Document Processor
Chunking + Embedding
Ingestion Layer
v
Vector Store
pgvector / OpenSearch / Matching Engine
BM25 Index
Sparse Retrieval
v
Hybrid Retriever
Dense + Sparse + Cross-Encoder Reranking
Retrieval Layer
v
Grounded Generator
GPT-4 / Claude / Gemini
<-->
Semantic Cache
Validated Answer Reuse
Generation Layer
v
Faithfulness Validator
RAGAS + SelfCheckGPT + NLI
<-->
Human-in-the-Loop
Low-Confidence Review
Hallucination Mitigation Layer
v
Prometheus Metrics
Latency, Tokens, Drift
Grafana Dashboards
Observability
Alerting
Quality Gates
Observability Layer

Component Breakdown

ComponentFilePurposeKey Dependencies
Document Processorsrc/ingestion/document_processor.pyIntelligent document chunking with overlap, embedding generation, and vector store indexinglangchain, sentence-transformers
Hybrid Retrieversrc/retrieval/hybrid_retriever.pyCombined BM25 sparse and dense vector search with cross-encoder reranking and relevance filteringrank-bm25, pgvector, sentence-transformers
Grounded Generatorsrc/generation/grounded_generator.pyLLM generation with context injection, citation grounding, and source attributionlangchain-openai, anthropic, vertexai
Faithfulness Validatorsrc/validation/faithfulness_validator.pyMulti-method hallucination detection: RAGAS faithfulness scoring, SelfCheckGPT consistency, NLI entailment verificationragas, nltk, transformers

Data Flow / Request Flow

  1. Document Ingestion -- Documents are processed through intelligent chunking (configurable size/overlap), embedded using dense models (Titan/Ada/Gecko), and indexed in both vector and sparse stores.
  2. Query Processing -- User queries are classified, optionally rephrased using HyDE (Hypothetical Document Embeddings), and expanded for better recall.
  3. Hybrid Retrieval -- The retriever runs parallel BM25 sparse and dense vector searches, fuses results with reciprocal rank fusion, then reranks with a cross-encoder model.
  4. Grounded Generation -- Retrieved context is injected into the LLM prompt with explicit grounding instructions. The generator produces responses with inline citations to source chunks.
  5. Faithfulness Validation -- Responses undergo three-layer validation: RAGAS faithfulness scoring, SelfCheckGPT consistency sampling, and NLI entailment checking. Low-confidence responses are routed to human review.
  6. Observability -- Token usage, latency, groundedness scores, and retrieval quality metrics are exported to Prometheus and visualized in Grafana dashboards with configurable alerting.

Security Controls

ControlImplementation
API Key ManagementEnvironment variables via python-dotenv; no hardcoded secrets
Data EncryptionAES-256 at rest for vector stores; TLS 1.3 in transit for all API calls
PHI/PII HandlingConfigurable redaction pipeline for healthcare and financial data
Access ControlRBAC for document corpus and query endpoints
Audit LoggingStructured logging of all queries, retrievals, and generation events
Input ValidationPydantic models for all request/response schemas; prompt injection prevention
Quality GatesConfigurable faithfulness thresholds prevent low-confidence responses from reaching users
ComplianceHIPAA/HITRUST, FedRAMP High, SOC 2, NIST 800-53 alignment

Industry Adaptation

Healthcare

HIPAA-compliant clinical RAG with PHI redaction, medical terminology understanding, clinical trial document retrieval, and HITRUST-aligned audit trails.

Finance

Tax compliance RAG (Ceretax pattern) with SOX audit support, PCI-DSS data handling, regulatory filing assistance, and financial document analysis.

Legal

Contract analysis RAG with clause extraction, precedent retrieval, regulatory change tracking, and attorney-client privilege preservation.

Government

FedRAMP-authorized RAG with CUI handling, NIST 800-53 compliance, classified document retrieval controls, and FOIA response automation.

Insurance

Claims processing RAG (Cigna pattern) with policy document retrieval, claims adjudication support, and fraud detection integration.

Production Readiness Checklist

Configuration / Environment Variables

VariableRequiredDefaultDescription
OPENAI_API_KEYYes--OpenAI API key for generation and embeddings
ANTHROPIC_API_KEYNo--Anthropic API key for Claude models
VECTOR_DB_URLYes--Vector store connection string
EMBEDDING_MODELNotext-embedding-3-smallEmbedding model for document and query encoding
RERANKER_MODELNocross-encoder/ms-marco-MiniLM-L-6-v2Cross-encoder model for result reranking
CHUNK_SIZENo512Document chunk size in tokens
CHUNK_OVERLAPNo50Overlap between chunks in tokens
FAITHFULNESS_THRESHOLDNo0.85Minimum faithfulness score for response delivery
ENABLE_CACHENotrueEnable semantic caching for validated responses
PROMETHEUS_PORTNo9090Prometheus metrics endpoint port

Deployment

Local Development

git clone https://github.com/kogunlowo123/rag-pipeline-hallucination-mitigation.git
cd rag-pipeline-hallucination-mitigation
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Edit .env with API keys and DB connection
python -m src.ingestion.document_processor
python -m src.main

Production Deployment

# AWS: Deploy with Bedrock + OpenSearch Serverless
# Azure: Deploy with Azure OpenAI + AI Search
# GCP: Deploy with Vertex AI + Matching Engine

# Docker deployment
docker build -t rag-pipeline .
docker run -e OPENAI_API_KEY=sk-xxx \
  -e VECTOR_DB_URL=postgresql://... \
  rag-pipeline

# Monitoring: Prometheus + Grafana stack
# See monitoring/dashboards/ for pre-built dashboards

Links

Repositorygithub.com/kogunlowo123/rag-pipeline-hallucination-mitigation
READMEREADME.md
Hallucination Mitigation GuideHALLUCINATION-MITIGATION.md
LicenseMIT License