Skip to content

Build and run agents you can see, understand and trust.

fix(model): preserve interrupted response reason (#2209)

logicwu00cd19d7dabe9
diff --git a/src/agentscope/model/_model_response.py b/src/agentscope/model/_model_response.py
index aa29902ce..a7b68450c 100644
--- a/src/agentscope/model/_model_response.py
+++ b/src/agentscope/model/_model_response.py
@@ -56,7 +56,7 @@ class ChatResponse(DictMixin):
"""The usage information of the chat response, if available."""
finished_reason: FinishedReason = field(
- default=FinishedReason.COMPLETED,
+ default_factory=lambda: FinishedReason.COMPLETED,
)
"""The finished reason of the chat response, available when `is_last`
is `True`."""
diff --git a/tests/model_response_test.py b/tests/model_response_test.py
index a9631c843..3f394a7bd 100644
--- a/tests/model_response_test.py
+++ b/tests/model_response_test.py
@@ -53,6 +53,23 @@ class ChatResponseAppendTest(IsolatedAsyncioTestCase):
async def asyncSetUp(self) -> None:
"""The async setup method."""
+ async def test_finished_reason_attribute_matches_mapping(self) -> None:
+ """Attribute access must return the explicitly provided reason."""
+ response = ChatResponse(
+ content=[],
+ is_last=True,
+ finished_reason=FinishedReason.INTERRUPTED,
+ )
+
+ self.assertEqual(
+ response.finished_reason,
+ response["finished_reason"],
+ )
+ self.assertEqual(
+ response.finished_reason,
+ FinishedReason.INTERRUPTED,
+ )
+
# ------------------------------------------------------------------
# append_text
# ------------------------------------------------------------------
diff --git a/tests/service_agent_interrupt_test.py b/tests/service_agent_interrupt_test.py
index 6d1ba41f2..9ae44fddd 100644
--- a/tests/service_agent_interrupt_test.py
+++ b/tests/service_agent_interrupt_test.py
@@ -21,6 +21,9 @@ import asyncio
from typing import Any
from unittest.async_case import IsolatedAsyncioTestCase
+from pydantic import BaseModel
+from utils import MockModel
+
from agentscope.agent import Agent
from agentscope.app._manager import (
CancelDispatcher,
@@ -40,6 +43,80 @@ from agentscope.tool import Toolkit
class ServiceAgentInterruptTest(IsolatedAsyncioTestCase):
"""Service-layer interrupt plumbing tests."""
+ async def _assert_chat_model_base_interruption(
+ self,
+ structured_schema: type[BaseModel] | None = None,
+ ) -> None:
+ """A cancelled model call must terminate the reply as interrupted."""
+
+ class InterruptibleModel(MockModel):
+ """ChatModelBase implementation that blocks on its first call."""
+
+ def __init__(self) -> None:
+ super().__init__(stream=False)
+ self.call_started = asyncio.Event()
+ self.call_count = 0
+
+ async def _call_api(
+ self,
+ *_args: Any,
+ **_kwargs: Any,
+ ) -> ChatResponse:
+ self.call_count += 1
+ if self.call_count > 1:
+ raise AssertionError(
+ "Interrupted reply made another model call",
+ )
+ self.call_started.set()
+ await asyncio.Event().wait()
+ raise AssertionError("Unreachable")
+
+ model = InterruptibleModel()
+ agent = Agent(
+ name="InterruptibleAgent",
+ system_prompt="You are a test agent.",
+ model=model,
+ toolkit=Toolkit(),
+ )
+ registry = ChatRunRegistry()
+ end_events: list[ReplyEndEvent] = []
+
+ async def _chat_run() -> None:
+ async for event in agent.reply_stream(
+ UserMsg(name="user", content="Hello"),
+ structured_schema=structured_schema,
+ ):
+ if isinstance(event, ReplyEndEvent):
+ end_events.append(event)
+
+ task = registry.spawn(
+ _chat_run(),
+ session_id="chat-model-base-interruption",
+ )
+ await asyncio.wait_for(model.call_started.wait(), timeout=1)
+ task.cancel()
+ await asyncio.wait_for(task, timeout=1)
+
+ self.assertEqual(model.call_count, 1)
+ self.assertEqual(len(end_events), 1)
+ self.assertEqual(end_events[0].finished_reason, "interrupted")
+
+ 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_with_structured_schema(
+ self,
+ ) -> None:
+ """Structured output must not retry an interrupted model call."""
+
+ class StructuredOutput(BaseModel):
+ """Minimal structured output schema."""
+
+ answer: str
+
+ await self._assert_chat_model_base_interruption(StructuredOutput)
+
async def test_full_interrupt_flow(self) -> None:
"""Complete flow: user message → agent runs → interrupt published
→ CancelDispatcher cancels task → agent exits with interrupted