Principle:Openai Openai node Realtime Connection
| Knowledge Sources | |
|---|---|
| Domains | Realtime, WebSocket |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
A principle for establishing persistent WebSocket connections to the OpenAI Realtime API for low-latency, bidirectional multi-modal conversations.
Description
Realtime Connection establishes a WebSocket connection to the OpenAI Realtime API, enabling bidirectional communication for voice and text conversations. Unlike REST APIs which follow a request-response pattern, the Realtime API maintains a persistent connection where both client and server can send events at any time.
The SDK provides two implementations: OpenAIRealtimeWS for Node.js (using the ws library) and OpenAIRealtimeWebSocket for browsers (using the native WebSocket API). Both share a common base class with identical event dispatch logic.
Authentication is handled by sending the API key as a Bearer token in the WebSocket upgrade request (Node.js) or as a query parameter (browser, when using ephemeral tokens).
Usage
Use this principle when building applications that require real-time voice conversations, low-latency text interactions, or multi-modal (audio + text) communication with OpenAI models.
Theoretical Basis
Realtime connection follows a Factory Method with platform-specific implementations:
// Platform-agnostic interface
interface RealtimeConnection:
send(event: ClientEvent): void
on(eventName: string, callback): void
close(): void
// Node.js implementation (ws library)
class OpenAIRealtimeWS implements RealtimeConnection:
static async create(client, { model }):
url = buildRealtimeURL(client.baseURL, model)
ws = new WebSocket(url, { headers: { Authorization: Bearer ${apiKey} } })
return new OpenAIRealtimeWS(ws)
// Browser implementation (native WebSocket)
class OpenAIRealtimeWebSocket implements RealtimeConnection:
static async create(client, { model }):
url = buildRealtimeURL(client.baseURL, model)
ws = new WebSocket(url) // Auth via ephemeral token in URL
return new OpenAIRealtimeWebSocket(ws)