Commit 67afcaa1 by sunqi02 Committed by 胡悦

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

1 parent 7ac6702a
......@@ -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 @@
| `agent_hub.py` | `AgentHub` | **中央调度器** — 唯一运行的 Agent 运行时 |
封装流程:
1. 接收 `process_message()` 调用
1. 接收 `process_message()` 调用(由 MessageGate actionable 分支调用,或兜底直接调用)
2. `get_or_create_session()` 获取/创建会话
3. `SessionMemory.get_messages()` 加载历史消息
4. `_build_main_prompt()` 组装 system prompt(DB prompt + soul_guide + 子Agent职责 + REVIEW_GUIDE + THINKING_GUIDE)
......@@ -73,9 +101,9 @@
| 目录 | 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/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/config/loader.py` | 是 | `ConfigLoader` 加载 agents/models/skills/mappings JSON 配置 |
| `app/model/session.py` | 是 | `Session`、`ConversationHistory` ORM 模型 |
......@@ -95,49 +123,69 @@ IM 网关 (5s 聚合窗口)
▼
POST /api/v1/chat/completions ← app/api/v1/endpoints/agent_hub.py
│ 解析 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
│
▼
AgentHub.process_message() ← app/service/agent_hub.py
│
├── ActiveSessionService.get_or_create_session()
│ 内存 KV → DB 冷恢复 → 新建
│
├── SessionMemory.get_messages()
│ 加载 conversation_history,超限自动压缩
│
├── _build_main_prompt()
│ DB prompt + soul/agent.md 回复风格 + 子Agent职责 + REVIEW_GUIDE + THINKING_GUIDE
MessageGate.evaluate() ← app/service/message_gate.py
│
├── 创建 ReActAgent (AgentScope)
│ 主 Agent 用 self.model,子 Agent 用 self.sub_model (temp=0.2)
│ toolkit = basic 工具 + agent 专属 skills
├── 获取 session 锁(按 session_id 串行化)
├── 等待非 text 消息补充窗口(默认 6s)
├── 检查 running task(已有则跳过)
├── _classify_and_rewrite() → LLM 意图分类 + query 重写
│
├── agent.reply(user_msg) ← ReAct 循环
│ │
│ ├── [推理] LLM 生成 thinking + tool_use
│ │ → post_reasoning hook: _summarize_thinking()
│ │ 用 thinking_summary_model (deepseek-v4-flash)
│ │ 摘要化后发送到 IM,不泄露内部推理细节
│ │
│ ├── [行动] 执行工具调用
│ │ → call_sub_agent / read_file / skill 工具 / execute_code
│ │
│ ├── [观察] 工具返回结果,注入 memory
│ │
│ └── 重复,直到 LLM 输出最终回复(无 tool_use)
├── intent=ignore → 移除 pending_messages,结束
├── intent=casual → 直接发 IM 回复 + save_to_db()
├── intent=incomplete → 追问用户 + 保留 pending 等待补充
│
├── SessionMemory.add("assistant", response)
│
├── ActiveSessionService.save_to_db()
│
└── PostReplyHook.execute()
→ IMService.send_message() → 自建 IM 服务 API → 用户收到回复
└── intent=actionable → _handle_actionable()
│
▼
AgentHub.process_message() ← app/service/agent_hub.py
│
├── ActiveSessionService.get_or_create_session()
│ 内存 KV → DB 冷恢复 → 新建
│
├── SessionMemory.get_messages()
│ 加载 conversation_history,超限自动压缩
│
├── _build_main_prompt()
│ DB prompt + soul/agent.md 回复风格 + 子Agent职责 + REVIEW_GUIDE + THINKING_GUIDE
│
├── 创建 ReActAgent (AgentScope)
│ 主 Agent 用 self.model,子 Agent 用 self.sub_model (temp=0.2)
│ toolkit = basic 工具 + agent 专属 skills
│
├── agent.reply(user_msg) ← ReAct 循环
│ │
│ ├── [推理] LLM 生成 thinking + tool_use
│ │ → post_reasoning hook: _summarize_thinking()
│ │ 用 thinking_summary_model (deepseek-v4-flash)
│ │ 摘要化后发送到 IM,不泄露内部推理细节
│ │ (call_sub_agent tool_result 后的 reasoning 跳过,避免与最终回复重复)
│ │
│ ├── [行动] 执行工具调用
│ │ → call_sub_agent / read_file / skill 工具 / execute_code
│ │
│ ├── [观察] 工具返回结果,注入 memory
│ │
│ └── 重复,直到 LLM 输出最终回复(无 tool_use)
│
├── SessionMemory.add("assistant", response)
│
├── ActiveSessionService.save_to_db()
│
└── PostReplyHook.execute()
→ IMService.send_message() → 自建 IM 服务 API → 用户收到回复
```
### MessageGate 兜底逻辑
当 MessageGate 评估异常时,endpoint 的 `_process_message_async_via_gate` 会 catch 异常并兜底直接调用 `AgentHub.process_message()`,确保消息不会丢失。
### 模型架构
| 实例 | 模型 | temperature | 用途 |
......@@ -145,6 +193,7 @@ AgentHub.process_message() ← app/service/agent_hub.py
| `self.model` | qwen3.6-plus | 默认 | 主 Agent ReAct 推理 |
| `self.sub_model` | qwen3.6-plus | 0.2 | 子 Agent ReAct 推理 |
| `self.thinking_summary_model` | deepseek-v4-flash | 默认 | thinking 摘要化(快、便宜) |
| MessageGate 模型 | deepseek-v4-flash | 默认 | 意图分类 + query 重写(轻量任务) |
### Prompt 装配顺序
......
......@@ -436,17 +436,23 @@ class AgentHub:
user_msg = Msg("user", effective_query, "user")
# Store user message BEFORE agent call so it persists even on error
memory.add("user", user_query, agent_code=target_agent)
# Run ReAct loop — exception path: no DB persist, no IM notify
try:
memory.add("user", user_query, agent_code=target_agent)
response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content() or ""
memory.add("assistant", response_content, agent_code=target_agent)
finally:
# 持久化到 DB — always save what we have
self.session_service.save_to_db(session_id)
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 ""
memory.add("assistant", response_content, agent_code=target_agent)
self.session_service.save_to_db(session_id)
# Send via hook
# Send via hook — failure non-fatal, only log
try:
await self.post_reply_hook.execute({
"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!