MHamdan's picture
Upload tool
841e77b verified
raw
history blame
2.87 kB
from smolagents import Tool
from typing import Any, Optional
class SimpleTool(Tool):
name = "calculate_journey_metrics"
description = "Calculates journey metrics including distance and time."
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 journey metrics including distance and time.
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: Journey distance and estimated time.
"""
from geopy.geocoders import Nominatim
from geopy.distance import geodesic
try:
# Initialize geocoder
geolocator = Nominatim(user_agent="journey_metrics_calculator")
# Get coordinates
start = geolocator.geocode(start_location)
end = geolocator.geocode(destination_location)
if not start or not end:
return "Could not find one or both locations"
# Calculate distance
distance_km = geodesic(
(start.latitude, start.longitude),
(end.latitude, end.longitude)
).kilometers
# Define speeds (km/h)
speeds = {
'driving': 60,
'walking': 5,
'bicycling': 15,
'transit': 30
}
# Get speed for mode
speed = speeds.get(transportation_mode, speeds['driving'])
# Calculate time
hours = distance_km / speed
# Format time string
if hours < 1:
time_str = f"{int(hours * 60)} 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"
return (
f"Journey metrics:\n"
f"Distance: {distance_km:.1f} kilometers\n"
f"Estimated time by {transportation_mode or 'driving'}: {time_str}"
)
except Exception as e:
return f"Error calculating journey metrics: {str(e)}"