Commit eff12437 by sunqi02 Committed by 胡悦

Refactor code structure for improved readability and maintainability

1 parent b6127b44
...@@ -23,6 +23,9 @@ class GateDecision: ...@@ -23,6 +23,9 @@ class GateDecision:
intent: str # chat | pass intent: str # chat | pass
BUSY_REPLY = "你的消息我记下了!手上还有件事没处理完,稍等片刻就来聊~"
class MessageGate: class MessageGate:
"""消息门控层 - 等待/分类/重写/调度。""" """消息门控层 - 等待/分类/重写/调度。"""
...@@ -91,63 +94,80 @@ class MessageGate: ...@@ -91,63 +94,80 @@ class MessageGate:
buffer = SessionBuffer(store, session_id, session_service=self.session_service) buffer = SessionBuffer(store, session_id, session_service=self.session_service)
lock = self._get_lock(session_id) lock = self._get_lock(session_id)
async with lock: # 检查在途任务:已有任务则保存消息 + 发 busy 回复,不排队等待
# 调试:记录锁获取时的 KV 状态 existing = self._running_tasks.get(session_id)
_kv_data = store.get(session_id) or {} if existing and not existing.done():
_kv_history = _kv_data.get("conversation_history") or []
_kv_pending = _kv_data.get("pending_messages") or []
logger.info( logger.info(
"[MessageGate] session=%s 获取锁,conversation_history 长度=%d,pending_messages 长度=%d", "[MessageGate] session=%s 有在途任务,保存消息并发送 busy 回复",
session_id, len(_kv_history), len(_kv_pending), session_id,
) )
pending = buffer.get_pending()
# 步骤 4:检查 buffer 是否全是 file/image/other 无 text if pending:
if not buffer.has_text_message() and buffer.get_pending(): await self._handle_busy(
logger.info( session_id=session_id,
"[MessageGate] session=%s 无 text 消息,等待 %.1fs", room_id=room_id,
session_id, wait_seconds, user_id=user_id,
pending=pending,
bot_id_mapping=bot_id_mapping,
) )
await asyncio.sleep(wait_seconds) buffer.clear_pending()
# 等待后重新读取 buffer return
buffer = SessionBuffer(store, session_id, session_service=self.session_service) elif existing and existing.done():
del self._running_tasks[session_id]
# 步骤 6:检查 running task(Phase 1 简化版:发现 running 直接跳过) # 标记在途任务
running_task = self._running_tasks.get(session_id) self._running_tasks[session_id] = asyncio.current_task()
if running_task and not running_task.done():
try:
async with lock:
# 调试:记录锁获取时的 KV 状态
_kv_data = store.get(session_id) or {}
_kv_history = _kv_data.get("conversation_history") or []
_kv_pending = _kv_data.get("pending_messages") or []
logger.info( logger.info(
"[MessageGate] session=%s 已有 running task,跳过", "[MessageGate] session=%s 获取锁,conversation_history 长度=%d,pending_messages 长度=%d",
session_id, session_id, len(_kv_history), len(_kv_pending),
) )
buffer.clear_pending()
return
# 步骤 7:调 LLM 做激活识别(无历史上下文)
pending = buffer.get_pending()
if not pending:
logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id)
return
decision = await self._classify_and_rewrite(pending=pending) # 步骤 4:检查 buffer 是否全是 file/image/other 无 text
if not buffer.has_text_message() and buffer.get_pending():
# 步骤 8:根据 intent 分支 logger.info(
if decision.intent == "chat": "[MessageGate] session=%s 无 text 消息,等待 %.1fs",
await self._handle_chat( session_id, wait_seconds,
)
await asyncio.sleep(wait_seconds)
# 等待后重新读取 buffer
buffer = SessionBuffer(store, session_id, session_service=self.session_service)
# 步骤 7:调 LLM 做激活识别(无历史上下文)
pending = buffer.get_pending()
if not pending:
logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id)
return
decision = await self._classify_and_rewrite(pending=pending)
# 步骤 8:根据 intent 分支
if decision.intent == "chat":
await self._handle_chat(
session_id=session_id,
pending=pending,
)
buffer.clear_pending()
return
# pass
await self._handle_actionable(
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 finally:
self._running_tasks.pop(session_id, None)
# pass
await self._handle_actionable(
session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=bot_id_mapping,
)
buffer.clear_pending()
async def _classify_and_rewrite( async def _classify_and_rewrite(
self, self,
...@@ -257,6 +277,35 @@ class MessageGate: ...@@ -257,6 +277,35 @@ class MessageGate:
"bot_id_mapping": bot_id_mapping, "bot_id_mapping": bot_id_mapping,
}) })
async def _handle_busy(
self,
session_id: str,
room_id: str,
user_id: str,
pending: List[Dict[str, Any]],
bot_id_mapping: Dict[str, str],
) -> None:
"""在途任务忙碌分支:保存用户消息到 history,发固定告知回复。"""
from app.service.memory import SessionMemory
from app.infrastructure.session_store import SessionStore
store = SessionStore()
text_msgs = [
m["msg_content"] for m in pending
if m.get("msg_type") == "text" and m.get("msg_content")
]
if text_msgs:
merged_text = "\n".join(text_msgs)
mem = SessionMemory(session_id, store)
mem.add("user", merged_text)
self.session_service.save_to_db(session_id)
await self.post_reply_hook.execute({
"agent_name": self.main_agent_key,
"response_content": BUSY_REPLY,
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping,
})
async def _handle_incomplete( async def _handle_incomplete(
self, self,
session_id: str, session_id: str,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!