| import os |
| from typing import Dict |
| from datetime import datetime |
| import pytz |
|
|
| from smolagents.tools import Tool |
|
|
| class WeatherApiTool(Tool): |
| name = "weather_api" |
| description = "Fetches the weather for a given location and date." |
| inputs = {'location': {'type': 'string', 'description': 'The location for which to fetch the weather.'}, 'date': {'type': 'string', 'description': 'The date for which to fetch the weather.'}} |
| output_type = "any" |
| |
| def __init__(self, *args, **kwargs): |
| super().__init__(*args, **kwargs) |
| self.api_key = os.environ.get("OPEN_WEATHER_MAP_API_KEY") |
| |
| |
| self.local_tz = pytz.timezone("Europe/Brussels") |
|
|
| def forward(self, location: str, date: str) -> Dict: |
| import requests |
| import json |
| |
| |
| geocoding_url = f"http://api.openweathermap.org/geo/1.0/direct?q={location}&appid={self.api_key}" |
| try: |
| response = requests.get(geocoding_url) |
| except requests.exceptions.RequestException as e: |
| return f"Error fetching geocoding data: {str(e)}" |
| geocoding_data = response.json() |
| |
| |
| lat = geocoding_data[0]["lat"] |
| lon = geocoding_data[0]["lon"] |
| country = geocoding_data[0]["country"] |
| state = geocoding_data[0]["state"] |
| |
| |
| weather_url = f"http://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude=current,minutely,hourly,alerts&appid={self.api_key}" |
| try: |
| response = requests.get(weather_url) |
| except requests.exceptions.RequestException as e: |
| return f"Error fetching weather data: {str(e)}" |
| weather_data = response.json() |
| |
| |
| for day in weather_data["daily"]: |
| date_time = datetime.fromtimestamp(day["dt"]) |
| if date_time.strftime('%Y-%m-%d') == date: |
| break |
| |
| return day |
| |