healthcare-rag-api / README.md
Santhakumar Ramesh
feat: initial deploy to HF Space
3872518
|
Raw
History Blame Contribute Delete
11.3 kB
metadata
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+ FastAPI LangChain License: MIT

Live Demo:


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


✨ 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

git clone https://github.com/Santhakumarramesh/healthcare-rag-agent.git
cd healthcare-rag-agent

2. Install Dependencies

pip install -r requirements.txt

3. Configure Environment

cp .env.example .env
# Edit .env and add your OPENAI_API_KEY

4. Run the Application

UI (AI Healthcare Copilot)

streamlit run streamlit_app/app_healthcare.py --server.port 8501

API Server

uvicorn api.main:app --host 0.0.0.0 --port 8000

πŸ—οΈ Architecture

System Overview

Architecture Diagram

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 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

docker-compose up --build

Hugging Face Spaces (API) + Streamlit Cloud (UI)

Step 1 β€” Build the FAISS index locally (one-time setup):

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 β†’ 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 β†’ 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:


πŸ“š 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

pytest tests/

Code Quality

# 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 file


πŸ™ Acknowledgments

Built with:

  • OpenAI GPT-4o and GPT-4o-mini
  • LangChain and LangGraph
  • FastAPI and Streamlit
  • FAISS for vector search

πŸ“ž Contact


⚠️ 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