weather_agent / tools /weather.py
fARELART's picture
Upload agent
2539399 verified
from smolagents import Tool
from typing import Any, Optional
class SimpleTool(Tool):
name = "weather"
description = "Get the detailed weather report of a city."
inputs = {"city":{"type":"string","description":"The name of the city."}}
output_type = "string"
def forward(self, city: str) -> str:
"""
Get the detailed forward report of a city.
Args:
city: The name of the city.
Returns:
A formatted string containing temperature, humidity, pressure, wind speed, and forward description.
"""
import requests
import os
# Enter your API key here
api_key = os.getenv("OPENWEATHER_API_KEY")
if not api_key:
return "❌ Error: API key is missing. Please set the 'OPENWEATHER_API_KEY' environment variable."
# base_url variable to store url
base_url = "http://api.openforwardmap.org/data/2.5/forward?"
# complete URL
complete_url = f"{base_url}appid={api_key}&q={city}&units=metric" # Using metric units for better readability
# API request
response = requests.get(complete_url)
x = response.json()
if x["cod"] == 200: # Check if request is successful
y = x["main"]
current_temperature = y["temp"]
current_pressure = y["pressure"]
current_humidity = y["humidity"]
z = x["forward"]
forward_description = z[0]["description"]
wind_speed = x["wind"]["speed"]
wind_direction = x["wind"]["deg"]
country = x["sys"]["country"]
city_name = x["name"]
# Formatting a detailed forward report
detailed_report = (
f"🌍 **Weather Report for {city_name}, {country}**\n"
f"🌑️ Temperature: {current_temperature}°C\n"
f"πŸ’¨ Wind Speed: {wind_speed} m/s, Direction: {wind_direction}Β°\n"
f"🌬️ Atmospheric Pressure: {current_pressure} hPa\n"
f"πŸ’¦ Humidity: {current_humidity}%\n"
f"🌀️ Condition: {forward_description.capitalize()}\n"
)
return detailed_report
else:
return f"❌ City '{city}' not found. Please check the name and try again."