A Production-Grade Retrieval-Augmented Generation System for Clinical Decision Support
Designed for Automated Clinical Assurance with Rigorous Evaluation Metrics
- Overview
- Key Features
- Performance Metrics
- Architecture
- Quick Start
- Technical Stack
- Evaluation Framework
- Project Structure
- Configuration
- Safety & Ethics
- About the Project
This repository implements a production-grade Clinical RAG (Retrieval-Augmented Generation) system specifically designed for clinical decision support. The system demonstrates advanced capabilities in:
- Hybrid Search Architecture: Combining BM25 keyword search with semantic vector search for optimal retrieval accuracy
- Automated Evaluation: Comprehensive evaluation framework using Ragas metrics with rigorous performance optimization
- Clinical Safety: Strict prompt engineering ensuring 100% context-grounded responses with explicit source attribution
- Production Readiness: Modular architecture with persistent storage, comprehensive error handling, and scalable design
Built on WHO Malaria Guidelines, this system showcases best practices for developing and evaluating clinical AI systems with measurable quality assurance.
- Dual Retrieval Strategy: Combines BM25 (keyword) and Vector (semantic) search via EnsembleRetriever
- Clinical Optimization: Specifically tuned for medical terminology, drug names, and dosage information
- Weighted Ensemble: Balanced 50/50 weighting for optimal retrieval precision
- Strict Context Enforcement: System prompts enforce context-only responses with zero tolerance for hallucinations
- Deterministic Outputs: Temperature set to 0.0 for reproducible, consistent results
- Explicit Uncertainty Handling: Clear messaging when information is not available in source documents
- Automated Test Generation: Synthetic test set generation using Ragas TestsetGenerator
- Multi-Metric Assessment: Evaluates Faithfulness, Answer Relevancy, and Context Precision
- Performance Optimization: Demonstrated improvement from baseline 57% to 87.5% faithfulness through systematic optimization
- Persistent Vector Store: ChromaDB with disk persistence for efficient operations
- Modular Architecture: Clean separation of concerns with type hints throughout
- Interactive UI: Streamlit-based chat interface for clinical decision support
The system is evaluated using industry-standard Ragas metrics on a comprehensive test set:
| Metric | Baseline | Optimized | Improvement | Status |
|---|---|---|---|---|
| Faithfulness | 57.42% | 87.50% | +30.08% ā¬ļø | š¢ Excellent |
| Answer Relevancy | 42.06% | 58.02% | +15.96% ā¬ļø | š” Good |
| Context Precision | 65.54% | 79.65% | +14.11% ā¬ļø | š¢ Very Good |
Through systematic optimization, the system achieved:
- ā 52% relative improvement in Faithfulness (57% ā 87.5%)
- ā 38% relative improvement in Answer Relevancy (42% ā 58%)
- ā 22% relative improvement in Context Precision (65% ā 79.6%)
Key Optimizations Applied:
- Model Upgrade: Migrated from
gpt-4o-minitogpt-4ofor enhanced accuracy - Retrieval Enhancement: Increased TOP_K from 5 to 10 documents for better context coverage
- Prompt Engineering: Advanced prompt optimization for maximum faithfulness and relevancy
š See
evaluation_results/BASELINE_METRICS.mdfor detailed analysis and comparison.
Clinical PDFs
ā
[1] PDF Parser (PyMuPDF)
ā
[2] Semantic Chunker (RecursiveCharacterTextSplitter)
ā
[3] Vector Embeddings (OpenAI text-embedding-3-small)
ā
[4] Hybrid Retrieval (BM25 + Vector Search)
ā
[5] Context-Aware Generation (GPT-4o with Strict Prompts)
ā
Clinical Response with Source Attribution
-
Ingestion Pipeline
- Clinical PDF parsing with robust handling of complex layouts
- Semantic chunking with intelligent boundary detection
- Persistent vector store management with ChromaDB
-
RAG System
- Hybrid retriever combining keyword and semantic search
- Context-aware generator with strict clinical prompts
- Source document attribution for transparency
-
Evaluation Framework
- Synthetic test set generation from source documents
- Multi-metric evaluation using Ragas
- Comprehensive performance reporting
- Python 3.9 or higher
- OpenAI API key (Get one here)
- WHO Malaria Guidelines PDF (or any clinical guideline PDF)
# 1. Clone the repository git clone <repository-url> cd Clinical_RAG_System # 2. Create virtual environment python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate # 3. Install dependencies pip install -r requirements.txt # 4. Configure environment cp .env.example .env # Edit .env and add your OPENAI_API_KEY # 5. Add PDF documents # Place your clinical guideline PDFs in data/raw_pdfs/
# Step 1: Parse and chunk PDFs python -m src.ingestion.parser python -m src.ingestion.chunker # Step 2: Create vector embeddings python -m src.ingestion.vector_store # Step 3: Generate test set (optional) python -m src.evaluation.generator # Step 4: Run evaluation (optional) python -m src.evaluation.metrics # Step 5: Launch interactive UI streamlit run src/app.py
| Category | Technology |
|---|---|
| Framework | LangChain 0.2+ |
| Vector Database | ChromaDB (Persistent, Local) |
| LLM | OpenAI GPT-4o |
| Embeddings | OpenAI text-embedding-3-small |
| Retrieval | Hybrid (BM25 + Vector) via EnsembleRetriever |
| Evaluation | Ragas |
| UI Framework | Streamlit |
| PDF Processing | PyMuPDF |
| Language | Python 3.9+ |
This project implements comprehensive evaluation using Ragas, an industry-standard framework for RAG evaluation:
-
Faithfulness (87.50%)
- Measures how grounded answers are in the provided context
- Critical for clinical applications to prevent hallucinations
- Target: >95%
-
Answer Relevancy (58.02%)
- Measures how relevant the answer is to the question asked
- Ensures responses directly address clinical queries
- Target: >95%
-
Context Precision (79.65%)
- Measures precision of retrieved context documents
- Validates retrieval quality and relevance
- Target: >95%
# Generate synthetic test set test_gen = TestSetGenerator() testset = test_gen.generate_testset(documents, test_size=10) # Evaluate system metrics = EvaluationMetrics() results = metrics.evaluate_rag_system(testset, rag_chain) metrics.save_results(results) # Exports to CSV
Clinical_RAG_System/
āāā .env.example # Environment variable template
āāā requirements.txt # Python dependencies
āāā README.md # This file
ā
āāā data/
ā āāā raw_pdfs/ # Input PDF documents
ā āāā vector_store/ # Persistent ChromaDB storage
ā
āāā evaluation_results/ # Evaluation outputs
ā āāā test_set.csv # Generated test questions
ā āāā evaluation_results.csv # Evaluation metrics
ā āāā BASELINE_METRICS.md # Performance analysis
ā
āāā src/
āāā config.py # Central configuration
ā
āāā ingestion/ # Data ingestion pipeline
ā āāā parser.py # PDF parsing
ā āāā chunker.py # Semantic chunking
ā āāā vector_store.py # Vector store management
ā
āāā rag/ # RAG system
ā āāā retriever.py # Hybrid retrieval
ā āāā generator.py # Answer generation
ā
āāā evaluation/ # Evaluation framework
ā āāā generator.py # Test set generation
ā āāā metrics.py # Evaluation metrics
ā
āāā app.py # Streamlit UI
Key configuration parameters in src/config.py:
| Parameter | Default | Description |
|---|---|---|
LLM_MODEL |
gpt-4o |
Language model for generation |
EMBEDDING_MODEL |
text-embedding-3-small |
Embedding model |
TOP_K_RETRIEVAL |
10 |
Number of documents to retrieve |
CHUNK_SIZE |
1000 |
Character size for chunking |
CHUNK_OVERLAP |
200 |
Overlap between chunks |
This system is designed for demonstration and research purposes. For clinical use:
ā ļø Always verify responses against authoritative sourcesā ļø Never rely solely on AI-generated medical adviceā ļø Consult healthcare professionals for patient care decisionsā ļø Follow regulatory requirements for medical AI systems
The system implements strict safety measures including:
- Context-only responses (no external knowledge injection)
- Explicit uncertainty handling
- Source attribution for transparency
- Deterministic outputs for reproducibility
This project demonstrates production-grade Clinical AI system development with a focus on:
- Systematic Evaluation: Comprehensive metrics-based assessment
- Performance Optimization: Demonstrated improvement from baseline through targeted enhancements
- Clinical Safety: Strict adherence to context-grounded responses
- Production Best Practices: Modular architecture, error handling, and scalability
- ā Achieved 87.5% Faithfulness through systematic optimization (+30% improvement)
- ā Implemented comprehensive evaluation framework with industry-standard metrics
- ā Developed hybrid retrieval system optimized for clinical terminology
- ā Built production-ready architecture with persistent storage and error handling
- Clinical decision support systems
- Evidence-based medical information retrieval
- Automated guideline compliance checking
- Medical education and training systems
| Module | File | Description |
|---|---|---|
| PDF Parser | ingestion/parser.py |
Clinical PDF parsing (PyMuPDF) |
| Chunker | ingestion/chunker.py |
Semantic chunking (RecursiveCharacterTextSplitter) |
| Vector Store | ingestion/vector_store.py |
ChromaDB vector store management |
| Hybrid Retriever | rag/retriever.py |
BM25 + Vector search |
| Generator | rag/generator.py |
Context-aware answer generation |
| Test Generator | evaluation/generator.py |
Synthetic test set generation |
| Metrics | evaluation/metrics.py |
Ragas evaluation suite |
| UI | app.py |
Streamlit chat interface |
This is a portfolio project demonstrating Clinical Evaluation Engineering capabilities. For improvements or suggestions:
- Fork the repository
- Create a feature branch
- Make your changes
- Submit a pull request
This project is for educational and demonstration purposes.
- WHO for providing Malaria Guidelines as reference material
- LangChain for the RAG framework
- Ragas for comprehensive evaluation metrics
- Streamlit for the UI framework
- OpenAI for language models and embeddings
Clinical Evaluation Engineer & LLMOps Specialist
- NVIDIA Associate Certification in LLMs and Generative AI
- Specialized in Clinical AI system evaluation and optimization
- Focus on measurable quality assurance and performance metrics
Built with ā¤ļø for Clinical AI Excellence
For questions or feedback, please open an issue in the repository.