Files
2026-10-21 23:23:48 +08:00

138 lines
4.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""用户记忆用例:摘要写入、关键词检索、按需载入。"""
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
# 消息中出现「记住…」即写入(不必整句以此开头)
_REMEMBER_RE = re.compile(
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:
self._settings = settings
self._repo = repo
async def list_public(self, actor: Actor, limit: int = 50) -> list[dict]:
rows = await self._repo.list_active(actor.company_id, actor.user_id, limit)
return [
{
"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",
}
for m in rows
]
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 count_active(self, actor: Actor) -> int:
return await self._repo.count_active(actor.company_id, actor.user_id)
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:
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=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