Commit 42257254 by sunqi02

refactor: simplify _dict_to_msg, remove tool_calls/tool result conversion

ReActAgent manages tool calling lifecycle internally. SessionStore only
stores user/assistant text dialogue — tool messages are transient ReAct state.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 7ff0fda3
...@@ -11,8 +11,9 @@ from app.service.memory import SessionMemory ...@@ -11,8 +11,9 @@ from app.service.memory import SessionMemory
from agentscope.model import OpenAIChatModel from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg from agentscope.message import Msg
from agentscope.message._message_block import TextBlock, ToolUseBlock, ToolResultBlock from agentscope.message._message_block import TextBlock, ToolUseBlock
from agentscope.tool._response import ToolResponse from agentscope.tool._response import ToolResponse
from agentscope.tool import execute_python_code, execute_shell_command
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
...@@ -79,6 +80,16 @@ class AgentHub: ...@@ -79,6 +80,16 @@ class AgentHub:
# Load skills metadata from Toolkit # Load skills metadata from Toolkit
self.skills = config_loader.load_skills_from_toolkit(self.toolkit) self.skills = config_loader.load_skills_from_toolkit(self.toolkit)
# Register built-in coding tools (shared by all agents)
self.toolkit.register_tool_function(
execute_python_code,
group_name="basic",
)
self.toolkit.register_tool_function(
execute_shell_command,
group_name="basic",
)
# Register call_sub_agent as a tool for serial chain collaboration # Register call_sub_agent as a tool for serial chain collaboration
call_sub = self._make_call_sub_agent_tool() call_sub = self._make_call_sub_agent_tool()
self.toolkit.register_tool_function( self.toolkit.register_tool_function(
...@@ -87,19 +98,26 @@ class AgentHub: ...@@ -87,19 +98,26 @@ class AgentHub:
group_name="basic", group_name="basic",
) )
def _build_main_prompt(self, context: Dict[str, Any]) -> str: def _build_main_prompt(
self,
context: Dict[str, Any],
allowed_agent_codes: Optional[list] = None,
) -> str:
""" """
Build the main agent's prompt including ALL sub-agent duty descriptions. Build the main agent's prompt including sub-agent duty descriptions.
The main agent uses this to judge intent and decide whether to route. When allowed_agent_codes is set, only agents in that list are advertised.
""" """
main_agent = self.agents.get("main") main_agent = self.agents.get("main")
if not main_agent: if not main_agent:
raise AgentHubError("主 Agent 配置未找到") raise AgentHubError("主 Agent 配置未找到")
# Collect duties from sub-agents (all except main) # Collect duties from sub-agents, filtered by position if applicable
duty_lines = [] duty_lines = []
for code, agent in self.agents.items(): for code, agent in self.agents.items():
if code != "main": if code == "main":
continue
if allowed_agent_codes is not None and code not in allowed_agent_codes:
continue
duty_lines.append(f"- {agent.name}({agent.role}): {agent.prompt_template}") duty_lines.append(f"- {agent.name}({agent.role}): {agent.prompt_template}")
duties_text = "\n".join(duty_lines) if duty_lines else "暂无子Agent" duties_text = "\n".join(duty_lines) if duty_lines else "暂无子Agent"
...@@ -117,14 +135,11 @@ class AgentHub: ...@@ -117,14 +135,11 @@ class AgentHub:
) )
review_guide = """ review_guide = """
## 工作规则 ## 收到子Agent返回后
收到子Agent的返回后,你需要判断:
1. 子Agent的结果是否完整、可用? 1. 判断结果是否完整,是否还需要其他子Agent协作
2. 是否还需要其他子Agent协作?(如:纪要整理后需要提取待办) 2. 如果已经可以回复,整合所有结果用自然语言回复用户
3. 是否可以直接整合结果回复用户? 3. 不要再调用同一个子Agent重复处理
如果还需要继续处理,调用相应的子Agent(call_sub_agent)或工具。
如果已经可以回复,请整合所有结果,用自然语言回复用户。
""" """
return prompt + review_guide return prompt + review_guide
...@@ -157,45 +172,11 @@ class AgentHub: ...@@ -157,45 +172,11 @@ class AgentHub:
return prompt return prompt
def _dict_to_msg(self, m: dict) -> Msg: def _dict_to_msg(self, m: dict) -> Msg:
"""Convert a chat completion API dict to a Msg object for the formatter.""" """SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
role = m.get("role", "user") role = m.get("role", "user")
if role not in ("user", "assistant", "system"):
role = "user"
content = m.get("content", "") content = m.get("content", "")
# Handle assistant messages with tool_calls
tool_calls = m.get("tool_calls")
if role == "assistant" and tool_calls:
blocks = []
if content:
blocks.append(TextBlock(type="text", text=content))
for tc in tool_calls:
func = tc["function"]
try:
args = json.loads(func["arguments"])
except (json.JSONDecodeError, KeyError):
args = {}
blocks.append(ToolUseBlock(
type="tool_use",
id=tc["id"],
name=func["name"],
input=args,
))
return Msg(name=role, role=role, content=blocks)
# Handle tool result messages (role="tool")
if role == "tool":
return Msg(
name="tool",
role="user", # Carrier role; formatter emits correct role="tool" for ToolResultBlock
content=[
ToolResultBlock(
type="tool_result",
id=m.get("tool_call_id", ""),
name="",
output=m.get("content", ""),
)
],
)
return Msg(name=role, role=role, content=content) return Msg(name=role, role=role, content=content)
def _build_history_section(self, messages: List) -> str: def _build_history_section(self, messages: List) -> str:
...@@ -219,7 +200,8 @@ class AgentHub: ...@@ -219,7 +200,8 @@ class AgentHub:
user_query: str, user_query: str,
mentioned_agent_code: Optional[str] = None, mentioned_agent_code: Optional[str] = None,
channel: str = "wechat_group", channel: str = "wechat_group",
file_url: Optional[str] = None file_url: Optional[str] = None,
allowed_agent_codes: Optional[list] = None,
) -> Dict[str, Any]: ) -> Dict[str, Any]:
""" """
Process a user message end-to-end. Process a user message end-to-end.
...@@ -250,10 +232,20 @@ class AgentHub: ...@@ -250,10 +232,20 @@ class AgentHub:
messages = memory.get_messages(max_rounds=10) messages = memory.get_messages(max_rounds=10)
# Determine target agent and routing reason # Determine target agent and routing reason
position_restricted = allowed_agent_codes is not None
if mentioned_agent_code and mentioned_agent_code in self.agents: if mentioned_agent_code and mentioned_agent_code in self.agents:
if position_restricted and mentioned_agent_code not in allowed_agent_codes:
target_agent = "main"
routing_reason = "position_restricted"
else:
target_agent = mentioned_agent_code target_agent = mentioned_agent_code
routing_reason = "mention" routing_reason = "mention"
elif session.current_agent_code and session.current_agent_code in self.agents: elif session.current_agent_code and session.current_agent_code in self.agents:
if position_restricted and session.current_agent_code not in allowed_agent_codes:
target_agent = "main"
routing_reason = "position_restricted"
else:
target_agent = session.current_agent_code target_agent = session.current_agent_code
routing_reason = "inheritance" routing_reason = "inheritance"
else: else:
...@@ -267,9 +259,15 @@ class AgentHub: ...@@ -267,9 +259,15 @@ class AgentHub:
"user_id": user_id "user_id": user_id
} }
logger.debug(
"路由决策: target=%s reason=%s position_restricted=%s allowed=%s",
target_agent, routing_reason,
allowed_agent_codes is not None, allowed_agent_codes,
)
# Build prompt based on target agent # Build prompt based on target agent
if target_agent == "main": if target_agent == "main":
system_prompt = self._build_main_prompt(context) system_prompt = self._build_main_prompt(context, allowed_agent_codes=allowed_agent_codes)
else: else:
system_prompt = self._build_sub_agent_prompt(target_agent, context) system_prompt = self._build_sub_agent_prompt(target_agent, context)
...@@ -287,11 +285,31 @@ class AgentHub: ...@@ -287,11 +285,31 @@ class AgentHub:
api_messages.append({"role": "user", "content": user_query}) api_messages.append({"role": "user", "content": user_query})
tool_schemas = self.toolkit.get_json_schemas() tool_schemas = self.toolkit.get_json_schemas()
response_content = await self._call_model( response_content, tools_called = await self._call_model(
api_messages, api_messages,
tools=tool_schemas if tool_schemas else None, tools=tool_schemas if tool_schemas else None,
) )
# 兜底:主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"
# Store messages via SessionMemory # Store messages via SessionMemory
memory.add("user", user_query, agent_code=mentioned_agent_code or "main") memory.add("user", user_query, agent_code=mentioned_agent_code or "main")
memory.add("assistant", response_content, agent_code=target_agent) memory.add("assistant", response_content, agent_code=target_agent)
...@@ -322,9 +340,14 @@ class AgentHub: ...@@ -322,9 +340,14 @@ class AgentHub:
messages: list[dict], messages: list[dict],
tools: Optional[list[dict]] = None, tools: Optional[list[dict]] = None,
max_iterations: int = 10, max_iterations: int = 10,
) -> str: ) -> tuple[str, list[str]]:
"""Call the model via AgentScope OpenAIChatModel with ReAct tool-calling loop.""" """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) current_messages = list(messages)
tools_called: list[str] = []
for iteration in range(max_iterations): for iteration in range(max_iterations):
# Convert dicts to Msg objects, then format for the API # Convert dicts to Msg objects, then format for the API
...@@ -351,7 +374,9 @@ class AgentHub: ...@@ -351,7 +374,9 @@ class AgentHub:
text_content = "\n".join(text_parts) text_content = "\n".join(text_parts)
if not tool_use_blocks: if not tool_use_blocks:
return text_content 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 # Tool calling: append assistant message with tool_calls
current_messages.append({ current_messages.append({
...@@ -374,6 +399,7 @@ class AgentHub: ...@@ -374,6 +399,7 @@ class AgentHub:
for tb in tool_use_blocks: for tb in tool_use_blocks:
tool_name = tb["name"] tool_name = tb["name"]
tool_input = tb.get("input", {}) tool_input = tb.get("input", {})
tools_called.append(tool_name)
# AgentScope call_tool_function receives ToolUseBlock (not dict) # AgentScope call_tool_function receives ToolUseBlock (not dict)
tool_use_block = ToolUseBlock( tool_use_block = ToolUseBlock(
...@@ -403,8 +429,9 @@ class AgentHub: ...@@ -403,8 +429,9 @@ class AgentHub:
sub_messages: list[dict] = [{"role": "system", "content": sub_prompt}] sub_messages: list[dict] = [{"role": "system", "content": sub_prompt}]
sub_messages.append({"role": "user", "content": instruction}) sub_messages.append({"role": "user", "content": instruction})
# Sub-agent uses pure text reasoning (no tools), single iteration # Sub-agent gets coding tools (execute_python_code, execute_shell_command) + skill tools
response = await self._call_model(sub_messages, tools=None, max_iterations=1) tool_schemas = self.toolkit.get_json_schemas()
response, _ = await self._call_model(sub_messages, tools=tool_schemas if tool_schemas else None)
return response return response
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!