First_agent / tools /weather.py
cjb97's picture
moved api key out of code
8d2dbda
raw
history blame
1.93 kB
from smolagents.tools import Tool
import requests
from typing import Any, Optional
import os # Added for accessing environment variables
class WeatherTool(Tool):
"""Tool for getting weather information for a location."""
name = "get_weather"
description = "Get the current weather for a specified location."
output_type = "string"
inputs = {
"location": {
"type": "string",
"description": "A string representing a city or location (e.g., 'New York', 'Paris, France')."
}
}
def __call__(self, location: str) -> str:
"""
Get the current weather for a specified location.
Args:
location: A string representing a city or location (e.g., 'New York', 'Paris, France').
Returns:
A string with the current weather information.
"""
try:
# Using OpenWeatherMap API with a free tier (limited requests)
api_key = os.getenv('OPENWEATHERMAP_API_KEY') # OpenWeatherMap API key from env variable
url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"
response = requests.get(url)
data = response.json()
if response.status_code == 200:
temp = data["main"]["temp"]
weather = data["weather"][0]["description"]
humidity = data["main"]["humidity"]
wind_speed = data["wind"]["speed"]
return f"The current weather in {location} is {temp}°C with {weather}. Humidity: {humidity}%, Wind speed: {wind_speed} m/s."
else:
return f"Error fetching weather for {location}: {data.get('message', 'Unknown error')}"
except Exception as e:
return f"Error fetching weather for {location}: {str(e)}"
forward = __call__