openai/openai-python · error · OpenAIError

WebSocket error: {event}

Error message

WebSocket error: {event}

What it means

Raised by dispatch_events() on a Responses WebSocket when the server sends an 'error' event and no handler (neither the specific 'error' handler nor a generic 'event' handler) is registered to consume it. Unhandled WebSocket-level errors are promoted to an OpenAIError so they are not silently swallowed.

Source

Thrown at src/openai/resources/responses/responses.py:4268

    async def dispatch_events(self) -> None:
        """Run the event loop, dispatching received events to registered handlers.

        Blocks until the connection is closed. This is the push-based
        alternative to iterating with ``async for event in connection``.

        If an ``"error"`` event arrives and no handler is registered for
        ``"error"`` or ``"event"``, an ``OpenAIError`` is raised.
        """
        import asyncio

        async for event in self:
            event_type = event.type
            specific = self._event_handler_registry.get_handlers(event_type)
            generic = self._event_handler_registry.get_handlers("event")

            if event_type == "error" and not specific and not generic:
                if isinstance(event, ResponseWsError):
                    raise OpenAIError(f"WebSocket error: {event}")

            for handler in specific:
                result = handler(event)
                if asyncio.iscoroutine(result):
                    await result

            for handler in generic:
                result = handler(event)
                if asyncio.iscoroutine(result):
                    await result


class AsyncResponsesConnectionManager:
    """
    Context manager over a `AsyncResponsesConnection` that is returned by `responses.connect()`

    This context manager ensures that the connection will be closed when it exits.

View on GitHub (pinned to 9917c6e28e)

Solutions

  1. Register an 'error' handler: @conn.on('error') async def on_error(e): ...
  2. Or register a generic 'event' handler to observe every server event including errors
  3. Log the error payload to identify the server-side cause (e.g. session config rejected)

Example fix

// before
@conn.on("response.output_text.delta")
async def on_delta(e): ...
// after
@conn.on("response.output_text.delta")
async def on_delta(e): ...

@conn.on("error")
async def on_error(e):
    logger.error("ws error: %s", e)
Defensive patterns

Strategy: try-catch

Validate before calling

handlers = conn._event_handler_registry.get_handlers('error')
if not handlers and not conn._event_handler_registry.get_handlers('event'):
    raise RuntimeError('register an error handler before dispatching')

Type guard

def has_error_handler(conn) -> bool:
    reg = conn._event_handler_registry
    return bool(reg.get_handlers('error') or reg.get_handlers('event'))

Try / catch

from openai import OpenAIError
try:
    await conn.dispatch_events()
except OpenAIError as e:
    if str(e).startswith('WebSocket error:'):
        logger.error('server-side ws error: %s', e)
        await recover()
    else:
        raise

Prevention

When it happens

Trigger: Registering event handlers for e.g. 'response.output_text.delta' but not for 'error' (nor a catch-all 'event' handler); the server then emits ResponseWsError (e.g. invalid session update, auth problem) and no one is listening.

Common situations: Selective handler registration that ignores error events; porting webhook/sse handler code that assumed errors always raise; server-side rate limits or malformed requests surfacing as ws error events.

Related errors


AI-assisted analysis of openai/openai-python@9917c6e28e (2026-08-28). Data as JSON: /api/errors/82f7bfc4c7f9b30c. Report an issue: GitHub.