Spaces:
Running
Running
File size: 892 Bytes
a31f556 | 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 | # backend/memory/working_memory.py
# In-memory store for current session only — cleared on session end
import time
class WorkingMemory:
def __init__(self):
self.messages: list[dict] = []
def add(self, role: str, content: str):
self.messages.append({"role": role, "content": content, "ts": time.time()})
def get_context_window(self, max_tokens=4000) -> list[dict]:
# trim from oldest until under max_tokens
# Crude approximation: 1 token ~= 4 chars
current_tokens = 0
window = []
for msg in reversed(self.messages):
msg_tokens = len(msg["content"]) // 4
if current_tokens + msg_tokens > max_tokens:
break
window.insert(0, msg)
current_tokens += msg_tokens
return window
def clear(self):
self.messages.clear()
|