-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemantic_cache.py
More file actions
62 lines (46 loc) · 1.65 KB
/
semantic_cache.py
File metadata and controls
62 lines (46 loc) · 1.65 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from __future__ import annotations
import hashlib
import json
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any, Protocol
from settings import Settings
class SemanticCache(Protocol):
def get(self, key: str) -> Any | None:
...
def set(self, key: str, value: Any) -> None:
...
class NullSemanticCache:
def get(self, key: str) -> Any | None:
return None
def set(self, key: str, value: Any) -> None:
return None
class MemorySemanticCache:
def __init__(self, max_entries: int = 512) -> None:
self._max_entries = max(1, int(max_entries))
self._entries: OrderedDict[str, Any] = OrderedDict()
def get(self, key: str) -> Any | None:
if key not in self._entries:
return None
self._entries.move_to_end(key)
return self._entries[key]
def set(self, key: str, value: Any) -> None:
self._entries[key] = value
self._entries.move_to_end(key)
while len(self._entries) > self._max_entries:
self._entries.popitem(last=False)
def build_cache_key(operation: str, payload: dict[str, Any]) -> str:
serialized = json.dumps(
{
"operation": operation,
"payload": payload,
},
sort_keys=True,
ensure_ascii=True,
separators=(",", ":"),
)
return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
def build_semantic_cache(settings: Settings) -> SemanticCache:
if settings.semantris_cache_backend == "memory":
return MemorySemanticCache(max_entries=settings.semantris_cache_max_entries)
return NullSemanticCache()