AI Coach & Agents

Conversational AI coaching interface powered by Supabase Edge Functions. Generates personalized workouts and nutrition plans, answers training questions, and recommends MTC programs based on conversation context.

Overview

The AI Coach is a conversational AI assistant embedded in the My Trainer Connect platform. It provides personalized fitness and nutrition guidance through a chat interface, acting as an always-available supplement to human trainers. The AI can generate custom workout programs, create nutrition plans, answer training and form questions, and recommend MTC programs and trainers based on conversation context.

The AI Coach is powered by Supabase Edge Functions that process user prompts with contextual awareness of the user's profile, goals, experience level, and training history. It uses rate limiting and usage guardrails to manage costs while providing a premium experience. Quick prompt templates lower the barrier to engagement with pre-written starting points like "Find my perfect program", "Build strength", "Lose weight sustainably", and "Train at home".

Chat sessions are persisted with full message history, allowing users to return to previous conversations. The system maintains conversation context across messages within a session, enabling follow-up questions and iterative refinement of recommendations. When the AI identifies relevant MTC programs, it generates inline program cards with pricing and enrollment links.

User Stories

Client Stories

As a client, I want to chat with an AI coach so that I can get instant answers to training and nutrition questions without waiting for my trainer.

As a client, I want the AI to generate a custom workout for me so that I have a structured plan even when I do not have a trainer assigned.

As a client, I want the AI to recommend MTC programs based on our conversation so that I can find relevant programs easily.

As a client, I want to use quick prompt templates so that I can start a conversation without having to think of what to ask.

As a client, I want to return to previous AI conversations so that I can reference past advice and generated plans.

As a client, I want the AI to know my fitness profile so that recommendations are personalized to my goals and experience level.

Admin Stories

As an admin, I want rate limiting on AI usage so that costs are controlled while maintaining a good user experience.

As an admin, I want usage analytics on AI conversations so that I can understand adoption and optimize the system.

Quick Prompt Templates

🏆

Find My Perfect Program

Get personalized program recommendations based on your goals and preferences.

💪

Build Strength

Generate a strength-focused workout plan tailored to your experience level.

Lose Weight Sustainably

Get a balanced approach to fat loss combining workouts with nutrition guidance.

🏠

Train at Home

Create effective workouts with minimal or no equipment for home training.

AI Capabilities

Workout Generation

Generate complete workout programs with exercises, sets, reps, and rest periods based on user goals, available equipment, and experience level. Outputs structured data compatible with the program builder.

Nutrition Planning

Create meal plans with macro breakdowns, suggest meal ideas based on dietary preferences and caloric goals, and answer nutrition-related questions.

Training Q&A

Answer questions about exercise form, programming principles, recovery, injury prevention, supplement guidance, and training periodization.

Program Recommendations

Analyze conversation context to recommend relevant MTC marketplace programs. Generates inline program cards with pricing, difficulty, and enrollment CTAs.

Profile-Aware Context

Incorporates user profile data (goals, experience, obstacles, preferences) into all responses for personalized guidance without requiring repetitive questions.

Session Persistence

Full message history saved per session. Users can return to previous conversations. Context maintained within sessions for natural follow-up interactions.

Data Model

Table Key Columns Description
ai_chat_sessions id, user_id, title, model, system_prompt, context_snapshot, message_count, last_message_at, created_at Chat session metadata. Title auto-generated from first message. Context snapshot stores user profile data at session creation time.
ai_chat_messages id, session_id, role, content, tokens_used, model, created_at Individual messages in a session. Role: user, assistant, system. Token usage tracked for rate limiting.

Technical Architecture

Request Flow

1. Client sends message via React Query mutation

2. Server function validates input & checks rate limits

3. User profile + conversation history assembled as context

4. Supabase Edge Function invokes LLM API with system prompt

5. Response streamed back to client (streaming optional)

6. Message + token usage persisted to ai_chat_messages

7. Program recommendations parsed and rendered as inline cards

Rate Limiting & Guardrails

Per-User Rate Limit

Maximum messages per hour / per day to control costs

Token Budget

Maximum tokens per session and per message to prevent abuse

Content Filtering

System prompt restricts responses to fitness/nutrition topics only

Usage Tracking

Token usage tracked per message for analytics and billing

Screens & Routes

Route File Description
/ai-coach src/routes/_authed/_onboarded/_client/ai-coach.tsx AI Coach chat page — session list, chat interface, quick prompts, message history

Acceptance Criteria

Chat Interface

AI Capabilities

Session Management

Technical

API Surface

The AI Coach API is planned but not yet implemented. The backend will use Supabase Edge Functions for LLM integration.

Planned Server Functions

GET getAiChatSessions — List all chat sessions for the current user

GET getAiChatMessages — Fetch messages for a specific session

POST createAiChatSession — Start a new chat session with context snapshot

POST sendAiMessage — Send a user message, get AI response (via Edge Function)

POST deleteAiChatSession — Delete a session and its messages

GET getAiUsageStats — Current rate limit status for the user

Planned Query Keys

aiCoachKeys.all → ['ai-coach']

aiCoachKeys.sessions() → ['ai-coach', 'sessions']

aiCoachKeys.messages(sessionId) → ['ai-coach', 'messages', sessionId]

aiCoachKeys.usage() → ['ai-coach', 'usage']

Edge Function

POST supabase/functions/v1/ai-coach — Processes user message with LLM, returns AI response

Input: { session_id, message, user_context }

Output: { response, tokens_used, recommended_programs? }

Current Status

Built
  • AI Coach page UI layout
  • Chat interface component
  • Quick prompt template cards
  • Message bubble components
  • Database tables (ai_chat_sessions, ai_chat_messages)
In Progress
  • Edge Function for LLM integration
  • System prompt design
Not Started
  • API server functions
  • React Query hooks
  • Session management (create, list, resume, delete)
  • LLM context assembly (profile + history)
  • Program recommendation parsing
  • Inline program card rendering
  • Response streaming
  • Rate limiting implementation
  • Token usage tracking
  • Markdown rendering in responses
  • Usage analytics dashboard