File size: 11,339 Bytes
3872518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
---
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**