Spaces:
Sleeping
Sleeping
add tools
Browse filesAdd tool functions to app.py so the smolagents chat agent can answer questions about local weather, time, or events by utilizing these functions. API keys have been provided to make use of appropriate Hugging Face, OpenAI, or OpenWeather APIs if necessary.
app.py
CHANGED
|
@@ -3,10 +3,27 @@ import datetime
|
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
|
|
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
| 7 |
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
| 11 |
@tool
|
| 12 |
def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
|
|
@@ -33,6 +50,156 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 33 |
except Exception as e:
|
| 34 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
final_answer = FinalAnswerTool()
|
| 38 |
|
|
@@ -55,7 +222,15 @@ with open("prompts.yaml", 'r') as stream:
|
|
| 55 |
|
| 56 |
agent = CodeAgent(
|
| 57 |
model=model,
|
| 58 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
max_steps=6,
|
| 60 |
verbosity_level=1,
|
| 61 |
grammar=None,
|
|
|
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
+
import os
|
| 7 |
from tools.final_answer import FinalAnswerTool
|
| 8 |
|
| 9 |
from Gradio_UI import GradioUI
|
| 10 |
|
| 11 |
+
from dotenv import load_dotenv
|
| 12 |
+
|
| 13 |
+
load_dotenv(os.path.expanduser("~/Projekte/MOOC/OpenCampus/codespace/.env"))
|
| 14 |
+
|
| 15 |
+
if not os.environ.get("HF_TOKEN"):
|
| 16 |
+
# os.environ["HF_TOKEN"] = getpass.getpass("Enter API key for Hugging Face: ")
|
| 17 |
+
raise EnvironmentError("HF_TOKEN not found in the .env file.")
|
| 18 |
+
|
| 19 |
+
if not os.environ.get("OPEN_WEATHER_API_KEY"):
|
| 20 |
+
# os.environ["OPEN_WEATHER_API_KEY"] = getpass.getpass("Enter API key for OpenWeather: ")
|
| 21 |
+
raise EnvironmentError("OPEN_WEATHER_API_KEY not found in the .env file.")
|
| 22 |
+
|
| 23 |
+
if not os.environ.get("OPENAI_API_KEY"):
|
| 24 |
+
# os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")
|
| 25 |
+
raise EnvironmentError("OPENAI_API_KEY not found in the .env file.")
|
| 26 |
+
|
| 27 |
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
| 28 |
@tool
|
| 29 |
def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
|
|
|
|
| 50 |
except Exception as e:
|
| 51 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 52 |
|
| 53 |
+
@tool
|
| 54 |
+
def get_weather_by_city(city: str, country_code: str = "") -> str:
|
| 55 |
+
"""A tool that fetches current weather information for a specific city.
|
| 56 |
+
Args:
|
| 57 |
+
city: The name of the city (e.g., 'London', 'New York')
|
| 58 |
+
country_code: Optional 2-letter country code (e.g., 'US', 'GB')
|
| 59 |
+
"""
|
| 60 |
+
try:
|
| 61 |
+
api_key = os.environ.get("OPEN_WEATHER_API_KEY")
|
| 62 |
+
if not api_key:
|
| 63 |
+
return "Error: OpenWeather API key not found"
|
| 64 |
+
|
| 65 |
+
# Build location string
|
| 66 |
+
location = city
|
| 67 |
+
if country_code:
|
| 68 |
+
location += f",{country_code}"
|
| 69 |
+
|
| 70 |
+
# Get current weather
|
| 71 |
+
url = f"https://api.openweathermap.org/data/2.5/weather"
|
| 72 |
+
params = {
|
| 73 |
+
'q': location,
|
| 74 |
+
'appid': api_key,
|
| 75 |
+
'units': 'metric' # Celsius
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
response = requests.get(url, params=params)
|
| 79 |
+
response.raise_for_status()
|
| 80 |
+
data = response.json()
|
| 81 |
+
|
| 82 |
+
# Extract relevant information
|
| 83 |
+
main = data['main']
|
| 84 |
+
weather = data['weather'][0]
|
| 85 |
+
wind = data.get('wind', {})
|
| 86 |
+
|
| 87 |
+
weather_info = f"""Current weather in {data['name']}, {data['sys']['country']}:
|
| 88 |
+
- Temperature: {main['temp']}°C (feels like {main['feels_like']}°C)
|
| 89 |
+
- Condition: {weather['description'].title()}
|
| 90 |
+
- Humidity: {main['humidity']}%
|
| 91 |
+
- Pressure: {main['pressure']} hPa"""
|
| 92 |
+
|
| 93 |
+
if 'speed' in wind:
|
| 94 |
+
weather_info += f"\n- Wind Speed: {wind['speed']} m/s"
|
| 95 |
+
|
| 96 |
+
return weather_info
|
| 97 |
+
|
| 98 |
+
except requests.exceptions.RequestException as e:
|
| 99 |
+
return f"Error fetching weather data: {str(e)}"
|
| 100 |
+
except KeyError as e:
|
| 101 |
+
return f"Error parsing weather data: Missing field {str(e)}"
|
| 102 |
+
except Exception as e:
|
| 103 |
+
return f"Unexpected error: {str(e)}"
|
| 104 |
+
|
| 105 |
+
@tool
|
| 106 |
+
def get_weather_forecast(city: str, country_code: str = "", days: int = 3) -> str:
|
| 107 |
+
"""A tool that fetches weather forecast for a specific city.
|
| 108 |
+
Args:
|
| 109 |
+
city: The name of the city (e.g., 'London', 'New York')
|
| 110 |
+
country_code: Optional 2-letter country code (e.g., 'US', 'GB')
|
| 111 |
+
days: Number of days to forecast (1-5, default: 3)
|
| 112 |
+
"""
|
| 113 |
+
try:
|
| 114 |
+
api_key = os.environ.get("OPEN_WEATHER_API_KEY")
|
| 115 |
+
if not api_key:
|
| 116 |
+
return "Error: OpenWeather API key not found"
|
| 117 |
+
|
| 118 |
+
# Limit days to 5 (API limitation)
|
| 119 |
+
days = min(max(1, days), 5)
|
| 120 |
+
|
| 121 |
+
# Build location string
|
| 122 |
+
location = city
|
| 123 |
+
if country_code:
|
| 124 |
+
location += f",{country_code}"
|
| 125 |
+
|
| 126 |
+
# Get forecast
|
| 127 |
+
url = f"https://api.openweathermap.org/data/2.5/forecast"
|
| 128 |
+
params = {
|
| 129 |
+
'q': location,
|
| 130 |
+
'appid': api_key,
|
| 131 |
+
'units': 'metric'
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
response = requests.get(url, params=params)
|
| 135 |
+
response.raise_for_status()
|
| 136 |
+
data = response.json()
|
| 137 |
+
|
| 138 |
+
forecast_info = f"Weather forecast for {data['city']['name']}, {data['city']['country']}:\n\n"
|
| 139 |
+
|
| 140 |
+
# Group forecasts by date
|
| 141 |
+
daily_forecasts = {}
|
| 142 |
+
for item in data['list'][:days*8]: # 8 forecasts per day (3-hour intervals)
|
| 143 |
+
date = datetime.datetime.fromtimestamp(item['dt']).strftime('%Y-%m-%d')
|
| 144 |
+
if date not in daily_forecasts:
|
| 145 |
+
daily_forecasts[date] = []
|
| 146 |
+
daily_forecasts[date].append(item)
|
| 147 |
+
|
| 148 |
+
# Summarize each day
|
| 149 |
+
for date, forecasts in list(daily_forecasts.items())[:days]:
|
| 150 |
+
day_name = datetime.datetime.strptime(date, '%Y-%m-%d').strftime('%A, %B %d')
|
| 151 |
+
temps = [f['main']['temp'] for f in forecasts]
|
| 152 |
+
conditions = [f['weather'][0]['description'] for f in forecasts]
|
| 153 |
+
|
| 154 |
+
min_temp = min(temps)
|
| 155 |
+
max_temp = max(temps)
|
| 156 |
+
most_common_condition = max(set(conditions), key=conditions.count)
|
| 157 |
+
|
| 158 |
+
forecast_info += f"📅 {day_name}:\n"
|
| 159 |
+
forecast_info += f" Temperature: {min_temp:.1f}°C - {max_temp:.1f}°C\n"
|
| 160 |
+
forecast_info += f" Condition: {most_common_condition.title()}\n\n"
|
| 161 |
+
|
| 162 |
+
return forecast_info.strip()
|
| 163 |
+
|
| 164 |
+
except requests.exceptions.RequestException as e:
|
| 165 |
+
return f"Error fetching forecast data: {str(e)}"
|
| 166 |
+
except Exception as e:
|
| 167 |
+
return f"Unexpected error: {str(e)}"
|
| 168 |
+
|
| 169 |
+
@tool
|
| 170 |
+
def search_local_events(city: str, query: str = "events") -> str:
|
| 171 |
+
"""A tool that searches for local events in a specific city using web search.
|
| 172 |
+
Args:
|
| 173 |
+
city: The name of the city to search events in
|
| 174 |
+
query: Optional search query to refine results (default: 'events')
|
| 175 |
+
"""
|
| 176 |
+
try:
|
| 177 |
+
# Use DuckDuckGo search to find local events
|
| 178 |
+
search_tool = DuckDuckGoSearchTool()
|
| 179 |
+
search_query = f"{query} in {city} today this week upcoming"
|
| 180 |
+
|
| 181 |
+
results = search_tool(search_query)
|
| 182 |
+
|
| 183 |
+
if not results or "No results found" in str(results):
|
| 184 |
+
return f"No events found for '{query}' in {city}. Try searching with different keywords."
|
| 185 |
+
|
| 186 |
+
return f"Local events in {city}:\n\n{results}"
|
| 187 |
+
|
| 188 |
+
except Exception as e:
|
| 189 |
+
return f"Error searching for events: {str(e)}"
|
| 190 |
+
|
| 191 |
+
@tool
|
| 192 |
+
def get_current_date_time() -> str:
|
| 193 |
+
"""A tool that returns the current date and time in UTC and local system time.
|
| 194 |
+
"""
|
| 195 |
+
try:
|
| 196 |
+
utc_time = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
|
| 197 |
+
local_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 198 |
+
|
| 199 |
+
return f"Current UTC time: {utc_time}\nLocal system time: {local_time}"
|
| 200 |
+
except Exception as e:
|
| 201 |
+
return f"Error getting current time: {str(e)}"
|
| 202 |
+
|
| 203 |
|
| 204 |
final_answer = FinalAnswerTool()
|
| 205 |
|
|
|
|
| 222 |
|
| 223 |
agent = CodeAgent(
|
| 224 |
model=model,
|
| 225 |
+
tools=[
|
| 226 |
+
final_answer,
|
| 227 |
+
get_current_time_in_timezone,
|
| 228 |
+
get_weather_by_city,
|
| 229 |
+
get_weather_forecast,
|
| 230 |
+
search_local_events,
|
| 231 |
+
get_current_date_time,
|
| 232 |
+
my_custom_tool
|
| 233 |
+
], ## add your tools here (don't remove final answer)
|
| 234 |
max_steps=6,
|
| 235 |
verbosity_level=1,
|
| 236 |
grammar=None,
|