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.
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
- 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 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)
- 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
@asynccontextmanager
async def lifespan(application: FastAPI):
# Startup sequence
await initialize_app()
yield
# Cleanup sequence
if cassio_session:
cassio_session.shutdown()
- 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
# Modern LangChain Implementation
conversation_chain = RunnableWithMessageHistory(
chain=fitness_prompt | llm,
get_session_history=get_session_history,
input_messages_key="question",
history_messages_key="history",
)
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
}
POST /profiles
- Create user profile with auto-calorie calculationGET /profiles/{user_id}
- Retrieve profile with computed metricsPUT /profiles/{user_id}
- Update profile with validationPOST /calculate-calories
- Standalone calorie calculation service
POST /ask-ai
- Process fitness questions with context- Session-based conversation history
- Profile-aware responses
- Automatic conversation logging
POST /calorie-logs
- Log daily meals with nutritional dataGET /calorie-logs/{user_id}/{date}
- Retrieve daily intake records
GET /health
- Comprehensive health checkGET /debug/astra
- Database connection diagnosticsGET /
- API status and version information
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")
# 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'
The backend performs comprehensive environment validation:
- API key verification on startup
- Database connectivity testing
- Graceful degradation for missing optional services
- Non-blocking database operations
- Concurrent request handling
- Efficient resource utilization
- Database connection pooling
- Session-based AI conversation tracking
- Memory-efficient data structures
# 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}")
- In-memory session storage for AI conversations
- Profile data caching for repeated requests
- Conversation history optimization
- Pydantic model validation for all endpoints
- Type checking and constraint enforcement
- SQL injection prevention via parameterized queries
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
- Sanitized error responses
- Comprehensive logging for debugging
- Graceful service degradation
- 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
// 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();
};
# 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
# 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
# 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"]
/health
endpoint provides comprehensive system status- Database connectivity monitoring
- AI service availability checks
- Environment configuration validation
- Structured logging for all operations
- Error tracking and debugging information
- Performance metrics collection
- User interaction analytics
/debug/astra
- Database connection diagnostics- Component status reporting
- Environment variable validation
- Database: Astra DB with multi-region replication
- API: FastAPI with Gunicorn/Uvicorn workers
- Frontend: Next.js with static optimization
- CDN: Asset delivery optimization
- SSL: HTTPS enforcement
- Monitoring: Health checks and alerting
- Horizontal scaling via container orchestration
- Database read replicas for performance
- API rate limiting and throttling
- CDN integration for static assets
- Type hints throughout Python codebase
- Comprehensive error handling
- Async/await best practices
- Database connection management
# 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
- Automatic OpenAPI/Swagger documentation at
/docs
- Interactive API testing interface
- Comprehensive endpoint descriptions
- Request/response examples
- Fork the repository
- Create feature branch:
git checkout -b feature/new-feature
- Implement changes with tests
- Update documentation
- Submit pull request
- Follow PEP 8 for Python code
- Use type hints consistently
- Write comprehensive docstrings
- Implement error handling
- Add unit tests for new features
This project is licensed under the MIT License - see the LICENSE file for details.
# 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