from typing import Any, Optional from smolagents.tools import Tool import requests import smolagents class GetWeatherTool(Tool): name = "get_weather" description = "Get the weather information for a given latitude and longitude." inputs = {'lat': {'type': 'number', 'description': 'Latitude, decimal (-90; 90).'}, 'lon': {'type': 'number', 'description': 'Longitude, decimal (-180; 180).'}} output_type = "any" def forward(self, lat: float, lon: float) -> Any: try: import requests import os from urllib.parse import quote from requests.exceptions import RequestException except ImportError as e: raise ImportError( "You must install packages `requests` and `urllib` to run this tool: for instance run `pip install requests urllib`." ) from e try: url = "https://api.openweathermap.org/data/3.0/onecall?lat=" + str(lat) + "&lon=" + str(lon) + "&appid=" + os.environ["WEATHER_API_KEY"] # Send a GET request to the URL with a 20-second timeout response = requests.get(url, timeout=20) response.raise_for_status() # Raise an exception for bad status codes return response.json() except requests.exceptions.Timeout: return "The request timed out. Please try again later or check the URL." except RequestException as e: return f"Error fetching the api: {str(e)}" except Exception as e: return f"An unexpected error occurred: {str(e)}"