microsoft/semantic-kernel · error · Exception
OpenAI WebRTC error: {error_text}
Error message
OpenAI WebRTC error: {error_text} What it means
During WebRTC session establishment, the service POSTs the local SDP offer to OpenAI's WebRTC endpoint with an ephemeral token. If the HTTP response status is not 200/201, the raw error body is wrapped in a bare Exception and re-raised. The chained except logs 'Failed to connect to OpenAI'. Common causes are expired/invalid ephemeral tokens, wrong model ID, or SDP format issues.
Source
Thrown at python/semantic_kernel/connectors/ai/open_ai/services/_open_ai_realtime.py:809
# this is the incoming audio, which sends audio to the service
self.peer_connection.addTransceiver(self.audio_track)
offer = await self.peer_connection.createOffer()
await self.peer_connection.setLocalDescription(offer)
try:
ephemeral_token = await self._get_ephemeral_token()
headers = {"Authorization": f"Bearer {ephemeral_token}", "Content-Type": "application/sdp"}
headers = prepend_semantic_kernel_to_user_agent(headers)
async with (
ClientSession() as session,
session.post(self._get_webrtc_url(), headers=headers, data=offer.sdp) as response,
):
if response.status not in [200, 201]:
error_text = await response.text()
raise Exception(f"OpenAI WebRTC error: {error_text}")
sdp_answer = await response.text()
answer = RTCSessionDescription(sdp=sdp_answer, type="answer")
await self.peer_connection.setRemoteDescription(answer)
logger.info("Connected to OpenAI WebRTC")
except Exception as e:
logger.error(f"Failed to connect to OpenAI: {e!s}")
raise
await self.update_session(settings=settings, chat_history=chat_history, **kwargs)
@override
async def close_session(self) -> None:
"""Close the session in the service."""
if self.peer_connection:
with contextlib.suppress(asyncio.CancelledError):
await self.peer_connection.close()View on GitHub (pinned to c028a0c7dc)
Solutions
- Read the error_text in the exception message to identify the HTTP status and OpenAI's error detail.
- If token-related (401), ensure the ephemeral token is fresh — check _get_ephemeral_token() succeeds and the token is used immediately.
- Verify the ai_model_id is a supported realtime model (e.g. gpt-4o-realtime-preview).
- Implement a retry with a fresh token for transient failures (429, 5xx).
Example fix
// before
await service.create_session() # fails with 'OpenAI WebRTC error: ...'
// after
try:
await service.create_session()
except Exception as e:
print(f'WebRTC connect failed: {e}') # read error_text for diagnosis
# retry with fresh token or fall back to WebSocket realtime Defensive patterns
Strategy: try-catch
Validate before calling
null
Type guard
null
Try / catch
try:
await service.create_session()
except Exception as e:
error_msg = str(e)
if '401' in error_msg or 'token' in error_msg.lower():
logger.error('Token expired or invalid — refresh and retry')
elif '429' in error_msg:
await asyncio.sleep(backoff)
await service.create_session()
else:
raise Prevention
- Ensure the ephemeral token is used immediately after generation — it expires quickly.
- Verify the model ID supports realtime WebRTC before connecting.
- Implement retry with backoff for transient (429, 5xx) errors.
- Monitor the error_text in the exception for diagnosis.
When it happens
Trigger: The POST to the OpenAI WebRTC SDP endpoint returns a non-2xx status — e.g. 401 (invalid/expired ephemeral token), 404 (wrong model), 400 (malformed SDP), 429 (rate limit), or 5xx (server error).
Common situations: Ephemeral token expired between generation and WebRTC POST; using a model ID that doesn't support realtime WebRTC; network/proxy stripping SDP headers; OpenAI API outage or regional issue.
Related errors
- Session is required for SessionUpdateEvent
- Audio is required for InputAudioBufferAppendEvent
- Audio track not initialized
- Failed to get ephemeral token: {error_text}
- The thread could not be created due to an error response fro
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/db19a0f9454c6146.
Report an issue: GitHub.