Commit 12427777 by sunqi02

feat(agent_hub): 优化 ReAct 循环异常处理,确保消息持久化和日志记录

1 parent a236ccbe
...@@ -4,6 +4,34 @@ ...@@ -4,6 +4,34 @@
## 我们负责的文件 ## 我们负责的文件
### 消息入口与门控
| 文件 | 类 | 职责 |
|------|----|------|
| `message_gate.py` | `MessageGate` | **消息门控层** — 意图分类、重写、分发 |
封装流程:
1. `evaluate()` 获取 session 锁,等待非 text 消息的补充窗口
2. `_classify_and_rewrite()` 调 LLM 分类意图(actionable / casual / incomplete / ignore)+ 重写 query
3. 根据 intent 分支:
- `actionable` → `_handle_actionable()` 调用 `AgentHub.process_message()`
- `casual` → `_handle_casual()` 直接发 IM 回复 + 记录对话历史 + `save_to_db()`
- `incomplete` → `_handle_incomplete()` 追问用户,保留 pending_messages 等待补充
- `ignore` → `remove_by_msg_ids()` 移除消息
4. `_get_lock(session_id)` 按 session 串行化,防止并发竞争
| 文件 | 类 | 职责 |
|------|----|------|
| `session_buffer.py` | `SessionBuffer` | **pending_messages 缓冲区** — 封装消息的追加/读取/清除 |
封装流程:
- `append(message)` — 追加消息到 `pending_messages`
- `get_pending()` — 返回当前 pending 消息列表副本
- `clear_pending()` — 清空缓冲区
- `remove_by_msg_ids(ids)` — 按 msg_id 移除指定消息(ignore 场景)
- `has_text_message()` — 检查是否有 text/other 类型消息
- `_ensure_session_exists()` — KV miss 时先尝试 DB 冷恢复,避免 conversation_history 丢失
### 核心调度 ### 核心调度
| 文件 | 类 | 职责 | | 文件 | 类 | 职责 |
...@@ -11,7 +39,7 @@ ...@@ -11,7 +39,7 @@
| `agent_hub.py` | `AgentHub` | **中央调度器** — 唯一运行的 Agent 运行时 | | `agent_hub.py` | `AgentHub` | **中央调度器** — 唯一运行的 Agent 运行时 |
封装流程: 封装流程:
1. 接收 `process_message()` 调用 1. 接收 `process_message()` 调用(由 MessageGate actionable 分支调用,或兜底直接调用)
2. `get_or_create_session()` 获取/创建会话 2. `get_or_create_session()` 获取/创建会话
3. `SessionMemory.get_messages()` 加载历史消息 3. `SessionMemory.get_messages()` 加载历史消息
4. `_build_main_prompt()` 组装 system prompt(DB prompt + soul_guide + 子Agent职责 + REVIEW_GUIDE + THINKING_GUIDE) 4. `_build_main_prompt()` 组装 system prompt(DB prompt + soul_guide + 子Agent职责 + REVIEW_GUIDE + THINKING_GUIDE)
...@@ -73,9 +101,9 @@ ...@@ -73,9 +101,9 @@
| 目录 | Agent 相关文件 | 说明 | | 目录 | Agent 相关文件 | 说明 |
|------|---------------|------| |------|---------------|------|
| `app/api/v1/endpoints/agent_hub.py` | 是 | API 入口,解析 `ChatRequest` → 调用 `AgentHub.process_message()` | | `app/api/v1/endpoints/agent_hub.py` | 是 | API 入口,解析 `ChatRequest` → 追加到 SessionBuffer → 后台调 MessageGate |
| `app/hooks/` | 是 | `PostReplyHook`(回复后 IM 发送)、`Hook` 基类 | | `app/hooks/` | 是 | `PostReplyHook`(回复后 IM 发送)、`Hook` 基类 |
| `app/infrastructure/session_store.py` | 是 | `SessionStore` 内存 KV,`ActiveSessionService` 的底层存储 | | `app/infrastructure/session_store.py` | 是 | `SessionStore` 内存 KV,`ActiveSessionService` 和 `SessionBuffer` 的底层存储 |
| `app/infrastructure/file_parser.py` | 是 | `FileParser` + `OSSClient`,`FileService` 的底层依赖 | | `app/infrastructure/file_parser.py` | 是 | `FileParser` + `OSSClient`,`FileService` 的底层依赖 |
| `app/config/loader.py` | 是 | `ConfigLoader` 加载 agents/models/skills/mappings JSON 配置 | | `app/config/loader.py` | 是 | `ConfigLoader` 加载 agents/models/skills/mappings JSON 配置 |
| `app/model/session.py` | 是 | `Session`、`ConversationHistory` ORM 模型 | | `app/model/session.py` | 是 | `Session`、`ConversationHistory` ORM 模型 |
...@@ -95,13 +123,28 @@ IM 网关 (5s 聚合窗口) ...@@ -95,13 +123,28 @@ IM 网关 (5s 聚合窗口)
▼ ▼
POST /api/v1/chat/completions ← app/api/v1/endpoints/agent_hub.py POST /api/v1/chat/completions ← app/api/v1/endpoints/agent_hub.py
│ 解析 ChatRequest: group, agents, messages │ 解析 ChatRequest: group, agents, messages
│ 提取 query, user_id, allowed_agent_codes, bot_id_mapping │ 提取 query, user_id, bot_id_mapping
│ 追加消息到 SessionBuffer
│ │
▼ ▼
BackgroundTasks.add_task() ← 异步后台处理,HTTP 立即返回 200 BackgroundTasks.add_task() ← 异步后台处理,HTTP 立即返回 200
│ │
▼ ▼
AgentHub.process_message() ← app/service/agent_hub.py MessageGate.evaluate() ← app/service/message_gate.py
│
├── 获取 session 锁(按 session_id 串行化)
├── 等待非 text 消息补充窗口(默认 6s)
├── 检查 running task(已有则跳过)
├── _classify_and_rewrite() → LLM 意图分类 + query 重写
│
├── intent=ignore → 移除 pending_messages,结束
├── intent=casual → 直接发 IM 回复 + save_to_db()
├── intent=incomplete → 追问用户 + 保留 pending 等待补充
│
└── intent=actionable → _handle_actionable()
│
▼
AgentHub.process_message() ← app/service/agent_hub.py
│ │
├── ActiveSessionService.get_or_create_session() ├── ActiveSessionService.get_or_create_session()
│ 内存 KV → DB 冷恢复 → 新建 │ 内存 KV → DB 冷恢复 → 新建
...@@ -122,6 +165,7 @@ AgentHub.process_message() ← app/service/agent_hub.py ...@@ -122,6 +165,7 @@ AgentHub.process_message() ← app/service/agent_hub.py
│ │ → post_reasoning hook: _summarize_thinking() │ │ → post_reasoning hook: _summarize_thinking()
│ │ 用 thinking_summary_model (deepseek-v4-flash) │ │ 用 thinking_summary_model (deepseek-v4-flash)
│ │ 摘要化后发送到 IM,不泄露内部推理细节 │ │ 摘要化后发送到 IM,不泄露内部推理细节
│ │ (call_sub_agent tool_result 后的 reasoning 跳过,避免与最终回复重复)
│ │ │ │
│ ├── [行动] 执行工具调用 │ ├── [行动] 执行工具调用
│ │ → call_sub_agent / read_file / skill 工具 / execute_code │ │ → call_sub_agent / read_file / skill 工具 / execute_code
...@@ -138,6 +182,10 @@ AgentHub.process_message() ← app/service/agent_hub.py ...@@ -138,6 +182,10 @@ AgentHub.process_message() ← app/service/agent_hub.py
→ IMService.send_message() → 自建 IM 服务 API → 用户收到回复 → IMService.send_message() → 自建 IM 服务 API → 用户收到回复
``` ```
### MessageGate 兜底逻辑
当 MessageGate 评估异常时,endpoint 的 `_process_message_async_via_gate` 会 catch 异常并兜底直接调用 `AgentHub.process_message()`,确保消息不会丢失。
### 模型架构 ### 模型架构
| 实例 | 模型 | temperature | 用途 | | 实例 | 模型 | temperature | 用途 |
...@@ -145,6 +193,7 @@ AgentHub.process_message() ← app/service/agent_hub.py ...@@ -145,6 +193,7 @@ AgentHub.process_message() ← app/service/agent_hub.py
| `self.model` | qwen3.6-plus | 默认 | 主 Agent ReAct 推理 | | `self.model` | qwen3.6-plus | 默认 | 主 Agent ReAct 推理 |
| `self.sub_model` | qwen3.6-plus | 0.2 | 子 Agent ReAct 推理 | | `self.sub_model` | qwen3.6-plus | 0.2 | 子 Agent ReAct 推理 |
| `self.thinking_summary_model` | deepseek-v4-flash | 默认 | thinking 摘要化(快、便宜) | | `self.thinking_summary_model` | deepseek-v4-flash | 默认 | thinking 摘要化(快、便宜) |
| MessageGate 模型 | deepseek-v4-flash | 默认 | 意图分类 + query 重写(轻量任务) |
### Prompt 装配顺序 ### Prompt 装配顺序
......
...@@ -436,17 +436,23 @@ class AgentHub: ...@@ -436,17 +436,23 @@ class AgentHub:
user_msg = Msg("user", effective_query, "user") user_msg = Msg("user", effective_query, "user")
# Store user message BEFORE agent call so it persists even on error # Run ReAct loop — exception path: no DB persist, no IM notify
memory.add("user", user_query, agent_code=target_agent)
try: try:
memory.add("user", user_query, agent_code=target_agent)
response_msg = await agent.reply(user_msg) response_msg = await agent.reply(user_msg)
except Exception:
logger.exception(
"[AgentHub] session=%s ReAct 执行异常,已跳过 DB 持久化和 IM 发送",
session_id,
)
raise
# Normal path: ReAct succeeded
response_content = response_msg.get_text_content() or "" response_content = response_msg.get_text_content() or ""
memory.add("assistant", response_content, agent_code=target_agent) memory.add("assistant", response_content, agent_code=target_agent)
finally:
# 持久化到 DB — always save what we have
self.session_service.save_to_db(session_id) self.session_service.save_to_db(session_id)
# Send via hook # Send via hook — failure non-fatal, only log
try: try:
await self.post_reply_hook.execute({ await self.post_reply_hook.execute({
"agent_name": target_agent, "agent_name": target_agent,
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!