Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(agent): propagate cancellation after interruption cleanup (#2650)
HU_Qiruie92acef4e590
diff --git a/src/agentscope/agent/_agent.py b/src/agentscope/agent/_agent.pyindex b79267e25..e4a129fb8 100644--- a/src/agentscope/agent/_agent.py+++ b/src/agentscope/agent/_agent.py@@ -1200,14 +1200,8 @@ class Agent:yield evtif interrupted:- end_event = ReplyEndEvent(- session_id=self.state.session_id,- reply_id=self.state.reply_id,- finished_reason=(- ReplyFinishedReason.INTERRUPTED- ),- )- return+ # Handled by the CancelledError branch below+ raise asyncio.CancelledError()case Acting(tool_calls=tool_calls):made_progress = True@@ -1253,14 +1247,8 @@ class Agent:break_execution_for_interruption = Trueif break_execution_for_interruption:- end_event = ReplyEndEvent(- session_id=self.state.session_id,- reply_id=self.state.reply_id,- finished_reason=(- ReplyFinishedReason.INTERRUPTED- ),- )- return+ # Handled by the CancelledError branch below+ raise asyncio.CancelledError()if break_execution_for_hitl:breakdiff --git a/tests/agent_interrupt_test.py b/tests/agent_interrupt_test.pyindex 626842552..8da9b3de2 100644--- a/tests/agent_interrupt_test.py+++ b/tests/agent_interrupt_test.py@@ -17,7 +17,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom utils import AnyString, MockModel-from agentscope.agent import Agent, InjectionConfig+from agentscope.agent import Agent, InjectionConfig, ReActConfigfrom agentscope.event import (ReplyEndEvent,ToolResultStartEvent,@@ -296,7 +296,11 @@ def _assert_interrupted_end(class AgentInterruptCancelTest(IsolatedAsyncioTestCase):"""``task.cancel()`` lands during tool execution."""- def _make_agent(self, tools: list[ToolBase]) -> tuple[Agent, MockModel]:+ def _make_agent(+ self,+ tools: list[ToolBase],+ raise_cancelled_error: bool = False,+ ) -> tuple[Agent, MockModel]:model = MockModel(model="mock-model", stream=True)agent = Agent(name="Friday",@@ -307,9 +311,57 @@ class AgentInterruptCancelTest(IsolatedAsyncioTestCase):# agent_injection_test, turn it off to keep the assertions# focused.injection_config=InjectionConfig(inject_runtime_state=False),+ react_config=ReActConfig(+ interruption_raise_cancelled_error=raise_cancelled_error,+ ),)return agent, model+ async def test_cancelled_error_propagates_after_tool_cleanup(self) -> None:+ """With ``interruption_raise_cancelled_error`` the cancellation+ reaches the caller once the interrupted tool call is closed."""+ tool = _TimeoutSequentialTool()+ agent, model = self._make_agent([tool], raise_cancelled_error=True)+ model.set_responses(+ [+ [+ ChatResponse(+ content=[+ ToolCallBlock(+ id="tc-1",+ name=tool.name,+ input="{}",+ ),+ ],+ is_last=True,+ ),+ ],+ ],+ )+ events: list[Any] = []++ async def _drive() -> None:+ inputs = UserMsg(name="user", content="Hi")+ async for evt in agent.reply_stream(inputs):+ events.append(evt)++ task = asyncio.create_task(_drive())+ await asyncio.sleep(0.05)+ task.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await task++ _assert_interrupted_end(+ self,+ events,+ reply_id=agent.state.reply_id,+ session_id=agent.state.session_id,+ )+ self.assertListEqual(+ agent.state.get_unfinished_tool_calls(agent.name),+ [],+ )+async def test_sequential_tool_cancelled_mid_execution(self) -> None:"""Sequential batch: model emits one slow sequential tool call,``task.cancel()`` fires while it sleeps, the tool call is patcheddiff --git a/tests/service_agent_interrupt_test.py b/tests/service_agent_interrupt_test.pyindex 744c3c419..a8cfac6de 100644--- a/tests/service_agent_interrupt_test.py+++ b/tests/service_agent_interrupt_test.py@@ -24,7 +24,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom pydantic import BaseModelfrom utils import MockModel-from agentscope.agent import Agent+from agentscope.agent import Agent, ReActConfigfrom agentscope.formatter import OpenAIChatFormatterfrom agentscope.app._manager import (CancelDispatcher,@@ -47,6 +47,7 @@ class ServiceAgentInterruptTest(IsolatedAsyncioTestCase):async def _assert_chat_model_base_interruption(self,structured_schema: type[BaseModel] | None = None,+ raise_cancelled_error: bool = False,) -> None:"""A cancelled model call must terminate the reply as interrupted."""@@ -78,6 +79,9 @@ class ServiceAgentInterruptTest(IsolatedAsyncioTestCase):system_prompt="You are a test agent.",model=model,toolkit=Toolkit(),+ react_config=ReActConfig(+ interruption_raise_cancelled_error=raise_cancelled_error,+ ),)registry = ChatRunRegistry()end_events: list[ReplyEndEvent] = []@@ -96,16 +100,29 @@ class ServiceAgentInterruptTest(IsolatedAsyncioTestCase):)await asyncio.wait_for(model.call_started.wait(), timeout=1)task.cancel()- await asyncio.wait_for(task, timeout=1)+ try:+ await asyncio.wait_for(task, timeout=1)+ except asyncio.CancelledError:+ if not raise_cancelled_error:+ raiseself.assertEqual(model.call_count, 1)self.assertEqual(len(end_events), 1)self.assertEqual(end_events[0].finished_reason, "interrupted")+ self.assertEqual(task.cancelled(), raise_cancelled_error)async def test_chat_model_base_interruption(self) -> None:"""ChatModelBase cancellation is reported as interrupted."""await self._assert_chat_model_base_interruption()+ async def test_chat_model_base_interruption_propagates_when_configured(+ self,+ ) -> None:+ """Configured cancellation propagates after terminal events."""+ await self._assert_chat_model_base_interruption(+ raise_cancelled_error=True,+ )+async def test_chat_model_base_interruption_with_structured_schema(self,) -> None: