-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_manager.py
More file actions
4248 lines (3886 loc) · 162 KB
/
Copy pathmemory_manager.py
File metadata and controls
4248 lines (3886 loc) · 162 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
"""
记忆管理器 - 封装知识库操作,通过 metadata 实现用户隔离
核心功能:
- 记忆存储 (store_memory)
- 记忆召回 (recall_memories)
- 记忆删除 (forget_memory)
- 记忆列表 (list_memories)
- 智能更新 (smart_update_memory)
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import math
import time
import uuid
from collections.abc import Callable
from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any
from astrbot.api import logger
from .maintenance.links import MemoryLinkManager
from .memory_protocol import (
MemoryMetadata,
MemoryScope,
MemoryType,
MemoryURI,
MemoryVisibility,
UMOInfo,
build_session_id,
build_user_id,
format_memory_content,
normalize_memory_scope,
)
if TYPE_CHECKING:
from astrbot.core.knowledge_base.kb_helper import KBHelper
from astrbot.core.knowledge_base.kb_mgr import KnowledgeBaseManager
from astrbot.core.platform import AstrMessageEvent
# KV 存储回调类型
KVPutFn = Callable[[str, Any], Any]
KVGetFn = Callable[[str, Any], Any]
KVDeleteFn = Callable[[str], Any]
SIMILARITY_THRESHOLD = 0.85 # 相似度阈值,用于记忆合并
# 允许的记忆域
_ALLOWED_DOMAINS = frozenset(
[
"user_profile",
"preferences",
"facts",
"events",
"context",
"fact",
"preference",
"event", # 别名支持
]
)
# 域别名映射
_DOMAIN_ALIASES = {
"fact": "facts",
"preference": "preferences",
"event": "events",
}
# 允许的记忆类型
_ALLOWED_MEMORY_TYPES = frozenset(
[
MemoryType.NORMAL,
MemoryType.PERMANENT,
"normal",
"permanent",
]
)
# 记忆类型别名映射
_MEMORY_TYPE_ALIASES = {
"normal": MemoryType.NORMAL,
"permanent": MemoryType.PERMANENT,
}
def _safe_parse_metadata(metadata: Any) -> dict[str, Any]:
"""安全解析 metadata,确保返回字典"""
if isinstance(metadata, dict):
return metadata
if isinstance(metadata, str):
try:
parsed = json.loads(metadata)
return parsed if isinstance(parsed, dict) else {}
except (json.JSONDecodeError, TypeError):
return {}
return {}
def normalize_domain(domain: str) -> str:
"""标准化记忆域名称"""
domain = (domain or "").lower().strip()
if domain in _DOMAIN_ALIASES:
return _DOMAIN_ALIASES[domain]
if domain in _ALLOWED_DOMAINS:
return domain
return "facts" # 默认域
def normalize_memory_type(memory_type: str) -> str:
"""标准化记忆类型"""
memory_type = (memory_type or "").lower().strip()
if memory_type in _MEMORY_TYPE_ALIASES:
return _MEMORY_TYPE_ALIASES[memory_type]
if memory_type in _ALLOWED_MEMORY_TYPES:
return memory_type
return MemoryType.NORMAL
def normalize_visibility(visibility: str, memory_scope: str) -> str:
"""标准化记忆可见性"""
visibility = (visibility or "").lower().strip()
if visibility in (MemoryVisibility.PRIVATE, MemoryVisibility.GROUP):
return visibility
return (
MemoryVisibility.GROUP
if memory_scope in (MemoryScope.GLOBAL, MemoryScope.GROUP)
else MemoryVisibility.PRIVATE
)
def _normalize_sender_ids(sender_ids: list[str] | None, fallback: str) -> list[str]:
values = sender_ids or [fallback]
result = []
for sender_id in values:
text = str(sender_id).strip()
if text:
result.append(text)
return list(dict.fromkeys(result))
def _clamp_importance(importance: int) -> int:
"""限制重要性范围在 1-5"""
try:
return max(1, min(5, int(importance)))
except (TypeError, ValueError):
return 3
def _debug_content_summary(value: Any, preview_limit: int = 80) -> dict[str, Any]:
"""返回用于 DEBUG 的脱敏内容摘要。"""
text = str(value or "").replace("\x00", " ")
compact = " ".join(text.split())
preview = compact[: max(0, preview_limit)]
if preview_limit > 0 and len(compact) > preview_limit:
preview += "..."
return {
"content_len": len(text),
"content_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest()[:12],
"preview": preview,
}
def _debug_filter_summary(filters: dict[str, Any]) -> dict[str, Any]:
"""返回不含用户和会话标识的过滤条件摘要。"""
return {
"keys": sorted(filters),
"domain": filters.get("domain", ""),
"scope": filters.get("memory_scope", ""),
"visibility": filters.get("visibility", ""),
"has_owner_filter": bool(
filters.get("owner_user_id") or filters.get("owner_session_id")
),
"deprecated": filters.get("deprecated"),
}
def _debug_memory_summary(memory: dict[str, Any]) -> dict[str, Any]:
"""返回实际召回或注入记忆的 URI 与正文预览。"""
metadata = _safe_parse_metadata(memory.get("metadata", {}))
body = (
metadata.get("memory_content")
or memory.get("text")
or memory.get("content", "")
)
return {
"uri": metadata.get("uri", ""),
"scope": metadata.get("memory_scope", ""),
"linked": bool(metadata.get("_is_linked", False)),
"created_at": metadata.get("created_at", ""),
"updated_at": metadata.get("updated_at", ""),
"curated_at": metadata.get("curated_at", ""),
"merged_from_count": len(metadata.get("merged_from", []))
if isinstance(metadata.get("merged_from"), list)
else 0,
"owner_user_ids": metadata.get("owner_user_ids", []),
"relation_types": metadata.get("_linked_relation_types", []),
**_debug_content_summary(body),
}
class MemoryManager:
"""记忆管理器 - 封装单知识库操作,通过 metadata 实现用户隔离"""
def __init__(
self,
kb_mgr: KnowledgeBaseManager,
config: dict,
kv_put: KVPutFn | None = None,
kv_get: KVGetFn | None = None,
kv_delete: KVDeleteFn | None = None,
):
self.kb_mgr = kb_mgr
self.config = config
self._kb_helper: KBHelper | None = None
self._kb_name: str = ""
self._rebuilding = False # 重建/迁移锁
self._pending_writes: list[dict[str, Any]] = [] # 重建期间暂存的写入
# KV 持久化回调(由 Star 插件注入)
self._kv_put = kv_put
self._kv_get = kv_get
self._kv_delete = kv_delete
# 关联表管理器(connect_kb 后初始化)
self._link_manager: MemoryLinkManager | None = None
self._last_active_memory_stats: dict[str, Any] = {}
# ---------- public state accessors ----------
@property
def is_kb_connected(self) -> bool:
"""KB 是否已连接"""
return self._kb_helper is not None
@property
def current_kb_name(self) -> str:
"""当前绑定的 KB 名称"""
return self._kb_name
@property
def is_rebuilding(self) -> bool:
"""当前是否正在执行重建/迁移。"""
return self._rebuilding
@property
def link_manager(self) -> MemoryLinkManager | None:
"""关联表管理器(KB 连接后可用)"""
return self._link_manager
@property
def last_active_memory_stats(self) -> dict[str, Any]:
"""返回最近一次活跃记忆分页的向量加载统计。"""
return dict(self._last_active_memory_stats)
async def purge_deprecated(
self, after_days: int = 7, *, dry_run: bool = False
) -> dict[str, Any]:
"""物理清理废弃记忆,或返回不写入的候选统计。"""
if not self._kb_helper:
return {
"purged": 0,
"links_cleaned": 0,
"candidates": 0,
"dry_run": dry_run,
}
from .maintenance.purge import purge_deprecated_memories
return await purge_deprecated_memories(
vec_db=self.vec_db,
kb_helper=self._kb_helper,
link_manager=self._link_manager,
after_days=after_days,
dry_run=dry_run,
)
def load_pending_writes(self, records: list[dict[str, Any]]) -> None:
"""从外部恢复重建期间未落盘的写入缓冲(启动恢复用)"""
self._pending_writes = list(records)
def initialize(self) -> None:
"""初始化记忆管理器(仅校验配置,不连接 KB)
Raises:
ValueError: 知识库未配置
"""
kb_name_raw = self.config.get("kb_name", [])
kb_name = (
kb_name_raw[0]
if isinstance(kb_name_raw, list) and kb_name_raw
else kb_name_raw
)
if not kb_name:
raise ValueError("记忆知识库未配置,请在插件设置中选择一个知识库")
self._kb_name = kb_name
async def connect_kb(self) -> None:
"""连接知识库(需在 KB 模块就绪后调用)
Raises:
ValueError: 知识库不存在
"""
kb = await self.kb_mgr.get_kb_by_name(self._kb_name)
if not kb:
raise ValueError(f"知识库 '{self._kb_name}' 不存在,请先在知识库管理中创建")
self._kb_helper = kb
logger.info(f"[简单长期记忆] 已连接知识库: {self._kb_name}")
await self._migrate_patch_chunk_index()
await self._migrate_patch_deprecated_at()
# 初始化关联表
self._link_manager = MemoryLinkManager(self.vec_db)
await self._link_manager.ensure_table()
async def _migrate_patch_chunk_index(self) -> None:
"""迁移补丁:为缺少 chunk_index 字段的旧记忆条目写入默认值 0。
旧版插件直接写入 vec_db 时未设置 chunk_index,导致 AstrBot 知识库检索
界面调用稀疏检索时抛出 KeyError: 'chunk_index'。
通过 SQLite json_set 原地修改 metadata,无需重新嵌入向量。
覆盖范围:有 is_memory_record 标记的新版记录 + 有 uri 但无标记的更早记录。
"""
try:
doc_storage = self.vec_db.document_storage
async with doc_storage.get_session() as session, session.begin():
from sqlalchemy import text as sa_text
result = await session.execute(
sa_text(
"UPDATE documents "
"SET metadata = json_set(metadata, '$.chunk_index', 0) "
"WHERE json_extract(metadata, '$.chunk_index') IS NULL "
" AND (json_extract(metadata, '$.is_memory_record') = 1 "
" OR json_extract(metadata, '$.uri') IS NOT NULL)"
)
)
patched = result.rowcount
if patched:
logger.info(
f"[简单长期记忆] 迁移补丁:已为 {patched} 条旧记忆补写 chunk_index=0"
)
except Exception as e:
logger.warning(f"[简单长期记忆] 迁移补丁执行失败(不影响功能): {e}")
async def _migrate_patch_deprecated_at(self) -> None:
"""迁移补丁:为已废弃但缺少 deprecated_at 的记忆回填时间戳。
旧版废弃操作只写 deprecated=1,没有记录废弃时间。
回填迁移执行时间(而非 created_at),确保宽限期从迁移时刻开始计算,
不会导致历史废弃记忆被立即清理。
"""
try:
doc_storage = self.vec_db.document_storage
async with doc_storage.get_session() as session, session.begin():
from sqlalchemy import text as sa_text
# 用 Python UTC ISO 格式,与 purge cutoff 的 isoformat() 保持一致
now_iso = datetime.now(timezone.utc).isoformat()
result = await session.execute(
sa_text(
"UPDATE documents "
"SET metadata = json_set(metadata, '$.deprecated_at', "
" :now_iso) "
"WHERE json_extract(metadata, '$.deprecated') = 1 "
" AND json_extract(metadata, '$.deprecated_at') IS NULL "
" AND json_extract(metadata, '$.is_memory_record') = 1"
),
{"now_iso": now_iso},
)
patched = result.rowcount
if patched:
logger.info(
f"[简单长期记忆] 迁移补丁:已为 {patched} 条废弃记忆回填 deprecated_at"
)
except Exception as e:
logger.warning(
f"[简单长期记忆] deprecated_at 迁移补丁失败(不影响功能): {e}"
)
@property
def vec_db(self):
"""获取向量数据库实例"""
if not self._kb_helper:
raise RuntimeError("记忆管理器未初始化")
return self._kb_helper.vec_db
async def _exec_metadata_update(
self,
set_clause: str,
where_clause: str,
params: dict[str, Any],
) -> int:
"""原地更新 documents.metadata(json_set),返回受影响行数。
绕过 FaissVecDB 无 update_metadata API 的限制:只改 metadata JSON 列,
不动 FAISS 向量、不动 FTS5 索引,廉价且安全。失败仅记录日志,不阻断检索。
"""
if not self._kb_helper:
return 0
try:
doc_storage = self.vec_db.document_storage
async with doc_storage.get_session() as session, session.begin():
from sqlalchemy import text as sa_text
result = await session.execute(
sa_text(
f"UPDATE documents SET metadata = {set_clause} WHERE {where_clause}"
),
params,
)
return int(result.rowcount or 0)
except Exception as e:
logger.warning(f"[简单长期记忆] metadata 原地更新失败(不影响检索): {e}")
return 0
async def _bump_recall_stats(self, uris: list[str], trace_id: str = "") -> int:
"""递增给定 uri 记忆的 recall_count 并刷新 last_recalled_at(P0.1 召回反馈)。"""
uris = [u for u in uris if u]
if not uris:
return 0
now = datetime.now(timezone.utc).isoformat()
set_clause = (
"json_set(metadata, '$.recall_count', "
"CAST(COALESCE(json_extract(metadata,'$.recall_count'),0) AS INTEGER) + 1, "
"'$.last_recalled_at', :now)"
)
placeholders = ",".join(f":u{i}" for i in range(len(uris)))
where_clause = (
f"json_extract(metadata,'$.uri') IN ({placeholders}) "
"AND json_extract(metadata,'$.is_memory_record') = 1"
)
params: dict[str, Any] = {"now": now}
params.update({f"u{i}": u for i, u in enumerate(uris)})
updated = await self._exec_metadata_update(set_clause, where_clause, params)
logger.debug(
"[简单长期记忆] 召回反馈更新: trace_id=%s, requested=%s, updated=%s",
trace_id or "-",
len(uris),
updated,
)
return updated
async def expire_stale_memories(self, ttl_days: int) -> int:
"""TTL 过期:把超过 ttl_days 且未废弃的记忆标记 deprecated=True(P1.1)。
召回 filter 已排除 deprecated,标记后即从召回移除。返回标记条数。
"""
if ttl_days <= 0 or not self._kb_helper:
return 0
kb_id = self._kb_helper.kb.kb_id
cutoff_iso = (datetime.now(timezone.utc) - timedelta(days=ttl_days)).isoformat()
set_clause = (
"json_set(metadata, '$.deprecated', 1, '$.deprecated_at', :now_iso)"
)
where_clause = (
"json_extract(metadata,'$.is_memory_record') = 1 "
"AND json_extract(metadata,'$.deprecated') IS NOT 1 "
"AND json_extract(metadata,'$.kb_id') = :kb_id "
"AND json_extract(metadata,'$.created_at') < :cutoff "
"AND json_extract(metadata,'$.memory_type') != 'permanent' "
"AND json_extract(metadata,'$.memory_scope') != 'global'"
)
params: dict[str, Any] = {
"kb_id": kb_id,
"cutoff": cutoff_iso,
"now_iso": datetime.now(timezone.utc).isoformat(),
}
return await self._exec_metadata_update(set_clause, where_clause, params)
async def fetch_consolidation_candidates(
self,
event: AstrMessageEvent,
min_age_days: int,
max_recall: int = 1,
limit: int = 30,
) -> list[dict[str, Any]]:
"""取出当前用户低频老旧、未废弃未压缩的个人记忆,作为巩固候选(P1.2)。
owner 与 memory_scope 由 event 推导并锁定为当前用户 personal,防止跨用户/跨作用域泄露。
"""
if not self._kb_helper or limit <= 0:
return []
owner_user_id = self._current_owner_user_id(event)
memory_scope = MemoryScope.PERSONAL
kb_id = self._kb_helper.kb.kb_id
cutoff_iso = (
datetime.now(timezone.utc) - timedelta(days=min_age_days)
).isoformat()
try:
doc_storage = self.vec_db.document_storage
async with doc_storage.get_session() as session:
from sqlalchemy import text as sa_text
rows = (
await session.execute(
sa_text(
"SELECT text, metadata FROM documents "
"WHERE json_extract(metadata,'$.is_memory_record') = 1 "
"AND json_extract(metadata,'$.deprecated') IS NOT 1 "
"AND json_extract(metadata,'$.compressed') IS NOT 1 "
"AND json_extract(metadata,'$.kb_id') = :kb_id "
"AND json_extract(metadata,'$.created_at') < :cutoff "
"AND CAST(COALESCE(json_extract(metadata,'$.recall_count'),0) AS INTEGER) <= :max_recall "
"AND json_extract(metadata,'$.owner_user_id') = :owner_user_id "
"AND json_extract(metadata,'$.memory_scope') = :memory_scope "
"ORDER BY json_extract(metadata,'$.created_at') ASC "
"LIMIT :limit"
),
{
"kb_id": kb_id,
"cutoff": cutoff_iso,
"max_recall": max_recall,
"owner_user_id": owner_user_id,
"memory_scope": memory_scope,
"limit": limit,
},
)
).all()
except Exception as e:
logger.warning(f"[简单长期记忆] 读取巩固候选失败: {e}")
return []
candidates: list[dict[str, Any]] = []
for row in rows:
text_val = getattr(row, "text", "") or ""
meta = _safe_parse_metadata(getattr(row, "metadata", {}) or {})
candidates.append({"text": text_val, "metadata": meta})
return candidates
async def mark_consolidated(self, uris: list[str]) -> int:
"""把已巩固的原记忆标记为 deprecated+compressed(P1.2)。"""
uris = [u for u in uris if u]
if not uris:
return 0
now_iso = datetime.now(timezone.utc).isoformat()
set_clause = (
"json_set(metadata, '$.deprecated', 1, '$.compressed', 1, "
"'$.deprecated_at', :now_iso)"
)
placeholders = ",".join(f":u{i}" for i in range(len(uris)))
where_clause = (
f"json_extract(metadata,'$.uri') IN ({placeholders}) "
"AND json_extract(metadata,'$.is_memory_record') = 1"
)
params: dict[str, Any] = {f"u{i}": u for i, u in enumerate(uris)}
params["now_iso"] = now_iso
return await self._exec_metadata_update(set_clause, where_clause, params)
def _rerank_by_signal(
self, memories: list[dict[str, Any]], query: str = ""
) -> list[dict[str, Any]]:
"""根据 importance/recall_count/recency/disclosure 对召回结果二次加权排序。
纯本地计算,不依赖 AstrBot。权重可经配置调整。
"""
if len(memories) <= 1:
return memories
now = time.time()
half_life = max(self.config.get("recall_recency_halflife_days", 14), 1) * 86400
w_importance = self.config.get("recall_weight_importance", 0.4)
w_frequency = self.config.get("recall_weight_frequency", 0.3)
w_recency = self.config.get("recall_weight_recency", 0.3)
disclosure_bonus = self.config.get("recall_disclosure_bonus", 0.25)
# 预计算 query tokens 用于 disclosure 匹配
query_tokens: set[str] = set()
if query and disclosure_bonus > 0:
tokens = self._tokenize_query(query)
if not tokens:
tokens = [t for t in query.lower().split() if len(t) >= 2]
query_tokens = set(tokens)
def _score(mem: dict[str, Any]) -> float:
meta = mem.get("metadata", {})
try:
_imp = meta.get("importance")
_imp = 3 if _imp is None or _imp == "" else _imp
importance = (int(float(_imp)) - 1) / 4.0
except (ValueError, TypeError):
importance = 0.5
try:
_rc = meta.get("recall_count")
_rc = 0 if _rc is None or _rc == "" else _rc
frequency = min(math.log1p(max(0, int(float(_rc)))) / 3.0, 1.0)
except (ValueError, TypeError):
frequency = 0.0
ts_str = meta.get("last_recalled_at") or meta.get("created_at")
recency = 0.5
if ts_str:
try:
ts = datetime.fromisoformat(
str(ts_str).replace("Z", "+00:00")
).timestamp()
recency = math.exp(-max(0.0, now - ts) / half_life)
except (ValueError, TypeError):
recency = 0.5
score = (
w_importance * importance
+ w_frequency * frequency
+ w_recency * recency
)
# disclosure 匹配加成:query 关键词与 disclosure 文本有交集时加分
if query_tokens:
disclosure = str(meta.get("disclosure", "")).lower()
if disclosure:
disc_tokens = self._tokenize_query(disclosure)
if not disc_tokens:
disc_tokens = [t for t in disclosure.split() if len(t) >= 2]
if query_tokens & set(disc_tokens):
score += disclosure_bonus
return score
return sorted(memories, key=_score, reverse=True)
# ==================== KB 文档注册 ====================
async def _register_kb_document(
self,
doc_id: str,
doc_name: str,
content_size: int,
kb_helper: KBHelper | None = None,
) -> None:
"""将记忆注册为 KB 文档,使其在知识库界面可见"""
from astrbot.core.knowledge_base.models import KBDocument
kb = kb_helper or self._kb_helper
doc = KBDocument(
doc_id=doc_id,
kb_id=kb.kb.kb_id,
doc_name=doc_name,
file_type="memory",
file_size=content_size,
file_path="",
chunk_count=1,
media_count=0,
)
async with kb.kb_db.get_db() as session:
async with session.begin():
session.add(doc)
await session.commit()
async def _ensure_kb_document(
self,
doc_id: str,
doc_name: str,
content_size: int,
kb_helper: KBHelper | None = None,
) -> bool:
"""确保向量文档对应的 KB 文档记录存在。"""
if not doc_id:
return False
kb = kb_helper or self._kb_helper
if not kb:
return False
try:
existing = await kb.get_document(doc_id)
if existing:
return True
await self._register_kb_document(
doc_id,
doc_name,
content_size,
kb_helper=kb,
)
return True
except Exception as e:
logger.warning(f"[简单长期记忆] KB 文档记录修复失败: {doc_id}, {e}")
return False
async def _find_memory_doc_by_uri(
self,
kb_helper: KBHelper,
uri: str,
) -> dict[str, Any] | None:
"""按 URI 精确查找目标 KB 中已存在的记忆向量文档。"""
if not uri:
return None
docs = await kb_helper.vec_db.document_storage.get_documents(
metadata_filters={
"uri": uri,
"is_memory_record": True,
"kb_id": kb_helper.kb.kb_id,
},
limit=1,
)
return docs[0] if docs else None
async def _repair_kb_document_for_vector_doc(
self,
kb_helper: KBHelper,
doc: dict[str, Any],
fallback_name: str,
) -> bool:
"""向量文档已存在时,补齐缺失的 KB 文档记录。"""
metadata = _safe_parse_metadata(doc.get("metadata", {}))
doc_id = metadata.get("kb_doc_id")
if not doc_id:
return False
doc_name = metadata.get("uri") or fallback_name or doc_id
content_size = len(doc.get("text", "") or "")
return await self._ensure_kb_document(
doc_id,
doc_name,
content_size,
kb_helper=kb_helper,
)
async def _unregister_kb_documents(
self,
doc_ids: list[str],
kb_helper: KBHelper | None = None,
) -> None:
"""批量移除 KB 文档记录"""
if not doc_ids:
return
from astrbot.core.knowledge_base.models import KBDocument
from sqlmodel import col, delete
kb = kb_helper or self._kb_helper
async with kb.kb_db.get_db() as session:
async with session.begin():
stmt = delete(KBDocument).where(col(KBDocument.doc_id).in_(doc_ids))
await session.execute(stmt)
await session.commit()
async def _sync_kb_stats(self, kb_helper: KBHelper | None = None) -> None:
"""同步知识库统计数据"""
kb = kb_helper or self._kb_helper
await kb.kb_db.update_kb_stats(
kb_id=kb.kb.kb_id,
vec_db=kb.vec_db,
)
await kb.refresh_kb()
async def _delete_rebuild_source_records(
self,
kb_helper: KBHelper,
memory_records: list[dict[str, Any]],
) -> None:
kb_id = kb_helper.kb.kb_id
await kb_helper.vec_db.delete_documents(
metadata_filters={"is_memory_record": True, "kb_id": kb_id}
)
legacy_uris: set[str] = set()
for record in memory_records:
metadata = _safe_parse_metadata(record.get("metadata", {}))
if (
not metadata.get("is_memory_record")
and metadata.get("kb_id") == kb_id
and metadata.get("uri")
):
legacy_uris.add(metadata["uri"])
for uri in legacy_uris:
await kb_helper.vec_db.delete_documents(
metadata_filters={"uri": uri, "kb_id": kb_id}
)
def _build_user_filter(self, event: AstrMessageEvent) -> dict[str, Any]:
"""构建用户隔离的 metadata 过滤器
Args:
event: 消息事件
Returns:
metadata 过滤器字典
"""
return {
"user_id": build_user_id(event.get_platform_id(), event.get_sender_id()),
}
def _event_scope_ids(
self, event: AstrMessageEvent, owner_sender_id: str | None = None
) -> tuple[UMOInfo, str, str]:
parsed = UMOInfo.parse(event.unified_msg_origin)
sender_id = owner_sender_id or event.get_sender_id()
owner_user_id = build_user_id(parsed.platform_id, sender_id)
owner_session_id = build_session_id(parsed.platform_id, parsed.session_id)
return parsed, owner_user_id, owner_session_id
def _build_owner_user_ids(
self, platform_id: str, owner_sender_ids: list[str]
) -> list[str]:
return [build_user_id(platform_id, sender_id) for sender_id in owner_sender_ids]
def _current_owner_user_id(self, event: AstrMessageEvent) -> str:
parsed = UMOInfo.parse(event.unified_msg_origin)
return build_user_id(parsed.platform_id, event.get_sender_id())
def _is_visible_shared_personal(
self, event: AstrMessageEvent, metadata: dict[str, Any]
) -> bool:
"""多 owner personal 记忆只对 owner_user_ids 内的用户可见。"""
if metadata.get("memory_scope") != MemoryScope.PERSONAL:
return True
if metadata.get("visibility") != MemoryVisibility.GROUP:
return True
owner_user_ids = metadata.get("owner_user_ids", [])
if not isinstance(owner_user_ids, list):
owner_user_ids = []
return self._current_owner_user_id(event) in owner_user_ids
def _filter_visible_shared_personal(
self, event: AstrMessageEvent, memories: list[dict[str, Any]]
) -> list[dict[str, Any]]:
visible = []
for memory in memories:
metadata = _safe_parse_metadata(memory.get("metadata", {}))
if self._is_visible_shared_personal(event, metadata):
visible.append(memory)
return visible
def _scope_filter(
self,
event: AstrMessageEvent,
memory_scope: str,
global_memory: bool = True,
) -> dict[str, Any]:
_, owner_user_id, owner_session_id = self._event_scope_ids(event)
scope = normalize_memory_scope(memory_scope)
if scope == MemoryScope.GLOBAL:
filters = {
"memory_scope": MemoryScope.GLOBAL,
}
elif scope == MemoryScope.GROUP:
filters = {
"memory_scope": MemoryScope.GROUP,
"owner_session_id": owner_session_id,
}
elif scope == MemoryScope.CONVERSATION:
filters = {
"memory_scope": MemoryScope.CONVERSATION,
"umo": event.unified_msg_origin,
}
else:
filters = {
"memory_scope": MemoryScope.PERSONAL,
"owner_user_id": owner_user_id,
}
if not global_memory:
filters["umo"] = event.unified_msg_origin
filters["is_memory_record"] = True
filters["deprecated"] = False
return filters
def _build_query_filter(
self,
event: AstrMessageEvent | None,
*,
all_users: bool,
domain: str | None = None,
include_deprecated: bool = False,
respect_global: bool = False,
) -> dict[str, Any]:
"""统一构建查询/列表/清空使用的 metadata 过滤器。
Args:
event: 消息事件(all_users 为 True 时可为 None)
all_users: True 时跳过用户隔离,使用 is_memory_record 标记
domain: 可选记忆域过滤
include_deprecated: 为 False 时排除 deprecated=True 的记忆
respect_global: True 时按 self.config['global_memory'] 决定是否限定 umo
"""
if all_users:
filters: dict[str, Any] = {"is_memory_record": True}
else:
if event is None:
raise ValueError("非 all_users 模式需要传入 event")
if respect_global:
global_memory = self.config.get("global_memory", True)
filters = self._scope_filter(event, MemoryScope.PERSONAL, global_memory)
else:
filters = self._build_user_filter(event)
if not include_deprecated:
filters["deprecated"] = False
if domain:
filters["domain"] = domain
return filters
def _build_memory_metadata(
self,
event: AstrMessageEvent,
**extra: Any,
) -> dict[str, Any]:
"""构建完整的记忆元数据
Args:
event: 消息事件
**extra: 额外的元数据字段
Returns:
完整的元数据字典
"""
umo = event.unified_msg_origin
memory_scope = normalize_memory_scope(extra.pop("memory_scope", ""))
visibility = normalize_visibility(extra.pop("visibility", ""), memory_scope)
speaker_id = extra.pop("speaker_id", event.get_sender_id())
owner_sender_id = extra.pop("owner_sender_id", None)
owner_sender_ids = _normalize_sender_ids(
extra.pop("owner_sender_ids", None),
owner_sender_id or event.get_sender_id(),
)
parsed, owner_user_id, owner_session_id = self._event_scope_ids(
event, owner_sender_ids[0]
)
owner_user_ids = self._build_owner_user_ids(
parsed.platform_id, owner_sender_ids
)
return {
"user_id": owner_user_id,
"platform_id": parsed.platform_id,
"sender_id": owner_sender_ids[0],
"umo": umo,
"session_type": parsed.session_type,
"session_id": parsed.session_id,
"memory_scope": memory_scope,
"owner_user_id": owner_user_id,
"owner_user_ids": owner_user_ids,
"owner_session_id": owner_session_id,
"visibility": visibility,
"speaker_id": speaker_id,
"created_at": datetime.now(timezone.utc).isoformat(),
"last_recalled_at": datetime.now(timezone.utc).isoformat(),
"recall_count": 0,
"compressed": False,
**extra,
}
async def store_memory(
self,
event: AstrMessageEvent,
content: str,
domain: str,
uri: str | None = None,
memory_type: str = MemoryType.NORMAL,
disclosure: str = "",
importance: int = 3,
memory_scope: str = MemoryScope.PERSONAL,
visibility: str = "",
subject: str = "",
entities: list[str] | None = None,
topics: list[str] | None = None,
owner_sender_id: str | None = None,
owner_sender_ids: list[str] | None = None,
) -> str:
"""存储记忆到知识库
Args:
event: 消息事件
content: 记忆内容
domain: 记忆域
uri: 记忆 URI(可选,自动生成)
memory_type: 记忆类型
disclosure: 触发召回条件描述
importance: 重要性等级 (1-5)
Returns:
存储的记忆 ID
"""
# 标准化参数
domain = normalize_domain(domain)
memory_type = normalize_memory_type(memory_type)
importance = _clamp_importance(importance)
memory_scope = normalize_memory_scope(memory_scope)
visibility = normalize_visibility(visibility, memory_scope)
entities = entities or []
topics = topics or []
owner_sender_ids = _normalize_sender_ids(
owner_sender_ids, owner_sender_id or event.get_sender_id()
)
if memory_scope == MemoryScope.PERSONAL and len(owner_sender_ids) > 1:
visibility = MemoryVisibility.GROUP
if uri is None:
uri = str(MemoryURI.generate(domain))
logger.debug(
"[简单长期记忆] 存储开始: uri=%s, domain=%s, memory_type=%s, "
"scope=%s, visibility=%s, importance=%s, content=%s",
uri,
domain,
memory_type,
memory_scope,
visibility,
importance,
_debug_content_summary(content),
)
# 重建/迁移期间:暂存到本地缓冲区并持久化到 KV,完成后批量处理
if self._rebuilding:
umo = event.unified_msg_origin
parsed, owner_user_id, owner_session_id = self._event_scope_ids(
event, owner_sender_ids[0]
)
owner_user_ids = self._build_owner_user_ids(