Skip to content

kspswati/HEAL_AI

ย 
ย 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

31 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

HEAL.AI - Healthcare Expenses Analyzer & Logger

๐Ÿ† 2nd Place Winner - Devlabs Hackathon

An AI-powered healthcare financial assistant that empowers patients to understand their medical bills and insurance policies with unprecedented clarity

FastAPI React TypeScript Vite Google Gemini Python Tailwind CSS


๐ŸŽฏ Overview

HEAL.AI is a comprehensive healthcare financial assistant that leverages cutting-edge AI technology to help patients navigate the complex world of medical insurance. Built during the Devlabs Hackathon where it secured 2nd place, this platform combines advanced document analysis, RAG-powered conversational AI, and intelligent bill verification to give users unprecedented clarity and control over their healthcare expenses.

๐ŸŒŸ Problem Statement

80% of medical bills contain errors - Patients struggle to understand:

  • What part is covered by insurance?
  • What's truly owed out-of-pocket?
  • Are there errors or duplicate charges?
  • How to dispute billing discrepancies?

Navigating medical billing and health insurance is confusing and stressful for most patients, leading to overpayment and financial stress.

๐ŸŒŸ Key Features

  • ๐Ÿ“„ AI-Powered Insurance Analysis - Upload insurance cards or policy documents to automatically extract deductibles, out-of-pocket maximums, copays, and comprehensive coverage details
  • ๐Ÿ’ฐ Smart Medical Bill Checker - Analyze medical bills against your insurance policy to identify billing errors, coverage discrepancies, and potential disputes with detailed financial breakdowns
  • ๐Ÿค– RAG-Powered Conversational AI - Ask natural language questions about your insurance policy and get accurate, source-attributed answers through an intuitive chat interface
  • ๐Ÿ“ง Automated Dispute Generation - Generate FDCPA-compliant dispute emails for billing errors with professional templates
  • ๐Ÿ” Advanced Semantic Search - Vector-based search across your policy documents with confidence scoring
  • ๐Ÿ“Š Comprehensive Dashboard - Modern, responsive interface with insurance summaries, bill history, and emergency QR codes
  • ๐Ÿ’ฌ Persistent Chat Sessions - Full conversation history with context-aware responses
  • ๐Ÿฅ Emergency QR Code - Instant access to critical medical information for emergency situations

๐Ÿ—๏ธ Architecture

Tech Stack

Frontend (Modern React SPA)

  • React 18.3 - Latest React with concurrent features and improved performance
  • TypeScript 5.8 - Full type safety and enhanced developer experience
  • Vite 5.4 - Lightning-fast build tool and development server
  • Tailwind CSS 3.4 - Utility-first CSS framework with custom design system
  • shadcn/ui - Modern, accessible component library with 50+ components
  • React Router 6 - Client-side routing with nested routes
  • TanStack Query - Powerful data fetching and caching
  • React Hook Form - Performant forms with validation
  • Lucide React - Beautiful, customizable icons
  • React Markdown - Rich markdown rendering with syntax highlighting

Backend (Python FastAPI)

  • FastAPI 0.109 - Modern, high-performance Python web framework
  • Google Gemini 2.5 - State-of-the-art multimodal AI (Flash & Pro models)
  • SQLite - Efficient local database with comprehensive schema
  • scikit-learn - Vector similarity and machine learning operations
  • pytesseract - OCR for image processing
  • PyMuPDF - PDF text extraction and processing
  • NLTK - Natural language processing and tokenization
  • Pydantic - Data validation and serialization

AI/ML Pipeline

  • Retrieval-Augmented Generation (RAG) - Context-aware document question answering
  • Vector Embeddings - Google's text-embedding-004 (768 dimensions)
  • Semantic Search - Cosine similarity-based retrieval with confidence scoring
  • Document Chunking - Intelligent text segmentation with 2-sentence overlap
  • Multimodal Analysis - Simultaneous processing of images and text

๐Ÿ“ Project Structure

HEAL/
โ”œโ”€โ”€ backend/                             # Python FastAPI Backend
โ”‚   โ”œโ”€โ”€ main.py                          # Main FastAPI application (2000+ lines)
โ”‚   โ”œโ”€โ”€ langchain_main.py                # LangChain integration server
โ”‚   โ”œโ”€โ”€ genkit_api.py                    # Genkit-style API patterns
โ”‚   โ”œโ”€โ”€ ai/                              # AI Processing Layer
โ”‚   โ”‚   โ”œโ”€โ”€ flows/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ policy_analysis.py       # Insurance policy extraction flows
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ chatbot.py               # RAG chatbot implementation
โ”‚   โ”‚   โ”œโ”€โ”€ embedder.py                  # Gemini embeddings with fallback
โ”‚   โ”‚   โ”œโ”€โ”€ genkit_config.py             # AI service configuration
โ”‚   โ”‚   โ””โ”€โ”€ schemas.py                   # Pydantic data models
โ”‚   โ”œโ”€โ”€ rag/                             # RAG System Components
โ”‚   โ”‚   โ”œโ”€โ”€ document_processor.py        # Text extraction & intelligent chunking
โ”‚   โ”‚   โ”œโ”€โ”€ retriever.py                 # Vector similarity search engine
โ”‚   โ”‚   โ””โ”€โ”€ chatbot.py                   # Context-aware RAG chatbot
โ”‚   โ”œโ”€โ”€ database/                        # Database Layer
โ”‚   โ”‚   โ””โ”€โ”€ schema.py                    # SQLite schema & connection management
โ”‚   โ”œโ”€โ”€ services/                        # Business Logic Services
โ”‚   โ”‚   โ”œโ”€โ”€ gemini_service.py            # Gemini API wrapper & utilities
โ”‚   โ”‚   โ””โ”€โ”€ bill_analysis_service.py     # Medical bill analysis engine
โ”‚   โ”œโ”€โ”€ uploads/                         # File storage directory
โ”‚   โ”œโ”€โ”€ requirements.txt                 # Python dependencies
โ”‚   โ””โ”€โ”€ venv/                            # Virtual environment
โ”œโ”€โ”€ frontend/ (Git Submodule)            # Modern React TypeScript Frontend
โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”œโ”€โ”€ App.tsx                      # Main application component
โ”‚   โ”‚   โ”œโ”€โ”€ main.tsx                     # Vite entry point
โ”‚   โ”‚   โ”œโ”€โ”€ components/                  # Reusable UI Components
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ ui/                      # shadcn/ui component library (50+ components)
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ layout/                  # Layout components (Header, Layout)
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ sections/                # Page sections (Hero, Features, Upload)
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ BillSummaryCard.tsx      # Bill analysis display (374 lines)
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ PolicySummary.tsx        # Insurance policy visualization
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ DisputeEmailModal.tsx    # Dispute generation interface
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ BillAnalysisLoader.tsx   # Loading states for analysis
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ MarkdownMessage.tsx      # Rich text message rendering
โ”‚   โ”‚   โ”œโ”€โ”€ pages/                       # Application Pages
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Index.tsx                # Landing page with hero section
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Dashboard.tsx            # Main dashboard with tabs
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Chat.tsx                 # AI chat interface
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ BillSummary.tsx          # Detailed bill analysis view
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ Admin.tsx                # Admin panel for data management
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ NotFound.tsx             # 404 error page
โ”‚   โ”‚   โ”œโ”€โ”€ contexts/                    # React Context Providers
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ AppContext.tsx           # Global application state
โ”‚   โ”‚   โ”œโ”€โ”€ services/                    # API Integration Layer
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ api.ts                   # Comprehensive API service (420+ lines)
โ”‚   โ”‚   โ”œโ”€โ”€ hooks/                       # Custom React Hooks
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ use-toast.ts             # Toast notification system
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ use-mobile.tsx           # Mobile responsive utilities
โ”‚   โ”‚   โ””โ”€โ”€ lib/                         # Utility Functions
โ”‚   โ”‚       โ””โ”€โ”€ utils.ts                 # Common utilities and helpers
โ”‚   โ”œโ”€โ”€ public/                          # Static Assets
โ”‚   โ”‚   โ”œโ”€โ”€ favicon.ico                  # Application favicon
โ”‚   โ”‚   โ””โ”€โ”€ placeholder.svg              # Placeholder images
โ”‚   โ”œโ”€โ”€ dist/                            # Production build output
โ”‚   โ”œโ”€โ”€ package.json                     # Node.js dependencies & scripts
โ”‚   โ”œโ”€โ”€ tailwind.config.ts               # Tailwind CSS configuration
โ”‚   โ”œโ”€โ”€ vite.config.ts                   # Vite build configuration
โ”‚   โ”œโ”€โ”€ tsconfig.json                    # TypeScript configuration
โ”‚   โ””โ”€โ”€ components.json                  # shadcn/ui component configuration
โ”œโ”€โ”€ docs/                                # Comprehensive Documentation
โ”‚   โ”œโ”€โ”€ RAG_IMPLEMENTATION_GUIDE.md      # RAG system implementation details
โ”‚   โ”œโ”€โ”€ BACKEND_SUCCESS_SUMMARY.md       # Backend development summary
โ”‚   โ”œโ”€โ”€ IMPLEMENTATION_SUMMARY.md        # Overall project implementation
โ”‚   โ”œโ”€โ”€ GEMINI_SETUP.md                  # Google Gemini API setup guide
โ”‚   โ”œโ”€โ”€ GENKIT_MIGRATION_GUIDE.md        # Genkit pattern migration
โ”‚   โ””โ”€โ”€ CHAT_IMPROVEMENTS_SUMMARY.md     # Chat system enhancements
โ”œโ”€โ”€ .gitmodules                          # Git submodule configuration
โ””โ”€โ”€ README.md                            # This comprehensive guide

๐Ÿš€ Getting Started

Prerequisites

  • Python 3.11 or higher
  • Node.js 16+ and npm
  • Google Gemini API key (Get one here)

Installation

1. Clone the Repository

git clone https://github.com/naman-ranka/HEAL_AI_Backend.git
cd HEAL_AI_Backend

2. Backend Setup

cd backend

# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Configure environment variables
cp env.example .env
# Edit .env and add your GEMINI_API_KEY

3. Frontend Setup

# Initialize submodules (if cloning fresh)
git submodule update --init --recursive

cd frontend

# Install dependencies
npm install

# Or using alternative package managers:
# yarn install
# pnpm install
# bun install

Configuration

Create a .env file in the backend directory:

GEMINI_API_KEY=your_api_key_here
ENVIRONMENT=development

Running the Application

Start Backend Server

cd backend

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate

# Start the FastAPI server
python main.py
# Or using uvicorn directly:
# uvicorn main:app --reload --host 0.0.0.0 --port 8000

Backend runs on http://localhost:8000

  • API Documentation: http://localhost:8000/docs
  • Alternative docs: http://localhost:8000/redoc

Start Frontend Development Server

cd frontend

# Start Vite development server
npm run dev
# Or using alternative package managers:
# yarn dev
# pnpm dev
# bun dev

# For production build:
# npm run build
# npm run preview

Frontend runs on http://localhost:8080 (Vite default)

  • Hot module replacement enabled
  • TypeScript compilation
  • Tailwind CSS processing

๐Ÿ“ก API Endpoints

Document Analysis

Method Endpoint Description
POST /upload Upload and analyze insurance policy documents
POST /summarize Generate comprehensive document summary
GET /documents List all uploaded documents
GET /documents/{id} Get specific document details

Bill Checker

Method Endpoint Description
POST /bill-checker/upload Upload medical bill for analysis
POST /bill-checker/analyze Analyze bill against insurance policy
GET /bill-checker/analysis/{id} Retrieve analysis results
POST /bill-checker/analysis/{id}/dispute Generate FDCPA-compliant dispute email
GET /bill-checker/history Get bill analysis history

RAG Chat System

Method Endpoint Description
POST /chat/sessions Create new chat session
POST /chat/sessions/{id}/messages Send message to chatbot
GET /chat/sessions/{id}/history Get conversation history
DELETE /chat/sessions/{id} Delete chat session
GET /chat/sessions List all sessions

System

Method Endpoint Description
GET / API information
GET /health Health check with AI service status
GET /models Available AI models

๐Ÿ’ก How It Works

1. Policy Analysis Pipeline

Upload Document โ†’ Text Extraction (OCR/PDF) โ†’ Gemini Analysis โ†’
Structured Extraction โ†’ Confidence Scoring โ†’ Database Storage
  • Supports images (JPEG, PNG) and PDF documents
  • Extracts: policyholder info, coverage costs, common services, prescriptions
  • Returns structured JSON with confidence scores

2. RAG (Retrieval-Augmented Generation) System

Document Upload โ†’ Text Chunking (750 words) โ†’ Embedding Generation (768-dim) โ†’
Vector Storage โ†’ Query Processing โ†’ Semantic Search โ†’ Context Building โ†’
AI Response Generation โ†’ Source Attribution

Features:

  • Intelligent chunking with 2-sentence overlap
  • Top-k retrieval with configurable thresholds
  • Conversation history integration (last 6 messages)
  • Source attribution showing which document sections informed the response

3. Bill Analysis

Upload Bill + Policy โ†’ Multimodal Gemini Analysis โ†’
Financial Breakdown โ†’ Coverage Analysis โ†’ Discrepancy Detection โ†’
Dispute Recommendations
  • Identifies billing errors and coverage issues
  • Calculates patient responsibility
  • Generates professional dispute emails

๐ŸŽจ Features in Detail

Modern Frontend Experience

  • Responsive Design - Mobile-first approach with adaptive layouts
  • Dark/Light Mode - System preference detection with manual toggle
  • Progressive Loading - Skeleton screens and optimistic updates
  • Real-time Updates - Live chat interface with typing indicators
  • Accessibility - WCAG 2.1 compliant with keyboard navigation
  • Component Library - 50+ reusable shadcn/ui components
  • Type Safety - Full TypeScript coverage with strict mode
  • State Management - React Context with optimistic updates

Advanced AI Capabilities

  • Multimodal Analysis - Processes both images and text simultaneously
  • Vector Embeddings - Google's latest text-embedding-004 model (768 dimensions)
  • Fallback Handling - Graceful degradation when AI services are unavailable
  • Confidence Scoring - All responses include reliability metrics (0-1 scale)
  • Semantic Search - Context-aware document retrieval with similarity thresholds
  • Conversation Memory - Maintains context across chat sessions
  • Source Attribution - Links responses to specific document sections

Comprehensive Database Schema

-- Core Tables
policies              # Insurance policy metadata and analysis results
documents             # Uploaded documents with file information
document_chunks       # Text chunks with vector embeddings (768-dim)
chat_sessions         # User chat sessions with document context
chat_messages         # Complete conversation history
bill_analyses         # Medical bill analysis results and recommendations
rag_queries           # RAG query logs with performance metrics

-- Analytics Tables
upload_logs           # File upload tracking and error logs
embedding_stats       # Vector embedding performance metrics
user_interactions     # User behavior analytics

Developer Experience

  • Hot Reload - Instant updates during development (Vite HMR)
  • Debug Endpoints - Comprehensive debugging tools for development
  • Admin Panel - Database management and cleanup utilities in frontend
  • Comprehensive Logging - Structured logging throughout the application
  • Type Safety - Pydantic models (backend) + TypeScript interfaces (frontend)
  • API Documentation - Auto-generated OpenAPI/Swagger docs
  • Error Boundaries - Graceful error handling with user-friendly messages

๐Ÿ”ง Configuration Options

Environment Variables

Variable Description Default
GEMINI_API_KEY Google Gemini API key Required
ENVIRONMENT Application environment development

RAG Configuration

  • Chunk Size: 750 words
  • Chunk Overlap: 2 sentences
  • Embedding Dimensions: 768
  • Top-k Results: Configurable (default: 5)
  • Similarity Threshold: Configurable (default: 0.3)

๐Ÿ“š Use Cases & User Journey

1. New User Onboarding

  • Upload insurance card or policy document via drag-and-drop interface
  • AI extracts key information (deductible, copay, out-of-pocket max)
  • View comprehensive policy summary in dashboard
  • Access emergency QR code for critical medical information

2. Medical Bill Analysis

  • Upload medical bill (PDF, image, or photo)
  • AI analyzes bill against insurance policy
  • Receive detailed financial breakdown with coverage analysis
  • Identify potential billing errors or discrepancies
  • Generate professional dispute emails if needed

3. Interactive Policy Consultation

  • Ask natural language questions about coverage
  • Get instant, source-attributed answers from AI chatbot
  • Explore coverage scenarios for planned procedures
  • Understand network restrictions and referral requirements

4. Ongoing Healthcare Management

  • Track bill analysis history with searchable interface
  • Monitor healthcare spending patterns
  • Access emergency medical information via QR code
  • Maintain conversation history for reference

5. Administrative Tasks

  • Generate FDCPA-compliant dispute letters
  • Export analysis results for record-keeping
  • Manage multiple insurance policies (family coverage)
  • Reset and clean data through admin panel

๐Ÿ› ๏ธ Development

Running Tests

# Backend tests
cd backend
python test_backend.py
python test_langchain_complete.py
python test_genkit_system.py

# Frontend tests (if configured)
cd frontend
npm run test
npm run test:coverage

Development Tools

Backend Debug Endpoints

  • /debug/upload-process/{id} - Debug upload flow
  • /debug/latest-upload - Latest document information
  • /debug/embeddings/stats - Embedding statistics
  • /debug/chat/context - Test chat context building
  • /admin/database-info - Database statistics
  • /admin/reset-all - Reset all data (development only)

Frontend Development

cd frontend

# Development server with hot reload
npm run dev

# Type checking
npm run type-check

# Linting
npm run lint

# Build for production
npm run build

# Preview production build
npm run preview

Git Submodule Management

# Update frontend submodule to latest
git submodule update --remote frontend

# Pull latest changes including submodules
git pull --recurse-submodules

# Clone with submodules
git clone --recurse-submodules <repository-url>

๐Ÿšง Known Limitations

  • Requires active internet connection for AI features
  • OCR accuracy depends on image quality
  • Response time varies based on document size
  • SQLite limits concurrent write operations

๐Ÿ”ฎ Future Enhancements

Frontend Improvements

  • Progressive Web App (PWA) support
  • Offline functionality with service workers
  • Advanced data visualization with charts
  • Multi-language internationalization (i18n)
  • Enhanced accessibility features
  • Mobile-optimized touch interactions

Backend & AI Enhancements

  • Multi-user authentication and authorization
  • Cloud database integration (PostgreSQL/MongoDB)
  • Integration with healthcare provider APIs
  • Advanced analytics and reporting dashboard
  • Export functionality (PDF/Excel/CSV)
  • Real-time collaboration features
  • Enhanced OCR with multiple AI models
  • Voice input and audio responses

System Architecture

  • Microservices architecture
  • Docker containerization
  • Kubernetes deployment
  • CI/CD pipeline automation
  • Performance monitoring and alerting
  • Automated testing suite expansion

๐Ÿ“„ License

This project was developed for the Devlabs Hackathon. All rights reserved.


๐Ÿ‘จโ€๐Ÿ’ป Author

Naman Ranka


๐Ÿ† Acknowledgments

  • 2nd Place at Devlabs Hackathon
  • Built with Google Gemini AI
  • Inspired by Genkit AI framework patterns
  • Special thanks to the Devlabs community

๐Ÿ“ž Support

For questions or issues, please open an issue on GitHub or contact the development team.


Made with โค๏ธ for the Devlabs Hackathon

Empowering patients through AI-powered healthcare transparency

About

HEAL.AI is an AI-powered application that explains medical bills and insurance in simple terms, detects errors, and provides instant chat support to help users confidently manage healthcare costs.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • TypeScript 65.5%
  • Python 32.5%
  • CSS 0.9%
  • HTML 0.5%
  • JavaScript 0.2%
  • Batchfile 0.2%
  • Other 0.2%