File size: 2,346 Bytes
f8fca49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from typing import Any, Optional
from smolagents.tools import Tool
import datetime
import re # 're' is in your allowed libraries

class GetCurrentTimeTool(Tool):
    name = "get_current_time"
    description = "Gets the current time for a given timezone. Provide timezone as a UTC offset (e.g., '+05:00', '-03:30', 'Z' for UTC) or 'UTC'."
    inputs = {'timezone': {'type': 'string', 'description': 'The timezone for which to get the current time (e.g., "+05:00", "-03:30", "UTC").'}}
    output_type = "string"

    def forward(self, timezone: str) -> str:
        try:
            # Handle UTC explicitly
            if timezone.upper() == "UTC" or timezone.upper() == "Z":
                # Get current UTC time and set its timezone info
                now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
                return now.strftime("%Y-%m-%d %H:%M:%S %Z%z")

            # Try to parse as a fixed offset (e.g., +HH:MM or -HH:MM)
            # Using regex to extract sign, hours, and minutes from the offset string
            match = re.match(r"([+-])(\d{2}):(\d{2})$", timezone)
            if match:
                sign = 1 if match.group(1) == '+' else -1
                hours = int(match.group(2))
                minutes = int(match.group(3))
                
                # Create a timedelta object for the offset
                offset_delta = datetime.timedelta(hours=sign * hours, minutes=sign * minutes)
                
                # Create a timezone object with the calculated offset
                tz_info = datetime.timezone(offset_delta)
                
                # Get the current time in that specific timezone
                now = datetime.datetime.now(tz_info)
                return now.strftime("%Y-%m-%d %H:%M:%S %Z%z")
            else:
                # If the format doesn't match, return an error
                return f"Error: Invalid timezone format '{timezone}'. Please provide a UTC offset (e.g., '+05:00', '-03:30', 'Z' for UTC) or 'UTC'."

        except Exception as e:
            # Catch any other unexpected errors
            return f"An unexpected error occurred: {str(e)}"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.is_initialized = False # This can be used to track if the tool has been initialized