Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
refactor(agent): refactor the structured output logic within the `ReActAgent` class (#910)
qbc23fb3c8b6403
diff --git a/src/agentscope/agent/_react_agent.py b/src/agentscope/agent/_react_agent.pyindex 07cbd3605..2e43c7f40 100644--- a/src/agentscope/agent/_react_agent.py+++ b/src/agentscope/agent/_react_agent.py@@ -5,7 +5,6 @@import asynciofrom typing import Type, Any, AsyncGenerator, Literal-import shortuuidfrom pydantic import BaseModel, ValidationError, Fieldfrom ._react_agent_base import ReActAgentBase@@ -30,40 +29,6 @@ class _QueryRewriteModel(BaseModel):)-def finish_function_pre_print_hook(- self: "ReActAgent",- kwargs: dict[str, Any],-) -> dict[str, Any] | None:- """A pre-speak hook function that check if finish_function is called. If- so, it will wrap the response argument into a message and return it to- replace the original message. By this way, the calling of the finish- function will be displayed as a text reply instead of a tool call."""-- msg = kwargs["msg"]-- if isinstance(msg.content, str):- return None-- if isinstance(msg.content, list):- for i, block in enumerate(msg.content):- if (- block["type"] == "tool_use"- and block["name"] == self.finish_function_name- ):- # Convert the response argument into a text block for- # displaying- try:- msg.content[i] = TextBlock(- type="text",- text=block["input"].get("response", ""),- )- return kwargs- except Exception:- print("Error in block input", block["input"])-- return None--class ReActAgent(ReActAgentBase):"""A ReAct agent implementation in AgentScope, which supports@@ -74,8 +39,8 @@ class ReActAgent(ReActAgentBase):"""finish_function_name: str = "generate_response"- """The function name used to finish replying and return a response to- the user."""+ """The name of the function used to generate structured output. Only+ registered when structured output model is provided in the reply call."""def __init__(self,@@ -192,9 +157,6 @@ class ReActAgent(ReActAgentBase):# -------------- Tool management --------------# If None, a default Toolkit will be createdself.toolkit = toolkit or Toolkit()- self.toolkit.register_tool_function(- getattr(self, self.finish_function_name),- )if self._agent_control:# Adding two tool functions into the toolkit to allow self-controlself.toolkit.register_tool_function(@@ -266,19 +228,13 @@ class ReActAgent(ReActAgentBase):self.register_state("name")self.register_state("_sys_prompt")- self.register_instance_hook(- "pre_print",- "finish_function_pre_print_hook",- finish_function_pre_print_hook,- )-@propertydef sys_prompt(self) -> str:"""The dynamic system prompt of the agent."""return self._sys_prompt@trace_reply- async def reply(+ async def reply( # pylint: disable=too-many-branchesself,msg: Msg | list[Msg] | None = None,structured_model: Type[BaseModel] | None = None,@@ -300,49 +256,120 @@ class ReActAgent(ReActAgentBase):# Record the input message(s) in the memoryawait self.memory.add(msg)+ # -------------- Retrieval process --------------# Retrieve relevant records from the long-term memory if activatedawait self._retrieve_from_long_term_memory(msg)# Retrieve relevant documents from the knowledge base(s) if anyawait self._retrieve_from_knowledge(msg)+ # -------------- Structured output management --------------self._required_structured_model = structured_model# Record structured output model if providedif structured_model:+ # Register generate_response tool only when structured output+ # is required+ if self.finish_function_name not in self.toolkit.tools:+ self.toolkit.register_tool_function(+ getattr(self, self.finish_function_name),+ )++ # Set the structured output modelself.toolkit.set_extended_model(self.finish_function_name,structured_model,)-- # The reasoning-acting loop- reply_msg = None+ else:+ # Remove generate_response tool if no structured output is required+ self.toolkit.remove_tool_function(self.finish_function_name)++ # -------------- The reasoning-acting loop --------------+ # Control if LLM generates tool calls in each reasoning step+ tool_choice = None+ # Cache the structured output generated in the finish function call+ structured_output = Nonefor _ in range(self.max_iters):- msg_reasoning = await self._reasoning()+ # -------------- The reasoning process --------------+ msg_reasoning = await self._reasoning(tool_choice)+ # -------------- The acting process --------------futures = [self._acting(tool_call)for tool_call in msg_reasoning.get_content_blocks("tool_use",)]-# Parallel tool calls or notif self.parallel_tool_calls:- acting_responses = await asyncio.gather(*futures)-+ structured_outputs = await asyncio.gather(*futures)else:# Sequential tool calls- acting_responses = [await _ for _ in futures]+ structured_outputs = [await _ for _ in futures]++ # -------------- Check for exit condition --------------+ # If structured output is still not satisfied+ if self._required_structured_model:+ # Remove None results+ structured_outputs = [_ for _ in structured_outputs if _]++ msg_hint = None+ # If the acting step generates structured outputs+ if structured_outputs:+ # Cache the structured output data+ structured_output = structured_outputs[-1]++ # Prepare textual response+ if msg_reasoning.has_content_blocks("text"):+ # Re-use the existing text response if any to avoid+ # duplicate text generation+ return Msg(+ self.name,+ msg_reasoning.get_content_blocks("text"),+ "assistant",+ metadata=structured_output,+ )++ # Generate a textual response in the next iteration+ msg_hint = Msg(+ "user",+ "<system-hint>Now generate a text "+ "response based on your current situation"+ "</system-hint>",+ "user",+ )+ await self._reasoning_hint_msgs.add(msg_hint)++ # Just generate text response in the next reasoning step+ tool_choice = "none"+ # The structured output is generated successfully+ self._required_structured_model = None++ elif not msg_reasoning.has_content_blocks("tool_use"):+ # If structured output is required but no tool call is+ # made, remind the llm to go on the task+ msg_hint = Msg(+ "user",+ "<system-hint>Structured output is "+ f"required, go on to finish your task or call "+ f"'{self.finish_function_name}' to generate the "+ f"required structured output.</system-hint>",+ "user",+ )+ await self._reasoning_hint_msgs.add(msg_hint)+ # Require tool call in the next reasoning step+ tool_choice = "required"- # Find the first non-None replying message from the acting- for acting_msg in acting_responses:- reply_msg = reply_msg or acting_msg+ if msg_hint and self.print_hint_msg:+ await self.print(msg_hint)- if reply_msg:- break+ elif not msg_reasoning.has_content_blocks("tool_use"):+ # Exit the loop when no structured output is required (or+ # already satisfied) and only text response is generated+ msg_reasoning.metadata = structured_output+ return msg_reasoning# When the maximum iterations are reached- if reply_msg is None:- reply_msg = await self._summarizing()+ reply_msg = await self._summarizing()+ reply_msg.metadata = structured_output# Post-process the memory, long-term memoryif self._static_control:@@ -359,6 +386,7 @@ class ReActAgent(ReActAgentBase):async def _reasoning(self,+ tool_choice: Literal["auto", "none", "any", "required"] | None = None,) -> Msg:"""Perform the reasoning process."""if self.plan_notebook:@@ -383,6 +411,7 @@ class ReActAgent(ReActAgentBase):res = await self.model(prompt,tools=self.toolkit.get_json_schemas(),+ tool_choice=tool_choice,)# handle output from the model@@ -409,19 +438,6 @@ class ReActAgent(ReActAgentBase):raise e from Nonefinally:- if msg and not msg.has_content_blocks("tool_use"):- # Turn plain text response into a tool call of the finish- # function- msg = Msg.from_dict(msg.to_dict())- msg.content = [- ToolUseBlock(- id=shortuuid.uuid(),- type="tool_use",- name=self.finish_function_name,- input={"response": msg.get_text_content()},- ),- ]-# None will be ignored by the memoryawait self.memory.add(msg)@@ -449,17 +465,18 @@ class ReActAgent(ReActAgentBase):await self.print(msg_res, True)return msg- async def _acting(self, tool_call: ToolUseBlock) -> Msg | None:- """Perform the acting process.+ async def _acting(self, tool_call: ToolUseBlock) -> dict | None:+ """Perform the acting process, and return the structured output if+ it's generated and verified in the finish function call.Args:tool_call (`ToolUseBlock`):The tool use block to be executed.Returns:- `Union[Msg, None]`:- Return a message to the user if the `finish_function` is- called, otherwise return `None`.+ `Union[dict, None]`:+ Return the structured output if it's verified in the finish+ function call, otherwise return None."""tool_res_msg = Msg(@@ -478,7 +495,6 @@ class ReActAgent(ReActAgentBase):# Execute the tool calltool_res = await self.toolkit.call_tool_function(tool_call)- response_msg = None# Async generator handlingasync for chunk in tool_res:# Turn into a tool result block@@ -486,16 +502,7 @@ class ReActAgent(ReActAgentBase):"output"] = chunk.content- # Skip the printing of the finish function call- if (- tool_call["name"] != self.finish_function_name- or tool_call["name"] == self.finish_function_name- and (- chunk.metadata is None- or not chunk.metadata.get("success")- )- ):- await self.print(tool_res_msg, chunk.is_last)+ await self.print(tool_res_msg, chunk.is_last)# Raise the CancelledError to handle the interruption in the# handle_interrupt function@@ -506,14 +513,12 @@ class ReActAgent(ReActAgentBase):if (tool_call["name"] == self.finish_function_nameand chunk.metadata- and chunk.metadata.get(- "success",- True,- )+ and chunk.metadata.get("success", False)):- response_msg = chunk.metadata.get("response_msg")+ # Only return the structured output+ return chunk.metadata.get("structured_output")- return response_msg+ return Nonefinally:# Record the tool result message in the memory@@ -588,29 +593,19 @@ class ReActAgent(ReActAgentBase):def generate_response(self,- response: str,**kwargs: Any,) -> ToolResponse:- """Generate a response. Note only the input argument `response` is- visible to the others, you should include all the necessary- information in the `response` argument.-- Args:- response (`str`):- Your response to the user."""- response_msg = Msg(- self.name,- response,- "assistant",- )+ Generate required structured output by this function and return it+ """+ structured_output = None# Prepare structured outputif self._required_structured_model:try:# Use the metadata field of the message to store the# structured output- response_msg.metadata = (+ structured_output = (self._required_structured_model.model_validate(kwargs,).model_dump()@@ -626,9 +621,14 @@ class ReActAgent(ReActAgentBase):],metadata={"success": False,- "response_msg": None,+ "structured_output": {},},)+ else:+ logger.warning(+ "The generate_response function is called when no structured "+ "output model is required.",+ )return ToolResponse(content=[@@ -639,7 +639,7 @@ class ReActAgent(ReActAgentBase):],metadata={"success": True,- "response_msg": response_msg,+ "structured_output": structured_output,},is_last=True,)diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex 41ea795f7..d7eb7beb0 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -354,18 +354,24 @@ class Toolkit(StateModule):self.tools[func_name] = func_obj- def remove_tool_function(self, tool_name: str) -> None:+ def remove_tool_function(+ self,+ tool_name: str,+ allow_not_exist: bool = True,+ ) -> None:"""Remove tool function from the toolkit by its name.Args:tool_name (`str`):The name of the tool function to be removed.+ allow_not_exist (`bool`):+ Allow the tool function to not exist when removing."""- if tool_name not in self.tools:- logger.warning(- "Skipping removing tool function '%s' as it does not exist.",- tool_name,+ if tool_name not in self.tools and not allow_not_exist:+ raise ValueError(+ f"Tool function '{tool_name}' does not exist in the "+ "toolkit.",)self.tools.pop(tool_name, None)diff --git a/tests/react_agent_test.py b/tests/react_agent_test.pyindex 2730db00b..5fe00af4f 100644--- a/tests/react_agent_test.py+++ b/tests/react_agent_test.py@@ -3,6 +3,8 @@from typing import Anyfrom unittest import IsolatedAsyncioTestCase+from pydantic import BaseModel, Field+from agentscope.agent import ReActAgentfrom agentscope.formatter import DashScopeChatFormatterfrom agentscope.memory import InMemoryMemory@@ -17,7 +19,22 @@ class MyModel(ChatModelBase):def __init__(self) -> None:"""Initialize the test model."""super().__init__("test_model", stream=False)- self.fake_content = [TextBlock(type="text", text="123")]+ self.cnt = 1+ self.fake_content_1 = [+ TextBlock(+ type="text",+ text="123",+ ),+ ]+ self.fake_content_2 = [+ TextBlock(type="text", text="456"),+ ToolUseBlock(+ type="tool_use",+ name="generate_response",+ id="xx",+ input={"result": "789"},+ ),+ ]async def __call__(self,@@ -25,9 +42,15 @@ class MyModel(ChatModelBase):**kwargs: Any,) -> ChatResponse:"""Mock model call."""- return ChatResponse(- content=self.fake_content,- )+ self.cnt += 1+ if self.cnt == 2:+ return ChatResponse(+ content=self.fake_content_1,+ )+ else:+ return ChatResponse(+ content=self.fake_content_2,+ )async def pre_reasoning_hook(self: ReActAgent, _kwargs: Any) -> None:@@ -118,25 +141,26 @@ class ReActAgentTest(IsolatedAsyncioTestCase):getattr(agent, "cnt_post_reasoning"),1,)- self.assertEqual(- getattr(agent, "cnt_pre_acting"),- 1,+ # Note: pre_acting and post_acting hooks are not called when model+ # returns plain text without structured output, as plain text is not+ # converted to tool call in this case+ self.assertFalse(+ hasattr(agent, "cnt_pre_acting"),+ "pre_acting hook should not be called for plain text response",)- self.assertEqual(- getattr(agent, "cnt_post_acting"),- 1,+ self.assertFalse(+ hasattr(agent, "cnt_post_acting"),+ "post_acting hook should not be called for plain text response",)- model.fake_content = [- ToolUseBlock(- type="tool_use",- name=agent.finish_function_name,- id="xx",- input={"response": "123"},- ),- ]+ # Test with structured output: generate_response should be registered+ # and visible in tool list+ class TestStructuredModel(BaseModel):+ """Test structured model."""- await agent()+ result: str = Field(description="Test result field.")++ await agent(structured_model=TestStructuredModel)self.assertEqual(getattr(agent, "cnt_pre_reasoning"),2,@@ -145,11 +169,23 @@ class ReActAgentTest(IsolatedAsyncioTestCase):getattr(agent, "cnt_post_reasoning"),2,)+ # pre_acting and post_acting hooks are called only when model returns+ # tool calls (not plain text). With structured_model, generate_response+ # is registered and model can call it.self.assertEqual(getattr(agent, "cnt_pre_acting"),- 2,+ 1, # Only called once (second call with tool use))self.assertEqual(getattr(agent, "cnt_post_acting"),- 2,+ 1, # Only called once (second call with tool use)+ )++ # Verify that generate_response is removed when no structured_model+ # Reset model to return plain text+ model.fake_content_2 = [TextBlock(type="text", text="456")]+ await agent()+ self.assertFalse(+ agent.finish_function_name in agent.toolkit.tools,+ "generate_response should be removed when no structured_model",)