Spoon-assassin's picture
Update app.py
ef6d1c7 verified
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool,LiteLLMModel
import datetime
import requests
import pytz
import yaml
import os
from geopy.geocoders import Nominatim
from tools.final_answer import FinalAnswerTool
import requests
from datetime import datetime, timedelta
from geopy.geocoders import Nominatim
from Gradio_UI import GradioUI
def date_to_friendly_format(date_string):
"""
Converts a date string to a more readable
"""
date_obj = datetime.strptime(date_string, "%Y-%m-%d")
friendly_date = date_obj.strftime("%a %b %d %Y")
return friendly_date
def meteo_weathercode_to_string(weathercode):
"""
Converts a weather code to a corresponding string.
"""
string_lookup = {
0: "Clear sky",
1: "Mainly clear",
2: "Partly cloudy",
3: "Overcast",
45: "Fog",
48: "Depositing rime fog",
51: "Light drizzle",
53: "Moderate drizzle",
55: "Dense drizzle",
56: "Light freezing drizzle",
57: "Dense freezing drizzle",
61: "Slight rain",
63: "Moderate rain",
65: "Heavy rain",
66: "Light freezing rain",
67: "Heavy freezing rain",
71: "Slight snow fall",
73: "Moderate snow fall",
75: "Heavy snow fall",
77: "Snow grains",
80: "Slight rain showers",
81: "Moderate rain showers",
82: "Heavy rain showers",
85: "Slight snow showers",
86: "Heavy snow showers",
95: "Thunderstorm",
96: "Thunderstorm with slight hail",
99: "Thunderstorm with heavy hail"
}
return string_lookup.get(weathercode, "Unknown")
def get_city_coordinates(city_name: str):
"""
Finds the GPS coordinates (latitude, longitude) of a city.
Args:
city_name: A string representing the name of a city (e.g., 'London').
Returns:
A tuple containing the latitude and longitude (floats), or None if the city is not found.
"""
geolocator = Nominatim(user_agent="city_coordinates_finder_andyh") # Important: Provide a user agent
location = geolocator.geocode(city_name)
if location:
latitude = location.latitude
longitude = location.longitude
return latitude, longitude
else:
print(f"Error: Could not find coordinates for '{city_name}'.") # Indicate failure
return None
@tool
def get_weather_forecast(city: str, days: str=3) -> str:
"""
Retrieves a weather forecast for a city over the next few days.
Args:
city: a sting of the name of the city to get weather
days: The number of days to forecast including today. So the weather 4 days from now would need an input of 5 (int, default is 3).
Returns:
A string containing the weather forecast in CSV format.
Prints an error message if the API request fails.
"""
latitude, longitude = get_city_coordinates(city)
url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&daily=weathercode,temperature_2m_max,temperature_2m_min,precipitation_sum&forecast_days={days}"
try:
response = requests.get(url)
response.raise_for_status()
forecast_data = response.json()
if "daily" in forecast_data:
csv = ["Date,Weather,High,Low,Rain"]
daily_date = forecast_data["daily"]
for weather in zip(daily_date["time"], daily_date["weathercode"], daily_date["temperature_2m_max"], daily_date["temperature_2m_min"], daily_date["precipitation_sum"]):
csv.append(f"{date_to_friendly_format(weather[0])},{meteo_weathercode_to_string(weather[1])},{weather[2]}°C,{weather[3]}°C,{weather[4]}mm")
return "\n".join(csv)
else:
print("Error: No 'daily' data found in the API response.")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching forecast data: {e}")
return None
except (ValueError, KeyError) as e:
print(f"Error processing forecast data: {e}")
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 get_current_time() -> str:
"""A tool that fetches the current local time.
"""
try:
# Create timezone object
tz = pytz.timezone("Europe/London")
# Get current time in that timezone
local_time = datetime.datetime.now(tz).strftime("%a, %b %d, %Y")
return f"The current local time is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
final_answer = FinalAnswerTool()
model = LiteLLMModel(
model_id="gemini/gemini-2.0-flash",
api_key=os.getenv("GEMINI_KEY"),
num_ctx=8192,
)
# 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_time, get_weather_forecast], ## 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()