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 Stable RealtimeWebSocket

From Leeroopedia
Revision as of 13:36, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Openai_Openai_node_Stable_RealtimeWebSocket.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains SDK, Realtime, WebSocket
Last Updated 2026-02-15 12:00 GMT

Overview

The OpenAIRealtimeWebSocket class provides a browser-compatible WebSocket client for the OpenAI Realtime API, built on the native WebSocket global.

Description

The OpenAIRealtimeWebSocket class extends OpenAIRealtimeEmitter and implements the concrete send and close methods using the browser's native WebSocket API. It manages the complete WebSocket lifecycle: URL construction via buildRealtimeURL, connection establishment with the realtime subprotocol and API key authentication, message parsing, and error handling.

The constructor validates the browser environment and enforces security by requiring dangerouslyAllowBrowser: true to run in browsers (since it exposes the API key). It also rejects function-based API keys in the constructor, directing users to the async create() factory method instead. Messages received from the server are parsed as JSON and dispatched as typed events through the emitter system. For Azure deployments, the constructor handles authentication via URL query parameters rather than WebSocket subprotocols.

The class provides two static factory methods: create() resolves function-based API keys before constructing the client, and azure() handles Azure-specific configuration including deployment names and authentication token resolution. After construction, the url property contains the connection URL (with credentials redacted for Azure).

Usage

Use this class when building browser-based applications that need to interact with the OpenAI Realtime API via WebSockets. For Node.js server environments, prefer the OpenAIRealtimeWS class which uses the ws library 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 OpenAI from 'openai';

I/O Contract

Inputs

Name Type Required Description
props.model string Yes The realtime model to connect to (e.g., 'gpt-realtime').
props.dangerouslyAllowBrowser boolean No Set to true to allow browser usage (exposes API key).
client 'baseURL'> No An OpenAI client instance; a new one is created if not provided.
event RealtimeClientEvent Yes (send) The client event to send as JSON over the WebSocket.
props.code number No (close) WebSocket close code; defaults to 1000.
props.reason string No (close) WebSocket close reason; defaults to 'OK'.

Outputs

Name Type Description
url URL The wss:// URL used for the WebSocket connection.
socket WebSocket The underlying native WebSocket instance.
event emissions RealtimeServerEvent Typed server events emitted through the listener system.
error emissions OpenAIRealtimeError Error events from the API or connection failures.

Usage Examples

import OpenAI from 'openai';

const client = new OpenAI({ dangerouslyAllowBrowser: true });

// Create a realtime WebSocket connection
const rt = new OpenAI.RealtimeWebSocket({ model: 'gpt-realtime' }, client);

// Listen for all events
rt.on('event', (event) => {
  console.log('Server event:', event.type);
});

// Handle errors
rt.on('error', (error) => {
  console.error('Error:', error.message);
});

// Listen for specific event types
rt.on('session.created', (event) => {
  console.log('Session created');
});

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

// Close the connection when done
rt.close();

// Using the async factory for function-based API keys
const rt2 = await OpenAI.RealtimeWebSocket.create(client, {
  model: 'gpt-realtime',
});

// Azure deployment
import { AzureOpenAI } from 'openai';
const azureClient = new AzureOpenAI();
const azureRt = await OpenAI.RealtimeWebSocket.azure(azureClient, {
  deploymentName: 'my-realtime-deployment',
});

Related Pages

Page Connections

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