Skip to content

FitAI is a comprehensive fitness and nutrition platform that leverages artificial intelligence to provide personalized health recommendations. The application features a robust backend API built with FastAPI and modern AI technologies, coupled with a responsive Next.js frontend for seamless user experience.

Notifications You must be signed in to change notification settings

PrajwalAmte/FitAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FitAI - Your Personal AI Fitness Assistant

FitAI is a comprehensive fitness and nutrition platform that leverages artificial intelligence to provide personalized health recommendations. The application features a robust backend API built with FastAPI and modern AI technologies, coupled with a responsive Next.js frontend for seamless user experience.

Architecture Overview

The application follows a microservices architecture with clear separation between frontend and backend services:

graph TD
    %% User Layer
    User[👤 User] --> Frontend
    
    %% Frontend Layer
    Frontend[Next.js Frontend<br/>React + TypeScript] --> API
    
    %% Backend API
    API[FastAPI Backend<br/>Python API] --> Services
    
    %% Core Services
    Services[Core Services] --> Profile[User Profiles]
    Services --> Calculator[Calorie Calculator]
    Services --> Chat[AI Chat]
    Services --> Logging[Meal Logging]
    
    %% AI Processing
    Chat --> AIEngine[Groq AI<br/>LLaMA Model]
    
    %% Database
    Profile --> Database[(Astra DB<br/>Cassandra)]
    Chat --> Database
    Logging --> Database
    
    %% Styling
    classDef user fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#000000
    classDef frontend fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#000000
    classDef backend fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#000000
    classDef services fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#000000
    classDef ai fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#000000
    classDef database fill:#e0f2f1,stroke:#00695c,stroke-width:2px,color:#000000
    
    class User user
    class Frontend frontend
    class API backend
    class Services,Profile,Calculator,Chat,Logging services
    class AIEngine ai
    class Database database
Loading

Backend Architecture Deep Dive

Core Technologies

FastAPI Framework

  • Version: Latest with async/await support
  • Features: Automatic OpenAPI documentation, type validation, async request handling
  • CORS: Configured for cross-origin requests from frontend
  • Middleware: Custom error handling and request logging

Database Layer - Astra DB (Apache Cassandra)

# Database Schema Design
user_profiles:
  - user_id (text, PRIMARY KEY)
  - profile_data (text, JSON serialized)
  - created_at (timestamp)
  - updated_at (timestamp)

conversations:
  - user_id (text)
  - timestamp (timestamp)
  - question (text)
  - response (text)
  - profile_snapshot (text, JSON)
  - PRIMARY KEY (user_id, timestamp)

calorie_logs:
  - user_id (text)
  - date (text)
  - meals (text, JSON array)
  - total_calories (double)
  - logged_at (timestamp)
  - PRIMARY KEY (user_id, date)

AI Integration Layer

  • Provider: Groq (High-performance AI inference)
  • Model: Meta LLaMA 4 Scout 17B (Instruction-tuned)
  • Framework: LangChain for conversation management
  • Features: Message history, context-aware responses, session management

Backend Components

1. Application Lifecycle Management

@asynccontextmanager
async def lifespan(application: FastAPI):
    # Startup sequence
    await initialize_app()
    yield
    # Cleanup sequence
    if cassio_session:
        cassio_session.shutdown()

2. Database Connection Management

  • Connection Pooling: Automatic connection management via Cassio
  • Failover: Graceful fallback to in-memory storage if DB unavailable
  • Health Checks: Continuous monitoring of database connectivity
  • Migration: Automatic table creation and schema validation

3. AI Service Integration

# Modern LangChain Implementation
conversation_chain = RunnableWithMessageHistory(
    chain=fitness_prompt | llm,
    get_session_history=get_session_history,
    input_messages_key="question",
    history_messages_key="history",
)

4. Calorie Calculation Engine

Mifflin-St Jeor Equation Implementation:

# BMR Calculation
if gender.lower() == "male":
    bmr = 10 * weight + 6.25 * height - 5 * age + 5
else:
    bmr = 10 * weight + 6.25 * height - 5 * age - 161

# TDEE with Activity Multipliers
activity_multipliers = {
    "sedentary": 1.2,
    "lightly active": 1.375,
    "moderately active": 1.55,
    "very active": 1.725,
    "extremely active": 1.9
}

API Endpoints Documentation

Profile Management

  • POST /profiles - Create user profile with auto-calorie calculation
  • GET /profiles/{user_id} - Retrieve profile with computed metrics
  • PUT /profiles/{user_id} - Update profile with validation
  • POST /calculate-calories - Standalone calorie calculation service

AI Conversation Engine

  • POST /ask-ai - Process fitness questions with context
    • Session-based conversation history
    • Profile-aware responses
    • Automatic conversation logging

Calorie Tracking System

  • POST /calorie-logs - Log daily meals with nutritional data
  • GET /calorie-logs/{user_id}/{date} - Retrieve daily intake records

System Health & Monitoring

  • GET /health - Comprehensive health check
  • GET /debug/astra - Database connection diagnostics
  • GET / - API status and version information

Data Models & Validation

Pydantic Models for Type Safety

class UserProfile(BaseModel):
    name: str
    age: int
    weight: float = Field(..., description="Weight in kg")
    height: float = Field(..., description="Height in cm")
    gender: str = Field(..., description="Male, Female, or Other")
    activity_level: str = Field(..., description="Activity level classification")
    fitness_goals: Optional[str] = None
    daily_calories: Optional[float] = None

class CalorieCalculationResponse(BaseModel):
    bmr: float = Field(..., description="Basal Metabolic Rate")
    tdee: float = Field(..., description="Total Daily Energy Expenditure")
    recommended_calories: float = Field(..., description="Goal-based recommendations")
    goal: str = Field(..., description="Weight management goal")

Environment Configuration

Required Environment Variables

# AI Service Configuration
GROQ_API_KEY=your_groq_api_key_here

# Database Configuration (Optional - falls back to in-memory)
ASTRA_DB_ID=your_astra_database_id
ASTRA_DB_APPLICATION_TOKEN=your_astra_token
ASTRA_DB_KEYSPACE=fitness_app  # Optional, defaults to 'fitness_app'

Configuration Validation

The backend performs comprehensive environment validation:

  • API key verification on startup
  • Database connectivity testing
  • Graceful degradation for missing optional services

Performance & Scalability Features

1. Async/Await Implementation

  • Non-blocking database operations
  • Concurrent request handling
  • Efficient resource utilization

2. Connection Management

  • Database connection pooling
  • Session-based AI conversation tracking
  • Memory-efficient data structures

3. Error Handling & Resilience

# Graceful fallback system
if not astra_db_initialized:
    # Fall back to in-memory storage
    user_profiles[user_id] = profile_data
    print(f"Profile saved to memory: {user_id}")

4. Caching Strategy

  • In-memory session storage for AI conversations
  • Profile data caching for repeated requests
  • Conversation history optimization

Security Implementation

1. Input Validation

  • Pydantic model validation for all endpoints
  • Type checking and constraint enforcement
  • SQL injection prevention via parameterized queries

2. CORS Configuration

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Configure for production
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

3. Error Handling

  • Sanitized error responses
  • Comprehensive logging for debugging
  • Graceful service degradation

Frontend Integration

Tech Stack

  • Next.js 14: React framework with App Router
  • TypeScript: Type-safe frontend development
  • Tailwind CSS: Utility-first styling framework
  • Shadcn/ui: Accessible component library
  • React Query: Server state management and caching

API Communication

// Example API integration
const createProfile = async (profile: UserProfile) => {
  const response = await fetch('/api/profiles', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(profile)
  });
  return response.json();
};

Installation & Setup

Backend Setup

# Clone repository
git clone <repository-url>
cd fitai-backend

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt

# Environment configuration
cp .env.example .env
# Edit .env with your API keys and database credentials

# Run database migrations (if using Astra DB)
python -c "import asyncio; from main import create_database_tables; asyncio.run(create_database_tables())"

# Start the server
uvicorn main:app --reload --host 0.0.0.0 --port 8000

Frontend Setup

# Navigate to frontend directory
cd fitai-frontend

# Install dependencies
npm install

# Environment configuration
cp .env.example .env.local
# Configure API endpoints

# Start development server
npm run dev

Docker Deployment

# Backend Dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Monitoring & Observability

Health Checks

  • /health endpoint provides comprehensive system status
  • Database connectivity monitoring
  • AI service availability checks
  • Environment configuration validation

Logging Strategy

  • Structured logging for all operations
  • Error tracking and debugging information
  • Performance metrics collection
  • User interaction analytics

Debug Endpoints

  • /debug/astra - Database connection diagnostics
  • Component status reporting
  • Environment variable validation

Deployment Architecture

Production Considerations

  1. Database: Astra DB with multi-region replication
  2. API: FastAPI with Gunicorn/Uvicorn workers
  3. Frontend: Next.js with static optimization
  4. CDN: Asset delivery optimization
  5. SSL: HTTPS enforcement
  6. Monitoring: Health checks and alerting

Scaling Strategy

  • Horizontal scaling via container orchestration
  • Database read replicas for performance
  • API rate limiting and throttling
  • CDN integration for static assets

Development Guidelines

Code Quality

  • Type hints throughout Python codebase
  • Comprehensive error handling
  • Async/await best practices
  • Database connection management

Testing Strategy

# Example test structure
@pytest.fixture
async def test_client():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        yield ac

async def test_create_profile(test_client):
    profile_data = {...}
    response = await test_client.post("/profiles", json=profile_data)
    assert response.status_code == 200

API Documentation

  • Automatic OpenAPI/Swagger documentation at /docs
  • Interactive API testing interface
  • Comprehensive endpoint descriptions
  • Request/response examples

Contributing

Backend Development

  1. Fork the repository
  2. Create feature branch: git checkout -b feature/new-feature
  3. Implement changes with tests
  4. Update documentation
  5. Submit pull request

Code Standards

  • Follow PEP 8 for Python code
  • Use type hints consistently
  • Write comprehensive docstrings
  • Implement error handling
  • Add unit tests for new features

License

This project is licensed under the MIT License - see the LICENSE file for details.


Quick Start Commands

# Backend development
uvicorn main:app --reload --port 8000

# Frontend development  
npm run dev

# Database setup (Astra DB)
# Visit https://astra.datastax.com/ for setup instructions

# API documentation
# Visit http://localhost:8000/docs after starting backend

About

FitAI is a comprehensive fitness and nutrition platform that leverages artificial intelligence to provide personalized health recommendations. The application features a robust backend API built with FastAPI and modern AI technologies, coupled with a responsive Next.js frontend for seamless user experience.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published