Spaces:
Sleeping
Sleeping
File size: 2,300 Bytes
869e6ae 324e81a baa37e5 4a5001f 869e6ae 0818c89 869e6ae 4a5001f 869e6ae 324e81a 869e6ae f9aedb3 869e6ae f9aedb3 869e6ae f9aedb3 869e6ae f9aedb3 baa37e5 16aecb0 afa002b 869e6ae afa002b 869e6ae | 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 | 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")
# TODO: get the timezone from the location
self.local_tz = pytz.timezone("Europe/Brussels")
def forward(self, location: str, date: str) -> Dict:
import requests
import json
# Get the latitude and longitude of the location
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()
# TODO: match if multiple using IP country info
lat = geocoding_data[0]["lat"]
lon = geocoding_data[0]["lon"]
country = geocoding_data[0]["country"]
state = geocoding_data[0]["state"]
# Get the weather data for the location
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()
weather_data["location"] = location
weather_data["country"] = country
weather_data["state"] = state
# Extract the weather data for the specified date
for day in weather_data["daily"]:
date_time = datetime.fromtimestamp(day["dt"])
if date_time.strftime('%Y-%m-%d') == date:
break
return day
|