Skip to content

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

fix(stream): Add raising error in stream_printing_messages (#981)

qbcca5718d746a2
diff --git a/src/agentscope/pipeline/_functional.py b/src/agentscope/pipeline/_functional.py
index e9e96f720..8770cd544 100644
--- a/src/agentscope/pipeline/_functional.py
+++ b/src/agentscope/pipeline/_functional.py
@@ -156,14 +156,18 @@ async def stream_printing_messages(
else:
task.add_done_callback(lambda _: queue.put_nowait(end_signal))
- # Receive the messages from the agent's message queue
while True:
# The message obj, and a boolean indicating whether it's the last chunk
# in a streaming message
printing_msg = await queue.get()
- # End the loop when the message is None
+ # Check if this is the end signal
if isinstance(printing_msg, str) and printing_msg == end_signal:
break
yield printing_msg
+
+ # Check exception after processing all messages
+ exception = task.exception()
+ if exception is not None:
+ raise exception from None
diff --git a/tests/pipeline_test.py b/tests/pipeline_test.py
index af6429b1b..68bf600d0 100644
--- a/tests/pipeline_test.py
+++ b/tests/pipeline_test.py
@@ -86,6 +86,37 @@ class StreamAgent(AgentBase):
"""Handle interrupt"""
+class ErrorAgent(AgentBase):
+ """Agent that raises an error during execution."""
+
+ def __init__(self, error_msg: str = "Test error") -> None:
+ """Initialize the agent"""
+ super().__init__()
+ self.name = "ErrorAgent"
+ self.error_msg = error_msg
+
+ async def reply(self) -> Msg | None:
+ """Reply function that raises an error"""
+ msg = Msg(
+ self.name,
+ "Message before error",
+ "user",
+ )
+ await self.print(msg)
+ # Raise error after printing
+ raise ValueError(self.error_msg)
+
+ async def observe(self, msg: Msg | list[Msg] | None) -> None:
+ """Observe function"""
+
+ async def handle_interrupt(
+ self,
+ *args: Any,
+ **kwargs: Any,
+ ) -> Msg:
+ """Handle interrupt"""
+
+
class MultAgent(AgentBase):
"""Mult agent class."""
@@ -376,3 +407,32 @@ class PipelineTest(IsolatedAsyncioTestCase):
)
i += 1
+
+ async def test_stream_printing_messages_with_error_after_print(
+ self,
+ ) -> None:
+ """Test stream_printing_messages function raises exception even
+ after printing some messages"""
+ error_agent = ErrorAgent("Error after printing")
+
+ messages_received = []
+ exception_raised = False
+
+ try:
+ async for msg, _ in stream_printing_messages(
+ [error_agent],
+ error_agent(),
+ ):
+ messages_received.append(msg)
+ except ValueError as e:
+ exception_raised = True
+ self.assertEqual(str(e), "Error after printing")
+
+ # Verify that we received the message before error
+ self.assertEqual(len(messages_received), 1)
+ self.assertEqual(
+ messages_received[0].content,
+ "Message before error",
+ )
+ # Verify that exception was raised
+ self.assertTrue(exception_raised)