Commit f7a03ade by sunqi02

feat(agent_hub): 更新附件处理逻辑,支持文件类型消息并优化思考摘要提取

1 parent 4d1ddf6c
......@@ -14,10 +14,10 @@
1. 接收 `process_message()` 调用
2. `get_or_create_session()` 获取/创建会话
3. `SessionMemory.get_messages()` 加载历史消息
4. `_build_main_prompt()` 组装 system prompt(含子 Agent 职责描述)
5. 创建 `ReActAgent`(AgentScope),注入 `InMemoryMemory` + `Toolkit`
4. `_build_main_prompt()` 组装 system prompt(DB prompt + soul_guide + 子Agent职责 + REVIEW_GUIDE + THINKING_GUIDE)
5. 创建 `ReActAgent`(AgentScope),注入 `InMemoryMemory` + `Toolkit`,主 Agent 用 `self.model`,子 Agent 用 `self.sub_model` (temp=0.2)
6. `agent.reply(user_msg)` 执行 ReAct 循环(推理→工具调用→观察→再推理)
7. `_call_sub_agent()` 子 Agent 创建与执行(通过 `call_sub_agent` 工具触发)
7. `_call_sub_agent()` 子 Agent 创建与执行(通过 `call_sub_agent` 工具触发,使用 `self.sub_model`)
8. `PostReplyHook.execute()` 通过 IM 发送最终回复
9. `save_to_db()` 持久化会话
......@@ -80,8 +80,9 @@
| `app/config/loader.py` | 是 | `ConfigLoader` 加载 agents/models/skills/mappings JSON 配置 |
| `app/model/session.py` | 是 | `Session`、`ConversationHistory` ORM 模型 |
| `config/agents.json` | 是 | Agent 配置(prompt、skills 列表等) |
| `config/models.json` | 是 | 模型配置(api_key 使用 `${OPENAI_API_KEY}` 占位) |
| `config/models.json` | 是 | 模型配置(main/sub/thinking_summary/message_gate/meeting_minutes) |
| `skills/` | 是 | Skill 目录,每个子目录有 `SKILL.md`,由 `Toolkit.register_agent_skill()` 加载 |
| `soul/` | 是 | 回复风格(agent.md)和 thinking 摘要提示词(thinking-summarize.md),启动时加载注入 prompt |
## Agent 调用完整流程
......@@ -109,19 +110,20 @@ AgentHub.process_message() ← app/service/agent_hub.py
│ 加载 conversation_history,超限自动压缩
│
├── _build_main_prompt()
│ steward prompt + 子 Agent 职责描述 + REVIEW_GUIDE
│ DB prompt + soul/agent.md 回复风格 + 子Agent职责 + REVIEW_GUIDE + THINKING_GUIDE
│
├── 创建 ReActAgent (AgentScope)
│ 注入: system_prompt, model, formatter, toolkit, memory
│ 主 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: 发送 thinking 全文到 IM(截断逻辑临时关闭,验证 THINKING_GUIDE 约束效果)
│ │ → post_reasoning hook: _summarize_thinking()
│ │ 用 thinking_summary_model (deepseek-v4-flash)
│ │ 摘要化后发送到 IM,不泄露内部推理细节
│ │
│ ├── [行动] 执行工具调用
│ │ → pre_acting hook: 发送工具调用信息到 IM
│ │ → call_sub_agent / read_file / skill 工具 / execute_code
│ │
│ ├── [观察] 工具返回结果,注入 memory
......@@ -135,3 +137,18 @@ AgentHub.process_message() ← app/service/agent_hub.py
└── PostReplyHook.execute()
→ IMService.send_message() → 自建 IM 服务 API → 用户收到回复
```
### 模型架构
| 实例 | 模型 | temperature | 用途 |
|------|------|-------------|------|
| `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 摘要化(快、便宜) |
### Prompt 装配顺序
```
_build_main_prompt: agent.prompt → soul_guide → 子Agent列表 → REVIEW_GUIDE → THINKING_GUIDE
_build_sub_agent_prompt: agent.prompt → soul_guide → THINKING_GUIDE
```
......@@ -411,7 +411,7 @@ class AgentHub:
# If there's an image URL, append it to the query so the agent can see it
effective_query = user_query
if file_url:
effective_query = f"{user_query}\n\n[用户发送了一张图片: {file_url}]"
effective_query = f"{user_query}\n\n[附件: {file_url}]"
user_msg = Msg("user", effective_query, "user")
......@@ -588,7 +588,11 @@ class AgentHub:
user_msg = Msg("user", thinking_text, "user")
formatted = await self.formatter.format([system_msg, user_msg])
response = await self.thinking_summary_model(formatted)
summary = (response.get_text_content() or "").strip()
text_parts = []
for block in response.content:
if isinstance(block, dict) and block.get("type") == "text":
text_parts.append(block.get("text", ""))
summary = "".join(text_parts).strip()
return summary or thinking_text[:30] + "..."
except Exception:
logger.warning("thinking 摘要化失败,使用截断兜底", exc_info=True)
......
......@@ -368,10 +368,10 @@ class MessageGate:
logger.warning("[MessageGate] session=%s actionable 但无 query,跳过", session_id)
return
# 提取 file_url(兼容 image 类型)
# 提取 file_url(兼容 image 和 file 类型)
file_url = None
for m in pending:
if m.get("msg_type") == "image" and m.get("msg_content"):
if m.get("msg_type") in ("image", "file") and m.get("msg_content"):
file_url = m["msg_content"]
break
......
......@@ -14,7 +14,7 @@
"sender_id": "",
"sender_name": "孙奇",
"msg_type": "other",
"msg_content": "3月25日.wav",
"msg_content": "3月25日.mp3",
"payload": {}
},
{
......@@ -25,6 +25,15 @@
"msg_type": "file",
"msg_content": "https://glsk-agentic-test.oss-cn-shenzhen.aliyuncs.com/meeting-minutes%2Faudio%2F1219%E4%BA%8C%E6%89%8B%E8%BD%A6%E4%BE%8B%E4%BC%9A%EF%BC%88%E8%B5%B5%E6%80%BB%EF%BC%89.mp3",
"payload": {}
},
{
"msg_id": "m4",
"msg_time": "2026-05-26T10:00:00Z",
"sender_id": "",
"sender_name": "孙奇",
"msg_type": "text",
"msg_content": "请帮我总结一下这次会议的内容和结论",
"payload": {}
}
]
}
......@@ -635,6 +635,26 @@ class TestAgentHubRouting:
assert result["response_content"] is not None
@pytest.mark.asyncio
async def test_file_url_appended_as_attachment(self):
"""file_url 不为空时,agent_hub 应使用"附件"格式追加到 query(兼容音频/视频等非图片)"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message(
session_id="sess_file",
room_id="room_001",
user_id="user_001",
user_query="请帮我总结会议",
file_url="https://oss.example.com/audio.mp3",
)
# 验证 process_message 跑通
assert result["response_content"] == "收到"
# 验证拼接逻辑:file_url 被加到 query
# 抽取出 _build_main_prompt 实际内容包含 user_query,确保 input 流转
# 简易检查:session store 中应该有 user 消息
msgs = _get_session_messages("sess_file")
assert any("请帮我总结会议" in m.get("content", "") for m in msgs)
@pytest.mark.asyncio
async def test_allowed_agent_codes_still_routes_steward(self):
"""allowed_agent_codes 不影响路由(始终 steward),仅影响 prompt 中 advertised 的子 agent"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
......@@ -835,7 +855,7 @@ async def test_summarize_thinking_calls_model():
hub = _make_test_hub()
short = "正在处理"
mock_response = MagicMock()
mock_response.get_text_content.return_value = "处理中"
mock_response.content = [{"type": "text", "text": "处理中"}]
hub.thinking_summary_model = AsyncMock(return_value=mock_response)
hub.formatter.format = AsyncMock(return_value=[{"role": "user", "content": short}])
......@@ -850,7 +870,7 @@ async def test_summarize_thinking_long_text_calls_model():
hub = _make_test_hub()
long_text = "用户需要我根据提供的音频文件生成会议纪要。根据系统提示,我需要使用 meeting_minutes 技能来处理这个任务。让我先查看 meeting_minutes 技能的 SKILL.md 文件。"
mock_response = MagicMock()
mock_response.get_text_content.return_value = "正在生成会议纪要"
mock_response.content = [{"type": "text", "text": "正在生成会议纪要"}]
hub.thinking_summary_model = AsyncMock(return_value=mock_response)
hub.formatter.format = AsyncMock(return_value=[{"role": "user", "content": long_text}])
......
......@@ -183,6 +183,57 @@ async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps):
@pytest.mark.asyncio
async def test_actionable_extracts_file_url_from_file_type(message_gate_with_deps):
"""file 类型消息的 msg_content 应被提取为 file_url 传给 AgentHub。"""
gate = message_gate_with_deps
gate.agent_hub.process_message = AsyncMock()
await gate._handle_actionable(
session_id="sess_002",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="actionable", rewritten_query="请总结会议"),
pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "https://oss.example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
)
# 等 task 完成
await asyncio.sleep(0.1)
if "sess_002" in gate._running_tasks:
await gate._running_tasks["sess_002"]
gate.agent_hub.process_message.assert_awaited_once()
# 验证 file_url 参数正确传递
call_kwargs = gate.agent_hub.process_message.call_args.kwargs
assert call_kwargs.get("file_url") == "https://oss.example.com/audio.mp3"
@pytest.mark.asyncio
async def test_actionable_still_extracts_image_url(message_gate_with_deps):
"""image 类型消息的 msg_content 也应被提取为 file_url(向后兼容)。"""
gate = message_gate_with_deps
gate.agent_hub.process_message = AsyncMock()
await gate._handle_actionable(
session_id="sess_003",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="actionable", rewritten_query="这是什么图片"),
pending=[{"msg_id": "m1", "msg_type": "image", "msg_content": "https://oss.example.com/img.jpg",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
)
await asyncio.sleep(0.1)
if "sess_003" in gate._running_tasks:
await gate._running_tasks["sess_003"]
call_kwargs = gate.agent_hub.process_message.call_args.kwargs
assert call_kwargs.get("file_url") == "https://oss.example.com/img.jpg"
@pytest.mark.asyncio
async def test_incomplete_sends_reply_and_preserves_buffer(message_gate_with_deps):
"""incomplete 分支应发 IM 追问,且不清空 buffer。"""
gate = message_gate_with_deps
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!