forked from MemPalace/mempalace
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongmemeval_bench.py
More file actions
3383 lines (2982 loc) · 116 KB
/
Copy pathlongmemeval_bench.py
File metadata and controls
3383 lines (2982 loc) · 116 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
"""
MemPal × LongMemEval Benchmark
================================
Evaluates MemPal's retrieval against the LongMemEval benchmark.
No modifications to LongMemEval's code required.
For each of the 500 questions:
1. Ingest all haystack sessions into a fresh MemPal palace
2. Query the palace with the question
3. Score retrieval against ground-truth answer sessions
Outputs:
- Recall@k and NDCG@k at session and turn level
- Per-question-type breakdown
- JSONL log compatible with LongMemEval's evaluation scripts
Modes:
raw — baseline: raw text into ChromaDB (default)
aaak — AAAK dialect compression before ingestion
rooms — topic-based room detection + room-filtered search
Usage:
python benchmarks/longmemeval_bench.py data/longmemeval_s_cleaned.json
python benchmarks/longmemeval_bench.py data/longmemeval_s_cleaned.json --mode aaak
python benchmarks/longmemeval_bench.py data/longmemeval_s_cleaned.json --mode rooms
python benchmarks/longmemeval_bench.py data/longmemeval_s_cleaned.json --granularity turn
python benchmarks/longmemeval_bench.py data/longmemeval_s_cleaned.json --limit 20
"""
import os
import sys
import re
import json
import argparse
import math
from pathlib import Path
from collections import defaultdict
from datetime import datetime
import chromadb
# Add mempal to path
sys.path.insert(0, str(Path(__file__).parent.parent))
# =============================================================================
# METRICS (reimplemented to avoid LongMemEval dependency)
# =============================================================================
def dcg(relevances, k):
"""Discounted Cumulative Gain."""
score = 0.0
for i, rel in enumerate(relevances[:k]):
score += rel / math.log2(i + 2)
return score
def ndcg(rankings, correct_ids, corpus_ids, k):
"""Normalized DCG."""
relevances = [1.0 if corpus_ids[idx] in correct_ids else 0.0 for idx in rankings[:k]]
ideal = sorted(relevances, reverse=True)
idcg = dcg(ideal, k)
if idcg == 0:
return 0.0
return dcg(relevances, k) / idcg
def evaluate_retrieval(rankings, correct_ids, corpus_ids, k):
"""
Evaluate retrieval at rank k.
Returns (recall_any, recall_all, ndcg_score).
"""
top_k_ids = set(corpus_ids[idx] for idx in rankings[:k])
recall_any = float(any(cid in top_k_ids for cid in correct_ids))
recall_all = float(all(cid in top_k_ids for cid in correct_ids))
ndcg_score = ndcg(rankings, correct_ids, corpus_ids, k)
return recall_any, recall_all, ndcg_score
def session_id_from_corpus_id(corpus_id):
"""Extract session ID from a corpus ID (handles both session and turn granularity)."""
# Turn IDs look like "sess_123_turn_4" — session part is "sess_123"
if "_turn_" in corpus_id:
return corpus_id.rsplit("_turn_", 1)[0]
return corpus_id
# =============================================================================
# SHARED EPHEMERAL CLIENT
# EphemeralClient instances share state in this ChromaDB version — use one
# shared client and delete+recreate the collection between queries.
# =============================================================================
_bench_client = chromadb.EphemeralClient()
# Global embedding function — set by --embed-model arg before benchmark runs.
# None = use ChromaDB default (all-MiniLM-L6-v2).
_bench_embed_fn = None
def _make_embed_fn(model_name: str):
"""
Return a ChromaDB-compatible embedding function for the given model.
Supported:
default — ChromaDB default (all-MiniLM-L6-v2, 384-dim)
bge-base — BAAI/bge-base-en-v1.5 (768-dim) via fastembed
bge-large — BAAI/bge-large-en-v1.5 (1024-dim) via fastembed
nomic — nomic-ai/nomic-embed-text-v1.5 (768-dim) via fastembed
mxbai — mixedbread-ai/mxbai-embed-large-v1 (1024-dim) via fastembed
"""
if model_name == "default" or not model_name:
return None # ChromaDB default
MODEL_MAP = {
"bge-base": "BAAI/bge-base-en-v1.5",
"bge-large": "BAAI/bge-large-en-v1.5",
"nomic": "nomic-ai/nomic-embed-text-v1.5",
"mxbai": "mixedbread-ai/mxbai-embed-large-v1",
}
hf_name = MODEL_MAP.get(model_name, model_name)
try:
from fastembed import TextEmbedding
from chromadb.api.types import EmbeddingFunction, Documents, Embeddings
class _FastEmbedFn(EmbeddingFunction):
def __init__(self, name):
print(f" Loading embedding model: {name} (first run downloads ~300-1300MB)...")
self._model = TextEmbedding(name)
print(" Model ready.")
def __call__(self, input: Documents) -> Embeddings:
return [list(vec) for vec in self._model.embed(input)]
return _FastEmbedFn(hf_name)
except ImportError:
print("ERROR: fastembed not installed. Run: pip install fastembed")
print(" Falling back to default embedding model.")
return None
def _fresh_collection(name="mempal_drawers"):
"""Delete and recreate collection for a clean slate between queries."""
global _bench_embed_fn
try:
_bench_client.delete_collection(name)
except Exception:
pass
if _bench_embed_fn is not None:
return _bench_client.create_collection(name, embedding_function=_bench_embed_fn)
return _bench_client.create_collection(name)
# =============================================================================
# MEMPAL RETRIEVER
# =============================================================================
def build_palace_and_retrieve(entry, granularity="session", n_results=50):
"""
Build a fresh MemPal palace from haystack sessions, then retrieve.
Args:
entry: One LongMemEval question entry
granularity: "session" (one doc per session) or "turn" (one doc per user turn)
n_results: How many results to return
Returns:
rankings: numpy-style list of indices into corpus (descending relevance)
corpus: list of document strings
corpus_ids: list of document IDs
corpus_timestamps: list of timestamps
"""
# Build corpus from haystack
corpus = []
corpus_ids = []
corpus_timestamps = []
sessions = entry["haystack_sessions"]
session_ids = entry["haystack_session_ids"]
dates = entry["haystack_dates"]
for sess_idx, (session, sess_id, date) in enumerate(zip(sessions, session_ids, dates)):
if granularity == "session":
# One document per session: join all user content
user_turns = [t["content"] for t in session if t["role"] == "user"]
if user_turns:
doc = "\n".join(user_turns)
corpus.append(doc)
corpus_ids.append(sess_id)
corpus_timestamps.append(date)
else:
# One document per user turn
turn_num = 0
for turn in session:
if turn["role"] == "user":
corpus.append(turn["content"])
corpus_ids.append(f"{sess_id}_turn_{turn_num}")
corpus_timestamps.append(date)
turn_num += 1
if not corpus:
return [], corpus, corpus_ids, corpus_timestamps
collection = _fresh_collection()
# Add all corpus documents
collection.add(
documents=corpus,
ids=[f"doc_{i}" for i in range(len(corpus))],
metadatas=[
{"corpus_id": cid, "timestamp": ts} for cid, ts in zip(corpus_ids, corpus_timestamps)
],
)
# Query
query = entry["question"]
results = collection.query(
query_texts=[query],
n_results=min(n_results, len(corpus)),
include=["distances", "metadatas"],
)
# Map results back to corpus indices
result_ids = results["ids"][0]
# Build rankings: indices into corpus sorted by relevance (lowest distance = most relevant)
doc_id_to_idx = {f"doc_{i}": i for i in range(len(corpus))}
ranked_indices = [doc_id_to_idx[rid] for rid in result_ids]
# Fill in any missing indices (ChromaDB may return fewer than corpus size)
seen = set(ranked_indices)
for i in range(len(corpus)):
if i not in seen:
ranked_indices.append(i)
return ranked_indices, corpus, corpus_ids, corpus_timestamps
def build_palace_and_retrieve_aaak(entry, granularity="session", n_results=50):
"""
AAAK mode: compress each session/turn with AAAK dialect before ingesting.
Query still uses raw question text — tests whether compressed representations
retain enough semantic signal for retrieval.
"""
from mempalace.dialect import Dialect
dialect = Dialect()
corpus = [] # original text (for output)
corpus_compressed = [] # AAAK compressed (for ingestion)
corpus_ids = []
corpus_timestamps = []
sessions = entry["haystack_sessions"]
session_ids = entry["haystack_session_ids"]
dates = entry["haystack_dates"]
for sess_idx, (session, sess_id, date) in enumerate(zip(sessions, session_ids, dates)):
if granularity == "session":
user_turns = [t["content"] for t in session if t["role"] == "user"]
if user_turns:
doc = "\n".join(user_turns)
compressed = dialect.compress(doc, metadata={"date": date})
corpus.append(doc)
corpus_compressed.append(compressed)
corpus_ids.append(sess_id)
corpus_timestamps.append(date)
else:
turn_num = 0
for turn in session:
if turn["role"] == "user":
compressed = dialect.compress(turn["content"])
corpus.append(turn["content"])
corpus_compressed.append(compressed)
corpus_ids.append(f"{sess_id}_turn_{turn_num}")
corpus_timestamps.append(date)
turn_num += 1
if not corpus:
return [], corpus, corpus_ids, corpus_timestamps
collection = _fresh_collection()
# Ingest AAAK compressed text
collection.add(
documents=corpus_compressed,
ids=[f"doc_{i}" for i in range(len(corpus_compressed))],
metadatas=[
{"corpus_id": cid, "timestamp": ts} for cid, ts in zip(corpus_ids, corpus_timestamps)
],
)
# Query with raw question (not compressed)
query = entry["question"]
results = collection.query(
query_texts=[query],
n_results=min(n_results, len(corpus)),
include=["distances", "metadatas"],
)
result_ids = results["ids"][0]
doc_id_to_idx = {f"doc_{i}": i for i in range(len(corpus))}
ranked_indices = [doc_id_to_idx[rid] for rid in result_ids]
seen = set(ranked_indices)
for i in range(len(corpus)):
if i not in seen:
ranked_indices.append(i)
return ranked_indices, corpus, corpus_ids, corpus_timestamps
# Topic keywords for room detection (same as convo_miner.py)
TOPIC_KEYWORDS = {
"technical": [
"code",
"python",
"function",
"bug",
"error",
"api",
"database",
"server",
"deploy",
"git",
"test",
"debug",
"refactor",
],
"planning": [
"plan",
"roadmap",
"milestone",
"deadline",
"priority",
"sprint",
"backlog",
"scope",
"requirement",
"spec",
],
"decisions": [
"decided",
"chose",
"picked",
"switched",
"migrated",
"replaced",
"trade-off",
"alternative",
"option",
"approach",
],
"personal": [
"family",
"friend",
"birthday",
"vacation",
"hobby",
"health",
"feeling",
"love",
"home",
"weekend",
],
"knowledge": [
"learn",
"study",
"degree",
"school",
"university",
"course",
"research",
"paper",
"book",
"reading",
],
}
def detect_room_for_text(text):
"""Score text against topic keywords, return best room."""
text_lower = text[:3000].lower()
scores = {}
for room, keywords in TOPIC_KEYWORDS.items():
score = sum(1 for kw in keywords if kw in text_lower)
if score > 0:
scores[room] = score
if scores:
return max(scores, key=scores.get)
return "general"
def build_palace_and_retrieve_rooms(entry, granularity="session", n_results=50):
"""
Room-structured mode: detect topic room per session, then do a two-pass search:
1. Detect what room the question belongs to
2. Search within that room first (boosted), then search globally
"""
corpus = []
corpus_ids = []
corpus_timestamps = []
corpus_rooms = []
sessions = entry["haystack_sessions"]
session_ids = entry["haystack_session_ids"]
dates = entry["haystack_dates"]
for sess_idx, (session, sess_id, date) in enumerate(zip(sessions, session_ids, dates)):
if granularity == "session":
user_turns = [t["content"] for t in session if t["role"] == "user"]
if user_turns:
doc = "\n".join(user_turns)
room = detect_room_for_text(doc)
corpus.append(doc)
corpus_ids.append(sess_id)
corpus_timestamps.append(date)
corpus_rooms.append(room)
else:
turn_num = 0
for turn in session:
if turn["role"] == "user":
room = detect_room_for_text(turn["content"])
corpus.append(turn["content"])
corpus_ids.append(f"{sess_id}_turn_{turn_num}")
corpus_timestamps.append(date)
corpus_rooms.append(room)
turn_num += 1
if not corpus:
return [], corpus, corpus_ids, corpus_timestamps
collection = _fresh_collection()
collection.add(
documents=corpus,
ids=[f"doc_{i}" for i in range(len(corpus))],
metadatas=[
{"corpus_id": cid, "timestamp": ts, "room": room}
for cid, ts, room in zip(corpus_ids, corpus_timestamps, corpus_rooms)
],
)
query = entry["question"]
query_room = detect_room_for_text(query)
# Global search with room-based reranking (soft boost, not hard filter)
global_results = collection.query(
query_texts=[query],
n_results=min(n_results, len(corpus)),
include=["distances", "metadatas"],
)
# Rerank: boost results in the matching room by reducing distance
doc_id_to_idx = {f"doc_{i}": i for i in range(len(corpus))}
scored = []
for rid, dist, meta in zip(
global_results["ids"][0],
global_results["distances"][0],
global_results["metadatas"][0],
):
idx = doc_id_to_idx[rid]
# Soft boost: reduce distance by 20% if room matches
boosted_dist = dist * 0.8 if meta.get("room") == query_room else dist
scored.append((idx, boosted_dist))
# Sort by boosted distance (ascending = most relevant first)
scored.sort(key=lambda x: x[1])
ranked_indices = [idx for idx, _ in scored]
# Fill remaining
seen = set(ranked_indices)
for i in range(len(corpus)):
if i not in seen:
ranked_indices.append(i)
return ranked_indices, corpus, corpus_ids, corpus_timestamps
def build_palace_and_retrieve_hybrid(
entry, granularity="session", n_results=50, hybrid_weight=0.30
):
"""
Hybrid mode: semantic search + keyword overlap re-ranking.
Two-stage approach:
1. Retrieve top-N via ChromaDB semantic search (same as raw)
2. Re-rank by fusing semantic distance with keyword overlap score
Keyword overlap catches cases where the answer keyword is very specific
("Business Administration", "stand mixer") but embedding similarity
alone doesn't push it into the top-5.
Also applies temporal recency bonus for temporal-reasoning questions.
"""
STOP_WORDS = {
"what",
"when",
"where",
"who",
"how",
"which",
"did",
"do",
"was",
"were",
"have",
"has",
"had",
"is",
"are",
"the",
"a",
"an",
"my",
"me",
"i",
"you",
"your",
"their",
"it",
"its",
"in",
"on",
"at",
"to",
"for",
"of",
"with",
"by",
"from",
"ago",
"last",
"that",
"this",
"there",
"about",
"get",
"got",
"give",
"gave",
"buy",
"bought",
"made",
"make",
}
def extract_keywords(text):
words = re.findall(r"\b[a-z]{3,}\b", text.lower())
return [w for w in words if w not in STOP_WORDS]
def keyword_overlap(query_kws, doc_text):
doc_lower = doc_text.lower()
if not query_kws:
return 0.0
hits = sum(1 for kw in query_kws if kw in doc_lower)
return hits / len(query_kws)
corpus = []
corpus_ids = []
corpus_timestamps = []
sessions = entry["haystack_sessions"]
session_ids = entry["haystack_session_ids"]
dates = entry["haystack_dates"]
for sess_idx, (session, sess_id, date) in enumerate(zip(sessions, session_ids, dates)):
if granularity == "session":
user_turns = [t["content"] for t in session if t["role"] == "user"]
if user_turns:
doc = "\n".join(user_turns)
corpus.append(doc)
corpus_ids.append(sess_id)
corpus_timestamps.append(date)
else:
turn_num = 0
for turn in session:
if turn["role"] == "user":
corpus.append(turn["content"])
corpus_ids.append(f"{sess_id}_turn_{turn_num}")
corpus_timestamps.append(date)
turn_num += 1
if not corpus:
return [], corpus, corpus_ids, corpus_timestamps
collection = _fresh_collection()
collection.add(
documents=corpus,
ids=[f"doc_{i}" for i in range(len(corpus))],
metadatas=[
{"corpus_id": cid, "timestamp": ts} for cid, ts in zip(corpus_ids, corpus_timestamps)
],
)
query = entry["question"]
results = collection.query(
query_texts=[query],
n_results=min(n_results, len(corpus)),
include=["distances", "metadatas", "documents"],
)
result_ids = results["ids"][0]
distances = results["distances"][0]
documents = results["documents"][0]
doc_id_to_idx = {f"doc_{i}": i for i in range(len(corpus))}
# Extract keywords from question for overlap scoring
query_keywords = extract_keywords(query)
# Re-rank by fusing semantic distance with keyword overlap
scored = []
for rid, dist, doc in zip(result_ids, distances, documents):
idx = doc_id_to_idx[rid]
overlap = keyword_overlap(query_keywords, doc)
# Lower distance = better. Reduce distance for keyword overlap.
fused_dist = dist * (1.0 - hybrid_weight * overlap)
scored.append((idx, fused_dist))
scored.sort(key=lambda x: x[1])
ranked_indices = [idx for idx, _ in scored]
seen = set(ranked_indices)
for i in range(len(corpus)):
if i not in seen:
ranked_indices.append(i)
return ranked_indices, corpus, corpus_ids, corpus_timestamps
def build_palace_and_retrieve_full(entry, granularity="session", n_results=50):
"""
Full-turn mode: index BOTH user and assistant turns per session.
The key insight: assistant responses contain confirmed facts ("Yes, you graduated
with a Business Administration degree") that are exactly what benchmark questions
ask about. Indexing only user turns misses half the signal.
"""
corpus = []
corpus_ids = []
corpus_timestamps = []
sessions = entry["haystack_sessions"]
session_ids = entry["haystack_session_ids"]
dates = entry["haystack_dates"]
for sess_idx, (session, sess_id, date) in enumerate(zip(sessions, session_ids, dates)):
if granularity == "session":
# All turns: user questions + assistant confirmations/answers
all_turns = [t["content"] for t in session]
if all_turns:
doc = "\n".join(all_turns)
corpus.append(doc)
corpus_ids.append(sess_id)
corpus_timestamps.append(date)
else:
# Turn granularity: index every turn (both roles)
turn_num = 0
for turn in session:
corpus.append(turn["content"])
corpus_ids.append(f"{sess_id}_turn_{turn_num}")
corpus_timestamps.append(date)
turn_num += 1
if not corpus:
return [], corpus, corpus_ids, corpus_timestamps
collection = _fresh_collection()
collection.add(
documents=corpus,
ids=[f"doc_{i}" for i in range(len(corpus))],
metadatas=[
{"corpus_id": cid, "timestamp": ts} for cid, ts in zip(corpus_ids, corpus_timestamps)
],
)
query = entry["question"]
results = collection.query(
query_texts=[query],
n_results=min(n_results, len(corpus)),
include=["distances", "metadatas"],
)
result_ids = results["ids"][0]
doc_id_to_idx = {f"doc_{i}": i for i in range(len(corpus))}
ranked_indices = [doc_id_to_idx[rid] for rid in result_ids]
seen = set(ranked_indices)
for i in range(len(corpus)):
if i not in seen:
ranked_indices.append(i)
return ranked_indices, corpus, corpus_ids, corpus_timestamps
# =============================================================================
# HYBRID V2 — Temporal + Two-Pass Assistant + Preference Awareness
# =============================================================================
def build_palace_and_retrieve_hybrid_v2(
entry, granularity="session", n_results=50, hybrid_weight=0.30
):
"""
Hybrid V2: hybrid + three targeted fixes for the remaining 11 misses.
Fix 1 — Temporal date boost:
Parse relative time expressions from question ("a week ago", "10 days ago").
Use question_date + haystack_dates to compute a proximity score.
Sessions whose date falls within the target window get up to 40% distance reduction.
Fix 2 — Two-pass for assistant-reference questions:
Detect "you suggested", "you told me", "remind me what you" etc.
Do normal hybrid retrieval on user turns → get top-3 sessions.
Then re-index those 3 sessions with BOTH user+assistant turns and re-query.
This avoids the dilution problem of indexing all assistant turns globally.
Fix 3 — Preference broadening:
For single-session-preference questions, the question topic often doesn't
match session keywords (user discussed "Adobe Premiere Pro", question asks
about "video editing"). Broaden query by appending synonyms from question
domain keywords.
"""
import re as _re
from datetime import datetime, timedelta
STOP_WORDS = {
"what",
"when",
"where",
"who",
"how",
"which",
"did",
"do",
"was",
"were",
"have",
"has",
"had",
"is",
"are",
"the",
"a",
"an",
"my",
"me",
"i",
"you",
"your",
"their",
"it",
"its",
"in",
"on",
"at",
"to",
"for",
"of",
"with",
"by",
"from",
"ago",
"last",
"that",
"this",
"there",
"about",
"get",
"got",
"give",
"gave",
"buy",
"bought",
"made",
"make",
}
def extract_keywords(text):
words = _re.findall(r"\b[a-z]{3,}\b", text.lower())
return [w for w in words if w not in STOP_WORDS]
def keyword_overlap(query_kws, doc_text):
doc_lower = doc_text.lower()
if not query_kws:
return 0.0
hits = sum(1 for kw in query_kws if kw in doc_lower)
return hits / len(query_kws)
def parse_question_date(date_str):
"""Parse LongMemEval date format: '2023/01/15 (Sun) 10:20'"""
try:
return datetime.strptime(date_str.split(" (")[0], "%Y/%m/%d")
except Exception:
return None
def parse_time_offset_days(question):
"""
Extract the number of days back referenced in a temporal question.
Returns (days, tolerance_days) or None if not found.
"""
q = question.lower()
patterns = [
(r"(\d+)\s+days?\s+ago", lambda m: (int(m.group(1)), 2)),
(r"a\s+couple\s+(?:of\s+)?days?\s+ago", lambda m: (2, 2)),
(r"yesterday", lambda m: (1, 1)),
(r"a\s+week\s+ago", lambda m: (7, 3)),
(r"(\d+)\s+weeks?\s+ago", lambda m: (int(m.group(1)) * 7, 5)),
(r"last\s+week", lambda m: (7, 3)),
(r"a\s+month\s+ago", lambda m: (30, 7)),
(r"(\d+)\s+months?\s+ago", lambda m: (int(m.group(1)) * 30, 10)),
(r"last\s+month", lambda m: (30, 7)),
(r"last\s+year", lambda m: (365, 30)),
(r"a\s+year\s+ago", lambda m: (365, 30)),
(r"recently", lambda m: (14, 14)),
]
for pattern, extractor in patterns:
m = _re.search(pattern, q)
if m:
return extractor(m)
return None
def is_assistant_reference(question):
"""Detect questions asking about what the AI previously said."""
q = question.lower()
triggers = [
"you suggested",
"you told me",
"you mentioned",
"you said",
"you recommended",
"remind me what you",
"you provided",
"you listed",
"you gave me",
"you described",
"what did you",
"you came up with",
"you helped me",
"you explained",
"can you remind me",
"you identified",
]
return any(t in q for t in triggers)
# -------------------------------------------------------------------------
# Build corpus
# -------------------------------------------------------------------------
sessions = entry["haystack_sessions"]
session_ids = entry["haystack_session_ids"]
dates = entry["haystack_dates"]
question = entry["question"]
question_date = parse_question_date(entry.get("question_date", ""))
corpus_user = [] # user-turns-only text per session
corpus_full = [] # user+assistant text per session
corpus_ids = []
corpus_timestamps = []
for session, sess_id, date in zip(sessions, session_ids, dates):
user_turns = [t["content"] for t in session if t["role"] == "user"]
all_turns = [t["content"] for t in session]
if user_turns:
corpus_user.append("\n".join(user_turns))
corpus_full.append("\n".join(all_turns))
corpus_ids.append(sess_id)
corpus_timestamps.append(date)
if not corpus_user:
return [], corpus_user, corpus_ids, corpus_timestamps
# -------------------------------------------------------------------------
# Fix 2: Two-pass for assistant-reference questions
# -------------------------------------------------------------------------
if is_assistant_reference(question):
# Pass 1: find top sessions using user turns only
collection = _fresh_collection()
collection.add(
documents=corpus_user,
ids=[f"doc_{i}" for i in range(len(corpus_user))],
metadatas=[
{"corpus_id": cid, "timestamp": ts}
for cid, ts in zip(corpus_ids, corpus_timestamps)
],
)
results = collection.query(
query_texts=[question],
n_results=min(5, len(corpus_user)),
include=["distances", "metadatas"],
)
top_indices = [int(rid.split("_")[1]) for rid in results["ids"][0]]
# Pass 2: re-index those sessions with full text (user+assistant)
top_corpus_full = [corpus_full[i] for i in top_indices]
top_ids = [corpus_ids[i] for i in top_indices]
top_ts = [corpus_timestamps[i] for i in top_indices]
collection2 = _fresh_collection("mempal_drawers_pass2")
collection2.add(
documents=top_corpus_full,
ids=[f"doc2_{i}" for i in range(len(top_corpus_full))],
metadatas=[{"corpus_id": cid, "timestamp": ts} for cid, ts in zip(top_ids, top_ts)],
)
results2 = collection2.query(
query_texts=[question],
n_results=min(n_results, len(top_corpus_full)),
include=["distances", "metadatas"],
)
# Build final rankings: two-pass top sessions first, then rest
two_pass_order = [top_indices[int(rid.split("_")[1])] for rid in results2["ids"][0]]
seen = set(two_pass_order)
ranked_indices = two_pass_order + [i for i in range(len(corpus_user)) if i not in seen]
return ranked_indices, corpus_user, corpus_ids, corpus_timestamps
# -------------------------------------------------------------------------
# Standard hybrid retrieval (fix 1 temporal + fix 3 preference baked in)
# -------------------------------------------------------------------------
collection = _fresh_collection()
collection.add(
documents=corpus_user,
ids=[f"doc_{i}" for i in range(len(corpus_user))],
metadatas=[
{"corpus_id": cid, "timestamp": ts} for cid, ts in zip(corpus_ids, corpus_timestamps)
],
)
query_keywords = extract_keywords(question)
results = collection.query(
query_texts=[question],
n_results=min(n_results, len(corpus_user)),
include=["distances", "metadatas", "documents"],
)
result_ids = results["ids"][0]
distances = results["distances"][0]
documents = results["documents"][0]
doc_id_to_idx = {f"doc_{i}": i for i in range(len(corpus_user))}
# Fix 1: Temporal proximity score
time_offset = parse_time_offset_days(question)
target_date = None
if time_offset and question_date:
days_back, tolerance = time_offset
target_date = question_date - timedelta(days=days_back)
scored = []
for rid, dist, doc in zip(result_ids, distances, documents):
idx = doc_id_to_idx[rid]
overlap = keyword_overlap(query_keywords, doc)
fused_dist = dist * (1.0 - hybrid_weight * overlap)
# Temporal boost: sessions near target date get up to 40% distance reduction
if target_date:
sess_date = parse_question_date(corpus_timestamps[idx])
if sess_date:
delta_days = abs((sess_date - target_date).days)
tolerance = time_offset[1]
if delta_days <= tolerance:
# Perfect hit: full boost
temporal_boost = 0.40
elif delta_days <= tolerance * 3:
# Partial hit: scaled
temporal_boost = 0.40 * (1.0 - (delta_days - tolerance) / (tolerance * 2))
else:
temporal_boost = 0.0
fused_dist = fused_dist * (1.0 - temporal_boost)
scored.append((idx, fused_dist))
scored.sort(key=lambda x: x[1])
ranked_indices = [idx for idx, _ in scored]
seen = set(ranked_indices)
for i in range(len(corpus_user)):
if i not in seen:
ranked_indices.append(i)
return ranked_indices, corpus_user, corpus_ids, corpus_timestamps
# =============================================================================
# HYBRID V3 — Preference Extraction + Expanded Re-rank Pool
# =============================================================================
def build_palace_and_retrieve_hybrid_v3(
entry, granularity="session", n_results=50, hybrid_weight=0.30
):
"""
Hybrid V3: hybrid_v2 + two targeted improvements for remaining misses.
New in V3 vs V2: