feat:客户agent以及记忆模块功能开发
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
"""从客服对话中提取长期记忆候选。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from service.memory.schemas import MemorySource, MemoryType
|
||||
|
||||
|
||||
class DialogueMemoryExtractor:
|
||||
"""使用项目统一 LLM 提取结构化客户记忆候选。"""
|
||||
|
||||
SYSTEM_PROMPT = """
|
||||
你是客服记忆提取器,只提取用户明确表达或稳定陈述的客户信息。
|
||||
只返回 JSON 数组,不要输出 Markdown 或解释文字。
|
||||
每项必须包含:tag、content、memory_type、source。
|
||||
memory_type 只能是 PROFILE_FACT、PROFILE_CANDIDATE、CUSTOMER_PREFERENCE、INVESTMENT_GOAL、SERVICE_FACT。
|
||||
source 只能是 dialogue_confirmed、dialogue_stated、dialogue_inferred。
|
||||
客服知识问题、产品政策、寒暄、客服回复内容不要提取。
|
||||
不确定的信息使用 dialogue_inferred,无法形成客户画像的信息不要提取。
|
||||
""".strip()
|
||||
|
||||
def __init__(self, llm_client):
|
||||
self.llm_client = llm_client
|
||||
|
||||
async def extract(self, query: str, *, context: dict[str, Any] | None = None) -> list[dict[str, str]]:
|
||||
"""提取并校验本轮用户消息中的客户记忆候选。"""
|
||||
prompt = [{"role": "system", "content": self.SYSTEM_PROMPT}]
|
||||
prompt.append(
|
||||
{
|
||||
"role": "user",
|
||||
"content": json.dumps(
|
||||
{"query": query, "existing_memory": context or {}},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
}
|
||||
)
|
||||
response = await self.llm_client.chat(prompt, temperature=0, max_tokens=800)
|
||||
return self._parse(response)
|
||||
|
||||
@staticmethod
|
||||
def _parse(response: str) -> list[dict[str, str]]:
|
||||
"""解析 LLM JSON,并过滤不符合记忆契约的内容。"""
|
||||
text = response.strip()
|
||||
fenced = re.search(r"```(?:json)?\s*(.*?)\s*```", text, re.S | re.I)
|
||||
if fenced:
|
||||
text = fenced.group(1)
|
||||
data = json.loads(text)
|
||||
if not isinstance(data, list):
|
||||
raise ValueError("记忆提取结果必须是数组")
|
||||
valid_types = {item.value for item in MemoryType}
|
||||
valid_sources = {item.value for item in MemorySource}
|
||||
result = []
|
||||
for item in data:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if not all(item.get(key) for key in ("tag", "content", "memory_type", "source")):
|
||||
continue
|
||||
if item["memory_type"] not in valid_types or item["source"] not in valid_sources:
|
||||
continue
|
||||
result.append(
|
||||
{
|
||||
"tag": str(item["tag"])[:64],
|
||||
"content": str(item["content"])[:512],
|
||||
"memory_type": item["memory_type"],
|
||||
"source": item["source"],
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
__all__ = ["DialogueMemoryExtractor"]
|
||||
Reference in New Issue
Block a user