from asyncio import timeout from warnings import catch_warnings import os from smolagents.tools import Tool import requests class GetWeatherTool(Tool): name="get_weather" description="Get weather information for a specific city using OpenWeatherAPI. Use this tool to fetch current weather data for a given city using the OpenWeatherAPI (e.g., 'Delhi')." inputs={'city':{'type':'string', 'description':'The name of the city for which to fetch weather information (e.g., "Delhi").' } } output_type="string" def __init__(self, api_key:str=None, timeout:int=10): super().__init__() self.api_key=api_key or os.getenv("OPENWEATHER_API_KEY") self.timeout=timeout self.base_url="http://api.openweathermap.org/data/2.5/weather" self.session=requests.Session() def forward(self, city:str) -> str: params={ 'q':city, 'appid':self.api_key, 'units':'metric' } try: res=self.session.get(self.base_url, params=params, timeout=self.timeout) res.raise_for_status() data=res.json() temp=data['main']['temp'] desc=data['weather'][0]['description'] return f"{city}:{temp} C, {desc}" except Exception as e: return f"failed to fetch weather for {city}: {str(e)}"