Repository navigation
Expand file tree
/
Copy pathmemory_engine.py
More file actions
860 lines (738 loc) · 36.4 KB
/
Copy pathmemory_engine.py
File metadata and controls
860 lines (738 loc) · 36.4 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
import asyncio
import logging
import time
import uuid
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
from app.memory.config.logging_config import memory_log_config
from app.api.v1.request.memory_request import MemoryRecordInput, SearchQuery
from app.api.v1.response.memory_response import (
MemoryResponse,
SearchResponse,
SearchResult,
)
from app.common.enum.memory import MemoryOperation, MemoryType
from app.memory.config.context_zero_config import ContextZeroConfig
from app.memory.inferencer.memory_type_inferencer import MemoryTypeInferencer
from app.memory.models.audit_log import AuditLogEntry
from app.memory.models.memory_entry import MemoryEntry
from app.memory.models.memory_record import MemoryRecord
from app.memory.router.memory_router import MemoryRouter
from app.memory.stores.base_store import (
AuditStore,
DocumentStore,
GraphStore,
TimeSeriesStore,
VectorStore,
)
class MemoryEngine:
"""Main memory processing engine that orchestrates the entire pipeline"""
_instance = None
def __init__(self, config: Optional[ContextZeroConfig] = None):
"""Initialize the memory engine with configuration"""
self.config = config or ContextZeroConfig()
self.inferencer = MemoryTypeInferencer(self.config.llm)
self.router = MemoryRouter(self.inferencer)
# Stores will be initialized in initialize()
self.vector_store: Optional[VectorStore] = None
self.graph_store: Optional[GraphStore] = None
self.doc_store: Optional[DocumentStore] = None
self.timeseries_store: Optional[TimeSeriesStore] = None
self.audit_store: Optional[AuditStore] = None
# Processing statistics
self.processing_stats = {
"total_memories": 0,
"memories_by_type": {},
"average_processing_time": 0,
"last_processed": None,
}
self._initialized = False
MemoryEngine._instance = self
@classmethod
def get_instance(cls) -> "MemoryEngine":
"""Get singleton instance of memory engine"""
if cls._instance is None:
cls._instance = cls()
return cls._instance
async def initialize(self):
"""Initialize all stores and components"""
if self._initialized:
return
# Setup memory logging configuration
memory_log_config.setup()
memory_log_config.log_info("Initializing Memory Engine...")
# Load configuration from YAML files
from app.memory.config.yaml_config_loader import get_config_loader
config_loader = get_config_loader()
try:
# Initialize Vector Store (Pinecone)
vector_config = config_loader.get_vector_store_config()
memory_log_config.log_config("Vector Store Config", vector_config)
if vector_config.get("provider") == "pinecone":
await self._initialize_pinecone(vector_config)
# Initialize Graph Store (Neo4j)
graph_config = config_loader.get_graph_store_config()
memory_log_config.log_config("Graph Store Config", graph_config)
if graph_config.get("provider") == "neo4j":
await self._initialize_neo4j(graph_config)
# Initialize Document Store (MongoDB)
doc_config = config_loader.get_doc_store_config()
memory_log_config.log_config("Document Store Config", doc_config)
if doc_config.get("provider") == "mongodb":
await self._initialize_mongodb(doc_config)
# Initialize Time Series Store (TimescaleDB)
try:
time_config = config_loader.get_time_store_config()
memory_log_config.log_config("Time Series Store Config", time_config)
if time_config and time_config.get("provider") == "timescaledb":
await self._initialize_timescaledb(time_config)
except Exception as e:
memory_log_config.log_warning(f"TimescaleDB not configured: {e}")
self.timeseries_store = None
# Initialize Audit Store (MongoDB)
audit_config = config_loader.get_audit_store_config()
memory_log_config.log_config("Audit Store Config", audit_config)
if audit_config.get("provider") == "mongodb":
await self._initialize_audit_store(audit_config)
# Print LLM and Embedder configs
try:
llm_config = config_loader.get_llm_config()
memory_log_config.log_config("LLM Config", llm_config)
except Exception as e:
memory_log_config.log_warning(f"LLM config error: {e}")
try:
embedder_config = config_loader.get_embedder_config()
memory_log_config.log_config("Embedder Config", embedder_config)
except Exception as e:
memory_log_config.log_warning(f"Embedder config error: {e}")
try:
system_config = config_loader.get_system_config()
memory_log_config.log_config("System Config", system_config)
except Exception as e:
memory_log_config.log_warning(f"System config error: {e}")
self._initialized = True
memory_log_config.log_success("Memory Engine initialized successfully")
except Exception as e:
memory_log_config.log_error(f"Error initializing Memory Engine: {e}")
import traceback
traceback.print_exc()
# Continue with in-memory stores as fallback
async def _initialize_pinecone(self, config: dict):
"""Initialize Pinecone vector store"""
try:
from app.memory.stores.pinecone_store import PineconeVectorStore
store_config = config.get("config", {})
self.vector_store = PineconeVectorStore(
api_key=store_config.get("api_key"),
environment=store_config.get("environment", "us-east-1-aws"),
index_name=store_config.get("index_name", "memory-index"),
)
await self.vector_store.initialize()
memory_log_config.log_success("Pinecone vector store initialized")
except Exception as e:
memory_log_config.log_error(f"Failed to initialize Pinecone: {e}")
self.vector_store = None
async def _initialize_neo4j(self, config: dict):
"""Initialize Neo4j graph store"""
try:
from app.memory.stores.neo4j_store import Neo4jGraphStore
store_config = config.get("config", {})
self.graph_store = Neo4jGraphStore(
uri=store_config.get("uri"),
username=store_config.get("username"),
password=store_config.get("password"),
database=store_config.get("database", "neo4j"),
)
await self.graph_store.initialize()
memory_log_config.log_success("Neo4j graph store initialized")
except Exception as e:
memory_log_config.log_error(f"Failed to initialize Neo4j: {e}")
async def _initialize_mongodb(self, config: dict):
"""Initialize MongoDB document store"""
try:
from app.memory.stores.mongodb_store import MongoDocumentStore
store_config = config.get("config", {})
self.doc_store = MongoDocumentStore(
connection_string=store_config.get("connection_string"),
database_name=store_config.get("database_name", "memory_system"),
collection_name=store_config.get("collection_name", "memories"),
)
await self.doc_store.initialize()
memory_log_config.log_success("MongoDB document store initialized")
except Exception as e:
memory_log_config.log_error(
f"Failed to initialize MongoDB document store: {e}"
)
async def _initialize_timescaledb(self, config: dict):
"""Initialize TimescaleDB time series store"""
try:
from app.memory.stores.timescale_store import TimescaleTimeSeriesStore
store_config = config.get("config", {})
self.timeseries_store = TimescaleTimeSeriesStore(
connection_string=store_config.get("connection_string"),
table_name=store_config.get("table_name", "memory_timeseries"),
)
await self.timeseries_store.initialize()
memory_log_config.log_success("TimescaleDB time series store initialized")
except Exception as e:
memory_log_config.log_error(f"Failed to initialize TimescaleDB: {e}")
async def _initialize_audit_store(self, config: dict):
"""Initialize MongoDB audit store"""
try:
from app.memory.stores.mongodb_audit_store import MongoAuditStore
store_config = config.get("config", {})
self.audit_store = MongoAuditStore(
connection_string=store_config.get("connection_string"),
database_name=store_config.get("database_name", "memory_audit"),
collection_name=store_config.get("collection_name", "audit_log"),
)
await self.audit_store.initialize()
memory_log_config.log_success("MongoDB audit store initialized")
except Exception as e:
memory_log_config.log_error(
f"Failed to initialize MongoDB audit store: {e}"
)
# ==========================================
# CORE MEMORY OPERATIONS
# ==========================================
async def add_memory(self, record_input: MemoryRecordInput) -> MemoryResponse:
"""Add a new memory to the system"""
if not self._initialized:
await self.initialize()
start_time = time.time()
try:
# Add category and emotion as tags if present
tags = record_input.tags.copy()
# Add primary category as a special tag
if record_input.category:
tags.append(f"primary_category:{record_input.category.value}")
# Also add the category itself as a regular tag
tags.append(record_input.category.value)
# Add primary emotion as a special tag
if record_input.emotion:
tags.append(f"primary_emotion:{record_input.emotion.value}")
# Also add the emotion itself as a regular tag
tags.append(record_input.emotion.value)
# Add emotion intensity if present
if record_input.emotion_intensity:
tags.append(
f"emotion_intensity:{record_input.emotion_intensity.value}"
)
# Store category and emotion in metadata for future reference
metadata = record_input.metadata.copy()
if record_input.category:
metadata["category"] = record_input.category.value
if record_input.emotion:
metadata["emotion"] = record_input.emotion.value
if record_input.emotion_intensity:
metadata["emotion_intensity"] = record_input.emotion_intensity.value
# Convert input to MemoryRecord
record = MemoryRecord(
user_id=record_input.user_id,
session_id=record_input.session_id,
raw_text=record_input.text,
memory_type=record_input.memory_type,
tags=tags,
metadata=metadata,
scope=record_input.scope or "default",
)
# Process through the pipeline
memory_entry = await self.process_memory(record)
# Store in all configured stores
await self._store_memory(memory_entry)
# Update statistics
processing_time = time.time() - start_time
self._update_stats(memory_entry.memory_type, processing_time)
return MemoryResponse(
success=True,
memory_id=memory_entry.id,
operation=MemoryOperation.ADD,
confidence=memory_entry.meta.confidence_score or 1.0,
processing_time_ms=int(processing_time * 1000),
message="Memory processed and stored successfully",
memory_type=memory_entry.memory_type,
)
except Exception as e:
return MemoryResponse(
success=False,
memory_id="",
operation=MemoryOperation.ADD,
confidence=0.0,
processing_time_ms=int((time.time() - start_time) * 1000),
message=f"Failed to process memory: {str(e)}",
)
async def process_memory(self, record: MemoryRecord) -> MemoryEntry:
"""Process a single memory through the entire pipeline"""
# Route to appropriate handler
handler = await self.router.route(record)
# Process the memory
memory_entry = await handler.process(record)
return memory_entry
async def search_memories(self, query: SearchQuery) -> SearchResponse:
"""Search for memories using semantic similarity"""
if not self._initialized:
await self.initialize()
start_time = time.time()
try:
results = []
# Use vector store for semantic search if available
if self.vector_store:
# Generate query embedding
try:
handler = self.router.get_handler(MemoryType.SEMANTIC_MEMORY)
if handler is None:
raise ValueError("Semantic memory handler not found")
query_embedding, _ = await handler.extract_embedding(query.query)
except Exception as e:
logger.error(f"Error generating query embedding: {e}")
# Fall back to document store search
handler = None
if handler is not None:
# Search vector store using similarity search
search_filter = {"user_id": query.user_id}
if query.memory_types:
search_filter["memory_type"] = {
"$in": [mt.value for mt in query.memory_types]
}
if query.tags:
search_filter["tags"] = {"$in": query.tags}
# Add category and emotion filters for primary values
if hasattr(query, "category") and query.category:
category_tag = f"primary_category:{query.category.value}"
if "tags" in search_filter:
if (
isinstance(search_filter["tags"], dict)
and "$in" in search_filter["tags"]
):
search_filter["tags"]["$in"].append(category_tag)
else:
search_filter["tags"] = {"$in": [category_tag]}
else:
search_filter["tags"] = {"$in": [category_tag]}
if hasattr(query, "emotion") and query.emotion:
emotion_tag = f"primary_emotion:{query.emotion.value}"
if "tags" in search_filter:
if (
isinstance(search_filter["tags"], dict)
and "$in" in search_filter["tags"]
):
search_filter["tags"]["$in"].append(emotion_tag)
else:
search_filter["tags"] = {"$in": [emotion_tag]}
else:
search_filter["tags"] = {"$in": [emotion_tag]}
vector_results = await self.vector_store.similarity_search(
embedding=query_embedding,
limit=query.limit,
filter=search_filter,
)
# Convert to SearchResult objects
for memory_entry, score in vector_results:
# Filter by threshold
if score >= query.threshold:
try:
# Handle both dict and MemoryEntry formats
if isinstance(memory_entry, dict):
# Pinecone returns dict format
metadata = memory_entry.get("metadata", {})
# Parse memory type - handle both string formats
memory_type_str = metadata.get(
"memory_type", "semantic_memory"
)
if "." in memory_type_str:
# Format: "MemoryType.EMOTIONAL_MEMORY"
memory_type_value = memory_type_str.split(".")[
-1
].lower()
else:
memory_type_value = memory_type_str
try:
memory_type = MemoryType(memory_type_value)
except ValueError:
memory_type = MemoryType.SEMANTIC_MEMORY
# Parse created_at
created_at_str = metadata.get("created_at")
if isinstance(created_at_str, str):
try:
created_at = datetime.fromisoformat(
created_at_str.replace("Z", "+00:00")
)
except:
created_at = datetime.now()
else:
created_at = created_at_str or datetime.now()
# Parse tags - handle both string and list formats
tags_data = metadata.get("tags", [])
if isinstance(tags_data, str):
tags = tags_data.split(",") if tags_data else []
tags = [
tag.strip() for tag in tags if tag.strip()
]
elif isinstance(tags_data, list):
tags = tags_data
else:
tags = []
# Parse confidence
confidence_data = metadata.get("confidence", 0.8)
if isinstance(confidence_data, str):
try:
confidence = float(confidence_data)
except:
confidence = 0.8
else:
confidence = confidence_data
# Extract category and emotion from metadata
category = None
emotion = None
if "category" in metadata:
try:
from app.common.enum.memory_category import (
MemoryCategory,
)
category = MemoryCategory(
metadata["category"]
)
except:
pass
if "emotion" in metadata:
try:
from app.common.enum.memory_emotion import (
MemoryEmotion,
)
emotion = MemoryEmotion(metadata["emotion"])
except:
pass
search_result = SearchResult(
id=memory_entry["id"],
content=metadata.get("input")
if query.include_content
else None,
summary=metadata.get("summary", ""),
memory_type=memory_type,
score=score,
confidence=confidence,
tags=tags,
created_at=created_at,
scope=metadata.get("scope"),
category=category,
emotion=emotion,
)
else:
# MemoryEntry object format
# Extract category and emotion from metadata or tags
category = None
emotion = None
if (
hasattr(memory_entry, "metadata")
and memory_entry.metadata
):
if "category" in memory_entry.metadata:
try:
from app.common.enum.memory_category import (
MemoryCategory,
)
category = MemoryCategory(
memory_entry.metadata["category"]
)
except:
pass
if "emotion" in memory_entry.metadata:
try:
from app.common.enum.memory_emotion import (
MemoryEmotion,
)
emotion = MemoryEmotion(
memory_entry.metadata["emotion"]
)
except:
pass
search_result = SearchResult(
id=memory_entry.id,
content=memory_entry.input
if query.include_content
else None,
summary=memory_entry.summary or "",
memory_type=memory_entry.memory_type,
score=score,
confidence=memory_entry.confidence
if hasattr(memory_entry, "confidence")
else 0.8,
tags=memory_entry.tags,
created_at=memory_entry.created_at,
scope=memory_entry.scope,
category=category,
emotion=emotion,
)
results.append(search_result)
except Exception as e:
logger.error(
f"Error processing search result {memory_entry}: {e}"
)
continue
# Fallback to document store text search
elif self.doc_store:
doc_results = await self.doc_store.search_memories(
user_id=query.user_id,
query_text=query.query,
memory_types=query.memory_types,
tags=query.tags,
limit=query.limit,
)
for result in doc_results:
search_result = SearchResult(
id=result["id"],
summary=result.get("summary", ""),
memory_type=MemoryType(result["memory_type"]),
score=0.8, # Default score for text search
tags=result.get("tags", []),
created_at=result["created_at"],
confidence=result.get("confidence", 0.0),
content=result.get("input") if query.include_content else None,
scope=result.get("scope"),
)
results.append(search_result)
return SearchResponse(
success=True,
results=results,
total_count=len(results),
query_time_ms=int((time.time() - start_time) * 1000),
query=query.query,
filters_applied={
"memory_types": query.memory_types,
"tags": query.tags,
"threshold": query.threshold,
},
)
except Exception as e:
return SearchResponse(
success=False,
results=[],
total_count=0,
query_time_ms=int((time.time() - start_time) * 1000),
query=query.query,
filters_applied={},
)
async def add_memories_bulk(
self, records: List[MemoryRecordInput]
) -> List[Dict[str, Any]]:
"""Bulk add memories with batch processing"""
if not self._initialized:
await self.initialize()
results = []
for record_input in records:
try:
response = await self.add_memory(record_input)
results.append(
{
"success": response.success,
"memory_id": response.memory_id,
"user_id": record_input.user_id,
"message": response.message,
"processing_time_ms": response.processing_time_ms,
}
)
except Exception as e:
results.append(
{
"success": False,
"memory_id": "",
"user_id": record_input.user_id,
"message": f"Failed to process: {str(e)}",
"processing_time_ms": 0,
}
)
return results
# ==========================================
# STORAGE OPERATIONS
# ==========================================
async def _store_memory(self, memory_entry: MemoryEntry):
"""Store memory in all configured stores"""
tasks = []
# Convert to dict for storage
memory_dict = memory_entry.dict()
memory_dict["created_at"] = datetime.utcnow()
memory_dict["updated_at"] = datetime.utcnow()
# Store in vector store
if self.vector_store:
tasks.append(self.vector_store.add_memory(memory_dict))
# Store in graph store
if self.graph_store:
tasks.append(self.graph_store.add_memory(memory_dict))
# Store in document store
if self.doc_store:
tasks.append(self.doc_store.add_memory(memory_dict))
# Store in time series store
if self.timeseries_store:
tasks.append(self.timeseries_store.add_memory(memory_dict))
# Store in audit store
if self.audit_store:
audit_entry = AuditLogEntry(
id=f"audit_{memory_entry.id}_{int(datetime.utcnow().timestamp())}",
action=MemoryOperation.ADD,
memory_id=memory_entry.id,
cid=memory_entry.cid,
user_id=memory_entry.source_user_id or "",
session_id=memory_entry.source_session_id or "",
timestamp=datetime.utcnow(),
after_state=memory_dict,
inferred_type=memory_entry.memory_type,
handler_used=memory_entry.meta.handler_version,
processing_time_ms=memory_entry.meta.processing_time_ms,
)
tasks.append(self.audit_store.log_operation(audit_entry))
# Execute all storage operations in parallel
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
# Check if at least one store succeeded
successes = sum(1 for r in results if not isinstance(r, Exception))
if successes == 0:
# Log available stores for debugging
available_stores = []
if self.vector_store:
available_stores.append("vector")
if self.graph_store:
available_stores.append("graph")
if self.doc_store:
available_stores.append("document")
if self.timeseries_store:
available_stores.append("timeseries")
if self.audit_store:
available_stores.append("audit")
memory_log_config.log_warning(
f"All stores failed for memory {memory_entry.id}"
)
memory_log_config.log_warning(f"Available stores: {available_stores}")
memory_log_config.log_warning(
"Continuing anyway to prevent blocking..."
)
else:
memory_log_config.log_success(
f"Memory stored in {successes}/{len(tasks)} stores"
)
# ==========================================
# UTILITY METHODS
# ==========================================
def _update_stats(self, memory_type: MemoryType, processing_time: float):
"""Update processing statistics"""
self.processing_stats["total_memories"] += 1
self.processing_stats["last_processed"] = datetime.utcnow().isoformat()
# Update memory type counts
type_name = memory_type.value
if type_name not in self.processing_stats["memories_by_type"]:
self.processing_stats["memories_by_type"][type_name] = 0
self.processing_stats["memories_by_type"][type_name] += 1
# Update average processing time
current_avg = self.processing_stats["average_processing_time"]
total = self.processing_stats["total_memories"]
self.processing_stats["average_processing_time"] = (
current_avg * (total - 1) + processing_time
) / total
def _calculate_similarity(
self, embedding1: List[float], embedding2: List[float]
) -> float:
"""Calculate cosine similarity between two embeddings"""
import numpy as np
arr1 = np.array(embedding1)
arr2 = np.array(embedding2)
# Cosine similarity
dot_product = np.dot(arr1, arr2)
norms = np.linalg.norm(arr1) * np.linalg.norm(arr2)
if norms == 0:
return 0.0
return float(dot_product / norms)
async def health_check(self) -> Dict[str, Any]:
"""Check health of all components"""
health = {"engine": True, "initialized": self._initialized, "stores": {}}
# Check store health
stores = {
"vector_store": self.vector_store,
"graph_store": self.graph_store,
"doc_store": self.doc_store,
"timeseries_store": self.timeseries_store,
"audit_store": self.audit_store,
}
for store_name, store in stores.items():
if store:
try:
store_health = await store.health_check()
health["stores"][store_name] = store_health
except Exception:
health["stores"][store_name] = False
else:
health["stores"][store_name] = None
return health
# ==========================================
# TIME-TRAVEL DEBUGGING METHODS
# ==========================================
async def time_travel_query(
self, user_id: str, query: str, target_time: datetime
) -> Dict[str, Any]:
"""Answer a query based on memory state at a specific point in time"""
if not self._initialized:
await self.initialize()
if not self.audit_store:
raise ValueError("Audit store not configured - time travel not available")
# Get memory state at target time
memory_state = await self.audit_store.get_memory_state_at_time(
user_id, target_time
)
# Generate embedding for query using current handlers
handler = self.router.get_handler(MemoryType.SEMANTIC_MEMORY)
query_embedding, _ = await handler.extract_embedding(query)
# Find relevant memories from the historical state
relevant_memories = []
for memory in memory_state:
if memory.get("embedding"):
similarity = self._calculate_similarity(
query_embedding, memory["embedding"]
)
if similarity > 0.7: # Threshold
memory["similarity_score"] = similarity
relevant_memories.append(memory)
# Sort by relevance
relevant_memories.sort(key=lambda x: x["similarity_score"], reverse=True)
return {
"success": True,
"target_time": target_time,
"query": query,
"total_memories_at_time": len(memory_state),
"relevant_memories": relevant_memories[:10], # Top 10
"context": f"Based on memory state at {target_time}",
}
async def close(self):
"""Clean shutdown of memory eng
ine and all stores"""
memory_log_config.log_info("Closing Memory Engine...")
# Close all stores
stores = [
("vector_store", self.vector_store),
("graph_store", self.graph_store),
("doc_store", self.doc_store),
("timeseries_store", self.timeseries_store),
("audit_store", self.audit_store),
]
for store_name, store in stores:
if store:
try:
if hasattr(store, "close"):
await store.close()
memory_log_config.log_success(
f"{store_name} closed successfully"
)
elif hasattr(store, "disconnect"):
await store.disconnect()
memory_log_config.log_success(
f"{store_name} disconnected successfully"
)
else:
memory_log_config.log_info(
f"{store_name} has no close/disconnect method"
)
except Exception as e:
memory_log_config.log_warning(f"Error closing {store_name}: {e}")
# Close thread pool executor if it exists
if hasattr(self, "executor"):
self.executor.shutdown(wait=True)
memory_log_config.log_success("Thread pool executor shutdown")
memory_log_config.log_success("Memory Engine closed successfully")