Commit 6001aa71 by sunqi02

refactor: adopt AgentScope Msg.to_dict() format in AgentHub

- delete _dict_to_msg(), use Msg.from_dict() for history restoration
- _save_tool_interactions() preserves full Block structure (type/id/name/input/output)
- tool_use → role=assistant, tool_result → role=system
- process_message() uses save-then-strip pattern for call_count >= 1
- remove sub-agent internal message save (call_sub_agent tool_result is sufficient)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent a18791af
...@@ -440,14 +440,6 @@ class AgentHub: ...@@ -440,14 +440,6 @@ class AgentHub:
return agent.prompt + self.soul_guide return agent.prompt + self.soul_guide
def _dict_to_msg(self, m: dict) -> Msg:
"""SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
role = m.get("role", "user")
if role not in ("user", "assistant", "system"):
role = "user"
content = m.get("content") or ""
return Msg(name=role, role=role, content=content)
async def process_message( async def process_message(
self, self,
session_id: str, session_id: str,
...@@ -520,7 +512,7 @@ class AgentHub: ...@@ -520,7 +512,7 @@ class AgentHub:
# Bridge: convert SessionStore dict history → AgentScope Msg[] # Bridge: convert SessionStore dict history → AgentScope Msg[]
agent_memory = InMemoryMemory() agent_memory = InMemoryMemory()
recent = messages[-10:] recent = messages[-10:]
history_msgs = [self._dict_to_msg(m) for m in recent] history_msgs = [Msg.from_dict(m) for m in recent]
if history_msgs: if history_msgs:
await agent_memory.add(history_msgs) await agent_memory.add(history_msgs)
...@@ -548,7 +540,7 @@ class AgentHub: ...@@ -548,7 +540,7 @@ class AgentHub:
# Run ReAct loop — exception path: no DB persist, no IM notify # Run ReAct loop — exception path: no DB persist, no IM notify
try: try:
memory.add("user", user_query, agent_code=target_agent) memory.add("user", user_query, name=target_agent)
response_msg = await agent.reply(user_msg) response_msg = await agent.reply(user_msg)
except Exception: except Exception:
logger.exception( logger.exception(
...@@ -558,9 +550,10 @@ class AgentHub: ...@@ -558,9 +550,10 @@ class AgentHub:
raise raise
# Normal path: ReAct succeeded # Normal path: ReAct succeeded
response_content = response_msg.get_text_content() or "" response_content = response_msg.content # 保留原生格式(str 或 list[dict])
target_agent_name = target_agent
# 将 ReAct 循环中所有工具调用/结果保存到 conversation_history # 1. 保存工具交互(先于 assistant,保证 remove_last 只命中最终回复)
try: try:
msg_list = await agent.memory.get_memory() msg_list = await agent.memory.get_memory()
self._save_tool_interactions(memory, msg_list) self._save_tool_interactions(memory, msg_list)
...@@ -570,25 +563,28 @@ class AgentHub: ...@@ -570,25 +563,28 @@ class AgentHub:
session_id, exc_info=True, session_id, exc_info=True,
) )
# 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束)
memory.add("assistant", response_content, name=target_agent_name)
call_count = self._current_route_ctx.get("call_count", 0) call_count = self._current_route_ctx.get("call_count", 0)
# 3. call_count >= 1 时剔除最后一条 assistant(主Agent 的"已委派"废话)
if call_count >= 1: if call_count >= 1:
# 主Agent 委托了子Agent,最终回复不写 KV、不发送 IM memory.remove_last()
# 但需持久化本轮写入的所有 KV 变更(user 消息 + tool 交互)
logger.info( logger.info(
"[主Agent 静默] call_count=%d,所有子Agent(含发言人)已发送回复,跳过主Agent 回复", "[主Agent 静默] call_count=%d,已剔除主Agent 最终回复,子Agent(含发言人)已发送回复",
call_count, call_count,
) )
self.session_service.save_to_db(session_id)
else: # 4. 持久化(仅一次)
# call_count == 0:主Agent 自己直接回复,正常写入 + 存 DB + 发送
memory.add("assistant", response_content, agent_code=target_agent)
self.session_service.save_to_db(session_id) self.session_service.save_to_db(session_id)
# 5. call_count == 0 时正常发 IM;>= 1 时不发
if call_count == 0:
try: try:
await self.post_reply_hook.execute({ await self.post_reply_hook.execute({
"agent_name": target_agent, "agent_name": target_agent_name,
"response_content": response_content, "response_content": response_msg.get_text_content() or "",
"room_id": room_id, "room_id": room_id,
"mentioned_list": [user_id], "mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping or {}, "bot_id_mapping": bot_id_mapping or {},
...@@ -596,7 +592,7 @@ class AgentHub: ...@@ -596,7 +592,7 @@ class AgentHub:
except Exception: except Exception:
logger.warning( logger.warning(
"[最终回复 IM 发送失败] agent=%s session=%s room=%s", "[最终回复 IM 发送失败] agent=%s session=%s room=%s",
target_agent, session_id, room_id, exc_info=True, target_agent_name, session_id, room_id, exc_info=True,
) )
processing_time_ms = (time.time() - start_time) * 1000 processing_time_ms = (time.time() - start_time) * 1000
...@@ -620,9 +616,8 @@ class AgentHub: ...@@ -620,9 +616,8 @@ class AgentHub:
def _save_tool_interactions( def _save_tool_interactions(
memory: SessionMemory, memory: SessionMemory,
agent_memory_msgs: list, agent_memory_msgs: list,
default_agent_code: str = "",
) -> None: ) -> None:
"""从 ReAct 循环内存中提取所有 tool_use/tool_result,保存到 conversation_history。""" """从 ReAct 循环内存中提取所有 tool_use/tool_result,保留 Block 结构保存到 conversation_history。"""
for msg in agent_memory_msgs: for msg in agent_memory_msgs:
if not hasattr(msg, "content") or not msg.content: if not hasattr(msg, "content") or not msg.content:
continue continue
...@@ -632,25 +627,27 @@ class AgentHub: ...@@ -632,25 +627,27 @@ class AgentHub:
continue continue
block_type = block.get("type") block_type = block.get("type")
if block_type == "tool_use": if block_type == "tool_use":
inp = block.get("input", {}) memory.add(
name = block.get("name", "") "assistant",
memory.add("assistant", str(inp), agent_code=default_agent_code or name) [{
"type": "tool_use",
"id": block["id"],
"name": block["name"],
"input": block.get("input", {}),
}],
name="assistant",
)
elif block_type == "tool_result": elif block_type == "tool_result":
output = block.get("output", "") memory.add(
if isinstance(output, list): "system",
texts = [ [{
item.get("text", "") "type": "tool_result",
for item in output "id": block["id"],
if isinstance(item, dict) and item.get("type") == "text" "name": block["name"],
] "output": block.get("output", ""),
result_text = "\n".join(texts) }],
elif isinstance(output, str): name="system",
result_text = output )
else:
result_text = str(output)
if result_text:
name = block.get("name", "")
memory.add("assistant", result_text, agent_code=default_agent_code or name)
def _get_mouth_key(self) -> str: def _get_mouth_key(self) -> str:
"""返回发言人口 agent 的 code。""" """返回发言人口 agent 的 code。"""
...@@ -695,13 +692,6 @@ class AgentHub: ...@@ -695,13 +692,6 @@ class AgentHub:
response_text = response.get_text_content() response_text = response.get_text_content()
logger.info("[子Agent 完成] agent_code=%s response_len=%d", agent_code, len(response_text) if response_text else 0) logger.info("[子Agent 完成] agent_code=%s response_len=%d", agent_code, len(response_text) if response_text else 0)
# 子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 账号发送最终回复 # 子 Agent 用自己的 bot 账号发送最终回复
try: try:
await self.post_reply_hook.execute({ 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!