Spaces:
Sleeping
Sleeping
| from smolagents.tools import tool | |
| import requests | |
| import os | |
| import re | |
| from typing import Optional | |
| def get_weather(location: str) -> str: | |
| """Get the current weather for a specified location. | |
| Args: | |
| location: A string representing a city (e.g., 'New York', 'Paris'). | |
| Returns: | |
| str: A json blob containing the current weather information for that city. | |
| """ | |
| # Validate that location contains only allowed characters: letters, digits, spaces, and hyphens | |
| if not re.fullmatch(r'[A-Za-z0-9\s-]+', location): | |
| return "Error: Location contains invalid characters. Only letters, digits, spaces, and hyphens are allowed." | |
| try: | |
| # Get the API key from environment variables | |
| api_key = os.getenv('OPENWEATHERMAP_API_KEY') | |
| if not api_key: | |
| return "Error: OPENWEATHERMAP_API_KEY not set in environment variables." | |
| # First, geocode the location to get latitude and longitude | |
| geo_url = f"http://api.openweathermap.org/geo/1.0/direct?q={location}&limit=1&appid={api_key}" | |
| geo_response = requests.get(geo_url) | |
| geo_data = geo_response.json() | |
| if not geo_data: | |
| return f"Error: Could not geocode location '{location}'." | |
| lat = geo_data[0].get('lat') | |
| lon = geo_data[0].get('lon') | |
| if lat is None or lon is None: | |
| return f"Error: Latitude or longitude not found for location '{location}'." | |
| # Call the OpenWeatherMap weather API 2.5 endpoint | |
| weather_url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={api_key}&units=imperial" | |
| weather_response = requests.get(weather_url) | |
| weather_data = weather_response.json() | |
| if weather_response.status_code == 200: | |
| temp = weather_data.get('main', {}).get('temp', 'N/A') | |
| weather_desc = weather_data.get('weather', [{}])[0].get('description', 'N/A') | |
| humidity = weather_data.get('main', {}).get('humidity', 'N/A') | |
| wind_speed = weather_data.get('wind', {}).get('speed', 'N/A') | |
| return f"The current weather in {location} is {temp}°F with {weather_desc}. Humidity: {humidity}%, Wind speed: {wind_speed} mph." | |
| else: | |
| return f"Error fetching weather for {location}: {weather_data.get('message', 'Unknown error')}" | |
| except Exception as e: | |
| return f"Error fetching weather for {location}: {str(e)}" |