Commit d41eb336 by sunqi02

refactor: replace _call_model with ReActAgent, remove dead code

- process_message(): create per-request ReActAgent with shared singletons
- _call_sub_agent(): use ReActAgent instead of manual message building
- Remove _call_model() (~83 lines), _build_history_section() (~12 lines)
- Remove fallback routing logic (~19 lines)
- Remove unused imports (json, ToolUseBlock, ToolResultBlock)
- Add ReActAgent and InMemoryMemory imports

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 6f134bb5
import json
import logging
import time
from pathlib import Path
......@@ -11,9 +10,11 @@ from app.service.memory import SessionMemory
from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg
from agentscope.message._message_block import TextBlock, ToolUseBlock
from agentscope.message._message_block import TextBlock
from agentscope.tool._response import ToolResponse
from agentscope.tool import execute_python_code, execute_shell_command
from agentscope.agent import ReActAgent
from agentscope.memory import InMemoryMemory
logger = logging.getLogger(__name__)
......@@ -163,19 +164,6 @@ class AgentHub:
content = m.get("content", "")
return Msg(name=role, role=role, content=content)
def _build_history_section(self, messages: List) -> str:
"""Build conversation history section from recent messages."""
if not messages:
return "(暂无历史对话)"
lines = []
recent = messages[-10:]
for msg in recent:
role_label = "用户" if msg.get("role") == "user" else f"助手({msg.get('agent_code', 'main')})"
content = (msg.get("content") or "")[:500]
lines.append(f"[{role_label}]: {content}")
return "\n".join(lines)
async def process_message(
self,
session_id: str,
......@@ -255,44 +243,28 @@ class AgentHub:
else:
system_prompt = self._build_sub_agent_prompt(target_agent, context)
# 构建 messages 列表(支持 ReAct tool calling)
api_messages: list[dict[str, Any]] = [{"role": "system", "content": system_prompt}]
# 历史对话作为独立消息
# Bridge: convert SessionStore dict history → AgentScope Msg[]
agent_memory = InMemoryMemory()
recent = messages[-10:]
for msg in recent:
role = msg.get("role", "user")
if role not in ("user", "assistant"):
role = "user"
api_messages.append({"role": role, "content": msg.get("content", "")})
api_messages.append({"role": "user", "content": user_query})
tool_schemas = self.toolkit.get_json_schemas()
response_content, tools_called = await self._call_model(
api_messages,
tools=tool_schemas if tool_schemas else None,
history_msgs = [self._dict_to_msg(m) for m in recent]
if history_msgs:
await agent_memory.add(history_msgs)
# Create per-request ReActAgent with shared singletons
agent = ReActAgent(
name=target_agent,
sys_prompt=system_prompt,
model=self.model,
formatter=self.formatter,
toolkit=self.toolkit,
memory=agent_memory,
max_iters=10,
)
# 兜底:主Agent没调任何工具,但有可用子Agent → 强制程序化路由
fake_keywords = ["正在处理", "正在为您处理", "请稍等", "请稍候", "处理中"]
has_fake_processing = any(kw in response_content for kw in fake_keywords)
if (
target_agent == "main"
and not tools_called
and has_fake_processing
and allowed_agent_codes
):
# Find the first non-main sub-agent and route to it
sub_codes = [c for c in allowed_agent_codes if c != "main"]
if sub_codes:
sub_code = sub_codes[0]
logger.info("触发兜底路由: main未调工具 → 程序化路由到 %s", sub_code)
sub_result = await self._call_sub_agent(sub_code, user_query)
response_content = sub_result
target_agent = sub_code
routing_reason = "fallback_programmatic"
# Run ReAct loop via framework
user_msg = Msg("user", user_query, "user")
response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content()
# Store messages via SessionMemory
memory.add("user", user_query, agent_code=mentioned_agent_code or "main")
......@@ -319,105 +291,24 @@ class AgentHub:
"processing_time_ms": round(processing_time_ms, 2)
}
async def _call_model(
self,
messages: list[dict],
tools: Optional[list[dict]] = None,
max_iterations: int = 10,
) -> tuple[str, list[str]]:
"""Call the model via AgentScope OpenAIChatModel with ReAct tool-calling loop.
Returns:
(response_text, list_of_tool_names_called) — tool_names may be empty.
"""
current_messages = list(messages)
tools_called: list[str] = []
for iteration in range(max_iterations):
# Convert dicts to Msg objects, then format for the API
msgs = [self._dict_to_msg(m) for m in current_messages]
formatted = await self.formatter.format(msgs)
try:
if tools:
response = await self.model(formatted, tools=tools)
else:
response = await self.model(formatted)
except Exception as e:
raise AgentHubError(f"模型API请求失败: {e}")
# Parse ChatResponse content blocks
text_parts = []
tool_use_blocks = []
for block in (response.content or []):
if block.get("type") == "text":
text_parts.append(block.get("text", ""))
elif block.get("type") == "tool_use":
tool_use_blocks.append(block)
text_content = "\n".join(text_parts)
if not tool_use_blocks:
return text_content, tools_called
logger.info("ReAct 第%d轮 Tool调用: %s", iteration + 1, [tb["name"] for tb in tool_use_blocks])
# Tool calling: append assistant message with tool_calls
current_messages.append({
"role": "assistant",
"content": text_content,
"tool_calls": [
{
"id": tb["id"],
"type": "function",
"function": {
"name": tb["name"],
"arguments": json.dumps(tb["input"], ensure_ascii=False),
}
}
for tb in tool_use_blocks
],
})
# Execute tools and append results
for tb in tool_use_blocks:
tool_name = tb["name"]
tool_input = tb.get("input", {})
tools_called.append(tool_name)
# AgentScope call_tool_function receives ToolUseBlock (not dict)
tool_use_block = ToolUseBlock(
id=tb["id"],
name=tool_name,
input=tool_input,
)
tool_response_content = ""
resp = await self.toolkit.call_tool_function(tool_use_block)
tool_response_content = resp.content if hasattr(resp, 'content') else str(resp)
current_messages.append({
"role": "tool",
"tool_call_id": tb["id"],
"content": tool_response_content,
})
raise AgentHubError("ReAct循环超过最大次数(10)")
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""Call a sub-agent to handle a task, return its reasoning result."""
"""通过 ReActAgent 调用子 Agent。"""
if agent_code not in self.agents:
return f"错误:子 Agent '{agent_code}' 不存在"
sub_prompt = self._build_sub_agent_prompt(agent_code, {})
sub_messages: list[dict] = [{"role": "system", "content": sub_prompt}]
sub_messages.append({"role": "user", "content": instruction})
# Sub-agent gets coding tools (execute_python_code, execute_shell_command) + skill tools
tool_schemas = self.toolkit.get_json_schemas()
response, _ = await self._call_model(sub_messages, tools=tool_schemas if tool_schemas else None)
return response
sub_memory = InMemoryMemory()
sub_agent = ReActAgent(
name=agent_code,
sys_prompt=sub_prompt,
model=self.model,
formatter=self.formatter,
toolkit=self.toolkit,
memory=sub_memory,
max_iters=10,
)
response = await sub_agent.reply(Msg("user", instruction, "user"))
return response.get_text_content()
def _make_call_sub_agent_tool(self):
"""Create closure tool function for registration to Toolkit."""
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!