File size: 3,363 Bytes
5d05d59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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)}"