First_agent_template / tools /time_tools.py
h8hawk's picture
add gitignore, add fuzzy search for matching places
8e92f09
Raw History Blame Contribute Delete
2.62 kB
import datetime
import pytz
from smolagents import tool
from thefuzz import fuzz
from typing import Tuple, Optional
def _format_time(dt: datetime.datetime) -> str:
"""Format a datetime object into a string.
Args:
dt: The datetime object to format
Returns:
A formatted time string
"""
return dt.strftime("%Y-%m-%d %H:%M:%S")
def _find_matching_timezone(
timezone: str, min_score: int = 70
) -> Optional[Tuple[str, int]]:
"""Find the best matching timezone using fuzzy matching.
Args:
timezone: The timezone string to match
min_score: Minimum fuzzy matching score to consider a valid match
Returns:
A tuple of (matched_timezone, score) or None if no match found
"""
best_match = None
best_score = 0
for tz_name in pytz.all_timezones:
score = fuzz.partial_token_sort_ratio(timezone.lower(), tz_name.lower())
if score > best_score:
best_score = score
best_match = tz_name
if best_score >= min_score and best_match is not None:
return (best_match, best_score)
return None
def _get_time_in_timezone(timezone_name: str) -> datetime.datetime:
"""Get the current time in the specified timezone.
Args:
timezone_name: A valid timezone name
Returns:
A datetime object with the current time in the specified timezone
"""
tz = pytz.timezone(timezone_name)
return datetime.datetime.now(tz)
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
Fuzzy matching is applied to find the closest timezone if exact match fails.
Returns:
A string with the current time in the specified timezone or an error message.
"""
# First try exact match
try:
local_time = _format_time(_get_time_in_timezone(timezone))
return f"The current local time in {timezone} is: {local_time}"
except pytz.exceptions.UnknownTimeZoneError:
# If exact match fails, try fuzzy matching
match_result = _find_matching_timezone(timezone)
if match_result:
best_match, _ = match_result
local_time = _format_time(_get_time_in_timezone(best_match))
return f"The current local time in {best_match} (matched from '{timezone}') is: {local_time}"
else:
return f"Could not find a close match for timezone '{timezone}'. Please try a valid timezone name."