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
+94 -23
View File
@@ -1,20 +1,32 @@
"""用户记忆用例。"""
"""用户记忆用例:摘要写入、关键词检索、按需载入。"""
from __future__ import annotations
import hashlib
import re
from config.settings import Settings
from domain.models import Actor, MemoryKind, UserMemory
from domain.ports import MemoryRepository
from config.settings import Settings
# 消息中出现「记住…」即写入(不必整句以此开头)
_REMEMBER_RE = re.compile(
r"^(?:请?记住|记住一下)[::\s]*(.+)$",
r"(?:请?帮?我?记住一下?|请?记住)[::\s,,]*(.+)",
re.DOTALL,
)
_SUMMARY_MAX = 80
def build_memory_summary(text: str) -> str:
"""规则摘要:压缩空白并截断,供搜索与列表展示。"""
s = re.sub(r"\s+", " ", (text or "").strip())
if not s:
return ""
if len(s) <= _SUMMARY_MAX:
return s
return s[: _SUMMARY_MAX - 1] + "…"
class MemoryService:
def __init__(self, settings: Settings, repo: MemoryRepository) -> None:
@@ -28,6 +40,7 @@ class MemoryService:
"id": m.id,
"kind": m.kind.value,
"key": m.key,
"summary": m.summary or build_memory_summary(m.text),
"text": m.text,
"updatedAt": m.updated_at.isoformat() + "Z",
}
@@ -37,30 +50,88 @@ class MemoryService:
async def delete(self, actor: Actor, memory_id: str) -> bool:
return await self._repo.soft_delete(actor.company_id, actor.user_id, memory_id)
async def lines_for_prompt(self, actor: Actor) -> list[str]:
rows = await self._repo.list_active(
actor.company_id, actor.user_id, self._settings.memory_inject_limit
)
return [m.text.strip() for m in rows if m.text and m.text.strip()]
async def count_active(self, actor: Actor) -> int:
return await self._repo.count_active(actor.company_id, actor.user_id)
async def maybe_capture_from_user(
self, actor: Actor, *, thread_id: str, text: str
) -> None:
"""显式「记住…」指令写入记忆;自动抽取留给 P2。"""
m = _REMEMBER_RE.match((text or "").strip())
if not m:
return
body = m.group(1).strip()
async def search(
self, actor: Actor, query: str, limit: int = 5
) -> list[dict]:
"""返回摘要命中列表(无正文)。"""
rows = await self._repo.search(
actor.company_id,
actor.user_id,
query,
max(1, min(limit, 20)),
)
return [
{
"id": m.id,
"summary": m.summary or build_memory_summary(m.text),
"kind": m.kind.value,
"updatedAt": m.updated_at.isoformat() + "Z",
}
for m in rows
]
async def load(self, actor: Actor, memory_ids: list[str]) -> list[dict]:
"""按 id 载入正文;单次最多 5 条。"""
ids = [i for i in memory_ids if i][:5]
rows = await self._repo.get_by_ids(actor.company_id, actor.user_id, ids)
return [
{
"id": m.id,
"summary": m.summary or build_memory_summary(m.text),
"text": m.text,
"kind": m.kind.value,
}
for m in rows
]
async def save(
self,
actor: Actor,
text: str,
*,
kind: MemoryKind = MemoryKind.FACT,
thread_id: str | None = None,
key: str | None = None,
) -> dict:
"""写入一条记忆(含规则摘要)。"""
body = (text or "").strip()
if not body:
return
key = "remember:" + hashlib.sha1(body.encode("utf-8")).hexdigest()[:16]
await self._repo.upsert(
raise ValueError("记忆内容不能为空")
body = body[:1000]
summary = build_memory_summary(body)
mem_key = key or ("remember:" + hashlib.sha1(body.encode("utf-8")).hexdigest()[:16])
saved = await self._repo.upsert(
UserMemory(
company_id=actor.company_id,
user_id=actor.user_id,
kind=MemoryKind.PREFERENCE,
key=key,
text=body[:1000],
kind=kind,
key=mem_key,
text=body,
summary=summary,
source_thread_id=thread_id,
)
)
return {"id": saved.id, "summary": saved.summary or summary, "kind": saved.kind.value}
async def maybe_capture_from_user(
self, actor: Actor, *, thread_id: str, text: str
) -> str | None:
"""显式「记住…」写入跨会话记忆;命中则返回写入正文,否则 None。"""
m = _REMEMBER_RE.search((text or "").strip())
if not m:
return None
body = m.group(1).strip().rstrip("。.!!")
if not body or len(body) > 1000:
return None
if body in ("一下", "下"):
return None
result = await self.save(
actor,
body,
kind=MemoryKind.PREFERENCE,
thread_id=thread_id,
)
return body if result else None