File size: 1,524 Bytes
4f981cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from smolagents.tools import Tool
import requests
from typing import Any, Optional


class GetLocationTool(Tool):
    name = "get_location"
    description = "Get geographical coordinates (lat, lon) by using name of the location (city name or area name)."
    inputs = {'name': {'type': 'string', 'description': 'The city name or area name of the location to check.'}}
    output_type = "any"

    def forward(self, name: str) -> Any:
        try:
            import requests
            import os
            from urllib.parse import quote
            from requests.exceptions import RequestException
        except ImportError as e:
            raise ImportError(
                "You must install packages `requests` and `urllib` to run this tool: for instance run `pip install requests urllib`."
            ) from e
        try:
            url = "http://api.openweathermap.org/geo/1.0/direct?q=" + quote(name) + "&limit=5&appid=" + os.environ["WEATHER_API_KEY"]
            # Send a GET request to the URL with a 20-second timeout
            response = requests.get(url, timeout=20)
            response.raise_for_status()  # Raise an exception for bad status codes
            return response.json()

        except requests.exceptions.Timeout:
            return "The request timed out. Please try again later or check the URL."
        except RequestException as e:
            return f"Error fetching the api: {str(e)}"
        except Exception as e:
            return f"An unexpected error occurred: {str(e)}"