Spaces:
Runtime error
Runtime error
Download Shelly/memory/memory.py from SkyWorlds01/Shelly_AI: direct link, hf CLI and curl.
- Browser
- Download file 24.1 kB
-
https://huggingface.co/spaces/SkyWorlds01/Shelly_AI/resolve/main/Shelly/memory/memory.py
- Command line
-
hf download hf://spaces/SkyWorlds01/Shelly_AI/Shelly/memory/memory.py
-
curl -L -o memory.py https://huggingface.co/spaces/SkyWorlds01/Shelly_AI/resolve/main/Shelly/memory/memory.py
24.1 kB
| """ | |
| Shelly AI - Main Memory System | |
| Integrates: | |
| - Memory encoding | |
| - Memory traces | |
| - Memory associations | |
| - Memory consolidation | |
| - Memory retrieval | |
| - Memory reconsolidation | |
| - Memory archive | |
| The system supports short-term and long-term memory, | |
| episodic and semantic records, and persistent state export. | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import threading | |
| import time | |
| from typing import Any, Dict, List, Optional | |
| from .memory_encoding import MemoryEncoder | |
| from .memory_trace import MemoryTraceManager | |
| from .memory_association import MemoryAssociationGraph | |
| from .memory_consolidation import MemoryConsolidator | |
| from .memory_retrieval import MemoryRetriever | |
| from .memory_reconsolidation import MemoryReconsolidator | |
| from .memory_archive import MemoryArchive | |
| class MemorySystem: | |
| """ | |
| Main interface for Shelly's memory architecture. | |
| Memory is separated into: | |
| - Short-term memory | |
| - Long-term memory | |
| - Episodic memory | |
| - Semantic memory | |
| - Archived memory | |
| The categories describe storage and retrieval organization. | |
| They are not separate databases in this implementation. | |
| """ | |
| def __init__( | |
| self, | |
| short_term_limit: int = 100, | |
| long_term_limit: int = 50000, | |
| ): | |
| self._lock = threading.RLock() | |
| self.short_term_limit = max( | |
| 1, | |
| int(short_term_limit), | |
| ) | |
| self.long_term_limit = max( | |
| 1, | |
| int(long_term_limit), | |
| ) | |
| self.short_term_memory: List[Dict[str, Any]] = [] | |
| self.long_term_memory: List[Dict[str, Any]] = [] | |
| self.episodic_memory: Dict[str, Dict[str, Any]] = {} | |
| self.semantic_memory: Dict[str, Dict[str, Any]] = {} | |
| self.encoder = MemoryEncoder() | |
| self.trace_manager = MemoryTraceManager() | |
| self.association_graph = MemoryAssociationGraph() | |
| self.consolidator = MemoryConsolidator() | |
| self.retriever = MemoryRetriever() | |
| self.reconsolidator = MemoryReconsolidator() | |
| self.archive = MemoryArchive() | |
| self.total_encoded = 0 | |
| self.total_retrieved = 0 | |
| self.total_deleted = 0 | |
| self.created_at = time.time() | |
| self.last_activity = self.created_at | |
| # ======================================================== | |
| # 1. MEMORY LOOKUP | |
| # ======================================================== | |
| def _find_memory( | |
| self, | |
| memory_id: str, | |
| ) -> Optional[Dict[str, Any]]: | |
| for memory in self.short_term_memory: | |
| if memory.get("id") == memory_id: | |
| return memory | |
| for memory in self.long_term_memory: | |
| if memory.get("id") == memory_id: | |
| return memory | |
| if memory_id in self.episodic_memory: | |
| return self.episodic_memory[memory_id] | |
| if memory_id in self.semantic_memory: | |
| return self.semantic_memory[memory_id] | |
| return None | |
| def get_all_active_memories(self) -> List[Dict[str, Any]]: | |
| """ | |
| Return unique active memories. | |
| Episodic and semantic indexes point to the same logical | |
| records, so they are not added as duplicate records. | |
| """ | |
| with self._lock: | |
| combined = {} | |
| for memory in self.short_term_memory: | |
| combined[memory["id"]] = memory | |
| for memory in self.long_term_memory: | |
| combined[memory["id"]] = memory | |
| return [ | |
| copy.deepcopy(memory) | |
| for memory in combined.values() | |
| if not memory.get("archived", False) | |
| ] | |
| # ======================================================== | |
| # 2. MEMORY ENCODING AND STORAGE | |
| # ======================================================== | |
| def encode( | |
| self, | |
| event: Any, | |
| context: Optional[Dict[str, Any]] = None, | |
| user_id: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| """ | |
| Encode an event and store it in memory. | |
| Supports dictionary events and plain text events. | |
| """ | |
| context = dict(context or {}) | |
| if user_id is not None: | |
| context["user_id"] = user_id | |
| memory = self.encoder.encode( | |
| event, | |
| context=context, | |
| ) | |
| if user_id is not None: | |
| memory["user_id"] = user_id | |
| with self._lock: | |
| self.short_term_memory.append(memory) | |
| self.episodic_memory[memory["id"]] = memory | |
| self.trace_manager.create_trace( | |
| memory_id=memory["id"], | |
| novelty=memory.get("novelty", 0.5), | |
| attention=memory.get("attention", 0.5), | |
| emotional_intensity=self._emotion_intensity( | |
| memory.get("emotion_state", {}) | |
| ), | |
| ) | |
| self.association_graph.add_memory(memory) | |
| self.total_encoded += 1 | |
| self.last_activity = time.time() | |
| self._enforce_short_term_limit() | |
| return copy.deepcopy(memory) | |
| def remember( | |
| self, | |
| event: Any, | |
| context: Optional[Dict[str, Any]] = None, | |
| user_id: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| """Convenience method for storing an experience.""" | |
| return self.encode( | |
| event, | |
| context=context, | |
| user_id=user_id, | |
| ) | |
| def store( | |
| self, | |
| event: Any, | |
| context: Optional[Dict[str, Any]] = None, | |
| user_id: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| """Alias for the main encoding operation.""" | |
| return self.encode( | |
| event, | |
| context=context, | |
| user_id=user_id, | |
| ) | |
| def _emotion_intensity( | |
| emotions: Dict[str, Any], | |
| ) -> float: | |
| if not isinstance(emotions, dict) or not emotions: | |
| return 0.0 | |
| values = [] | |
| for value in emotions.values(): | |
| try: | |
| values.append( | |
| max(0.0, min(1.0, float(value))) | |
| ) | |
| except (TypeError, ValueError): | |
| continue | |
| if not values: | |
| return 0.0 | |
| return max(values) | |
| # ======================================================== | |
| # 3. MEMORY LIMIT MANAGEMENT | |
| # ======================================================== | |
| def _enforce_short_term_limit(self) -> None: | |
| """ | |
| Move older short-term records into long-term memory. | |
| Records are preserved unless an explicit deletion occurs. | |
| """ | |
| while len(self.short_term_memory) > self.short_term_limit: | |
| memory = self.short_term_memory.pop(0) | |
| if not any( | |
| item.get("id") == memory.get("id") | |
| for item in self.long_term_memory | |
| ): | |
| self.long_term_memory.append(memory) | |
| self._enforce_long_term_limit() | |
| def _enforce_long_term_limit(self) -> None: | |
| """ | |
| Archive the oldest long-term records when the configured | |
| storage limit is exceeded. | |
| """ | |
| while len(self.long_term_memory) > self.long_term_limit: | |
| memory = self.long_term_memory.pop(0) | |
| self.archive.archive( | |
| memory, | |
| reason="long_term_capacity", | |
| ) | |
| self.episodic_memory.pop( | |
| memory.get("id"), | |
| None, | |
| ) | |
| self.association_graph.remove_memory( | |
| memory.get("id"), | |
| ) | |
| self.trace_manager.remove_trace( | |
| memory.get("id"), | |
| ) | |
| # ======================================================== | |
| # 4. MEMORY RETRIEVAL | |
| # ======================================================== | |
| def retrieve( | |
| self, | |
| query: str, | |
| user_id: Optional[str] = None, | |
| limit: int = 10, | |
| include_archived: bool = False, | |
| ) -> List[Dict[str, Any]]: | |
| """ | |
| Retrieve memories relevant to a query. | |
| When user_id is provided, records belonging to another | |
| user are excluded unless they are shared records. | |
| """ | |
| memories = self.get_all_active_memories() | |
| if user_id is not None: | |
| memories = [ | |
| memory | |
| for memory in memories | |
| if ( | |
| memory.get("user_id") is None | |
| or memory.get("user_id") == user_id | |
| ) | |
| ] | |
| results = self.retriever.retrieve( | |
| query=query, | |
| memories=memories, | |
| trace_manager=self.trace_manager, | |
| limit=limit, | |
| ) | |
| formatted = [ | |
| { | |
| **copy.deepcopy(item["memory"]), | |
| "relevance_score": item["score"], | |
| } | |
| for item in results | |
| ] | |
| if include_archived and len(formatted) < limit: | |
| archived = self.archive.search( | |
| query, | |
| limit=limit - len(formatted), | |
| ) | |
| for memory in archived: | |
| if user_id is not None: | |
| if ( | |
| memory.get("user_id") is not None | |
| and memory.get("user_id") != user_id | |
| ): | |
| continue | |
| formatted.append(memory) | |
| with self._lock: | |
| self.total_retrieved += 1 | |
| self.last_activity = time.time() | |
| return formatted | |
| def recall( | |
| self, | |
| query: str, | |
| user_id: Optional[str] = None, | |
| limit: int = 10, | |
| ) -> List[Dict[str, Any]]: | |
| """Convenience method for memory retrieval.""" | |
| return self.retrieve( | |
| query=query, | |
| user_id=user_id, | |
| limit=limit, | |
| ) | |
| def search( | |
| self, | |
| query: str, | |
| user_id: Optional[str] = None, | |
| limit: int = 10, | |
| ) -> List[Dict[str, Any]]: | |
| """Search active memory records.""" | |
| return self.retrieve( | |
| query=query, | |
| user_id=user_id, | |
| limit=limit, | |
| ) | |
| # ======================================================== | |
| # 5. MEMORY REINFORCEMENT | |
| # ======================================================== | |
| def reinforce( | |
| self, | |
| memory_id: str, | |
| amount: float = 0.1, | |
| reason: str = "important_memory", | |
| ) -> bool: | |
| with self._lock: | |
| memory = self._find_memory(memory_id) | |
| if memory is None: | |
| return False | |
| memory["repetitions"] = ( | |
| int(memory.get("repetitions", 1)) + 1 | |
| ) | |
| self.trace_manager.reinforce( | |
| memory_id, | |
| amount=amount, | |
| reason=reason, | |
| ) | |
| memory["last_reinforced"] = time.time() | |
| return True | |
| # ======================================================== | |
| # 6. MEMORY ASSOCIATION | |
| # ======================================================== | |
| def associate( | |
| self, | |
| memory_id: str, | |
| minimum_similarity: float = 0.15, | |
| ) -> List[Dict[str, Any]]: | |
| return self.association_graph.associate( | |
| memory_id, | |
| minimum_similarity=minimum_similarity, | |
| ) | |
| def get_associations( | |
| self, | |
| memory_id: str, | |
| limit: int = 20, | |
| ) -> List[Dict[str, Any]]: | |
| return self.association_graph.get_related( | |
| memory_id, | |
| limit=limit, | |
| ) | |
| # ======================================================== | |
| # 7. MEMORY CONSOLIDATION | |
| # ======================================================== | |
| def consolidate(self) -> Dict[str, Any]: | |
| """ | |
| Consolidate active memories. | |
| This method can be called by the idle-mode system. | |
| """ | |
| memories = self.get_all_active_memories() | |
| report = self.consolidator.consolidate( | |
| memories, | |
| trace_manager=self.trace_manager, | |
| ) | |
| with self._lock: | |
| for memory in memories: | |
| original = self._find_memory( | |
| memory.get("id") | |
| ) | |
| if original is not None: | |
| original["importance"] = memory.get( | |
| "importance", | |
| 0.5, | |
| ) | |
| original["last_consolidated"] = ( | |
| memory.get("last_consolidated") | |
| ) | |
| self.last_activity = time.time() | |
| report["possible_contradictions"] = ( | |
| self.consolidator.detect_possible_contradictions( | |
| memories | |
| ) | |
| ) | |
| return report | |
| # ======================================================== | |
| # 8. EPISODIC MEMORY | |
| # ======================================================== | |
| def get_episodic_memory( | |
| self, | |
| memory_id: str, | |
| ) -> Optional[Dict[str, Any]]: | |
| memory = self.episodic_memory.get(memory_id) | |
| return ( | |
| copy.deepcopy(memory) | |
| if memory is not None | |
| else None | |
| ) | |
| def list_episodic_memories( | |
| self, | |
| limit: int = 100, | |
| ) -> List[Dict[str, Any]]: | |
| memories = list(self.episodic_memory.values()) | |
| return [ | |
| copy.deepcopy(memory) | |
| for memory in memories[-max(1, limit):] | |
| ] | |
| # ======================================================== | |
| # 9. SEMANTIC MEMORY | |
| # ======================================================== | |
| def add_semantic_knowledge( | |
| self, | |
| concept: str, | |
| knowledge: str, | |
| source: str = "unknown", | |
| confidence: float = 0.5, | |
| ) -> Dict[str, Any]: | |
| concept = str(concept).strip().lower() | |
| if not concept: | |
| raise ValueError("Concept cannot be empty.") | |
| record = { | |
| "id": concept, | |
| "concept": concept, | |
| "knowledge": str(knowledge), | |
| "source": str(source), | |
| "confidence": max( | |
| 0.0, | |
| min(1.0, float(confidence)), | |
| ), | |
| "updated_at": time.time(), | |
| } | |
| with self._lock: | |
| self.semantic_memory[concept] = record | |
| return copy.deepcopy(record) | |
| def get_semantic_knowledge( | |
| self, | |
| concept: str, | |
| ) -> Optional[Dict[str, Any]]: | |
| concept = str(concept).strip().lower() | |
| record = self.semantic_memory.get(concept) | |
| return ( | |
| copy.deepcopy(record) | |
| if record is not None | |
| else None | |
| ) | |
| def search_semantic_knowledge( | |
| self, | |
| query: str, | |
| limit: int = 20, | |
| ) -> List[Dict[str, Any]]: | |
| query = str(query).lower().strip() | |
| results = [] | |
| for record in self.semantic_memory.values(): | |
| searchable = ( | |
| record["concept"] + " " + record["knowledge"] | |
| ).lower() | |
| if query in searchable: | |
| results.append(copy.deepcopy(record)) | |
| if len(results) >= limit: | |
| break | |
| return results | |
| # ======================================================== | |
| # 10. MEMORY RECONSOLIDATION | |
| # ======================================================== | |
| def add_interpretation( | |
| self, | |
| memory_id: str, | |
| interpretation: str, | |
| source: str, | |
| confidence: float = 0.5, | |
| verified: bool = False, | |
| ) -> Optional[Dict[str, Any]]: | |
| with self._lock: | |
| memory = self._find_memory(memory_id) | |
| if memory is None: | |
| archived = self.archive.get(memory_id) | |
| if archived is None: | |
| return None | |
| memory = archived | |
| result = self.reconsolidator.add_interpretation( | |
| memory=memory, | |
| interpretation=interpretation, | |
| source=source, | |
| confidence=confidence, | |
| verified=verified, | |
| ) | |
| return copy.deepcopy(result) | |
| # ======================================================== | |
| # 11. MEMORY ARCHIVING | |
| # ======================================================== | |
| def archive_memory( | |
| self, | |
| memory_id: str, | |
| reason: str = "manual_archive", | |
| ) -> bool: | |
| with self._lock: | |
| memory = self._find_memory(memory_id) | |
| if memory is None: | |
| return False | |
| archived = self.archive.archive( | |
| memory, | |
| reason=reason, | |
| ) | |
| if not archived: | |
| return False | |
| self.short_term_memory = [ | |
| item | |
| for item in self.short_term_memory | |
| if item.get("id") != memory_id | |
| ] | |
| self.long_term_memory = [ | |
| item | |
| for item in self.long_term_memory | |
| if item.get("id") != memory_id | |
| ] | |
| self.episodic_memory.pop(memory_id, None) | |
| self.association_graph.remove_memory( | |
| memory_id | |
| ) | |
| self.trace_manager.remove_trace( | |
| memory_id | |
| ) | |
| return True | |
| def restore_archived_memory( | |
| self, | |
| memory_id: str, | |
| ) -> Optional[Dict[str, Any]]: | |
| restored = self.archive.restore(memory_id) | |
| if restored is None: | |
| return None | |
| with self._lock: | |
| self.long_term_memory.append(restored) | |
| self.episodic_memory[memory_id] = restored | |
| self.association_graph.add_memory(restored) | |
| self.trace_manager.create_trace( | |
| memory_id, | |
| novelty=restored.get("novelty", 0.5), | |
| attention=restored.get("attention", 0.5), | |
| emotional_intensity=self._emotion_intensity( | |
| restored.get("emotion_state", {}) | |
| ), | |
| ) | |
| self._enforce_long_term_limit() | |
| return copy.deepcopy(restored) | |
| # ======================================================== | |
| # 12. MEMORY DELETION | |
| # ======================================================== | |
| def delete_memory( | |
| self, | |
| memory_id: str, | |
| ) -> bool: | |
| """ | |
| Delete a memory from active and archived storage. | |
| This also removes its association edges and trace. | |
| """ | |
| with self._lock: | |
| existed = self._find_memory(memory_id) is not None | |
| self.short_term_memory = [ | |
| memory | |
| for memory in self.short_term_memory | |
| if memory.get("id") != memory_id | |
| ] | |
| self.long_term_memory = [ | |
| memory | |
| for memory in self.long_term_memory | |
| if memory.get("id") != memory_id | |
| ] | |
| self.episodic_memory.pop( | |
| memory_id, | |
| None, | |
| ) | |
| archived_deleted = self.archive.delete( | |
| memory_id | |
| ) | |
| self.association_graph.remove_memory( | |
| memory_id | |
| ) | |
| self.trace_manager.remove_trace( | |
| memory_id | |
| ) | |
| if existed or archived_deleted: | |
| self.total_deleted += 1 | |
| return True | |
| return False | |
| # ======================================================== | |
| # 13. MEMORY EXPORT AND RESTORATION | |
| # ======================================================== | |
| def export_state(self) -> Dict[str, Any]: | |
| """ | |
| Export memory state for persistent storage. | |
| The caller is responsible for securely writing this | |
| state to a persistent database or file. | |
| """ | |
| with self._lock: | |
| return { | |
| "version": 1, | |
| "exported_at": time.time(), | |
| "short_term_memory": copy.deepcopy( | |
| self.short_term_memory | |
| ), | |
| "long_term_memory": copy.deepcopy( | |
| self.long_term_memory | |
| ), | |
| "episodic_memory": copy.deepcopy( | |
| self.episodic_memory | |
| ), | |
| "semantic_memory": copy.deepcopy( | |
| self.semantic_memory | |
| ), | |
| "traces": self.trace_manager.export_state(), | |
| "associations": ( | |
| self.association_graph.export_state() | |
| ), | |
| "archive": self.archive.export_state(), | |
| "statistics": { | |
| "total_encoded": self.total_encoded, | |
| "total_retrieved": self.total_retrieved, | |
| "total_deleted": self.total_deleted, | |
| "created_at": self.created_at, | |
| "last_activity": self.last_activity, | |
| }, | |
| } | |
| def import_state(self, state: Dict[str, Any]) -> None: | |
| if not isinstance(state, dict): | |
| raise TypeError("Memory state must be a dictionary.") | |
| if state.get("version") != 1: | |
| raise ValueError("Unsupported memory state version.") | |
| with self._lock: | |
| self.short_term_memory = copy.deepcopy( | |
| state.get("short_term_memory", []) | |
| ) | |
| self.long_term_memory = copy.deepcopy( | |
| state.get("long_term_memory", []) | |
| ) | |
| self.episodic_memory = copy.deepcopy( | |
| state.get("episodic_memory", {}) | |
| ) | |
| self.semantic_memory = copy.deepcopy( | |
| state.get("semantic_memory", {}) | |
| ) | |
| self.trace_manager.import_state( | |
| state.get("traces", {}) | |
| ) | |
| self.association_graph.import_state( | |
| state.get("associations", {}) | |
| ) | |
| self.archive.import_state( | |
| state.get("archive", {}) | |
| ) | |
| statistics = state.get("statistics", {}) | |
| self.total_encoded = statistics.get( | |
| "total_encoded", | |
| 0, | |
| ) | |
| self.total_retrieved = statistics.get( | |
| "total_retrieved", | |
| 0, | |
| ) | |
| self.total_deleted = statistics.get( | |
| "total_deleted", | |
| 0, | |
| ) | |
| self.created_at = statistics.get( | |
| "created_at", | |
| time.time(), | |
| ) | |
| self.last_activity = statistics.get( | |
| "last_activity", | |
| time.time(), | |
| ) | |
| # ======================================================== | |
| # 14. MEMORY STATUS | |
| # ======================================================== | |
| def get_status(self) -> Dict[str, Any]: | |
| with self._lock: | |
| return { | |
| "running": True, | |
| "short_term_count": len( | |
| self.short_term_memory | |
| ), | |
| "long_term_count": len( | |
| self.long_term_memory | |
| ), | |
| "episodic_count": len( | |
| self.episodic_memory | |
| ), | |
| "semantic_count": len( | |
| self.semantic_memory | |
| ), | |
| "archived_count": len( | |
| self.archive.archived_memories | |
| ), | |
| "total_encoded": self.total_encoded, | |
| "total_retrieved": self.total_retrieved, | |
| "total_deleted": self.total_deleted, | |
| "created_at": self.created_at, | |
| "last_activity": self.last_activity, | |
| "association_count": sum( | |
| len(connections) | |
| for connections in ( | |
| self.association_graph.edges.values() | |
| ) | |
| ) // 2, | |
| } | |