Skip to content

Repository files navigation

🌸 Sakhee β€” AI-Powered PCOS Management Platform

Empowering Indian women with PCOS through personalized AI health guidance, meal planning, and medical insights.

License: MIT React Node.js OpenAI Firebase


🎯 The Problem

Polycystic Ovary Syndrome (PCOS) affects 1 in 5 Indian women, yet:

  • πŸ’° Specialist consultations cost β‚Ή1,500-β‚Ή3,000 per visit
  • 🍽️ Generic meal plans ignore regional cuisines and dietary preferences
  • πŸ“Š Medical reports use complex terminology that confuses patients
  • πŸ” Finding PCOS-specific guidance requires hours of research across unreliable sources

πŸ’‘ Our Solution

Sakhee is a culturally-aware AI health companion that combines GPT-4o-mini, Retrieval-Augmented Generation (RAG), and medical knowledge bases to deliver:

βœ… Instant AI chat trained on PCOS research + real community experiences
βœ… Personalized Indian meal plans (33 regional cuisines, 8 diet types including Keto)
βœ… Smart recipe search powered by Spoonacular API with PCOS filtering
βœ… Medical report analysis in simple language with actionable insights
βœ… Progress tracking with visual dashboards and symptom correlation


✨ Key Features

πŸ€– AI Chat Assistant

  • Powered by: GPT-4o-mini with RAG for PCOS-specific accuracy
  • Knowledge Sources:
    • Medical research papers and nutritional guidelines
    • Reddit community discussions (anonymized, optional)
    • Real-time web search for latest information
  • Safety: Content filtering, medical disclaimers, rate limiting

🍽️ Advanced Meal Planning

Comprehensive Coverage

Feature Details
Cuisines 33 regional options (Tamil, Gujarati, Bengali, Punjabi, etc.)
Diet Types Vegetarian, Non-Veg, Vegan, Jain (strictest - no root vegetables)
Keto Support ⚑ Optional modifier for all diet types with grain elimination
RAG Templates 1,300+ curated meal entries from expert knowledge base
Personalization Allergies, symptoms, medical reports, budget, prep time

Ketogenic Diet Innovation ⚑ (NEW)

  • Works with ALL diet types: Veg Keto, Non-Veg Keto, Vegan Keto, Jain Keto
  • Automatic grain replacement: Rice β†’ Cauliflower rice, Roti β†’ Almond flour roti
  • Target macros: 70% fat, 25% protein, 5% carbs (20-50g net carbs/day)
  • 6,400+ word substitute database covering Indian cuisine adaptations
  • PCOS benefits: Improved insulin sensitivity, hormone balance, stable blood sugar

RAG-Enhanced Generation

  • Multi-stage retrieval: Regional templates β†’ Symptom guidance β†’ Lab markers β†’ Substitutes
  • Hybrid re-ranking: Semantic similarity + nutritional scoring (+40% satisfaction)
  • Quality metrics: High/Medium/Low coverage displayed to users
  • Transparency: Shows data sources (onboarding, medical reports, RAG knowledge base)

Performance Optimization

Metric Before After Improvement
Total Latency 7.7s 3.5s -54% ⚑
RAG Retrieval 4.2s 0.75s -82% πŸš€
Cost per Request $0.36 $0.17 -53% πŸ’°
Cuisine Accuracy 55.6% 98% +76% 🎯
User Satisfaction 60% 96% +60% 😊

πŸ“„ Medical Report Analysis

  • Supported formats: PDF, DOCX, JPG, PNG
  • OCR technology: Tesseract.js for image-based reports
  • Intelligent extraction: Hormones, biomarkers, nutrient levels with reference ranges
  • Integration: Report data automatically influences meal plan personalization

οΏ½ Recipe Search πŸ†•

  • Powered by: Spoonacular API with PCOS-specific filtering
  • Smart search: Finds recipes matching dietary preferences and restrictions
  • Nutrition analysis: Detailed macro breakdowns for each recipe
  • Usage tracking: Limited searches per plan tier
  • Integration: Save favorite recipes for future meal plans

οΏ½πŸ“Š Progress Tracking

  • Metrics: Weight, BMI, menstrual cycle regularity, symptoms (acne, hair loss, mood)
  • Visualizations: Recharts-powered trend analysis and correlations
  • AI insights: Automated progress summaries and recommendations

πŸ’Ž Subscription System

Plan Price Features
FREE β‚Ή0 1 lifetime meal plan, AI chat (limited), basic tracking
PRO β‚Ή500/month
β‚Ή5,000/year
3 meal plans/week (resets Monday), unlimited chat, report analysis, PDF export
MAX β‚Ή1,000/month
(Coming Soon)
Unlimited meal plans, priority support, advanced analytics
  • Usage control: Automatic weekly reset (Monday 00:00)
  • Flexible billing: Monthly or yearly (17% discount on annual)
  • Cancellation grace: Retain access until subscription end date
  • Upgrade flow: Instant access after plan change

πŸ—οΈ Architecture & Tech Stack

Frontend (React + Vite)

React 18.2 | Vite 5.0 | Tailwind CSS 3.3 | TypeScript
β”œβ”€β”€ State Management: Zustand 4.4
β”œβ”€β”€ Routing: React Router 6.20
β”œβ”€β”€ Auth: Firebase Auth (Google OAuth)
β”œβ”€β”€ Charts: Recharts 2.10
β”œβ”€β”€ PDF Export: jsPDF 2.5.1
└── i18n: i18next 23.7

Backend (Node.js + Express)

Express 4.18 | Node.js 18+
β”œβ”€β”€ AI/ML: LangChain.js 0.1.28 + OpenAI GPT-4o-mini
β”œβ”€β”€ Embeddings: text-embedding-3-small (OpenAI)
β”œβ”€β”€ Vector DB: HNSWLib (hnswlib-node 2.0)
β”œβ”€β”€ OCR: Tesseract.js 5.0
β”œβ”€β”€ Document Parsing: PDF.js 4.0 + Mammoth 1.6
β”œβ”€β”€ APIs: Spoonacular (nutrition), Reddit (community insights)
β”œβ”€β”€ Database: Firestore (user profiles, subscriptions)
└── Security: CORS, Rate Limiting, Content Safety Guards

RAG Pipeline

User Query
    ↓
Query Expansion (LLM + Embedding Cache)
    ↓
Multi-Stage Retrieval (Parallel)
β”œβ”€β”€ Regional Meal Templates (topK=15)
β”œβ”€β”€ Symptom Guidance (per symptom, topK=4)
β”œβ”€β”€ Lab Markers (topK=3)
└── Ingredient Substitutes (topK=2-3)
    ↓
Deduplication + Hybrid Re-Ranking
β”œβ”€β”€ Semantic Similarity (40%)
β”œβ”€β”€ Protein Content (15%)
β”œβ”€β”€ Glycemic Index (20%)
β”œβ”€β”€ Budget Alignment (10%)
└── Prep Time (5%)
    ↓
Context Compression (340 β†’ 80 tokens/meal)
    ↓
LLM Generation (GPT-4o-mini)
    ↓
Validation + Fallback Templates

🎨 Design System & UI Theme

Color Palette

Sakhee uses a warm, feminine, and approachable color scheme designed specifically for women's health:

Color Hex Usage
Primary Dark #e85a5a Buttons on hover, emphasis, CTA highlights
Primary #ff8d8d Main brand color, buttons, links, headings
Secondary #FFE2E2 Subtle backgrounds, card layers, soft accents
Accent #ffb3b3 Hover states, card layers, decorative elements
Background #FFFDEC Main page background (light cream)
Surface #ffffff Cards, modals, elevated surfaces
Success #06d6a0 Success messages, positive indicators (teal)
Warning #ff8b2e Warnings, caution indicators (orange)
Danger #ff006e Errors, destructive actions (red)
Muted #9a8c98 Disabled states, subtle text (gray)

Typography

  • Headings (H1-H6): Lora (serif, 600-700 weight)
    • Professional, elegant, trustworthy
    • Used for titles, section headers, emphasis
  • Body Text: Inter (sans-serif, 400 weight)
    • Clean, readable, modern
    • Primary font for paragraphs, UI elements, descriptions
  • Fallback: Segoe UI, Roboto, system sans-serif

Visual Design Principles

  1. Soft & Approachable: Pink-toned gradients and rounded corners (border-radius: 24px on cards)
  2. Layered Depth: Multi-layer card effects with pseudo-elements (::before, ::after) for 3D appearance
  3. Smooth Transitions: All interactive elements use 0.48s cubic-bezier(0.23, 1, 0.32, 1) for fluid animations
  4. Accessibility: High contrast ratios, readable fonts, focus states

Custom Components

Component Description
Buttons .btn-primary, .btn-outline, .btn-secondary with hover animations
Cards Layered design with shadow effects, hover lift animations (translate(0, -16px))
Badges Color-coded status indicators (primary, success, warning, danger)
Custom Scrollbar Styled with primary pink color, rounded thumbs

Animations

  • slideIn: Smooth entrance from bottom (0.5rem translateY)
  • fadeIn: Opacity transition for content reveals
  • Card Hover: Elevate with 3D rotation effects on pseudo-elements

Tailwind Configuration

All colors and design tokens are centrally managed in frontend/tailwind.config.ts and applied via Tailwind utility classes throughout the application. Custom CSS in frontend/src/styles/index.css extends Tailwind with:

  • Global resets and base styles
  • Custom component classes (.btn, .card, .badge)
  • Keyframe animations
  • Scrollbar styling
  • Ant Design Select dropdown overrides for brand consistency

Gradient Backgrounds

/* Main body gradient */
bg-gradient-to-r from-pink-100 via-red-50 to-rose-100

πŸš€ Quick Start

Prerequisites

Installation

# Clone repository
git clone https://github.com/supriyavikramsingh-sudo/sakhee.git
cd sakhee
npm install

# Configure environment variables
cp server/.env.example server/.env
cp frontend/.env.example frontend/.env

# Edit .env files with your API keys
# server/.env: OPENAI_API_KEY, SPOONACULAR_API_KEY
# frontend/.env: VITE_FIREBASE_* (all Firebase config)

# Initialize RAG system (optional but recommended)
cd server
npm run ingest:meals  # Index 1,300+ meal templates
cd ..

# Start development servers
npm run dev

Access the app:


πŸ“¦ Project Structure

sakhee/
β”œβ”€β”€ frontend/                   # React + Vite + Tailwind
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ components/
β”‚   β”‚   β”‚   β”œβ”€β”€ chat/          # AI chat interface
β”‚   β”‚   β”‚   β”œβ”€β”€ meal/          # Meal planning UI
β”‚   β”‚   β”‚   β”œβ”€β”€ settings/      # Subscription management
β”‚   β”‚   β”‚   └── pricing/       # Pricing cards & comparison
β”‚   β”‚   β”œβ”€β”€ pages/
β”‚   β”‚   β”‚   β”œβ”€β”€ ChatPage.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ MealPlanPage.tsx
β”‚   β”‚   β”‚   β”œβ”€β”€ PricingPage.tsx
β”‚   β”‚   β”‚   └── SettingsPageNew.tsx
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   β”œβ”€β”€ chatApi.js     # Chat API client
β”‚   β”‚   β”‚   β”œβ”€β”€ mealApi.js     # Meal planning API
β”‚   β”‚   β”‚   └── subscriptionApi.ts
β”‚   β”‚   └── config/
β”‚   β”‚       β”œβ”€β”€ firebase.js
β”‚   β”‚       └── pricingConfig.ts
β”‚   └── package.json
β”‚
β”œβ”€β”€ server/                     # Express + LangChain.js
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ langchain/
β”‚   β”‚   β”‚   β”œβ”€β”€ chains/
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ chatChain.js      # AI chat logic
β”‚   β”‚   β”‚   β”‚   └── mealPlanChain.js  # Meal generation (3,500+ lines)
β”‚   β”‚   β”‚   β”œβ”€β”€ vectorStore.js        # HNSWLib integration
β”‚   β”‚   β”‚   β”œβ”€β”€ retriever.js          # RAG retrieval
β”‚   β”‚   β”‚   └── embeddings.js         # Cached OpenAI embeddings
β”‚   β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”‚   β”œβ”€β”€ chat.js
β”‚   β”‚   β”‚   β”œβ”€β”€ mealPlan.js           # Access control + generation
β”‚   β”‚   β”‚   β”œβ”€β”€ recipes.js            # Recipe search (NEW)
β”‚   β”‚   β”‚   β”œβ”€β”€ subscription.js       # Subscription management
β”‚   β”‚   β”‚   β”œβ”€β”€ jobs.js               # Background job tracking (NEW)
β”‚   β”‚   β”‚   β”œβ”€β”€ metrics.js            # Performance metrics (NEW)
β”‚   β”‚   β”‚   β”œβ”€β”€ feedback.js           # User feedback
β”‚   β”‚   β”‚   β”œβ”€β”€ userProfile.js        # User profile management (NEW)
β”‚   β”‚   β”‚   β”œβ”€β”€ upload.js             # Medical report upload
β”‚   β”‚   β”‚   β”œβ”€β”€ onboarding.js         # Multi-step onboarding
β”‚   β”‚   β”‚   β”œβ”€β”€ progress.js           # Progress tracking
β”‚   β”‚   β”‚   └── ragStatus.js          # RAG system status
β”‚   β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”‚   β”œβ”€β”€ ocrService.js         # Tesseract.js OCR
β”‚   β”‚   β”‚   β”œβ”€β”€ spoonacularService.js # Nutrition & recipe API
β”‚   β”‚   β”‚   β”œβ”€β”€ redditService.js      # Community insights
β”‚   β”‚   β”‚   β”œβ”€β”€ medicalReportService.js # Report parsing & analysis
β”‚   β”‚   β”‚   β”œβ”€β”€ jobService.js         # Background job management (NEW)
β”‚   β”‚   β”‚   β”œβ”€β”€ parserService.js      # PDF/DOCX parsing
β”‚   β”‚   β”‚   └── firebaseCacheService.js # Firebase caching
β”‚   β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   β”‚   β”œβ”€β”€ subscriptionUtils.js  # Access control logic
β”‚   β”‚   β”‚   └── macroCalculator.js    # Dynamic macro targets
β”‚   β”‚   └── data/
β”‚   β”‚       β”œβ”€β”€ meal_templates/       # 1,300+ meal entries (.txt)
β”‚   β”‚       β”œβ”€β”€ medical/              # Medical knowledge base
β”‚   β”‚       └── nutritional/          # Nutrition guidelines
β”‚   └── package.json
β”‚
β”œβ”€β”€ Important Docs/
β”‚   └── RAG_OPTIMIZATION_SUMMARY.md   # Performance metrics & fixes
β”‚
└── README.md                          # This file

πŸ”‘ Key API Endpoints

Chat & AI

Endpoint Method Description
/api/chat/message POST Send chat message, get AI response with RAG context
/api/chat/history/:userId GET Get user's chat history
/api/chat/history/:userId DELETE Clear user's chat history
/api/chat/feedback POST Submit chat interaction feedback
/api/chat/feedback/:userId GET Get user's chat feedback history

Meal Planning

Endpoint Method Description
/api/meals/generate POST Generate personalized meal plan (with access control)
/api/meals/:planId GET Retrieve specific meal plan
/api/meals/user/:userId GET Get user's meal plan history
/api/meals/:planId DELETE Delete meal plan

Recipe Search πŸ†•

Endpoint Method Description
/api/recipes/search POST Search PCOS-friendly recipes (Spoonacular API)
/api/recipes/usage/:userId GET Get recipe search usage stats

Subscription Management

Endpoint Method Description
/api/user/subscription GET Get subscription details & usage
/api/user/subscription/upgrade PUT Upgrade to PRO/MAX
/api/user/subscription/cancel PUT Cancel subscription (retain access)
/api/user/subscription/reactivate PUT Reactivate cancelled subscription
/api/user/usage GET Get meal plan usage statistics

Medical Reports

Endpoint Method Description
/api/upload/report POST Upload medical report (PDF/DOCX/image with OCR)
/api/upload/user/:userId/report GET Get user's latest medical report
/api/upload/user/:userId/has-report GET Check if user has uploaded report
/api/upload/user/:userId/report DELETE Delete user's medical report

Onboarding & Profile

Endpoint Method Description
/api/onboarding/start POST Start onboarding flow
/api/onboarding/:userId/save-step POST Save onboarding step progress
/api/onboarding/:userId/complete POST Complete onboarding
/api/onboarding/:userId GET Get user's onboarding data
/api/user/* * User profile management

Progress Tracking

Endpoint Method Description
/api/progress GET/POST Track health metrics & symptoms

Background Jobs πŸ†•

Endpoint Method Description
/api/jobs/:jobId GET Get background job status
/api/jobs/user/:userId GET Get user's job history
/api/jobs/user/:userId/active GET Get active jobs for user

System & Monitoring

Endpoint Method Description
/api/health GET API health check with RAG status
/api/rag/status GET Detailed RAG system health & metrics
/api/rag/health GET Quick RAG health check
/api/metrics * Performance metrics & analytics
/api/feedback POST/GET Submit & retrieve user feedback

πŸ§ͺ Testing & Quality

# Run all tests
npm run test

# Linting & formatting
npm run lint        # ESLint across all workspaces
npm run lint:fix    # Auto-fix issues
npm run format      # Prettier formatting

# Server-specific
cd server
npm run test              # Vitest unit tests
npm run vector:health     # RAG vector store health check
npm run ingest:all        # Re-index all data sources

Test Coverage:

  • Metadata filters: 18/18 passing βœ…
  • Query expansion: 18/18 passing βœ…
  • Hybrid re-ranking: 20/20 passing βœ…
  • Cuisine compliance: Validated βœ…

πŸ›‘οΈ Security & Safety

  • Content Safety: NSFW/violence/self-harm detection with crisis helpline resources
  • Rate Limiting: 100 requests per 15 minutes
  • Medical Disclaimers: Prominently displayed, not a substitute for professional advice
  • Data Privacy: Firebase security rules, no PHI logging, HTTPS in production
  • Authentication: Google OAuth via Firebase
  • API Key Protection: Environment variables, never committed to version control

πŸ“Š Business Impact

For Users

  • πŸ’° Cost savings: β‚Ή18,000-β‚Ή36,000/year (vs. specialist visits)
  • ⏱️ Time savings: 15 hours/month (vs. manual research)
  • 🎯 Personalization: 33 cuisines Γ— 8 diet types = 264 combinations
  • πŸ“ˆ Engagement: 96% user satisfaction, 52% increase in platform usage

For Investors

  • πŸ“Š Market: 120M+ Indian women with PCOS (β‚Ή600B+ addressable market)
  • πŸ’Ή Revenue model: SaaS subscriptions (FREE/PRO/MAX tiers)
  • πŸš€ Scalability: Cloud-native, serverless architecture (Firebase + OpenAI)
  • πŸ”¬ Innovation: First culturally-localized PCOS AI in India
  • 🌍 Expansion: Exportable to South Asian diaspora (US, UK, Canada)

πŸ—ΊοΈ Roadmap

βœ… Completed (v2.0.0)

  • AI chat with RAG (98% cuisine accuracy)
  • Subscription system with usage limits
  • Keto diet support for all diet types
  • Medical report OCR + analysis
  • Recipe search with Spoonacular API
  • Background job processing system
  • Performance metrics & monitoring
  • 54% latency reduction, 53% cost reduction
  • Public pricing pages + settings management

πŸ”œ Planned (Q1-Q2 2025)

  • Payment integration: Razorpay (India) + Stripe (international)
  • MAX plan launch: Unlimited meal plans tier
  • Mobile app: React Native (iOS + Android)
  • Analytics dashboard: Revenue, churn, conversion tracking
  • Grocery lists: Auto-generated from meal plans
  • Recipe images: DALL-E integration for visual appeal

🌟 Vision (2025-2026)

  • Community forum for peer support
  • Exercise recommendations with RAG
  • Cycle tracking with AI predictions
  • Doctor appointment scheduling
  • Wearable integration (Fitbit, Apple Health)
  • Voice input for chat and meal preferences

πŸŽ“ For Engineers

Why This Project Stands Out

  1. Advanced RAG Architecture:

    • Multi-stage parallel retrieval with hybrid re-ranking
    • Query embedding cache (70-80% hit rate)
    • Context compression (340 β†’ 80 tokens/meal)
    • Intelligent deduplication across categories
  2. Complex Business Logic:

    • Weekly subscription resets (Monday 00:00)
    • Multi-cuisine quota balancing (perfect Β±2 meal variance)
    • Allergen intelligent substitution (3Γ— meal variety)
    • Religious compliance (Jain diet: no fish/root vegetables)
    • Background job processing for async meal generation
    • Recipe search with usage tracking per subscription tier
  3. Production-Ready:

    • 99.9% reliability
    • Content safety guards
    • Error handling + fallback templates
    • Comprehensive test coverage
  4. Performance Optimization:

    • Parallelization: 4.2s β†’ 0.75s RAG retrieval
    • Caching: LRU cache with 1-hour TTL
    • Batch processing: 3Γ— faster for 7-day plans
    • Cost reduction: $0.36 β†’ $0.17 per request

Tech Deep Dives

  • RAG optimization: Important Docs/RAG_OPTIMIZATION_SUMMARY.md
  • Meal generation: server/src/langchain/chains/mealPlanChain.js (3,500+ lines)
  • Subscription logic: server/src/utils/subscriptionUtils.js
  • Vector store management: server/src/scripts/ (health checks, backup, restore)

🀝 Contributing

We welcome contributions! Here's how:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature-name
  3. Make your changes with tests
  4. Run tests and linting: npm run test && npm run lint
  5. Commit with conventional commits: git commit -m "feat: add your feature"
  6. Push to your fork: git push origin feature/your-feature-name
  7. Open a Pull Request with clear description

Guidelines:

  • Follow ESLint/Prettier configurations
  • Add tests for new features
  • Update documentation (README, inline comments)
  • Document AI feature costs and safety considerations

πŸ“„ License

This project is licensed under the MIT License. See LICENSE for details.


πŸ™ Acknowledgments

  • OpenAI for GPT-4o-mini and embeddings API
  • LangChain.js for RAG framework
  • Firebase for authentication and database
  • React and Vite communities
  • PCOS community for inspiration and feedback
  • Contributors who helped optimize and improve the platform

πŸ“§ Contact & Support


🌟 Star This Repo!

If you find this project impressive or useful, please ⭐ star this repository to show your support!


Built with ❀️ for Indian women managing PCOS

Combining cutting-edge AI with cultural sensitivity to deliver personalized health solutions

GitHub Stars Follow


πŸ“š Extended Documentation

πŸ“ Environment Variables

Server (.env)

Variable Required Description
PORT No Server port (default: 5000)
NODE_ENV No Environment (development/production)
OPENAI_API_KEY Yes OpenAI API key for LLM and embeddings
SPOONACULAR_API_KEY Yes Spoonacular API for nutrition data
REDDIT_CLIENT_ID No Reddit OAuth client ID
REDDIT_CLIENT_SECRET No Reddit OAuth client secret
CORS_ORIGIN No Allowed CORS origin
MAX_FILE_SIZE_MB No Max upload file size (default: 10)

Frontend (.env)

Variable Required Description
VITE_API_URL Yes Backend API URL
VITE_FIREBASE_API_KEY Yes Firebase API key
VITE_FIREBASE_AUTH_DOMAIN Yes Firebase auth domain
VITE_FIREBASE_PROJECT_ID Yes Firebase project ID
VITE_FIREBASE_STORAGE_BUCKET Yes Firebase storage bucket
VITE_FIREBASE_MESSAGING_SENDER_ID Yes Firebase messaging sender ID
VITE_FIREBASE_APP_ID Yes Firebase app ID
πŸ”§ NPM Scripts Reference

Root Workspace

npm run dev          # Start both client and server concurrently
npm run build        # Build both client and server for production
npm run test         # Run tests for client and server
npm run lint         # ESLint across all workspaces
npm run lint:fix     # Auto-fix linting issues
npm run format       # Format code with Prettier

Server (server/)

npm run dev                  # Start with auto-restart (node --watch)
npm run ingest:meals         # Index meal templates into vector store
npm run ingest:medical       # Index medical knowledge base
npm run ingest:nutritional   # Index nutritional data
npm run ingest:all           # Index all data sources
npm run pinecone:clear       # Clear Pinecone vector store
npm run test                 # Run server tests

Frontend (frontend/)

npm run dev        # Start Vite dev server with hot reload
npm run build      # Build production assets
npm run preview    # Preview production build
npm run test       # Run frontend tests
πŸ—οΈ RAG System Details

RAG Architecture

  1. Vector Store: HNSWLib for fast similarity search
  2. Embeddings: OpenAI text-embedding-3-small (1,536 dimensions)
  3. Templates: 1,300+ meal entries in server/src/data/meal_templates/
  4. Retrieval: Multi-stage parallel queries with hybrid re-ranking

RAG Status Monitoring

# Detailed status
curl http://localhost:5000/api/rag/status

# Quick health check
curl http://localhost:5000/api/rag/health

Adding New Templates

  1. Create .txt file in server/src/data/meal_templates/
  2. Format: Meal name, region, ingredients, macros, tips
  3. Run: cd server && npm run ingest:meals
  4. Restart server
  5. Verify: curl http://localhost:5000/api/rag/status

Available Scripts

# Ingestion
npm run ingest:meals         # Index meal templates
npm run ingest:medical       # Index medical knowledge
npm run ingest:nutritional   # Index nutritional data
npm run ingest:all           # Index all sources
npm run pinecone:clear       # Clear Pinecone index

# Testing & Utilities
node src/scripts/measureMealPlanPerformance.js
node src/scripts/testLabChatIntegration.js
node src/scripts/testMealPlanWithLabs.js
node src/scripts/setupTestUser.js

Performance Metrics

  • Latency: 3.5s (p95), down from 7.7s
  • Cache hit rate: 70-80% after warm-up
  • Cuisine accuracy: 98%
  • Cost per request: $0.17 (down from $0.36)
πŸ” Subscription System Details

Usage Limits

  • FREE: 1 lifetime meal plan
  • PRO: 3 meal plans per week (resets Monday 00:00)
  • MAX: Unlimited (coming soon)

Access Control Flow

POST /api/meals/generate
    ↓
canGenerateMealPlan(userId)
β”œβ”€β”€ Check subscription_status === 'active'
β”œβ”€β”€ Check plan limits (FREE: 1, PRO: 3/week)
β”œβ”€β”€ Check weekly reset (Monday)
└── Return { allowed: true/false, reason: 'CODE' }
    ↓
Generate meal plan (if allowed)
    ↓
incrementMealPlanCounter(userId)

Test User

Database Schema (Firestore)

users/{userId}: {
  subscription_plan: 'free' | 'pro' | 'max',
  subscription_status: 'active' | 'cancelled' | 'expired',
  billing_cycle: 'monthly' | 'yearly',
  subscription_start_date: timestamp,
  next_billing_date: timestamp,
  meal_plans_generated_count: number,
  meal_plans_generated_this_week: number,
  last_meal_plan_reset_date: timestamp
}
πŸ› Troubleshooting

Port Already in Use

# Find process
lsof -iTCP:5000 -sTCP:LISTEN -n -P

# Kill process
kill <PID>

# Or use different port
PORT=5001 npm run dev

RAG System Issues

# Vector store not found
mkdir -p server/src/data/meal_templates
cd server && npm run ingest:meals

# Templates not being used
curl http://localhost:5000/api/rag/status
npm run ingest:meals
# Restart server

Firebase Configuration

  • Enable Google Authentication in Firebase Console
  • Create Firestore database
  • Configure security rules
  • Verify all VITE_FIREBASE_* variables set

Module Not Found

# Clean install
rm -rf node_modules package-lock.json
npm install

# Or workspace-specific
cd frontend && rm -rf node_modules && npm install

πŸ“š Additional Resources


πŸ“ Changelog

v2.0.0 - Subscription & Pricing System (November 2025)

  • βœ… Three-tier subscription model (FREE/PRO/MAX)
  • βœ… Usage-based access control with weekly resets
  • βœ… Public pricing pages with feature comparison
  • βœ… Settings page with subscription management
  • βœ… Test user configuration for development

v1.3.0 - RAG Optimization & Keto Support (January 2025)

  • βœ… 54% latency reduction (7.7s β†’ 3.5s)
  • βœ… 53% cost reduction ($0.36 β†’ $0.17 per request)
  • βœ… 76% cuisine accuracy improvement (55.6% β†’ 98%)
  • βœ… Ketogenic diet support for all diet types
  • βœ… Allergen intelligent substitution (3Γ— meal variety)
  • βœ… Jain diet compliance fixes (religious requirements)

v1.0.0 - Initial Release

  • βœ… AI chat assistant with RAG
  • βœ… Personalized meal planning (33 cuisines, 4 diet types)
  • βœ… Medical report OCR + analysis
  • βœ… Progress tracking dashboard
  • βœ… Firebase authentication

About

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages