Spaces:
Sleeping
Sleeping
created new tool get_current_time
Browse files- tools/get_current_time +47 -0
tools/get_current_time
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional
|
| 2 |
+
from smolagents.tools import Tool
|
| 3 |
+
import datetime
|
| 4 |
+
import re # 're' is in your allowed libraries
|
| 5 |
+
|
| 6 |
+
class GetCurrentTimeTool(Tool):
|
| 7 |
+
name = "get_current_time"
|
| 8 |
+
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'."
|
| 9 |
+
inputs = {'timezone': {'type': 'string', 'description': 'The timezone for which to get the current time (e.g., "+05:00", "-03:30", "UTC").'}}
|
| 10 |
+
output_type = "string"
|
| 11 |
+
|
| 12 |
+
def forward(self, timezone: str) -> str:
|
| 13 |
+
try:
|
| 14 |
+
# Handle UTC explicitly
|
| 15 |
+
if timezone.upper() == "UTC" or timezone.upper() == "Z":
|
| 16 |
+
# Get current UTC time and set its timezone info
|
| 17 |
+
now = datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
|
| 18 |
+
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z")
|
| 19 |
+
|
| 20 |
+
# Try to parse as a fixed offset (e.g., +HH:MM or -HH:MM)
|
| 21 |
+
# Using regex to extract sign, hours, and minutes from the offset string
|
| 22 |
+
match = re.match(r"([+-])(\d{2}):(\d{2})$", timezone)
|
| 23 |
+
if match:
|
| 24 |
+
sign = 1 if match.group(1) == '+' else -1
|
| 25 |
+
hours = int(match.group(2))
|
| 26 |
+
minutes = int(match.group(3))
|
| 27 |
+
|
| 28 |
+
# Create a timedelta object for the offset
|
| 29 |
+
offset_delta = datetime.timedelta(hours=sign * hours, minutes=sign * minutes)
|
| 30 |
+
|
| 31 |
+
# Create a timezone object with the calculated offset
|
| 32 |
+
tz_info = datetime.timezone(offset_delta)
|
| 33 |
+
|
| 34 |
+
# Get the current time in that specific timezone
|
| 35 |
+
now = datetime.datetime.now(tz_info)
|
| 36 |
+
return now.strftime("%Y-%m-%d %H:%M:%S %Z%z")
|
| 37 |
+
else:
|
| 38 |
+
# If the format doesn't match, return an error
|
| 39 |
+
return f"Error: Invalid timezone format '{timezone}'. Please provide a UTC offset (e.g., '+05:00', '-03:30', 'Z' for UTC) or 'UTC'."
|
| 40 |
+
|
| 41 |
+
except Exception as e:
|
| 42 |
+
# Catch any other unexpected errors
|
| 43 |
+
return f"An unexpected error occurred: {str(e)}"
|
| 44 |
+
|
| 45 |
+
def __init__(self, *args, **kwargs):
|
| 46 |
+
super().__init__(*args, **kwargs)
|
| 47 |
+
self.is_initialized = False # This can be used to track if the tool has been initialized
|