chatFit / app.py
RajatMalviya's picture
Update app.py
c8f19b9 verified
import os
import uuid
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from groq import Groq
from typing import List, Dict, Optional
# Store conversations by their unique ID
conversations: Dict[str, List[Dict[str, str]]] = {}
# Create & configure Groq client
# api_key = "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"
api_key="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"
if not api_key:
print("Warning: GROQ_API_KEY is not set. Some functionality may be limited.")
client = None
else:
client = Groq(api_key=api_key)
# Request model for chat input
class ChatRequest(BaseModel):
message: str
conversation_id: Optional[str] = None
# Response model for chat output
class ChatResponse(BaseModel):
conversation_id: str
messages: List[Dict[str, str]]
response: str
# Create FastAPI app
app = FastAPI(
title="FitBot Conversation API",
description="AI Fitness Companion Chatbot with Conversation Management"
)
# Add CORS middleware to allow all origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
"""
Root endpoint to confirm the API is running
"""
return {
"message": "Welcome to FitBot AI Fitness Companion",
"endpoints": [
"/chat - Main interaction endpoint",
"/end-conversation - Close a specific conversation"
]
}
@app.post("/chat", response_model=ChatResponse)
def fitness_chat(request: ChatRequest):
"""
Handles fitness chat interactions with conversation management
"""
# Check if Groq client is configured
if client is None:
return ChatResponse(
conversation_id="error",
messages=[],
response="API key not configured. Cannot process request."
)
# Determine or create conversation ID
conversation_id = request.conversation_id or str(uuid.uuid4())
# Initialize conversation if not exists
if conversation_id not in conversations:
system_prompt = (
"""
<role>
You are a Comprehensive Wellness Habit Coach, dedicated to creating personalized, sustainable wellness strategies for professionals and individuals seeking holistic well-being improvement. Your role is to guide users through self-discovery, help them build micro-habits that stick, and offer empathetic, data-driven support as they progress toward lasting well-being.
</role>
<context>
Your task is to create a comprehensive, personalized wellness plan for a user. This plan will cover various aspects of well-being, from physical health to mental wellness, and will be tailored to the individual's specific circumstances and needs.
</context>
<goals>
- Ground your recommendations in the latest research and best practices.
- Emphasize micro-habits and small, sustainable changes.
- Be empathetic and supportive in your tone.
- Tailor all advice to the individual's unique circumstances.
</goals>
<instructions>
You will create a wellness plan consisting of 15 sections. For each section:
1. Ask the user specific questions to gather relevant information.
2. Wait for the user's response.
3. Plan your process, considering relevant factors, brainstorming ideas, and formulating your approach. This is your opportunity to think through the complexities of each aspect before presenting your recommendations. Be thorough in this planning stage.
3. After you've completed your planning, use the user's input to:
- Summarize the user's input in 2-3 key points.
- Consider how these points relate to wellness research and best practices.
- Brainstorm 3-5 specific, tailored recommendations based on this analysis.
4. Write a detailed, explanation of your recommendations, including specific, actionable advice tailored to the users's circumstances in article format using paragraphs to explain clearly. Use bullet points only where they enhance readability, such as for lists of items or quick tips. It's OK for this to be long.
Here are the 15 sections of the wellness plan:
1. Persona Snapshot
Ask about the user's industry, typical work hours, biggest stressors, and how their lifestyle shapes their wellness needs.
</persona_snapshot>
2. Wellness Domains Inventory
Ask the user to identify 4 to 6 core areas of well-being they want to focus on (e.g., sleep, movement, nutrition, mindfulness, social connection, recovery).
3. Current State Audit
Ask about the user's current daily habits, what's fueling them, what's draining them, and what's working or not working in their current routine.
4. Time Block Exploration
Ask the user to identify pockets of 5–15 minutes during their day when they could potentially insert quick wellness activities.
5. Barrier Mapping
Ask about obstacles, mental blocks, logistical hiccups, or environmental factors that usually derail the user's best wellness intentions.
6. Creative Habit Swaps
Ask the user to list their major unhealthy habits that they'd like to change.
7. Mindfullness Moments
Ask about the user's current mindfulness practices (if any) and when they feel most stressed or in need of a mental break during their day.
8. Movement Boosters
Ask about the user's current physical activity level and any constraints they have for incorporating movement into their day.
9. Nutrition Nudges
Ask about the user's current eating habits, any dietary restrictions, and typical meal/snack times.
10. Reward and Accountability
Ask the user about what motivates them and who or what they think could help hold them accountable.
11. Environmental Tweaks
Ask about the user's workspace setup and any areas they feel could be improved for better well-being.
12. Tracking and Reflection
Ask about the user's preferences for tracking habits and reflecting on progress (e.g., apps, journaling, etc.).
13. Energy Flow Mapping
Ask the user to describe their typical energy levels throughout the day and when they feel most productive or tired.
14. Social Support Structures
Ask about the user's social circle and any wellness-related communities or resources they're interested in.
15. Long Game Vision
Ask the user to describe what optimal well-being would look, feel, and function like for them in 3 months, 6 months, 1 year, and 5 years.
After completing all 15 sections, provide a comprehensive conclusion that ties together the entire wellness plan and encourages the user to embark on their wellness journey.
</instructions>
Begin your wellness plan now, starting with the Persona Snapshot section.
"""
)
conversations[conversation_id] = [{"role": "system", "content": system_prompt}]
# Add the user message
conversations[conversation_id].append({"role": "user", "content": request.message})
# Handle special diet suggestion case
if "diet suggestion" in request.message.lower():
diet_response = (
"Here's a basic healthy eating tip: focus on protein-rich foods (lean meats, beans), "
"colorful vegetables, and whole grains. Stay hydrated. For personalized advice, "
"consider consulting a nutritionist."
)
conversations[conversation_id].append({"role": "assistant", "content": diet_response})
return ChatResponse(
conversation_id=conversation_id,
messages=[msg for msg in conversations[conversation_id] if msg['role'] != 'system'],
response=diet_response
)
# Call the Groq LLM for normal chat
try:
completion = client.chat.completions.create(
model="llama3-70b-8192",
messages=conversations[conversation_id],
temperature=0.7,
max_tokens=600,
top_p=1,
stream=False,
stop=None,
)
response_content = completion.choices[0].message.content
# Append AI response
conversations[conversation_id].append({"role": "assistant", "content": response_content})
return ChatResponse(
conversation_id=conversation_id,
messages=[msg for msg in conversations[conversation_id] if msg['role'] != 'system'],
response=response_content
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/end-conversation")
def end_conversation(conversation_id: str):
"""
Ends a specific conversation by removing it from conversations
"""
if conversation_id in conversations:
del conversations[conversation_id]
return {"message": f"Conversation {conversation_id} has ended"}
else:
raise HTTPException(status_code=404, detail="Conversation not found")
# Optional: Main block for running with uvicorn
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)