22from datetime import datetime
33from dataclasses import dataclass , asdict
44
5+
56@dataclass
67class Memory :
78 """Structure for storing individual memory entries"""
9+
810 timestamp : str
911 type : str # 'interaction', 'event', 'system', etc.
1012 content : Dict [str , Any ]
1113 metadata : Optional [Dict [str , Any ]] = None
1214 character_name : str = ""
1315
16+
1417@dataclass
1518class MemoryConfig :
1619 """Configuration for memory management"""
20+
1721 max_memories : int = 1000
1822 summary_threshold : int = 10
1923 auto_summarize : bool = True
2024
25+
2126class MemoryManager :
22- def __init__ (
23- self ,
24- character_name : str ,
25- config : Optional [Dict [str , Any ]] = None
26- ):
27+ def __init__ (self , character_name : str , config : Optional [Dict [str , Any ]] = None ):
2728 if not character_name or not character_name .strip ():
2829 raise ValueError ("Character name cannot be empty" )
29-
30+
3031 self .character_name = character_name
3132 self .config = MemoryConfig (** config ) if config else MemoryConfig ()
32-
33+
3334 # Validate config values
3435 if self .config .max_memories <= 0 :
3536 raise ValueError ("max_memories must be greater than 0" )
3637 if self .config .summary_threshold <= 0 :
3738 raise ValueError ("summary_threshold must be greater than 0" )
38-
39+
3940 self .memories : List [Memory ] = []
4041 self .summarized_memories : List [Memory ] = []
4142 self ._last_accessed = datetime .now ()
@@ -44,28 +45,26 @@ def add_memory(
4445 self ,
4546 content : Dict [str , Any ],
4647 memory_type : str = "interaction" ,
47- metadata : Optional [Dict [str , Any ]] = None
48+ metadata : Optional [Dict [str , Any ]] = None ,
4849 ):
4950 memory = Memory (
5051 timestamp = datetime .now ().isoformat (),
5152 type = memory_type ,
5253 content = content ,
5354 metadata = metadata or {},
54- character_name = self .character_name
55+ character_name = self .character_name ,
5556 )
5657
5758 self .memories .append (memory )
5859 self ._manage_memory_size ()
5960
6061 def get_memories (
61- self ,
62- limit : Optional [int ] = None ,
63- memory_types : Optional [List [str ]] = None
62+ self , limit : Optional [int ] = None , memory_types : Optional [List [str ]] = None
6463 ) -> List [Memory ]:
6564 """Get relevant memories based on configuration"""
6665 if limit is not None and limit < 0 :
6766 raise ValueError ("Memory limit cannot be negative" )
68-
67+
6968 memories = self .memories
7069
7170 if memory_types :
@@ -83,26 +82,26 @@ def _manage_memory_size(self):
8382 self ._summarize_old_memories ()
8483 else :
8584 # Keep most recent memories
86- self .memories = self .memories [- self .config .max_memories :]
85+ self .memories = self .memories [- self .config .max_memories :]
8786
8887 def _summarize_old_memories (self ):
8988 """Summarize old memories to maintain important information"""
90- memories_to_summarize = self .memories [:- self .config .max_memories ]
91-
89+ memories_to_summarize = self .memories [: - self .config .max_memories ]
90+
9291 # Only create summary if there are memories to summarize
9392 if memories_to_summarize :
9493 summary = Memory (
9594 timestamp = datetime .now ().isoformat (),
9695 type = "summary" ,
9796 content = {
9897 "period" : f"{ memories_to_summarize [0 ].timestamp } to { memories_to_summarize [- 1 ].timestamp } " ,
99- "summary" : f"Summary of { len (memories_to_summarize )} memories"
98+ "summary" : f"Summary of { len (memories_to_summarize )} memories" ,
10099 },
101- character_name = self .character_name
100+ character_name = self .character_name ,
102101 )
103102 self .summarized_memories .append (summary )
104-
105- self .memories = self .memories [- self .config .max_memories :]
103+
104+ self .memories = self .memories [- self .config .max_memories :]
106105
107106 def to_dict (self ) -> Dict [str , Any ]:
108107 """Convert memory manager to dictionary"""
@@ -111,16 +110,13 @@ def to_dict(self) -> Dict[str, Any]:
111110 "config" : asdict (self .config ),
112111 "memories" : [asdict (m ) for m in self .memories ],
113112 "summarized_memories" : [asdict (m ) for m in self .summarized_memories ],
114- "last_accessed" : self ._last_accessed .isoformat ()
113+ "last_accessed" : self ._last_accessed .isoformat (),
115114 }
116115
117116 @classmethod
118- def from_dict (cls , data : Dict [str , Any ]) -> ' MemoryManager' :
117+ def from_dict (cls , data : Dict [str , Any ]) -> " MemoryManager" :
119118 """Create memory manager from dictionary"""
120- manager = cls (
121- character_name = data ["character_name" ],
122- config = data ["config" ]
123- )
119+ manager = cls (character_name = data ["character_name" ], config = data ["config" ])
124120 manager .memories = [Memory (** m ) for m in data ["memories" ]]
125121 manager .summarized_memories = [Memory (** m ) for m in data ["summarized_memories" ]]
126122 manager ._last_accessed = datetime .fromisoformat (data ["last_accessed" ])
0 commit comments