| from smolagents import Tool | |
| from typing import Any, Optional | |
| class SimpleTool(Tool): | |
| name = "get_coordinates" | |
| description = "Retrieves the geographical coordinates (latitude and longitude) of a city." | |
| inputs = {"city":{"type":"string","description":"The name of the city to retrieve coordinates for."}} | |
| output_type = "array" | |
| def forward(self, city: str) -> tuple[float, float]: | |
| """ | |
| Retrieves the geographical coordinates (latitude and longitude) of a city. | |
| Args: | |
| city (str): The name of the city to retrieve coordinates for. | |
| Returns: | |
| tuple[float, float]: The latitude and longitude of the city, or None if the coordinates could not be retrieved. | |
| """ | |
| import requests | |
| API_KEY = "d8376952ee1e3b3e591cec518a7d41cb" | |
| api_url = f"http://api.openweathermap.org/geo/1.0/direct?q={city}&limit=1&appid={API_KEY}" | |
| try: | |
| response = requests.get(api_url) | |
| response.raise_for_status() | |
| data = response.json() | |
| if data: | |
| return data[0]["lat"], data[0]["lon"] | |
| else: | |
| return None | |
| except (requests.RequestException, ValueError, KeyError) as e: | |
| print(f"Error retrieving coordinates: {e}") | |
| return None |