A programming framework for agentic AI
Make sure exceptions in process publish is logged. (#3774)
Eric Zhu43ccc811e046
diff --git a/python/packages/autogen-core/src/autogen_core/application/_single_threaded_agent_runtime.py b/python/packages/autogen-core/src/autogen_core/application/_single_threaded_agent_runtime.pyindex 38066f1f5..7feff6bab 100644--- a/python/packages/autogen-core/src/autogen_core/application/_single_threaded_agent_runtime.py+++ b/python/packages/autogen-core/src/autogen_core/application/_single_threaded_agent_runtime.py@@ -339,50 +339,50 @@ class SingleThreadedAgentRuntime(AgentRuntime):async def _process_publish(self, message_envelope: PublishMessageEnvelope) -> None:with self._tracer_helper.trace_block("publish", message_envelope.topic_id, parent=message_envelope.metadata):- responses: List[Awaitable[Any]] = []- recipients = await self._subscription_manager.get_subscribed_recipients(message_envelope.topic_id)- for agent_id in recipients:- # Avoid sending the message back to the sender- if message_envelope.sender is not None and agent_id == message_envelope.sender:- continue-- sender_agent = (- await self._get_agent(message_envelope.sender) if message_envelope.sender is not None else None- )- sender_name = str(sender_agent.id) if sender_agent is not None else "Unknown"- logger.info(- f"Calling message handler for {agent_id.type} with message type {type(message_envelope.message).__name__} published by {sender_name}"- )- # event_logger.info(- # MessageEvent(- # payload=message_envelope.message,- # sender=message_envelope.sender,- # receiver=agent,- # kind=MessageKind.PUBLISH,- # delivery_stage=DeliveryStage.DELIVER,- # )- # )- message_context = MessageContext(- sender=message_envelope.sender,- topic_id=message_envelope.topic_id,- is_rpc=False,- cancellation_token=message_envelope.cancellation_token,- )- agent = await self._get_agent(agent_id)+ try:+ responses: List[Awaitable[Any]] = []+ recipients = await self._subscription_manager.get_subscribed_recipients(message_envelope.topic_id)+ for agent_id in recipients:+ # Avoid sending the message back to the sender+ if message_envelope.sender is not None and agent_id == message_envelope.sender:+ continue++ sender_agent = (+ await self._get_agent(message_envelope.sender) if message_envelope.sender is not None else None+ )+ sender_name = str(sender_agent.id) if sender_agent is not None else "Unknown"+ logger.info(+ f"Calling message handler for {agent_id.type} with message type {type(message_envelope.message).__name__} published by {sender_name}"+ )+ # event_logger.info(+ # MessageEvent(+ # payload=message_envelope.message,+ # sender=message_envelope.sender,+ # receiver=agent,+ # kind=MessageKind.PUBLISH,+ # delivery_stage=DeliveryStage.DELIVER,+ # )+ # )+ message_context = MessageContext(+ sender=message_envelope.sender,+ topic_id=message_envelope.topic_id,+ is_rpc=False,+ cancellation_token=message_envelope.cancellation_token,+ )+ agent = await self._get_agent(agent_id)- async def _on_message(agent: Agent, message_context: MessageContext) -> Any:- with self._tracer_helper.trace_block("process", agent.id, parent=None):- with MessageHandlerContext.populate_context(agent.id):- return await agent.on_message(- message_envelope.message,- ctx=message_context,- )+ async def _on_message(agent: Agent, message_context: MessageContext) -> Any:+ with self._tracer_helper.trace_block("process", agent.id, parent=None):+ with MessageHandlerContext.populate_context(agent.id):+ return await agent.on_message(+ message_envelope.message,+ ctx=message_context,+ )- future = _on_message(agent, message_context)- responses.append(future)+ future = _on_message(agent, message_context)+ responses.append(future)- try:- _all_responses = await asyncio.gather(*responses)+ await asyncio.gather(*responses)except BaseException as e:# Ignore cancelled errors from logsif isinstance(e, CancelledError):diff --git a/python/packages/autogen-core/tests/test_runtime.py b/python/packages/autogen-core/tests/test_runtime.pyindex d1a1a3299..0f56e42a7 100644--- a/python/packages/autogen-core/tests/test_runtime.py+++ b/python/packages/autogen-core/tests/test_runtime.py@@ -1,4 +1,5 @@import asyncio+import loggingimport pytestfrom autogen_core.application import SingleThreadedAgentRuntime@@ -91,6 +92,26 @@ async def test_register_receives_publish(tracer_provider: TracerProvider) -> Non]+async def test_register_receives_publish_with_exception(caplog: pytest.LogCaptureFixture) -> None:+ runtime = SingleThreadedAgentRuntime()++ runtime.add_message_serializer(try_get_known_serializers_for_type(MessageType))++ async def agent_factory() -> LoopbackAgent:+ raise ValueError("test")++ await runtime.register_factory(type=AgentType("name"), agent_factory=agent_factory, expected_class=LoopbackAgent)+ await runtime.add_subscription(TypeSubscription("default", "name"))++ with caplog.at_level(logging.ERROR):+ runtime.start()+ await runtime.publish_message(MessageType(), topic_id=TopicId("default", "default"))+ await runtime.stop_when_idle()+ # Check if logger has the exception.+ assert any("Error processing publish message" in e.message for e in caplog.records)++@pytest.mark.asyncioasync def test_register_receives_publish_cascade() -> None:num_agents = 5