Spaces:
Sleeping
Sleeping
File size: 5,966 Bytes
0bb16f2 9b5b26a c19d193 9a4eca0 5b41d86 6aae614 8bf57ed 8fe992b 9b5b26a 5b41d86 0495093 5b41d86 0495093 5b41d86 0495093 5b41d86 0495093 5b41d86 0627a44 5b41d86 9b5b26a 0627a44 5b41d86 9b5b26a 5b41d86 c3a2736 5b41d86 7d52581 5b41d86 9b5b26a 5b41d86 0495093 5b41d86 0495093 5b41d86 9b5b26a 8c01ffb 43b31fb ef6d1c7 43b31fb ef6d1c7 43b31fb 8c01ffb 6aae614 4ccfef6 3395892 4ccfef6 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b 43b31fb 8c01ffb 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 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | 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() |