Commit 2e85b37e by sunqi02 Committed by 胡悦

refactor: simplify MessageGate to activation recognition, add _handle_chat

1 parent 3aa2b07a
...@@ -121,56 +121,24 @@ class MessageGate: ...@@ -121,56 +121,24 @@ class MessageGate:
buffer.clear_pending() buffer.clear_pending()
return return
# 步骤 7:调 LLM 分类 + 重写 # 步骤 7:调 LLM 做激活识别(无历史上下文)
pending = buffer.get_pending() pending = buffer.get_pending()
if not pending: if not pending:
logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id) logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id)
return return
decision = await self._classify_and_rewrite( decision = await self._classify_and_rewrite(pending=pending)
session_id=session_id,
pending=pending,
agent_codes=list(bot_id_mapping.keys()),
)
# 步骤 8:根据 intent 分支 # 步骤 8:根据 intent 分支
if decision.intent == "ignore": if decision.intent == "chat":
# 按 msg_id 移除本批次 await self._handle_chat(
ids = [m["msg_id"] for m in pending if "msg_id" in m]
buffer.remove_by_msg_ids(ids)
# 清空 intent_session 并持久化
data = store.get(session_id) or {}
data["intent_session"] = ""
store.set(session_id, data)
self.session_service.save_to_db(session_id)
return
if decision.intent == "casual":
await self._handle_casual(
session_id=session_id, session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending, pending=pending,
bot_id_mapping=bot_id_mapping,
) )
buffer.clear_pending() buffer.clear_pending()
return return
if decision.intent == "incomplete": # pass
await self._handle_incomplete(
session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=bot_id_mapping,
)
# 不清空 buffer:用户后续补充的消息需要合并
return
# actionable
await self._handle_actionable( await self._handle_actionable(
session_id=session_id, session_id=session_id,
room_id=room_id, room_id=room_id,
...@@ -183,169 +151,49 @@ class MessageGate: ...@@ -183,169 +151,49 @@ class MessageGate:
async def _classify_and_rewrite( async def _classify_and_rewrite(
self, self,
session_id: str,
pending: List[Dict[str, Any]], pending: List[Dict[str, Any]],
agent_codes: Optional[List[str]] = None,
) -> "GateDecision": ) -> "GateDecision":
"""调 LLM 进行意图分类 + query 重写。""" """调 LLM 判断当前消息是否需要激活助手。无历史上下文,只看当前消息。
from app.infrastructure.session_store import SessionStore
store = SessionStore()
# 合并 pending 消息文本:text 类型原文照录,非 text 标记为文件 Returns:
parts = [] GateDecision with intent="chat" or "pass"
for m in pending: """
mt = m.get("msg_type", "") merged_text = self._merge_text_from_pending(pending)
mc = m.get("msg_content", "") if not merged_text:
if mt == "text" and mc: return GateDecision(intent="chat")
parts.append(mc)
elif mc: prompt = (
parts.append(f"[文件: {mc}]") "你是助手激活识别器。判断当前消息是否需要AI助手响应。\n"
merged_text = "\n".join(parts) if parts else "(空消息)" "- chat:打招呼、道谢、确认收到、纯社交寒暄、群友间对话 —— 助手沉默\n"
"- pass:提问、命令、文件处理、提到某Agent名称、需要协助 —— 激活助手\n"
# 加载 KV data "\n只输出 \"chat\" 或 \"pass\"。\n"
data = store.get(session_id) or {} "\n当前消息:\n" + merged_text
history = (data.get("conversation_history") or [])[-10:]
# 构建子 agent 的 prompts(过滤 is_steward=True 的主 agent)
agent_prompts: Dict[str, str] = {}
if agent_codes:
for code in agent_codes:
cfg = self.agent_hub.agents.get(code) if hasattr(self.agent_hub, "agents") else None
if cfg and not getattr(cfg, "is_steward", False):
agent_prompts[code] = getattr(cfg, "prompt", "")
# 取 base_messages(intent_session フィールド,冷恢复或上次写入)
base_messages = data.get("intent_session")
if not isinstance(base_messages, list) or not base_messages:
base_messages = self._build_default_classify_messages(
agent_codes=agent_codes or [], agent_prompts=agent_prompts,
) )
messages = [{"role": "user", "content": prompt}]
# 抽 system(不含 history)
system_msg = next(
(m for m in base_messages if m.get("role") == "system"),
None,
)
if not system_msg:
system_msg = {
"role": "system",
"content": self._build_classify_prompt(
agent_codes=agent_codes or [], agent_prompts=agent_prompts,
),
}
# 拼 intent_session 中的非 system 消息(incomplete 路径追加的追问上下文)
messages = [system_msg]
for m in base_messages:
content = (m.get("content") or "").strip()
if m.get("role") != "system" and content:
messages.append({"role": m["role"], "content": m.get("content", "")})
# 拼 history 成多轮 messages 对
for h in history:
if h.get("role") in ("user", "assistant"):
messages.append({"role": h["role"], "content": h.get("content", "")})
# 加 user current
user_prompt = f"## 当前用户消息\n{merged_text}\n\n请按 system 指令输出 JSON。"
messages.append({"role": "user", "content": user_prompt})
# 调 LLM
response = await self.model(messages=messages) response = await self.model(messages=messages)
text = self._extract_text(response).strip().lower()
logger.debug("[MessageGate] activation response: %s", text)
# 解析 JSON if text == "pass":
text = self._extract_text(response) return GateDecision(intent="pass")
logger.debug( return GateDecision(intent="chat") # 兜底默认:chat
"[MessageGate] LLM raw response type=%s, extracted text=%s",
type(response).__name__, text[:300],
)
# 写回 intent_session:保留 system + incomplete 追问上下文 + 本次 user_current async def _handle_chat(
# "## 当前用户消息" 前缀的消息是历次 classify 的 user_current,丢弃
intent_session = [system_msg]
for m in base_messages:
content = (m.get("content") or "").strip()
if m.get("role") != "system" and "## 当前用户消息" not in content and content:
intent_session.append({"role": m["role"], "content": m.get("content", "")})
# 截断超长 user_prompt,防止 intent_session 列写入超限(VARCHAR 8192)
MAX_USER_PROMPT = 2000
stored_prompt = user_prompt if len(user_prompt) <= MAX_USER_PROMPT else user_prompt[:MAX_USER_PROMPT] + "...[已截断]"
intent_session.append({"role": "user", "content": stored_prompt})
data["intent_session"] = intent_session
store.set(session_id, data)
self.session_service.save_to_db(session_id)
return self._parse_decision_json(text)
def _build_classify_prompt(
self, agent_codes: List[str], agent_prompts: Dict[str, str]
) -> str:
"""构造不含 history 段的 system prompt,注入子 agent 人设。"""
if agent_prompts:
lines = []
for code in agent_codes:
p = agent_prompts.get(code)
if p:
lines.append(f"- {code}: {p}")
agent_section = "\n".join(lines) if lines else "(未指定任何子 Agent)"
else:
agent_section = "(未指定任何子 Agent)"
return f"""你是 MessageGate 助手,负责:
1. 识别用户消息的意图(actionable / casual / incomplete / ignore)
2. 将用户消息重写为完整、明确的指令
## 风格指南
- 保持自然、说人话,不官方
- 简洁,不超过 50 字
- emoji 适度
## 当前会话可用的 Agent 及其职责
{agent_section}
## 消息结构说明
- 以 `## 当前用户消息` 标记的内容为**本轮输入**,是你需要分类和重写的目标
- 其余消息(不含该标记的)是历史上下文,仅供理解对话背景,**不作为本轮输入**
## 判定规则(必须遵守)
分类和重写时,**只依据 `## 当前用户消息` 标记的内容**。
- **actionable**: 任务类型明确 + `## 当前用户消息` 中已提供所需资源 + 可独立执行
- 在已有对话上下文内可完成的任务(追问细节、引用历史结论、修改上一轮输出)也属此类
- **casual**: 打招呼、感谢、确认、闲聊
- **incomplete**: 满足以下任一:
- 任务需要文件/数据等资源但 `## 当前用户消息` 中未提供(根据 Agent 职责判断需要什么)
- 任务类型明确但缺少关键参数(收件人、目标语言等)
- 意图模糊、缺少关键信息
- **ignore**: 纯表情、无意义字符、系统通知
## 追问规范
- reply 必须明确点出缺什么("请提供需要处理的音频文件"、"请补充收件人邮箱")
- 若历史上下文中有相关资源,可在 reply 中反问确认("您是想处理刚才的 xxx.mp3 吗?"),但**不能把历史资源写入 rewritten_query**
## 消息格式说明
- 非 text 消息(文件、图片等)会被标记为 [文件: URL]
- 用户输入的文本消息保持原样
- `## 当前用户消息` 中的 URL 是用户本轮主动提供的,应保留到 rewritten_query
## 输出格式(严格 JSON)
{{
"intent": "actionable|casual|incomplete|ignore",
"rewritten_query": "完整指令(actionable 时必填)。只包含 `## 当前用户消息` 中的内容,不从历史消息中提取链接或文件",
"reply": "回复文本(casual/incomplete 时必填)"
}}
"""
def _build_default_classify_messages(
self, self,
agent_codes: List[str], session_id: str,
agent_prompts: Dict[str, str], pending: List[Dict[str, Any]],
) -> List[Dict[str, Any]]: ) -> None:
"""默认 messages(KV 完全空 / 损坏时用)。""" """chat 分支:追加用户消息到 conversation_history,不触发 AgentHub,不发 IM。"""
return [ from app.service.memory import SessionMemory
{"role": "system", "content": self._build_classify_prompt( from app.infrastructure.session_store import SessionStore
agent_codes=agent_codes, agent_prompts=agent_prompts)},
{"role": "user", "content": ""}, store = SessionStore()
] mem = SessionMemory(session_id, store)
for m in pending:
if m.get("msg_type") == "text" and m.get("msg_content"):
mem.add("user", m["msg_content"])
self.session_service.save_to_db(session_id)
@staticmethod @staticmethod
def _extract_text(response: Any) -> str: def _extract_text(response: Any) -> str:
...@@ -372,28 +220,6 @@ class MessageGate: ...@@ -372,28 +220,6 @@ class MessageGate:
parts.append(f"[文件: {mc}]") parts.append(f"[文件: {mc}]")
return "\n".join(parts) if parts else "" return "\n".join(parts) if parts else ""
@staticmethod
def _parse_decision_json(text: str) -> "GateDecision":
"""解析 LLM 返回的 JSON 字符串为 GateDecision。"""
import json
import re
# 尝试提取 JSON 块(可能包在 ```json 中)
match = re.search(r"\{.*\}", text, re.DOTALL)
if not match:
logger.warning("MessageGate LLM 输出无 JSON: %s", text[:200])
return GateDecision(intent="ignore")
try:
data = json.loads(match.group(0))
return GateDecision(
intent=data.get("intent", "ignore"),
rewritten_query=data.get("rewritten_query"),
reply=data.get("reply"),
)
except json.JSONDecodeError:
logger.warning("MessageGate LLM 输出 JSON 解析失败: %s", text[:200])
return GateDecision(intent="ignore")
async def _handle_casual( async def _handle_casual(
self, self,
session_id: str, session_id: str,
...@@ -480,15 +306,8 @@ class MessageGate: ...@@ -480,15 +306,8 @@ class MessageGate:
pending: List[Dict[str, Any]], pending: List[Dict[str, Any]],
bot_id_mapping: Dict[str, str], bot_id_mapping: Dict[str, str],
) -> None: ) -> None:
"""actionable 分支:分发到 AgentHub。""" """pass 分支:分发到 AgentHub。"""
rewritten = decision.rewritten_query or "" query = self._merge_text_from_pending(pending)
original = self._merge_text_from_pending(pending)
if rewritten and original and original not in rewritten:
query = f"{rewritten}\n\n---\n{original}"
elif rewritten:
query = rewritten
else:
query = original
if not query: if not query:
logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id) logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
...@@ -505,13 +324,6 @@ class MessageGate: ...@@ -505,13 +324,6 @@ class MessageGate:
if url not in query: if url not in query:
query = f"{query}\n{url}" query = f"{query}\n{url}"
# 清空 intent_session(AgentHub 内部的 save_to_db 会顺带写库)
from app.infrastructure.session_store import SessionStore
store = SessionStore()
data = store.get(session_id) or {}
data["intent_session"] = ""
store.set(session_id, data)
# 提取 file_url(取第一个非 text 消息的 URL) # 提取 file_url(取第一个非 text 消息的 URL)
file_url = None file_url = None
for m in pending: for m in pending:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!