@livekit/agents-plugin-openai 1.9.0 → 1.9.2

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 (46) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/models.cjs +14 -1
  4. package/dist/models.cjs.map +1 -1
  5. package/dist/models.d.cts +2 -2
  6. package/dist/models.d.ts +2 -2
  7. package/dist/models.d.ts.map +1 -1
  8. package/dist/models.js +14 -1
  9. package/dist/models.js.map +1 -1
  10. package/dist/realtime/gpt_live_model.cjs.map +1 -1
  11. package/dist/realtime/gpt_live_model.js.map +1 -1
  12. package/dist/realtime/realtime_model.cjs +88 -20
  13. package/dist/realtime/realtime_model.cjs.map +1 -1
  14. package/dist/realtime/realtime_model.d.cts +4 -0
  15. package/dist/realtime/realtime_model.d.ts +4 -0
  16. package/dist/realtime/realtime_model.d.ts.map +1 -1
  17. package/dist/realtime/realtime_model.js +88 -20
  18. package/dist/realtime/realtime_model.js.map +1 -1
  19. package/dist/realtime/realtime_model.test.cjs +176 -0
  20. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  21. package/dist/realtime/realtime_model.test.js +176 -0
  22. package/dist/realtime/realtime_model.test.js.map +1 -1
  23. package/dist/stt.cjs +128 -86
  24. package/dist/stt.cjs.map +1 -1
  25. package/dist/stt.d.ts.map +1 -1
  26. package/dist/stt.js +133 -87
  27. package/dist/stt.js.map +1 -1
  28. package/dist/stt_recovery.test.cjs +197 -0
  29. package/dist/stt_recovery.test.cjs.map +1 -0
  30. package/dist/stt_recovery.test.d.cts +2 -0
  31. package/dist/stt_recovery.test.d.ts +2 -0
  32. package/dist/stt_recovery.test.d.ts.map +1 -0
  33. package/dist/stt_recovery.test.js +174 -0
  34. package/dist/stt_recovery.test.js.map +1 -0
  35. package/dist/ws/llm.cjs +1 -1
  36. package/dist/ws/llm.cjs.map +1 -1
  37. package/dist/ws/llm.js +1 -1
  38. package/dist/ws/llm.js.map +1 -1
  39. package/package.json +7 -7
  40. package/src/models.ts +21 -2
  41. package/src/realtime/gpt_live_model.ts +1 -1
  42. package/src/realtime/realtime_model.test.ts +199 -1
  43. package/src/realtime/realtime_model.ts +111 -25
  44. package/src/stt.ts +147 -104
  45. package/src/stt_recovery.test.ts +190 -0
  46. package/src/ws/llm.ts +1 -1
@@ -396,9 +396,7 @@ export function processBaseURL({
396
396
  azureDeployment?: string;
397
397
  apiVersion?: string;
398
398
  }): string {
399
- // Azure GA (no apiVersion) uses /v1/realtime; legacy preview uses /realtime
400
- const realtimePath = isAzure && !apiVersion ? 'v1/realtime' : 'realtime';
401
- const url = new URL([baseURL, realtimePath].join('/'));
399
+ const url = new URL(baseURL);
402
400
 
403
401
  if (url.protocol === 'https:') {
404
402
  url.protocol = 'wss:';
@@ -406,11 +404,21 @@ export function processBaseURL({
406
404
  url.protocol = 'ws:';
407
405
  }
408
406
 
409
- // ensure "/realtime" is added if the path is empty OR "/v1"
410
- if (!url.pathname || ['', '/v1', '/openai'].includes(url.pathname.replace(/\/$/, ''))) {
411
- url.pathname = url.pathname.replace(/\/$/, '') + '/realtime';
412
- } else {
413
- url.pathname = url.pathname.replace(/\/$/, '');
407
+ const pathStripped = url.pathname.replace(/\/$/, '');
408
+ if (isAzure) {
409
+ if (['', '/openai'].includes(pathStripped)) {
410
+ // Azure GA (no apiVersion) uses /v1/realtime; legacy preview uses /realtime.
411
+ url.pathname = pathStripped + (apiVersion ? '/realtime' : '/v1/realtime');
412
+ } else if (pathStripped === '/openai/v1') {
413
+ url.pathname = '/openai/v1/realtime';
414
+ }
415
+ } else if (!url.pathname || ['', '/v1', '/openai', '/openai/v1'].includes(pathStripped)) {
416
+ url.pathname = pathStripped + '/realtime';
417
+ }
418
+
419
+ if (isAzure) {
420
+ // remove from endpoint URL if present
421
+ url.searchParams.delete('api-version');
414
422
  }
415
423
 
416
424
  const queryParams: Record<string, string> = {};
@@ -422,12 +430,14 @@ export function processBaseURL({
422
430
  }
423
431
  } else if (isAzure) {
424
432
  // GA Azure: /v1/realtime?model=<deployment>
425
- if (azureDeployment) {
433
+ if (!url.searchParams.has('model') && azureDeployment) {
426
434
  queryParams['model'] = azureDeployment;
427
435
  }
428
436
  } else {
429
437
  // Standard OpenAI: /realtime?model=<model>
430
- queryParams['model'] = model;
438
+ if (!url.searchParams.has('model')) {
439
+ queryParams['model'] = model;
440
+ }
431
441
  }
432
442
 
433
443
  for (const [key, value] of Object.entries(queryParams)) {
@@ -467,6 +477,9 @@ export class RealtimeSession extends llm.RealtimeSession {
467
477
  private itemCreateFutures: { [id: string]: Future } = {};
468
478
  private itemDeleteFutures: { [id: string]: Future } = {};
469
479
  private chatCtxEventFutures: { [id: string]: Future } = {};
480
+ private sentChatCtxEvents: { [id: string]: api_proto.ClientEvent } = {};
481
+ private replayItemCreateEventIds: { [id: string]: string[] } = {};
482
+ private replayItemCreateEventItems: { [eventId: string]: string } = {};
470
483
 
471
484
  private inputTranscriptAccumulators = new Map<string, Map<number, string>>();
472
485
 
@@ -621,6 +634,7 @@ export class RealtimeSession extends llm.RealtimeSession {
621
634
  const ownedCreateFutures: { [id: string]: Future<void> } = {};
622
635
  const ownedDeleteFutures: { [id: string]: Future<void> } = {};
623
636
  const ownedEventFutures: { [id: string]: Future<void> } = {};
637
+ this.sentChatCtxEvents = {};
624
638
 
625
639
  const cleanupFutures = () => {
626
640
  for (const [itemId, future] of Object.entries(ownedDeleteFutures)) {
@@ -694,6 +708,7 @@ export class RealtimeSession extends llm.RealtimeSession {
694
708
  }
695
709
  } finally {
696
710
  cleanupFutures();
711
+ this.sentChatCtxEvents = {};
697
712
  if (!timeoutController.signal.aborted) {
698
713
  timeoutController.abort();
699
714
  }
@@ -1155,17 +1170,6 @@ export class RealtimeSession extends llm.RealtimeSession {
1155
1170
  'Reconnecting to OpenAI Realtime API',
1156
1171
  );
1157
1172
 
1158
- // Clean up pending futures from old connection to prevent memory leaks
1159
- for (const fut of Object.values(this.itemCreateFutures)) {
1160
- if (!fut.done) fut.reject(new Error('Session reconnected'));
1161
- }
1162
- this.itemCreateFutures = {};
1163
-
1164
- for (const fut of Object.values(this.itemDeleteFutures)) {
1165
- if (!fut.done) fut.reject(new Error('Session reconnected'));
1166
- }
1167
- this.itemDeleteFutures = {};
1168
-
1169
1173
  this.rejectResponseCreatedFutures('Session reconnected');
1170
1174
  this.discardedEventIds.clear();
1171
1175
  this.closeCurrentGeneration('session reconnection');
@@ -1185,15 +1189,62 @@ export class RealtimeSession extends llm.RealtimeSession {
1185
1189
  }
1186
1190
 
1187
1191
  // chat context
1188
- const chatCtx = this.chatCtx.copy({
1189
- excludeFunctionCall: true,
1192
+ const fullChatCtx = this.chatCtx;
1193
+ const chatCtx = fullChatCtx.copy({
1190
1194
  excludeInstructions: true,
1191
1195
  excludeEmptyMessage: true,
1192
1196
  });
1193
1197
 
1194
1198
  const oldChatCtx = this.remoteChatCtx;
1195
1199
  this.remoteChatCtx = new llm.RemoteChatContext();
1196
- events.push(...(await this.createChatCtxUpdateEvents(chatCtx)));
1200
+ const replayEvents = await this.createChatCtxUpdateEvents(chatCtx);
1201
+ events.push(...replayEvents);
1202
+
1203
+ const availableItemIds = new Set(
1204
+ replayEvents
1205
+ .filter((event) => event.type === 'conversation.item.create')
1206
+ .map((event) => event.item.id),
1207
+ );
1208
+ this.replayItemCreateEventIds = {};
1209
+ this.replayItemCreateEventItems = {};
1210
+ for (const event of replayEvents) {
1211
+ if (
1212
+ event.type === 'conversation.item.create' &&
1213
+ event.event_id &&
1214
+ this.itemCreateFutures[event.item.id]
1215
+ ) {
1216
+ (this.replayItemCreateEventIds[event.item.id] ??= []).push(event.event_id);
1217
+ this.replayItemCreateEventItems[event.event_id] = event.item.id;
1218
+ }
1219
+ }
1220
+
1221
+ // The replay holds only confirmed items. Resend events the lost connection never
1222
+ // confirmed so their confirmations settle the original updateChatCtx waiter.
1223
+ for (const [eventId, event] of Object.entries(this.sentChatCtxEvents)) {
1224
+ const future = this.chatCtxEventFutures[eventId];
1225
+ if (!future || future.done) continue;
1226
+
1227
+ if (event.type === 'conversation.item.create') {
1228
+ let previousItemId = event.previous_item_id;
1229
+ if (previousItemId && !availableItemIds.has(previousItemId)) {
1230
+ const previousIndex = fullChatCtx.indexById(previousItemId);
1231
+ previousItemId = undefined;
1232
+ if (previousIndex !== undefined) {
1233
+ for (let i = previousIndex - 1; i >= 0; i--) {
1234
+ const candidateId = fullChatCtx.items[i]!.id;
1235
+ if (availableItemIds.has(candidateId)) {
1236
+ previousItemId = candidateId;
1237
+ break;
1238
+ }
1239
+ }
1240
+ }
1241
+ }
1242
+ events.push({ ...event, previous_item_id: previousItemId });
1243
+ availableItemIds.add(event.item.id);
1244
+ } else {
1245
+ events.push(event);
1246
+ }
1247
+ }
1197
1248
 
1198
1249
  try {
1199
1250
  for (const ev of events) {
@@ -1306,6 +1357,9 @@ export class RealtimeSession extends llm.RealtimeSession {
1306
1357
  normalizeAzureClientEvent(event as unknown as Record<string, unknown>);
1307
1358
  }
1308
1359
  wsConn.send(JSON.stringify(event));
1360
+ if (event.event_id && this.chatCtxEventFutures[event.event_id]) {
1361
+ this.sentChatCtxEvents[event.event_id] = event;
1362
+ }
1309
1363
  } catch (error) {
1310
1364
  break;
1311
1365
  }
@@ -1491,6 +1545,8 @@ export class RealtimeSession extends llm.RealtimeSession {
1491
1545
  }
1492
1546
  }
1493
1547
  this.itemDeleteFutures = {};
1548
+ this.replayItemCreateEventIds = {};
1549
+ this.replayItemCreateEventItems = {};
1494
1550
 
1495
1551
  this.inputTranscriptAccumulators.clear();
1496
1552
 
@@ -1626,7 +1682,10 @@ export class RealtimeSession extends llm.RealtimeSession {
1626
1682
  const serverEventType = event.type as string;
1627
1683
  const incomingItem = openAIItemToLivekitItem(event.item);
1628
1684
  const existingItem = this.remoteChatCtx.get(event.item.id);
1629
- const pendingCreateFuture = this.itemCreateFutures[event.item.id];
1685
+ const replayConfirmation = this.consumeReplayItemCreate(event.item.id);
1686
+ const pendingCreateFuture = replayConfirmation
1687
+ ? undefined
1688
+ : this.itemCreateFutures[event.item.id];
1630
1689
  if (existingItem && serverEventType === 'conversation.item.added' && !pendingCreateFuture) {
1631
1690
  // The server may emit a later input-audio-backed view of a user item whose
1632
1691
  // transcribed text variant we already inserted locally under the same ID.
@@ -1917,6 +1976,15 @@ export class RealtimeSession extends llm.RealtimeSession {
1917
1976
  }
1918
1977
 
1919
1978
  private handleResponseOutputItemDone(event: api_proto.ResponseOutputItemDoneEvent): void {
1979
+ // conversation.item.added carries a function call before its arguments are generated;
1980
+ // retain the completed arguments so a reconnection can replay them.
1981
+ if (event.item.type === 'function_call') {
1982
+ const remoteItem = this.remoteChatCtx.get(event.item.id);
1983
+ if (remoteItem?.item instanceof llm.FunctionCall) {
1984
+ remoteItem.item.args = event.item.arguments;
1985
+ }
1986
+ }
1987
+
1920
1988
  if (this.currentGeneration instanceof DiscardedGeneration) return;
1921
1989
 
1922
1990
  if (!this.currentGeneration) {
@@ -2091,6 +2159,11 @@ export class RealtimeSession extends llm.RealtimeSession {
2091
2159
  private handleError(event: api_proto.ErrorEvent): void {
2092
2160
  const eventId = event.error.event_id;
2093
2161
  if (eventId) {
2162
+ const replayItemId = this.replayItemCreateEventItems[eventId];
2163
+ if (replayItemId) {
2164
+ this.consumeReplayItemCreate(replayItemId, eventId);
2165
+ }
2166
+
2094
2167
  const future = this.chatCtxEventFutures[eventId];
2095
2168
  if (future) {
2096
2169
  delete this.chatCtxEventFutures[eventId];
@@ -2126,6 +2199,19 @@ export class RealtimeSession extends llm.RealtimeSession {
2126
2199
  this.emitError({ error, recoverable: true });
2127
2200
  }
2128
2201
 
2202
+ private consumeReplayItemCreate(itemId: string, eventId?: string): boolean {
2203
+ const eventIds = this.replayItemCreateEventIds[itemId];
2204
+ if (!eventIds?.length) return false;
2205
+
2206
+ const index = eventId ? eventIds.indexOf(eventId) : 0;
2207
+ if (index === -1) return false;
2208
+
2209
+ const [consumedEventId] = eventIds.splice(index, 1);
2210
+ if (consumedEventId) delete this.replayItemCreateEventItems[consumedEventId];
2211
+ if (eventIds.length === 0) delete this.replayItemCreateEventIds[itemId];
2212
+ return true;
2213
+ }
2214
+
2129
2215
  private emitError({ error, recoverable }: { error: Error; recoverable: boolean }): void {
2130
2216
  // IMPORTANT: only emit error if there are listeners; otherwise emit will throw an error
2131
2217
  this.emit('error', {
package/src/stt.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  import {
5
5
  type APIConnectOptions,
6
+ APIConnectionError,
7
+ APIError,
6
8
  Event as AsyncEvent,
7
9
  type AudioBuffer,
8
10
  AudioByteStream,
@@ -15,10 +17,12 @@ import {
15
17
  mergeFrames,
16
18
  normalizeLanguage,
17
19
  stt,
20
+ waitForAbort,
21
+ waitForWebSocketOpen,
18
22
  } from '@livekit/agents';
19
23
  import type { AudioFrame } from '@livekit/rtc-node';
20
24
  import { OpenAI } from 'openai';
21
- import { type MessageEvent, WebSocket } from 'ws';
25
+ import { type RawData, WebSocket } from 'ws';
22
26
  import { z } from 'zod';
23
27
  import type { GroqAudioModels, STTModels } from './models.js';
24
28
  import type * as api_proto from './realtime/api_proto.js';
@@ -304,7 +308,7 @@ type ResolvedSTTOptions = Omit<STTOptions, 'apiKey' | 'language' | 'keywords' |
304
308
  export class STT extends stt.STT {
305
309
  #opts: ResolvedSTTOptions;
306
310
  #client: OpenAI;
307
- #streams = new Set<SpeechStream>();
311
+ #streams = new Set<WeakRef<SpeechStream>>();
308
312
  #specifiedLanguages: string[];
309
313
  #userKeywords: string[];
310
314
  #sessionKeyterms: string[] = [];
@@ -543,7 +547,7 @@ export class STT extends stt.STT {
543
547
  const vadOptedOut = opts.vad === null || (opts.vad === undefined && this.#vadOptedOut);
544
548
  validateContext(model, languages, userKeywords);
545
549
  if (opts.language === undefined) {
546
- for (const stream of this.#streams) {
550
+ for (const stream of this.#activeStreams()) {
547
551
  validateContext(model, stream.languages, userKeywords);
548
552
  }
549
553
  }
@@ -607,11 +611,7 @@ export class STT extends stt.STT {
607
611
  interimResults: useRealtime,
608
612
  keyterms: supportsContextHints(model),
609
613
  });
610
- for (const stream of this.#streams) {
611
- if (stream.isClosed) {
612
- this.#streams.delete(stream);
613
- continue;
614
- }
614
+ for (const stream of this.#activeStreams()) {
615
615
  stream._updateOptions(this.#opts, languageGiven ? languages : undefined);
616
616
  }
617
617
  }
@@ -629,7 +629,7 @@ export class STT extends stt.STT {
629
629
  }
630
630
  this.#sessionKeyterms = [...keyterms];
631
631
  this.#opts.keywords = [...new Set([...this.#userKeywords, ...keyterms])];
632
- for (const stream of this.#streams) stream._updateOptions(this.#opts);
632
+ for (const stream of this.#activeStreams()) stream._updateOptions(this.#opts);
633
633
  }
634
634
 
635
635
  stream(
@@ -646,18 +646,35 @@ export class STT extends stt.STT {
646
646
  keywords: [...this.#opts.keywords],
647
647
  };
648
648
  validateContext(streamOptions.model, streamOptions.languages, streamOptions.keywords);
649
+ // Prune failed streams when replacements are created.
650
+ this.#activeStreams();
649
651
  const stream = new SpeechStream(
650
652
  this,
651
653
  streamOptions,
652
654
  options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS,
653
- () => this.#streams.delete(stream),
655
+ () => this.#streams.delete(ref),
654
656
  );
655
- this.#streams.add(stream);
657
+ const ref = new WeakRef(stream);
658
+ this.#streams.add(ref);
656
659
  return stream;
657
660
  }
658
661
 
662
+ #activeStreams(): SpeechStream[] {
663
+ const streams: SpeechStream[] = [];
664
+ for (const ref of this.#streams) {
665
+ const stream = ref.deref();
666
+ if (!stream || stream.isClosed || stream.terminalError) {
667
+ stream?.close();
668
+ this.#streams.delete(ref);
669
+ continue;
670
+ }
671
+ streams.push(stream);
672
+ }
673
+ return streams;
674
+ }
675
+
659
676
  override async close(): Promise<void> {
660
- for (const stream of this.#streams) {
677
+ for (const stream of this.#activeStreams()) {
661
678
  stream.close();
662
679
  }
663
680
  this.#streams.clear();
@@ -673,8 +690,7 @@ export class SpeechStream extends stt.SpeechStream {
673
690
  #itemAudioTiming = new Map<string, { startMs?: number; endMs?: number }>();
674
691
  #speaking = false;
675
692
  #ws?: WebSocket;
676
- #wsReady = new AsyncEvent();
677
- #vadStream?: VADStream;
693
+ #connectionController?: AbortController;
678
694
  #reconnectRequested = false;
679
695
 
680
696
  constructor(
@@ -718,7 +734,7 @@ export class SpeechStream extends stt.SpeechStream {
718
734
  this.#reconnectRequested = true;
719
735
  const ws = this.#ws;
720
736
  this.#ws = undefined;
721
- this.#wsReady.clear();
737
+ this.#connectionController?.abort();
722
738
  ws.close();
723
739
  return;
724
740
  }
@@ -739,46 +755,44 @@ export class SpeechStream extends stt.SpeechStream {
739
755
  }
740
756
 
741
757
  protected async run(): Promise<void> {
742
- // Avoid fusing an open segment into the next connection attempt after a retry.
743
758
  this.#emitEndOfSpeech();
744
- const inputTask = this.#forwardInput();
745
- try {
746
- while (!this.abortSignal.aborted) {
747
- const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection)
748
- ? this.#options.vad
749
- ? await _loadRealtimeVad(this.#options.vad)
750
- : undefined
751
- : undefined;
752
- const vadStream = vad?.stream();
753
- const ws = await this.#connect();
759
+ while (!this.abortSignal.aborted) {
760
+ const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection)
761
+ ? this.#options.vad
762
+ ? await _loadRealtimeVad(this.#options.vad)
763
+ : undefined
764
+ : undefined;
765
+ const ws = await this.#connect();
766
+ const attemptController = new AbortController();
767
+ this.#connectionController = attemptController;
768
+ const attemptSignal = AbortSignal.any([this.abortSignal, attemptController.signal]);
769
+ const connectionTasks: Promise<void>[] = [];
770
+ let vadStream: VADStream | undefined;
771
+ try {
772
+ vadStream = vad?.stream();
754
773
  this.#ws = ws;
755
- this.#vadStream = vadStream;
756
- this.#wsReady.set();
757
- const abort = () => {
758
- if (ws.readyState < WebSocket.CLOSING) ws.close();
759
- };
760
- this.abortSignal.addEventListener('abort', abort, { once: true });
761
-
762
- try {
763
- ws.send(JSON.stringify(this.#sessionUpdateEvent()));
764
- const connectionTasks: Promise<void>[] = [this.#forwardEvents(ws, Boolean(vadStream))];
765
- if (vadStream) connectionTasks.push(this.#forwardVadEvents(ws, vadStream));
766
- await Promise.race([inputTask, ...connectionTasks]);
767
- } finally {
768
- this.#ws = undefined;
769
- this.#vadStream = undefined;
770
- this.#wsReady.clear();
771
- this.abortSignal.removeEventListener('abort', abort);
772
- vadStream?.close();
773
- if (ws.readyState < WebSocket.CLOSING) ws.close();
774
+ ws.send(JSON.stringify(this.#sessionUpdateEvent()));
775
+ connectionTasks.push(this.#forwardEvents(ws, Boolean(vadStream), attemptSignal));
776
+ if (vadStream) {
777
+ connectionTasks.push(this.#forwardVadEvents(ws, vadStream, attemptSignal));
774
778
  }
779
+ connectionTasks.push(this.#forwardInput(ws, vadStream, attemptSignal));
780
+ await Promise.race(connectionTasks);
781
+ } finally {
782
+ this.#ws = undefined;
783
+ this.#connectionController = undefined;
784
+ attemptController.abort();
785
+ vadStream?.close();
786
+ if (ws.readyState < WebSocket.CLOSING) ws.close();
787
+ await Promise.allSettled(connectionTasks);
788
+ }
775
789
 
776
- if (!this.#reconnectRequested) return;
777
- this.#reconnectRequested = false;
778
- this.#emitEndOfSpeech();
790
+ if (!this.#reconnectRequested) {
791
+ this.#onClose();
792
+ return;
779
793
  }
780
- } finally {
781
- this.#onClose();
794
+ this.#reconnectRequested = false;
795
+ this.#emitEndOfSpeech();
782
796
  }
783
797
  }
784
798
 
@@ -788,13 +802,16 @@ export class SpeechStream extends stt.SpeechStream {
788
802
  Authorization: `Bearer ${this.#options.apiKey}`,
789
803
  },
790
804
  });
791
-
792
- await new Promise<void>((resolve, reject) => {
793
- ws.onopen = () => resolve();
794
- ws.onerror = (error) => reject(new Error(error.message));
795
- });
796
-
797
- return ws;
805
+ const connected = waitForWebSocketOpen(ws, 'OpenAI STT');
806
+ const abort = () => ws.close();
807
+ this.abortSignal.addEventListener('abort', abort, { once: true });
808
+ if (this.abortSignal.aborted) abort();
809
+ try {
810
+ await connected;
811
+ return ws;
812
+ } finally {
813
+ this.abortSignal.removeEventListener('abort', abort);
814
+ }
798
815
  }
799
816
 
800
817
  #realtimeUrl(): string {
@@ -827,41 +844,52 @@ export class SpeechStream extends stt.SpeechStream {
827
844
  };
828
845
  }
829
846
 
830
- async #forwardInput(): Promise<void> {
847
+ async #forwardInput(
848
+ ws: WebSocket,
849
+ vadStream: VADStream | undefined,
850
+ signal: AbortSignal,
851
+ ): Promise<void> {
831
852
  const audioStream = new AudioByteStream(
832
853
  REALTIME_SAMPLE_RATE,
833
854
  REALTIME_NUM_CHANNELS,
834
855
  REALTIME_SAMPLE_RATE / 20,
835
856
  );
836
857
 
837
- for await (const item of this.input) {
838
- while (!this.#ws && !this.abortSignal.aborted) await this.#wsReady.wait();
839
- const ws = this.#ws;
840
- if (!ws) return;
841
- const vadStream = this.#vadStream;
842
- if (item === SpeechStream.FLUSH_SENTINEL) {
843
- for (const frame of audioStream.flush()) {
844
- this.#sendAudioFrame(ws, frame);
845
- }
846
- if (
847
- _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) &&
848
- !this.#options.vad
849
- ) {
850
- ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
858
+ try {
859
+ while (!signal.aborted) {
860
+ const result = await this.input.next({ signal });
861
+ if (result.done) break;
862
+ const item = result.value;
863
+ if (item === SpeechStream.FLUSH_SENTINEL) {
864
+ for (const frame of audioStream.flush()) {
865
+ this.#sendAudioFrame(ws, frame);
866
+ }
867
+ if (
868
+ _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) &&
869
+ !this.#options.vad
870
+ ) {
871
+ ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
872
+ }
873
+ continue;
851
874
  }
852
- continue;
853
- }
854
875
 
855
- vadStream?.pushFrame(item);
856
- for (const frame of audioStream.write(item.data.buffer as ArrayBuffer)) {
857
- this.#sendAudioFrame(ws, frame);
876
+ vadStream?.pushFrame(item);
877
+ for (const frame of audioStream.write(item.data.buffer as ArrayBuffer)) {
878
+ this.#sendAudioFrame(ws, frame);
879
+ }
858
880
  }
881
+ if (!signal.aborted) vadStream?.endInput();
882
+ } catch (error) {
883
+ if (!signal.aborted) throw error;
859
884
  }
860
- this.#vadStream?.endInput();
861
885
  }
862
886
 
863
- async #forwardVadEvents(ws: WebSocket, vadStream: VADStream): Promise<void> {
864
- for await (const event of vadStream) {
887
+ async #forwardVadEvents(ws: WebSocket, vadStream: VADStream, signal: AbortSignal): Promise<void> {
888
+ const aborted = waitForAbort(signal);
889
+ while (!signal.aborted) {
890
+ const result = await Promise.race([vadStream.next(), aborted]);
891
+ if (!result || result.done) return;
892
+ const event = result.value;
865
893
  if (event.type === VADEventType.START_OF_SPEECH) {
866
894
  this.#emitStartOfSpeech();
867
895
  } else if (event.type === VADEventType.END_OF_SPEECH) {
@@ -873,8 +901,8 @@ export class SpeechStream extends stt.SpeechStream {
873
901
  }
874
902
  }
875
903
 
876
- async #forwardEvents(ws: WebSocket, hasClientVad: boolean): Promise<void> {
877
- for await (const data of this.#messages(ws)) {
904
+ async #forwardEvents(ws: WebSocket, hasClientVad: boolean, signal: AbortSignal): Promise<void> {
905
+ for await (const data of this.#messages(ws, signal)) {
878
906
  const event = parseRealtimeTranscriptionServerEvent(data);
879
907
  switch (event.type) {
880
908
  case 'input_audio_buffer.speech_started': {
@@ -924,48 +952,63 @@ export class SpeechStream extends stt.SpeechStream {
924
952
  break;
925
953
  }
926
954
  case 'error': {
927
- throw new Error(event.error?.message || 'OpenAI realtime transcription error');
955
+ throw new APIError(event.error?.message || 'OpenAI realtime transcription error', {
956
+ body: event,
957
+ retryable: false,
958
+ });
928
959
  }
929
960
  }
930
961
  }
931
962
  }
932
963
 
933
- async *#messages(ws: WebSocket): AsyncGenerator<string> {
964
+ async *#messages(ws: WebSocket, signal: AbortSignal): AsyncGenerator<string> {
934
965
  const queue: string[] = [];
935
966
  const messageEvent = new AsyncEvent();
936
967
  let closed = false;
937
968
  let error: Error | undefined;
938
969
 
939
- ws.onmessage = (message: MessageEvent) => {
940
- queue.push(
941
- typeof message.data === 'string'
942
- ? message.data
943
- : Buffer.from(message.data as ArrayBuffer).toString(),
944
- );
970
+ const onMessage = (message: RawData) => {
971
+ queue.push(message.toString());
945
972
  messageEvent.set();
946
973
  };
947
- ws.onclose = () => {
974
+ const onClose = (code: number) => {
975
+ if (!signal.aborted && !this.#reconnectRequested) {
976
+ error ??= new APIConnectionError({
977
+ message: `OpenAI STT WebSocket closed unexpectedly (${code})`,
978
+ });
979
+ }
948
980
  closed = true;
949
981
  messageEvent.set();
950
982
  };
951
- ws.onerror = (event) => {
952
- error = new Error(event.message);
983
+ const onError = (event: Error) => {
984
+ error = new APIConnectionError({ message: `OpenAI STT WebSocket failed (${event.name})` });
953
985
  closed = true;
954
986
  messageEvent.set();
955
987
  };
956
-
957
- while (!closed || queue.length > 0) {
958
- if (queue.length > 0) {
959
- yield queue.shift()!;
960
- continue;
988
+ const onAbort = () => {
989
+ closed = true;
990
+ messageEvent.set();
991
+ };
992
+ ws.on('message', onMessage);
993
+ ws.on('close', onClose);
994
+ ws.on('error', onError);
995
+ signal.addEventListener('abort', onAbort, { once: true });
996
+ try {
997
+ while (!signal.aborted && (!closed || queue.length > 0)) {
998
+ if (queue.length > 0) {
999
+ yield queue.shift()!;
1000
+ continue;
1001
+ }
1002
+ messageEvent.clear();
1003
+ await messageEvent.wait();
961
1004
  }
962
-
963
- messageEvent.clear();
964
- if (closed || queue.length > 0) continue;
965
- await messageEvent.wait();
1005
+ if (error && !signal.aborted) throw error;
1006
+ } finally {
1007
+ signal.removeEventListener('abort', onAbort);
1008
+ ws.off('message', onMessage);
1009
+ ws.off('close', onClose);
1010
+ ws.off('error', onError);
966
1011
  }
967
-
968
- if (error) throw error;
969
1012
  }
970
1013
 
971
1014
  #sendAudioFrame(ws: WebSocket, frame: AudioFrame): void {