Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(agent): generate a final text summary after reaching max iterations (#2443)
qbc6c5c9eedb0a1
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex de04813d5..06ef01479 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -3404,17 +3404,69 @@ class Agent:# The last reasoning produced a text-only final messageif final_msg is not None:+ # In the normal flow, ``cur_iter == max_iters + 1`` here means+ # this text came from the one forced finalization call.+ exceeded_max_iters = (+ self.state.cur_iter > self.react_config.max_iters+ )+ finished_reason = (+ ReplyFinishedReason.EXCEED_MAX_ITERS+ if exceeded_max_iters+ else ReplyFinishedReason.COMPLETED+ )+ exit_events: list[AgentEvent] = []++ if exceeded_max_iters:+ logger.warning(+ "Agent %s exceeds the max iteration numbers %d. "+ "Stop the react loop.",+ self.name,+ self.react_config.max_iters,+ )+ final_msg.finished_reason = finished_reason+ # Deprecated but still emitted for backward compatibility;+ # suppressed since the warning targets consumers+ with warnings.catch_warnings():+ warnings.simplefilter("ignore", DeprecationWarning)+ exit_events.append(+ ExceedMaxItersEvent(+ reply_id=self.state.reply_id,+ name=self.name,+ ),+ )++ exit_events.append(+ ReplyEndEvent(+ session_id=self.state.session_id,+ reply_id=self.state.reply_id,+ finished_reason=finished_reason,+ ),+ )return Exit(- exit_events=[- ReplyEndEvent(- session_id=self.state.session_id,- reply_id=self.state.reply_id,- finished_reason=ReplyFinishedReason.COMPLETED,- ),- ],+ exit_events=exit_events,exit_msg=final_msg,)+ # At equality, the regular iteration budget is exhausted, but the+ # one forced finalization call has not run yet.+ if self.state.cur_iter == self.react_config.max_iters:+ return Reasoning(+ hint=HintBlock(+ hint=(+ f"<system-reminder>You have reached the maximum of "+ f"{self.react_config.max_iters} reasoning-acting "+ f"iterations. Summarize the work and findings so far "+ f"and return the final answer as text. Do not call "+ f"any tools.</system-reminder>"+ ),+ source='{"label": "System", "sublabel": '+ '"Max Iterations Reached"}',+ ),+ tool_choice=ToolChoice(mode="none"),+ )++ # Equality returned above, so reaching this check means the forced+ # finalization call also failed to produce a final message.if self.state.cur_iter >= self.react_config.max_iters:logger.warning("Agent %s exceeds the max iteration numbers %d. "diff --git a/tests/agent_basic_test.py b/tests/agent_basic_test.pyindex 383653c7e..61f708e88 100644--- a/tests/agent_basic_test.py+++ b/tests/agent_basic_test.py@@ -981,6 +981,129 @@ class AgentBasicTest(IsolatedAsyncioTestCase):context_dicts = [msg.model_dump() for msg in self.agent.state.context]self.assertListEqual(context_dicts, expected_context)+ async def test_last_thinking_only_response_forces_final_text(self) -> None:+ """A final thinking-only round gets one text-only model call."""+ received_tool_choices: list = []++ class TrackingModel(MockModel):+ """A mock model that records tool choice arguments."""++ async def _call_api(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> ChatResponse:+ """Record the tool choice and return the next response."""+ received_tool_choices.append(kwargs.get("tool_choice"))+ return await super()._call_api(*args, **kwargs)++ model = TrackingModel()+ model.set_responses(+ [+ ChatResponse(+ content=[ThinkingBlock(thinking="Working on it")],+ is_last=True,+ ),+ ChatResponse(+ content=[TextBlock(text="Final summary")],+ is_last=True,+ ),+ ],+ )+ agent = Agent(+ name="Friday",+ system_prompt="You are a helpful assistant.",+ model=model,+ toolkit=Toolkit(),+ injection_config=InjectionConfig(inject_runtime_state=False),+ react_config=ReActConfig(max_iters=1),+ )++ items = []+ async for item in agent.reply_stream(+ UserMsg(name="user", content="Think"),+ yield_final_msg=True,+ ):+ items.append(item)+ msg = items[-1]++ self.assertEqual(model.cnt, 2)+ self.assertEqual(agent.state.cur_iter, 2)+ self.assertEqual(received_tool_choices[0], None)+ self.assertEqual(received_tool_choices[1].mode, "none")+ event_base = self._get_event_base(agent.state.reply_id)+ self.assertListEqual(+ [item.model_dump() for item in items[-3:-1]],+ [+ {+ **event_base,+ "type": "EXCEED_MAX_ITERS",+ "name": "Friday",+ },+ {+ **event_base,+ "type": "REPLY_END",+ "error": None,+ "session_id": agent.state.session_id,+ "finished_reason": (ReplyFinishedReason.EXCEED_MAX_ITERS),+ },+ ],+ )+ self.assertDictEqual(+ msg.model_dump(),+ {+ **self._get_msg_base(),+ "finished_reason": ReplyFinishedReason.EXCEED_MAX_ITERS,+ "content": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "Final summary",+ },+ ],+ },+ )++ async def test_forced_final_text_call_is_bounded(self) -> None:+ """The forced final text call runs at most once."""+ self.agent.react_config = ReActConfig(max_iters=1)+ self.model.set_responses(+ [+ ChatResponse(+ content=[ThinkingBlock(thinking="First thought")],+ is_last=True,+ ),+ ChatResponse(+ content=[ThinkingBlock(thinking="Second thought")],+ is_last=True,+ ),+ ],+ )++ msg = await self.agent.reply(UserMsg(name="user", content="Think"))++ self.assertEqual(self.model.cnt, 2)+ self.assertEqual(self.agent.state.cur_iter, 2)+ self.assertDictEqual(+ msg.model_dump(),+ {+ **self._get_msg_base(),+ "finished_reason": ReplyFinishedReason.EXCEED_MAX_ITERS,+ "content": [+ {+ "type": "text",+ "created_at": AnyString(),+ "finished_at": None,+ "id": AnyString(),+ "text": "The maximum reasoning-acting iterations "+ "are exceeded.",+ },+ ],+ },+ )+async def test_streaming_sequential_tool_calls(self) -> None:"""Test the streaming model inference with tool calls generated.