from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool import datetime import requests import pytz import yaml 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 my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type #Keep this format for the description / args / args description but feel free to modify the tool """A tool that does nothing yet Args: arg1: the first argument arg2: the second argument """ return "What magic will you build ?" @tool def get_current_time_in_timezone(timezone: str) -> str: """A tool that fetches the current local time in a specified timezone. Args: timezone: A string representing a valid timezone (e.g., 'America/New_York'). """ try: # Create timezone object tz = pytz.timezone(timezone) # Get current time in that timezone local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"The current local time in {timezone} is: {local_time}" except Exception as e: return f"Error fetching time for timezone '{timezone}': {str(e)}" @tool def create_healthy_diet_plan(weight: float, height: float, age: int = 30, gender: str = "not specified", activity_level: str = "moderate") -> str: """A tool that creates a personalized healthy diet plan based on user metrics. Args: weight: Weight in kilograms (kg) height: Height in centimeters (cm) age: Age in years (default: 30) gender: "male", "female", or "not specified" (default: "not specified") activity_level: "sedentary", "light", "moderate", "active", or "very active" (default: "moderate") """ # Calculate BMI bmi = weight / ((height/100) ** 2) bmi_rounded = round(bmi, 1) # Determine BMI category if bmi < 18.5: bmi_category = "underweight" elif bmi < 25: bmi_category = "normal weight" elif bmi < 30: bmi_category = "overweight" else: bmi_category = "obese" # Calculate Basal Metabolic Rate (BMR) using Mifflin-St Jeor Equation if gender.lower() == "male": bmr = 10 * weight + 6.25 * height - 5 * age + 5 elif gender.lower() == "female": bmr = 10 * weight + 6.25 * height - 5 * age - 161 else: # Average of male and female calculations for non-specified gender bmr = 10 * weight + 6.25 * height - 5 * age - 78 # Activity level multiplier for Total Daily Energy Expenditure (TDEE) activity_multipliers = { "sedentary": 1.2, # Little or no exercise "light": 1.375, # Light exercise 1-3 days/week "moderate": 1.55, # Moderate exercise 3-5 days/week "active": 1.725, # Hard exercise 6-7 days/week "very active": 1.9 # Very hard exercise & physical job or training twice a day } multiplier = activity_multipliers.get(activity_level.lower(), 1.55) tdee = round(bmr * multiplier) # Diet recommendation based on BMI category if bmi_category == "underweight": calorie_adjustment = 300 # Surplus for weight gain protein_ratio = 1.6 # g per kg of body weight diet_focus = "nutrient-dense, calorie-rich foods to gain healthy weight" elif bmi_category == "normal weight": calorie_adjustment = 0 # Maintenance protein_ratio = 1.4 diet_focus = "balanced nutrition to maintain your healthy weight" elif bmi_category == "overweight": calorie_adjustment = -300 # Deficit for weight loss protein_ratio = 1.8 diet_focus = "portion control and nutrient-dense, lower-calorie foods" else: # obese calorie_adjustment = -500 # Larger deficit for weight loss protein_ratio = 2.0 diet_focus = "whole foods with high satiety and controlled portions" # Calculate daily calorie target daily_calories = tdee + calorie_adjustment # Calculate macronutrient breakdown daily_protein = round(weight * protein_ratio) # grams daily_protein_calories = daily_protein * 4 # 4 calories per gram of protein # Fat is about 25-30% of calories daily_fat_calories = round(daily_calories * 0.28) daily_fat = round(daily_fat_calories / 9) # 9 calories per gram of fat # Remaining calories from carbs daily_carb_calories = daily_calories - daily_protein_calories - daily_fat_calories daily_carb = round(daily_carb_calories / 4) # 4 calories per gram of carb # Generate diet plan response response = f""" Based on your measurements: - Weight: {weight} kg - Height: {height} cm - BMI: {bmi_rounded} ({bmi_category}) Your estimated daily calorie needs are approximately {daily_calories} calories. RECOMMENDED DAILY NUTRITION: • Protein: {daily_protein}g ({round(daily_protein_calories)} calories) • Carbohydrates: {daily_carb}g ({round(daily_carb_calories)} calories) • Fats: {daily_fat}g ({round(daily_fat_calories)} calories) MEAL PLAN FOCUS: Your diet should focus on {diet_focus}. SAMPLE DAILY MEAL STRUCTURE: BREAKFAST (25% of daily calories): • Protein source (eggs, Greek yogurt, or protein shake) • Complex carbohydrates (oatmeal, whole grain toast) • Healthy fat (nuts, seeds, or avocado) • Fruit for vitamins and fiber LUNCH (30% of daily calories): • Lean protein (chicken, fish, tofu, or legumes) • Complex carbohydrates (brown rice, quinoa, or sweet potato) • Vegetables (at least 2 varieties) • Healthy fat source (olive oil dressing or nuts) DINNER (30% of daily calories): • Lean protein (fish, turkey, beef, or plant-based alternative) • Non-starchy vegetables (half your plate) • Small portion of complex carbohydrates • Healthy fat source SNACKS (15% of daily calories): • Mid-morning: Fruit with nuts or yogurt • Mid-afternoon: Vegetable sticks with hummus or a small protein shake HYDRATION: • Aim for 8-10 glasses of water daily • Limit sugary drinks and alcohol This plan is personalized based on your metrics and designed to support your health goals while providing adequate nutrition. """ return response final_answer = FinalAnswerTool() # 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], ## add your tools here (don't remove final answer) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch()