@livekit/agents-plugin-openai 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/llm.cjs +3 -0
  4. package/dist/llm.cjs.map +1 -1
  5. package/dist/llm.d.cts +1 -0
  6. package/dist/llm.d.ts +1 -0
  7. package/dist/llm.d.ts.map +1 -1
  8. package/dist/llm.js +3 -0
  9. package/dist/llm.js.map +1 -1
  10. package/dist/realtime/realtime_model.cjs +36 -4
  11. package/dist/realtime/realtime_model.cjs.map +1 -1
  12. package/dist/realtime/realtime_model.d.cts +19 -1
  13. package/dist/realtime/realtime_model.d.ts +19 -1
  14. package/dist/realtime/realtime_model.d.ts.map +1 -1
  15. package/dist/realtime/realtime_model.js +34 -3
  16. package/dist/realtime/realtime_model.js.map +1 -1
  17. package/dist/realtime/realtime_model.test.cjs +71 -0
  18. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  19. package/dist/realtime/realtime_model.test.js +77 -1
  20. package/dist/realtime/realtime_model.test.js.map +1 -1
  21. package/dist/stt.cjs +22 -14
  22. package/dist/stt.cjs.map +1 -1
  23. package/dist/stt.d.cts +16 -0
  24. package/dist/stt.d.ts +16 -0
  25. package/dist/stt.d.ts.map +1 -1
  26. package/dist/stt.js +20 -13
  27. package/dist/stt.js.map +1 -1
  28. package/dist/stt.test.cjs +51 -0
  29. package/dist/stt.test.cjs.map +1 -1
  30. package/dist/stt.test.js +52 -1
  31. package/dist/stt.test.js.map +1 -1
  32. package/dist/ws/llm.cjs +11 -3
  33. package/dist/ws/llm.cjs.map +1 -1
  34. package/dist/ws/llm.d.cts +16 -0
  35. package/dist/ws/llm.d.ts +16 -0
  36. package/dist/ws/llm.d.ts.map +1 -1
  37. package/dist/ws/llm.js +9 -2
  38. package/dist/ws/llm.js.map +1 -1
  39. package/dist/ws/llm.test.cjs +61 -18
  40. package/dist/ws/llm.test.cjs.map +1 -1
  41. package/dist/ws/llm.test.js +62 -19
  42. package/dist/ws/llm.test.js.map +1 -1
  43. package/package.json +5 -5
  44. package/src/llm.ts +5 -0
  45. package/src/realtime/realtime_model.test.ts +96 -1
  46. package/src/realtime/realtime_model.ts +46 -3
  47. package/src/stt.test.ts +64 -1
  48. package/src/stt.ts +37 -14
  49. package/src/ws/llm.test.ts +72 -19
  50. package/src/ws/llm.ts +25 -3
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ws/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { initializeLogger } from '@livekit/agents';\nimport { llm, llmStrict } from '@livekit/agents-plugins-test';\nimport { describe } from 'vitest';\nimport { LLM } from '../responses/llm.js';\n\ninitializeLogger({ level: 'silent', pretty: false });\n\ndescribe('OpenAI Responses WS wrapper', async () => {\n await llm(\n new LLM({\n temperature: 0,\n strictToolSchema: false,\n useWebSocket: true,\n }),\n true,\n );\n});\n\ndescribe('OpenAI Responses WS wrapper strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n useWebSocket: true,\n }),\n );\n});\n"],"mappings":"AAGA,SAAS,wBAAwB;AACjC,SAAS,KAAK,iBAAiB;AAC/B,SAAS,gBAAgB;AACzB,SAAS,WAAW;AAEpB,iBAAiB,EAAE,OAAO,UAAU,QAAQ,MAAM,CAAC;AAEnD,SAAS,+BAA+B,YAAY;AAClD,QAAM;AAAA,IACJ,IAAI,IAAI;AAAA,MACN,aAAa;AAAA,MACb,kBAAkB;AAAA,MAClB,cAAc;AAAA,IAChB,CAAC;AAAA,IACD;AAAA,EACF;AACF,CAAC;AAED,SAAS,kDAAkD,YAAY;AACrE,QAAM;AAAA,IACJ,IAAI,IAAI;AAAA,MACN,aAAa;AAAA,MACb,kBAAkB;AAAA,MAClB,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AACF,CAAC;","names":[]}
1
+ {"version":3,"sources":["../../src/ws/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { initializeLogger } from '@livekit/agents';\nimport { llm, llmStrict } from '@livekit/agents-plugins-test';\nimport { describe, expect, it } from 'vitest';\nimport { LLM } from '../responses/llm.js';\nimport { buildResponsesWsUrl } from './llm.js';\n\ninitializeLogger({ level: 'silent', pretty: false });\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\ndescribe('buildResponsesWsUrl', () => {\n it('points at the OpenAI Responses WS endpoint with model when no baseURL is set', () => {\n const url = new URL(buildResponsesWsUrl(undefined, 'gpt-4.1'));\n\n expect(url.protocol).toBe('wss:');\n expect(url.host).toBe('api.openai.com');\n expect(url.pathname).toBe('/v1/responses');\n expect(url.searchParams.get('model')).toBe('gpt-4.1');\n });\n\n it('rewrites https baseURL to wss and appends /responses with the model', () => {\n const url = new URL(buildResponsesWsUrl('https://gateway.example.com/v1', 'gpt-4o'));\n\n expect(url.protocol).toBe('wss:');\n expect(url.host).toBe('gateway.example.com');\n expect(url.pathname).toBe('/v1/responses');\n expect(url.searchParams.get('model')).toBe('gpt-4o');\n });\n\n it('strips a trailing slash on baseURL before appending /responses', () => {\n const url = new URL(buildResponsesWsUrl('https://gateway.example.com/v1/', 'gpt-4o-mini'));\n\n expect(url.pathname).toBe('/v1/responses');\n expect(url.searchParams.get('model')).toBe('gpt-4o-mini');\n });\n\n it('rewrites http baseURL to ws (not wss)', () => {\n const url = new URL(buildResponsesWsUrl('http://gateway.example.com/v1', 'gpt-4o-mini'));\n\n expect(url.protocol).toBe('ws:');\n expect(url.host).toBe('gateway.example.com');\n expect(url.pathname).toBe('/v1/responses');\n expect(url.searchParams.get('model')).toBe('gpt-4o-mini');\n });\n\n it('strips a trailing slash on an http baseURL before appending /responses', () => {\n const url = new URL(buildResponsesWsUrl('http://gateway.example.com/v1/', 'gpt-4o-mini'));\n\n expect(url.protocol).toBe('ws:');\n expect(url.pathname).toBe('/v1/responses');\n expect(url.searchParams.get('model')).toBe('gpt-4o-mini');\n });\n});\n\nif (hasOpenAIApiKey) {\n describe('OpenAI Responses WS wrapper', async () => {\n await llm(\n new LLM({\n temperature: 0,\n strictToolSchema: false,\n useWebSocket: true,\n }),\n true,\n );\n });\n\n describe('OpenAI Responses WS wrapper strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n useWebSocket: true,\n }),\n );\n });\n} else {\n describe('OpenAI Responses WS wrapper', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAAS,wBAAwB;AACjC,SAAS,KAAK,iBAAiB;AAC/B,SAAS,UAAU,QAAQ,UAAU;AACrC,SAAS,WAAW;AACpB,SAAS,2BAA2B;AAEpC,iBAAiB,EAAE,OAAO,UAAU,QAAQ,MAAM,CAAC;AAEnD,MAAM,kBAAkB,QAAQ,QAAQ,IAAI,cAAc;AAE1D,SAAS,uBAAuB,MAAM;AACpC,KAAG,gFAAgF,MAAM;AACvF,UAAM,MAAM,IAAI,IAAI,oBAAoB,QAAW,SAAS,CAAC;AAE7D,WAAO,IAAI,QAAQ,EAAE,KAAK,MAAM;AAChC,WAAO,IAAI,IAAI,EAAE,KAAK,gBAAgB;AACtC,WAAO,IAAI,QAAQ,EAAE,KAAK,eAAe;AACzC,WAAO,IAAI,aAAa,IAAI,OAAO,CAAC,EAAE,KAAK,SAAS;AAAA,EACtD,CAAC;AAED,KAAG,uEAAuE,MAAM;AAC9E,UAAM,MAAM,IAAI,IAAI,oBAAoB,kCAAkC,QAAQ,CAAC;AAEnF,WAAO,IAAI,QAAQ,EAAE,KAAK,MAAM;AAChC,WAAO,IAAI,IAAI,EAAE,KAAK,qBAAqB;AAC3C,WAAO,IAAI,QAAQ,EAAE,KAAK,eAAe;AACzC,WAAO,IAAI,aAAa,IAAI,OAAO,CAAC,EAAE,KAAK,QAAQ;AAAA,EACrD,CAAC;AAED,KAAG,kEAAkE,MAAM;AACzE,UAAM,MAAM,IAAI,IAAI,oBAAoB,mCAAmC,aAAa,CAAC;AAEzF,WAAO,IAAI,QAAQ,EAAE,KAAK,eAAe;AACzC,WAAO,IAAI,aAAa,IAAI,OAAO,CAAC,EAAE,KAAK,aAAa;AAAA,EAC1D,CAAC;AAED,KAAG,yCAAyC,MAAM;AAChD,UAAM,MAAM,IAAI,IAAI,oBAAoB,iCAAiC,aAAa,CAAC;AAEvF,WAAO,IAAI,QAAQ,EAAE,KAAK,KAAK;AAC/B,WAAO,IAAI,IAAI,EAAE,KAAK,qBAAqB;AAC3C,WAAO,IAAI,QAAQ,EAAE,KAAK,eAAe;AACzC,WAAO,IAAI,aAAa,IAAI,OAAO,CAAC,EAAE,KAAK,aAAa;AAAA,EAC1D,CAAC;AAED,KAAG,0EAA0E,MAAM;AACjF,UAAM,MAAM,IAAI,IAAI,oBAAoB,kCAAkC,aAAa,CAAC;AAExF,WAAO,IAAI,QAAQ,EAAE,KAAK,KAAK;AAC/B,WAAO,IAAI,QAAQ,EAAE,KAAK,eAAe;AACzC,WAAO,IAAI,aAAa,IAAI,OAAO,CAAC,EAAE,KAAK,aAAa;AAAA,EAC1D,CAAC;AACH,CAAC;AAED,IAAI,iBAAiB;AACnB,WAAS,+BAA+B,YAAY;AAClD,UAAM;AAAA,MACJ,IAAI,IAAI;AAAA,QACN,aAAa;AAAA,QACb,kBAAkB;AAAA,QAClB,cAAc;AAAA,MAChB,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF,CAAC;AAED,WAAS,kDAAkD,YAAY;AACrE,UAAM;AAAA,MACJ,IAAI,IAAI;AAAA,QACN,aAAa;AAAA,QACb,kBAAkB;AAAA,QAClB,cAAc;AAAA,MAChB,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,OAAO;AACL,WAAS,+BAA+B,MAAM;AAC5C,OAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livekit/agents-plugin-openai",
3
- "version": "1.4.2",
3
+ "version": "1.4.4",
4
4
  "description": "OpenAI plugin for LiveKit Node Agents",
5
5
  "main": "dist/index.js",
6
6
  "require": "dist/index.cjs",
@@ -30,9 +30,9 @@
30
30
  "@types/ws": "^8.5.10",
31
31
  "tsup": "^8.3.5",
32
32
  "typescript": "^5.0.0",
33
- "@livekit/agents": "1.4.2",
34
- "@livekit/agents-plugin-silero": "1.4.2",
35
- "@livekit/agents-plugins-test": "1.4.2"
33
+ "@livekit/agents": "1.4.4",
34
+ "@livekit/agents-plugin-silero": "1.4.4",
35
+ "@livekit/agents-plugins-test": "1.4.4"
36
36
  },
37
37
  "dependencies": {
38
38
  "@livekit/mutex": "^1.1.1",
@@ -42,7 +42,7 @@
42
42
  "peerDependencies": {
43
43
  "@livekit/rtc-node": "^0.13.27",
44
44
  "zod": "^3.25.76 || ^4.1.8",
45
- "@livekit/agents": "1.4.2"
45
+ "@livekit/agents": "1.4.4"
46
46
  },
47
47
  "scripts": {
48
48
  "build": "tsup --onSuccess \"pnpm build:types\"",
package/src/llm.ts CHANGED
@@ -23,6 +23,7 @@ export interface LLMOptions {
23
23
  baseURL?: string;
24
24
  user?: string;
25
25
  temperature?: number;
26
+ topP?: number;
26
27
  client?: OpenAI;
27
28
  toolChoice?: llm.ToolChoice;
28
29
  parallelToolCalls?: boolean;
@@ -499,6 +500,10 @@ export class LLM extends llm.LLM {
499
500
  extras.temperature = this.#opts.temperature;
500
501
  }
501
502
 
503
+ if (this.#opts.topP !== undefined) {
504
+ extras.top_p = this.#opts.topP;
505
+ }
506
+
502
507
  if (this.#opts.serviceTier) {
503
508
  extras.service_tier = this.#opts.serviceTier;
504
509
  }
@@ -4,7 +4,44 @@
4
4
  import { llm } from '@livekit/agents';
5
5
  import { afterEach, describe, expect, it, vi } from 'vitest';
6
6
  import type * as api_proto from './api_proto.js';
7
- import { RealtimeModel, livekitItemToOpenAIItem } from './realtime_model.js';
7
+ import {
8
+ RealtimeModel,
9
+ RealtimeSession,
10
+ livekitItemToOpenAIItem,
11
+ processBaseURL,
12
+ } from './realtime_model.js';
13
+
14
+ type RealtimeSessionInternals = {
15
+ generateReply: RealtimeSession['generateReply'];
16
+ responseCreatedFutures: Record<string, unknown>;
17
+ sendEvent: ReturnType<typeof vi.fn>;
18
+ textModeRecoveryRetries: number;
19
+ };
20
+
21
+ function createSessionForTest(): RealtimeSessionInternals {
22
+ const session = Object.create(RealtimeSession.prototype) as RealtimeSessionInternals;
23
+ session.responseCreatedFutures = {};
24
+ session.sendEvent = vi.fn();
25
+ session.textModeRecoveryRetries = 0;
26
+ return session;
27
+ }
28
+
29
+ describe('RealtimeSession.generateReply', () => {
30
+ it('cancels an in-flight response when aborted before response.created', async () => {
31
+ const session = createSessionForTest();
32
+ const abortController = new AbortController();
33
+
34
+ const promise = session.generateReply('say pineapple', { signal: abortController.signal });
35
+ abortController.abort();
36
+
37
+ await expect(promise).rejects.toThrow('generateReply aborted');
38
+ expect(Object.keys(session.responseCreatedFutures)).toHaveLength(0);
39
+ expect(session.sendEvent).toHaveBeenCalledWith(
40
+ expect.objectContaining({ type: 'response.create' }),
41
+ );
42
+ expect(session.sendEvent).toHaveBeenCalledWith({ type: 'response.cancel' });
43
+ });
44
+ });
8
45
 
9
46
  describe('livekitItemToOpenAIItem', () => {
10
47
  describe('message items', () => {
@@ -331,3 +368,61 @@ describe('RealtimeSession.updateOptions', () => {
331
368
  expect(sendEventSpyB).toHaveBeenCalledTimes(1);
332
369
  });
333
370
  });
371
+
372
+ describe('processBaseURL', () => {
373
+ it('upgrades https baseURL to wss and appends /realtime with model', () => {
374
+ const url = new URL(
375
+ processBaseURL({
376
+ baseURL: 'https://gateway.example.com/v1',
377
+ model: 'gpt-4o-realtime-preview',
378
+ isAzure: false,
379
+ }),
380
+ );
381
+
382
+ expect(url.protocol).toBe('wss:');
383
+ expect(url.host).toBe('gateway.example.com');
384
+ expect(url.pathname).toBe('/v1/realtime');
385
+ expect(url.searchParams.get('model')).toBe('gpt-4o-realtime-preview');
386
+ });
387
+
388
+ it('downgrades http baseURL to ws (not wss)', () => {
389
+ const url = new URL(
390
+ processBaseURL({
391
+ baseURL: 'http://gateway.example.com/v1',
392
+ model: 'gpt-4o-realtime-preview',
393
+ isAzure: false,
394
+ }),
395
+ );
396
+
397
+ expect(url.protocol).toBe('ws:');
398
+ expect(url.host).toBe('gateway.example.com');
399
+ expect(url.pathname).toBe('/v1/realtime');
400
+ expect(url.searchParams.get('model')).toBe('gpt-4o-realtime-preview');
401
+ });
402
+
403
+ it('passes through an already-wss baseURL unchanged', () => {
404
+ const url = new URL(
405
+ processBaseURL({
406
+ baseURL: 'wss://gateway.example.com/v1',
407
+ model: 'gpt-4o-realtime-preview',
408
+ isAzure: false,
409
+ }),
410
+ );
411
+
412
+ expect(url.protocol).toBe('wss:');
413
+ expect(url.pathname).toBe('/v1/realtime');
414
+ });
415
+
416
+ it('passes through an already-ws baseURL unchanged', () => {
417
+ const url = new URL(
418
+ processBaseURL({
419
+ baseURL: 'ws://gateway.example.com/v1',
420
+ model: 'gpt-4o-realtime-preview',
421
+ isAzure: false,
422
+ }),
423
+ );
424
+
425
+ expect(url.protocol).toBe('ws:');
426
+ expect(url.pathname).toBe('/v1/realtime');
427
+ });
428
+ });
@@ -153,6 +153,10 @@ export class RealtimeModel extends llm.RealtimeModel {
153
153
  }
154
154
  }
155
155
 
156
+ label(): string {
157
+ return 'openai.RealtimeModel';
158
+ }
159
+
156
160
  constructor(
157
161
  options: {
158
162
  model?: string;
@@ -346,7 +350,15 @@ function normalizeAzureClientEvent(event: Record<string, unknown>): void {
346
350
  }
347
351
  }
348
352
 
349
- function processBaseURL({
353
+ /**
354
+ * Build the conversational Realtime API WebSocket URL.
355
+ *
356
+ * The scheme of `baseURL` is respected: `http://` maps to `ws://`
357
+ * and `https://` maps to `wss://`.
358
+ *
359
+ * @internal
360
+ */
361
+ export function processBaseURL({
350
362
  baseURL,
351
363
  model,
352
364
  isAzure = false,
@@ -365,6 +377,8 @@ function processBaseURL({
365
377
 
366
378
  if (url.protocol === 'https:') {
367
379
  url.protocol = 'wss:';
380
+ } else if (url.protocol === 'http:') {
381
+ url.protocol = 'ws:';
368
382
  }
369
383
 
370
384
  // ensure "/realtime" is added if the path is empty OR "/v1"
@@ -813,10 +827,39 @@ export class RealtimeSession extends llm.RealtimeSession {
813
827
  this.pushedDurationMs = 0;
814
828
  }
815
829
 
816
- async generateReply(instructions?: string): Promise<llm.GenerationCreatedEvent> {
830
+ async generateReply(
831
+ instructions?: string,
832
+ options: { signal?: AbortSignal } = {},
833
+ ): Promise<llm.GenerationCreatedEvent> {
817
834
  const handle = this.createResponse({ instructions, userInitiated: true });
818
835
  this.textModeRecoveryRetries = 0;
819
- return handle.doneFut.await;
836
+
837
+ const onAbort = () => {
838
+ const eventId = Object.entries(this.responseCreatedFutures).find(
839
+ ([, pendingHandle]) => pendingHandle === handle,
840
+ )?.[0];
841
+ if (eventId) {
842
+ delete this.responseCreatedFutures[eventId];
843
+ }
844
+ if (!handle.doneFut.done) {
845
+ handle.doneFut.reject(new Error('generateReply aborted'));
846
+ this.sendEvent({
847
+ type: 'response.cancel',
848
+ } as api_proto.ResponseCancelEvent);
849
+ }
850
+ };
851
+
852
+ if (options.signal?.aborted) {
853
+ onAbort();
854
+ } else {
855
+ options.signal?.addEventListener('abort', onAbort, { once: true });
856
+ }
857
+
858
+ try {
859
+ return await handle.doneFut.await;
860
+ } finally {
861
+ options.signal?.removeEventListener('abort', onAbort);
862
+ }
820
863
  }
821
864
 
822
865
  async interrupt(): Promise<void> {
package/src/stt.test.ts CHANGED
@@ -6,7 +6,7 @@ import { VAD } from '@livekit/agents-plugin-silero';
6
6
  import { stt } from '@livekit/agents-plugins-test';
7
7
  import { describe, expect, it, vi } from 'vitest';
8
8
  import type { SpeechStream } from './stt.js';
9
- import { STT } from './stt.js';
9
+ import { STT, buildRealtimeSttUrl } from './stt.js';
10
10
 
11
11
  const hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);
12
12
 
@@ -73,6 +73,69 @@ describe('OpenAI STT options', () => {
73
73
  });
74
74
  });
75
75
 
76
+ describe('buildRealtimeSttUrl', () => {
77
+ it('points at OpenAI realtime with intent and model when no baseURL is set', () => {
78
+ const url = new URL(buildRealtimeSttUrl(undefined, 'gpt-realtime-whisper'));
79
+
80
+ expect(url.protocol).toBe('wss:');
81
+ expect(url.host).toBe('api.openai.com');
82
+ expect(url.pathname).toBe('/v1/realtime');
83
+ expect(url.searchParams.get('intent')).toBe('transcription');
84
+ expect(url.searchParams.get('model')).toBe('gpt-realtime-whisper');
85
+ });
86
+
87
+ it('upgrades https baseURL to wss and appends /realtime when path is /v1', () => {
88
+ const url = new URL(
89
+ buildRealtimeSttUrl('https://gateway.example.com/v1', 'gpt-4o-mini-transcribe'),
90
+ );
91
+
92
+ expect(url.protocol).toBe('wss:');
93
+ expect(url.host).toBe('gateway.example.com');
94
+ expect(url.pathname).toBe('/v1/realtime');
95
+ expect(url.searchParams.get('model')).toBe('gpt-4o-mini-transcribe');
96
+ });
97
+
98
+ it('preserves an existing /realtime path without duplicating it', () => {
99
+ const url = new URL(
100
+ buildRealtimeSttUrl('wss://gateway.example.com/v1/realtime', 'gpt-realtime-whisper'),
101
+ );
102
+
103
+ expect(url.pathname).toBe('/v1/realtime');
104
+ expect(url.searchParams.get('model')).toBe('gpt-realtime-whisper');
105
+ });
106
+
107
+ it('appends /realtime to a non-/v1 path', () => {
108
+ const url = new URL(
109
+ buildRealtimeSttUrl('https://gateway.example.com/proxy/openai', 'gpt-realtime-whisper'),
110
+ );
111
+
112
+ expect(url.pathname).toBe('/proxy/openai/realtime');
113
+ expect(url.searchParams.get('intent')).toBe('transcription');
114
+ expect(url.searchParams.get('model')).toBe('gpt-realtime-whisper');
115
+ });
116
+
117
+ it('downgrades http baseURL to ws (not wss)', () => {
118
+ const url = new URL(
119
+ buildRealtimeSttUrl('http://gateway.example.com/v1', 'gpt-realtime-whisper'),
120
+ );
121
+
122
+ expect(url.protocol).toBe('ws:');
123
+ expect(url.host).toBe('gateway.example.com');
124
+ expect(url.pathname).toBe('/v1/realtime');
125
+ expect(url.searchParams.get('intent')).toBe('transcription');
126
+ expect(url.searchParams.get('model')).toBe('gpt-realtime-whisper');
127
+ });
128
+
129
+ it('downgrades http baseURL with a trailing slash to ws', () => {
130
+ const url = new URL(
131
+ buildRealtimeSttUrl('http://gateway.example.com/v1/', 'gpt-realtime-whisper'),
132
+ );
133
+
134
+ expect(url.protocol).toBe('ws:');
135
+ expect(url.pathname).toBe('/v1/realtime');
136
+ });
137
+ });
138
+
76
139
  if (hasOpenAIApiKey) {
77
140
  describe('OpenAI STT integration', async () => {
78
141
  const vad = await VAD.load();
package/src/stt.ts CHANGED
@@ -24,6 +24,42 @@ import type * as api_proto from './realtime/api_proto.js';
24
24
  const REALTIME_SAMPLE_RATE = 24000;
25
25
  const REALTIME_NUM_CHANNELS = 1;
26
26
  const DEFAULT_REALTIME_MODEL = 'gpt-realtime-whisper';
27
+
28
+ /**
29
+ * Build the realtime transcription WebSocket URL.
30
+ *
31
+ * Includes the model on the upgrade URL so OpenAI-compatible gateways
32
+ * (which can only see the URL at the WebSocket upgrade, not the subsequent
33
+ * `session.update` frame) can route by model. Mirrors the existing
34
+ * convention in `realtime/realtime_model.ts` for the conversational
35
+ * Realtime API. OpenAI's native endpoint accepts and ignores the
36
+ * parameter, so this is a no-op for direct connections.
37
+ *
38
+ * The scheme of `baseURL` is respected: `http://` maps to `ws://`
39
+ * and `https://` maps to `wss://`.
40
+ *
41
+ * @internal
42
+ */
43
+ export function buildRealtimeSttUrl(baseURL: string | undefined, model: string): string {
44
+ const url = new URL(baseURL || 'https://api.openai.com/v1');
45
+ if (url.protocol === 'https:') {
46
+ url.protocol = 'wss:';
47
+ } else if (url.protocol === 'http:') {
48
+ url.protocol = 'ws:';
49
+ }
50
+
51
+ const path = url.pathname.replace(/\/$/, '');
52
+ if (!path || path === '/v1') {
53
+ url.pathname = `${path}/realtime`;
54
+ } else if (!path.endsWith('/realtime')) {
55
+ url.pathname = `${path}/realtime`;
56
+ }
57
+
58
+ url.searchParams.set('intent', 'transcription');
59
+ url.searchParams.set('model', model);
60
+ return url.toString();
61
+ }
62
+
27
63
  const DEFAULT_REALTIME_TURN_DETECTION: api_proto.TurnDetectionType = {
28
64
  type: 'server_vad',
29
65
  threshold: 0.5,
@@ -530,20 +566,7 @@ export class SpeechStream extends stt.SpeechStream {
530
566
  }
531
567
 
532
568
  #realtimeUrl(): string {
533
- const url = new URL(this.#options.baseURL || 'https://api.openai.com/v1');
534
- if (url.protocol === 'https:') {
535
- url.protocol = 'wss:';
536
- }
537
-
538
- const path = url.pathname.replace(/\/$/, '');
539
- if (!path || path === '/v1') {
540
- url.pathname = `${path}/realtime`;
541
- } else if (!path.endsWith('/realtime')) {
542
- url.pathname = `${path}/realtime`;
543
- }
544
-
545
- url.searchParams.set('intent', 'transcription');
546
- return url.toString();
569
+ return buildRealtimeSttUrl(this.#options.baseURL, this.#options.model);
547
570
  }
548
571
 
549
572
  #sessionUpdateEvent(): api_proto.SessionUpdateEvent {
@@ -3,28 +3,81 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  import { initializeLogger } from '@livekit/agents';
5
5
  import { llm, llmStrict } from '@livekit/agents-plugins-test';
6
- import { describe } from 'vitest';
6
+ import { describe, expect, it } from 'vitest';
7
7
  import { LLM } from '../responses/llm.js';
8
+ import { buildResponsesWsUrl } from './llm.js';
8
9
 
9
10
  initializeLogger({ level: 'silent', pretty: false });
10
11
 
11
- describe('OpenAI Responses WS wrapper', async () => {
12
- await llm(
13
- new LLM({
14
- temperature: 0,
15
- strictToolSchema: false,
16
- useWebSocket: true,
17
- }),
18
- true,
19
- );
20
- });
12
+ const hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);
13
+
14
+ describe('buildResponsesWsUrl', () => {
15
+ it('points at the OpenAI Responses WS endpoint with model when no baseURL is set', () => {
16
+ const url = new URL(buildResponsesWsUrl(undefined, 'gpt-4.1'));
17
+
18
+ expect(url.protocol).toBe('wss:');
19
+ expect(url.host).toBe('api.openai.com');
20
+ expect(url.pathname).toBe('/v1/responses');
21
+ expect(url.searchParams.get('model')).toBe('gpt-4.1');
22
+ });
23
+
24
+ it('rewrites https baseURL to wss and appends /responses with the model', () => {
25
+ const url = new URL(buildResponsesWsUrl('https://gateway.example.com/v1', 'gpt-4o'));
26
+
27
+ expect(url.protocol).toBe('wss:');
28
+ expect(url.host).toBe('gateway.example.com');
29
+ expect(url.pathname).toBe('/v1/responses');
30
+ expect(url.searchParams.get('model')).toBe('gpt-4o');
31
+ });
32
+
33
+ it('strips a trailing slash on baseURL before appending /responses', () => {
34
+ const url = new URL(buildResponsesWsUrl('https://gateway.example.com/v1/', 'gpt-4o-mini'));
21
35
 
22
- describe('OpenAI Responses WS wrapper strict tool schema', async () => {
23
- await llmStrict(
24
- new LLM({
25
- temperature: 0,
26
- strictToolSchema: true,
27
- useWebSocket: true,
28
- }),
29
- );
36
+ expect(url.pathname).toBe('/v1/responses');
37
+ expect(url.searchParams.get('model')).toBe('gpt-4o-mini');
38
+ });
39
+
40
+ it('rewrites http baseURL to ws (not wss)', () => {
41
+ const url = new URL(buildResponsesWsUrl('http://gateway.example.com/v1', 'gpt-4o-mini'));
42
+
43
+ expect(url.protocol).toBe('ws:');
44
+ expect(url.host).toBe('gateway.example.com');
45
+ expect(url.pathname).toBe('/v1/responses');
46
+ expect(url.searchParams.get('model')).toBe('gpt-4o-mini');
47
+ });
48
+
49
+ it('strips a trailing slash on an http baseURL before appending /responses', () => {
50
+ const url = new URL(buildResponsesWsUrl('http://gateway.example.com/v1/', 'gpt-4o-mini'));
51
+
52
+ expect(url.protocol).toBe('ws:');
53
+ expect(url.pathname).toBe('/v1/responses');
54
+ expect(url.searchParams.get('model')).toBe('gpt-4o-mini');
55
+ });
30
56
  });
57
+
58
+ if (hasOpenAIApiKey) {
59
+ describe('OpenAI Responses WS wrapper', async () => {
60
+ await llm(
61
+ new LLM({
62
+ temperature: 0,
63
+ strictToolSchema: false,
64
+ useWebSocket: true,
65
+ }),
66
+ true,
67
+ );
68
+ });
69
+
70
+ describe('OpenAI Responses WS wrapper strict tool schema', async () => {
71
+ await llmStrict(
72
+ new LLM({
73
+ temperature: 0,
74
+ strictToolSchema: true,
75
+ useWebSocket: true,
76
+ }),
77
+ );
78
+ });
79
+ } else {
80
+ describe('OpenAI Responses WS wrapper', () => {
81
+ it.skip('requires OPENAI_API_KEY', () => {});
82
+ });
83
+ }
package/src/ws/llm.ts CHANGED
@@ -31,6 +31,30 @@ const OPENAI_RESPONSES_WS_URL = 'wss://api.openai.com/v1/responses';
31
31
  // OpenAI enforces a 60-minute maximum duration on Responses WebSocket connections.
32
32
  const WS_MAX_SESSION_DURATION = 3_600_000;
33
33
 
34
+ /**
35
+ * Build the Responses-API WebSocket URL.
36
+ *
37
+ * Includes the model on the upgrade URL so OpenAI-compatible gateways
38
+ * (which can only see the URL at the WebSocket upgrade, not the subsequent
39
+ * `response.create` frame) can route by model. Mirrors the existing
40
+ * convention in `realtime/realtime_model.ts` for the conversational
41
+ * Realtime API. OpenAI's native endpoint accepts and ignores the
42
+ * parameter, so this is a no-op for direct connections.
43
+ *
44
+ * The scheme of `baseURL` is respected: `http://` maps to `ws://`
45
+ * and `https://` maps to `wss://`.
46
+ *
47
+ * @internal
48
+ */
49
+ export function buildResponsesWsUrl(baseURL: string | undefined, model: string): string {
50
+ const base = baseURL
51
+ ? `${baseURL.replace(/^http(s?):/, 'ws$1:').replace(/\/+$/, '')}/responses`
52
+ : OPENAI_RESPONSES_WS_URL;
53
+ const url = new URL(base);
54
+ url.searchParams.set('model', model);
55
+ return url.toString();
56
+ }
57
+
34
58
  // ============================================================================
35
59
  // Internal: ResponsesWebSocket
36
60
  //
@@ -186,9 +210,7 @@ export class WSLLM extends llm.LLM {
186
210
  this.#pool = new ConnectionPool<ResponsesWebSocket>({
187
211
  maxSessionDuration: WS_MAX_SESSION_DURATION,
188
212
  connectCb: async (timeoutMs: number) => {
189
- const wsUrl = this.#opts.baseURL
190
- ? `${this.#opts.baseURL.replace(/^https?/, 'wss').replace(/\/+$/, '')}/responses`
191
- : OPENAI_RESPONSES_WS_URL;
213
+ const wsUrl = buildResponsesWsUrl(this.#opts.baseURL, String(this.#opts.model));
192
214
  const ws = await connectWs(wsUrl, this.#opts.apiKey!, timeoutMs);
193
215
  return new ResponsesWebSocket(ws);
194
216
  },