mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 21:49:19 +08:00
feat: 长期记忆改为摘要检索并由模型按需载入
This commit is contained in:
@@ -14,6 +14,10 @@ from domain.ports import ChatStreamer
|
||||
_BASE_SYSTEM = (
|
||||
"你是电商 DMB 系统的经营助手。回答简洁、可执行。"
|
||||
"需要经营数据时优先调用可用工具。"
|
||||
"你具备跨会话的用户级长期记忆,但内容不会自动注入对话。"
|
||||
"需要称呼、偏好或用户事实时:先 memory_search,再对命中 id 调用 memory_load;"
|
||||
"禁止编造未 load 的记忆内容,也不要声称没有长期记忆能力。"
|
||||
"用户要求记住某事:可用 memory_save,或若系统提示「本轮已写入长期记忆」则明确确认已跨会话保存。"
|
||||
"用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time,"
|
||||
"用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。"
|
||||
"用户用名称或编码指代店铺、商品、SKU 时,先调用 catalog_search;"
|
||||
@@ -32,13 +36,15 @@ class OpenAICompatibleStreamer(ChatStreamer):
|
||||
llm: LlmRuntimeConfig,
|
||||
history: list[ChatMessage],
|
||||
user_text: str,
|
||||
memory_lines: list[str] | None = None,
|
||||
tools: list[Any] | None = None,
|
||||
memory_count: int = 0,
|
||||
memory_just_saved: str | None = None,
|
||||
) -> AsyncIterator[str]:
|
||||
system = _BASE_SYSTEM
|
||||
if memory_lines:
|
||||
joined = "\n".join(f"- {line}" for line in memory_lines[:20])
|
||||
system += f"\n\n以下是关于当前用户的长期记忆(可能过时,请谨慎引用):\n{joined}"
|
||||
if memory_count > 0:
|
||||
system += f"\n\n当前用户约有 {memory_count} 条长期记忆,需要时用 memory_search / memory_load。"
|
||||
if memory_just_saved:
|
||||
system += f"\n\n【本轮已写入长期记忆】{memory_just_saved}"
|
||||
|
||||
model = ChatOpenAI(
|
||||
api_key=llm.api_key,
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in New Issue
Block a user