Alfred_RAG / tools /weather_tool.py
chughtaihamad's picture
Main commit
b9744a5
from smolagents import Tool
import requests
class WeatherTool(Tool):
name = "weather"
description = "Returns current weather information for a given location. Use `/weather <location>` to call."
inputs = {"location": {"type": "string", "description": "City or location name"}}
output_type = "string"
def __init__(self, timeout: int = 5):
self.timeout = timeout
def forward(self, location: str) -> str:
# Use Open-Meteo geocoding + weather APIs (no API key required)
try:
geo = requests.get(
"https://geocoding-api.open-meteo.com/v1/search",
params={"name": location, "count": 1},
timeout=self.timeout,
).json()
if not geo.get("results"):
return f"Could not find location: {location}"
loc = geo["results"][0]
lat, lon = loc["latitude"], loc["longitude"]
weather = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={"latitude": lat, "longitude": lon, "current_weather": True},
timeout=self.timeout,
).json()
cw = weather.get("current_weather")
if not cw:
return f"No weather data available for {location} (lat={lat}, lon={lon})"
return f"Weather for {loc.get('name', location)}, {loc.get('country','')}: {cw.get('temperature')}°C, wind {cw.get('windspeed')} km/h, conditions code {cw.get('weathercode')}"
except Exception as e:
return f"Weather lookup failed: {e}"