First_agent_template / tools /get_location.py
yplam's picture
add location and weather tool
4f981cb
raw
history blame
1.52 kB
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)}"