feat: add timezone conversion for time tool (#9393)

This commit is contained in:
zhuhao 2024-10-16 11:17:40 +08:00 committed by GitHub
parent dd22e78515
commit 7d3dad3d1d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,48 @@
from datetime import datetime
from typing import Any, Union
import pytz
from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.errors import ToolInvokeError
from core.tools.tool.builtin_tool import BuiltinTool
class TimezoneConversionTool(BuiltinTool):
def _invoke(
self,
user_id: str,
tool_parameters: dict[str, Any],
) -> Union[ToolInvokeMessage, list[ToolInvokeMessage]]:
"""
Convert time to equivalent time zone
"""
current_time = tool_parameters.get("current_time")
current_timezone = tool_parameters.get("current_timezone", "Asia/Shanghai")
target_timezone = tool_parameters.get("target_timezone", "Asia/Tokyo")
target_time = self.timezone_convert(current_time, current_timezone, target_timezone)
if not target_time:
return self.create_text_message(
f"Invalid datatime and timezone: {current_time},{current_timezone},{target_timezone}"
)
return self.create_text_message(f"{target_time}")
@staticmethod
def timezone_convert(current_time: str, source_timezone: str, target_timezone: str) -> str:
"""
Convert a time string from source timezone to target timezone.
"""
time_format = "%Y-%m-%d %H:%M:%S"
try:
# get source timezone
input_timezone = pytz.timezone(source_timezone)
# get target timezone
output_timezone = pytz.timezone(target_timezone)
local_time = datetime.strptime(current_time, time_format)
datetime_with_tz = input_timezone.localize(local_time)
# timezone convert
converted_datetime = datetime_with_tz.astimezone(output_timezone)
return converted_datetime.strftime(format=time_format)
except Exception as e:
raise ToolInvokeError(str(e))

View File

@ -0,0 +1,44 @@
identity:
name: timezone_conversion
author: zhuhao
label:
en_US: convert time to equivalent time zone
zh_Hans: 时区转换
description:
human:
en_US: A tool to convert time to equivalent time zone
zh_Hans: 时区转换
llm: A tool to convert time to equivalent time zone
parameters:
- name: current_time
type: string
required: true
form: llm
label:
en_US: current time
zh_Hans: 当前时间
human_description:
en_US: current time, such as 2024-1-1 0:0:0
zh_Hans: 当前时间, 比如2024-1-1 0:0:0
- name: current_timezone
type: string
required: true
form: llm
label:
en_US: Current Timezone
zh_Hans: 当前时区
human_description:
en_US: Current Timezone, such as Asia/Shanghai
zh_Hans: 当前时区, 比如Asia/Shanghai
default: Asia/Shanghai
- name: target_timezone
type: string
required: true
form: llm
label:
en_US: Target Timezone
zh_Hans: 目标时区
human_description:
en_US: Target Timezone, such as Asia/Tokyo
zh_Hans: 目标时区, 比如Asia/Tokyo
default: Asia/Tokyo