""" hf_core/memory.py ───────────────── MemoryBank — a lightweight key-value store for conversation history, generation metadata, and semantic context. """ from __future__ import annotations import time import json from dataclasses import dataclass, asdict, field from typing import List, Dict, Optional, Any @dataclass class MemoryEntry: id: int prompt: str response: str metadata: Dict[str, Any] timestamp: float = field(default_factory=time.time) def age_sec(self) -> float: return time.time() - self.timestamp def to_dict(self) -> dict: return asdict(self) class MemoryBank: """ Stores generation history. - Capped at `max_entries` (FIFO eviction). - Can dump / load from JSON. - Can build a context string for multi-turn conversations. """ def __init__(self, max_entries: int = 256): self._entries: List[MemoryEntry] = [] self._max = max_entries self._counter = 0 # ── write ───────────────────────────────────────────────────────────────── def store( self, prompt: str, response: str, metadata: Optional[Dict[str, Any]] = None, ) -> MemoryEntry: entry = MemoryEntry( id = self._counter, prompt = prompt, response = response, metadata = metadata or {}, ) self._entries.append(entry) self._counter += 1 if len(self._entries) > self._max: self._entries.pop(0) # FIFO eviction return entry # ── read ────────────────────────────────────────────────────────────────── def get(self, entry_id: int) -> Optional[MemoryEntry]: for e in self._entries: if e.id == entry_id: return e return None def recent(self, n: int = 5) -> List[MemoryEntry]: return self._entries[-n:] def search(self, keyword: str) -> List[MemoryEntry]: kw = keyword.lower() return [e for e in self._entries if kw in e.prompt.lower() or kw in e.response.lower()] # ── context builder ─────────────────────────────────────────────────────── def build_context( self, n: int = 4, user_tag: str = "User", bot_tag: str = "AI", ) -> str: """Build a multi-turn prompt context from recent entries.""" parts = [] for e in self.recent(n): parts.append(f"{user_tag}: {e.prompt.strip()}") parts.append(f"{bot_tag}: {e.response.strip()}") return "\n".join(parts) # ── persistence ─────────────────────────────────────────────────────────── def dump(self, path: str) -> None: with open(path, "w", encoding="utf-8") as f: json.dump([e.to_dict() for e in self._entries], f, indent=2) print(f"[Memory] Saved {len(self._entries)} entries → {path}") def load(self, path: str) -> None: with open(path, "r", encoding="utf-8") as f: data = json.load(f) self._entries = [MemoryEntry(**d) for d in data] if self._entries: self._counter = max(e.id for e in self._entries) + 1 print(f"[Memory] Loaded {len(self._entries)} entries from {path}") # ── stats ───────────────────────────────────────────────────────────────── def stats(self) -> Dict[str, Any]: if not self._entries: return {"entries": 0} toks = [e.metadata.get("tokens", 0) for e in self._entries] return { "entries": len(self._entries), "total_tokens": sum(toks), "avg_tokens": round(sum(toks) / len(toks), 1), "oldest_sec": round(self._entries[0].age_sec()), "newest_sec": round(self._entries[-1].age_sec()), } def clear(self) -> None: self._entries.clear() print("[Memory] Cleared.") def __len__(self) -> int: return len(self._entries) def __repr__(self) -> str: return f"MemoryBank(entries={len(self._entries)}, max={self._max})"