Spaces:
Sleeping
Sleeping
File size: 5,515 Bytes
9b5b26a c19d193 16c23e0 6aae614 8fe992b 9b5b26a 5df72d6 9b5b26a 577ff52 e3a2be9 07a01a7 9b5b26a 6bf44fe 577ff52 6bf44fe 577ff52 6bf44fe 8c01ffb 6aae614 2742231 d1daeaf 2742231 577ff52 d1daeaf 577ff52 6bf44fe d1daeaf e3576c3 f1ceff8 d1daeaf e3576c3 1017415 d1daeaf 1017415 6bf44fe 1017415 6bf44fe ae7a494 e121372 bf6d34c 29ec968 fe328e0 13d500a 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b d1daeaf 8c01ffb 2742231 861422e 8fe992b 9b5b26a 8c01ffb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | 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() |