Commit fc05a786 by sunqi02

Refactor code structure for improved readability and maintainability

1 parent 46f69a10
......@@ -23,6 +23,9 @@ class GateDecision:
intent: str # chat | pass
BUSY_REPLY = "你的消息我记下了!手上还有件事没处理完,稍等片刻就来聊~"
class MessageGate:
"""消息门控层 - 等待/分类/重写/调度。"""
......@@ -91,63 +94,80 @@ class MessageGate:
buffer = SessionBuffer(store, session_id, session_service=self.session_service)
lock = self._get_lock(session_id)
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 []
# 检查在途任务:已有任务则保存消息 + 发 busy 回复,不排队等待
existing = self._running_tasks.get(session_id)
if existing and not existing.done():
logger.info(
"[MessageGate] session=%s 获取锁,conversation_history 长度=%d,pending_messages 长度=%d",
session_id, len(_kv_history), len(_kv_pending),
"[MessageGate] session=%s 有在途任务,保存消息并发送 busy 回复",
session_id,
)
# 步骤 4:检查 buffer 是否全是 file/image/other 无 text
if not buffer.has_text_message() and buffer.get_pending():
logger.info(
"[MessageGate] session=%s 无 text 消息,等待 %.1fs",
session_id, wait_seconds,
pending = buffer.get_pending()
if pending:
await self._handle_busy(
session_id=session_id,
room_id=room_id,
user_id=user_id,
pending=pending,
bot_id_mapping=bot_id_mapping,
)
await asyncio.sleep(wait_seconds)
# 等待后重新读取 buffer
buffer = SessionBuffer(store, session_id, session_service=self.session_service)
buffer.clear_pending()
return
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)
if running_task and not running_task.done():
# 标记在途任务
self._running_tasks[session_id] = asyncio.current_task()
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(
"[MessageGate] session=%s 已有 running task,跳过",
session_id,
"[MessageGate] session=%s 获取锁,conversation_history 长度=%d,pending_messages 长度=%d",
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)
# 步骤 8:根据 intent 分支
if decision.intent == "chat":
await self._handle_chat(
# 步骤 4:检查 buffer 是否全是 file/image/other 无 text
if not buffer.has_text_message() and buffer.get_pending():
logger.info(
"[MessageGate] session=%s 无 text 消息,等待 %.1fs",
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,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=bot_id_mapping,
)
buffer.clear_pending()
return
# 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()
finally:
self._running_tasks.pop(session_id, None)
async def _classify_and_rewrite(
self,
......@@ -257,6 +277,35 @@ class MessageGate:
"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(
self,
session_id: str,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!