Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Environment variables and secrets
.env
.env.local
.env.*.local
*.env

# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# Virtual environments
venv/
env/
ENV/
env.bak/
venv.bak/

# IDEs
.vscode/
.idea/
*.swp
*.swo
*~
.DS_Store

# Database files
chroma_db/
*.db
*.sqlite
*.sqlite3

# Data files (do not commit large datasets)
Data/

# Logs
*.log
logs/

# Jupyter Notebook
.ipynb_checkpoints

# pytest
.pytest_cache/
.coverage
htmlcov/

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

111 changes: 111 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
# MedGuard: FDA-Label-Grounded Medication Safety Assistant

## Problem Statement

Medication errors are a leading cause of preventable harm in healthcare. Patients frequently misunderstand drug labels, take incorrect doses, ignore food-related instructions, or rely on unreliable online sources. Traditional AI chatbots are unsafe in this domain because they may hallucinate or provide unverified medical advice.

MedGuard solves this by using **Retrieval-Augmented Generation (RAG)** over **official FDA drug labels**. Every response is grounded in regulatory-grade documentation, ensuring that users receive accurate, traceable, and safe medication information.

## Current Status

✅ **Working MVP** - Core RAG backend is working end-to-end (FastAPI + LangChain + ChromaDB). All API endpoints (`/ask`, `/validate`, `/schedule`) are returning the expected JSON responses, and ingestion/chunking has been tuned to improve FDA-label coverage and answer quality.

## Getting Started

For detailed setup instructions, please refer to [SETUP.md](SETUP.md).

### Quickstart (Windows + Conda)

The full openFDA label dataset is large. For a demo/hackathon, ingest a small subset (4–5 partitions) and cap the total chunks so setup finishes quickly while still proving the end-to-end RAG flow.

## System Architecture

MedGuard follows a safety-first Retrieval-Augmented Generation (RAG) pipeline:

1. The user submits a medication-related question along with optional patient context (age, pregnancy, etc.).

2. The system retrieves relevant sections (Dosage, Warnings, Contraindications, ADRs) from FDA drug labels stored in ChromaDB.

3. A Safety & Conflict Analyzer checks for contradictions or risk factors.

4. The retrieved FDA text is passed to the LLM via LangChain.

5. The LLM generates a grounded answer and a structured reminder plan.

6. The system returns a JSON response with citations and confidence.

This architecture ensures that every output is verifiable, explainable, and compliant with medical safety requirements.

## Technology Stack

| Layer | Technology |
|--------------|------------|
| Language | Python |
| LLM | OpenAI GPT / Google Gemini |
| Framework | LangChain |
| Vector Store | ChromaDB |
| API Layer | FastAPI |
| Data Source | openFDA Drug Label Dataset |
| Validation | Pydantic |

## System Flow

1. The user submits a medication-related question.

2. The system enriches the query with basic patient context (age, pregnancy, etc.).

3. Relevant sections from FDA drug labels are retrieved from the vector database.

4. Safety and conflict checks are applied to validate dosage and warnings.

5. The LLM generates a grounded response using only the retrieved FDA data.

6. A structured medication reminder plan is created from the dosage instructions.

7. The final answer is returned as a JSON response with citations and confidence.

## Future Innovations

- **Adherence + escalation workflow**: reminders + missed-dose logic (label-only) and an optional escalation workflow (email/SMS) when high-risk keywords appear.
- **Dose Safety Engine (label-first)**: parse dose limits, frequency, max daily dose, food/alcohol rules from labels and return a structured “safe/unsafe + why” verdict with citations.
- **Multilingual label-grounded mode**: translate retrieved FDA text first, then answer in the user’s language while keeping citations to the original English sections.

## Screenshots

### System architecture (RAG + safety-first pipeline)
![Architecture flow](Screenshots/Flowchart.jpeg)

### Optional workflow automation (n8n)
![n8n workflow](Screenshots/n8n%20Workflow.jpeg)

### FastAPI docs (endpoints)
![FastAPI docs - endpoints](Screenshots/api-docs-endpoints.png)

Swagger UI showing the available endpoints: `/ask`, `/validate`, `/schedule`.

### FastAPI docs (schemas)
![FastAPI docs - schemas](Screenshots/api-docs-schemas.png)

Request/response schemas used by the API.

### Testing phase (Swagger UI)
#### Debug: `/debug/chroma`
![Debug chroma - parameters](Screenshots/testing/debug-chroma-params.png)

![Debug chroma - response](Screenshots/testing/debug-chroma-response.png)

#### Chat: `/ask`
![Ask - request](Screenshots/testing/ask-request.png)

![Ask - response](Screenshots/testing/ask-response.png)

#### Dosage validation: `/validate`
![Validate - request](Screenshots/testing/validate-request.png)

![Validate - response](Screenshots/testing/validate-response.png)

#### Schedule generator: `/schedule`
![Schedule - request](Screenshots/testing/schedule-request.png)

![Schedule - response](Screenshots/testing/schedule-response.png)

160 changes: 160 additions & 0 deletions SETUP.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# Local Setup Guide

## ⚠️ Important: Python Version Requirement

**ChromaDB requires Python 3.8-3.12**. Python 3.13+ may have compatibility issues.

If you're using Python 3.14, please use **Python 3.11 or 3.12** instead. See `LOCAL_SETUP.md` for details.

## Prerequisites

- Python 3.8-3.12 (3.11 or 3.12 recommended)
- OpenAI API key ([Get one here](https://platform.openai.com/api-keys))
- Virtual environment (recommended)

## Step-by-Step Setup

### 1. Activate Virtual Environment

**Windows (PowerShell):**
```powershell
.\venv\Scripts\Activate.ps1
```

**Windows (Command Prompt):**
```cmd
venv\Scripts\activate.bat
```

**Linux/Mac:**
```bash
source venv/bin/activate
```

### 2. Install Dependencies

```bash
pip install -r requirements.txt
```

### 3. Set OpenAI API Key

**Windows (PowerShell):**
```powershell
$env:OPENAI_API_KEY="your-api-key-here"
```

**Windows (Command Prompt):**
```cmd
set OPENAI_API_KEY=your-api-key-here
```

**Linux/Mac:**
```bash
export OPENAI_API_KEY="your-api-key-here"
```

**Or create a `.env` file** (recommended for persistence):
```env
OPENAI_API_KEY=your-api-key-here
```

Then install `python-dotenv` and load it:
```bash
pip install python-dotenv
```

### 4. Run Data Ingestion (First Time Only)

This populates your ChromaDB with drug label data:

```bash
# For testing (downloads 1 partition - faster, ~5-10 minutes)
python ingest_cloud_embeddings.py --limit-partitions 1

# For full dataset (downloads all partitions - slower, ~30-60 minutes)
python ingest_cloud_embeddings.py
```

**Note:** This only needs to be run once. The data persists in `./chroma_db/` directory.

### 5. Start the API Server

```bash
uvicorn app.main:app --reload
```

The API will be available at:
- **API Base**: http://localhost:8000
- **Interactive Docs**: http://localhost:8000/docs
- **Alternative Docs**: http://localhost:8000/redoc

### 6. Test the API

Visit http://localhost:8000/docs to test the endpoints interactively, or use curl:

```bash
# Test question answering
curl -X POST "http://localhost:8000/ask" \
-H "Content-Type: application/json" \
-d '{"drug_name": "Aspirin", "query": "What are the side effects?"}'
```

## Troubleshooting

### Missing Dependencies

If you get import errors, make sure all dependencies are installed:
```bash
pip install -r requirements.txt --upgrade
```

### API Key Not Found

Make sure the environment variable is set:
```powershell
# Check if set (PowerShell)
$env:OPENAI_API_KEY

# Check if set (Linux/Mac)
echo $OPENAI_API_KEY
```

### ChromaDB Errors

If you get ChromaDB errors, try clearing and re-ingesting:
```bash
python ingest_cloud_embeddings.py --clear-existing --limit-partitions 1
```

### Port Already in Use

If port 8000 is in use, specify a different port:
```bash
uvicorn app.main:app --reload --port 8001
```

## Project Structure

```
supervity/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI application
│ ├── chains.py # LangChain chains (QA, validation, schedule)
│ └── rag.py # Vector store configuration
├── ingest_cloud_embeddings.py # Data ingestion script
├── requirements.txt # Python dependencies
├── chroma_db/ # ChromaDB database (created after ingestion)
└── Data/ # Downloaded FDA data (created after ingestion)
```

## Next Steps

1. ✅ Set up environment
2. ✅ Install dependencies
3. ✅ Set API key
4. ✅ Run ingestion
5. ✅ Start server
6. 🎉 Use the API!

Binary file added Screenshots/Flowchart.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/api-docs-endpoints.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/api-docs-schemas.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/n8n Workflow.jpeg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/ask-request.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/ask-response.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/debug-chroma-params.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/debug-chroma-response.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/schedule-request.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/schedule-response.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/validate-request.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Screenshots/testing/validate-response.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file added app/__init__.py
Empty file.
Loading