{"record":{"id":"22884292f4cd22b3","repo":"microsoft/autogen","slug":"the-stream-should-have-returned-the-final-result-228842","errorCode":null,"errorMessage":"The stream should have returned the final result.","messagePattern":"The stream should have returned the final result\\.","errorType":"exception","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-ext/src/autogen_ext/agents/azure/_azure_ai_agent.py","lineNumber":649,"sourceCode":"        It delegates to on_messages_stream and returns the final response.\n\n        Args:\n            messages (Sequence[BaseChatMessage]): The messages to process\n            cancellation_token (CancellationToken): Token for cancellation handling\n            message_limit (int, optional): Maximum number of messages to retrieve from the thread\n\n        Returns:\n            Response: The agent's response, including the chat message and any inner events\n\n        Raises:\n            AssertionError: If the stream doesn't return a final result\n        \"\"\"\n        async for message in self.on_messages_stream(\n            messages=messages, cancellation_token=cancellation_token, message_limit=message_limit\n        ):\n            if isinstance(message, Response):\n                return message\n        raise AssertionError(\"The stream should have returned the final result.\")\n\n    async def on_messages_stream(\n        self,\n        messages: Sequence[BaseChatMessage],\n        cancellation_token: Optional[CancellationToken] = None,\n        message_limit: int = 1,\n        polling_interval: float = 0.5,\n    ) -> AsyncGenerator[AgentEvent | ChatMessage | Response, None]:\n        \"\"\"\n        Process incoming messages and yield streaming responses from the Azure AI agent.\n\n        This method handles the complete interaction flow with the Azure AI agent:\n        1. Processing input messages\n        2. Creating and monitoring a run\n        3. Handling tool calls and their results\n        4. Retrieving and returning the agent's final response\n\n        The method yields events during processing (like tool calls) and finally yields","sourceCodeStart":631,"sourceCodeEnd":667,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/agents/azure/_azure_ai_agent.py#L631-L667","documentation":"on_messages iterates on_messages_stream and asserts a final Response event arrives. If the stream finishes without ever yielding a Response (e.g. it was cancelled, an exception path ended the generator, or a bug/edge case dropped the terminal event), the AssertionError fires — an invariant violation, not an expected user error.","triggerScenarios":"The CancellationToken cancels mid-stream so the generator exits without a final Response; an upstream exception inside on_messages_stream is swallowed by an inner handler; edge cases (message_limit reached before any response event) in specific versions.","commonSituations":"Cancelling a run via CancellationToken and still awaiting on_messages; wrapping the stream in custom generators that drop the final event; version-specific bugs after upgrading autogen-ext.","solutions":["If cancelling is intended, don't await on_messages afterwards — treat CancelledError as the outcome rather than letting the loop fall through.","Upgrade autogen-ext — stream/Response invariants have had fixes across releases.","Don't wrap on_messages_stream in a generator that filters events unless you forward Response objects.","If reproducible without cancellation, capture the full event sequence and file an issue; it indicates a bug."],"exampleFix":"# before\nresp = await agent.on_messages(msgs, ct)  # ct already cancelled\n# after\nif ct.is_cancelled():\n    return\nresp = await agent.on_messages(msgs, ct)","handlingStrategy":"try-catch","validationCode":"if cancellation_token and cancellation_token.is_cancelled():\n    return  # don't start/await on_messages","typeGuard":null,"tryCatchPattern":"try:\n    resp = await agent.on_messages(msgs, ct)\nexcept AssertionError:\n    if ct.is_cancelled():\n        handle_cancelled()\n    else:\n        raise  # genuine bug — capture the event stream and report","preventionTips":["Don't await on_messages after cancelling its token.","Upgrade autogen-ext regularly; stream invariants get fixed.","Don't wrap on_messages_stream in filtering generators that drop Response events."],"tags":["azure","streaming","cancellation","assertion","azure-ai-agent"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}