Commit ac012c9d by sunqi02 Committed by 胡悦

feat: 保存 ReAct 循环中的工具调用和结果到 conversation_history

1 parent a49b026c
...@@ -449,6 +449,17 @@ class AgentHub: ...@@ -449,6 +449,17 @@ class AgentHub:
# Normal path: ReAct succeeded # Normal path: ReAct succeeded
response_content = response_msg.get_text_content() or "" response_content = response_msg.get_text_content() or ""
# 将 ReAct 循环中所有工具调用/结果保存到 conversation_history
try:
msg_list = await agent.memory.get_memory()
self._save_tool_interactions(memory, msg_list)
except Exception:
logger.warning(
"[AgentHub] session=%s 保存工具消息异常(不影响主流程)",
session_id, exc_info=True,
)
memory.add("assistant", response_content, agent_code=target_agent) 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)
...@@ -477,6 +488,39 @@ class AgentHub: ...@@ -477,6 +488,39 @@ class AgentHub:
"processing_time_ms": round(processing_time_ms, 2) "processing_time_ms": round(processing_time_ms, 2)
} }
@staticmethod
def _save_tool_interactions(
memory: SessionMemory,
agent_memory_msgs: list,
) -> None:
"""从 ReAct 循环内存中提取所有 tool_use/tool_result,保存到 conversation_history。"""
for msg in agent_memory_msgs:
if not hasattr(msg, "content") or not msg.content:
continue
blocks = msg.content if isinstance(msg.content, list) else []
for block in blocks:
if not isinstance(block, dict):
continue
block_type = block.get("type")
if block_type == "tool_use":
inp = block.get("input", {})
memory.add("user", str(inp), agent_code=block.get("name", ""))
elif block_type == "tool_result":
output = block.get("output", "")
if isinstance(output, list):
texts = [
item.get("text", "")
for item in output
if isinstance(item, dict) and item.get("type") == "text"
]
result_text = "\n".join(texts)
elif isinstance(output, str):
result_text = output
else:
result_text = str(output)
if result_text:
memory.add("assistant", result_text, agent_code=block.get("name", ""))
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str: async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""通过 ReActAgent 调用子 Agent。""" """通过 ReActAgent 调用子 Agent。"""
if agent_code not in self.agents: if agent_code not in self.agents:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!