Repository navigation
Expand file tree
/
Copy pathmemory.py
More file actions
2168 lines (1688 loc) · 71.5 KB
/
Copy pathmemory.py
File metadata and controls
2168 lines (1688 loc) · 71.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
memory.py - Memory Systems for Neuron Framework
This module implements the memory systems used by agents in the Neuron framework.
The memory system is inspired by human memory architecture, with different types
of memory for different purposes and varying retention characteristics.
The memory system provides agents with the ability to store, retrieve, and forget
information, enabling them to maintain state and learn from past experiences.
"""
import asyncio
import heapq
import json
import logging
import threading
import time
from abc import ABC, abstractmethod
from collections import OrderedDict, deque
from dataclasses import asdict, dataclass
from enum import Enum
from pathlib import Path
from typing import Any, Callable, Dict, Generic, List, Optional, Set, Tuple, TypeVar, Union
from .config import config
from .exceptions import MemoryAccessError, MemoryStorageError
from .neuron_types import AgentID, MemoryEntry, MemoryID, MemoryType
logger = logging.getLogger(__name__)
# Type for memory query results
T = TypeVar('T')
class MemoryStore(ABC):
"""
Abstract base class for memory storage backends.
This defines the interface that all memory stores must implement,
allowing for different storage backends to be used (e.g., in-memory,
file-based, database).
"""
@abstractmethod
async def store(self, entry: MemoryEntry) -> None:
"""
Store a memory entry.
Args:
entry: Memory entry to store
Raises:
MemoryStorageError: If storage fails
"""
pass
@abstractmethod
async def retrieve(self, memory_id: MemoryID) -> Optional[MemoryEntry]:
"""
Retrieve a memory entry by ID.
Args:
memory_id: ID of the memory to retrieve
Returns:
Memory entry if found, None otherwise
Raises:
MemoryAccessError: If retrieval fails
"""
pass
@abstractmethod
async def delete(self, memory_id: MemoryID) -> bool:
"""
Delete a memory entry.
Args:
memory_id: ID of the memory to delete
Returns:
True if deleted, False if not found
Raises:
MemoryAccessError: If deletion fails
"""
pass
@abstractmethod
async def query(self, query: Dict[str, Any], limit: Optional[int] = None) -> List[MemoryEntry]:
"""
Query for memory entries matching criteria.
Args:
query: Query criteria
limit: Maximum number of results to return
Returns:
List of matching memory entries
Raises:
MemoryAccessError: If query fails
"""
pass
@abstractmethod
async def clear(self) -> None:
"""
Clear all memory entries.
Raises:
MemoryAccessError: If clearing fails
"""
pass
class InMemoryStore(MemoryStore):
"""
In-memory implementation of MemoryStore.
This provides a simple, fast memory store that keeps all entries
in memory. It's suitable for testing and small-scale deployments
but does not persist across restarts.
"""
def __init__(self):
"""Initialize an in-memory store."""
self._store = {} # memory_id -> MemoryEntry
self._lock = asyncio.Lock()
async def store(self, entry: MemoryEntry) -> None:
"""
Store a memory entry.
Args:
entry: Memory entry to store
"""
async with self._lock:
self._store[entry.id] = entry
async def retrieve(self, memory_id: MemoryID) -> Optional[MemoryEntry]:
"""
Retrieve a memory entry by ID.
Args:
memory_id: ID of the memory to retrieve
Returns:
Memory entry if found, None otherwise
"""
async with self._lock:
entry = self._store.get(memory_id)
if entry:
# Update access metadata
entry.access()
return entry
async def delete(self, memory_id: MemoryID) -> bool:
"""
Delete a memory entry.
Args:
memory_id: ID of the memory to delete
Returns:
True if deleted, False if not found
"""
async with self._lock:
if memory_id in self._store:
del self._store[memory_id]
return True
return False
async def query(self, query: Dict[str, Any], limit: Optional[int] = None) -> List[MemoryEntry]:
"""
Query for memory entries matching criteria.
This implements a simple filtering mechanism based on exact matches
of query parameters to memory entry attributes and metadata.
Args:
query: Query criteria
limit: Maximum number of results to return
Returns:
List of matching memory entries
"""
async with self._lock:
results = []
for entry in self._store.values():
match = True
# to_dict() gives memory_type as its name, the form the memory
# systems filter on (asdict kept the enum, so no query matched)
entry_dict = entry.to_dict()
# Check each query parameter
for key, value in query.items():
# Handle nested keys (dot notation)
if '.' in key:
parts = key.split('.')
current = entry_dict
for part in parts[:-1]:
if not isinstance(current, dict) or part not in current:
match = False
break
current = current[part]
if match and (parts[-1] not in current or current[parts[-1]] != value):
match = False
# Handle direct keys
elif key not in entry_dict or entry_dict[key] != value:
match = False
if match:
# Update access metadata for matched entries
entry.access()
results.append(entry)
# Apply limit if specified
if limit is not None and limit > 0:
results = results[:limit]
return results
async def clear(self) -> None:
"""Clear all memory entries."""
async with self._lock:
self._store.clear()
class FileStore(MemoryStore):
"""
File-based implementation of MemoryStore.
This provides a persistent memory store that saves entries to files.
It's slower than InMemoryStore but persists across restarts.
"""
def __init__(self, directory: Union[str, Path]):
"""
Initialize a file-based store.
Args:
directory: Directory to store memory files in
"""
self._directory = Path(directory)
self._directory.mkdir(parents=True, exist_ok=True)
self._lock = asyncio.Lock()
self._cache = {} # memory_id -> MemoryEntry (small cache for frequent accesses)
self._max_cache_size = 1000
def _get_file_path(self, memory_id: MemoryID) -> Path:
"""
Get the file path for a memory ID.
Args:
memory_id: Memory ID
Returns:
Path to the memory file
"""
# Use a simple sharded structure to avoid too many files in one directory
shard = memory_id[:2]
shard_dir = self._directory / shard
shard_dir.mkdir(exist_ok=True)
return shard_dir / f"{memory_id}.json"
async def store(self, entry: MemoryEntry) -> None:
"""
Store a memory entry.
Args:
entry: Memory entry to store
Raises:
MemoryStorageError: If storage fails
"""
async with self._lock:
try:
# Add to cache
self._cache[entry.id] = entry
# Trim cache if needed
if len(self._cache) > self._max_cache_size:
# Remove oldest entries (approximation)
remove_count = len(self._cache) - self._max_cache_size
for _ in range(remove_count):
self._cache.pop(next(iter(self._cache)))
# Write to file
file_path = self._get_file_path(entry.id)
entry_dict = entry.to_dict()
# Write to a temporary file, then atomically rename
temp_path = file_path.with_suffix('.tmp')
with open(temp_path, 'w') as f:
json.dump(entry_dict, f)
temp_path.rename(file_path)
except Exception as e:
raise MemoryStorageError(f"Failed to store memory entry: {e}") from e
async def retrieve(self, memory_id: MemoryID) -> Optional[MemoryEntry]:
"""
Retrieve a memory entry by ID.
Args:
memory_id: ID of the memory to retrieve
Returns:
Memory entry if found, None otherwise
Raises:
MemoryAccessError: If retrieval fails
"""
async with self._lock:
# Check cache first
if memory_id in self._cache:
entry = self._cache[memory_id]
entry.access()
return entry
# Try to load from file
file_path = self._get_file_path(memory_id)
if not file_path.exists():
return None
try:
with open(file_path, 'r') as f:
entry_dict = json.load(f)
entry = MemoryEntry.from_dict(entry_dict)
# Update access metadata
entry.access()
# Add to cache
self._cache[memory_id] = entry
return entry
except Exception as e:
raise MemoryAccessError(f"Failed to retrieve memory entry: {e}") from e
async def delete(self, memory_id: MemoryID) -> bool:
"""
Delete a memory entry.
Args:
memory_id: ID of the memory to delete
Returns:
True if deleted, False if not found
Raises:
MemoryAccessError: If deletion fails
"""
async with self._lock:
try:
# Remove from cache
if memory_id in self._cache:
del self._cache[memory_id]
# Remove file
file_path = self._get_file_path(memory_id)
if file_path.exists():
file_path.unlink()
return True
return False
except Exception as e:
raise MemoryAccessError(f"Failed to delete memory entry: {e}") from e
async def query(self, query: Dict[str, Any], limit: Optional[int] = None) -> List[MemoryEntry]:
"""
Query for memory entries matching criteria.
This implementation is not efficient for file-based storage as it
needs to load all entries to perform the query. In a real-world
implementation, you would want to use an indexed database.
Args:
query: Query criteria
limit: Maximum number of results to return
Returns:
List of matching memory entries
Raises:
MemoryAccessError: If query fails
"""
async with self._lock:
try:
results = []
# Iterate through all files in the directory (inefficient, but simple)
for shard_dir in self._directory.iterdir():
if not shard_dir.is_dir():
continue
for file_path in shard_dir.glob("*.json"):
try:
# Load the entry
with open(file_path, 'r') as f:
entry_dict = json.load(f)
# Check if it matches the query
match = True
for key, value in query.items():
# Handle nested keys (dot notation)
if '.' in key:
parts = key.split('.')
current = entry_dict
for part in parts[:-1]:
if not isinstance(current, dict) or part not in current:
match = False
break
current = current[part]
if match and (parts[-1] not in current or current[parts[-1]] != value):
match = False
# Handle direct keys
elif key not in entry_dict or entry_dict[key] != value:
match = False
if match:
entry = MemoryEntry.from_dict(entry_dict)
entry.access()
results.append(entry)
# Update the file with new access time
await self.store(entry)
# Stop if we've reached the limit
if limit is not None and len(results) >= limit:
break
except Exception as e:
logger.warning(f"Error reading memory file {file_path}: {e}")
# Stop if we've reached the limit
if limit is not None and len(results) >= limit:
break
return results
except Exception as e:
raise MemoryAccessError(f"Failed to query memory entries: {e}") from e
async def clear(self) -> None:
"""
Clear all memory entries.
Raises:
MemoryAccessError: If clearing fails
"""
async with self._lock:
try:
# Clear cache
self._cache.clear()
# Remove all files
for shard_dir in self._directory.iterdir():
if not shard_dir.is_dir():
continue
for file_path in shard_dir.glob("*.json"):
file_path.unlink()
# Remove empty shard directories
if not any(shard_dir.iterdir()):
shard_dir.rmdir()
except Exception as e:
raise MemoryAccessError(f"Failed to clear memory store: {e}") from e
class MemoryManagerBase(ABC):
"""
Abstract base class for memory systems.
This defines the interface for memory systems, which allow agents
to store, retrieve, and manage information. Different memory system
implementations can provide different types of memory (working, episodic,
semantic, etc.) with different characteristics.
"""
def __init__(self):
"""Initialize the memory system."""
self._agent_id = None
def set_agent_id(self, agent_id: AgentID) -> None:
"""
Set the agent ID for this memory system.
Args:
agent_id: ID of the agent this memory belongs to
"""
self._agent_id = agent_id
@abstractmethod
async def store(self, content: Any, memory_type: MemoryType,
importance: float = 0.5, metadata: Optional[Dict[str, Any]] = None) -> MemoryID:
"""
Store an item in memory.
Args:
content: Content to store
memory_type: Type of memory to store in
importance: Importance score (0.0 to 1.0)
metadata: Additional metadata
Returns:
ID of the stored memory
Raises:
MemoryStorageError: If storage fails
"""
pass
@abstractmethod
async def retrieve(self, memory_id: MemoryID) -> Optional[MemoryEntry]:
"""
Retrieve an item from memory by ID.
Args:
memory_id: ID of the memory to retrieve
Returns:
Memory entry if found, None otherwise
Raises:
MemoryAccessError: If retrieval fails
"""
pass
@abstractmethod
async def query(self, query: Dict[str, Any], limit: Optional[int] = None) -> List[MemoryEntry]:
"""
Query for memory entries matching criteria.
Args:
query: Query criteria
limit: Maximum number of results to return
Returns:
List of matching memory entries
Raises:
MemoryAccessError: If query fails
"""
pass
@abstractmethod
async def forget(self, memory_id: MemoryID) -> bool:
"""
Forget (delete) a memory.
Args:
memory_id: ID of the memory to forget
Returns:
True if forgotten, False if not found
Raises:
MemoryAccessError: If forgetting fails
"""
pass
@abstractmethod
async def update_importance(self, memory_id: MemoryID, importance: float) -> bool:
"""
Update the importance of a memory.
Args:
memory_id: ID of the memory to update
importance: New importance score (0.0 to 1.0)
Returns:
True if updated, False if not found
Raises:
MemoryAccessError: If update fails
ValueError: If importance is outside valid range
"""
pass
@abstractmethod
async def consolidate(self) -> None:
"""
Consolidate memories based on memory management policies.
This process might involve forgetting less important memories,
summarizing related memories, or transferring between memory types.
Raises:
MemoryAccessError: If consolidation fails
"""
pass
@abstractmethod
async def clear(self, memory_type: Optional[MemoryType] = None) -> None:
"""
Clear all memories of a specific type or all types.
Args:
memory_type: Type of memory to clear, or None for all types
Raises:
MemoryAccessError: If clearing fails
"""
pass
class WorkingMemory(MemoryManagerBase):
"""
Working (short-term) memory implementation.
Working memory has limited capacity and is used for temporary storage
of information needed for current processing. It follows a least-recently-used
eviction policy when capacity is exceeded.
"""
def __init__(self, capacity: int = 100, store: Optional[MemoryStore] = None):
"""
Initialize working memory.
Args:
capacity: Maximum number of items in working memory
store: Memory store to use (creates InMemoryStore if None)
"""
super().__init__()
self._capacity = capacity
self._store = store or InMemoryStore()
self._lru_tracker = OrderedDict() # memory_id -> access timestamp
async def store(self, content: Any, memory_type: MemoryType = MemoryType.WORKING,
importance: float = 0.5, metadata: Optional[Dict[str, Any]] = None) -> MemoryID:
"""
Store an item in working memory.
If capacity is exceeded, the least recently used item is evicted.
Args:
content: Content to store
memory_type: Type of memory (ignored, always WORKING)
importance: Importance score (0.0 to 1.0)
metadata: Additional metadata
Returns:
ID of the stored memory
Raises:
MemoryStorageError: If storage fails
ValueError: If importance is outside valid range
"""
if not 0.0 <= importance <= 1.0:
raise ValueError("Importance must be between 0.0 and 1.0")
# Always use WORKING memory type
memory_type = MemoryType.WORKING
# Create memory entry
entry = MemoryEntry.create(
content=content,
memory_type=memory_type,
importance=importance,
metadata=metadata or {}
)
# Store the entry
await self._store.store(entry)
# Update LRU tracker
self._lru_tracker[entry.id] = entry.last_accessed
# Check capacity and evict if needed
await self._check_capacity()
return entry.id
async def retrieve(self, memory_id: MemoryID) -> Optional[MemoryEntry]:
"""
Retrieve an item from working memory by ID.
Args:
memory_id: ID of the memory to retrieve
Returns:
Memory entry if found, None otherwise
Raises:
MemoryAccessError: If retrieval fails
"""
entry = await self._store.retrieve(memory_id)
if entry:
# Update LRU tracker
self._lru_tracker[entry.id] = entry.last_accessed
return entry
async def query(self, query: Dict[str, Any], limit: Optional[int] = None) -> List[MemoryEntry]:
"""
Query for memory entries matching criteria.
Args:
query: Query criteria
limit: Maximum number of results to return
Returns:
List of matching memory entries
Raises:
MemoryAccessError: If query fails
"""
# Ensure we only query for WORKING memory type
query = {**query, "memory_type": MemoryType.WORKING.name}
results = await self._store.query(query, limit)
# Update LRU tracker for all retrieved entries
for entry in results:
self._lru_tracker[entry.id] = entry.last_accessed
return results
async def forget(self, memory_id: MemoryID) -> bool:
"""
Forget (delete) a memory.
Args:
memory_id: ID of the memory to forget
Returns:
True if forgotten, False if not found
Raises:
MemoryAccessError: If forgetting fails
"""
result = await self._store.delete(memory_id)
if result and memory_id in self._lru_tracker:
del self._lru_tracker[memory_id]
return result
async def update_importance(self, memory_id: MemoryID, importance: float) -> bool:
"""
Update the importance of a memory.
Args:
memory_id: ID of the memory to update
importance: New importance score (0.0 to 1.0)
Returns:
True if updated, False if not found
Raises:
MemoryAccessError: If update fails
ValueError: If importance is outside valid range
"""
if not 0.0 <= importance <= 1.0:
raise ValueError("Importance must be between 0.0 and 1.0")
# Retrieve the entry
entry = await self.retrieve(memory_id)
if not entry:
return False
# Update importance
entry.update_importance(importance)
# Store the updated entry
await self._store.store(entry)
return True
async def consolidate(self) -> None:
"""
Consolidate working memory.
For working memory, this just checks capacity and evicts
if needed.
"""
await self._check_capacity()
async def clear(self, memory_type: Optional[MemoryType] = None) -> None:
"""
Clear all memories.
Args:
memory_type: Ignored for working memory
"""
await self._store.clear()
self._lru_tracker.clear()
async def _check_capacity(self) -> None:
"""
Check if capacity is exceeded and evict if needed.
This implements a least-recently-used eviction policy.
"""
while len(self._lru_tracker) > self._capacity:
# Get the least recently used item
oldest_id, _ = next(iter(self._lru_tracker.items()))
# Forget it
await self.forget(oldest_id)
class EpisodicMemory(MemoryManagerBase):
"""
Episodic (event-based) memory implementation.
Episodic memory stores records of experiences and events, with
temporal context. It has a larger capacity than working memory
but may forget less important memories over time.
"""
def __init__(self, store: Optional[MemoryStore] = None,
forget_threshold: float = 0.3,
time_decay_factor: float = 0.1):
"""
Initialize episodic memory.
Args:
store: Memory store to use (creates InMemoryStore if None)
forget_threshold: Importance threshold below which memories may be forgotten
time_decay_factor: Factor for time-based importance decay
"""
super().__init__()
self._store = store or InMemoryStore()
self._forget_threshold = forget_threshold
self._time_decay_factor = time_decay_factor
self._last_consolidation = time.time()
async def store(self, content: Any, memory_type: MemoryType = MemoryType.EPISODIC,
importance: float = 0.5, metadata: Optional[Dict[str, Any]] = None) -> MemoryID:
"""
Store an item in episodic memory.
Args:
content: Content to store
memory_type: Type of memory (ignored, always EPISODIC)
importance: Importance score (0.0 to 1.0)
metadata: Additional metadata
Returns:
ID of the stored memory
Raises:
MemoryStorageError: If storage fails
ValueError: If importance is outside valid range
"""
if not 0.0 <= importance <= 1.0:
raise ValueError("Importance must be between 0.0 and 1.0")
# Always use EPISODIC memory type
memory_type = MemoryType.EPISODIC
# Ensure metadata includes temporal context
metadata = metadata or {}
if "timestamp" not in metadata:
metadata["timestamp"] = time.time()
# Create memory entry
entry = MemoryEntry.create(
content=content,
memory_type=memory_type,
importance=importance,
metadata=metadata
)
# Store the entry
await self._store.store(entry)
return entry.id
async def retrieve(self, memory_id: MemoryID) -> Optional[MemoryEntry]:
"""
Retrieve an item from episodic memory by ID.
Args:
memory_id: ID of the memory to retrieve
Returns:
Memory entry if found, None otherwise
Raises:
MemoryAccessError: If retrieval fails
"""
entry = await self._store.retrieve(memory_id)
if entry and entry.memory_type == MemoryType.EPISODIC:
# Boost importance slightly when accessed (memory strengthening)
if entry.importance < 0.95:
entry.update_importance(entry.importance + 0.05)
await self._store.store(entry)
return entry
async def query(self, query: Dict[str, Any], limit: Optional[int] = None) -> List[MemoryEntry]:
"""
Query for memory entries matching criteria.
Args:
query: Query criteria
limit: Maximum number of results to return
Returns:
List of matching memory entries
Raises:
MemoryAccessError: If query fails
"""
# Ensure we only query for EPISODIC memory type
query = {**query, "memory_type": MemoryType.EPISODIC.name}
results = await self._store.query(query, limit)
# Boost importance slightly for all retrieved entries
for entry in results:
if entry.importance < 0.95:
entry.update_importance(entry.importance + 0.05)
await self._store.store(entry)
return results
async def forget(self, memory_id: MemoryID) -> bool:
"""
Forget (delete) a memory.
Args:
memory_id: ID of the memory to forget
Returns:
True if forgotten, False if not found
Raises:
MemoryAccessError: If forgetting fails
"""
return await self._store.delete(memory_id)
async def update_importance(self, memory_id: MemoryID, importance: float) -> bool:
"""
Update the importance of a memory.
Args:
memory_id: ID of the memory to update
importance: New importance score (0.0 to 1.0)
Returns:
True if updated, False if not found
Raises:
MemoryAccessError: If update fails
ValueError: If importance is outside valid range
"""
if not 0.0 <= importance <= 1.0:
raise ValueError("Importance must be between 0.0 and 1.0")
# Retrieve the entry
entry = await self.retrieve(memory_id)
if not entry or entry.memory_type != MemoryType.EPISODIC:
return False
# Update importance
entry.update_importance(importance)
# Store the updated entry
await self._store.store(entry)
return True
async def consolidate(self) -> None:
"""
Consolidate episodic memory.
This process involves:
1. Decaying importance of memories over time
2. Forgetting memories below the importance threshold
"""
current_time = time.time()
time_since_last = current_time - self._last_consolidation
# Don't consolidate too frequently
if time_since_last < 3600: # 1 hour
return
self._last_consolidation = current_time
# Query all episodic memories
all_memories = await self.query({}, None)
for entry in all_memories:
# Calculate time decay
age = current_time - entry.created_at
decay = min(0.9, self._time_decay_factor * (age / 86400)) # 86400 seconds in a day
# Apply decay to importance
new_importance = max(0.0, entry.importance - decay)
entry.update_importance(new_importance)
if new_importance < self._forget_threshold: