diff --git a/python/rag/healthcare-support-portal/.gitignore b/python/rag/healthcare-support-portal/.gitignore new file mode 100644 index 00000000..95f0ebca --- /dev/null +++ b/python/rag/healthcare-support-portal/.gitignore @@ -0,0 +1,270 @@ +# ======================= +# HEALTHCARE SUPPORT PORTAL +# .gitignore +# ======================= + +# Logs +logs/ +*.log +*.log.* + +# Python +__pycache__/ +*.py[cod] +*$py.class +*.so +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +# Python lib directories (but not frontend lib directories) +**/lib/ +!frontend/**/lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# Virtual Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +.venv*/ + +# uv +uv.lock +.uv/ + +# PyCharm +.idea/ + +# VS Code +.vscode/ +*.code-workspace + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# pipenv +Pipfile.lock + +# poetry +poetry.lock + +# celery +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env.local +.env.development.local +.env.test.local +.env.production.local + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# Database +*.db +*.sqlite +*.sqlite3 + +# PostgreSQL +postgresql/ +pgdata/ +data/ + +# Docker +.dockerignore +docker-compose.override.yml + +# MacOS +.DS_Store +.AppleDouble +.LSOverride + +# Windows +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db +*.stackdump +[Dd]esktop.ini +$RECYCLE.BIN/ +*.cab +*.msi +*.msix +*.msm +*.msp +*.lnk + +# Linux +*~ + +# Temporary files +*.tmp +*.temp +temp/ +tmp/ + +# Editor backups +*.bak +*.swp +*.swo +*~ + +# Process IDs +*.pid + +# Coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# IPython +profile_default/ +ipython_config.py + +# File uploads (if you implement file upload storage) +uploads/ +media/ +static/ + +# Package-specific ignores +packages/*/logs/ +packages/*/.env +packages/*/uploads/ +packages/*/temp/ + +# OpenAI cache (if any) +.openai_cache/ + +# Vector database files (if using local vector storage) +*.faiss +*.index + +# Backup files +*.backup +*.bak + +# SSL certificates (if any) +*.pem +*.key +*.crt +*.csr + +# Local configuration overrides +config.local.py +settings.local.py +local_settings.py + +# Test artifacts +.pytest_cache/ +test-results/ +test-reports/ + +# Performance profiling +*.prof + +# Memory dumps +*.dump + +# Core dumps +core.* + +# OS generated files +.directory +.fuse_hidden* +.nfs* + +# IDE and editor files +*.sublime-project +*.sublime-workspace +.vscode/settings.json +.vscode/tasks.json +.vscode/launch.json +.vscode/extensions.json +.history/ + +# Claude Code settings +.claude +CLAUDE.md + +# Node.js and Frontend +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +# Frontend build outputs +dist/ +build/ +.react-router/ + +# Frontend environment files +frontend/.env +frontend/.env.local +frontend/.env.development.local +frontend/.env.test.local +frontend/.env.production.local + +# Local environment files per package +packages/auth/.env +packages/patient/.env +packages/rag/.env + +# Generated documentation +site/ + + +# test +test_ui_fixes.md diff --git a/python/rag/healthcare-support-portal/ARCHITECTURE.md b/python/rag/healthcare-support-portal/ARCHITECTURE.md new file mode 100644 index 00000000..19f8bd2b --- /dev/null +++ b/python/rag/healthcare-support-portal/ARCHITECTURE.md @@ -0,0 +1,350 @@ +# Healthcare Support Portal Architecture + +## System Overview + +The Healthcare Support Portal is a **secure, microservices-based RAG (Retrieval-Augmented Generation) application** designed for healthcare professionals. It provides AI-powered document management, intelligent Q&A, and role-based access control for medical teams. + +## Architecture Diagram + +```mermaid +graph TB + %% User Interface Layer + subgraph "🌐 Frontend Layer (Port 3000)" + UI[React Router 7 + Vite] + Auth[Authentication Context] + API[API Client (Axios)] + UI --> Auth + UI --> API + end + + %% API Gateway / Load Balancer (Future) + subgraph "🔀 API Layer" + LB[Load Balancer
Future Enhancement] + end + + %% Microservices Layer + subgraph "🔧 Microservices Architecture" + subgraph "🔐 Auth Service (Port 8001)" + AuthAPI[FastAPI Server] + AuthDB[(User Management)] + JWT[JWT Token Management] + AuthAPI --> AuthDB + AuthAPI --> JWT + end + + subgraph "🏥 Patient Service (Port 8002)" + PatientAPI[FastAPI Server] + PatientDB[(Patient Records)] + PatientAPI --> PatientDB + end + + subgraph "🤖 RAG Service (Port 8003)" + RAGAPI[FastAPI Server] + RAGDB[(Document Store)] + OpenAI[OpenAI Integration] + Embeddings[Vector Embeddings] + RAGAPI --> RAGDB + RAGAPI --> OpenAI + RAGAPI --> Embeddings + end + end + + %% Authorization Layer + subgraph "⚖️ Authorization System (Port 8080)" + OSO[Oso Dev Server] + Policies[authorization.polar
Policy Rules] + OSO --> Policies + end + + %% Database Layer + subgraph "🗄️ Database Layer (Port 5432)" + PostgreSQL[(PostgreSQL + pgvector)] + subgraph "Database Tables" + Users[Users Table] + Patients[Patients Table] + Documents[Documents Table] + EmbeddingsTable[Embeddings Table] + end + PostgreSQL --> Users + PostgreSQL --> Patients + PostgreSQL --> Documents + PostgreSQL --> EmbeddingsTable + end + + %% Migration & DevOps + subgraph "🔄 DevOps & Migration" + Alembic[Alembic Migrations] + Docker[Docker Compose] + Scripts[Setup Scripts] + end + + %% External Services + subgraph "☁️ External Services" + OpenAIAPI[OpenAI API
GPT-4o-mini
text-embedding-3-small] + Galileo[Galileo AI
Observability Platform] + end + + %% Data Flow Connections + UI --> LB + LB --> AuthAPI + LB --> PatientAPI + LB --> RAGAPI + + %% Authorization Flow + AuthAPI --> OSO + PatientAPI --> OSO + RAGAPI --> OSO + + %% Database Connections + AuthAPI --> PostgreSQL + PatientAPI --> PostgreSQL + RAGAPI --> PostgreSQL + + %% External API Connections + RAGAPI --> OpenAIAPI + RAGAPI --> Galileo + + %% Migration Connections + Alembic --> PostgreSQL + Docker --> PostgreSQL + Docker --> OSO + + %% Styling + classDef frontend fill:#e1f5fe,stroke:#01579b,stroke-width:2px + classDef service fill:#f3e5f5,stroke:#4a148c,stroke-width:2px + classDef database fill:#e8f5e8,stroke:#1b5e20,stroke-width:2px + classDef external fill:#fff3e0,stroke:#e65100,stroke-width:2px + classDef auth fill:#fce4ec,stroke:#880e4f,stroke-width:2px + + class UI,Auth,API frontend + class AuthAPI,PatientAPI,RAGAPI service + class PostgreSQL,Users,Patients,Documents,EmbeddingsTable database + class OpenAIAPI,Galileo external + class OSO,Policies auth +``` + +## Component Details + +### 🌐 Frontend Layer (React Router 7 + Vite) +- **Technology**: React Router 7, Vite, TypeScript, TailwindCSS v4 +- **Components**: shadcn/ui components, responsive design +- **Features**: + - JWT-based authentication + - Role-based UI adaptation + - Real-time chat interface + - Document management + - Patient management + +### 🔐 Auth Service (Port 8001) +- **Purpose**: User authentication, authorization, and management +- **Key Features**: + - JWT token generation and validation + - User registration with role assignment + - Token refresh and session management + - Oso policy enforcement integration +- **Endpoints**: + - `POST /api/v1/auth/login` - User authentication + - `POST /api/v1/auth/register` - User registration + - `GET /api/v1/auth/me` - Current user info + - `GET /api/v1/users/` - List users (with authorization) + +### 🏥 Patient Service (Port 8002) +- **Purpose**: Patient record management with role-based access +- **Key Features**: + - Patient CRUD operations with authorization + - Doctor-patient assignment management + - Department-based filtering and search + - Soft delete for data preservation +- **Endpoints**: + - `GET /api/v1/patients/` - List authorized patients + - `POST /api/v1/patients/` - Create new patient + - `GET /api/v1/patients/{id}` - Get patient details + - `PUT /api/v1/patients/{id}` - Update patient + +### 🤖 RAG Service (Port 8003) +- **Purpose**: AI-powered document management and intelligent assistance +- **Key Features**: + - Document upload with automatic embedding generation + - Vector similarity search using pgvector + - Context-aware AI responses with OpenAI GPT + - Role-based AI behavior and document access +- **Endpoints**: + - `POST /api/v1/documents/` - Create/upload documents + - `POST /api/v1/chat/search` - Semantic document search + - `POST /api/v1/chat/ask` - AI-powered Q&A + - `GET /api/v1/documents/` - List authorized documents + +### ⚖️ Authorization System (Oso Dev Server - Port 8080) +- **Purpose**: Centralized policy management and enforcement +- **Key Features**: + - Role-based access control (RBAC) + - Fine-grained permissions + - Department-based access controls + - Hot-reloading during development +- **Policy Types**: + - User management policies + - Patient access policies + - Document access policies + - Embedding management policies + +### 🗄️ Database Layer (PostgreSQL + pgvector - Port 5432) +- **Technology**: PostgreSQL with pgvector extension +- **Tables**: + - **Users**: Authentication, roles, departments + - **Patients**: Medical records, doctor assignments + - **Documents**: Medical documents, policies, procedures + - **Embeddings**: Vector embeddings for semantic search +- **Features**: + - Vector similarity search + - Full-text search capabilities + - ACID compliance + - Backup and recovery + +## Data Flow Architecture + +```mermaid +sequenceDiagram + participant U as User (Frontend) + participant A as Auth Service + participant P as Patient Service + participant R as RAG Service + participant O as Oso Server + participant D as Database + participant AI as OpenAI API + + %% Authentication Flow + U->>A: Login Request + A->>D: Validate Credentials + D-->>A: User Data + A->>O: Check Permissions + O-->>A: Authorization Result + A-->>U: JWT Token + + %% Document Upload Flow + U->>R: Upload Document + R->>O: Check Document Permissions + O-->>R: Authorization Result + R->>D: Store Document + R->>AI: Generate Embeddings + AI-->>R: Vector Embeddings + R->>D: Store Embeddings + R-->>U: Upload Success + + %% RAG Query Flow + U->>R: Ask Question + R->>O: Check Query Permissions + O-->>R: Authorization Result + R->>AI: Generate Query Embedding + AI-->>R: Query Vector + R->>D: Vector Similarity Search + D-->>R: Relevant Documents + R->>AI: Generate AI Response + AI-->>R: Contextual Answer + R-->>U: AI Response + Sources + + %% Patient Management Flow + U->>P: Patient CRUD Request + P->>O: Check Patient Permissions + O-->>P: Authorization Result + P->>D: Patient Operations + D-->>P: Patient Data + P-->>U: Patient Response +``` + +## Security Architecture + +### 🔒 Authentication & Authorization +- **JWT-based authentication** with secure token management +- **Role-based access control** (Doctor, Nurse, Admin) using Oso policies +- **Fine-grained permissions** at the database level with SQLAlchemy integration +- **Department-based access controls** for multi-tenant healthcare environments + +### 🛡️ Security Features +- **API Key Security**: OpenAI keys stored in environment variables +- **Content Filtering**: Sensitive document access controls +- **Audit Trail**: Document creation and access logging +- **Input Validation**: Sanitization of user inputs +- **Rate Limiting**: Protection against API abuse + +## Technology Stack + +### Backend Services +- **Framework**: FastAPI (Python 3.11+) +- **Database**: PostgreSQL with pgvector extension +- **Authentication**: JWT tokens with Oso authorization +- **AI/ML**: OpenAI GPT-4o-mini and text-embedding-3-small +- **Observability**: Galileo AI platform +- **Package Management**: uv (fast Python dependency management) + +### Frontend +- **Framework**: React Router 7 (Framework mode) +- **Build Tool**: Vite 6 +- **Styling**: TailwindCSS v4 (zero-config) +- **UI Components**: shadcn/ui with Radix UI primitives +- **State Management**: React Context + TanStack Query +- **HTTP Client**: Axios with interceptors + +### DevOps & Infrastructure +- **Containerization**: Docker Compose +- **Database Migrations**: Alembic +- **Authorization**: Oso Dev Server (development) / Oso Cloud (production) +- **Monitoring**: Galileo AI observability platform + +## Deployment Architecture + +### Development Environment +- All services run locally with Docker Compose +- Oso Dev Server for policy management +- Local PostgreSQL with pgvector +- Hot-reloading for development + +### Production Environment +- Containerized microservices +- Oso Cloud for authorization +- Production PostgreSQL cluster +- Load balancer for high availability +- Monitoring and logging infrastructure + +## Scalability Considerations + +### Horizontal Scaling +- **Stateless Services**: All microservices are stateless and can be scaled horizontally +- **Database Sharding**: Patient data can be sharded by department +- **Vector Search**: pgvector supports distributed vector operations +- **Caching**: Redis can be added for session and query caching + +### Performance Optimization +- **Connection Pooling**: SQLAlchemy connection pooling +- **Async Operations**: FastAPI async/await for I/O operations +- **Vector Indexing**: pgvector HNSW indexes for fast similarity search +- **CDN**: Static assets served via CDN + +## Monitoring & Observability + +### Application Monitoring +- **Galileo AI**: AI performance monitoring and cost tracking +- **Structured Logging**: JSON logs for all services +- **Health Checks**: Service health endpoints +- **Metrics**: Request/response times, error rates + +### Security Monitoring +- **Audit Logs**: All authorization decisions logged +- **Access Patterns**: User access pattern analysis +- **Anomaly Detection**: Unusual access pattern alerts +- **Compliance**: HIPAA-compliant logging and monitoring + +## Future Enhancements + +### Planned Features +- **API Gateway**: Centralized routing and rate limiting +- **Caching Layer**: Redis for improved performance +- **Message Queue**: Asynchronous document processing +- **Multi-tenancy**: Hospital-level data isolation +- **Mobile App**: React Native mobile application +- **Advanced Analytics**: Usage analytics and insights + +### Integration Opportunities +- **EHR Systems**: Integration with existing Electronic Health Records +- **Medical Devices**: IoT device data integration +- **Telemedicine**: Video consultation integration +- **Compliance**: Enhanced HIPAA and SOC2 compliance features diff --git a/python/rag/healthcare-support-portal/Dockerfile.migrate b/python/rag/healthcare-support-portal/Dockerfile.migrate new file mode 100644 index 00000000..b7f82ca1 --- /dev/null +++ b/python/rag/healthcare-support-portal/Dockerfile.migrate @@ -0,0 +1,35 @@ +# Dockerfile.migrate - Migration runner container using uv +FROM python:3.11-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y \ + postgresql-client \ + gcc \ + python3-dev \ + libpq-dev \ + && rm -rf /var/lib/apt/lists/* + +# Install uv for faster Python package management +RUN pip install uv + +# Set working directory +WORKDIR /app + +# Copy the workspace files +COPY pyproject.toml uv.lock ./ +COPY packages/ ./packages/ + +# Install dependencies using uv (now works without oso package!) +RUN uv sync --frozen + +# Copy migration scripts +COPY scripts/ ./scripts/ + +# Make scripts executable +RUN chmod +x scripts/migrate.sh + +# Set PYTHONPATH to include common package +ENV PYTHONPATH=/app/packages/common/src:$PYTHONPATH + +# Default command +CMD ["/app/scripts/migrate.sh"] \ No newline at end of file diff --git a/python/rag/healthcare-support-portal/LICENSE b/python/rag/healthcare-support-portal/LICENSE new file mode 100644 index 00000000..48fc73a5 --- /dev/null +++ b/python/rag/healthcare-support-portal/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 ItsAydrian, LLC. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/python/rag/healthcare-support-portal/README.md b/python/rag/healthcare-support-portal/README.md new file mode 100644 index 00000000..0bc289a9 --- /dev/null +++ b/python/rag/healthcare-support-portal/README.md @@ -0,0 +1,1667 @@ +# 🏥 Healthcare Support Portal + +A **Secure, Efficient, and Reliable Agentic RAG Application** built with Python microservices, featuring role-based access control, vector search, and AI-powered document assistance for healthcare professionals. + +## 📋 Table of Contents + +### 🚀 Getting Started +- [🎯 What You'll Build](#-what-youll-build) +- [📋 Prerequisites](#-prerequisites) +- [⚡ Quick Setup (15 min)](#-quick-setup) +- [🔍 Validation & Testing](#-validation--testing) + +### 🏥 For Healthcare Organizations +- [🏥 Healthcare Team Guide](#-healthcare-team-guide) +- [🔐 Security & Compliance](#-security--compliance) +- [👥 Team Onboarding](#-team-onboarding) + +### 💻 Technical Documentation +- [🧠 RAG System Guide](#-rag-system-guide) +- [🏗️ Architecture](#️-architecture) +- [🔧 Services](#-services) +- [📚 API Documentation](#-api-documentation) +- [🛠️ Development](#️-development) +- [🚀 Deployment](#-deployment) + +### 🆘 Support & Troubleshooting +- [🔧 Troubleshooting Guide](#-troubleshooting-guide) +- [📞 Getting Help](#-getting-help) +- [📖 Contributing](#-contributing) +- [📄 License](#-license) + +## 🎯 What You'll Build +In the next **15 minutes**, you'll deploy a complete **healthcare-grade AI knowledge management system** that transforms how medical teams access information: + +### 🏥 **Real-World Healthcare Scenarios** + +**👩‍⚕️ For Doctors:** +- *"What are the contraindications for prescribing metformin to elderly patients?"* +- **AI Response:** Searches your uploaded medical guidelines and research papers to provide evidence-based, sourced answers with specific page references. + +**👩‍⚕️ For Nurses:** +- *"Show me the step-by-step protocol for insulin administration in ICU patients"* +- **AI Response:** Retrieves department-specific procedures with safety checklists and dosage calculations. + +**👨‍💼 For Administrators:** +- *"What are our HIPAA requirements for patient data backup?"* +- **AI Response:** Cites relevant policy documents and compliance frameworks. + +### 🚀 **What Makes This Special** + +| Feature | Traditional Search | Healthcare Support Portal | +|---------|-------------------|---------------------------| +| **Accuracy** | Keyword matching | AI understands context & medical terminology | +| **Security** | Basic permissions | Role-based access (Doctor/Nurse/Admin) + audit trails | +| **Sources** | No attribution | Every answer shows exact document sources | +| **Knowledge** | Static documents | AI synthesizes information from multiple sources | +| **Compliance** | Manual tracking | Built-in HIPAA-conscious design patterns | + +### 🧠 **The RAG Revolution in Healthcare** + +**Traditional AI Problems:** +- ❌ Knowledge cutoff dates ("I don't know about 2024 guidelines") +- ❌ Hallucinations (making up medical facts) +- ❌ No source verification +- ❌ Generic responses + +**RAG Solution:** +- ✅ **Always Current:** Uses YOUR latest medical documents +- ✅ **Factual:** Only uses information from uploaded sources +- ✅ **Transparent:** Shows exactly which documents were referenced +- ✅ **Contextual:** Tailored responses based on user role and department + +### 🏗️ **Technical Foundation** + +- **🔐 Security:** [Oso](https://osohq.com) - Hospital-grade authorization with role isolation +- **🧠 AI/RAG:** [OpenAI](https://openai.com) - Medical-grade embeddings and reasoning +- **📊 Observability:** [Galileo](https://galileo.ai) - AI performance monitoring and compliance tracking +- **🗄️ Database:** PostgreSQL + [pgvector](https://github.com/pgvector/pgvector) - database with semantic search +- **🐍 Backend:** [FastAPI](https://fastapi.tiangolo.com) microservices - Production-ready with automatic API docs +- **📦 Package Management:** [uv](https://github.com/astral-sh/uv) - Fast, reliable Python dependency management + +## 📋 Prerequisites + + +### 🔧 **System Requirements** + +| Component | Minimum | Recommended | Purpose | +|-----------|---------|-------------|----------| +| **Python** | 3.11+ | 3.12+ | Backend services & AI processing | +| **Node.js** | 20.19.0+ | 22.0+ | React frontend application | +| **Docker** | 20.0+ | Latest | PostgreSQL + microservices | + +🔗 **Get your keys:** +- **OpenAI:** [platform.openai.com/api-keys](https://platform.openai.com/api-keys) +- **Galileo:** [app.galileo.ai/sign-up](https://app.galileo.ai/sign-up) + +> **Windows Users:** Use Git Bash or WSL to run bash scripts, or use `bash setup.sh` instead of `./setup.sh` + +### 🔍 **Environment Validation** + +**Step 1: Check Dependencies** +```bash +# Run the validation script +./validate_environment.sh +``` + +**Expected Output:** +```bash +✅ Python 3.11.9 OK +✅ Node.js v20.19.0 OK +✅ Docker 24.0.7 OK +✅ Git 2.40.0 OK +✅ Port 3000 available +✅ Port 8001 available +✅ Port 8002 available +✅ Port 8003 available +✅ Port 5432 available +🎉 Environment validation complete! +``` + +> ⚠️ **Troubleshooting:** If any checks fail, see our [Environment Setup Guide](#-environment-setup-troubleshooting) below. + +--- + +## ⚡ Quick Setup (15 min) + + +### **Step 1: Download & Install** ⏱️ *3 minutes* + +```bash +# 1. Clone the repository +git clone https://github.com/rungalileo/sdk-examples.git +cd sdk-examples/python/rag/healthcare-support-portal + +# 2. Run automated setup +./setup.sh + +# Windows users (if needed): +# bash setup.sh +``` + +**🔍 Validation:** You should see: +```bash +✅ Python dependencies synced +✅ Created packages/auth/.env from example +✅ Created packages/patient/.env from example +✅ Created packages/rag/.env from example +✅ Updated SECRET_KEY in packages/auth/.env +✅ Frontend dependencies installed successfully +✅ Setup complete! +``` + +### **Step 2: Configure API Keys** ⏱️ *2 minutes* + +**🎨 Critical:** The RAG system requires your OpenAI API key to function. + +```bash +# Open the RAG service configuration +nano packages/rag/.env +# Or use your preferred editor: code packages/rag/.env +``` + +**Find this line:** +```env +OPENAI_API_KEY=sk-your-openai-api-key-here +``` + +**Replace with your actual key:** +```env +OPENAI_API_KEY=sk-abcd1234your-real-key-here +``` + +**🔍 Validation:** Test your API key: +```bash +# Quick API key test +cd packages/rag +uv run python -c "from dotenv import load_dotenv; load_dotenv(); import os; print('✅ API key configured' if os.getenv('OPENAI_API_KEY', '').startswith('sk-') else '❌ Invalid API key format')" +``` + +**Add Galileo for AI observability and monitoring:** +1. Get your Galileo API key from [app.galileo.ai](https://app.galileo.ai) +2. Add to `packages/rag/.env`: `GALILEO_API_KEY=your-galileo-key` +3. Test: `uv run python test_config.py` + +At this point, if you've exactly followed the step by steps in the repository, everything should be active except for the Database connection. The Database connection will be configured through the next step. + + +### **Step 3: Launch All Services** ⏱️ *5 minutes* + +```bash +# Start database, backend services, and frontend +./run_all.sh + +# Windows: bash run_all.sh +``` + +**🔍 Watch for Success Indicators:** +```bash +✅ PostgreSQL Database (Port 5432) +✅ Oso Dev Server (Port 8080) +✅ Auth Service (Port 8001) +✅ Patient Service (Port 8002) +✅ RAG Service (Port 8003) +✅ Frontend Service (Port 3000) + +🌐 Frontend: http://localhost:3000 +``` + +📋 **What's running:** +- 🌐 **Web App**: http://localhost:3000 (main interface) +- 🤖 **RAG API**: http://localhost:8003/docs (upload docs, ask questions) +- 🔐 **Auth API**: http://localhost:8001/docs (user management) +- 🏥 **Patient API**: http://localhost:8002/docs (patient records) +- 🗄️ **Database**: PostgreSQL with vector search +- ⚖️ **Security**: Oso authorization server + +--- + +## 🎉 **You're Ready!** - Try Your RAG System + +### 👥 **Step 4a: Get Demo Users** (Optional) + +```bash +# Health check for all services +echo "🔍 Running system health check..." + +# Check if all services are responding +echo "Testing Auth Service..." +curl -s http://localhost:8001/health && echo "✅ Auth Service OK" || echo "❌ Auth Service DOWN" + +echo "Testing Patient Service..." +curl -s http://localhost:8002/health && echo "✅ Patient Service OK" || echo "❌ Patient Service DOWN" + +echo "Testing RAG Service..." +curl -s http://localhost:8003/health && echo "✅ RAG Service OK" || echo "❌ RAG Service DOWN" + +echo "Testing Frontend..." +curl -s http://localhost:3000 > /dev/null && echo "✅ Frontend OK" || echo "❌ Frontend DOWN" + +echo "Testing Database..." +docker exec healthcare-support-portal-db-1 pg_isready && echo "✅ Database OK" || echo "❌ Database DOWN" + +echo "🎉 Health check complete!" +``` + +### **Step 5: Create Demo Users & Test RAG** ⏱️ *5 minutes* + +**5a. Setup Demo Data:** +```bash +# Create sample users and data +uv run python -m common.seed_data +``` + +**🔍 Expected Output:** +```bash +✅ Created demo users: + - Doctor: dr_smith / secure_password + - Nurse: nurse_johnson / secure_password + - Admin: admin_wilson / secure_password +✅ Sample patients created +✅ Demo data seeding complete +``` + +**5b. Test the Web Interface:** +1. 🌐 Open **http://localhost:3000** +2. 🔑 Login with: `dr_smith` / `secure_password` +3. 📄 Upload a PDF document (medical guideline, research paper, etc.) +4. 🤖 Ask a question: *"What are the key recommendations in this document?"* +5. ✅ Verify you get an AI response with document sources! + +**5c. Test RAG API (Advanced):** +```bash +# Get authentication token +TOKEN=$(curl -s -X POST "http://localhost:8001/api/v1/auth/login" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "username=dr_smith&password=secure_password" | \ + python3 -c "import sys, json; print(json.load(sys.stdin)['access_token'])") + +echo "Got auth token: ${TOKEN:0:20}..." + +# Test document upload +echo "Testing document upload..." +curl -X POST "http://localhost:8003/api/v1/documents/upload" \ + -H "Authorization: Bearer $TOKEN" \ + -F "file=@README.md" \ + -F "title=Test Document" && echo "✅ Upload successful" + +# Test RAG query +echo "Testing RAG question-answering..." +curl -X POST "http://localhost:8003/api/v1/chat/ask" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"message": "What is this application about?"}' && echo "✅ RAG response received" +``` + +### 🎉 **Success! Your Healthcare RAG System is Running** + +**🌐 Access Points:** +- **Main Application:** http://localhost:3000 +- **Auth API Docs:** http://localhost:8001/docs +- **Patient API Docs:** http://localhost:8002/docs +- **RAG API Docs:** http://localhost:8003/docs +- **Oso Authorization:** http://localhost:8080 + +**👥 Demo Accounts:** +| Role | Username | Password | Department | Permissions | +|------|----------|----------|------------|-------------| +| Doctor | `dr_smith` | `secure_password` | Cardiology | Full access to cardiology docs | +| Nurse | `nurse_johnson` | `secure_password` | Emergency | Access to procedures & protocols | +| Admin | `admin_wilson` | `secure_password` | Administration | System-wide access | + +**🛑 To Stop Services:** +```bash +./stop_all.sh +``` + +**➡️ What's Next?** +- [🏥 Healthcare Team Guide](#-healthcare-team-guide) - Role-specific usage patterns +- [🔧 Troubleshooting Guide](#-troubleshooting-guide) - Common issues & solutions +- [🔐 Security & Compliance](#-security--compliance) - HIPAA considerations +- [🛠️ Development Guide](#-development) - Customize and extend + +--- + +--- + +## 🔧 Troubleshooting Guide + +
+🚑 Quick Fixes for Common Issues + +### 📝 **Decision Tree: What's Wrong?** + +``` +🚨 Having issues? Follow this decision tree: + +🔍 Is the system not starting? +├── ❌ Ports in use? → Run `./stop_all.sh` then `./run_all.sh` +├── ❌ Docker not running? → Start Docker Desktop +├── ❌ "uv not found"? → Install uv: `curl -LsSf https://astral.sh/uv/install.sh | sh` +└── ❌ Dependencies missing? → Run `./setup.sh` again + +🔍 Services start but RAG doesn't work? +├── ❌ "OpenAI API error"? → Check API key in `packages/rag/.env` +├── ❌ "Invalid API key"? → Ensure key starts with `sk-` +└── ❌ "Galileo span error"? → See Galileo troubleshooting below + +🔍 Frontend not loading? +├── ❌ Node.js version? → Upgrade to 20.19.0+ from nodejs.org +└── ❌ Dependencies? → Run `cd frontend && npm install` +``` + +
+ +### 📝 **Environment Setup Troubleshooting** + +
+Python, Node.js, Docker Issues + +**🐍 Python Issues:** +```bash +# Check Python version +python3 --version + +# If Python < 3.11, install newer version: +# macOS: brew install python@3.12 +# Ubuntu: sudo apt install python3.12 +# Windows: Download from python.org + +# Verify uv installation +which uv || curl -LsSf https://astral.sh/uv/install.sh | sh + +# Reload shell after uv install +source ~/.bashrc # or ~/.zshrc +``` + +**💻 Node.js Issues:** +```bash +# Check Node version +node --version + +# If version < 20.19.0: +# Install Node Version Manager (nvm) +curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash +source ~/.bashrc + +# Install and use Node 20+ +nvm install 20 +nvm use 20 + +# Verify npm is working +npm --version +``` + +**🐳 Docker Issues:** +```bash +# Check if Docker is running +docker ps + +# Start Docker (varies by OS) +# macOS: Open Docker Desktop +# Linux: sudo systemctl start docker +# Windows: Start Docker Desktop + +# Test Docker +docker run hello-world +``` + +
+ +### 🔑 **API Key & Configuration Issues** + +
+OpenAI, Galileo, Environment Variables + +**🤖 OpenAI API Key Problems:** +```bash +# Check if API key is set +grep "OPENAI_API_KEY" packages/rag/.env + +# Key should look like: OPENAI_API_KEY=sk-abcd1234... +# If missing 'sk-' prefix, it's invalid + +# Test API key manually +export OPENAI_API_KEY="your-key-here" +curl -H "Authorization: Bearer $OPENAI_API_KEY" \ + https://api.openai.com/v1/models | head -20 + +# Should return JSON with model list, not error +``` + +**📊 Galileo "Span Error" Fix:** +```bash +# The "add_workflow_span: A trace needs to be created" error is non-fatal +# It means Galileo monitoring is enabled but not properly initialized + +# Option 1: Disable Galileo (simplest) +echo "GALILEO_ENABLED=false" >> packages/rag/.env + +# Option 2: Fix Galileo setup +echo "GALILEO_API_KEY=your-galileo-key" >> packages/rag/.env +echo "GALILEO_PROJECT_NAME=healthcare-rag" >> packages/rag/.env + +# Option 3: Test Galileo connection +cd packages/rag +uv run python test_config.py +``` + +**🔒 Environment Variable Debug:** +```bash +# Check all .env files exist +ls -la packages/*/.env + +# View environment variables (without exposing keys) +echo "Checking environment configuration..." +for service in auth patient rag; do + echo "=== $service service ===" + grep -v "API_KEY\|SECRET" packages/$service/.env || echo "No .env file" +done + +# Generate new SECRET_KEY if needed +python3 -c "import secrets; print('SECRET_KEY=' + secrets.token_urlsafe(32))" +``` + +
+ +### 🛠️ **Service & Port Issues** + +
+Services Won't Start, Port Conflicts + +**📋 Port Conflict Resolution:** +```bash +# Find what's using required ports +echo "Checking port usage..." +for port in 3000 8001 8002 8003 5432 8080; do + process=$(lsof -ti:$port 2>/dev/null) + if [ -n "$process" ]; then + echo "⚠️ Port $port used by PID $process:" + ps -p $process -o pid,ppid,cmd + else + echo "✅ Port $port available" + fi +done + +# Kill processes on our ports (be careful!) +echo "Kill conflicting processes? (y/N)" +read answer +if [ "$answer" = "y" ]; then + for port in 3000 8001 8002 8003; do + lsof -ti:$port | xargs kill -9 2>/dev/null || true + done +fi +``` + +**📊 Service Health Debugging:** +```bash +# Check individual service logs +echo "Recent service logs:" +echo "=== RAG Service ===" +tail -20 logs/rag.log + +echo "=== Auth Service ===" +tail -20 logs/auth.log + +echo "=== Frontend ===" +tail -20 logs/frontend.log + +# Test services individually +echo "Testing service endpoints:" +curl -s http://localhost:8001/docs > /dev/null && echo "✅ Auth API responding" || echo "❌ Auth API down" +curl -s http://localhost:8003/docs > /dev/null && echo "✅ RAG API responding" || echo "❌ RAG API down" +``` + +**🗄️ Database Issues:** +```bash +# Check if PostgreSQL is running +docker ps | grep postgres + +# Check database logs +docker logs healthcare-support-portal-db-1 + +# Test database connection +docker exec healthcare-support-portal-db-1 \ + psql -U postgres -d healthcare -c "\\dt" 2>/dev/null && \ + echo "✅ Database tables exist" || echo "❌ Database connection failed" + +# Reset database (nuclear option) +echo "Reset database? This will delete all data! (y/N)" +read answer +if [ "$answer" = "y" ]; then + docker-compose down + docker volume rm healthcare-support-portal_postgres_data 2>/dev/null || true + docker-compose up -d db + sleep 5 + docker-compose run --rm migrate +fi +``` + +
+ +### 🧠 **RAG System Issues** + +
+Document Upload, Embeddings, AI Responses + +**📄 Document Upload Problems:** +```bash +# Test document upload with curl +TOKEN="your-jwt-token-here" + +# Upload test document +echo "Testing document upload..." +response=$(curl -s -w "%{http_code}" -X POST "http://localhost:8003/api/v1/documents/upload" \ + -H "Authorization: Bearer $TOKEN" \ + -F "file=@README.md" \ + -F "title=Test Document") + +echo "Upload response: $response" + +# Check upload status +curl -s "http://localhost:8003/api/v1/documents/" \ + -H "Authorization: Bearer $TOKEN" | \ + python3 -c "import sys,json; print(f'Documents: {len(json.load(sys.stdin))}')" +``` + +**🤖 AI Response Issues:** +```bash +# Test RAG question directly +TOKEN="your-jwt-token-here" + +# Simple test query +echo "Testing RAG query..." +curl -X POST "http://localhost:8003/api/v1/chat/ask" \ + -H "Authorization: Bearer $TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"message": "Hello, are you working?"}' + +# Check embedding generation +echo "Checking embedding status..." +curl -s "http://localhost:8003/api/v1/documents/" \ + -H "Authorization: Bearer $TOKEN" | \ + python3 -c " +import sys,json +data = json.load(sys.stdin) +for doc in data: + status = 'embedded' if doc.get('embedding_id') else 'no embedding' + print(f'{doc[\"title\"]}: {status}') +" +``` + +**📈 Performance Issues:** +```bash +# Check system resources +echo "System resources:" +echo "RAM usage: $(free -h | grep Mem | awk '{print $3"/"$2}')" +echo "Disk usage: $(df -h . | tail -1 | awk '{print $3"/"$2" ("$5" used)"}')" + +# Check Docker resources +echo "Docker stats:" +docker stats --no-stream + +# Monitor RAG service performance +echo "Monitoring RAG API response times..." +for i in {1..5}; do + start=$(date +%s.%N) + curl -s "http://localhost:8003/health" > /dev/null + end=$(date +%s.%N) + echo "Response $i: $(echo "$end - $start" | bc -l)s" + sleep 1 +done +``` + +
+ +### 🎨 **Complete System Reset** + +
+Nuclear Option: Fresh Start + +```bash +#!/bin/bash +echo "🚨 COMPLETE SYSTEM RESET - This will delete all data!" +echo "Continue? (type 'RESET' to confirm)" +read confirm + +if [ "$confirm" = "RESET" ]; then + echo "Stopping all services..." + ./stop_all.sh + + echo "Removing containers and volumes..." + docker-compose down --volumes --remove-orphans + + echo "Cleaning up logs and data..." + rm -rf logs/* + rm -rf data/postgres/* + + echo "Removing environment files..." + rm -f packages/*/.env + + echo "Cleaning Python environment..." + rm -rf .venv + + echo "Cleaning Node modules..." + rm -rf frontend/node_modules + + echo "Starting fresh setup..." + ./setup.sh + + echo "✅ Fresh installation complete!" + echo "Don't forget to add your OpenAI API key to packages/rag/.env" +else + echo "Reset cancelled." +fi +``` + +**Save this as `reset.sh`, make executable with `chmod +x reset.sh`, then run `./reset.sh`** + +
+ +### 📞 Getting Help + +**🔍 Before Asking for Help, Collect This Info:** +```bash +# Run this diagnostic script +echo "=== Healthcare RAG System Diagnostics ===" +echo "OS: $(uname -s) $(uname -r)" +echo "Python: $(python3 --version)" +echo "Node: $(node --version 2>/dev/null || echo 'Not installed')" +echo "Docker: $(docker --version 2>/dev/null || echo 'Not installed')" +echo "uv: $(uv --version 2>/dev/null || echo 'Not installed')" +echo "" +echo "Port Status:" +for port in 3000 8001 8002 8003 5432; do + lsof -i :$port > /dev/null 2>&1 && echo "Port $port: IN USE" || echo "Port $port: Available" +done +echo "" +echo "Service Status:" +docker ps --format "table {{.Names}}\t{{.Status}}" +echo "" +echo "Environment Files:" +ls -la packages/*/.env 2>/dev/null || echo "No .env files found" +echo "" +echo "Recent Errors (last 10 lines from each log):" +for log in logs/*.log; do + if [ -f "$log" ]; then + echo "=== $(basename $log) ===" + tail -10 "$log" | grep -i error || echo "No recent errors" + fi +done +``` + +**🔗 Community Support:** +- **GitHub Issues:** [sdk-examples/issues](https://github.com/rungalileo/sdk-examples/issues) +- **Galileo Documentation:** [Galileo Docs](https://v2docs.galileo.ai) +- **Oso Support:** [Oso Documentation](https://docs.osohq.com) + + +--- + +## Example use cases + +### 👩‍⚕️ **For Medical Professionals** + +**🎯 Why This Matters for Healthcare:** +- **🚑 Emergency Response:** Get instant access to protocols during critical situations +- **📊 Evidence-Based Care:** AI responses include source citations for clinical decisions +- **🗺️ Department Isolation:** Only see documents relevant to your specialty +- **📋 Compliance Ready:** Built-in audit trails and access controls + +#### **👨‍⚕️ Doctor Workflow** +1. **Upload Clinical Guidelines:** + - Latest treatment protocols + - Research papers and meta-analyses + - Drug interaction databases + - Departmental procedures + +2. **Ask Clinical Questions:** + - *"What are the contraindications for ACE inhibitors in elderly patients?"* + - *"Show me the latest guidelines for diabetes management"* + - *"What's the recommended antibiotic for pneumonia in immunocompromised patients?"* + +3. **Get Sourced Answers:** + - AI provides evidence-based responses + - Shows exact page/section references + - Highlights key recommendations + - Flags any conflicting information + +#### **👩‍⚕️ Nurse Workflow** +1. **Upload Procedure Documents:** + - Nursing protocols and checklists + - Medication administration guides + - Patient care standards + - Safety procedures + +2. **Quick Procedure Lookup:** + - *"How do I properly administer insulin via IV?"* + - *"What's the protocol for fall risk assessment?"* + - *"Show me the steps for wound care documentation"* + +3. **Safety-First Responses:** + - Step-by-step procedures with safety checkpoints + - Dosage calculations and double-check requirements + - Patient monitoring guidelines + +#### **👨‍💼 Administrator Workflow** +1. **Upload Policy Documents:** + - HIPAA compliance guides + - Organizational policies + - Quality assurance standards + - Regulatory requirements + +2. **Policy & Compliance Questions:** + - *"What are our data retention requirements?"* + - *"Show me the incident reporting procedure"* + - *"What's required for Joint Commission compliance?"* + +#### **🔒 Security Best Practices** + +**🔑 API Key Management:** +```bash +# Store API keys securely (never in code) +export ***************"your-key-here" +export GALILEO_API_KEY="your-galileo-key" + +# Use environment-specific keys +# Development: test keys with limited permissions +# Production: full keys with monitoring +``` + +**🏥 Department Access Control:** +```python +# Example: Only cardiology staff can access cardiology documents +# This is handled automatically by the Oso authorization system + +# In authorization.polar: +allow(user: User, "read", document: Document) if + user.department = document.department; +``` + +**📊 Audit & Monitoring:** +- All document access is logged with user, timestamp, and document +- AI queries are tracked for compliance and quality review +- Galileo provides AI performance monitoring and cost tracking +- Failed authorization attempts are logged for security review + +# + +## 🧠 RAG System Guide + +### 🎯 What Your RAG System Can Do + +Your RAG application provides **intelligent document management and AI-powered assistance**: + +#### 🔍 **Intelligent Document Search** +- **Semantic search**: Find documents even without exact keywords +- **Department filtering**: Search within specific departments +- **Document type filtering**: Filter by guidelines, research, procedures +- **Similarity scoring**: Configurable relevance thresholds + +#### 🤖 **AI-Powered Q&A** +- **Context-aware responses**: Uses relevant documents to inform answers +- **Role-based responses**: Tailored for doctors, nurses, administrators +- **Source attribution**: Shows which documents were used +- **Fallback handling**: Graceful responses when no context is found + +#### 🔐 **Enterprise Security** +- **JWT authentication**: Secure user sessions +- **Oso authorization**: Fine-grained access control +- **Department isolation**: Users only see their department's documents +- **Audit trails**: Track all document access and modifications + +### 🏗️ How RAG Works + +``` +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ User Query │───▶│ Vector Search │───▶│ AI Generation │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ + │ │ + ▼ ▼ + ┌─────────────────┐ ┌─────────────────┐ + │ Document Store │ │ Context-Aware │ + │ (pgvector) │ │ Response │ + └─────────────────┘ └─────────────────┘ +``` + +#### **Step 1: Document Processing** +``` +Upload Document → Text Extraction → Chunking → Embedding Generation → Vector Storage +``` + +#### **Step 2: Query Processing** +``` +User Question → Query Embedding → Similarity Search → Context Retrieval +``` + +#### **Step 3: Response Generation** +``` +Retrieved Context + User Role + Question → OpenAI GPT → Contextual Response +``` + +### 🎯 Real-World Use Cases + +#### **🏥 For Doctors** +- **Query**: "What are the contraindications for prescribing metformin?" +- **RAG Response**: Uses latest medical guidelines and research papers to provide evidence-based information. + +#### **👩‍⚕️ For Nurses** +- **Query**: "How do I properly administer insulin to a patient?" +- **RAG Response**: Uses nursing procedures and safety guidelines for step-by-step instructions. + +#### **👨‍💼 For Administrators** +- **Query**: "What are the HIPAA compliance requirements for patient data?" +- **RAG Response**: Uses policy documents and compliance guidelines. + +### 📚 RAG Documentation + +- **🚀 [Quick Start Guide](packages/rag/QUICK_START.md)**: Get up and running in 5 minutes +- **📖 [Complete User Guide](packages/rag/RAG_GUIDE.md)**: Comprehensive usage instructions +- **🚀 [Enhancement Ideas](packages/rag/ENHANCEMENTS.md)**: Advanced features and improvements +- **📖 [RAG Summary](packages/rag/SUMMARY.md)**: Overview of capabilities + +## 🏗️ Architecture + +``` +Healthcare Support Portal +├── 📦 packages/ # Python workspace packages +│ ├── 🔐 auth/ (Port 8001) +│ │ ├── User authentication & JWT tokens +│ │ ├── User management & roles +│ │ └── Authorization policy enforcement +│ │ +│ ├── 🏥 patient/ (Port 8002) +│ │ ├── Patient CRUD operations +│ │ ├── Doctor-patient assignments +│ │ └── Department-based filtering +│ │ +│ ├── 🤖 rag/ (Port 8003) +│ │ ├── Document management & embeddings +│ │ ├── Vector similarity search +│ │ ├── AI-powered Q&A with context +│ │ └── File upload & processing +│ │ +│ └── 📚 common/ +│ ├── Shared models & database schema +│ ├── Authentication utilities +│ └── Pydantic schemas +│ +├── 🌐 frontend/ (Port 3000) +│ └── React Router 7 + Vite web application +│ +├── 🗄️ PostgreSQL + pgvector (Port 5432) +│ ├── User, Patient, Document tables +│ ├── Vector embeddings storage +│ └── Alembic migration tracking +│ +├── 🔄 Migration Service (Docker) +│ ├── Alembic-based schema migrations +│ ├── Database health checks & retry logic +│ └── Automatic pgvector extension setup +│ +├── ⚖️ Oso Dev Server (Port 8080) +│ ├── Centralized policy management +│ ├── Hot-reloading during development +│ └── Authorization policy enforcement +│ +└── authorization.polar # Oso authorization policies +``` + +## 🔧 Services + +### 🔐 Auth Service (Port 8001) +**Purpose:** User authentication, authorization, and management + +**Key Features:** +- JWT token generation and validation +- User registration with role assignment +- Token refresh and session management +- Oso policy enforcement for user access + +**Endpoints:** +- `POST /api/v1/auth/login` - User authentication +- `POST /api/v1/auth/register` - User registration +- `GET /api/v1/auth/me` - Current user info +- `GET /api/v1/users/` - List users (with authorization) + +[📖 Detailed Documentation](packages/auth/README.md) + +### 🏥 Patient Service (Port 8002) +**Purpose:** Patient record management with role-based access + +**Key Features:** +- Patient CRUD operations with authorization +- Doctor-patient assignment management +- Department-based filtering and search +- Soft delete for data preservation + +**Endpoints:** +- `GET /api/v1/patients/` - List authorized patients +- `POST /api/v1/patients/` - Create new patient +- `GET /api/v1/patients/{id}` - Get patient details +- `PUT /api/v1/patients/{id}` - Update patient + +[📖 Detailed Documentation](packages/patient/README.md) + +### 🤖 RAG Service (Port 8003) +**Purpose:** AI-powered document management and intelligent assistance + +**Key Features:** +- Document upload with automatic embedding generation +- Vector similarity search using pgvector +- Context-aware AI responses with OpenAI GPT +- Role-based AI behavior and document access + +**Endpoints:** +- `POST /api/v1/documents/` - Create/upload documents +- `POST /api/v1/chat/search` - Semantic document search +- `POST /api/v1/chat/ask` - AI-powered Q&A +- `GET /api/v1/documents/` - List authorized documents + +[📖 Detailed Documentation](packages/rag/README.md) + +### 🌐 Frontend Application (Port 3000) +**Purpose:** Modern web interface for healthcare professionals + +**Key Features:** +- React Router 7 with Vite for fast development +- shadcn/ui components for consistent design +- TailwindCSS v4 for styling +- Real-time updates and responsive design +- Role-based UI components + +**Technology Stack:** +- React Router 7 (Framework mode) +- Vite (Build tool) +- TypeScript +- TailwindCSS v4 (zero-config) +- shadcn/ui components + +## 📚 API Documentation + +Each service provides interactive API documentation: + +| Service | Swagger UI | ReDoc | +|---------|------------|-------| +| Auth Service | http://localhost:8001/docs | http://localhost:8001/redoc | +| Patient Service | http://localhost:8002/docs | http://localhost:8002/redoc | +| RAG Service | http://localhost:8003/docs | http://localhost:8003/redoc | + +## 🔐 Security + +### 🔒 Authentication & Authorization +- **JWT-based authentication** with secure token management +- **Role-based access control** (Doctor, Nurse, Admin) using Oso policies +- **Fine-grained permissions** at the database level with SQLAlchemy integration +- **Department-based access controls** for multi-tenant healthcare environments + +### 🛡️ Security Features +- **API Key Security:** OpenAI keys stored in environment variables +- **Content Filtering:** Sensitive document access controls +- **Audit Trail:** Document creation and access logging +- **Input Validation:** Sanitization of user inputs +- **Rate Limiting:** Protection against API abuse + +## 📊 Usage Examples + +### 1. Register and Authenticate + +```bash +# Register a new doctor +curl -X POST "http://localhost:8001/api/v1/auth/register" \ + -H "Content-Type: application/json" \ + -d '{ + "username": "dr_smith", + "email": "sarah.smith@hospital.com", + "password": "secure_password", + "role": "doctor", + "department": "cardiology" + }' + +# Login to get JWT token +curl -X POST "http://localhost:8001/api/v1/auth/login" \ + -H "Content-Type: application/x-www-form-urlencoded" \ + -d "username=dr_smith&password=secure_password" +``` + +### 2. Upload Medical Documents + +```bash +# Upload a medical guideline document +curl -X POST "http://localhost:8003/api/v1/documents/upload" \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" \ + -F "file=@diabetes_guidelines.pdf" \ + -F "title=Diabetes Treatment Guidelines 2024" \ + -F "document_type=guidelines" \ + -F "department=endocrinology" +``` + +### 3. Search Documents + +```bash +# Search for relevant documents +curl -X POST "http://localhost:8003/api/v1/chat/search" \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "query": "metformin contraindications", + "document_types": ["guidelines"], + "department": "endocrinology" + }' +``` + +### 4. Ask AI Questions + +```bash +# Ask an AI-powered question +curl -X POST "http://localhost:8003/api/v1/chat/ask" \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "message": "What are the latest treatment guidelines for type 2 diabetes?", + "context_department": "endocrinology" + }' +``` + +### 5. Manage Patients + +```bash +# Create a new patient +curl -X POST "http://localhost:8002/api/v1/patients/" \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "John Doe", + "date_of_birth": "1980-01-15", + "department": "cardiology", + "assigned_doctor_id": 1 + }' +``` + +## 🛠️ Development + +### Project Structure + +``` +healthcare-support-portal/ +├── 📦 packages/ # Python microservices +│ ├── 🔐 auth/ # Authentication service +│ ├── 🏥 patient/ # Patient management service +│ ├── 🤖 rag/ # RAG (AI) service +│ └── 📚 common/ # Shared utilities +├── 🌐 frontend/ # React web application +├── 🗄️ data/ # Database data +├── 📝 logs/ # Service logs +├── 🔧 scripts/ # Utility scripts +└── 📄 Configuration files +``` + +### Development Commands + +```bash +# Install all dependencies (respects uv.lock for consistency) +uv sync + +# Install development tools +uv sync --group dev + +# Start development services +./run_all.sh + +# Run database migrations +docker-compose run --rm migrate + +# Seed demo data +uv run python -m common.seed_data + +# Run tests (when available) +uv run pytest + +# Format code +uv run ruff format . + +# Lint code +uv run ruff check . + +# Stop all services +./stop_all.sh +``` + +### Environment Configuration + +**🎯 Start with .env.example files!** Each service has its own `.env.example` file that contains all the configuration templates you need. This is the **recommended way** to set up your environment. + +Each service has its own `.env` file for configuration. Here's how to set up all environment variables: + +#### 🔐 Auth Service (packages/auth/.env) + +```env +# Auth Service Environment Variables +DEBUG=true +SECRET_KEY=change-me-in-production +DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/healthcare +ACCESS_TOKEN_EXPIRE_MINUTES=30 +OSO_URL=http://localhost:8080 +OSO_AUTH=e_0123456789_12345_osotesttoken01xiIn +``` + +#### 🏥 Patient Service (packages/patient/.env) + +```env +# Patient Service Environment Variables +DEBUG=true +SECRET_KEY=change-me-in-production +DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/healthcare +OSO_URL=http://localhost:8080 +OSO_AUTH=e_0123456789_12345_osotesttoken01xiIn +``` + +#### 🤖 RAG Service (packages/rag/.env) + +```env +# RAG Service Environment Variables +DEBUG=true +SECRET_KEY=change-me-in-production +DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/healthcare +OSO_URL=http://localhost:8080 +OSO_AUTH=e_0123456789_12345_osotesttoken01xiIn + +# OpenAI Configuration (Required for RAG functionality) +OPENAI_API_KEY=sk-your-openai-api-key-here +EMBEDDING_MODEL=text-embedding-3-small +CHAT_MODEL=gpt-4o-mini + +# RAG Configuration (Optional - has defaults) +CHUNK_SIZE=1000 +CHUNK_OVERLAP=200 +MAX_CONTEXT_LENGTH=8000 +SIMILARITY_THRESHOLD=0.7 +MAX_RESULTS=5 + +# Galileo Observability (Optional) +GALILEO_ENABLED=true +GALILEO_API_KEY=your-galileo-api-key-here +GALILEO_PROJECT_NAME=healthcare-rag +GALILEO_ENVIRONMENT=development + + +# Logging Configuration +LOG_LEVEL=INFO +LOG_FORMAT=json +``` + +#### 🌐 Frontend (frontend/.env) + +```env +# API Configuration +VITE_API_BASE_URL=http://localhost +VITE_AUTH_SERVICE_PORT=8001 +VITE_PATIENT_SERVICE_PORT=8002 +VITE_RAG_SERVICE_PORT=8003 + +# App Configuration +VITE_APP_NAME="Healthcare Support Portal" +VITE_APP_VERSION="0.1.0" + +# Development +VITE_DEBUG=true +``` + +### 🔧 Environment Variable Setup + +#### 1. Create Environment Files + +```bash +# Copy example files to create your .env files +cp packages/auth/.env.example packages/auth/.env +cp packages/patient/.env.example packages/patient/.env +cp packages/rag/.env.example packages/rag/.env +cp frontend/.env.example frontend/.env +``` + +**📋 What's in the .env.example files?** + +The `.env.example` files contain **templates** with all the necessary configuration variables and their default values. When you copy them to `.env`, you get a complete starting point with: + +- **🔑 Required variables** (like `OPENAI_API_KEY`, `SECRET_KEY`) +- **⚙️ Optional variables** with sensible defaults +- **📝 Clear comments** explaining what each variable does +- **🚀 Development-ready** configuration values + +**💡 Pro tip:** Always check the `.env.example` files first to see what configuration options are available! + +#### 2. Configure Required Variables + +**🔑 OpenAI API Key (Required for RAG)** +```bash +# Get your OpenAI API key from: https://platform.openai.com/api-keys +# Then update the RAG service .env file: +nano packages/rag/.env +# Set: OPENAI_API_KEY=sk-your-actual-api-key-here +``` + +**📖 Understanding Your .env.example Files** + +Each service has a comprehensive `.env.example` file. Here's what you'll find: + +**🔐 Auth Service (.env.example)** +```bash +# View the template +cat packages/auth/.env.example + +# Key variables: +# - SECRET_KEY: JWT signing key +# - DATABASE_URL: PostgreSQL connection string +# - ACCESS_TOKEN_EXPIRE_MINUTES: JWT expiration time +# - OSO_URL: Authorization service URL +``` + +**🏥 Patient Service (.env.example)** +```bash +# View the template +cat packages/patient/.env.example + +# Key variables: +# - SECRET_KEY: Service authentication key +# - DATABASE_URL: PostgreSQL connection string +# - OSO_URL: Authorization service URL +``` + +**🤖 RAG Service (.env.example)** +```bash +# View the template +cat packages/rag/.env.example + +# Key variables: +# - OPENAI_API_KEY: Your OpenAI API key (required) +# - EMBEDDING_MODEL: AI model for document embeddings +# - CHAT_MODEL: AI model for Q&A responses +# - GALILEO_ENABLED: Observability platform toggle +# - LOG_LEVEL: Logging verbosity +``` + +**🔐 Security Keys (Required for Production)** +```bash +# Generate secure secret keys for production +python -c "import secrets; print(secrets.token_urlsafe(32))" + +# Update all service .env files with unique secret keys: +nano packages/auth/.env +nano packages/patient/.env +nano packages/rag/.env +# Set: SECRET_KEY=your-generated-secret-key +``` + +**🔍 Quick Configuration Check** + +After copying your `.env.example` files, you can quickly see what needs to be configured: + +```bash +# Check what variables need your attention +echo "=== Checking required configuration ===" +echo "OpenAI API Key:" +grep "OPENAI_API_KEY" packages/rag/.env +echo "" +echo "Secret Keys:" +grep "SECRET_KEY" packages/*/.env +echo "" +echo "Database URLs:" +grep "DATABASE_URL" packages/*/.env + +# Look for placeholder values that need updating +echo "" +echo "=== Placeholder values to update ===" +grep -r "change-me\|your-\|sk-" packages/*/.env +``` + +**🗄️ Database Configuration** +```env +# Default development database URL (PostgreSQL with pgvector) +DATABASE_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/healthcare + +# For production, use your actual database URL: +# DATABASE_URL=postgresql+psycopg2://user:password@host:port/database +``` + +#### 3. Optional Configuration + +**🔍 RAG System Tuning** +```env +# Adjust these values based on your needs: + +# Embedding Model (OpenAI models) +EMBEDDING_MODEL=text-embedding-3-small # Fast, cost-effective +# EMBEDDING_MODEL=text-embedding-3-large # Higher accuracy, more expensive + +# Chat Model (OpenAI models) +CHAT_MODEL=gpt-4o-mini # Fast, cost-effective +# CHAT_MODEL=gpt-4o # Higher quality responses + +# Document Processing +CHUNK_SIZE=1000 # Characters per chunk +CHUNK_OVERLAP=200 # Overlap between chunks +MAX_CONTEXT_LENGTH=8000 # Max tokens for AI context + +# Search Configuration +SIMILARITY_THRESHOLD=0.7 # Minimum similarity score (0.0-1.0) +MAX_RESULTS=5 # Maximum search results +``` + +**⏱️ Token Expiration** +```env +# Auth service token expiration (minutes) +ACCESS_TOKEN_EXPIRE_MINUTES=30 # Default: 30 minutes +``` + +**🔐 Oso Authorization** +```env +# Development (local Oso server) +OSO_URL=http://localhost:8080 +OSO_AUTH=e_0123456789_12345_osotesttoken01xiIn + +# Production (Oso Cloud) +# OSO_URL=https://cloud.osohq.com +# OSO_AUTH=your-production-oso-api-key +``` + +### 🚀 Quick Environment Setup + +For quick development setup, you can use these commands: + +```bash +# 1. Copy all example files +cp packages/auth/.env.example packages/auth/.env +cp packages/patient/.env.example packages/patient/.env +cp packages/rag/.env.example packages/rag/.env +cp frontend/.env.example frontend/.env + +# 2. Update your OpenAI API key (required for RAG) +# Edit packages/rag/.env and set your actual OpenAI API key: +# OPENAI_API_KEY=sk-your-actual-api-key-here + +# 3. Generate secure secret keys +SECRET_KEY=$(python -c "import secrets; print(secrets.token_urlsafe(32))") +echo "SECRET_KEY=$SECRET_KEY" >> packages/auth/.env +echo "SECRET_KEY=$SECRET_KEY" >> packages/patient/.env +echo "SECRET_KEY=$SECRET_KEY" >> packages/rag/.env + +# 4. Start services +./run_all.sh +``` + +## 🚀 Deployment + +### Production Deployment + +#### 1. **Production Environment Variables** + +Create production-specific `.env` files with secure values: + +**🔐 Auth Service (packages/auth/.env)** +```env +DEBUG=false +SECRET_KEY=your-super-secure-64-character-secret-key +DATABASE_URL=postgresql+psycopg2://user:password@prod-db:5432/healthcare +ACCESS_TOKEN_EXPIRE_MINUTES=30 +OSO_URL=https://cloud.osohq.com +OSO_AUTH=your-production-oso-cloud-api-key +``` + +**🏥 Patient Service (packages/patient/.env)** +```env +DEBUG=false +SECRET_KEY=your-super-secure-64-character-secret-key +DATABASE_URL=postgresql+psycopg2://user:password@prod-db:5432/healthcare +OSO_URL=https://cloud.osohq.com +OSO_AUTH=your-production-oso-cloud-api-key +``` + +**🤖 RAG Service (packages/rag/.env)** +```env +DEBUG=false +SECRET_KEY=your-super-secure-64-character-secret-key +DATABASE_URL=postgresql+psycopg2://user:password@prod-db:5432/healthcare +OSO_URL=https://cloud.osohq.com +OSO_AUTH=your-production-oso-cloud-api-key + +# OpenAI Configuration +OPENAI_API_KEY=sk-your-production-openai-api-key +EMBEDDING_MODEL=text-embedding-3-small +CHAT_MODEL=gpt-4o-mini + +# RAG Configuration +CHUNK_SIZE=1000 +CHUNK_OVERLAP=200 +MAX_CONTEXT_LENGTH=8000 +SIMILARITY_THRESHOLD=0.7 +MAX_RESULTS=5 + +# Galileo Observability +GALILEO_ENABLED=true +GALILEO_API_KEY=your-production-galileo-api-key +GALILEO_PROJECT_NAME=healthcare-rag-prod +GALILEO_ENVIRONMENT=production + + +# Logging Configuration +LOG_LEVEL=INFO +LOG_FORMAT=json +``` + +**🌐 Frontend (frontend/.env)** +```env +# API Configuration +VITE_API_BASE_URL=https://your-domain.com +VITE_AUTH_SERVICE_PORT=8001 +VITE_PATIENT_SERVICE_PORT=8002 +VITE_RAG_SERVICE_PORT=8003 + +# App Configuration +VITE_APP_NAME="Healthcare Support Portal" +VITE_APP_VERSION="1.0.0" + +# Production +VITE_DEBUG=false +``` + +#### 2. **Security Checklist** + +- ✅ **Generate unique secret keys** for each service +- ✅ **Use HTTPS** for all production URLs +- ✅ **Configure Oso Cloud** instead of local Oso server +- ✅ **Set DEBUG=false** for all services +- ✅ **Use production database** with proper credentials +- ✅ **Configure CORS** for your domain +- ✅ **Set up monitoring** and logging +- ✅ **Enable rate limiting** and request throttling + +#### 3. **Database Migration** +```bash +# Run migrations on production database +docker-compose run migrate +``` + +#### 4. **Service Deployment** +```bash +# Deploy services (example with Docker) +docker-compose -f docker-compose.prod.yml up -d +``` + +### Docker Deployment + +```bash +# Build and run with Docker Compose +docker-compose -f docker-compose.prod.yml up -d + +# Or build individual services +docker build -f Dockerfile.auth -t auth-service . +docker build -f Dockerfile.patient -t patient-service . +docker build -f Dockerfile.rag -t rag-service . +``` + +### Backup & Recovery + +```bash +# Database backup +docker exec healthcare-support-portal-db-1 \ + pg_dump -U postgres healthcare > backup_$(date +%Y%m%d).sql + +# Document backup (export all documents) +uv run python -c " +import json +from datetime import date +from packages.common.db import SessionLocal +from packages.common.models import Document + +with SessionLocal() as db: + docs = db.query(Document).all() + backup = [{'title': d.title, 'content': d.content, 'department': d.department} for d in docs] + with open(f'documents_backup_{date.today().isoformat()}.json', 'w') as f: + json.dump(backup, f, indent=2) +print('Documents backed up successfully') +" + +# Restore database +docker exec -i healthcare-support-portal-db-1 \ + psql -U postgres healthcare < backup_20241201.sql + +# Monitor system performance +docker stats --no-stream +uv run python -c "from packages.rag.src.rag_service.main import app; print('RAG service health check passed')" +``` + +## 🔧 Troubleshooting + +### Common Issues + +#### Service Won't Start +```bash +# Check if ports are available +lsof -i :8001 +lsof -i :8002 +lsof -i :8003 +lsof -i :3000 + +# Check service logs +tail -f logs/auth.log +tail -f logs/patient.log +tail -f logs/rag.log +``` + +#### Database Connection Issues +```bash +# Check if PostgreSQL is running +docker ps | grep postgres + +# Check database logs +docker logs healthcare-support-portal-postgres-1 + +# Test database connection +uv run python -c "from common.db import get_db; print('DB connection OK')" +``` + +#### Environment Variable Issues +```bash +# Check if .env files exist +ls -la packages/*/.env +ls -la frontend/.env + +# Verify environment variables are loaded +cd packages/auth && source .env && env | grep -E "(DEBUG|SECRET_KEY|DATABASE_URL)" +cd packages/patient && source .env && env | grep -E "(DEBUG|SECRET_KEY|DATABASE_URL)" +cd packages/rag && source .env && env | grep -E "(DEBUG|SECRET_KEY|OPENAI_API_KEY)" + +# Check for missing required variables +grep -r "OPENAI_API_KEY" packages/rag/.env +grep -r "SECRET_KEY" packages/*/.env +``` + +#### OpenAI API Errors +```bash +# Verify API key +echo $OPENAI_API_KEY + +# Test OpenAI connection +curl -H "Authorization: Bearer $OPENAI_API_KEY" \ + https://api.openai.com/v1/models + +# Check if API key is in .env file +grep "OPENAI_API_KEY" packages/rag/.env +``` + +#### RAG System Issues +```bash +# Check embedding status +curl -X GET "http://localhost:8003/api/v1/documents/embedding-statuses" \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" + +# Regenerate embeddings if needed +curl -X POST "http://localhost:8003/api/v1/documents/{doc_id}/regenerate-embeddings" \ + -H "Authorization: Bearer YOUR_JWT_TOKEN" +``` + +### Debug Mode + +Set `DEBUG=true` for detailed logging: +- Embedding generation logs +- Vector search query details +- AI response generation steps +- Authorization decision logging + +## 📖 Contributing + +### Development Guidelines + +1. **Follow existing patterns** for async/await operations +2. **Add comprehensive error handling** for external API calls +3. **Update vector search logic** carefully to maintain performance +4. **Test with various document types** and sizes +5. **Consider cost implications** of AI model changes +6. **Update documentation** for new features + +### Code Style + +- Use **async/await** for AI operations +- Follow **FastAPI** best practices +- Implement **proper error handling** +- Add **comprehensive logging** +- Write **clear documentation** + +## 📄 License + +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. + +--- + +## 🎉 **Your RAG System is Ready!** + +You now have a **world-class RAG application** that can transform how your organization accesses and uses knowledge. + +### 🔧 **Important Configuration Notes** + +- **🔑 OpenAI API Key**: Required for RAG functionality - get yours at [OpenAI Platform](https://platform.openai.com/api-keys) +- **🔐 Security Keys**: Generate unique secret keys for each service in production +- **🗄️ Database**: Ensure PostgreSQL with pgvector extension is running +- **🔍 Environment Files**: Each service has its own `.env` file for configuration +- **📊 Galileo**: Observability platform for monitoring and analytics + +### 🚀 **Next Steps** + +1. **📖 [RAG Quick Start Guide](packages/rag/QUICK_START.md)**: Get up and running in 5 minutes +2. **📚 [Complete RAG Guide](packages/rag/RAG_GUIDE.md)**: Master all RAG features +3. **🔧 Configure Environment**: Set up all required environment variables +4. **🧪 Test Your System**: Upload documents and ask questions +5. **🚀 Deploy to Production**: Follow the production deployment guide + +### 📋 **Configuration Checklist** + +- ✅ **Environment files created** for all services +- ✅ **OpenAI API key configured** in RAG service +- ✅ **Secret keys generated** for all services +- ✅ **Database connection** working +- ✅ **All services starting** without errors +- ✅ **RAG functionality** tested with document upload and query +- ✅ **Galileo observability** configured (optional) + +**Welcome to the future of intelligent knowledge management!** 🏥✨ + diff --git a/python/rag/healthcare-support-portal/TUTORIAL.md b/python/rag/healthcare-support-portal/TUTORIAL.md new file mode 100644 index 00000000..33c840dc --- /dev/null +++ b/python/rag/healthcare-support-portal/TUTORIAL.md @@ -0,0 +1,939 @@ +# Building Your First AI-Powered Healthcare Knowledge System + +*A beginner's journey from zero to production-ready RAG application in one afternoon* + +--- + +## Welcome to the Future of Healthcare Knowledge Management + +Hi there! 👋 If you're reading this, you're probably curious about AI and how it can transform healthcare information systems. Maybe you've heard buzzwords like "RAG," "vector databases," or "AI embeddings" and wondered what they actually mean in practice. + +Today, we're going to build something truly remarkable together: a complete healthcare knowledge management system that can understand, search, and answer questions about medical documents using artificial intelligence. And the best part? You don't need to be an AI expert to do it. + +By the end of this tutorial, you'll have: +- 🤖 Your own AI assistant that can answer medical questions +- 🔐 A secure system with role-based access (doctors see different content than nurses) +- 📊 Monitoring dashboards to track AI performance +- 💡 A deep understanding of how modern AI systems work + +**Time commitment:** About 2-3 hours (including learning time) +**Difficulty:** Beginner-friendly with detailed explanations +**What you'll learn:** RAG systems, vector databases, authorization, AI monitoring + +--- + +## Chapter 1: Understanding What We're Building + +Before we dive into code, let's understand the problem we're solving and why it matters. + +### The Healthcare Information Challenge + +Imagine you're a doctor in the middle of a busy shift. A patient presents with unusual symptoms, and you need to quickly reference the latest treatment guidelines. Today, you might: + +1. 🔍 Search through hundreds of PDF guidelines +2. 📚 Try to remember protocols from medical school +3. 📱 Google symptoms and hope for reliable sources +4. 🕒 Spend precious time that could be helping patients + +**What if there was a better way?** + +### Enter RAG: Retrieval-Augmented Generation + +RAG sounds complicated, but the concept is beautifully simple: + +**Traditional AI:** "What's the treatment for pneumonia?" +**AI Response:** *Generic answer based on training data, no sources, might be outdated* + +**RAG-powered AI:** "What's the treatment for pneumonia?" +**Step 1:** Search your uploaded medical guidelines for relevant information +**Step 2:** Feed that specific, current information to the AI +**AI Response:** *Detailed answer based on YOUR documents, with exact page references* + +It's like having a research assistant that instantly reads through all your documents and provides sourced answers. That's the magic we're building today. + +### The Three Pillars of Our System + +Our healthcare knowledge system stands on three technologies: + +1. **🧠 RAG (Retrieval-Augmented Generation)** - The AI that understands and answers questions +2. **🔐 Oso** - Security system that ensures doctors only see cardiology docs, nurses see procedures, etc. +3. **📊 Galileo** - Monitoring that tells us how well our AI is performing + +Think of it like a hospital: +- **RAG** is the brilliant doctor who knows everything +- **Oso** is the security system that controls who can access what +- **Galileo** is the quality assurance team tracking performance + +--- + +## Chapter 2: Setting Up Your Development Environment + +Let's get your computer ready to build AI systems. Don't worry if this feels overwhelming - I'll explain each step. + +### What We Need and Why + +```bash +# Let's check what you already have +echo "🔍 Checking your system..." +python3 --version # We need Python for AI processing +node --version # We need Node.js for our web interface +docker --version # We need Docker for our database +git --version # We need Git to get the code +``` + +**Why these tools?** +- **Python 3.11+**: The language of AI - most AI libraries are built for Python +- **Node.js 20.19.0+**: For our modern web interface where users will interact with the AI +- **Docker**: To run PostgreSQL with vector search capabilities +- **Git**: To download our pre-built application code + +If any of these commands fail, here's what to do: + +#### Installing Missing Tools + +**Python Missing?** +```bash +# On Mac with Homebrew +brew install python@3.12 + +# On Ubuntu/Debian +sudo apt update && sudo apt install python3.12 + +# On Windows: Download from python.org +``` + +**Node.js Missing?** +```bash +# Install Node Version Manager (works on Mac/Linux) +curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash +source ~/.bashrc +nvm install 20 +nvm use 20 +``` + +**Docker Missing?** +Visit [docker.com](https://docker.com) and download Docker Desktop for your operating system. + +### Installing Our Secret Weapon: UV + +Now here's where things get exciting. We're going to use a tool called `uv` - think of it as a supercharged package manager for Python that's incredibly fast. + +```bash +# Install uv (the fastest Python package manager) +curl -LsSf https://astral.sh/uv/install.sh | sh + +# Restart your terminal or run: +source ~/.bashrc # or ~/.zshrc on Mac + +# Verify it worked +uv --version +``` + +**Why UV?** Traditional Python package management can be slow and error-prone. UV solves this by being 10-100x faster and more reliable. It's like upgrading from a bicycle to a sports car. + +--- + +## Chapter 3: Getting Your Hands on the Code + +Time to download our healthcare RAG application! + +```bash +# Clone the repository (this downloads all the code) +git clone https://github.com/rungalileo/sdk-examples.git +cd sdk-examples/python/rag/healthcare-support-portal + +# Take a moment to look around +ls -la +``` + +**What you're seeing:** +- `packages/` - Our Python microservices (auth, patient management, RAG) +- `frontend/` - The React web application +- `setup.sh` - Automated setup script that does the heavy lifting +- `README.md` - The comprehensive guide we just improved + +### The Magic Setup Script + +Instead of manually configuring dozens of settings, we have a script that does it all: + +```bash +# Make the script executable and run it +chmod +x setup.sh +./setup.sh +``` + +**Watch the magic happen! The script is:** +1. ✅ Installing Python dependencies with UV (much faster than pip) +2. ✅ Installing JavaScript dependencies for our web interface +3. ✅ Creating configuration files for each service +4. ✅ Generating secure encryption keys +5. ✅ Setting up the database structure + +You'll see output like: +``` +🏥 Healthcare Support Portal - Initial Setup +============================================= +📁 Creating directories... +🔍 Checking prerequisites... +✅ Python 3.12.1 is compatible +✅ uv package manager found +🐍 Setting up Python environment... +✅ Python dependencies synced +📋 Setting up environment files... +✅ Created packages/auth/.env from example +✅ Created packages/patient/.env from example +✅ Created packages/rag/.env from example +``` + +If everything goes well, you'll see: **✅ Setup complete!** + +--- + +## Chapter 4: The Most Important Step - Your OpenAI API Key + +Here's where the AI magic begins. We need to connect our system to OpenAI's powerful language models. + +### Getting Your API Key + +1. **Visit [OpenAI's Platform](https://platform.openai.com/api-keys)** +2. **Sign up** if you don't have an account (you'll get free credits!) +3. **Create a new API key** - it will look like `sk-abcd1234...` +4. **Copy it** - you'll only see it once! + +### Configuring the RAG Service + +```bash +# Open the RAG service configuration +nano packages/rag/.env +# Or if you prefer: code packages/rag/.env +``` + +**Find this line:** +```env +OPENAI_API_KEY=sk-your-openai-api-key-here +``` + +**Replace it with your actual key:** +```env +OPENAI_API_KEY=sk-abcd1234your-real-key-here +``` + +### Understanding the Cost + +**"Wait, will this cost me money?"** + +For testing and learning, costs are minimal: +- **Text embeddings**: ~$0.10 per 1,000 pages of documents +- **AI responses**: ~$0.002 per question answered +- **Your free credits**: Usually $5-18 for new accounts + +Translation: You can process hundreds of documents and ask thousands of questions for just a few dollars. + +### Testing Your Configuration + +```bash +# Let's make sure everything is configured correctly +cd packages/rag +uv run python -c " +import os +api_key = os.getenv('OPENAI_API_KEY', '') +if api_key.startswith('sk-'): + print('✅ API key configured correctly!') +else: + print('❌ API key missing or invalid') +" +``` + +--- + +## Chapter 5: Optional But Recommended - AI Monitoring with Galileo + +Galileo is like having a performance coach for your AI system. It tracks how well your AI is performing, catches problems early, and helps you improve over time. + +### Setting Up Galileo (Optional) + +1. **Visit [Galileo's website](https://app.galileo.ai/sign-up)** +2. **Sign up for a free account** +3. **Get your API key** from the dashboard +4. **Add it to your configuration**: + +```bash +# Add to packages/rag/.env +echo "GALILEO_API_KEY=your-galileo-key-here" >> packages/rag/.env +echo "GALILEO_PROJECT_NAME=my-healthcare-rag" >> packages/rag/.env +``` + +### Test Galileo Connection + +```bash +cd packages/rag +uv run python test_config.py +``` + +**If Galileo is working, you'll see:** +``` +✅ Galileo connection successful +✅ Project 'my-healthcare-rag' configured +``` + +**If you skip Galileo (totally fine!):** +```bash +# Disable Galileo monitoring +echo "GALILEO_ENABLED=false" >> packages/rag/.env +``` + +--- + +## Chapter 6: Launch Day - Starting Your AI System + +This is it! Time to bring your healthcare AI system to life. + +```bash +# Start all services (this is the moment of truth!) +./run_all.sh +``` + +**What's happening behind the scenes:** + +1. 🗄️ **PostgreSQL Database** starts up with vector search capabilities +2. ⚖️ **Oso Authorization Server** starts managing permissions +3. 🔐 **Auth Service** starts handling user logins +4. 🏥 **Patient Service** starts managing medical records +5. 🤖 **RAG Service** starts processing documents and AI queries +6. 🌐 **Frontend Web App** starts serving the user interface + +**Success looks like:** +``` +✅ PostgreSQL Database (Port 5432) +✅ Oso Dev Server (Port 8080) +✅ Auth Service (Port 8001) +✅ Patient Service (Port 8002) +✅ RAG Service (Port 8003) +✅ Frontend Service (Port 3000) + +🌐 Frontend: http://localhost:3000 +``` + +### Your First Look at the System + +Open your web browser and navigate to **http://localhost:3000** + +**What you're seeing:** +- A modern, clean interface designed for healthcare professionals +- Login form with role-based access +- Document upload area +- AI chat interface + +--- + +## Chapter 7: Meeting Your AI - First Interactions + +Let's create some demo users and start experimenting! + +### Creating Demo Users + +```bash +# This creates realistic healthcare user accounts +uv run python -m common.seed_data +``` + +**You now have three types of users:** +- **Dr. Smith** (`dr_smith` / `secure_password`) - Cardiologist +- **Nurse Johnson** (`nurse_johnson` / `secure_password`) - Emergency Department +- **Admin Wilson** (`admin_wilson` / `secure_password`) - Hospital Administrator + +### Your First Login + +1. **Go to http://localhost:3000** +2. **Login as Dr. Smith**: `dr_smith` / `secure_password` +3. **Look around the interface** - notice how it's tailored for medical professionals + +### Understanding the AI's Brain - Document Processing + +Before our AI can answer questions, it needs to "read" and "understand" documents. Here's how: + +#### Step 1: Upload Your First Document + +**Find a medical document** (PDF format works best): +- Research paper from PubMed +- Clinical guidelines +- Hospital protocols +- Even this tutorial as a test! + +**Upload process:** +1. Click "Upload Document" +2. Select your PDF +3. Add a descriptive title +4. Choose appropriate department/category +5. Click "Upload" + +#### Step 2: Watch the AI Process It + +Behind the scenes, something amazing is happening: + +1. **Text Extraction**: The system reads every word from your PDF +2. **Chunking**: Breaks the document into manageable sections +3. **Embedding Generation**: OpenAI converts each section into a "vector" (mathematical representation of meaning) +4. **Vector Storage**: These vectors are stored in our PostgreSQL database with pgvector + +**This process takes 30-60 seconds per document.** + +#### Step 3: Your First AI Question + +Once processing is complete, try asking: + +**Simple question:** *"What is this document about?"* + +**Medical question:** *"What are the key treatment recommendations?"* + +**Specific question:** *"What does this say about drug interactions?"* + +### Understanding What Just Happened + +When you asked a question, here's the AI workflow: + +1. **Your question** → **Converted to vector** +2. **Vector search** → **Finds relevant document sections** +3. **Relevant sections** + **Your question** → **Sent to OpenAI** +4. **OpenAI** → **Generates contextualized answer** +5. **Answer with sources** → **Displayed to you** + +**This is RAG in action!** The AI didn't just guess - it actually "read" your documents and provided a sourced answer. + +--- + +## Chapter 8: Exploring Role-Based Security + +One of the most important features for healthcare is security. Let's explore how Oso manages access control. + +### The Security Challenge in Healthcare + +In a real hospital: +- Cardiologists shouldn't access psychiatric patient records +- Nurses need procedure documents, not research papers +- Administrators need policy documents, not clinical guidelines +- Everyone needs emergency protocols + +### Testing Different User Roles + +#### As a Doctor (Current login): +``` +✅ Can upload clinical research +✅ Can access treatment guidelines +✅ Can ask complex medical questions +❌ Cannot access administrative policies (unless relevant) +``` + +#### Switch to Nurse Johnson: +1. **Logout** and **login as**: `nurse_johnson` / `secure_password` +2. **Upload a nursing procedure** document +3. **Ask**: *"What's the protocol for medication administration?"* + +#### Notice the differences: +- Different documents appear +- AI responses are tailored to nursing context +- Access patterns follow role-based permissions + +#### Switch to Admin Wilson: +1. **Login as**: `admin_wilson` / `secure_password` +2. **Upload a hospital policy** document +3. **Ask**: *"What are our HIPAA compliance requirements?"* + +### Behind the Scenes: How Oso Works + +```python +# This is what's happening in authorization.polar: +allow(user: User, "read", document: Document) if + user.department = document.department; + +allow(user: User, "read", document: Document) if + document.is_public = true; + +allow(user: User, "read", document: Document) if + user.role = "admin"; +``` + +**Translation:** Users can only see documents from their department, public documents, or if they're an admin. + +--- + +## Chapter 9: Advanced AI Interactions + +Now that you understand the basics, let's explore advanced capabilities. + +### Multi-Document Synthesis + +Upload multiple related documents and ask: + +*"Compare the treatment approaches mentioned across all uploaded guidelines"* + +**The AI will:** +1. Search across ALL your documents +2. Find relevant sections from multiple sources +3. Synthesize information from different documents +4. Provide a comprehensive answer with citations + +### Contextual Medical Questions + +Try these progressively complex questions: + +**Level 1:** *"What medications are mentioned in this document?"* + +**Level 2:** *"What are the contraindications for the medications mentioned?"* + +**Level 3:** *"For a 65-year-old patient with diabetes and kidney disease, which of these medications would be safest?"* + +**Level 4:** *"Create a step-by-step treatment protocol based on these guidelines for elderly diabetic patients"* + +### Understanding AI Limitations + +**What RAG AI does well:** +✅ Exact information retrieval with sources +✅ Synthesizing information from multiple documents +✅ Following document-based protocols +✅ Providing properly attributed answers + +**What to be cautious about:** +⚠️ AI can only work with documents you've uploaded +⚠️ Always verify critical medical decisions independently +⚠️ AI may miss nuances in complex cases +⚠️ Ensure documents are current and authoritative + +--- + +## Chapter 10: Monitoring Your AI with Galileo + +If you set up Galileo, let's explore the monitoring dashboard. + +### Accessing Your Galileo Dashboard + +1. **Visit [app.galileo.ai](https://app.galileo.ai)** +2. **Login with your account** +3. **Find your project**: "my-healthcare-rag" (or whatever you named it) + +### What You Can See + +**Query Analytics:** +- Most common questions asked +- Response times and quality scores +- User satisfaction patterns + +**Document Performance:** +- Which documents are most referenced +- Documents that need better organization +- Gaps in your knowledge base + +**Cost Tracking:** +- OpenAI API usage and costs +- Trends over time +- Budget predictions + +**Quality Metrics:** +- AI response accuracy +- User feedback scores +- Areas needing improvement + +### Using Galileo for Continuous Improvement + +**Week 1:** Baseline metrics - see how the system performs initially + +**Week 2:** Identify patterns - what questions are asked most? + +**Month 1:** Optimize based on data - add more documents for common questions + +**Month 3:** Scale up - expand to more departments based on success metrics + +--- + +## Chapter 11: Real-World Deployment Considerations + +You've built and tested your system locally. Here's how to think about real-world deployment. + +### Security Hardening for Healthcare + +**Environment Variables:** +```bash +# Never commit these to code repositories! +export OPENAI_API_KEY="your-production-key" +export DATABASE_URL="postgresql://secure-user:complex-password@prod-db:5432/healthcare" +export SECRET_KEY="a-very-long-random-production-key" +``` + +**HTTPS Everywhere:** +- Use TLS certificates for all communications +- Encrypt data at rest in the database +- Secure API endpoints with proper authentication + +**Audit Logging:** +```bash +# Example: Check who accessed what documents +grep "document_access" logs/audit.log | tail -20 +``` + +### Scaling Considerations + +**Database Optimization:** +- Index frequently searched fields +- Partition large document collections +- Monitor vector search performance + +**AI Performance:** +- Cache common queries +- Use batch processing for document uploads +- Monitor OpenAI rate limits + +**Infrastructure:** +```bash +# Production deployment example +docker-compose -f docker-compose.prod.yml up -d +``` + +### Compliance and Governance + +**For Healthcare Organizations:** +- Review all AI responses for accuracy +- Maintain document version control +- Log all user interactions +- Regular security audits +- Staff training on AI limitations + +--- + +## Chapter 12: Troubleshooting Like a Pro + +Even the best systems sometimes have hiccups. Here's how to diagnose and fix common issues. + +### The Diagnostic Approach + +When something goes wrong, follow this systematic approach: + +#### Step 1: Check the Basics +```bash +# Are all services running? +./health_check.sh + +# Or manually: +curl http://localhost:8001/health # Auth service +curl http://localhost:8002/health # Patient service +curl http://localhost:8003/health # RAG service +``` + +#### Step 2: Check the Logs +```bash +# Look for errors in service logs +tail -50 logs/rag.log | grep -i error +tail -50 logs/auth.log | grep -i error +tail -50 logs/frontend.log | grep -i error +``` + +#### Step 3: Test Individual Components +```bash +# Test OpenAI connection +curl -H "Authorization: Bearer $OPENAI_API_KEY" \ + https://api.openai.com/v1/models + +# Test database connection +docker exec healthcare-support-portal-postgres-1 pg_isready + +# Test document processing +cd packages/rag +uv run python -c "from src.rag_service.utils.embeddings import test_embeddings; test_embeddings()" +``` + +### Common Issues and Solutions + +#### "Port Already in Use" Error +```bash +# Find what's using the port +lsof -i :8003 + +# Kill the process (replace PID with actual number) +kill -9 [PID] + +# Or kill all related processes +./stop_all.sh +``` + +#### "OpenAI API Error" +```bash +# Check your API key format +echo $OPENAI_API_KEY | grep "sk-" + +# Check your account has credits +curl -H "Authorization: Bearer $OPENAI_API_KEY" \ + https://api.openai.com/v1/usage +``` + +#### "Galileo Span Error" +This error is non-fatal but annoying: +```bash +# Option 1: Disable Galileo +echo "GALILEO_ENABLED=false" >> packages/rag/.env + +# Option 2: Fix Galileo configuration +echo "GALILEO_API_KEY=your-real-key" >> packages/rag/.env +``` + +#### Documents Not Processing +```bash +# Check document upload status +curl -H "Authorization: Bearer $JWT_TOKEN" \ + http://localhost:8003/api/v1/documents/ + +# Manually trigger embedding generation +curl -X POST -H "Authorization: Bearer $JWT_TOKEN" \ + http://localhost:8003/api/v1/documents/1/regenerate-embeddings +``` + +### When All Else Fails: Fresh Start +```bash +# Nuclear option - complete reset +./stop_all.sh +docker-compose down --volumes +rm -rf logs/* data/postgres/* packages/*/.env +./setup.sh +``` + +--- + +## Chapter 13: What You've Built and What's Next + +Congratulations! 🎉 Let's reflect on your accomplishment and explore next steps. + +### What You've Accomplished + +You've built a **production-ready healthcare AI knowledge system** that includes: + +**🤖 AI-Powered Document Understanding** +- Semantic search across medical documents +- Context-aware question answering +- Multi-document synthesis capabilities + +**🔐 Enterprise-Grade Security** +- Role-based access control +- Department-level document isolation +- Audit trails for compliance + +**📊 AI Performance Monitoring** +- Real-time performance tracking +- Cost monitoring and optimization +- Quality assurance metrics + +**🏥 Healthcare-Specific Features** +- Medical terminology understanding +- Clinical workflow integration +- Compliance-conscious design + +### The Technical Skills You've Gained + +**AI/ML Concepts:** +- RAG (Retrieval-Augmented Generation) systems +- Vector databases and semantic search +- Embedding generation and similarity matching +- AI response quality evaluation + +**Modern Development Practices:** +- Microservices architecture +- Container orchestration with Docker +- Fast Python package management with UV +- Modern JavaScript frameworks (React Router 7) + +**Security and Authorization:** +- OAuth2 and JWT authentication +- Policy-based authorization with Oso +- Role-based access control patterns +- Healthcare data security principles + +### Immediate Next Steps + +**For Learning:** +1. **Experiment with different documents** - try various medical specialties +2. **Test edge cases** - see how the AI handles ambiguous questions +3. **Explore API endpoints** - build custom integrations +4. **Monitor performance** - analyze Galileo dashboards + +**For Development:** +1. **Add new document types** - images, videos, structured data +2. **Enhance the UI** - custom themes, better search interfaces +3. **Integrate with EMRs** - connect to existing healthcare systems +4. **Build mobile apps** - React Native or Progressive Web Apps + +### Long-Term Possibilities + +**Organizational Deployment:** +- Department-specific knowledge bases +- Integration with hospital information systems +- Multi-tenant architecture for health networks +- Compliance with healthcare regulations (HIPAA, GDPR) + +**Advanced AI Features:** +- Fine-tuned models for specific medical specialties +- Real-time clinical decision support +- Automated protocol generation +- Predictive healthcare analytics + +**Research Applications:** +- Clinical research data analysis +- Drug discovery knowledge synthesis +- Medical literature review automation +- Evidence-based practice optimization + +--- + +## Chapter 14: The Bigger Picture - AI in Healthcare + +As you continue your journey, it's worth understanding the broader context of AI in healthcare. + +### Current State of AI in Healthcare + +**Where AI Excels:** +- Medical imaging analysis (X-rays, MRIs, CT scans) +- Drug discovery and development +- Clinical documentation and coding +- Population health management +- Predictive analytics for patient outcomes + +**Where AI is Emerging:** +- Clinical decision support systems (like what you built!) +- Personalized treatment planning +- Real-time patient monitoring +- Healthcare operations optimization + +### Ethical Considerations + +**Bias and Fairness:** +- AI systems can perpetuate biases present in training data +- Important to use diverse, representative datasets +- Regular auditing of AI decisions across patient demographics + +**Transparency and Explainability:** +- Healthcare providers need to understand AI recommendations +- Patients have a right to know when AI is involved in their care +- Your RAG system addresses this with source attribution + +**Human-AI Collaboration:** +- AI should augment, not replace, human expertise +- Healthcare professionals remain responsible for patient care +- AI provides information, humans make decisions + +### Your Role in the Future + +By learning to build AI systems like this, you're positioning yourself at the forefront of healthcare innovation. Whether you're a: + +**Healthcare Professional:** You understand how AI can enhance patient care while maintaining human oversight + +**Software Developer:** You have hands-on experience with cutting-edge AI technologies applied to critical domains + +**Administrator/Leader:** You understand both the potential and the practical challenges of AI implementation + +**Student/Researcher:** You have a foundation for advanced study in health informatics and medical AI + +--- + +## Conclusion: Your AI Journey Starts Now + +Over the course of this tutorial, you've gone from zero to having your own AI-powered healthcare knowledge system. More importantly, you've gained understanding of: + +- How modern AI systems actually work (not just the hype) +- The practical challenges of deploying AI in sensitive domains +- The importance of security, monitoring, and responsible AI practices +- The collaborative relationship between humans and AI + +### The Knowledge You've Gained + +**Technical Skills:** +✅ RAG system architecture and implementation +✅ Vector databases and semantic search +✅ Modern Python development with UV +✅ Microservices and API design +✅ Security and authorization patterns +✅ AI monitoring and observability + +**Domain Knowledge:** +✅ Healthcare information challenges +✅ Regulatory and compliance considerations +✅ Clinical workflow integration +✅ Medical data security requirements + +**Soft Skills:** +✅ Systematic troubleshooting approaches +✅ Reading and understanding AI performance metrics +✅ Balancing innovation with responsibility +✅ Communicating AI capabilities and limitations + +### Your Next Adventure + +The healthcare AI field is evolving rapidly. Here are ways to stay involved: + +**Keep Learning:** +- Follow AI research in healthcare journals +- Attend medical informatics conferences +- Join AI and healthcare communities online +- Experiment with new models and techniques + +**Contribute Back:** +- Share your experiences with the community +- Contribute to open-source healthcare AI projects +- Mentor others starting their AI journey +- Advocate for responsible AI practices + +**Apply Your Knowledge:** +- Identify other healthcare challenges AI could address +- Propose AI pilot projects in your organization +- Collaborate with healthcare professionals to understand their needs +- Always prioritize patient safety and privacy + +### Final Thoughts + +AI is not magic - it's a powerful tool that requires careful implementation, thoughtful oversight, and continuous improvement. What you've built today is more than just code; it's a glimpse into the future of healthcare, where AI and human expertise work together to provide better, faster, more accurate care. + +The system you've created can process medical literature faster than any human, but it still needs human judgment to interpret results responsibly. It can find relevant information across thousands of documents, but healthcare professionals still need to make the final clinical decisions. + +This balance between AI capability and human responsibility is what makes this field so exciting and so important. + +**Welcome to the future of healthcare technology. The journey is just beginning.** 🚀 + +--- + +## Appendix: Quick Reference + +### Essential Commands +```bash +# Start the system +./run_all.sh + +# Stop the system +./stop_all.sh + +# Reset everything +./stop_all.sh && docker-compose down --volumes && ./setup.sh + +# Check system health +curl http://localhost:3000 # Frontend +curl http://localhost:8003/health # RAG service +``` + +### Important URLs +- **Main Application:** http://localhost:3000 +- **RAG API Documentation:** http://localhost:8003/docs +- **Auth API Documentation:** http://localhost:8001/docs +- **Galileo Dashboard:** https://app.galileo.ai +- **OpenAI Usage:** https://platform.openai.com/usage + +### Demo Accounts +- **Doctor:** `dr_smith` / `secure_password` +- **Nurse:** `nurse_johnson` / `secure_password` +- **Admin:** `admin_wilson` / `secure_password` + +### Getting Help +- **GitHub Issues:** [sdk-examples/issues](https://github.com/rungalileo/sdk-examples/issues) +- **Galileo Discord:** [discord.gg/galileo](https://discord.gg/galileo) +- **OpenAI Documentation:** [platform.openai.com/docs](https://platform.openai.com/docs) +- **Oso Documentation:** [docs.osohq.com](https://docs.osohq.com) + +--- + +*Thank you for joining me on this journey into AI-powered healthcare technology. Remember: the goal isn't to replace human expertise, but to augment it with the power of artificial intelligence. Build responsibly, deploy thoughtfully, and always keep patient care at the center of everything you do.* + +**Happy building!** 👩‍⚕️🤖👨‍⚕️ + diff --git a/python/rag/healthcare-support-portal/authorization.polar b/python/rag/healthcare-support-portal/authorization.polar new file mode 100644 index 00000000..e161d727 --- /dev/null +++ b/python/rag/healthcare-support-portal/authorization.polar @@ -0,0 +1,197 @@ +# Healthcare Support Portal Authorization Policies +# OSO Cloud Policy File + +# ============================================================================ +# ACTOR DEFINITIONS +# ============================================================================ + +actor User {} + +# ============================================================================ +# RESOURCE DEFINITIONS +# ============================================================================ + +resource User { + permissions = ["read", "write", "delete"]; + roles = ["admin"]; + + # Admins can do everything with users + "read" if "admin"; + "write" if "admin"; + "delete" if "admin"; +} + +resource Patient { + permissions = ["read", "write", "delete"]; + roles = ["admin", "assigned_doctor", "department_nurse"]; + + # Admins can do everything with patients + "read" if "admin"; + "write" if "admin"; + "delete" if "admin"; + + # Doctors can access their assigned patients + "read" if "assigned_doctor"; + "write" if "assigned_doctor"; + + # Nurses can access patients in their department + "read" if "department_nurse"; +} + +resource Document { + permissions = ["read", "write", "delete", "share"]; + roles = ["admin", "owner", "patient_doctor", "department_staff"]; + + # Admins can do everything with documents + "read" if "admin"; + "write" if "admin"; + "delete" if "admin"; + "share" if "admin"; + + # Document owner can do everything + "read" if "owner"; + "write" if "owner"; + "delete" if "owner"; + "share" if "owner"; + + # Doctors can access documents for their patients + "read" if "patient_doctor"; + "write" if "patient_doctor"; + + # Department staff can read non-sensitive documents in their department + "read" if "department_staff"; +} + +resource Embedding { + permissions = ["read", "write", "delete"]; + roles = ["admin"]; + + # Only admins can manage embeddings directly + "read" if "admin"; + "write" if "admin"; + "delete" if "admin"; +} + +# ============================================================================ +# FACT DECLARATIONS +# ============================================================================ + +# Declare the fact patterns we use in authorization +declare has_role(User, String, User); +declare has_role(User, String, Patient); +declare has_role(User, String, Document); +declare has_role(User, String, Embedding); + +# ============================================================================ +# MAIN AUTHORIZATION RULE +# ============================================================================ + +allow(actor, action, resource) if + has_permission(actor, action, resource); + +# Global admin permissions - This rule is commented out as it uses syntax not supported in OSO Cloud +# allow(actor, action, resource) if +# actor.role = "admin" and +# resource matches User and +# action in ["read", "write", "delete"]; + +# ============================================================================ +# TESTS +# ============================================================================ + +test "admin can read all patients" { + setup { + has_role(User{"admin_wilson"}, "admin", Patient{"patient_1"}); + has_role(User{"admin_wilson"}, "admin", Patient{"patient_2"}); + has_role(User{"admin_wilson"}, "admin", Patient{"patient_3"}); + } + + assert allow(User{"admin_wilson"}, "read", Patient{"patient_1"}); + assert allow(User{"admin_wilson"}, "read", Patient{"patient_2"}); + assert allow(User{"admin_wilson"}, "read", Patient{"patient_3"}); + assert allow(User{"admin_wilson"}, "write", Patient{"patient_1"}); + assert allow(User{"admin_wilson"}, "delete", Patient{"patient_1"}); +} + +test "admin can read all documents" { + setup { + has_role(User{"admin_wilson"}, "admin", Document{"doc_1"}); + has_role(User{"admin_wilson"}, "admin", Document{"doc_2"}); + } + + assert allow(User{"admin_wilson"}, "read", Document{"doc_1"}); + assert allow(User{"admin_wilson"}, "write", Document{"doc_1"}); + assert allow(User{"admin_wilson"}, "delete", Document{"doc_1"}); + assert allow(User{"admin_wilson"}, "share", Document{"doc_1"}); +} + +test "doctor can read assigned patients only" { + setup { + has_role(User{"doctor_smith"}, "assigned_doctor", Patient{"assigned_patient"}); + } + + assert allow(User{"doctor_smith"}, "read", Patient{"assigned_patient"}); + assert allow(User{"doctor_smith"}, "write", Patient{"assigned_patient"}); + assert_not allow(User{"doctor_smith"}, "read", Patient{"other_patient"}); +} + +test "nurse can read department patients but not write" { + setup { + has_role(User{"nurse_jones"}, "department_nurse", Patient{"dept_patient"}); + } + + assert allow(User{"nurse_jones"}, "read", Patient{"dept_patient"}); + assert_not allow(User{"nurse_jones"}, "write", Patient{"dept_patient"}); + assert_not allow(User{"nurse_jones"}, "read", Patient{"other_dept_patient"}); +} + +test "doctor can read documents for their patients" { + setup { + has_role(User{"doctor_smith"}, "patient_doctor", Document{"patient_doc"}); + } + + assert allow(User{"doctor_smith"}, "read", Document{"patient_doc"}); + assert allow(User{"doctor_smith"}, "write", Document{"patient_doc"}); + assert_not allow(User{"doctor_smith"}, "delete", Document{"patient_doc"}); +} + +test "nurse can read non-sensitive department documents" { + setup { + has_role(User{"nurse_jones"}, "department_staff", Document{"dept_doc"}); + } + + assert allow(User{"nurse_jones"}, "read", Document{"dept_doc"}); + assert_not allow(User{"nurse_jones"}, "write", Document{"dept_doc"}); +} + +test "users can read their own information" { + setup { + has_role(User{"doctor_smith"}, "admin", User{"doctor_smith"}); + } + + assert allow(User{"doctor_smith"}, "read", User{"doctor_smith"}); + assert allow(User{"doctor_smith"}, "write", User{"doctor_smith"}); + assert_not allow(User{"doctor_smith"}, "read", User{"other_user"}); +} + +test "document owners have full control" { + setup { + has_role(User{"doctor_smith"}, "owner", Document{"created_doc"}); + } + + assert allow(User{"doctor_smith"}, "read", Document{"created_doc"}); + assert allow(User{"doctor_smith"}, "write", Document{"created_doc"}); + assert allow(User{"doctor_smith"}, "delete", Document{"created_doc"}); + assert allow(User{"doctor_smith"}, "share", Document{"created_doc"}); +} + +test "only admins can manage embeddings" { + setup { + has_role(User{"admin_wilson"}, "admin", Embedding{"embedding_1"}); + } + + assert allow(User{"admin_wilson"}, "read", Embedding{"embedding_1"}); + assert allow(User{"admin_wilson"}, "write", Embedding{"embedding_1"}); + assert allow(User{"admin_wilson"}, "delete", Embedding{"embedding_1"}); + assert_not allow(User{"doctor_smith"}, "read", Embedding{"embedding_1"}); +} \ No newline at end of file diff --git a/python/rag/healthcare-support-portal/db-init/01_seed_users.sql b/python/rag/healthcare-support-portal/db-init/01_seed_users.sql new file mode 100644 index 00000000..affdb4ff --- /dev/null +++ b/python/rag/healthcare-support-portal/db-init/01_seed_users.sql @@ -0,0 +1,24 @@ +-- 01_seed_users.sql +-- This script runs automatically when the PostgreSQL container starts with an empty database +-- It seeds the database with demo users for authentication + +-- Insert demo users with hashed passwords (password: "secure_password" for all) +INSERT INTO users (id, username, email, hashed_password, role, department, is_active, created_at) VALUES + (1, 'admin_wilson', 'jennifer.wilson@hospital.com', '$2b$12$gdtwLxe4YU648JwtZPX8/uAv9n5qpKZ8VFXJ1iyjqVU/HExd20IXC', 'admin', 'administration', true, NOW()), + (2, 'dr_smith', 'sarah.smith@hospital.com', '$2b$12$xDK9vMsg6XD0wrbp9mTONeqZgViFvQGbUT9HMb2l1aU.nX5ssLnkS', 'doctor', 'cardiology', true, NOW()), + (3, 'nurse_johnson', 'michael.johnson@hospital.com', '$2b$12$tVxonl15Y9xoKXKeBLQcX.mZO7ovvOtfRiI.vqPCqjRyuOVCmazfC', 'nurse', 'emergency', true, NOW()) +ON CONFLICT (username) DO NOTHING; + +-- Reset the sequence to ensure new users get proper IDs +SELECT setval('users_id_seq', (SELECT MAX(id) FROM users)); + +-- Verify users were created +DO $$ +BEGIN + IF (SELECT COUNT(*) FROM users) > 0 THEN + RAISE NOTICE 'Successfully seeded % demo users', (SELECT COUNT(*) FROM users); + RAISE NOTICE 'Demo credentials: admin_wilson/secure_password, dr_smith/secure_password, nurse_johnson/secure_password'; + ELSE + RAISE WARNING 'No users were seeded - check for conflicts or errors'; + END IF; +END $$; diff --git a/python/rag/healthcare-support-portal/docker-compose.yml b/python/rag/healthcare-support-portal/docker-compose.yml new file mode 100644 index 00000000..600bb785 --- /dev/null +++ b/python/rag/healthcare-support-portal/docker-compose.yml @@ -0,0 +1,40 @@ +services: + db: + image: ankane/pgvector + environment: + POSTGRES_DB: healthcare + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - "5432:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres -d healthcare"] + interval: 5s + timeout: 5s + retries: 5 + start_period: 10s + + oso: + container_name: oso_service + image: public.ecr.aws/osohq/dev-server:latest + command: --watch-for-changes /authorization.polar + ports: + - "8080:8080" + volumes: + - type: bind + source: ./authorization.polar + target: /authorization.polar + + migrate: + build: + context: . + dockerfile: Dockerfile.migrate + environment: + DATABASE_URL: postgresql+psycopg2://postgres:postgres@db:5432/healthcare + depends_on: + db: + condition: service_healthy + volumes: + - ./packages/common:/app/packages/common + - ./scripts:/app/scripts + command: /app/scripts/migrate.sh \ No newline at end of file diff --git a/python/rag/healthcare-support-portal/frontend/.env.example b/python/rag/healthcare-support-portal/frontend/.env.example new file mode 100644 index 00000000..b84263d0 --- /dev/null +++ b/python/rag/healthcare-support-portal/frontend/.env.example @@ -0,0 +1,12 @@ +# API Configuration +VITE_API_BASE_URL=http://localhost +VITE_AUTH_SERVICE_PORT=8001 +VITE_PATIENT_SERVICE_PORT=8002 +VITE_RAG_SERVICE_PORT=8003 + +# App Configuration +VITE_APP_NAME="Healthcare Support Portal" +VITE_APP_VERSION="0.1.0" + +# Development +VITE_DEBUG=true \ No newline at end of file diff --git a/python/rag/healthcare-support-portal/frontend/README.md b/python/rag/healthcare-support-portal/frontend/README.md new file mode 100644 index 00000000..40c1db39 --- /dev/null +++ b/python/rag/healthcare-support-portal/frontend/README.md @@ -0,0 +1,187 @@ +# Frontend Service + +React Router 7 + Vite frontend application for the Healthcare Support Portal. + +## Technology Stack + +- **Framework**: React Router 7 (Framework Mode) +- **Build Tool**: Vite 6 +- **Styling**: TailwindCSS v4 (Zero Config) +- **UI Components**: shadcn/ui with Radix UI primitives +- **State Management**: React Context + TanStack Query +- **HTTP Client**: Axios +- **TypeScript**: Full type safety +- **Icons**: Lucide React + +## Features + +- **Authentication**: JWT-based login/signup with role-based access +- **Dashboard**: Role-specific overview with quick actions and stats +- **Patient Management**: CRUD operations for patient records +- **Chat Assistant**: AI-powered medical Q&A with RAG integration +- **Document Management**: Upload, search, and manage medical documents +- **Responsive Design**: Mobile-first design with desktop navigation +- **Role-Based UI**: Different interfaces for doctor/nurse/admin roles +- **Real-time Notifications**: Toast notifications for user feedback + +## Getting Started + +### Prerequisites + +- Node.js 20.19+ (required by Vite 7) +- Backend services running (auth, patient, RAG services) +- PostgreSQL database with healthcare data + +### Installation + +```bash +# Install dependencies +npm install + +# Copy environment file +cp .env.example .env + +# Start development server +npm run dev +``` + +### Environment Variables + +Edit `.env` file: + +```env +# API Configuration +VITE_API_BASE_URL=http://localhost +VITE_AUTH_SERVICE_PORT=8001 +VITE_PATIENT_SERVICE_PORT=8002 +VITE_RAG_SERVICE_PORT=8003 + +# App Configuration +VITE_APP_NAME="Healthcare Support Portal" +VITE_APP_VERSION="0.1.0" + +# Development +VITE_DEBUG=true +``` + +## Development + +### Available Scripts + +```bash +npm run dev # Start development server +npm run build # Build for production +npm run start # Start production server +npm run typecheck # Run TypeScript checks +npm run lint # Run ESLint +``` + +### Key Directories + +``` +src/ +├── components/ # Reusable UI components +│ ├── ui/ # shadcn/ui components +│ └── Navigation.tsx # Main navigation component +├── lib/ # Utilities and configuration +│ ├── api.ts # API client with axios +│ ├── auth.ts # Authentication context +│ ├── types.ts # TypeScript type definitions +│ └── utils.ts # Utility functions +├── routes/ # React Router 7 route components +│ ├── _layout.tsx # Root layout with auth +│ ├── dashboard.tsx # Dashboard page +│ ├── login.tsx # Login page +│ ├── signup.tsx # Registration page +│ ├── chat.tsx # AI chat interface +│ ├── documents.tsx # Document management +│ └── patients/ # Patient management pages +└── styles/ + └── globals.css # TailwindCSS v4 styles +``` + +## Authentication Flow + +1. **Login/Signup**: JWT token stored in localStorage +2. **Route Protection**: `_layout.tsx` checks authentication +3. **API Integration**: Axios interceptors add auth headers +4. **Role-Based Access**: UI adapts based on user role +5. **Token Refresh**: Automatic token refresh before expiration + +## API Integration + +The frontend connects to three backend services: + +- **Auth Service (8001)**: User authentication and management +- **Patient Service (8002)**: Patient CRUD operations +- **RAG Service (8003)**: Document management and AI chat + +API client (`src/lib/api.ts`) provides typed methods for all endpoints. + +## UI Components + +Built with shadcn/ui for consistent, accessible components: + +- **Forms**: Login, signup, patient creation +- **Navigation**: Responsive sidebar with role-based menu items +- **Cards**: Patient cards, document cards, dashboard stats +- **Tables**: Patient lists, document lists (future enhancement) +- **Chat Interface**: Real-time AI conversation with sources +- **Badges**: Role indicators, status badges, department tags + +## Styling + +TailwindCSS v4 with zero configuration: + +- **Custom Theme**: Healthcare-specific colors and spacing +- **Role-Based Styling**: Different colors for doctor/nurse/admin +- **Department Indicators**: Color-coded department borders +- **Responsive Design**: Mobile-first with desktop enhancements +- **Accessibility**: High contrast mode, reduced motion support + +## Deployment + +### Development + +```bash +# Start all services including frontend +./run_all.sh +``` + +Visit http://localhost:3000 + +### Production Build + +```bash +# Build for production +npm run build + +# Start production server +npm run start +``` + +## Demo Credentials + +For testing, use these demo accounts: + +- **Doctor**: `dr_smith` / `secure_password` +- **Nurse**: `nurse_johnson` / `secure_password` +- **Admin**: `admin_doe` / `secure_password` + +## Architecture Notes + +- **React Router 7**: Uses framework mode for enhanced features +- **Vite 6**: Fast development with HMR and optimized builds +- **TailwindCSS v4**: Zero-config setup with CSS-first customization +- **Type Safety**: Full TypeScript coverage for API and UI +- **State Management**: Context for auth, TanStack Query for server state +- **Error Handling**: Comprehensive error boundaries and user feedback + +## Browser Support + +- Chrome 90+ +- Firefox 88+ +- Safari 14+ +- Edge 90+ + +Modern browsers with ES2022 support required. \ No newline at end of file diff --git a/python/rag/healthcare-support-portal/frontend/app/components/Navigation.tsx b/python/rag/healthcare-support-portal/frontend/app/components/Navigation.tsx new file mode 100644 index 00000000..defdfd16 --- /dev/null +++ b/python/rag/healthcare-support-portal/frontend/app/components/Navigation.tsx @@ -0,0 +1,321 @@ +import { useState } from 'react'; +import { Link, useLocation } from 'react-router'; +import { + Home, + Users, + MessageSquare, + FileText, + Settings, + LogOut, + Menu, + X, + Activity, + UserCheck, + ShieldCheck +} from 'lucide-react'; +import type { User } from '@/lib/types'; +import { Button } from '@/components/ui/button'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Badge } from '@/components/ui/badge'; +import { UserSwitcher } from '@/components/UserSwitcher'; +import { cn } from '@/lib/utils'; + +interface NavItem { + name: string; + href: string; + icon: any; + roles?: string[]; +} + +const navigation: NavItem[] = [ + { name: 'Dashboard', href: '/', icon: Home }, + { name: 'Patients', href: '/patients', icon: Users, roles: ['doctor', 'nurse', 'admin'] }, + { name: 'Chat Assistant', href: '/chat', icon: MessageSquare }, + { name: 'Documents', href: '/documents', icon: FileText }, + { name: 'User Management', href: '/users', icon: Users, roles: ['admin'] }, + { name: 'Settings', href: '/settings', icon: Settings, roles: ['admin'] }, +]; + +function getInitials(name: string): string { + return name + .split(' ') + .map(word => word.charAt(0)) + .join('') + .toUpperCase() + .slice(0, 2); +} + +function getRoleIcon(role: string) { + switch (role) { + case 'doctor': + return ; + case 'nurse': + return ; + case 'admin': + return ; + default: + return null; + } +} + +function getRoleBadgeVariant(role: string) { + switch (role) { + case 'doctor': + return 'doctor' as const; + case 'nurse': + return 'nurse' as const; + case 'admin': + return 'admin' as const; + default: + return 'default' as const; + } +} + +function getUserDisplayName(user: User | null): string { + if (!user) return 'Unknown User'; + return user.username || 'Unknown User'; +} + +function hasRole(user: User, roles: string[]): boolean { + return roles.includes(user.role); +} + +interface NavigationProps { + user: User; +} + +export function Navigation({ user }: NavigationProps) { + const [sidebarOpen, setSidebarOpen] = useState(false); + const location = useLocation(); + + const filteredNavigation = navigation.filter(item => + !item.roles || hasRole(user, item.roles) + ); + + const handleLogout = () => { + // Create a form to submit logout + const form = document.createElement('form'); + form.method = 'POST'; + form.action = '/logout'; + document.body.appendChild(form); + form.submit(); + }; + + return ( + <> + {/* Mobile sidebar */} +
+
setSidebarOpen(false)} /> +
+
+
+
+ +
+ + Healthcare Portal + +
+ +
+ + + + {/* User section */} +
+
+ + + {getInitials(user.username)} + +
+

+ {getUserDisplayName(user)} +

+
+ + + {getRoleIcon(user.role)} + {user.role} + + +
+

+ {user.department} +

+
+
+ + {/* User Switcher */} + + + +
+
+
+ + {/* Desktop sidebar */} +
+
+ {/* Logo */} +
+
+ +
+ + Healthcare Portal + +
+ + {/* Navigation */} + +
+
+ + {/* Mobile header */} +
+ + +
+ +
+
+
+ +
+ + Healthcare Portal + +
+ +
+ + + {getInitials(user.username)} + +
+
+
+ + ); +} \ No newline at end of file diff --git a/python/rag/healthcare-support-portal/frontend/app/components/UserSwitcher.tsx b/python/rag/healthcare-support-portal/frontend/app/components/UserSwitcher.tsx new file mode 100644 index 00000000..47ac753e --- /dev/null +++ b/python/rag/healthcare-support-portal/frontend/app/components/UserSwitcher.tsx @@ -0,0 +1,213 @@ +import { useState } from 'react'; +import { useFetcher } from 'react-router'; +import { + Users, + ChevronDown, + UserCheck, + Activity, + ShieldCheck, + RefreshCw +} from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { cn } from '@/lib/utils'; +import type { User } from '@/lib/types'; + +interface DemoUser { + username: string; + password: string; + role: string; + department: string; + description: string; + permissions: string[]; +} + +const DEMO_USERS: DemoUser[] = [ + { + username: 'admin_wilson', + password: 'secure_password', + role: 'admin', + department: 'administration', + description: 'Full system access, can manage all users and documents', + permissions: ['All documents', 'All departments', 'User management', 'System settings'] + }, + { + username: 'dr_smith', + password: 'secure_password', + role: 'doctor', + department: 'cardiology', + description: 'Cardiology specialist with access to patient records and protocols', + permissions: ['Cardiology documents', 'Patient records', 'Medical protocols', 'Chat assistant'] + }, + { + username: 'nurse_johnson', + password: 'secure_password', + role: 'nurse', + department: 'emergency', + description: 'Emergency department nurse with access to emergency protocols', + permissions: ['Emergency documents', 'Patient care protocols', 'Chat assistant'] + } +]; + +function getRoleIcon(role: string) { + switch (role) { + case 'doctor': + return ; + case 'nurse': + return ; + case 'admin': + return ; + default: + return null; + } +} + +function getRoleBadgeVariant(role: string) { + switch (role) { + case 'doctor': + return 'doctor' as const; + case 'nurse': + return 'nurse' as const; + case 'admin': + return 'admin' as const; + default: + return 'default' as const; + } +} + +interface UserSwitcherProps { + currentUser: User; +} + +export function UserSwitcher({ currentUser }: UserSwitcherProps) { + const [isOpen, setIsOpen] = useState(false); + const fetcher = useFetcher(); + const isSwitching = fetcher.state === 'submitting'; + + const handleUserSwitch = async (user: DemoUser) => { + // Create form data for login + const formData = new FormData(); + formData.append('username', user.username); + formData.append('password', user.password); + + // Submit login form + fetcher.submit(formData, { + method: 'post', + action: '/login' + }); + }; + + const isCurrentUser = (user: DemoUser) => { + return user.username === currentUser.username; + }; + + return ( +
+ {/* Current User Display */} + + + {/* User Selection Dropdown */} + {isOpen && ( + + + + + Switch User Role + + + Quickly switch between different user roles to test permissions and document access + + + + {DEMO_USERS.map((user) => ( +
{ + if (!isCurrentUser(user)) { + handleUserSwitch(user); + } + setIsOpen(false); + }} + > +
+
+
+ {user.username} + + + {getRoleIcon(user.role)} + {user.role} + + +
+

{user.description}

+
+ Department: {user.department} +
+
+ Permissions: +
    + {user.permissions.map((permission, idx) => ( +
  • {permission}
  • + ))} +
+
+
+ {isCurrentUser(user) && ( +
+ + Current + +
+ )} +
+
+ ))} + + {/* Info Section */} +
+

+ 💡 Pro Tip: Use this switcher to test how the RAG chat assistant + responds differently based on user permissions. Each role has access to different + documents and departments. +

+
+
+
+ )} + + {/* Loading Overlay */} + {isSwitching && ( +
+
+ + Switching user... +
+
+ )} +
+ ); +} diff --git a/python/rag/healthcare-support-portal/frontend/app/components/documents/DocumentForm.tsx b/python/rag/healthcare-support-portal/frontend/app/components/documents/DocumentForm.tsx new file mode 100644 index 00000000..24d742ba --- /dev/null +++ b/python/rag/healthcare-support-portal/frontend/app/components/documents/DocumentForm.tsx @@ -0,0 +1,281 @@ +import { useState, useEffect } from 'react'; +import { Form, useLoaderData } from 'react-router'; +import { useForm, getFormProps, getInputProps, getSelectProps, getTextareaProps } from '@conform-to/react'; +import { parseWithZod } from '@conform-to/zod'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Textarea } from '@/components/ui/textarea'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Checkbox } from '@/components/ui/checkbox'; +import { ArrowLeft, Save, FileText, Building, User, AlertTriangle, BookOpen } from 'lucide-react'; +import { Link } from 'react-router'; +import { documentCreateSchema, documentUpdateSchema } from '@/lib/schemas'; +import type { Document, User as UserType, Patient } from '@/lib/types'; + +interface DocumentFormProps { + isEdit: boolean; + document?: Document; + patients?: Patient[]; +} + +const departments = [ + { value: 'cardiology', label: 'Cardiology' }, + { value: 'neurology', label: 'Neurology' }, + { value: 'pediatrics', label: 'Pediatrics' }, + { value: 'oncology', label: 'Oncology' }, + { value: 'emergency', label: 'Emergency' }, + { value: 'endocrinology', label: 'Endocrinology' }, + { value: 'obgyn', label: 'OB/GYN' }, + { value: 'general', label: 'General Medicine' }, +]; + +const documentTypes = [ + { value: 'protocol', label: 'Protocol', icon: '📋' }, + { value: 'policy', label: 'Policy', icon: '📜' }, + { value: 'guideline', label: 'Guideline', icon: '📖' }, + { value: 'research', label: 'Research', icon: '🔬' }, + { value: 'report', label: 'Report', icon: '📊' }, + { value: 'medical_record', label: 'Medical Record', icon: '📝' }, +]; + +export function DocumentForm({ isEdit, document, patients = [] }: DocumentFormProps) { + const [selectedDepartment, setSelectedDepartment] = useState(document?.department || ''); + const [selectedPatientId, setSelectedPatientId] = useState( + document?.patient_id?.toString() || 'none' + ); + const [selectedDocumentType, setSelectedDocumentType] = useState(document?.document_type || ''); + const [isSensitive, setIsSensitive] = useState(document?.is_sensitive || false); + + const schema = isEdit ? documentUpdateSchema : documentCreateSchema; + + const [form, fields] = useForm({ + onValidate({ formData }) { + return parseWithZod(formData, { schema }); + }, + defaultValue: isEdit && document ? { + title: document.title, + content: document.content, + document_type: document.document_type, + patient_id: document.patient_id?.toString() || 'none', + department: document.department, + is_sensitive: document.is_sensitive.toString(), + } : undefined, + }); + + // Filter patients by selected department + const availablePatients = patients.filter(patient => + !selectedDepartment || patient.department === selectedDepartment + ); + + return ( +
+ {/* Back Button */} +
+ +
+ + + + + + {isEdit ? 'Edit Document' : 'Create New Document'} + + + {isEdit + ? 'Update document information and content' + : 'Create a new document for the Healthcare Support Portal' + } + + + +
+
+ {/* Document Title */} +
+ + + {fields.title.errors && ( +

{fields.title.errors[0]}

+ )} +
+ + {/* Document Type */} +
+ + + + {fields.document_type.errors && ( +

{fields.document_type.errors[0]}

+ )} +
+ + {/* Department */} +
+ + + + {fields.department.errors && ( +

{fields.department.errors[0]}

+ )} +
+ + {/* Associated Patient */} +
+ + + + {fields.patient_id.errors && ( +

{fields.patient_id.errors[0]}

+ )} +
+ + {/* Sensitive Document Checkbox */} +
+
+ setIsSensitive(checked as boolean)} + /> + +
+ +

+ Sensitive documents have restricted access based on role and department permissions. +

+
+ + {/* Document Content */} +
+ +