--- title: Healthcare RAG API emoji: ๐Ÿฅ colorFrom: blue colorTo: green sdk: docker app_port: 8000 pinned: false --- # Healthcare AI Platform **Production-style healthcare AI system with multi-agent routing, RAG pipeline, report analysis, and monitoring.** [![Python 3.11+](https://img.shields.io/badge/Python-3.11+-blue?logo=python)](https://python.org) [![FastAPI](https://img.shields.io/badge/FastAPI-0.115-green?logo=fastapi)](https://fastapi.tiangolo.com) [![LangChain](https://img.shields.io/badge/LangChain-0.3-orange)](https://langchain.com) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) **Live Demo**: - **UI**: [Streamlit Community Cloud](https://your-app.streamlit.app) *(set up at share.streamlit.io)* - **API**: [Hugging Face Spaces](https://your-username-healthcare-rag-api.hf.space) *(set up at huggingface.co/spaces)* - **API Docs**: [/docs](https://your-username-healthcare-rag-api.hf.space/docs) --- ## What It Does An intelligent healthcare assistant that: - ๐Ÿ’ฌ **Answers medical questions** with evidence-based responses - ๐Ÿ“„ **Analyzes lab reports** (PDF/images) with AI-powered explanations - ๐Ÿง  **Multi-step reasoning** for complex medical queries - ๐Ÿ‘๏ธ **Multimodal support** using GPT-4o vision - โš ๏ธ **Emergency detection** for 14 critical symptoms - ๐Ÿ” **Enterprise security** with authentication and audit logs ![AI Healthcare Copilot Dashboard](docs/screenshots/dashboard.png) --- ## โœจ Key Features ### Core RAG Pipeline - **Multi-agent routing** - Classify queries into 7 types (symptom check, drug info, emergency, etc.) - **Hybrid retrieval** - FAISS vector search + BM25 keyword matching - **Streaming responses** - Real-time answer generation - **Confidence scoring** - Multi-factor quality assessment - **Source citations** - Grounded answers with references ### Medical Features - **Report analysis** - Upload PDF/images, extract lab values, flag abnormal results - **Serious condition follow-up** - Daily monitoring workflow for high-risk patients - **Emergency detection** - Alert for 14 critical symptoms - **Drug interaction warnings** - Common dangerous combinations - **Health recommendations** - AI-powered dietary and lifestyle advice - **Session memory** - Remember conversation context ### Production Features - **Authentication** - JWT tokens with role-based access (Patient, Clinician, Admin) - **Database persistence** - SQLite with 7 tables (PostgreSQL-ready) - **Audit logging** - Track all user actions - **API key management** - For external integrations - **Real-time monitoring** - Query metrics, latency, confidence distribution --- ## ๐Ÿš€ Quick Start ### 1. Clone Repository ```bash git clone https://github.com/Santhakumarramesh/healthcare-rag-agent.git cd healthcare-rag-agent ``` ### 2. Install Dependencies ```bash pip install -r requirements.txt ``` ### 3. Configure Environment ```bash cp .env.example .env # Edit .env and add your OPENAI_API_KEY ``` ### 4. Run the Application **UI (AI Healthcare Copilot)** ```bash streamlit run streamlit_app/app_healthcare.py --server.port 8501 ``` **API Server** ```bash uvicorn api.main:app --host 0.0.0.0 --port 8000 ``` --- ## ๐Ÿ—๏ธ Architecture ### System Overview ![Architecture Diagram](docs/screenshots/architecture.png) **5-Stage Pipeline:** ``` 1. Router โ†’ Classify query intent (7 types: symptom, drug, emergency, etc.) 2. Retriever โ†’ Hybrid search (FAISS vector + BM25 keyword matching) 3. Web/Search โ†’ Optional fallback for current information 4. Reasoning โ†’ Structured multi-step analysis with evidence grounding 5. Evaluation โ†’ Quality validation, confidence scoring, safety checks ``` **Production Layers:** - **Authentication** - JWT tokens with role-based access control - **Knowledge Graph** - Disease-symptom-drug relationship mapping - **Clinical Alerts** - Emergency detection for 14 critical symptoms - **Session Memory** - Database-backed conversation history - **Audit Logging** - HIPAA-compliant activity tracking - **Monitoring** - Real-time metrics and performance analytics **Tech Stack**: FastAPI + LangChain + LangGraph + OpenAI + FAISS + SQLAlchemy + Streamlit **See**: [ARCHITECTURE.md](ARCHITECTURE.md) for detailed system design --- ## ๐Ÿ“ฆ Technology Stack ### Backend - **FastAPI** - Async REST API - **LangChain + LangGraph** - Multi-agent orchestration - **OpenAI** - GPT-4o-mini + GPT-4o vision - **FAISS** - Vector similarity search - **SQLAlchemy** - Database ORM ### Frontend - **Streamlit** - Interactive web UI (2 versions) - **Plotly** - Data visualizations - **Custom CSS** - Professional design ### Infrastructure - **SQLite/PostgreSQL** - Database - **Docker** - Containerization - **Render** - Cloud deployment - **GitHub Actions** - CI/CD --- ## ๐ŸŽ“ Use Cases ### 1. Medical Q&A Ask questions and get evidence-based answers with sources: - "What are the symptoms of diabetes?" - "Can I take ibuprofen with aspirin?" - "What does high blood pressure mean?" ### 2. Lab Report Analysis Upload reports (PDF or image) for instant analysis: - Extract all lab values - Explain abnormal results - Get personalized health recommendations - Identify critical values ### 3. Symptom Checking Describe symptoms and get guidance: - Possible causes - When to see a doctor - Emergency detection - Multi-symptom risk assessment ### 4. Medication Information Learn about drugs and treatments: - What they treat - Side effects - Drug interactions - Contraindications --- ## ๐Ÿ” Security & Compliance - **JWT Authentication** - Secure token-based auth - **Role-Based Access Control** - Patient, Clinician, Admin roles - **HIPAA-Compliant Audit Logs** - Track all user actions - **Password Hashing** - bcrypt with salt - **API Key Management** - Rate limiting and usage tracking - **Clinical Alerts** - Automatic danger detection --- ## ๐Ÿ“Š API Endpoints ### Core - `GET /health` - System health check - `POST /chat` - Ask questions - `GET /monitoring/stats` - Real-time metrics ### Medical Records - `POST /records/upload` - Upload report - `POST /records/analyze` - Analyze report - `POST /records/qa` - Ask questions about report ### Authentication - `POST /auth/login` - User login - `POST /auth/register` - User registration - `GET /auth/me` - Current user info ### Admin - `GET /admin/audit-logs` - Audit logs (admin only) - `POST /admin/api-keys` - Create API key (clinician/admin) - `GET /admin/system/health` - System health (admin only) **Full API documentation**: Visit `/docs` endpoint --- ## ๐Ÿ—„๏ธ Database Schema 7 tables for complete data persistence: - **users** - User accounts - **sessions** - Conversation history - **interactions** - Query/response pairs - **reports** - Uploaded medical reports - **api_keys** - External API access - **audit_logs** - Compliance tracking - **alerts** - Clinical alerts --- ## ๐Ÿงช Demo Credentials ``` Admin: admin@healthcare.ai / admin123 Clinician: doctor@healthcare.ai / doctor123 Patient: patient@healthcare.ai / patient123 ``` --- ## ๐Ÿ“ˆ Performance - **Average Latency**: 3-4 seconds - **Complex Reasoning**: 9-12 seconds - **Image Analysis**: 3-5 seconds - **Report Analysis**: 30-60 seconds - **Success Rate**: 97%+ --- ## ๐Ÿš€ Deployment ### Docker ```bash docker-compose up --build ``` ### Hugging Face Spaces (API) + Streamlit Cloud (UI) **Step 1 โ€” Build the FAISS index locally** (one-time setup): ```bash python vectorstore/ingest.py git add vectorstore/faiss_index/ git commit -m "chore: add pre-built FAISS index" git push ``` **Step 2 โ€” Deploy API to Hugging Face Spaces**: 1. Create a Space at [huggingface.co/new-space](https://huggingface.co/new-space) โ†’ SDK: **Docker** 2. Link your GitHub repo under *Files โ†’ Link to GitHub repository* 3. Add secrets in Space Settings: `OPENAI_API_KEY`, `JWT_SECRET_KEY`, `CORS_ORIGINS` 4. The Space auto-builds from the `Dockerfile` and redeploys on every push to `main` **Step 3 โ€” Deploy UI to Streamlit Community Cloud**: 1. Go to [share.streamlit.io](https://share.streamlit.io) โ†’ *New app* 2. Repo: `Santhakumarramesh/healthcare-rag-agent`, branch: `main` 3. Main file: `streamlit_app/app_healthcare.py` 4. Requirements file: `requirements-ui.txt` 5. Add secret: `API_BASE_URL = https://your-username-healthcare-rag-api.hf.space` **Step 4 โ€” CI/CD auto-sync** (every push to main auto-deploys): Add to *GitHub โ†’ Settings โ†’ Secrets โ†’ Actions*: - Secret `HF_TOKEN` โ€” from [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) (write scope) - Variable `HF_USERNAME` โ€” your Hugging Face username --- ## ๐Ÿ“š Documentation - **[User Guide](USER_GUIDE.md)** - How to use the app - **[Architecture](ARCHITECTURE.md)** - System design - **[Implementation Roadmap](IMPLEMENTATION_ROADMAP.md)** - Development plan - **[Security](SECURITY.md)** - Security features - **[Level 2-4 Docs](docs/)** - Feature documentation --- ## ๐Ÿ› ๏ธ Development ### Project Structure ``` healthcare-rag-agent/ โ”œโ”€โ”€ api/ # FastAPI backend โ”‚ โ”œโ”€โ”€ main.py # Main API app โ”‚ โ”œโ”€โ”€ auth.py # Authentication endpoints โ”‚ โ”œโ”€โ”€ admin.py # Admin endpoints โ”‚ โ””โ”€โ”€ records.py # Medical records endpoints โ”œโ”€โ”€ agents/ # AI agents โ”‚ โ”œโ”€โ”€ rag_pipeline.py # Main RAG pipeline โ”‚ โ”œโ”€โ”€ router_agent.py # Query routing โ”‚ โ””โ”€โ”€ reasoning_agent.py # Multi-step reasoning โ”œโ”€โ”€ services/ # Business logic โ”‚ โ”œโ”€โ”€ auth_service.py # Authentication โ”‚ โ”œโ”€โ”€ memory_service.py # Conversation memory โ”‚ โ”œโ”€โ”€ alert_service.py # Clinical alerts โ”‚ โ””โ”€โ”€ monitoring_service.py # Metrics โ”œโ”€โ”€ database/ # Database layer โ”‚ โ”œโ”€โ”€ models.py # SQLAlchemy models โ”‚ โ””โ”€โ”€ database.py # Connection management โ”œโ”€โ”€ multimodal/ # Image processing โ”‚ โ””โ”€โ”€ image_analyzer.py # GPT-4o vision โ”œโ”€โ”€ streamlit_app/ # Frontend โ”‚ โ”œโ”€โ”€ app.py # Advanced UI โ”‚ โ””โ”€โ”€ app_v2.py # Simple UI โ””โ”€โ”€ vectorstore/ # Vector storage โ””โ”€โ”€ personal_store.py # Document indexing ``` ### Running Tests ```bash pytest tests/ ``` ### Code Quality ```bash # Format code black . # Lint flake8 . # Type check mypy . ``` --- ## ๐Ÿค Contributing Contributions welcome! Please: 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests 5. Submit a pull request --- ## ๐Ÿ“„ License MIT License - see [LICENSE](LICENSE) file --- ## ๐Ÿ™ Acknowledgments Built with: - OpenAI GPT-4o and GPT-4o-mini - LangChain and LangGraph - FastAPI and Streamlit - FAISS for vector search --- ## ๐Ÿ“ž Contact - **GitHub**: https://github.com/Santhakumarramesh - **Issues**: https://github.com/Santhakumarramesh/healthcare-rag-agent/issues --- ## โš ๏ธ Disclaimer This AI assistant provides general health information for educational purposes only. It does not replace professional medical advice, diagnosis, or treatment. Always consult a qualified healthcare provider for medical concerns or emergencies. For emergencies, call 911 immediately. --- **Built with โค๏ธ for better healthcare access**