Spaces:
Sleeping
Sleeping
Download memory_system.py from ownusageid007/periyappa-ai: direct link, hf CLI and curl.
- Browser
- Download file 6.51 kB
-
https://huggingface.co/spaces/ownusageid007/periyappa-ai/resolve/main/memory_system.py
- Command line
-
hf download hf://spaces/ownusageid007/periyappa-ai/memory_system.py
-
curl -L -o memory_system.py https://huggingface.co/spaces/ownusageid007/periyappa-ai/resolve/main/memory_system.py
6.51 kB
| """ | |
| Memory System Module | |
| Handles conversation storage and retrieval using ChromaDB | |
| """ | |
| import chromadb | |
| from chromadb.config import Settings | |
| from datetime import datetime | |
| from typing import List, Dict, Optional | |
| from pathlib import Path | |
| import sys | |
| # Allow running from project root | |
| sys.path.insert(0, str(Path(__file__).parent.parent)) | |
| from config import MEMORY_CONFIG | |
| class MemorySystem: | |
| """ | |
| Manages conversation memories using ChromaDB for persistent storage. | |
| Supports trigger-based save and semantic recall. | |
| """ | |
| def __init__(self): | |
| """Initialize ChromaDB for memory storage.""" | |
| print("Initializing memory system...") | |
| storage_path = MEMORY_CONFIG["storage_path"] | |
| storage_path.mkdir(parents=True, exist_ok=True) | |
| self.client = chromadb.PersistentClient( | |
| path=str(storage_path), | |
| settings=Settings(anonymized_telemetry=False) | |
| ) | |
| self.collection = self.client.get_or_create_collection( | |
| name="periyappa_memories", | |
| metadata={"description": "Periyappa Memorial AI conversation memories"} | |
| ) | |
| self.trigger_phrases = MEMORY_CONFIG["trigger_phrases"] | |
| self.recall_phrases = MEMORY_CONFIG["recall_phrases"] | |
| print("✅ Memory system ready!") | |
| # ------------------------------------------------------------------ | |
| # Trigger detection | |
| # ------------------------------------------------------------------ | |
| def should_store_memory(self, user_message: str) -> bool: | |
| """Return True if the message contains a memory-save trigger phrase.""" | |
| msg_lower = user_message.lower() | |
| return any(trigger in msg_lower for trigger in self.trigger_phrases) | |
| def should_recall_memory(self, user_message: str) -> bool: | |
| """Return True if the message contains a memory-recall trigger phrase.""" | |
| msg_lower = user_message.lower() | |
| return any(recall in msg_lower for recall in self.recall_phrases) | |
| # ------------------------------------------------------------------ | |
| # Storage | |
| # ------------------------------------------------------------------ | |
| def store_memory( | |
| self, | |
| speaker_name: str, | |
| conversation: str, | |
| metadata: Optional[Dict] = None | |
| ) -> str: | |
| """ | |
| Store a conversation snippet as a memory. | |
| Args: | |
| speaker_name: Identifier of who is speaking (e.g. "abi") | |
| conversation: The text to memorise | |
| metadata: Optional extra metadata dict | |
| Returns: | |
| Unique memory ID string | |
| """ | |
| memory_id = f"{speaker_name}_{datetime.now().strftime('%Y%m%d_%H%M%S')}" | |
| if metadata is None: | |
| metadata = {} | |
| metadata.update({ | |
| "speaker": speaker_name, | |
| "timestamp": datetime.now().isoformat(), | |
| "type": "conversation" | |
| }) | |
| # ChromaDB requires string values in metadata | |
| clean_meta = {k: str(v) for k, v in metadata.items()} | |
| self.collection.add( | |
| documents=[conversation], | |
| metadatas=[clean_meta], | |
| ids=[memory_id] | |
| ) | |
| print(f"✅ Memory stored: {memory_id}") | |
| return memory_id | |
| # ------------------------------------------------------------------ | |
| # Retrieval | |
| # ------------------------------------------------------------------ | |
| def recall_memories( | |
| self, | |
| query: str, | |
| speaker_name: Optional[str] = None, | |
| n_results: int = 3 | |
| ) -> List[Dict]: | |
| """ | |
| Retrieve semantically relevant memories. | |
| Args: | |
| query: Search query text | |
| speaker_name: Optional filter by speaker | |
| n_results: Maximum number of results to return | |
| Returns: | |
| List of memory dicts with keys: text, metadata, distance | |
| """ | |
| where_filter = {} | |
| if speaker_name: | |
| where_filter["speaker"] = speaker_name | |
| results = self.collection.query( | |
| query_texts=[query], | |
| n_results=n_results, | |
| where=where_filter if where_filter else None | |
| ) | |
| memories = [] | |
| if results["documents"] and results["documents"][0]: | |
| for i, doc in enumerate(results["documents"][0]): | |
| memories.append({ | |
| "text": doc, | |
| "metadata": results["metadatas"][0][i] if results["metadatas"] else {}, | |
| "distance": results["distances"][0][i] if results["distances"] else 0 | |
| }) | |
| return memories | |
| def get_speaker_memories(self, speaker_name: str, limit: int = 10) -> List[Dict]: | |
| """ | |
| Retrieve all stored memories for a specific speaker. | |
| Args: | |
| speaker_name: Speaker key (e.g. "abi") | |
| limit: Max number of results | |
| Returns: | |
| List of memory dicts with keys: id, text, metadata | |
| """ | |
| results = self.collection.get( | |
| where={"speaker": speaker_name}, | |
| limit=limit | |
| ) | |
| memories = [] | |
| if results["documents"]: | |
| for i, doc in enumerate(results["documents"]): | |
| memories.append({ | |
| "id": results["ids"][i], | |
| "text": doc, | |
| "metadata": results["metadatas"][i] if results["metadatas"] else {} | |
| }) | |
| return memories | |
| def clear_speaker_memories(self, speaker_name: str) -> int: | |
| """ | |
| Delete all memories for a given speaker. | |
| Args: | |
| speaker_name: Speaker key | |
| Returns: | |
| Number of memories deleted | |
| """ | |
| results = self.collection.get(where={"speaker": speaker_name}) | |
| if results["ids"]: | |
| self.collection.delete(ids=results["ids"]) | |
| count = len(results["ids"]) | |
| print(f"✅ Deleted {count} memories for {speaker_name}") | |
| return count | |
| return 0 | |
| # Quick test | |
| if __name__ == "__main__": | |
| mem = MemorySystem() | |
| mem.store_memory("abi", "We talked about her new job at the tech company.", {"topic": "career"}) | |
| found = mem.recall_memories("job", speaker_name="abi") | |
| print(f"Recalled {len(found)} memories:") | |
| for m in found: | |
| print(f" - {m['text']}") | |