Spaces:
Sleeping
Sleeping
from smolagents import Tool | |
from typing import Any, Optional | |
class SimpleTool(Tool): | |
name = "calculate_journey_metrics" | |
description = "Calculates comprehensive journey metrics including distance and time using OpenStreetMap." | |
inputs = {"start_location":{"type":"string","description":"The starting point of the journey."},"destination_location":{"type":"string","description":"The endpoint of the journey."},"transportation_mode":{"type":"string","nullable":True,"description":"Mode of transport ('driving', 'walking', 'bicycling', or 'transit'). Defaults to 'driving'."}} | |
output_type = "string" | |
def forward(self, start_location: str, destination_location: str, transportation_mode: Optional[str] = None) -> str: | |
"""Calculates comprehensive journey metrics including distance and time using OpenStreetMap. | |
Args: | |
start_location: The starting point of the journey. | |
destination_location: The endpoint of the journey. | |
transportation_mode: Mode of transport ('driving', 'walking', 'bicycling', or 'transit'). | |
Defaults to 'driving'. | |
Returns: | |
str: A detailed description of the journey including distance and time. | |
""" | |
import osmnx as ox | |
from geopy.distance import geodesic | |
try: | |
# Get coordinates | |
start_coords = ox.geocode(start_location) | |
end_coords = ox.geocode(destination_location) | |
# Calculate straight-line distance | |
distance_km = geodesic(start_coords, end_coords).kilometers | |
# Define speeds (km/h) | |
speeds = { | |
'driving': 60, | |
'walking': 5, | |
'bicycling': 15, | |
'transit': 25 | |
} | |
# Get speed for mode | |
speed = speeds.get(transportation_mode, speeds['driving']) | |
# Calculate time | |
hours = distance_km / speed | |
minutes = hours * 60 | |
# Format response based on time | |
if minutes < 60: | |
time_str = f"{int(minutes)} minutes" | |
elif hours < 24: | |
hrs = int(hours) | |
mins = int((hours - hrs) * 60) | |
time_str = f"{hrs} hours and {mins} minutes" | |
else: | |
days = hours / 24 | |
time_str = f"{days:.1f} days" | |
response = ( | |
f"Journey metrics:\n" | |
f"Distance: {distance_km:.1f} kilometers\n" | |
f"Estimated time: {time_str}\n" | |
f"Mode: {transportation_mode or 'driving'}" | |
) | |
return response | |
except Exception as e: | |
return f"Error calculating journey metrics: {str(e)}" |