-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_longmemeval_chunked.py
More file actions
2304 lines (1881 loc) · 97.3 KB
/
Copy pathtest_longmemeval_chunked.py
File metadata and controls
2304 lines (1881 loc) · 97.3 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
#!/usr/bin/env python3
"""
Improved Chunked LongMemEval Test Script with Better Retrieval
Key Improvements:
1. Better session summary generation that captures ALL topics discussed
2. Enhanced embedding strategy that includes both summary AND key content
3. Improved retrieval with multi-query strategy
4. Better context prioritization based on session relevance
"""
import os
import sys
import json
import logging
import time
import uuid
import re
import pickle
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from dotenv import load_dotenv
from collections import defaultdict
from tqdm import tqdm
import warnings
warnings.filterwarnings("ignore")
os.environ["TRANSFORMERS_VERBOSITY"] = "error"
load_dotenv()
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from load_longmemeval import load_longmemeval_dataset, LongMemQuestion
from memory.trg_memory import TemporalResonanceGraphMemory
from memory.graph_db import NetworkXGraphDB, EventNode, EpisodeNode, Link, LinkType, LinkSubType, NodeType
from memory.vector_db import NumpyVectorDB
from memory.query_engine import QueryEngine
from memory.answer_formatter import AnswerFormatter
from memory.longmemeval_evaluator import LongMemEvalEvaluator
from utils.memory_layer import LLMController
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
class ChunkedLongMemEvalTester:
"""Improved test harness with better retrieval strategies"""
def __init__(self, model: str = "gpt-4o-mini", embedding_model: str = "minilm",
chunk_size: int = 4, use_episodes: bool = False, memory_level: str = "session", backend: str = "openai", ollama_base_url: str = "http://localhost:11434"):
"""
Initialize the improved tester
Args:
chunk_size: Target number of turns per chunk (default 4)
use_episodes: If True, use episode/session-level retrieval
memory_level: 'session' for session-level or 'message' for message-level memory
"""
self.model = model
self.embedding_model = embedding_model
self.chunk_size = chunk_size
self.use_episodes = use_episodes
self.memory_level = memory_level
self.backend = backend
self.ollama_base_url = ollama_base_url
# Initialize LLM controller
api_key = os.getenv('OPENAI_API_KEY') if backend == 'openai' else None
if backend == 'openai' and not api_key:
raise ValueError("OPENAI_API_KEY not found in environment")
self.llm_controller = LLMController(
backend=self.backend,
model=self.model,
api_key=api_key,
ollama_base_url=self.ollama_base_url
)
# Initialize evaluator
self.evaluator = LongMemEvalEvaluator(model=model)
# Initialize answer formatter
self.answer_formatter = AnswerFormatter()
def _extract_facts_from_text(self, text: str) -> dict:
"""Extract facts from a single text message"""
import re
facts = {
'education': [],
'work': [],
'locations': [],
'family': [],
'activities': [],
'purchases': [],
'times': [],
'names': [],
'preferences': [],
'gifts': []
}
text_lower = text.lower()
if any(word in text_lower for word in ['graduated', 'degree', 'university', 'college', 'studied']):
education_matches = re.findall(r'(?:bachelor|master|phd|degree).*?(?:in|of)\s+([^.,]+)', text_lower)
facts['education'].extend(education_matches[:2])
if any(word in text_lower for word in ['work', 'commute', 'job', 'position']):
work_matches = re.findall(r'work(?:s|ed|ing)?\s+(?:at|for|with)\s+([^.,]{3,30})', text_lower)
facts['work'].extend(work_matches[:2])
location_matches = re.findall(r'(?:at|in)\s+([A-Z][^.,]{2,20})', text, re.IGNORECASE)
facts['locations'].extend(location_matches[:2])
name_matches = re.findall(r'\b([A-Z][a-z]+)\b', text)
facts['names'].extend(name_matches[:3])
time_matches = re.findall(r'(\d+\s+(?:hours?|days?|minutes?))', text_lower)
facts['times'].extend(time_matches[:2])
for key in facts:
facts[key] = list(set([f.strip() for f in facts[key] if f and len(f.strip()) > 2]))[:3]
return facts
def extract_user_facts(self, user_messages: list) -> dict:
"""
Extract specific facts from user messages that are commonly asked in questions.
CRITICAL for reaching 80% accuracy.
"""
import re
facts = {
'education': [],
'work': [],
'locations': [],
'family': [],
'activities': [],
'purchases': [],
'times': [],
'names': [],
'preferences': [],
'gifts': []
}
all_text = ' '.join(user_messages).lower()
education_patterns = [
r'graduated.*?(?:with|from)\s+([^.,]+)',
r'(?:bachelor|master|phd|degree).*?(?:in|of)\s+([^.,]+)',
r'studied\s+(?:at\s+)?([^.,]+)',
r'(?:university|college)\s+of\s+([^.,]+)',
r'ucla|stanford|harvard|mit|berkeley|([a-z]+\s+university)',
]
for pattern in education_patterns:
matches = re.findall(pattern, all_text, re.IGNORECASE)
facts['education'].extend(matches)
work_patterns = [
r'commute.*?(\d+\s+(?:minutes|hours)[^.,]*)',
r'(\d+\s+(?:minutes|hours)).*?(?:each way|one way|round trip)',
r'stop.*?(?:work|email|checking).*?(\d+\s*(?:am|pm|o\'clock))',
r'work(?:s|ed|ing)?\s+(?:at|for|with)\s+([^.,]{3,30})',
r'(?:my|the)\s+(?:job|position|role).*?(?:at|with|in)\s+([^.,]{3,30})',
]
for pattern in work_patterns:
matches = re.findall(pattern, all_text, re.IGNORECASE)
facts['work'].extend(matches)
location_patterns = [
r'(?:shop|shopped|shopping)\s+(?:at|in)\s+([A-Z][^.,]{2,20})',
r'(?:redeem|used?|apply).*?(?:coupon|discount).*?(?:at|in)\s+([A-Z][^.,]{2,20})',
r'(?:take|attend|go to).*?(?:yoga|gym|fitness|class\w*).*?(?:at|in)?\s*([A-Z][^.,]{2,30})',
r'(?:live|living|reside)\s+(?:in|at)\s+([^.,]{3,30})',
r'study.*?abroad.*?(?:at|in)\s+([^.,]{5,50})',
r'(?:university|college|school)\s+(?:of|at|in)\s+([^.,]{3,30})',
r'(?:went|go|visit\w*).*?(?:to|at)\s+(?:the\s+)?([A-Z][^.,]{3,30})',
]
for pattern in location_patterns:
matches = re.findall(pattern, all_text, re.IGNORECASE)
facts['locations'].extend(matches)
family_patterns = [
r'(?:my\s+)?(?:sister|brother|mother|father|cousin|aunt|uncle)(?:\'s)?\s+(?:name\s+is\s+)?([A-Z][a-z]+)',
r'([A-Z][a-z]+)\s+is\s+my\s+(?:sister|brother|mother|father|cousin)',
r'(?:last|sur|family)\s*name.*?(?:was|used to be|before)\s+([A-Z][a-z]+)',
r'changed.*?(?:name|it).*?(?:from|was)\s+([A-Z][a-z]+)',
r'(?:maiden|birth)\s*name.*?([A-Z][a-z]+)',
r'(?:my\s+)?(?:cat|dog|pet|hamster|bird)(?:\'s)?\s+(?:name\s+is\s+)?([A-Z][a-z]+)',
r'(?:bought|got|gave).*?(?:for|to)\s+(?:my\s+)?(?:sister|brother|mother).*?([^.,]{3,30})',
]
for pattern in family_patterns:
matches = re.findall(pattern, all_text, re.IGNORECASE)
facts['family'].extend(matches)
time_patterns = [
r'(january|february|march|april|may|june|july|august|september|october|november|december)\s+\d+',
r'(\d+\s+hours)',
r'(\d+\s+days)',
r'(last\s+(?:sunday|monday|tuesday|wednesday|thursday|friday|saturday))',
]
for pattern in time_patterns:
matches = re.findall(pattern, all_text, re.IGNORECASE)
facts['times'].extend(matches)
gift_patterns = [
r'(?:bought|got|gave).*?(?:gift|birthday|present).*?([^.,]+)',
r'birthday.*?(?:gift|present).*?([^.,]+)',
r'(?:yellow|blue|red|green)\s+(?:dress|shirt|sweater)',
r'sister.*?(?:gift|birthday).*?([^.,]+)',
r'(?:gift|present).*?(?:was|is)\s+([^.,]+)',
]
for pattern in gift_patterns:
matches = re.findall(pattern, all_text, re.IGNORECASE)
facts['gifts'].extend(matches)
for key in facts:
facts[key] = list(set([f.strip() for f in facts[key] if f and len(f.strip()) > 2]))[:5]
return facts
def create_comprehensive_session_summary(self, messages: list) -> str:
"""
Create a COMPREHENSIVE summary that captures ALL important topics and details.
This is CRITICAL for good retrieval - OPTIMIZED FOR 80% ACCURACY.
"""
full_text = []
user_messages = []
assistant_messages = []
for msg in messages:
if hasattr(msg, 'role') and hasattr(msg, 'content'):
role = msg.role
content = msg.content[:1000]
if role == "user":
user_messages.append(content)
full_text.append(f"User mentioned: {content}")
else:
assistant_messages.append(content)
full_text.append(f"Assistant said: {content}")
combined_text = "\n".join(full_text)
extracted_facts = self.extract_user_facts(user_messages)
all_topics = set()
text_lower = combined_text.lower()
topic_patterns = [
("language learning", ["spanish", "french", "italian", "german", "chinese", "japanese",
"language", "practice", "fluent", "speaking", "conversation"]),
("cultural events", ["cultural", "festival", "event", "celebration", "exhibit", "museum",
"art", "music", "performance", "show", "concert"]),
("miami travel", ["miami", "florida", "south beach", "hotels", "ocean view"]),
("hawaii travel", ["hawaii", "honolulu", "maui", "beach", "island"]),
("seattle travel", ["seattle", "washington", "puget sound", "skyline"]),
("ai research", ["artificial intelligence", "ai", "machine learning", "deep learning",
"neural", "research", "paper", "conference", "healthcare"]),
("video editing", ["video", "editing", "premiere", "adobe", "after effects", "final cut"]),
("photography", ["camera", "photo", "sony", "canon", "nikon", "lens", "shoot"]),
("vegetarian cooking", ["vegetarian", "vegan", "plant-based", "chickpea", "salad"]),
("nigerian cuisine", ["nigerian", "african", "akara", "jollof", "plantain"]),
("meal prep", ["meal prep", "healthy", "cooking", "recipe", "ingredients"]),
("fitness", ["exercise", "gym", "workout", "yoga", "running", "health"]),
("reading", ["book", "reading", "novel", "author", "literature"]),
("movies", ["movie", "film", "watch", "show", "documentary"])
]
for topic_name, keywords in topic_patterns:
if any(kw in text_lower for kw in keywords):
all_topics.add(topic_name)
for kw in keywords:
if kw in text_lower:
all_topics.add(kw)
questions_asked = []
for user_msg in user_messages[:5]:
if '?' in user_msg:
questions_asked.append(user_msg[:150])
preferences = []
preference_patterns = [
r"(?:prefer|like|enjoy|want|interested in|looking for)\s+([^.,!?]+)",
r"recommend(?:ed|ing|ation)?\s+([^.,!?]+)",
r"suggest(?:ed|ing|ion)?\s+([^.,!?]+)"
]
for pattern in preference_patterns:
matches = re.findall(pattern, text_lower, re.IGNORECASE)
for match in matches[:3]:
if len(match) > 10:
preferences.append(match[:100])
if hasattr(self, 'llm_controller'):
try:
prompt = f"""Create an EXTREMELY COMPREHENSIVE summary of this conversation.
CRITICAL: Include EVERY important detail:
- ALL topics discussed (travel destinations, languages, food, technology, etc.)
- EVERY specific brand, product, location, or name mentioned
- ALL questions the user asked
- EVERY preference or interest expressed
- Any recommendations or suggestions made
- Specific details like dates, prices, features
Conversation (sample):
{combined_text[:2000]}
Topics detected: {', '.join(list(all_topics)[:20])}
User questions: {'; '.join(questions_asked[:3])}
COMPREHENSIVE SUMMARY (include EVERYTHING important):"""
summary = self.llm_controller.llm.get_completion(prompt, response_format={"type": "text"})
topic_prefix = f"TOPICS: {', '.join(list(all_topics)[:15])} | "
if questions_asked:
topic_prefix += f"QUESTIONS: {questions_asked[0][:100]} | "
return topic_prefix + summary.strip()
except Exception as e:
logger.warning(f"LLM summary failed: {e}")
summary_parts = []
if extracted_facts:
fact_strings = []
for category, items in extracted_facts.items():
if items:
fact_strings.append(f"{category.upper()}: {', '.join(items)}")
if fact_strings:
summary_parts.append("FACTS: " + " | ".join(fact_strings))
if all_topics:
summary_parts.append(f"TOPICS: {', '.join(list(all_topics)[:20])}")
if questions_asked:
summary_parts.append(f"QUESTIONS: {' | '.join(questions_asked[:5])}")
if preferences:
summary_parts.append(f"PREFERENCES: {' | '.join(preferences[:5])}")
summary_parts.append(f"CONVERSATION: {combined_text[:1500]}")
return " | ".join(summary_parts)
def create_multi_perspective_embeddings(self, session_text: str, session_summary: str) -> list:
"""
Create multiple embeddings from different perspectives for better retrieval.
Returns a list of embeddings to try.
"""
embeddings = []
embeddings.append(('summary', session_summary[:1500]))
questions = re.findall(r'[^.!?]*\?', session_text)[:5]
if questions:
questions_text = "Questions discussed: " + " | ".join(questions)
embeddings.append(('questions', questions_text[:1000]))
topics_match = re.search(r'TOPICS: ([^|]+)', session_summary)
if topics_match:
topics_text = f"Topics: {topics_match.group(1)}"
embeddings.append(('topics', topics_text))
first_user = re.search(r'User asked: ([^\\n]+)', session_text)
if first_user:
embeddings.append(('first_user', f"User focus: {first_user.group(1)[:500]}"))
return embeddings
def build_memory_message_level(self, question: LongMemQuestion, rebuild: bool = False) -> tuple:
"""Build proper TRG memory from individual messages using TRG's add_event method"""
# Use a hash of all sessions to create a consistent cache key
import hashlib
sessions_str = str([(s.session_id, len(s.messages)) for s in question.haystack_sessions])
cache_key = hashlib.md5(sessions_str.encode()).hexdigest()[:16]
cache_dir = f"./locomo_message_cache/cache_{cache_key}"
# Check cache
if not rebuild and os.path.exists(cache_dir):
print(f"Loading message-level memory from cache: {cache_dir}")
# Load the TRG memory from cache files
try:
from memory.trg_memory import TemporalResonanceGraphMemory
# Create a new TRG instance
trg = TemporalResonanceGraphMemory(
persist_dir=cache_dir,
embedding_model=self.embedding_model,
llm_backend=self.backend,
llm_model=self.model,
ollama_base_url=self.ollama_base_url
)
# Load the saved state
trg.load(cache_dir)
# Load the node index
import json
with open(os.path.join(cache_dir, "node_index.json"), 'r') as f:
node_index = json.load(f)
# Convert lists back to sets for efficient lookup
node_index = {k: set(v) if isinstance(v, list) else v
for k, v in node_index.items()}
query_engine = QueryEngine(trg, node_index)
node_count = len(trg.graph_db.nodes) if hasattr(trg.graph_db, 'nodes') else 0
print(f"Loaded memory with {node_count} nodes from cache")
return trg, query_engine
except Exception as e:
print(f"Failed to load cache: {e}, rebuilding...")
# Build fresh memory from messages using proper TRG
print(f"Building message-level TRG memory (cache: {cache_dir})")
# Initialize MemoryBuilder for proper TRG construction
from memory.memory_builder import MemoryBuilder
builder = MemoryBuilder(
cache_dir=cache_dir,
llm_model=self.model,
use_episodes=False, # Process individual messages
embedding_model=self.embedding_model
)
# Count total messages
total_messages = sum(len(session.messages) for session in question.haystack_sessions)
print(f"Processing {total_messages} individual messages with proper TRG...")
message_counter = 0
# Process each message individually using TRG's add_event
for s_idx, session in enumerate(question.haystack_sessions):
# Parse session date
try:
session_date = datetime.strptime(session.date, '%Y/%m/%d (%a) %H:%M')
except:
session_date = datetime.now()
for m_idx, msg in enumerate(session.messages):
message_counter += 1
print(f"\rProcessing message {message_counter}/{total_messages} with TRG", end='')
# Prepare message content with role prefix
role_prefix = "User: " if msg.role == 'user' else "Assistant: "
message_content = f"{role_prefix}{msg.content}"
# Calculate timestamp for this message (add minutes based on message index)
msg_timestamp = session_date + timedelta(minutes=m_idx * 5)
# Use TRG's add_event method which does proper:
# - Event extraction with LLM
# - Embedding generation
# - Link creation (temporal, semantic, causal)
# - Keyword indexing
try:
event_id = builder.trg.add_event(
interaction_content=message_content,
timestamp=msg_timestamp,
metadata={
'role': msg.role,
'session_id': s_idx,
'message_index': m_idx,
'session_date': session.date,
'original_content': msg.content
}
)
# Index the event for search (adds keywords to the index)
builder.index_event(event_id, message_content, metadata={
'entities': [], # Will be extracted by TRG
'topic': msg.role
})
except Exception as e:
logger.warning(f"Failed to add event for message {m_idx} in session {s_idx}: {e}")
continue
# Count the nodes created
node_count = len(builder.trg.graph_db.nodes) if hasattr(builder.trg.graph_db, 'nodes') else 0
print(f"\n✓ Message-level TRG memory building complete: {node_count} events created")
# TRG automatically creates temporal links during add_event
# We can optionally create additional semantic links
print("Analyzing semantic connections...")
# The create_semantic_links method doesn't exist, but TRG creates them during add_event
# Save the properly built TRG memory using TRG's save method
os.makedirs(cache_dir, exist_ok=True)
# Save TRG using its built-in persistence
builder.trg.save(cache_dir)
# Save the node index separately
import json
with open(os.path.join(cache_dir, "node_index.json"), 'w') as f:
# Convert sets to lists for JSON serialization
serializable_index = {k: list(v) if isinstance(v, set) else v
for k, v in builder.node_index.items()}
json.dump(serializable_index, f)
print(f"Saved message-level TRG memory to {cache_dir}")
# Create query engine with the keyword index
query_engine = QueryEngine(builder.trg, builder.node_index)
return builder.trg, query_engine
def build_memory_for_question_improved(self, question: LongMemQuestion, rebuild: bool = False) -> tuple:
"""
Build memory with improved retrieval strategy
"""
from sentence_transformers import SentenceTransformer
import hashlib
import pickle
# Create cache key
sessions_text = "".join([
f"{s.date}:{len(s.messages)}"
for s in question.haystack_sessions
])
cache_key = hashlib.md5(sessions_text.encode()).hexdigest()[:8]
cache_dir = f"./longmem_improved_cache/{cache_key}"
# Check cache
if not rebuild and os.path.exists(cache_dir):
print(f"Loading cached memory from {cache_dir}")
with open(f"{cache_dir}/graph.pkl", 'rb') as f:
graph_db = pickle.load(f)
with open(f"{cache_dir}/vectors.pkl", 'rb') as f:
vector_db = pickle.load(f)
with open(f"{cache_dir}/metadata.json", 'r') as f:
metadata = json.load(f)
trg = TemporalResonanceGraphMemory(graph_db, vector_db, embedding_model=self.embedding_model, llm_backend=self.backend, llm_model=self.model, ollama_base_url=self.ollama_base_url)
# Restore nodes
from memory.graph_db import NodeType
all_episode_nodes = []
for node_id in graph_db.nodes.keys():
node = graph_db.get_node(node_id)
if node.node_type == NodeType.EPISODE:
all_episode_nodes.append(node)
trg.episode_nodes = all_episode_nodes
trg.session_metadata = metadata.get('session_metadata', [])
trg.session_index = metadata.get('session_index', {}) # Add session index
query_engine = QueryEngine(trg, metadata['node_index'])
print(f"Loaded {len(all_episode_nodes)} sessions from cache")
return trg, query_engine
# Build fresh memory
print(f"Building improved memory (cache: {cache_dir})")
total_sessions = len(question.haystack_sessions)
print(f"Processing {total_sessions} sessions")
# Initialize TRG
embedding_dim = 384 if self.embedding_model == "minilm" else 1536
graph_db = NetworkXGraphDB()
vector_db = NumpyVectorDB(dimension=embedding_dim)
trg = TemporalResonanceGraphMemory(graph_db, vector_db, embedding_model=self.embedding_model, llm_backend=self.backend, llm_model=self.model, ollama_base_url=self.ollama_base_url)
# Load encoder
from sentence_transformers import SentenceTransformer
encoder = SentenceTransformer('all-MiniLM-L6-v2') if self.embedding_model == "minilm" else None
node_index = defaultdict(list)
session_metadata = []
all_episode_nodes = []
session_index = {} # Map session_id to node_id for quick lookup
# Process each session
for s_idx, session in enumerate(question.haystack_sessions):
print(f"\rProcessing session {s_idx+1}/{total_sessions}", end='')
# Parse date
try:
session_date = datetime.strptime(session.date, '%Y/%m/%d (%a) %H:%M')
except:
session_date = datetime.now()
# Combine session messages
session_text = ""
for msg in session.messages:
role_prefix = "User: " if msg.role == 'user' else "Assistant: "
session_text += f"{role_prefix}{msg.content}\n\n"
# Create COMPREHENSIVE summary
print(f"\r Creating comprehensive summary for session {s_idx+1}/{total_sessions}...", end='')
session_summary = self.create_comprehensive_session_summary(session.messages)
# Extract keywords from summary for indexing (BEFORE using them in embeddings)
keywords = set(self._extract_comprehensive_keywords(session_summary))
# Create MULTIPLE embeddings for better retrieval (inspired by LoCoMo)
embeddings_to_add = []
if self.embedding_model == "minilm":
# Primary embedding from summary
embedding = encoder.encode(session_summary[:1500])
embeddings_to_add.append((f"summary_{s_idx}", embedding))
# Additional embeddings for key aspects
# 1. First user message (often contains the main topic)
if session.messages and session.messages[0].role == 'user':
first_msg_embedding = encoder.encode(session.messages[0].content[:500])
embeddings_to_add.append((f"first_msg_{s_idx}", first_msg_embedding))
# 2. Keywords-focused embedding
if keywords:
keywords_text = " ".join(list(keywords)[:20])
keywords_embedding = encoder.encode(keywords_text)
embeddings_to_add.append((f"keywords_{s_idx}", keywords_embedding))
else:
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
model="text-embedding-3-small",
input=session_summary[:8000]
)
embedding = response.data[0].embedding
embeddings_to_add.append((f"summary_{s_idx}", embedding))
# Also extract keywords from first user message (often contains key facts)
if session.messages and session.messages[0].role == 'user':
first_msg_keywords = self._extract_comprehensive_keywords(session.messages[0].content[:500])
keywords.update(first_msg_keywords) # This works because keywords is now a set
# Create episode node
episode_node_id = str(uuid.uuid4())
episode_node = EpisodeNode(
node_id=episode_node_id,
start_timestamp=session_date,
end_timestamp=session_date,
summary=session_summary, # Comprehensive summary
title=f"Session {s_idx+1}",
event_count=len(session.messages),
attributes={
'content': session_text[:10000], # Store more content
'session_id': session.session_id if hasattr(session, 'session_id') else str(s_idx),
'session_index': s_idx,
'turn_count': len(session.messages),
'keywords': keywords,
'full_text_length': len(session_text),
# Store first few messages for quick access
'first_messages': session_text[:2000]
},
embedding_vector=embedding
)
# Add to graph
graph_db.add_node(episode_node)
# Add MULTIPLE embeddings for better retrieval (LoCoMo optimization)
for emb_id, emb_vector in embeddings_to_add:
# Use composite ID for multiple embeddings of same node
composite_id = f"{episode_node_id}_{emb_id}"
vector_db.add_vector(composite_id, emb_vector)
# Also add primary embedding with original ID for compatibility
vector_db.add_vector(episode_node_id, embedding)
all_episode_nodes.append(episode_node)
# Update session index
session_id = session.session_id if hasattr(session, 'session_id') else str(s_idx)
session_index[session_id] = episode_node_id
# Index keywords (more comprehensive)
for kw in keywords:
node_index[kw.lower()].append(episode_node_id)
# Also index topic words from summary
topic_words = re.findall(r'\b[a-zA-Z]{4,}\b', session_summary.lower())
for word in set(topic_words[:50]): # Index top 50 unique words
if word not in ['that', 'this', 'with', 'from', 'have', 'been', 'were', 'they']:
node_index[word].append(episode_node_id)
# Store metadata
session_metadata.append({
'session_id': session_id,
'node_id': episode_node_id,
'date': session_date.isoformat() if hasattr(session_date, 'isoformat') else str(session_date),
'summary': session_summary[:500],
'keyword_sample': list(keywords)[:20]
})
print(f"\n✓ Memory building complete: {len(all_episode_nodes)} sessions processed")
# Store in TRG
trg.session_metadata = session_metadata
trg.episode_nodes = all_episode_nodes
trg.session_index = session_index # Add quick lookup index
# Create query engine
query_engine = QueryEngine(trg, dict(node_index))
# Save cache
os.makedirs(cache_dir, exist_ok=True)
with open(f"{cache_dir}/graph.pkl", 'wb') as f:
pickle.dump(graph_db, f)
with open(f"{cache_dir}/vectors.pkl", 'wb') as f:
pickle.dump(vector_db, f)
with open(f"{cache_dir}/metadata.json", 'w') as f:
json.dump({
'node_index': dict(node_index),
'session_count': len(all_episode_nodes),
'session_metadata': session_metadata,
'session_index': session_index
}, f, indent=2, default=str)
print(f"Saved improved memory cache to {cache_dir}")
return trg, query_engine
def _extract_comprehensive_keywords(self, text: str) -> list:
"""Extract comprehensive keywords including multi-word phrases"""
keywords = set()
words = re.findall(r'\b[a-zA-Z]{3,}\b', text.lower())
stop_words = {'the', 'and', 'for', 'that', 'this', 'with', 'from', 'have', 'been'}
keywords.update([w for w in words[:100] if w not in stop_words])
phrase_patterns = [
r'(spanish|french|italian|german) language',
r'cultural event\w*',
r'language practice',
r'(miami|hawaii|seattle) hotel\w*',
r'artificial intelligence',
r'video editing',
r'adobe premiere',
r'vegetarian recipe\w*',
r'meal prep'
]
for pattern in phrase_patterns:
matches = re.findall(pattern, text.lower())
keywords.update(matches)
return list(keywords)[:150]
def extract_all_countable_items(self, session_content: str, question: str) -> str:
"""
Extract ALL countable items from a session for multi-session counting questions.
This ensures we don't miss any items that should be counted.
"""
q_lower = question.lower()
lines = session_content.split('\n')
relevant_lines = []
count_keywords = []
action_words = []
if 'clothing' in q_lower or 'clothes' in q_lower:
count_keywords = ['shirt', 'pants', 'dress', 'jacket', 'coat', 'sweater', 'jeans',
'blouse', 'skirt', 'suit', 'tie', 'clothes', 'clothing', 'outfit']
action_words = ['pick up', 'return', 'retrieve', 'collect', 'drop off', 'get']
elif 'project' in q_lower:
count_keywords = ['project', 'initiative', 'program', 'development', 'implementation']
action_words = ['led', 'lead', 'leading', 'manage', 'direct', 'oversee', 'head', 'in charge']
elif 'model' in q_lower and 'kit' in q_lower:
count_keywords = ['model', 'kit', 'scale', 'build', 'assemble', 'plane', 'car', 'tank',
'ship', 'aircraft', 'vehicle', 'miniature']
action_words = ['bought', 'purchased', 'worked on', 'built', 'assembled', 'completed']
elif 'fitness' in q_lower or 'class' in q_lower:
count_keywords = ['class', 'session', 'workout', 'fitness', 'exercise', 'yoga', 'pilates',
'spin', 'zumba', 'training', 'gym']
action_words = ['attend', 'go to', 'participate', 'join', 'take']
elif 'money' in q_lower or 'raise' in q_lower or 'spent' in q_lower or 'expense' in q_lower:
count_keywords = ['$', 'dollar', 'money', 'amount', 'raise', 'donation', 'fund',
'cost', 'price', 'paid', 'expense', 'fee', 'charge']
action_words = ['raise', 'raised', 'donate', 'donated', 'collect', 'gathered', 'spent',
'paid', 'cost', 'bought', 'purchased', 'expense']
elif 'bike' in q_lower:
count_keywords = ['bike', 'bicycle', 'cycle', 'repair', 'service', 'maintenance',
'tire', 'chain', 'brake', 'gear', 'helmet', 'lock', 'light']
if 'expense' in q_lower or 'spent' in q_lower or 'money' in q_lower:
count_keywords.extend(['$', 'dollar', 'cost', 'price', 'paid', 'expense'])
action_words = ['service', 'serviced', 'repair', 'fixed', 'maintain', 'tune',
'bought', 'purchased', 'spent', 'paid', 'cost']
elif 'camping' in q_lower or 'camp' in q_lower:
count_keywords = ['camping', 'camp', 'campsite', 'tent', 'outdoor', 'wilderness',
'park', 'days', 'night', 'trip']
action_words = ['spent', 'stayed', 'camped', 'went', 'visited']
elif 'driving' in q_lower or 'road trip' in q_lower:
count_keywords = ['drive', 'driving', 'drove', 'hours', 'road', 'trip', 'destination',
'miles', 'journey', 'travel']
action_words = ['drove', 'driving', 'traveled', 'spent', 'took']
elif 'jewelry' in q_lower:
count_keywords = ['jewelry', 'necklace', 'ring', 'bracelet', 'earring', 'pendant',
'chain', 'jewel', 'accessory']
action_words = ['acquire', 'bought', 'received', 'got', 'purchased', 'gifted']
if not count_keywords:
words = q_lower.split()
for i, word in enumerate(words):
if word == 'many' and i+1 < len(words):
count_keywords.append(words[i+1].rstrip('s'))
elif word == 'much' and i+1 < len(words):
count_keywords.append(words[i+1])
for i, line in enumerate(lines):
line_lower = line.lower()
keyword_match = any(kw in line_lower for kw in count_keywords) if count_keywords else False
action_match = any(aw in line_lower for aw in action_words) if action_words else False
has_number = bool(re.search(r'\b\d+', line))
has_list_marker = bool(re.search(r'^[\s]*[-•*\d]+[.)]\s', line))
if keyword_match or action_match or (has_number and (keyword_match or action_match)):
relevant_lines.append(line)
if i > 0 and lines[i-1] not in relevant_lines:
relevant_lines.append(lines[i-1])
if i < len(lines) - 1 and lines[i+1] not in relevant_lines:
relevant_lines.append(lines[i+1])
elif has_list_marker and i > 0:
prev_line = lines[i-1].lower()
if any(kw in prev_line for kw in count_keywords):
relevant_lines.append(line)
if relevant_lines:
seen = set()
unique_lines = []
for line in relevant_lines:
if line not in seen:
seen.add(line)
unique_lines.append(line)
result = '\n'.join(unique_lines)
if len(result) > 4000:
priority_lines = [l for l in unique_lines if re.search(r'\b\d+', l) or
any(kw in l.lower() for kw in count_keywords)]
if priority_lines:
result = '\n'.join(priority_lines[:50])
return result
return session_content[:3000]
def extract_relevant_chunks(self, session_content: str, question: str) -> str:
"""
Extract only the relevant parts from a session that relate to the question.
This is the KEY innovation - reduce information overload by selective extraction.
"""
q_lower = question.lower()
if 'how many' in q_lower or 'count' in q_lower or 'how much' in q_lower:
count_target = None
action_context = []
if 'pick up' in q_lower or 'return' in q_lower:
action_context = ['pick up', 'return', 'collect', 'retrieve', 'drop off', 'get back', 'fetch']
elif 'led' in q_lower or 'leading' in q_lower:
action_context = ['led', 'lead', 'leading', 'in charge', 'manage', 'head', 'direct', 'oversee']
elif 'bought' in q_lower or 'purchased' in q_lower:
action_context = ['bought', 'purchased', 'buy', 'paid for', 'acquired', 'got new']
elif 'acquire' in q_lower:
action_context = ['acquired', 'got', 'received', 'bought', 'obtained', 'added', 'new']
elif 'visit' in q_lower:
action_context = ['visit', 'visited', 'saw', 'went to', 'appointment with']
patterns = [
r'how many (\w+)',
r'count.*?(\w+)',
r'number of (\w+)'
]
for pattern in patterns:
match = re.search(pattern, q_lower)
if match:
count_target = match.group(1)
break
if not count_target:
return session_content[:1500]
lines = session_content.split('\n')
relevant_indices = set()
if count_target:
target_terms = [count_target.lower()]
target_terms.extend(self.get_related_terms(count_target))
for i, line in enumerate(lines):
line_lower = line.lower()
if any(term in line_lower for term in target_terms):
relevant_indices.add(i)
if i > 0:
relevant_indices.add(i - 1)
if i < len(lines) - 1:
relevant_indices.add(i + 1)
if action_context:
for i, line in enumerate(lines):
line_lower = line.lower()
if any(action in line_lower for action in action_context):
relevant_indices.add(i)
if i > 0:
relevant_indices.add(i - 1)
if i < len(lines) - 1:
relevant_indices.add(i + 1)
for i, line in enumerate(lines):
if re.search(r'\b\d+\.?\d*\b', line) or re.search(r'\b(one|two|three|four|five|six|seven|eight|nine|ten)\b', line.lower()):
for j in range(max(0, i-2), min(len(lines), i+3)):
if j in relevant_indices:
relevant_indices.add(i)
break
if relevant_indices:
sorted_indices = sorted(relevant_indices)
relevant_lines = []
for i in sorted_indices:
if i < len(lines):
relevant_lines.append(lines[i][:400])
return '\n'.join(relevant_lines[:30])
else:
return session_content[:2000]
elif 'what time' in q_lower or 'when' in q_lower:
lines = session_content.split('\n')
relevant_lines = []
time_keywords = ['AM', 'PM', 'morning', 'evening', 'night', 'afternoon',
'monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'saturday', 'sunday', 'o\'clock']
for line in lines:
if any(kw in line.lower() for kw in [w.lower() for w in time_keywords]):
relevant_lines.append(line[:200])
if relevant_lines:
return '\n'.join(relevant_lines[:10])
else:
return session_content[:1500]
elif 'how much' in q_lower and ('money' in q_lower or 'spent' in q_lower or 'cost' in q_lower):
lines = session_content.split('\n')
relevant_lines = []
for line in lines:
if '$' in line or any(word in line.lower() for word in ['cost', 'spent', 'price', 'dollar', 'paid', 'expense']):
relevant_lines.append(line[:200])
if relevant_lines:
return '\n'.join(relevant_lines[:15])
else:
return session_content[:1500]
if len(session_content) > 2000:
try:
extract_prompt = f"""Extract ONLY the parts of this conversation that are relevant to answering the question.
Question: {question}
Conversation:
{session_content[:3000]}
Return ONLY the relevant excerpts (sentences or exchanges) that help answer the question. Be selective:"""
relevant = self.llm_controller.llm.get_completion(extract_prompt, response_format={"type": "text"})
return relevant
except:
pass
return session_content[:1500]
def get_related_terms(self, term: str) -> list:
"""Get related terms for better extraction"""
related = {
'items': ['thing', 'object', 'piece', 'article'],
'clothing': ['clothes', 'shirt', 'pants', 'dress', 'jacket', 'shoe'],
'doctor': ['physician', 'dr.', 'medical', 'appointment', 'specialist'],
'project': ['work', 'task', 'assignment', 'initiative'],
'plant': ['flower', 'succulent', 'herb', 'garden'],
'model': ['kit', 'scale', 'build', 'assemble'],
'book': ['novel', 'read', 'author', 'title'],
'movie': ['film', 'watch', 'cinema', 'show'],
}
term_lower = term.lower()
for key, values in related.items():
if key in term_lower or term_lower in key:
return values
return []
def _clean_json_answer(self, answer):
"""Extract the actual answer from JSON or other formats"""
import json
import re