Files
baji-vc/gateway/server_clock.py
T

24 lines
1.3 KiB
Python

"""Request-local wall clock. Durations/deadlines must continue using monotonic time."""
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
import re
class ServerClock:
def __init__(self, zone='Asia/Shanghai', now=None):
self.zone = ZoneInfo(zone) # Invalid configuration fails before any HTTP request.
self.now = now or (lambda: datetime.now(timezone.utc))
def messages(self, messages):
copied = [dict(message) for message in messages]
systems = [re.sub(r'\n*\[gateway_request_clock\].*?\[/gateway_request_clock\]', '',
message['content'], flags=re.S) for message in copied if message.get('role') == 'system']
# Do not mutate the caller's persona/history, or accept a client time as authority.
instant = self.now()
if instant.tzinfo is None:
raise ValueError('server wall clock must be timezone aware')
reference = ('[gateway_request_clock]\n当前服务器时间:' + instant.astimezone(self.zone).isoformat(timespec='seconds') +
'\n时区:' + self.zone.key + '。这是本次请求的时间参考,不代表用户所在地。\n[/gateway_request_clock]')
return [{'role': 'system', 'content': '\n\n'.join(systems + [reference])}] + [
message for message in copied if message.get('role') != 'system']