{"record":{"id":"10e67b8124adc50d","repo":"microsoft/semantic-kernel","slug":"connection-is-not-established","errorCode":null,"errorMessage":"Connection is not established.","messagePattern":"Connection is not established\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/connectors/ai/open_ai/services/_open_ai_realtime.py","lineNumber":951,"sourceCode":"@experimental\nclass OpenAIRealtimeWebsocketBase(OpenAIRealtimeBase):\n    \"\"\"OpenAI Realtime service.\"\"\"\n\n    protocol: ClassVar[Literal[\"websocket\"]] = \"websocket\"  # type: ignore\n    connection: AsyncRealtimeConnection | None = None\n    connected: asyncio.Event = Field(default_factory=asyncio.Event)\n\n    @override\n    async def receive(\n        self,\n        audio_output_callback: Callable[[ndarray], Coroutine[Any, Any, None]] | None = None,\n        **kwargs: Any,\n    ) -> AsyncGenerator[RealtimeEvents, None]:\n        if audio_output_callback:\n            self.audio_output_callback = audio_output_callback\n        await self.connected.wait()\n        if not self.connection:\n            raise ValueError(\"Connection is not established.\")\n\n        async for event in self.connection:\n            if event.type == ListenEvents.RESPONSE_AUDIO_DELTA.value:\n                if self.audio_output_callback:\n                    await self.audio_output_callback(np.frombuffer(base64.b64decode(event.delta), dtype=np.int16))\n                yield RealtimeAudioEvent(\n                    audio=AudioContent(data=event.delta, data_format=\"base64\", inner_content=event),\n                    service_type=event.type,\n                    service_event=event,\n                )\n                continue\n            async for realtime_event in self._parse_event(event):\n                yield realtime_event\n\n    async def _send(self, event: RealtimeClientEvent) -> None:\n        await self.connected.wait()\n        if not self.connection:\n            raise ValueError(\"Connection is not established.\")","sourceCodeStart":933,"sourceCodeEnd":969,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/ai/open_ai/services/_open_ai_realtime.py#L933-L969","documentation":"In the receive() async generator of the realtime service, after awaiting self.connected.wait(), if self.connection is still None (falsy), a ValueError is raised. This indicates the connection was never established or was torn down between the connected event firing and the receive() call executing — a state where the service thinks it's connected but has no underlying transport.","triggerScenarios":"Calling receive() on a realtime service instance where create_session() never ran or failed, or where close/disconnect was called concurrently — the connected Event may have been set spuriously or the connection was set to None by a cleanup path.","commonSituations":"Calling receive() before create_session(); a race between session teardown and receive(); the connected Event was set manually for testing without a real connection; using the WebSocket service variant where connection setup failed silently.","solutions":["Ensure create_session() completes successfully before calling receive().","Guard with an explicit check: verify service.connection is not None before calling receive().","Investigate why connected was set but connection is None — check for concurrent close_session() calls or failed session setup.","Add lifecycle management to prevent receive() being called in a disconnected state."],"exampleFix":"// before\nasync for event in service.receive():\n    process(event)\n// after\nif not service.connection:\n    await service.create_session(settings=settings)\nasync for event in service.receive():\n    process(event)","handlingStrategy":"validation","validationCode":"def ensure_connection_for_receive(service) -> None:\n    if not getattr(service, 'connection', None):\n        raise RuntimeError(\n            'Connection is not established. Call create_session() before receive().'\n        )","typeGuard":"def is_connected(service) -> bool:\n    return getattr(service, 'connection', None) is not None","tryCatchPattern":"try:\n    async for event in service.receive():\n        process(event)\nexcept ValueError as e:\n    if 'Connection is not established' in str(e):\n        await service.create_session(settings=settings)\n        async for event in service.receive():\n            process(event)","preventionTips":["Always call create_session() and await it before calling receive().","Check service.connection is not None as a precondition guard.","Prevent concurrent close_session() calls during an active receive() loop."],"tags":["openai","realtime","connection","lifecycle","semantic-kernel"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}