File size: 3,336 Bytes
94d81ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from typing import Any, Optional
from smolagents.tools import Tool
import pytz
import datetime
import re
from duckduckgo_search import DDGS

class CityTimeTool(Tool):
    name = "city_time"
    description = "Get the current local time for any city by searching for its timezone and converting current UTC time."
    inputs = {'city': {'type': 'string', 'description': 'The name of the city to get the current time for'}}
    output_type = "string"
    
    def __init__(self):
        super().__init__()
        self.ddgs = DDGS()
        
    def _find_timezone(self, city: str) -> str:
        """Search for the timezone of a given city."""
        # Search for timezone information
        query = f"{city} timezone UTC time zone"
        results = list(self.ddgs.text(query, max_results=3))
        
        if not results:
            raise Exception(f"Could not find timezone information for {city}")
            
        # Common timezone patterns in city names
        common_cities = {
            'new york': 'America/New_York',
            'london': 'Europe/London',
            'paris': 'Europe/Paris',
            'tokyo': 'Asia/Tokyo',
            'sydney': 'Australia/Sydney',
            'dubai': 'Asia/Dubai',
            'singapore': 'Asia/Singapore',
            'hong kong': 'Asia/Hong_Kong',
            'los angeles': 'America/Los_Angeles',
            'chicago': 'America/Chicago',
            'toronto': 'America/Toronto',
            'sao paulo': 'America/Sao_Paulo',
            'rio': 'America/Sao_Paulo',
            'moscow': 'Europe/Moscow',
            'berlin': 'Europe/Berlin',
            'madrid': 'Europe/Madrid',
            'rome': 'Europe/Rome',
            'beijing': 'Asia/Shanghai',
            'shanghai': 'Asia/Shanghai',
            'seoul': 'Asia/Seoul',
            'bangkok': 'Asia/Bangkok',
            'cairo': 'Africa/Cairo',
            'johannesburg': 'Africa/Johannesburg',
            'mexico city': 'America/Mexico_City',
            'buenos aires': 'America/Argentina/Buenos_Aires'
        }
        
        # Check if city is in common cities first
        city_lower = city.lower()
        if city_lower in common_cities:
            return common_cities[city_lower]
            
        # Try to extract timezone from search results
        for result in results:
            text = result['body'].lower()
            # Look for common timezone patterns
            for known_city, timezone in common_cities.items():
                if known_city in text and city_lower in text:
                    return timezone
                    
        # Default to UTC if we can't determine the timezone
        raise Exception(f"Could not determine timezone for {city}. Please try a major city name.")

    def forward(self, city: str) -> str:
        try:
            # Find the timezone
            timezone_str = self._find_timezone(city)
            
            # Get current time in that timezone
            tz = pytz.timezone(timezone_str)
            utc_now = datetime.datetime.now(pytz.UTC)
            local_time = utc_now.astimezone(tz)
            
            return f"Current time in {city} ({timezone_str}) is: {local_time.strftime('%Y-%m-%d %H:%M:%S %Z')}"
            
        except Exception as e:
            return f"Error getting time for {city}: {str(e)}"