pgdemo2 / cache.py
Beracles
add cache module
18bfb47
raw
history blame
895 Bytes
import os
import json
from pgsoft.pgdate.date_utils import beijing
cache_ai = {}
def normalize_text(text: str) -> str:
tmp = text.split(" ")
tmp = [word for word in tmp if word != ""]
return " ".join(tmp)
def load_cache(filepath: str):
"""load cached ai calling from a json file"""
global cache_ai
if os.path.exists(filepath):
with open(filepath, "r+") as f:
cache_ai = json.load(f)
def add_cache(command: str, result: dict):
"""add a cache of ai calling"""
command = normalize_text(command)
global cache_ai
cache_ai[command] = result
print(f'[cache] added "{command}"')
def get_cache(command: str) -> dict | None:
"""return a cached ai calling with new "timestamp" """
command = normalize_text(command)
outp = cache_ai.get(command)
if outp:
outp["timestamp"] = beijing().__str__()
return outp