UNPKG

@openai/agents-realtime

Version:

The OpenAI Agents SDK is a lightweight yet powerful framework for building multi-agent workflows. This package contains the logic for building realtime voice agents on the server or in the browser.

647 lines • 27.6 kB
/// <reference lib="dom" /> import { isBrowserEnvironment } from '@openai/agents-core/_shims'; import { UserError } from '@openai/agents-core'; import logger from "./logger.mjs"; import { OpenAIRealtimeBase, } from "./openaiRealtimeBase.mjs"; import { parseRealtimeEvent } from "./openaiRealtimeEvents.mjs"; import { ResponseCreateSequencer } from "./responseCreateSequencer.mjs"; import { HEADERS } from "./utils.mjs"; const PEER_CONNECTION_DISCONNECTED_GRACE_MS = 5000; /** * Transport layer that's handling the connection between the client and OpenAI's Realtime API * via WebRTC. While this transport layer is designed to be used within a RealtimeSession, it can * also be used standalone if you want to have a direct connection to the Realtime API. * * Unless you specify a `mediaStream` or `audioElement` option, the transport layer will * automatically configure the microphone and audio output to be used by the session. */ export class OpenAIRealtimeWebRTC extends OpenAIRealtimeBase { options; #url; #state = { status: 'disconnected', peerConnection: undefined, dataChannel: undefined, callId: undefined, }; #useInsecureApiKey; #cancelOngoingResponse = false; #muted = false; #connectPromise; #cancelConnectionAttempt; #connectAttemptId = 0; #peerConnectionDisconnectedTimeout; #responseCreateSequencer = new ResponseCreateSequencer((event) => this.#sendEventNow(event), (error) => this._onError(error)); #reportError(error) { try { this._onError(error); } catch { // Error observers must not interrupt connection state cleanup. } } #cleanupFailedConnection(error, reportError = true) { let cleanupFailed = false; let cleanupError; try { this.close(); } catch (caughtError) { cleanupFailed = true; cleanupError = caughtError; } if (reportError) { this.#reportError(error); } if (cleanupFailed) { this.#reportError(cleanupError); } } constructor(options = {}) { if (typeof RTCPeerConnection === 'undefined') { throw new Error('WebRTC is not supported in this environment'); } super(options); this.options = options; this.#url = options.baseUrl ?? `https://api.openai.com/v1/realtime/calls`; this.#useInsecureApiKey = options.useInsecureApiKey ?? false; } /** * The current call ID of the WebRTC connection. */ get callId() { return this.#state.callId; } /** * The current status of the WebRTC connection. */ get status() { return this.#state.status; } /** * The current connection state of the WebRTC connection including the peer connection and data * channel. */ get connectionState() { return this.#state; } /** * Whether the session is muted. */ get muted() { return this.#muted; } /** * Connect to the Realtime API. This will establish the connection to the OpenAI Realtime API * via WebRTC. * * If you are using a browser, the transport layer will also automatically configure the * microphone and audio output to be used by the session. * * @param options - The options for the connection. */ async connect(options) { if (this.#state.status === 'connected') { return; } if (this.#connectPromise) { return this.#connectPromise; } if (this.#state.status === 'connecting') { logger.warn('Realtime connection already in progress but no promise found'); return; } const previousModel = this.currentModel; const model = options.model ?? previousModel; this.currentModel = model; const baseUrl = options.url ?? this.#url; const attemptId = ++this.#connectAttemptId; let resolveConnection; let rejectConnection; const connectionReady = new Promise((resolve, reject) => { resolveConnection = resolve; rejectConnection = reject; }); let shouldRestoreModel = true; const isActiveAttempt = () => this.#connectAttemptId === attemptId; const releaseConnectionAttempt = () => { if (!isActiveAttempt()) { return false; } if (shouldRestoreModel) { this.currentModel = previousModel; } this.#connectPromise = undefined; this.#cancelConnectionAttempt = undefined; this.#connectAttemptId += 1; return true; }; const prepareConnection = async () => { let apiKey; try { apiKey = await this._getApiKey(options); } catch (error) { releaseConnectionAttempt(); rejectConnection(error); return; } if (!isActiveAttempt()) { return; } const isClientKey = typeof apiKey === 'string' && apiKey.startsWith('ek_'); if (isBrowserEnvironment() && !this.#useInsecureApiKey && !isClientKey) { releaseConnectionAttempt(); rejectConnection(new UserError('Using the WebRTC connection in a browser environment requires an ephemeral client key. If you need to use a regular API key, use the WebSocket transport or set the `useInsecureApiKey` option to true.')); return; } try { const userSessionConfig = { ...(options.initialSessionConfig || {}), model: this.currentModel, }; const connectionUrl = new URL(baseUrl); let peerConnection = new RTCPeerConnection(); const dataChannel = peerConnection.createDataChannel('oai-events'); let callId = undefined; const attachConnectionStateHandler = (connection) => { connection.onconnectionstatechange = () => { this.#handlePeerConnectionStateChange(connection); }; }; attachConnectionStateHandler(peerConnection); this.#state = { status: 'connecting', peerConnection, dataChannel, callId, }; this.emit('connection_change', this.#state.status); if (this.#connectAttemptId !== attemptId || this.#state.dataChannel !== dataChannel) { throw new Error('Connection closed before setup completed'); } dataChannel.addEventListener('open', () => { if (this.#connectAttemptId !== attemptId || this.#state.dataChannel !== dataChannel) { return; } this.#state = { status: 'connecting', peerConnection, dataChannel, callId, }; // Wait for session.updated acknowledgement before resolving connect(). // Without this, audio can flow to the server before config (instructions, // tools, modalities) is applied, causing the server to use defaults. let settled = false; // eslint-disable-next-line prefer-const -- declared before finish() to avoid TDZ if a callback fires synchronously let timeoutId; const removeConfigAckListeners = () => { if (timeoutId !== undefined) clearTimeout(timeoutId); dataChannel.removeEventListener('message', onConfigAck); dataChannel.removeEventListener('close', onClose); }; const fail = (error, cleanupTransport = true, reportError = true) => { if (settled) return; settled = true; removeConfigAckListeners(); rejectConnection(error); const released = releaseConnectionAttempt(); if (cleanupTransport && released && this.#state.dataChannel === dataChannel) { this.#cleanupFailedConnection(error, reportError); } else if (cleanupTransport && reportError) { this.#reportError(error); } }; this.#cancelConnectionAttempt = () => { fail(new Error('Connection closed before session config was acknowledged'), false); }; const isActiveConnection = () => this.#connectAttemptId === attemptId && this.#state.status === 'connected' && this.#state.dataChannel === dataChannel && dataChannel.readyState === 'open'; const finish = () => { if (settled) return; removeConfigAckListeners(); // Reject if the transport was closed/errored while waiting, // the dataChannel is no longer open, or a different connection // attempt is now active (stale timeout from an earlier connect). if (this.#state.status !== 'connecting' || this.#state.dataChannel !== dataChannel || dataChannel.readyState !== 'open') { const error = new Error('Connection closed before session config was acknowledged'); fail(error); return; } this.#state = { status: 'connected', peerConnection, dataChannel, callId, }; if (this.#connectAttemptId === attemptId) { this.#connectPromise = undefined; } try { this.emit('connection_change', this.#state.status); if (!isActiveConnection()) { fail(new Error('Connection closed before session config was acknowledged')); return; } this._onOpen(); if (!isActiveConnection()) { fail(new Error('Connection closed before session config was acknowledged')); return; } } catch (error) { fail(error); return; } shouldRestoreModel = false; if (isActiveAttempt()) { this.#cancelConnectionAttempt = undefined; } settled = true; resolveConnection(); }; const onConfigAck = (ackEvent) => { const { data: parsed } = parseRealtimeEvent(ackEvent); if (parsed?.type === 'session.updated') { finish(); } }; const onClose = () => { finish(); }; timeoutId = setTimeout(() => { if (!settled) { logger.warn('Timed out waiting for session.updated ack — resolving connect() anyway'); finish(); } }, 5000); dataChannel.addEventListener('message', onConfigAck); dataChannel.addEventListener('close', onClose); // Register the general message handler AFTER onConfigAck so that // finish() resolves connect() before _onMessage emits the // session.updated event to external listeners. dataChannel.addEventListener('message', (event) => { if (this.#connectAttemptId !== attemptId || this.#state.dataChannel !== dataChannel) { return; } const { data: parsed } = parseRealtimeEvent(event); if (parsed?.type === 'error' && !settled) { // A server rejection during setup must not become a successful // connection through the acknowledgement timeout fallback. fail(parsed, true, false); this._onMessage(event); return; } this._onMessage(event); if (this.#connectAttemptId !== attemptId || this.#state.dataChannel !== dataChannel) { return; } if (!parsed) { return; } if (parsed.type === 'error') { this.#responseCreateSequencer.handleResponseCreateError(parsed); } if (parsed.type === 'response.created') { this.#cancelOngoingResponse = true; this.#responseCreateSequencer.markResponseCreated(); } else if (parsed.type === 'response.done') { this.#cancelOngoingResponse = false; this.#responseCreateSequencer.markResponseDone(); } if (parsed.type === 'session.created') { this._tracingConfig = 'tracing' in parsed.session ? (parsed.session.tracing ?? null) : null; // Trying to turn on tracing after the session is created const tracingConfig = typeof userSessionConfig.tracing === 'undefined' ? 'auto' : userSessionConfig.tracing; this._updateTracingConfig(tracingConfig); } }); try { this.updateSessionConfig(userSessionConfig); } catch (error) { fail(error); } }); dataChannel.addEventListener('error', (event) => { if (this.#connectAttemptId !== attemptId || this.#state.dataChannel !== dataChannel) { return; } rejectConnection(event); releaseConnectionAttempt(); this.#cleanupFailedConnection(event); }); // set up audio playback const audioElement = this.options.audioElement ?? document.createElement('audio'); audioElement.autoplay = true; peerConnection.ontrack = (event) => { audioElement.srcObject = event.streams[0]; }; // get microphone stream const stream = this.options.mediaStream ?? (await navigator.mediaDevices.getUserMedia({ audio: true, })); if (!isActiveAttempt()) { if (!this.options.mediaStream) { for (const track of stream.getAudioTracks()) { try { track.stop(); } catch (error) { this.#reportError(error); } } } return; } peerConnection.addTrack(stream.getAudioTracks()[0]); if (this.options.changePeerConnection) { const originalPeerConnection = peerConnection; const changedPeerConnection = await this.options.changePeerConnection(peerConnection); if (!isActiveAttempt()) { return; } peerConnection = changedPeerConnection; if (originalPeerConnection !== peerConnection) { originalPeerConnection.onconnectionstatechange = null; } attachConnectionStateHandler(peerConnection); this.#state = { ...this.#state, peerConnection }; } const offer = await peerConnection.createOffer(); if (!isActiveAttempt()) { return; } await peerConnection.setLocalDescription(offer); if (!isActiveAttempt()) { return; } if (!offer.sdp) { throw new Error('Failed to create offer'); } const sdpResponse = await fetch(connectionUrl, { method: 'POST', body: offer.sdp, headers: { 'Content-Type': 'application/sdp', Authorization: `Bearer ${apiKey}`, 'X-OpenAI-Agents-SDK': HEADERS['X-OpenAI-Agents-SDK'], }, }); if (!isActiveAttempt()) { return; } if (!sdpResponse.ok) { // Without this the error body is passed to setRemoteDescription and // surfaces as an opaque "Failed to parse SessionDescription", hiding // the real cause (e.g. insufficient_quota, invalid ephemeral key). const detail = await readSdpErrorDetail(sdpResponse); if (!isActiveAttempt()) { return; } throw new Error(`Realtime call request failed with status ${sdpResponse.status}${detail}`); } callId = sdpResponse.headers?.get('Location')?.split('/').pop(); this.#state = { ...this.#state, callId }; const answerSdp = await sdpResponse.text(); if (!isActiveAttempt()) { return; } const answer = { type: 'answer', sdp: answerSdp, }; await peerConnection.setRemoteDescription(answer); } catch (error) { rejectConnection(error); if (releaseConnectionAttempt()) { this.#cleanupFailedConnection(error); } else { this.#reportError(error); } } }; this.#cancelConnectionAttempt = () => { rejectConnection(new Error('Connection closed before setup completed')); releaseConnectionAttempt(); }; this.#connectPromise = connectionReady.finally(() => { // Only clear if this is still the active connection attempt. // A newer connect() may have already replaced #connectPromise. if (this.#connectAttemptId === attemptId) { this.#connectPromise = undefined; this.#cancelConnectionAttempt = undefined; } }); void prepareConnection(); return this.#connectPromise; } /** * Send an event to the Realtime API. This will stringify the event and send it directly to the * API. This can be used if you want to take control over the connection and send events manually. * * @param event - The event to send. */ sendEvent(event) { this.#assertConnected(); if (event.type === 'response.create') { this.#responseCreateSequencer.requestResponseCreate(event, { manual: true, }); return; } if (event.type === 'response.cancel') { this.#responseCreateSequencer.beginCancelResponse(); } this.#sendEventNow(event); } requestResponse(response) { this.#assertConnected(); this.#responseCreateSequencer.requestResponseCreate({ type: 'response.create', ...(response ? { response } : {}), }, { manual: response !== undefined }); } #assertConnected() { if (!this.#state.dataChannel || this.#state.dataChannel.readyState !== 'open') { throw new Error('WebRTC data channel is not connected. Make sure you call `connect()` before sending events.'); } } #sendEventNow(event) { this.#assertConnected(); this.#state.dataChannel.send(JSON.stringify(event)); } #handlePeerConnectionStateChange(connection) { if (this.#state.peerConnection !== connection) { return; } switch (connection.connectionState) { case 'connected': this.#clearPeerConnectionDisconnectedTimeout(); break; case 'disconnected': this.#schedulePeerConnectionDisconnectedClose(connection); break; case 'failed': case 'closed': this.#clearPeerConnectionDisconnectedTimeout(); this.close(); break; // 'new' and 'connecting' are intermediate states and do not require action here. } } #schedulePeerConnectionDisconnectedClose(connection) { this.#clearPeerConnectionDisconnectedTimeout(); this.#peerConnectionDisconnectedTimeout = setTimeout(() => { if (this.#state.peerConnection === connection && connection.connectionState === 'disconnected') { this.close(); } }, PEER_CONNECTION_DISCONNECTED_GRACE_MS); } #clearPeerConnectionDisconnectedTimeout() { if (this.#peerConnectionDisconnectedTimeout === undefined) { return; } clearTimeout(this.#peerConnectionDisconnectedTimeout); this.#peerConnectionDisconnectedTimeout = undefined; } /** * Mute or unmute the session. * @param muted - Whether to mute the session. */ mute(muted) { this.#muted = muted; if (this.#state.peerConnection) { const peerConnection = this.#state.peerConnection; peerConnection.getSenders().forEach((sender) => { if (sender.track) { sender.track.enabled = !muted; } }); } } _afterAudioDoneEvent() { this.#cancelOngoingResponse = false; } /** * Close the connection to the Realtime API and disconnects the underlying WebRTC connection. */ close() { this.#clearPeerConnectionDisconnectedTimeout(); this.#cancelConnectionAttempt?.(); const { dataChannel, peerConnection } = this.#state; const shouldNotify = this.#state.status !== 'disconnected'; this.#state = { status: 'disconnected', peerConnection: undefined, dataChannel: undefined, callId: undefined, }; let cleanupError; const runCleanup = (cleanup) => { try { cleanup(); } catch (error) { cleanupError ??= error; } }; runCleanup(() => this.#responseCreateSequencer.releaseWaiters()); this.#cancelOngoingResponse = false; if (dataChannel) { runCleanup(() => dataChannel.close()); } if (peerConnection) { runCleanup(() => { peerConnection.onconnectionstatechange = null; }); // Skip sender cleanup when the caller supplied `mediaStream`. That stream belongs to the // application, which may still be using it for a level meter, a recorder, or a later // reconnect, so stopping it here would end the track permanently. This is deliberately // scoped to that one case rather than a per-track ownership rule, so senders added through // `changePeerConnection` are left to whoever added them. if (!this.options.mediaStream) { let senders = []; runCleanup(() => { senders = peerConnection.getSenders(); }); for (const sender of senders) { runCleanup(() => sender.track?.stop()); } } runCleanup(() => peerConnection.close()); } if (shouldNotify) { runCleanup(() => this.emit('connection_change', this.#state.status)); runCleanup(() => this._onClose()); } if (cleanupError) { throw cleanupError; } } /** * Interrupt the current response if one is ongoing and clear the audio buffer so that the agent * stops talking. */ interrupt() { if (this.#cancelOngoingResponse && this.#responseCreateSequencer.beginCancelResponse()) { this.#sendEventNow({ type: 'response.cancel', }); this.#cancelOngoingResponse = false; } this.#sendEventNow({ type: 'output_audio_buffer.clear', }); } } async function readSdpErrorDetail(response) { try { const text = await response.text(); if (text) { try { const message = JSON.parse(text)?.error?.message; if (typeof message === 'string' && message) { return `: ${message}`; } } catch { // Non-JSON body — fall through to the raw text below. } return `: ${text}`; } } catch { // Ignore response body read failures and use the status text below. } return response.statusText ? `: ${response.statusText}` : ''; } //# sourceMappingURL=openaiRealtimeWebRtc.mjs.map