Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai node Beta RealtimeWebSocket

From Leeroopedia
Knowledge Sources
Domains SDK, Realtime, WebSocket
Last Updated 2026-02-15 12:00 GMT

Overview

OpenAIRealtimeWebSocket is the browser-compatible beta realtime client that uses the native WebSocket API to connect to the OpenAI Realtime API.

Description

OpenAIRealtimeWebSocket extends OpenAIRealtimeEmitter to provide a complete realtime client implementation backed by the browser-native WebSocket global. It authenticates using WebSocket sub-protocols, passing the API key as an openai-insecure-api-key.{key} sub-protocol alongside the openai-beta.realtime-v1 protocol identifier.

The constructor validates the runtime environment. By default, browser usage is blocked to protect API credentials unless dangerouslyAllowBrowser is set to true or the key starts with ek_ (ephemeral session key). It builds the WSS URL using the shared buildRealtimeURL utility and registers event listeners that parse incoming JSON messages, emitting them as typed events. Error events from both the WebSocket and the API are unified through the inherited _onError handler.

The class provides three static factory methods. create() is an async factory that resolves function-based API keys before opening the connection. azure() is a specialized factory for Azure OpenAI deployments that handles Azure-specific authentication (API key or AD token via URL query parameters) and deployment name resolution. For Azure connections, sensitive credentials in the URL are redacted after the socket is opened.

Usage

Use OpenAIRealtimeWebSocket in browser environments or any runtime that provides a global WebSocket implementation. For Node.js server-side usage where the ws library is available, prefer OpenAIRealtimeWS instead.

Code Reference

Source Location

Signature

export class OpenAIRealtimeWebSocket extends OpenAIRealtimeEmitter {
  url: URL;
  socket: WebSocket;

  constructor(
    props: {
      model: string;
      dangerouslyAllowBrowser?: boolean;
    },
    client?: Pick<OpenAI, 'apiKey' | 'baseURL'>,
  );

  static async create(
    client: Pick<OpenAI, 'apiKey' | 'baseURL' | '_callApiKey'>,
    props: { model: string; dangerouslyAllowBrowser?: boolean },
  ): Promise<OpenAIRealtimeWebSocket>;

  static async azure(
    client: Pick<AzureOpenAI, '_callApiKey' | 'apiVersion' | 'apiKey' | 'baseURL' | 'deploymentName'>,
    options?: { deploymentName?: string; dangerouslyAllowBrowser?: boolean },
  ): Promise<OpenAIRealtimeWebSocket>;

  send(event: RealtimeClientEvent): void;
  close(props?: { code: number; reason: string }): void;
}

Import

import { OpenAIRealtimeWebSocket } from 'openai/beta/realtime/websocket';

I/O Contract

Inputs

Name Type Required Description
model string Yes The model identifier for the realtime session (e.g. "gpt-4o-realtime-preview").
dangerouslyAllowBrowser boolean No Opt-in flag to permit browser-side usage. Automatically true for ephemeral keys (ek_ prefix) or when an azureADTokenProvider is set.
client 'baseURL'> No An existing OpenAI or AzureOpenAI client instance. A new OpenAI client is created if not provided.

Outputs

Name Type Description
(instance) OpenAIRealtimeWebSocket A connected realtime client with event emitter interface.
url URL The WSS URL used for the connection (credentials redacted for Azure).
socket WebSocket The underlying native WebSocket instance.

Usage Examples

import { OpenAIRealtimeWebSocket } from 'openai/beta/realtime/websocket';
import OpenAI from 'openai';

// Browser usage with ephemeral session token
const rt = new OpenAIRealtimeWebSocket({
  model: 'gpt-4o-realtime-preview',
  dangerouslyAllowBrowser: true,
});

rt.on('session.created', (event) => {
  console.log('Session started:', event.session.id);
});

rt.on('error', (error) => {
  console.error('Realtime error:', error.message);
});

rt.send({
  type: 'conversation.item.create',
  item: {
    type: 'message',
    role: 'user',
    content: [{ type: 'input_text', text: 'Hello!' }],
  },
});

// Using static create() with an existing client
const client = new OpenAI();
const rt2 = await OpenAIRealtimeWebSocket.create(client, {
  model: 'gpt-4o-realtime-preview',
});

// Azure usage
import { AzureOpenAI } from 'openai';
const azureClient = new AzureOpenAI({ /* ... */ });
const rt3 = await OpenAIRealtimeWebSocket.azure(azureClient, {
  deploymentName: 'my-realtime-deployment',
});

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment