Habit_Advisor / app.py
Premkumar2025's picture
Update app.py
1017415 verified
Raw History Blame Contribute Delete
5.52 kB
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from dateutil import parser
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
# Below is an example of a tool that does nothing. Amaze us with your creativity !
@tool
def calculate_age(birthdate: str) -> int:
"""
Parses a natural language birthdate string and calculates the age.
Args:
birthdate (str): A string representing the birthdate in natural language (e.g., "I was born on March 17, 1993, by evening 6").
Returns:
int: The calculated age, or -1 if parsing fails.
"""
if not birthdate or not isinstance(birthdate, str):
print("Invalid input: birthdate must be a non-empty string.")
return -1
try:
birth_date = parser.parse(birthdate, fuzzy=True)
today = datetime.now(pytz.UTC).date()
age = today.year - birth_date.year
if (today.month, today.day) < (birth_date.month, birth_date.day):
age -= 1
return age
except Exception as e:
print(f"Error parsing birthdate: {e}")
return -1
final_answer = FinalAnswerTool()
search_tool = DuckDuckGoSearchTool()
@tool
def get_lifestyle_recommendations_web(age: int) -> str:
"""Fetches lifestyle recommendations based on age using web search.
Args:
age: The calculated age of the user.
Returns:
A summary of lifestyle recommendations.
"""
search_query = f"Lifestyle health and wellness tips for {age} years old"
return search_tool(search_query)
@tool
def get_lifestyle_recommendations_offline(age: int) -> str:
"""Provides daily lifestyle habits based on age with the following dataset.
Args:
age: The age of the user.
"""
habits = {
(10, 20): ["Stretching or Yoga", "Learn a new skill daily", "Keep a journal"],
(20, 30): ["Strength training", "Time-block work/study", "Socialize daily"],
(30, 40): ["Regular cardio", "Reduce screen time", "Practice gratitude"],
(40, 50): ["Mindful eating", "Prioritize deep work", "Spend time with family"],
(50, 60): ["Daily walks", "Mentor someone", "Explore a hobby"],
(60, 100): ["Light exercise", "Read daily", "Stay socially engaged"],
}
for age_range, habit_list in habits.items():
if age_range[0] <= age <= age_range[1]:
return f"Based on your age ({age}), here are 3 habits to follow daily:\n1️⃣ {habit_list[0]}\n2️⃣ {habit_list[1]}\n3️⃣ {habit_list[2]}"
return "Age not in expected range. Try again."
@tool
def get_lifestyle_recommendations(age: int, user_input: str) -> str:
"""Fetches lifestyle recommendations based on age.
Args:
age: The calculated age of the user.
user_input: The user's input as natural language.
Returns:
A summary of lifestyle recommendations as a string.
"""
try:
if determine_user_preference(user_input):
web_recommendations = get_lifestyle_recommendations_web(age)
return web_recommendations # Web search
else:
offline_recommendations = get_lifestyle_recommendations_offline(age)
return offline_recommendations # Offline dataset
except Exception as e:
return "An error occurred while fetching recommendations."
@tool
def determine_user_preference(user_input: str) -> bool:
"""
Determines if the user prefers web-based recommendations based on input.
Args:
user_input: The user's natural language input.
Returns:
True if web-based recommendations should be used, False otherwise.
"""
prompt = f"""
The user has provided the following request: "{user_input}".
Determine if the user is explicitly asking for real-time or external data-based insights.
Respond with ONLY 'yes' or 'no'. Do not include any additional text or explanation.
- 'yes' if the user wants real-time or web-based recommendations.
- 'no' if the user does not explicitly ask for real-time or web-based recommendations.
"""
try:
response = model(prompt)
response = response.strip().lower()
if response == "yes":
return True
elif response == "no":
return False
else:
return False
except Exception as e:
return False
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer,get_lifestyle_recommendations,calculate_age], ## add your tools here (don't remove final answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name='LifestyleAdvisor',
description='Provides lifestyle recommendations based on age',
prompt_templates=prompt_templates
)
GradioUI(agent).launch()