feat: 长期记忆改为摘要检索并由模型按需载入

This commit is contained in:
2026-09-20 11:33:35 +08:00
parent 177036cf3d
commit 9b240b35a9
12 changed files with 300 additions and 52 deletions
@@ -4,6 +4,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
import re
from bson import ObjectId
from motor.motor_asyncio import AsyncIOMotorDatabase
@@ -178,14 +179,79 @@ class MongoMemoryRepository(MemoryRepository):
)
return [self._to_mem(d) async for d in cursor]
async def count_active(self, company_id: int, user_id: str) -> int:
return int(
await self._col.count_documents(
{
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
)
)
async def search(
self, company_id: int, user_id: str, query: str, limit: int
) -> list[UserMemory]:
"""按摘要/正文关键词匹配(非向量);无关键词时退化为最近更新列表。"""
tokens = _keyword_tokens(query)
filt: dict[str, Any] = {
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
if tokens:
token_clauses = []
for t in tokens:
escaped = re.escape(t)
token_clauses.append(
{
"$or": [
{"summary": {"$regex": escaped, "$options": "i"}},
{"text": {"$regex": escaped, "$options": "i"}},
]
}
)
filt["$and"] = token_clauses
cursor = self._col.find(filt).sort("updated_at", -1).limit(max(1, min(limit, 20)))
return [self._to_mem(d) async for d in cursor]
async def get_by_ids(
self, company_id: int, user_id: str, memory_ids: list[str]
) -> list[UserMemory]:
oids: list[ObjectId] = []
for mid in memory_ids:
try:
oids.append(ObjectId(mid))
except Exception:
continue
if not oids:
return []
cursor = self._col.find(
{
"_id": {"$in": oids},
"company_id": company_id,
"user_id": user_id,
"status": MemoryStatus.ACTIVE.value,
}
)
by_id: dict[str, UserMemory] = {}
async for d in cursor:
by_id[str(d["_id"])] = self._to_mem(d)
# 保持调用方 id 顺序
return [by_id[mid] for mid in memory_ids if mid in by_id]
async def upsert(self, memory: UserMemory) -> UserMemory:
memory.updated_at = datetime.utcnow()
if not (memory.summary or "").strip():
memory.summary = _fallback_summary(memory.text)
payload = {
"company_id": memory.company_id,
"user_id": memory.user_id,
"kind": memory.kind.value,
"key": memory.key,
"text": memory.text,
"summary": memory.summary,
"value": memory.value,
"source_thread_id": memory.source_thread_id,
"status": memory.status.value,
@@ -230,13 +296,16 @@ class MongoMemoryRepository(MemoryRepository):
@staticmethod
def _to_mem(doc: dict[str, Any]) -> UserMemory:
text = doc.get("text") or ""
summary = (doc.get("summary") or "").strip() or _fallback_summary(text)
return UserMemory(
id=str(doc.get("_id")),
company_id=int(doc["company_id"]),
user_id=str(doc["user_id"]),
kind=MemoryKind(doc.get("kind") or MemoryKind.FACT.value),
key=doc.get("key"),
text=doc.get("text") or "",
text=text,
summary=summary,
value=doc.get("value") or {},
source_thread_id=doc.get("source_thread_id"),
status=MemoryStatus(doc.get("status") or MemoryStatus.ACTIVE.value),
@@ -244,3 +313,21 @@ class MongoMemoryRepository(MemoryRepository):
created_at=_dt(doc.get("created_at")),
updated_at=_dt(doc.get("updated_at")),
)
def _fallback_summary(text: str, max_len: int = 80) -> str:
s = (text or "").strip().replace("\n", " ")
if len(s) <= max_len:
return s
return s[: max_len - 1] + "…"
def _keyword_tokens(query: str) -> list[str]:
"""按空白与常见标点切词;过短 token 丢弃。"""
parts = re.split(r"[\s,,。.!!??;;::、/\\|]+", (query or "").strip())
out: list[str] = []
for p in parts:
t = p.strip()
if len(t) >= 1 and t not in out:
out.append(t)
return out[:8]