Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions lib/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,39 @@ export class RealtimeAPI extends RealtimeEventHandler {
}
}

/**
* Private method to build a WebSocket URL with optional query parameters.
* @param {string} baseUrl - Base URL to which query parameters will be added.
* @param {Object} queryParams - Key-value pairs of query parameters.
* @returns {string} - The constructed WebSocket URL.
*/
#buildWebSocketUrl(baseUrl, queryParams) {
if (typeof URL === 'function') {
try {
const urlObj = new URL(baseUrl);
for (const [key, value] of Object.entries(queryParams)) {
if (value !== undefined && value !== null) {
urlObj.searchParams.set(key, value);
}
}
return urlObj.toString();
} catch (error) {
console.warn('Failed to use URL constructor:', error);
}
}

// Fallback for environments without `URL` support
let url = baseUrl;
const queryString = Object.entries(queryParams)
.filter(([_, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
if (queryString) {
url += (url.includes('?') ? '&' : '?') + queryString;
}
return url;
}

/**
* Tells us whether or not the WebSocket is connected
* @returns {boolean}
Expand Down Expand Up @@ -73,7 +106,7 @@ export class RealtimeAPI extends RealtimeEventHandler {
);
}
const WebSocket = globalThis.WebSocket;
const ws = new WebSocket(`${this.url}${model ? `?model=${model}` : ''}`, [
const ws = new WebSocket( this.#buildWebSocketUrl(this.url, { model }), [
'realtime',
`openai-insecure-api-key.${this.apiKey}`,
'openai-beta.realtime-v1',
Expand Down Expand Up @@ -113,7 +146,7 @@ export class RealtimeAPI extends RealtimeEventHandler {
const wsModule = await import(/* webpackIgnore: true */ moduleName);
const WebSocket = wsModule.default;
const ws = new WebSocket(
'wss://api.openai.com/v1/realtime?model=gpt-4o-realtime-preview-2024-10-01',
this.#buildWebSocketUrl(this.url, { model }),
[],
{
finishRequest: (request) => {
Expand Down