microsoft/semantic-kernel · error · ValueError
Connection is not established.
Error message
Connection is not established.
What it means
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.
Source
Thrown at python/semantic_kernel/connectors/ai/open_ai/services/_open_ai_realtime.py:951
@experimental
class OpenAIRealtimeWebsocketBase(OpenAIRealtimeBase):
"""OpenAI Realtime service."""
protocol: ClassVar[Literal["websocket"]] = "websocket" # type: ignore
connection: AsyncRealtimeConnection | None = None
connected: asyncio.Event = Field(default_factory=asyncio.Event)
@override
async def receive(
self,
audio_output_callback: Callable[[ndarray], Coroutine[Any, Any, None]] | None = None,
**kwargs: Any,
) -> AsyncGenerator[RealtimeEvents, None]:
if audio_output_callback:
self.audio_output_callback = audio_output_callback
await self.connected.wait()
if not self.connection:
raise ValueError("Connection is not established.")
async for event in self.connection:
if event.type == ListenEvents.RESPONSE_AUDIO_DELTA.value:
if self.audio_output_callback:
await self.audio_output_callback(np.frombuffer(base64.b64decode(event.delta), dtype=np.int16))
yield RealtimeAudioEvent(
audio=AudioContent(data=event.delta, data_format="base64", inner_content=event),
service_type=event.type,
service_event=event,
)
continue
async for realtime_event in self._parse_event(event):
yield realtime_event
async def _send(self, event: RealtimeClientEvent) -> None:
await self.connected.wait()
if not self.connection:
raise ValueError("Connection is not established.")View on GitHub (pinned to c028a0c7dc)
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.
Example fix
// before
async for event in service.receive():
process(event)
// after
if not service.connection:
await service.create_session(settings=settings)
async for event in service.receive():
process(event) Defensive patterns
Strategy: validation
Validate before calling
def ensure_connection_for_receive(service) -> None:
if not getattr(service, 'connection', None):
raise RuntimeError(
'Connection is not established. Call create_session() before receive().'
) Type guard
def is_connected(service) -> bool:
return getattr(service, 'connection', None) is not None Try / catch
try:
async for event in service.receive():
process(event)
except ValueError as e:
if 'Connection is not established' in str(e):
await service.create_session(settings=settings)
async for event in service.receive():
process(event) Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- The thread cannot be deleted because it has not been created
- Session is required for SessionUpdateEvent
- Audio is required for InputAudioBufferAppendEvent
- Item is required for ConversationItemCreateEvent
- Item ID is required for ConversationItemDeleteEvent
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/10e67b8124adc50d.
Report an issue: GitHub.