@livekit/agents-plugin-openai 1.4.3 → 1.4.5

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 (61) 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/api_proto.cjs.map +1 -1
  11. package/dist/realtime/api_proto.d.cts +8 -2
  12. package/dist/realtime/api_proto.d.ts +8 -2
  13. package/dist/realtime/api_proto.d.ts.map +1 -1
  14. package/dist/realtime/api_proto.js.map +1 -1
  15. package/dist/realtime/realtime_model.cjs +118 -13
  16. package/dist/realtime/realtime_model.cjs.map +1 -1
  17. package/dist/realtime/realtime_model.d.cts +23 -1
  18. package/dist/realtime/realtime_model.d.ts +23 -1
  19. package/dist/realtime/realtime_model.d.ts.map +1 -1
  20. package/dist/realtime/realtime_model.js +116 -12
  21. package/dist/realtime/realtime_model.js.map +1 -1
  22. package/dist/realtime/realtime_model.test.cjs +307 -9
  23. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  24. package/dist/realtime/realtime_model.test.js +314 -11
  25. package/dist/realtime/realtime_model.test.js.map +1 -1
  26. package/dist/responses/llm.cjs +1 -1
  27. package/dist/responses/llm.cjs.map +1 -1
  28. package/dist/responses/llm.js +1 -1
  29. package/dist/responses/llm.js.map +1 -1
  30. package/dist/stt.cjs +2 -0
  31. package/dist/stt.cjs.map +1 -1
  32. package/dist/stt.d.cts +3 -0
  33. package/dist/stt.d.ts +3 -0
  34. package/dist/stt.d.ts.map +1 -1
  35. package/dist/stt.js +2 -0
  36. package/dist/stt.js.map +1 -1
  37. package/dist/stt.test.cjs +17 -0
  38. package/dist/stt.test.cjs.map +1 -1
  39. package/dist/stt.test.js +17 -0
  40. package/dist/stt.test.js.map +1 -1
  41. package/dist/ws/llm.cjs +2 -2
  42. package/dist/ws/llm.cjs.map +1 -1
  43. package/dist/ws/llm.d.cts +3 -0
  44. package/dist/ws/llm.d.ts +3 -0
  45. package/dist/ws/llm.d.ts.map +1 -1
  46. package/dist/ws/llm.js +2 -2
  47. package/dist/ws/llm.js.map +1 -1
  48. package/dist/ws/llm.test.cjs +13 -0
  49. package/dist/ws/llm.test.cjs.map +1 -1
  50. package/dist/ws/llm.test.js +13 -0
  51. package/dist/ws/llm.test.js.map +1 -1
  52. package/package.json +7 -7
  53. package/src/llm.ts +5 -0
  54. package/src/realtime/api_proto.ts +9 -0
  55. package/src/realtime/realtime_model.test.ts +417 -13
  56. package/src/realtime/realtime_model.ts +143 -15
  57. package/src/responses/llm.ts +1 -1
  58. package/src/stt.test.ts +21 -0
  59. package/src/stt.ts +5 -0
  60. package/src/ws/llm.test.ts +17 -0
  61. package/src/ws/llm.ts +5 -2
@@ -225,7 +225,7 @@ export class RealtimeModel extends llm.RealtimeModel {
225
225
  this._options = {
226
226
  ...DEFAULT_REALTIME_MODEL_OPTIONS,
227
227
  ...optionsWithoutModalities,
228
- baseURL: options.baseURL || BASE_URL,
228
+ baseURL: options.baseURL || process.env.OPENAI_BASE_URL || BASE_URL,
229
229
  apiKey,
230
230
  isAzure,
231
231
  model: options.model || DEFAULT_REALTIME_MODEL_OPTIONS.model,
@@ -350,7 +350,15 @@ function normalizeAzureClientEvent(event: Record<string, unknown>): void {
350
350
  }
351
351
  }
352
352
 
353
- 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({
354
362
  baseURL,
355
363
  model,
356
364
  isAzure = false,
@@ -369,6 +377,8 @@ function processBaseURL({
369
377
 
370
378
  if (url.protocol === 'https:') {
371
379
  url.protocol = 'wss:';
380
+ } else if (url.protocol === 'http:') {
381
+ url.protocol = 'ws:';
372
382
  }
373
383
 
374
384
  // ensure "/realtime" is added if the path is empty OR "/v1"
@@ -431,6 +441,8 @@ export class RealtimeSession extends llm.RealtimeSession {
431
441
  private itemCreateFutures: { [id: string]: Future } = {};
432
442
  private itemDeleteFutures: { [id: string]: Future } = {};
433
443
 
444
+ private inputTranscriptAccumulators = new Map<string, Map<number, string>>();
445
+
434
446
  // Track items that have real server-side audio (created in current session, not restored)
435
447
  // Items restored after reconnection are text-only and cannot be truncated
436
448
  private audioCapableItemIds: Set<string> = new Set();
@@ -817,10 +829,39 @@ export class RealtimeSession extends llm.RealtimeSession {
817
829
  this.pushedDurationMs = 0;
818
830
  }
819
831
 
820
- async generateReply(instructions?: string): Promise<llm.GenerationCreatedEvent> {
832
+ async generateReply(
833
+ instructions?: string,
834
+ options: { signal?: AbortSignal } = {},
835
+ ): Promise<llm.GenerationCreatedEvent> {
821
836
  const handle = this.createResponse({ instructions, userInitiated: true });
822
837
  this.textModeRecoveryRetries = 0;
823
- return handle.doneFut.await;
838
+
839
+ const onAbort = () => {
840
+ const eventId = Object.entries(this.responseCreatedFutures).find(
841
+ ([, pendingHandle]) => pendingHandle === handle,
842
+ )?.[0];
843
+ if (eventId) {
844
+ delete this.responseCreatedFutures[eventId];
845
+ }
846
+ if (!handle.doneFut.done) {
847
+ handle.doneFut.reject(new Error('generateReply aborted'));
848
+ this.sendEvent({
849
+ type: 'response.cancel',
850
+ } as api_proto.ResponseCancelEvent);
851
+ }
852
+ };
853
+
854
+ if (options.signal?.aborted) {
855
+ onAbort();
856
+ } else {
857
+ options.signal?.addEventListener('abort', onAbort, { once: true });
858
+ }
859
+
860
+ try {
861
+ return await handle.doneFut.await;
862
+ } finally {
863
+ options.signal?.removeEventListener('abort', onAbort);
864
+ }
824
865
  }
825
866
 
826
867
  async interrupt(): Promise<void> {
@@ -991,6 +1032,7 @@ export class RealtimeSession extends llm.RealtimeSession {
991
1032
 
992
1033
  // Clear audio-capable item tracking - restored items are text-only on the server
993
1034
  this.audioCapableItemIds.clear();
1035
+ this.inputTranscriptAccumulators.clear();
994
1036
 
995
1037
  const events: api_proto.ClientEvent[] = [];
996
1038
 
@@ -1159,6 +1201,9 @@ export class RealtimeSession extends llm.RealtimeSession {
1159
1201
  case 'conversation.item.deleted':
1160
1202
  this.handleConversationItemDeleted(event);
1161
1203
  break;
1204
+ case 'conversation.item.input_audio_transcription.delta':
1205
+ this.handleConversationItemInputAudioTranscriptionDelta(event);
1206
+ break;
1162
1207
  case 'conversation.item.input_audio_transcription.completed':
1163
1208
  this.handleConversationItemInputAudioTranscriptionCompleted(event);
1164
1209
  break;
@@ -1274,6 +1319,8 @@ export class RealtimeSession extends llm.RealtimeSession {
1274
1319
  }
1275
1320
  this.itemDeleteFutures = {};
1276
1321
 
1322
+ this.inputTranscriptAccumulators.clear();
1323
+
1277
1324
  // Clean up current generation if exists
1278
1325
  if (this.currentGeneration) {
1279
1326
  for (const gen of this.currentGeneration.messages.values()) {
@@ -1431,6 +1478,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1431
1478
 
1432
1479
  // Clean up audio-capable tracking for deleted items
1433
1480
  this.audioCapableItemIds.delete(event.item_id);
1481
+ this.inputTranscriptAccumulators.delete(event.item_id);
1434
1482
 
1435
1483
  try {
1436
1484
  this.remoteChatCtx.delete(event.item_id);
@@ -1445,26 +1493,56 @@ export class RealtimeSession extends llm.RealtimeSession {
1445
1493
  }
1446
1494
  }
1447
1495
 
1496
+ private handleConversationItemInputAudioTranscriptionDelta(
1497
+ event: api_proto.ConversationItemInputAudioTranscriptionDeltaEvent,
1498
+ ): void {
1499
+ if (!event.delta) return;
1500
+
1501
+ const contentIndex = event.content_index ?? 0;
1502
+ let byIndex = this.inputTranscriptAccumulators.get(event.item_id);
1503
+ if (!byIndex) {
1504
+ byIndex = new Map();
1505
+ this.inputTranscriptAccumulators.set(event.item_id, byIndex);
1506
+ }
1507
+ const accumulated = (byIndex.get(contentIndex) ?? '') + event.delta;
1508
+ byIndex.set(contentIndex, accumulated);
1509
+
1510
+ this.emit('input_audio_transcription_completed', {
1511
+ itemId: event.item_id,
1512
+ transcript: accumulated,
1513
+ isFinal: false,
1514
+ });
1515
+ }
1516
+
1517
+ private clearAccumulator(itemId: string, contentIndex: number): string | undefined {
1518
+ const byIndex = this.inputTranscriptAccumulators.get(itemId);
1519
+ if (!byIndex) return undefined;
1520
+ const partial = byIndex.get(contentIndex);
1521
+ byIndex.delete(contentIndex);
1522
+ if (byIndex.size === 0) this.inputTranscriptAccumulators.delete(itemId);
1523
+ return partial;
1524
+ }
1525
+
1448
1526
  private handleConversationItemInputAudioTranscriptionCompleted(
1449
1527
  event: api_proto.ConversationItemInputAudioTranscriptionCompletedEvent,
1450
1528
  ): void {
1451
- const remoteItem = this.remoteChatCtx.get(event.item_id);
1452
- if (!remoteItem) {
1453
- return;
1454
- }
1529
+ this.clearAccumulator(event.item_id, event.content_index ?? 0);
1455
1530
 
1456
- const item = remoteItem.item;
1457
- if (item instanceof llm.ChatMessage) {
1458
- item.content.push(event.transcript);
1459
- } else {
1460
- throw new Error('item is not a chat message');
1531
+ const remoteItem = this.remoteChatCtx.get(event.item_id);
1532
+ if (remoteItem) {
1533
+ const item = remoteItem.item;
1534
+ if (item instanceof llm.ChatMessage) {
1535
+ item.content.push(event.transcript);
1536
+ } else {
1537
+ throw new Error('item is not a chat message');
1538
+ }
1461
1539
  }
1462
1540
 
1463
1541
  this.emit('input_audio_transcription_completed', {
1464
1542
  itemId: event.item_id,
1465
1543
  transcript: event.transcript,
1466
1544
  isFinal: true,
1467
- } as llm.InputTranscriptionCompleted);
1545
+ });
1468
1546
  }
1469
1547
 
1470
1548
  private handleConversationItemInputAudioTranscriptionFailed(
@@ -1474,6 +1552,18 @@ export class RealtimeSession extends llm.RealtimeSession {
1474
1552
  { error: event.error },
1475
1553
  'OpenAI Realtime API failed to transcribe input audio',
1476
1554
  );
1555
+ this.finalizePartialOnTranscriptionFailure(event.item_id, event.content_index ?? 0);
1556
+ }
1557
+
1558
+ // Close any open partial stream so consumers waiting for isFinal don't hang.
1559
+ private finalizePartialOnTranscriptionFailure(itemId: string, contentIndex: number): void {
1560
+ const partial = this.clearAccumulator(itemId, contentIndex);
1561
+ if (partial === undefined) return;
1562
+ this.emit('input_audio_transcription_completed', {
1563
+ itemId,
1564
+ transcript: partial,
1565
+ isFinal: true,
1566
+ });
1477
1567
  }
1478
1568
 
1479
1569
  private handleResponseContentPartAdded(event: api_proto.ResponseContentPartAddedEvent): void {
@@ -1736,7 +1826,44 @@ export class RealtimeSession extends llm.RealtimeSession {
1736
1826
  };
1737
1827
 
1738
1828
  this.emit('metrics_collected', realtimeMetrics);
1739
- // TODO(brian): handle response done but not complete
1829
+ this.handleResponseDoneButNotComplete(_event);
1830
+ }
1831
+
1832
+ private handleResponseDoneButNotComplete(event: api_proto.ResponseDoneEvent): void {
1833
+ if (event.response.status === 'completed') {
1834
+ return;
1835
+ }
1836
+
1837
+ const statusDetails = event.response.status_details;
1838
+ if (event.response.status === 'failed') {
1839
+ const errorBody = statusDetails?.type === 'failed' ? statusDetails.error : undefined;
1840
+ const errorTypeValue = errorBody && 'type' in errorBody ? errorBody.type : undefined;
1841
+ const errorType = typeof errorTypeValue === 'string' ? errorTypeValue : 'unknown';
1842
+
1843
+ this.emitError({
1844
+ error: new APIError(`OpenAI Realtime API response failed with error type: ${errorType}`, {
1845
+ body: errorBody ?? null,
1846
+ retryable: true,
1847
+ }),
1848
+ recoverable: true,
1849
+ });
1850
+ } else if (event.response.status === 'cancelled' || event.response.status === 'incomplete') {
1851
+ const statusType = statusDetails?.type;
1852
+ const statusReason =
1853
+ statusDetails && 'reason' in statusDetails ? statusDetails.reason : undefined;
1854
+
1855
+ this.#logger.debug(
1856
+ {
1857
+ eventId: event.response.id,
1858
+ eventResponseStatus: event.response.status,
1859
+ eventResponseStatusType: statusType,
1860
+ eventResponseStatusReason: statusReason,
1861
+ },
1862
+ `OpenAI Realtime API response done but not complete with status: ${event.response.status} (type=${statusType}, reason=${statusReason})`,
1863
+ );
1864
+ } else {
1865
+ this.#logger.debug({ eventResponseStatus: event.response.status }, 'Unknown response status');
1866
+ }
1740
1867
  }
1741
1868
 
1742
1869
  private handleError(event: api_proto.ErrorEvent): void {
@@ -1768,6 +1895,7 @@ export class RealtimeSession extends llm.RealtimeSession {
1768
1895
  private emitError({ error, recoverable }: { error: Error; recoverable: boolean }): void {
1769
1896
  // IMPORTANT: only emit error if there are listeners; otherwise emit will throw an error
1770
1897
  this.emit('error', {
1898
+ type: 'realtime_model_error',
1771
1899
  timestamp: Date.now(),
1772
1900
  // TODO(brian): add label
1773
1901
  label: '',
@@ -182,7 +182,7 @@ class ResponsesHttpLLMStream extends llm.LLMStream {
182
182
  )) as OpenAI.Responses.ResponseInputItem[];
183
183
 
184
184
  const tools = this.toolCtx
185
- ? Object.entries(this.toolCtx).map(([name, func]) => {
185
+ ? llm.sortedToolEntries(this.toolCtx).map(([name, func]) => {
186
186
  const oaiParams = {
187
187
  type: 'function' as const,
188
188
  name: name,
package/src/stt.test.ts CHANGED
@@ -113,6 +113,27 @@ describe('buildRealtimeSttUrl', () => {
113
113
  expect(url.searchParams.get('intent')).toBe('transcription');
114
114
  expect(url.searchParams.get('model')).toBe('gpt-realtime-whisper');
115
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
+ });
116
137
  });
117
138
 
118
139
  if (hasOpenAIApiKey) {
package/src/stt.ts CHANGED
@@ -35,12 +35,17 @@ const DEFAULT_REALTIME_MODEL = 'gpt-realtime-whisper';
35
35
  * Realtime API. OpenAI's native endpoint accepts and ignores the
36
36
  * parameter, so this is a no-op for direct connections.
37
37
  *
38
+ * The scheme of `baseURL` is respected: `http://` maps to `ws://`
39
+ * and `https://` maps to `wss://`.
40
+ *
38
41
  * @internal
39
42
  */
40
43
  export function buildRealtimeSttUrl(baseURL: string | undefined, model: string): string {
41
44
  const url = new URL(baseURL || 'https://api.openai.com/v1');
42
45
  if (url.protocol === 'https:') {
43
46
  url.protocol = 'wss:';
47
+ } else if (url.protocol === 'http:') {
48
+ url.protocol = 'ws:';
44
49
  }
45
50
 
46
51
  const path = url.pathname.replace(/\/$/, '');
@@ -36,6 +36,23 @@ describe('buildResponsesWsUrl', () => {
36
36
  expect(url.pathname).toBe('/v1/responses');
37
37
  expect(url.searchParams.get('model')).toBe('gpt-4o-mini');
38
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
+ });
39
56
  });
40
57
 
41
58
  if (hasOpenAIApiKey) {
package/src/ws/llm.ts CHANGED
@@ -41,11 +41,14 @@ const WS_MAX_SESSION_DURATION = 3_600_000;
41
41
  * Realtime API. OpenAI's native endpoint accepts and ignores the
42
42
  * parameter, so this is a no-op for direct connections.
43
43
  *
44
+ * The scheme of `baseURL` is respected: `http://` maps to `ws://`
45
+ * and `https://` maps to `wss://`.
46
+ *
44
47
  * @internal
45
48
  */
46
49
  export function buildResponsesWsUrl(baseURL: string | undefined, model: string): string {
47
50
  const base = baseURL
48
- ? `${baseURL.replace(/^https?/, 'wss').replace(/\/+$/, '')}/responses`
51
+ ? `${baseURL.replace(/^http(s?):/, 'ws$1:').replace(/\/+$/, '')}/responses`
49
52
  : OPENAI_RESPONSES_WS_URL;
50
53
  const url = new URL(base);
51
54
  url.searchParams.set('model', model);
@@ -444,7 +447,7 @@ export class WSLLMStream extends llm.LLMStream {
444
447
  )) as OpenAI.Responses.ResponseInputItem[];
445
448
 
446
449
  const tools = this.toolCtx
447
- ? Object.entries(this.toolCtx).map(([name, func]) => {
450
+ ? llm.sortedToolEntries(this.toolCtx).map(([name, func]) => {
448
451
  const oaiParams = {
449
452
  type: 'function' as const,
450
453
  name,