""" Per-conversation short-term memory. Memory is scoped to a conversation_id and reset when a new conversation starts (new id -> fresh state) or is deleted. A background TTL evicts stale ones. Swap ConversationStore for Redis/DB later without touching the agent. """ from __future__ import annotations import threading import time from dataclasses import dataclass, field @dataclass class Turn: role: str # 'user' | 'assistant' text: str tool: str = "" @dataclass class ConversationState: conv_id: str turns: list[Turn] = field(default_factory=list) context: dict = field(default_factory=dict) # last_tool, artifacts, ... updated_at: float = field(default_factory=time.time) def add(self, role: str, text: str, tool: str = "") -> None: self.turns.append(Turn(role, text, tool)) self.updated_at = time.time() def transcript(self, max_turns: int = 8) -> str: out = [] for t in self.turns[-max_turns:]: who = "Người dùng" if t.role == "user" else "Trợ lý" tag = f" [{t.tool}]" if t.tool else "" out.append(f"{who}{tag}: {t.text}") return "\n".join(out) class ConversationStore: def __init__(self, ttl_seconds: int = 3 * 3600): self._d: dict[str, ConversationState] = {} self._lock = threading.Lock() self._ttl = ttl_seconds def get(self, conv_id: str | None) -> ConversationState: conv_id = conv_id or "default" with self._lock: self._evict() st = self._d.get(conv_id) if st is None: st = ConversationState(conv_id) self._d[conv_id] = st return st def reset(self, conv_id: str | None) -> None: with self._lock: self._d.pop(conv_id or "default", None) def _evict(self) -> None: now = time.time() for k in [k for k, v in self._d.items() if now - v.updated_at > self._ttl]: self._d.pop(k, None) STORE = ConversationStore()