Commit 8167d602 by sunqi02 Committed by 胡悦

refactor: main agent dispatch mode — prompt, shielding, self-call guard, sub-age…

…nt persistence, mouth toolkit exclusion
1 parent d343edb8
......@@ -23,12 +23,13 @@ logger = logging.getLogger(__name__)
# sub_agent 专用低 temperature:调用子 Agent 处理确定性任务时使用更稳定的输出
SUB_AGENT_TEMPERATURE = 0.2
REVIEW_GUIDE = """
## 收到子Agent返回后
DISPATCH_GUIDE = """
## 调度规则
1. 判断结果是否完整,是否还需要其他子Agent协作
2. 如果已经可以回复,整合所有结果用自然语言回复用户
3. 不要再调用同一个子Agent重复处理
1. 分析用户意图,判断是否在你的能力范围内(追问、澄清、简单对话等),可以直接回复
2. 复杂任务拆解为子任务步骤,按顺序调用子Agent(通过 call_sub_agent 工具),每次一个
3. 所有子Agent 执行完毕后,必须调用"发言人"Agent(调用码: -1)总结回复
4. 不要再调用同一个子Agent重复处理同一任务
"""
THINKING_GUIDE = """
......@@ -255,6 +256,9 @@ class AgentHub:
# 复制 basic 组工具(所有 agent 共用)
for name, tool in self.toolkit.tools.items():
if tool.group == "basic":
# 口 agent 不需要 call_sub_agent 工具
if agent_code == "-1" and name == "call_sub_agent":
continue
agent_tk.register_tool_function(
tool.original_func,
group_name=tool.group,
......@@ -329,7 +333,7 @@ class AgentHub:
if sub_lines:
prompt += "\n\n## 可调用的子Agent\n" + "\n".join(sub_lines)
return prompt + self.soul_guide + REVIEW_GUIDE + THINKING_GUIDE
return prompt + self.soul_guide + DISPATCH_GUIDE + THINKING_GUIDE
def _build_sub_agent_prompt(self, agent_code: str) -> str:
"""Build prompt for a sub-agent when handling a routed query."""
......@@ -389,6 +393,7 @@ class AgentHub:
store=self.session_service.store,
max_rounds=20,
)
self._current_route_ctx["session_memory"] = memory
messages = memory.get_messages(max_rounds=10)
......@@ -461,12 +466,19 @@ class AgentHub:
session_id, exc_info=True,
)
memory.add("assistant", response_content, agent_code=target_agent)
self.session_service.save_to_db(session_id)
call_count = self._current_route_ctx.get("call_count", 0)
if call_count >= 1:
# 主Agent 委托了子Agent,最终回复不写 KV、不存 DB、不发送
logger.info(
"[主Agent 静默] call_count=%d,所有子Agent(含发言人)已发送回复,跳过主Agent 回复",
call_count,
)
else:
# call_count == 0:主Agent 自己直接回复,正常写入 + 存 DB + 发送
memory.add("assistant", response_content, agent_code=target_agent)
self.session_service.save_to_db(session_id)
# Send via hook — failure non-fatal, only log
# 1 次 call_sub_agent 时跳过:子 Agent 已用自己的 bot 发送回复
if self._current_route_ctx.get("call_count", 0) != 1:
try:
await self.post_reply_hook.execute({
"agent_name": target_agent,
......@@ -480,10 +492,6 @@ class AgentHub:
"[最终回复 IM 发送失败] agent=%s session=%s room=%s",
target_agent, session_id, room_id, exc_info=True,
)
else:
logger.info(
"[主Agent 静默] call_count=1,子 Agent 已发送回复,跳过主 Agent post_reply"
)
processing_time_ms = (time.time() - start_time) * 1000
......@@ -499,6 +507,7 @@ class AgentHub:
def _save_tool_interactions(
memory: SessionMemory,
agent_memory_msgs: list,
default_agent_code: str = "",
) -> None:
"""从 ReAct 循环内存中提取所有 tool_use/tool_result,保存到 conversation_history。"""
for msg in agent_memory_msgs:
......@@ -511,7 +520,8 @@ class AgentHub:
block_type = block.get("type")
if block_type == "tool_use":
inp = block.get("input", {})
memory.add("user", str(inp), agent_code=block.get("name", ""))
name = block.get("name", "")
memory.add("user", str(inp), agent_code=default_agent_code or name)
elif block_type == "tool_result":
output = block.get("output", "")
if isinstance(output, list):
......@@ -526,10 +536,22 @@ class AgentHub:
else:
result_text = str(output)
if result_text:
memory.add("assistant", result_text, agent_code=block.get("name", ""))
name = block.get("name", "")
memory.add("assistant", result_text, agent_code=default_agent_code or name)
def _get_mouth_key(self) -> str:
"""返回发言人口 agent 的 code。"""
return "-1"
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""通过 ReActAgent 调用子 Agent。"""
# 自调用防护
steward_key = self._find_steward_key()
if agent_code == steward_key:
return (
f"错误:不允许主Agent自调用。"
f"如需总结回复,请调用发言人Agent(调用码: {self._get_mouth_key()})。"
)
if agent_code not in self.agents:
valid = [c for c, a in self.agents.items() if not a.is_steward]
return (
......@@ -557,6 +579,13 @@ class AgentHub:
response = await sub_agent.reply(Msg("user", instruction, "user"))
response_text = response.get_text_content()
# 子Agent 的 ReAct 消息落地到同一 session
sub_msgs = await sub_agent.memory.get_memory()
ctx = self._current_route_ctx
session_memory = ctx.get("session_memory") if ctx else None
if session_memory:
self._save_tool_interactions(session_memory, sub_msgs, default_agent_code=agent_code)
# 子 Agent 用自己的 bot 账号发送最终回复
try:
await self.post_reply_hook.execute({
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!