daianadte's picture
Fix app.py
e2a35fa verified
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
import re
from Gradio_UI import GradioUI
@tool
def get_current_weather(location: str) -> str:
"""
Returns the weather report by querying Google Search using DuckDuckGo.
Args:
location: the name of the place that you want the weather for. Should be a place name, followed by possibly a city name, then a country, like "Anchor Point, Taghazout, Morocco".
"""
try:
# Get the current date and time from the machine
date_time_obj = datetime.datetime.now()
# Convert the current datetime object to the desired string format
date_time_str = date_time_obj.strftime("%m/%d/%y %H:%M:%S")
except Exception as e:
return f"Failed to get current date and time. Error: {str(e)}"
# Use DuckDuckGo to search for weather information for the specified location
search_query = f"weather in {location}"
try:
search_results = DuckDuckGoSearchTool().search(search_query)
# Extract weather details using regex (simplified for general use)
weather_info = extract_weather_from_search_results(search_results)
if weather_info:
return f"Weather for {location} on {date_time_str}: {weather_info}"
else:
return f"Could not extract weather information for {location} from search results."
except Exception as e:
return f"Failed to fetch weather data for {location}. Error: {str(e)}"
def extract_weather_from_search_results(search_results: str) -> str:
"""
Extracts weather information from the DuckDuckGo search results.
"""
# A simple regex to extract temperature and weather condition (this can be more complex depending on the result structure)
temperature_match = re.search(r'(\d+)\s?°C', search_results)
condition_match = re.search(r"(clear|cloudy|rainy|sunny|stormy)", search_results, re.IGNORECASE)
if temperature_match and condition_match:
temperature = temperature_match.group(1)
condition = condition_match.group(1)
return f"Temperature: {temperature}°C, Condition: {condition.capitalize()}"
return None
@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 recommend_activities_auto(location: str = "Your City, Your Country", timezone: str = "America/New_York") -> str:
"""
Suggests an activity based on the current weather and time without requiring the user to specify them manually.
Args:
location: The name of the location to fetch weather for. Defaults to "Your City, Your Country".
timezone: The timezone for fetching local time. Defaults to "America/New_York".
Returns:
A friendly activity suggestion based on the current conditions.
"""
# Get the current weather using the location
weather_report = get_current_weather(location)
if "Temperature" not in weather_report: # Check if weather data was successfully retrieved
return "Sorry, I couldn't retrieve the weather data right now."
# Extract temperature and weather condition from the report
temperature_match = re.search(r"Temperature: (\d+)°C", weather_report)
condition_match = re.search(r"Condition: (\w+)", weather_report)
if temperature_match and condition_match:
temperature = float(temperature_match.group(1))
condition = condition_match.group(1).lower()
else:
return "Sorry, there was an issue extracting weather details."
# Get the current time using the timezone
time_report = get_current_time_in_timezone(timezone)
if "Error" in time_report: # Check if time data was successfully retrieved
return "Sorry, I couldn't retrieve the current time."
# Extract the time of day from the time report
time_of_day_match = re.search(r"current local time in [\w/]+ is: (\d+:\d+:\d+)", time_report)
if time_of_day_match:
time_of_day = get_time_of_day() # This function can extract time of day based on the time
else:
return "Sorry, there was an issue extracting the time of day."
# Now, use the current weather and time to recommend activities
risk_of_rain = 1 if condition in ["rainy", "stormy"] else 0
activity_suggestion = recommend_activities(temperature, risk_of_rain, time_of_day)
return activity_suggestion
def get_time_of_day() -> str:
"""
Helper function to determine the time of day based on the current time.
Returns one of "morning", "afternoon", "evening", or "night".
"""
current_time = datetime.datetime.now()
if 5 <= current_time.hour < 12:
return "morning"
elif 12 <= current_time.hour < 17:
return "afternoon"
elif 17 <= current_time.hour < 21:
return "evening"
else:
return "night"
def recommend_activities(temperature: float, risk_of_rain: float, time_of_day: str) -> str:
"""
Suggests a friendly activity recommendation based on temperature, risk of rain, and time of day.
Args:
temperature: The temperature in Celsius.
risk_of_rain: The probability of rain (as a decimal between 0 and 1).
time_of_day: Part of the day (morning, afternoon, evening, night).
Returns:
A friendly activity suggestion as a sentence.
"""
time_of_day = time_of_day.lower()
if time_of_day not in ["morning", "afternoon", "evening", "night"]:
return "Hmm, I don’t recognize that time of day. Try 'morning', 'afternoon', 'evening', or 'night'."
cold = temperature < 10
warm = 10 <= temperature <= 25
hot = temperature > 25
rainy = risk_of_rain > 0.5
if time_of_day == "morning":
if rainy or cold:
return "It's the perfect time to stay in, enjoy a warm cup of coffee, and start your day with a good book or a cozy movie."
return "A fresh morning awaits! Go for a peaceful walk, grab a nice breakfast, or enjoy some outdoor yoga."
elif time_of_day == "afternoon":
if rainy:
return "Rainy afternoon? How about visiting a museum, watching a movie, or enjoying a relaxed café break?"
if hot:
return "It's warm outside! A swim, a cold drink, or a relaxing afternoon indoors sounds perfect."
return "Great time to explore! A bike ride, a picnic, or a casual city stroll could be just what you need."
elif time_of_day == "evening":
if rainy or cold:
return "A cozy dinner indoors, a movie night, or a relaxed evening at home sounds just right."
return "How about a sunset walk, a rooftop café visit, or a fun evening with friends?"
elif time_of_day == "night":
if rainy or cold:
return "Snuggle up with a blanket, put on your favorite series, or enjoy a warm drink before bed."
return "A quiet night walk, some stargazing, or a laid-back evening out could be a great way to end the day."
return "Not sure what to recommend, but whatever you do, enjoy your time!"
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, get_current_time_in_timezone, get_current_weather, recommend_activities_auto], ## 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()