initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,110 @@
|
||||
"""Global shared memory across all topics and chats."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MemoryItem:
|
||||
id: str
|
||||
fact: str
|
||||
category: str = "general"
|
||||
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
||||
|
||||
|
||||
class GlobalMemory:
|
||||
"""Persistent global memory store shared across all forum topics."""
|
||||
|
||||
def __init__(self, storage_path: Path):
|
||||
self.storage_path = storage_path
|
||||
self._items: dict[str, MemoryItem] = {}
|
||||
self._load()
|
||||
|
||||
def _load(self) -> None:
|
||||
if not self.storage_path.exists():
|
||||
return
|
||||
try:
|
||||
with open(self.storage_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
for item_data in data:
|
||||
item = MemoryItem(**item_data)
|
||||
self._items[item.id] = item
|
||||
logger.info("Loaded %d items into global memory from %s", len(self._items), self.storage_path)
|
||||
except Exception as e:
|
||||
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
||||
|
||||
def _save(self) -> None:
|
||||
try:
|
||||
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(self.storage_path, "w", encoding="utf-8") as f:
|
||||
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
|
||||
|
||||
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
||||
"""Add a new fact or preference to global memory."""
|
||||
item_id = str(uuid.uuid4())[:8]
|
||||
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
||||
self._items[item_id] = item
|
||||
self._save()
|
||||
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
|
||||
return item
|
||||
|
||||
def remove_fact(self, fact_id: str) -> bool:
|
||||
"""Remove a fact by its ID."""
|
||||
if fact_id in self._items:
|
||||
del self._items[fact_id]
|
||||
self._save()
|
||||
return True
|
||||
return False
|
||||
|
||||
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
||||
"""List all facts, optionally filtered by category."""
|
||||
if category:
|
||||
cat = category.strip().lower()
|
||||
return [item for item in self._items.values() if item.category == cat]
|
||||
return list(self._items.values())
|
||||
|
||||
def search(self, query: str) -> list[MemoryItem]:
|
||||
"""Search memory for keywords in query."""
|
||||
q = query.lower()
|
||||
return [
|
||||
item for item in self._items.values()
|
||||
if q in item.fact.lower() or q in item.category.lower()
|
||||
]
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear all stored memory."""
|
||||
self._items.clear()
|
||||
self._save()
|
||||
|
||||
def get_memory_summary(self, max_items: int = 30) -> str:
|
||||
"""Produce a formatted summary of remembered facts for the system prompt."""
|
||||
if not self._items:
|
||||
return ""
|
||||
|
||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||
items = list(self._items.values())[-max_items:]
|
||||
for item in items:
|
||||
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# Singleton instance container
|
||||
_global_memory_instance: Optional[GlobalMemory] = None
|
||||
|
||||
|
||||
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
||||
global _global_memory_instance
|
||||
if _global_memory_instance is None:
|
||||
if storage_path is None:
|
||||
storage_path = Path("data") / "global_memory.json"
|
||||
_global_memory_instance = GlobalMemory(storage_path)
|
||||
return _global_memory_instance
|
||||
Reference in new issue
Block a user