Spaces:
Sleeping
Sleeping
Download tools/weather_tool.py from mahichr/First_agent_template: direct link, hf CLI and curl.
- Browser
- Download file 3.36 kB
-
https://huggingface.co/spaces/mahichr/First_agent_template/resolve/main/tools/weather_tool.py
- Command line
-
hf download hf://spaces/mahichr/First_agent_template/tools/weather_tool.py
-
curl -L -o weather_tool.py https://huggingface.co/spaces/mahichr/First_agent_template/resolve/main/tools/weather_tool.py
3.36 kB
| from typing import Any, Optional | |
| from smolagents.tools import Tool | |
| import requests | |
| import json | |
| class WeatherTool(Tool): | |
| name = "get_weather" | |
| description = "Gets current weather information for a specified city using OpenWeatherMap API." | |
| inputs = {'city': {'type': 'string', 'description': 'The name of the city to get weather information for (e.g., "New York", "London", "Tokyo")'}} | |
| output_type = "string" | |
| def __init__(self, api_key: Optional[str] = None, **kwargs): | |
| super().__init__() | |
| # You can get a free API key from https://openweathermap.org/api | |
| self.api_key = api_key or "demo_key" # Note: demo_key has limited functionality | |
| self.base_url = "https://api.openweathermap.org/data/2.5/weather" | |
| def forward(self, city: str) -> str: | |
| """ | |
| Fetches current weather data for the specified city. | |
| Args: | |
| city: Name of the city to get weather for | |
| Returns: | |
| Formatted string with weather information | |
| """ | |
| try: | |
| # Prepare API request parameters | |
| params = { | |
| 'q': city, | |
| 'appid': self.api_key, | |
| 'units': 'metric' # Use Celsius, can be changed to 'imperial' for Fahrenheit | |
| } | |
| # Make API request | |
| response = requests.get(self.base_url, params=params, timeout=10) | |
| # Check if request was successful | |
| if response.status_code == 401: | |
| return f"Weather API authentication failed. Please provide a valid OpenWeatherMap API key. You can get one free at https://openweathermap.org/api" | |
| elif response.status_code == 404: | |
| return f"City '{city}' not found. Please check the spelling and try again." | |
| elif response.status_code != 200: | |
| return f"Error fetching weather data: HTTP {response.status_code}" | |
| # Parse JSON response | |
| data = response.json() | |
| # Extract relevant information | |
| city_name = data.get('name', 'Unknown') | |
| country = data.get('sys', {}).get('country', 'Unknown') | |
| temp = data.get('main', {}).get('temp', 'N/A') | |
| feels_like = data.get('main', {}).get('feels_like', 'N/A') | |
| humidity = data.get('main', {}).get('humidity', 'N/A') | |
| pressure = data.get('main', {}).get('pressure', 'N/A') | |
| description = data.get('weather', [{}])[0].get('description', 'N/A') | |
| wind_speed = data.get('wind', {}).get('speed', 'N/A') | |
| # Format the weather information | |
| weather_info = f"""## Weather in {city_name}, {country} | |
| **Current Conditions:** {description.title()} | |
| **Temperature:** {temp}°C (feels like {feels_like}°C) | |
| **Humidity:** {humidity}% | |
| **Pressure:** {pressure} hPa | |
| **Wind Speed:** {wind_speed} m/s | |
| *Weather data provided by OpenWeatherMap*""" | |
| return weather_info | |
| except requests.RequestException as e: | |
| return f"Network error while fetching weather data: {str(e)}" | |
| except json.JSONDecodeError: | |
| return "Error parsing weather data response" | |
| except Exception as e: | |
| return f"Unexpected error while fetching weather data: {str(e)}" | |