@livekit/agents-plugin-openai 1.6.2 → 1.6.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 (73) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.js +1 -1
  3. package/dist/llm.cjs +1 -1
  4. package/dist/llm.cjs.map +1 -1
  5. package/dist/llm.js +1 -1
  6. package/dist/llm.js.map +1 -1
  7. package/dist/llm.test.cjs +60 -0
  8. package/dist/llm.test.cjs.map +1 -1
  9. package/dist/llm.test.js +40 -2
  10. package/dist/llm.test.js.map +1 -1
  11. package/dist/models.cjs.map +1 -1
  12. package/dist/models.d.cts +2 -1
  13. package/dist/models.d.ts +2 -1
  14. package/dist/models.d.ts.map +1 -1
  15. package/dist/models.js.map +1 -1
  16. package/dist/realtime/api_proto.cjs.map +1 -1
  17. package/dist/realtime/api_proto.d.cts +3 -0
  18. package/dist/realtime/api_proto.d.ts +3 -0
  19. package/dist/realtime/api_proto.d.ts.map +1 -1
  20. package/dist/realtime/api_proto.js.map +1 -1
  21. package/dist/realtime/realtime_model.cjs +71 -17
  22. package/dist/realtime/realtime_model.cjs.map +1 -1
  23. package/dist/realtime/realtime_model.d.cts +37 -11
  24. package/dist/realtime/realtime_model.d.ts +37 -11
  25. package/dist/realtime/realtime_model.d.ts.map +1 -1
  26. package/dist/realtime/realtime_model.js +70 -17
  27. package/dist/realtime/realtime_model.js.map +1 -1
  28. package/dist/realtime/realtime_model.test.cjs +132 -2
  29. package/dist/realtime/realtime_model.test.cjs.map +1 -1
  30. package/dist/realtime/realtime_model.test.js +132 -2
  31. package/dist/realtime/realtime_model.test.js.map +1 -1
  32. package/dist/responses/llm.cjs +3 -1
  33. package/dist/responses/llm.cjs.map +1 -1
  34. package/dist/responses/llm.d.ts.map +1 -1
  35. package/dist/responses/llm.js +3 -1
  36. package/dist/responses/llm.js.map +1 -1
  37. package/dist/responses/llm.test.cjs +64 -0
  38. package/dist/responses/llm.test.cjs.map +1 -1
  39. package/dist/responses/llm.test.js +64 -0
  40. package/dist/responses/llm.test.js.map +1 -1
  41. package/dist/stt.cjs +249 -83
  42. package/dist/stt.cjs.map +1 -1
  43. package/dist/stt.d.cts +37 -10
  44. package/dist/stt.d.ts +37 -10
  45. package/dist/stt.d.ts.map +1 -1
  46. package/dist/stt.js +249 -82
  47. package/dist/stt.js.map +1 -1
  48. package/dist/stt.test.cjs +406 -1
  49. package/dist/stt.test.cjs.map +1 -1
  50. package/dist/stt.test.js +413 -3
  51. package/dist/stt.test.js.map +1 -1
  52. package/dist/ws/llm.cjs +13 -4
  53. package/dist/ws/llm.cjs.map +1 -1
  54. package/dist/ws/llm.d.ts.map +1 -1
  55. package/dist/ws/llm.js +13 -4
  56. package/dist/ws/llm.js.map +1 -1
  57. package/dist/ws/llm.test.cjs +69 -0
  58. package/dist/ws/llm.test.cjs.map +1 -1
  59. package/dist/ws/llm.test.js +71 -2
  60. package/dist/ws/llm.test.js.map +1 -1
  61. package/package.json +5 -5
  62. package/src/llm.test.ts +49 -3
  63. package/src/llm.ts +1 -1
  64. package/src/models.ts +9 -10
  65. package/src/realtime/api_proto.ts +3 -0
  66. package/src/realtime/realtime_model.test.ts +177 -0
  67. package/src/realtime/realtime_model.ts +89 -32
  68. package/src/responses/llm.test.ts +88 -0
  69. package/src/responses/llm.ts +5 -1
  70. package/src/stt.test.ts +466 -3
  71. package/src/stt.ts +331 -96
  72. package/src/ws/llm.test.ts +94 -2
  73. package/src/ws/llm.ts +13 -4
package/src/stt.ts CHANGED
@@ -10,6 +10,8 @@ import {
10
10
  type VAD,
11
11
  VADEventType,
12
12
  type VADStream,
13
+ getBaseLanguage,
14
+ inference,
13
15
  mergeFrames,
14
16
  normalizeLanguage,
15
17
  stt,
@@ -18,12 +20,14 @@ import type { AudioFrame } from '@livekit/rtc-node';
18
20
  import { OpenAI } from 'openai';
19
21
  import { type MessageEvent, WebSocket } from 'ws';
20
22
  import { z } from 'zod';
21
- import type { GroqAudioModels, WhisperModels } from './models.js';
23
+ import type { GroqAudioModels, STTModels } from './models.js';
22
24
  import type * as api_proto from './realtime/api_proto.js';
23
25
 
24
26
  const REALTIME_SAMPLE_RATE = 24000;
25
27
  const REALTIME_NUM_CHANNELS = 1;
26
28
  const DEFAULT_REALTIME_MODEL = 'gpt-realtime-whisper';
29
+ const REALTIME_ONLY_MODELS = ['gpt-realtime-whisper', 'gpt-live-transcribe'];
30
+ const CONTEXT_HINT_MODELS = ['gpt-transcribe', 'gpt-live-transcribe'];
27
31
 
28
32
  /**
29
33
  * Build the realtime transcription WebSocket URL.
@@ -71,7 +75,58 @@ const DEFAULT_REALTIME_TURN_DETECTION: api_proto.TurnDetectionType = {
71
75
  prefix_padding_ms: 600,
72
76
  silence_duration_ms: 350,
73
77
  };
74
- const REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION = new Set([DEFAULT_REALTIME_MODEL]);
78
+ function isRealtimeOnly(model: string): boolean {
79
+ return REALTIME_ONLY_MODELS.some((candidate) => model.startsWith(candidate));
80
+ }
81
+
82
+ function supportsContextHints(model: string): boolean {
83
+ return CONTEXT_HINT_MODELS.some((candidate) => model.startsWith(candidate));
84
+ }
85
+
86
+ function asLanguages(language: string | string[]): string[] {
87
+ return (typeof language === 'string' ? [language] : language).filter(Boolean);
88
+ }
89
+
90
+ function normalizedLanguages(languages: string[]): string[] {
91
+ return [...new Set(languages.map(getBaseLanguage))];
92
+ }
93
+
94
+ function transcriptLanguage(languages: string[]): ReturnType<typeof normalizeLanguage> {
95
+ return normalizeLanguage(languages.length === 1 ? languages[0]! : '');
96
+ }
97
+
98
+ function validateContext(model: string, languages: string[], keywords: string[]): void {
99
+ if (supportsContextHints(model)) return;
100
+ const supported = CONTEXT_HINT_MODELS.join(' and ');
101
+ if (keywords.length > 0) {
102
+ throw new Error(`keywords are only supported by ${supported}, not ${model}`);
103
+ }
104
+ if (languages.length > 1) {
105
+ throw new Error(`${model} accepts a single language; only ${supported} accept a list`);
106
+ }
107
+ }
108
+
109
+ export function buildRealtimeTranscriptionConfig(options: {
110
+ model: string;
111
+ languages: string[];
112
+ keywords?: string[];
113
+ prompt?: string;
114
+ }): api_proto.InputAudioTranscription {
115
+ const supportsHints = supportsContextHints(options.model);
116
+ const languages = normalizedLanguages(options.languages);
117
+ return {
118
+ model: options.model,
119
+ ...(options.prompt !== undefined ? { prompt: options.prompt } : {}),
120
+ ...(supportsHints
121
+ ? {
122
+ keywords: options.keywords ?? [],
123
+ ...(languages.length > 0 ? { languages } : {}),
124
+ }
125
+ : languages.length > 0
126
+ ? { language: languages[0] }
127
+ : {}),
128
+ };
129
+ }
75
130
 
76
131
  const realtimeTranscriptionSpeechStartedEventSchema = z.object({
77
132
  type: z.literal('input_audio_buffer.speech_started'),
@@ -95,6 +150,7 @@ const realtimeTranscriptionCompletedEventSchema = z.object({
95
150
  type: z.literal('conversation.item.input_audio_transcription.completed'),
96
151
  item_id: z.string().optional(),
97
152
  transcript: z.string().optional(),
153
+ languages: z.array(z.object({ code: z.string() })).optional(),
98
154
  usage: z
99
155
  .object({
100
156
  input_tokens: z.number().optional(),
@@ -174,21 +230,23 @@ export function _requiresRealtimeVad(
174
230
  model: string,
175
231
  turnDetection: api_proto.TurnDetectionType | null | undefined,
176
232
  ): boolean {
177
- return turnDetection === null || REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model);
233
+ return turnDetection === null || isRealtimeOnly(model);
178
234
  }
179
235
 
180
236
  export function _normalizeRealtimeTurnDetection(
181
237
  model: string,
182
- turnDetection: api_proto.TurnDetectionType | null | undefined,
238
+ turnDetection: SessionTurnDetection | null | undefined,
183
239
  ): api_proto.TurnDetectionType | null | undefined {
184
- if (turnDetection !== null && REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model)) {
240
+ if (turnDetection !== null && isRealtimeOnly(model)) {
185
241
  console.warn(
186
242
  `Turn detection is not supported for ${model}; ignoring the provided turnDetection and ` +
187
243
  'using plugin-side VAD commits instead.',
188
244
  );
189
245
  return null;
190
246
  }
191
- return turnDetection;
247
+ return turnDetection
248
+ ? ({ type: 'server_vad', ...turnDetection } as api_proto.TurnDetectionType)
249
+ : turnDetection;
192
250
  }
193
251
 
194
252
  export function _validateRealtimeVad(
@@ -206,18 +264,28 @@ export function _validateRealtimeVad(
206
264
 
207
265
  export interface STTOptions {
208
266
  apiKey?: string;
209
- language: string;
267
+ language: string | string[];
210
268
  prompt?: string;
269
+ /** Literal terms expected in the audio. Supported by gpt-transcribe and gpt-live-transcribe. */
270
+ keywords?: string[];
211
271
  detectLanguage: boolean;
212
- model: WhisperModels | string;
272
+ model: STTModels | string;
213
273
  baseURL?: string;
214
274
  client?: OpenAI;
215
275
  useRealtime: boolean;
216
- turnDetection?: api_proto.TurnDetectionType | null;
276
+ turnDetection?: SessionTurnDetection | null;
217
277
  noiseReductionType?: api_proto.NoiseReductionType;
218
- vad?: VAD;
278
+ /** Pass null to opt out of the default client VAD and commit audio manually. */
279
+ vad?: VAD | null;
280
+ temperature?: number;
219
281
  }
220
282
 
283
+ export type SessionTurnDetection =
284
+ | (Omit<Extract<api_proto.TurnDetectionType, { type: 'server_vad' }>, 'type'> & {
285
+ type?: 'server_vad';
286
+ })
287
+ | Extract<api_proto.TurnDetectionType, { type: 'semantic_vad' }>;
288
+
221
289
  const defaultSTTOptions: STTOptions = {
222
290
  apiKey: process.env.OPENAI_API_KEY,
223
291
  language: 'en',
@@ -226,12 +294,21 @@ const defaultSTTOptions: STTOptions = {
226
294
  useRealtime: true,
227
295
  };
228
296
 
229
- type ResolvedSTTOptions = Omit<STTOptions, 'apiKey'> & { apiKey: string };
297
+ type ResolvedSTTOptions = Omit<STTOptions, 'apiKey' | 'language' | 'keywords' | 'turnDetection'> & {
298
+ apiKey: string;
299
+ languages: string[];
300
+ keywords: string[];
301
+ turnDetection?: api_proto.TurnDetectionType | null;
302
+ };
230
303
 
231
304
  export class STT extends stt.STT {
232
305
  #opts: ResolvedSTTOptions;
233
306
  #client: OpenAI;
234
307
  #streams = new Set<SpeechStream>();
308
+ #specifiedLanguages: string[];
309
+ #userKeywords: string[];
310
+ #sessionKeyterms: string[] = [];
311
+ #vadOptedOut: boolean;
235
312
  label = 'openai.STT';
236
313
 
237
314
  get model(): string {
@@ -265,6 +342,7 @@ export class STT extends stt.STT {
265
342
  streaming: useRealtime,
266
343
  interimResults: useRealtime,
267
344
  alignedTranscript: false,
345
+ keyterms: supportsContextHints(model),
268
346
  });
269
347
 
270
348
  const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
@@ -276,22 +354,43 @@ export class STT extends stt.STT {
276
354
  model,
277
355
  opts.turnDetection !== undefined
278
356
  ? opts.turnDetection
279
- : model === DEFAULT_REALTIME_MODEL
357
+ : isRealtimeOnly(model)
280
358
  ? null
281
359
  : DEFAULT_REALTIME_TURN_DETECTION,
282
360
  );
283
- if (useRealtime) {
284
- _validateRealtimeVad(model, turnDetection, opts.vad);
361
+ let resolvedVad = opts.vad;
362
+ this.#vadOptedOut = opts.vad === null;
363
+ if (useRealtime && isRealtimeOnly(model) && opts.vad === undefined) {
364
+ resolvedVad = new inference.VAD();
365
+ }
366
+ if (useRealtime && !this.#vadOptedOut) {
367
+ _validateRealtimeVad(model, turnDetection, resolvedVad ?? undefined);
368
+ }
369
+
370
+ this.#specifiedLanguages = asLanguages(opts.language ?? defaultSTTOptions.language);
371
+ const languages = opts.detectLanguage ? [] : this.#specifiedLanguages;
372
+ const keywords = [...(opts.keywords ?? [])];
373
+ validateContext(model, languages, keywords);
374
+ this.#userKeywords = keywords;
375
+ let temperature = opts.temperature;
376
+ if (useRealtime && temperature !== undefined) {
377
+ console.warn(
378
+ 'temperature is not supported for realtime transcription; ignoring the provided value',
379
+ );
380
+ temperature = undefined;
285
381
  }
286
382
 
287
383
  this.#opts = {
288
384
  ...defaultSTTOptions,
289
385
  ...opts,
290
386
  apiKey,
291
- language: normalizeLanguage(opts.language ?? defaultSTTOptions.language),
387
+ languages,
388
+ keywords,
292
389
  model,
293
390
  useRealtime,
294
391
  turnDetection,
392
+ vad: resolvedVad,
393
+ temperature,
295
394
  };
296
395
 
297
396
  this.#client =
@@ -316,7 +415,7 @@ export class STT extends stt.STT {
316
415
  apiKey?: string;
317
416
  baseURL?: string;
318
417
  client: OpenAI;
319
- language: string;
418
+ language: string | string[];
320
419
  detectLanguage: boolean;
321
420
  }> = {},
322
421
  ): STT {
@@ -346,7 +445,7 @@ export class STT extends stt.STT {
346
445
  apiKey?: string;
347
446
  baseURL?: string;
348
447
  client: OpenAI;
349
- language: string;
448
+ language: string | string[];
350
449
  detectLanguage: boolean;
351
450
  }> = {},
352
451
  ): STT {
@@ -365,14 +464,6 @@ export class STT extends stt.STT {
365
464
  });
366
465
  }
367
466
 
368
- #sanitizeOptions(language?: string): ResolvedSTTOptions {
369
- if (language) {
370
- return { ...this.#opts, language: normalizeLanguage(language) };
371
- } else {
372
- return this.#opts;
373
- }
374
- }
375
-
376
467
  #createWav(frame: AudioFrame): Buffer {
377
468
  const bitsPerSample = 16;
378
469
  const byteRate = (frame.sampleRate * frame.channels * bitsPerSample) / 8;
@@ -396,30 +487,35 @@ export class STT extends stt.STT {
396
487
  }
397
488
 
398
489
  async _recognize(buffer: AudioBuffer, abortSignal?: AbortSignal): Promise<stt.SpeechEvent> {
399
- const config = this.#sanitizeOptions();
490
+ const config = this.#opts;
400
491
  buffer = mergeFrames(buffer);
401
492
  const wavBuffer = this.#createWav(buffer);
402
493
  const file = new File([new Uint8Array(wavBuffer)], 'audio.wav', { type: 'audio/wav' });
403
494
 
404
- const resp = await this.#client.audio.transcriptions.create(
405
- {
406
- file,
407
- model: this.#opts.model,
408
- language: config.language,
409
- prompt: config.prompt,
410
- response_format: 'json',
411
- },
412
- {
413
- signal: abortSignal,
414
- },
415
- );
495
+ const contextHints = supportsContextHints(config.model);
496
+ const languages = normalizedLanguages(config.languages);
497
+ const transcriptionParams = {
498
+ file,
499
+ model: config.model,
500
+ ...(contextHints
501
+ ? { languages: languages.length > 0 ? languages : undefined, keywords: config.keywords }
502
+ : { language: languages[0] }),
503
+ prompt: config.prompt,
504
+ response_format: 'json' as const,
505
+ temperature: config.temperature,
506
+ };
507
+ const resp = (await this.#client.audio.transcriptions.create(transcriptionParams as never, {
508
+ signal: abortSignal,
509
+ })) as { text: string; languages?: { code: string }[] };
416
510
 
417
511
  return {
418
512
  type: stt.SpeechEventType.FINAL_TRANSCRIPT,
419
513
  alternatives: [
420
514
  {
421
515
  text: resp.text || '',
422
- language: normalizeLanguage(config.language || ''),
516
+ language: resp.languages?.[0]?.code
517
+ ? normalizeLanguage(resp.languages[0].code)
518
+ : transcriptLanguage(config.languages),
423
519
  startTime: 0,
424
520
  endTime: 0,
425
521
  confidence: 0,
@@ -431,47 +527,128 @@ export class STT extends stt.STT {
431
527
  updateOptions(opts: Partial<STTOptions>): void {
432
528
  const useRealtime = opts.useRealtime ?? this.#opts.useRealtime;
433
529
  const model = opts.model ?? this.#opts.model;
530
+ const languages =
531
+ opts.language !== undefined
532
+ ? asLanguages(opts.language)
533
+ : opts.detectLanguage
534
+ ? []
535
+ : opts.detectLanguage === false && this.#opts.languages.length === 0
536
+ ? (console.warn(
537
+ `detectLanguage: false names no language; falling back to ${this.#specifiedLanguages.join(', ')}`,
538
+ ),
539
+ this.#specifiedLanguages)
540
+ : this.#opts.languages;
541
+ const userKeywords = opts.keywords !== undefined ? [...opts.keywords] : this.#userKeywords;
542
+ const vad = opts.vad !== undefined ? opts.vad : this.#opts.vad;
543
+ const vadOptedOut = opts.vad === null || (opts.vad === undefined && this.#vadOptedOut);
544
+ validateContext(model, languages, userKeywords);
545
+ if (opts.language === undefined) {
546
+ for (const stream of this.#streams) {
547
+ validateContext(model, stream.languages, userKeywords);
548
+ }
549
+ }
550
+ if (opts.model !== undefined && isRealtimeOnly(opts.model)) {
551
+ if (!useRealtime) {
552
+ throw new Error(
553
+ `${model} is served only over the realtime API, and this STT was created for the ` +
554
+ 'transcriptions endpoint; pass useRealtime: true to the constructor to reach it',
555
+ );
556
+ }
557
+ if (!vad && !vadOptedOut) {
558
+ throw new Error(
559
+ `${model} has no server-side endpointing, so it needs a vad to commit the audio buffer`,
560
+ );
561
+ }
562
+ }
434
563
  const turnDetection = _normalizeRealtimeTurnDetection(
435
564
  model,
436
565
  opts.turnDetection !== undefined
437
566
  ? opts.turnDetection
438
- : opts.model === DEFAULT_REALTIME_MODEL
567
+ : isRealtimeOnly(model)
439
568
  ? null
440
- : this.#opts.turnDetection,
569
+ : opts.model !== undefined && isRealtimeOnly(this.#opts.model)
570
+ ? DEFAULT_REALTIME_TURN_DETECTION
571
+ : this.#opts.turnDetection,
441
572
  );
442
- if (useRealtime) {
443
- _validateRealtimeVad(model, turnDetection, opts.vad ?? this.#opts.vad);
573
+ if (useRealtime && !vadOptedOut) {
574
+ _validateRealtimeVad(model, turnDetection, vad ?? undefined);
575
+ }
576
+ let temperature = opts.temperature ?? this.#opts.temperature;
577
+ if (useRealtime && temperature !== undefined) {
578
+ console.warn(
579
+ 'temperature is not supported for realtime transcription; ignoring the provided value',
580
+ );
581
+ temperature = undefined;
444
582
  }
583
+ const languagesChanged =
584
+ languages.some((value, index) => value !== this.#opts.languages[index]) ||
585
+ languages.length !== this.#opts.languages.length;
586
+ const languageGiven = opts.language !== undefined || languagesChanged;
587
+ if (languages.length > 0) this.#specifiedLanguages = languages;
588
+ this.#userKeywords = userKeywords;
589
+ this.#vadOptedOut = vadOptedOut;
590
+ const keywords = supportsContextHints(model)
591
+ ? [...new Set([...userKeywords, ...this.#sessionKeyterms])]
592
+ : [];
445
593
  this.#opts = {
446
594
  ...this.#opts,
447
595
  ...opts,
448
596
  apiKey: opts.apiKey ?? this.#opts.apiKey,
449
- language: opts.language ? normalizeLanguage(opts.language) : this.#opts.language,
597
+ languages,
598
+ keywords,
450
599
  model,
451
600
  useRealtime,
452
601
  turnDetection,
602
+ temperature,
603
+ vad,
453
604
  };
454
605
  this.updateCapabilities({
455
606
  streaming: useRealtime,
456
607
  interimResults: useRealtime,
608
+ keyterms: supportsContextHints(model),
457
609
  });
458
610
  for (const stream of this.#streams) {
459
611
  if (stream.isClosed) {
460
612
  this.#streams.delete(stream);
461
613
  continue;
462
614
  }
463
- stream.updateOptions(this.#opts);
615
+ stream._updateOptions(this.#opts, languageGiven ? languages : undefined);
464
616
  }
465
617
  }
466
618
 
467
- stream(options: { connOptions?: APIConnectOptions } = {}): stt.SpeechStream {
619
+ override _updateSessionKeyterms(keyterms: string[]): void {
620
+ if (!this.capabilities.keyterms) {
621
+ super._updateSessionKeyterms(keyterms);
622
+ return;
623
+ }
624
+ if (
625
+ keyterms.length === this.#sessionKeyterms.length &&
626
+ keyterms.every((term, index) => term === this.#sessionKeyterms[index])
627
+ ) {
628
+ return;
629
+ }
630
+ this.#sessionKeyterms = [...keyterms];
631
+ this.#opts.keywords = [...new Set([...this.#userKeywords, ...keyterms])];
632
+ for (const stream of this.#streams) stream._updateOptions(this.#opts);
633
+ }
634
+
635
+ stream(
636
+ options: { connOptions?: APIConnectOptions; language?: string | string[] } = {},
637
+ ): stt.SpeechStream {
468
638
  if (!this.#opts.useRealtime) {
469
639
  throw new Error('Streaming is not supported on OpenAI STT unless useRealtime is enabled');
470
640
  }
471
641
 
642
+ const streamOptions = {
643
+ ...this.#opts,
644
+ languages:
645
+ options.language !== undefined ? asLanguages(options.language) : [...this.#opts.languages],
646
+ keywords: [...this.#opts.keywords],
647
+ };
648
+ validateContext(streamOptions.model, streamOptions.languages, streamOptions.keywords);
472
649
  const stream = new SpeechStream(
473
650
  this,
474
- { ...this.#opts },
651
+ streamOptions,
475
652
  options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS,
476
653
  () => this.#streams.delete(stream),
477
654
  );
@@ -495,6 +672,10 @@ export class SpeechStream extends stt.SpeechStream {
495
672
  #currentItemId = '';
496
673
  #itemAudioTiming = new Map<string, { startMs?: number; endMs?: number }>();
497
674
  #speaking = false;
675
+ #ws?: WebSocket;
676
+ #wsReady = new AsyncEvent();
677
+ #vadStream?: VADStream;
678
+ #reconnectRequested = false;
498
679
 
499
680
  constructor(
500
681
  stt: STT,
@@ -507,8 +688,45 @@ export class SpeechStream extends stt.SpeechStream {
507
688
  this.#onClose = onClose;
508
689
  }
509
690
 
510
- updateOptions(options: ResolvedSTTOptions): void {
511
- this.#options = { ...options };
691
+ get languages(): string[] {
692
+ return this.#options.languages;
693
+ }
694
+
695
+ updateOptions(options: { language?: string | string[] }): void {
696
+ const languages =
697
+ options.language !== undefined ? asLanguages(options.language) : this.#options.languages;
698
+ validateContext(this.#options.model, languages, this.#options.keywords);
699
+ this.#applyOptions(this.#options, languages);
700
+ }
701
+
702
+ /** @internal */
703
+ _updateOptions(options: ResolvedSTTOptions, languages?: string[]): void {
704
+ this.#applyOptions(options, languages ?? this.#options.languages);
705
+ }
706
+
707
+ #applyOptions(options: ResolvedSTTOptions, languages: string[]): void {
708
+ const previous = this.#options;
709
+ this.#options = {
710
+ ...options,
711
+ languages: [...languages],
712
+ keywords: [...options.keywords],
713
+ };
714
+ const modelChanged = previous.model !== this.#options.model;
715
+ const clearedLanguage = previous.languages.length > 0 && this.#options.languages.length === 0;
716
+ if (!this.#ws) return;
717
+ if (modelChanged || clearedLanguage) {
718
+ this.#reconnectRequested = true;
719
+ const ws = this.#ws;
720
+ this.#ws = undefined;
721
+ this.#wsReady.clear();
722
+ ws.close();
723
+ return;
724
+ }
725
+ try {
726
+ this.#ws.send(JSON.stringify(this.#sessionUpdateEvent()));
727
+ } catch (error) {
728
+ console.warn('failed to update the OpenAI transcription session', error);
729
+ }
512
730
  }
513
731
 
514
732
  get isClosed(): boolean {
@@ -523,41 +741,43 @@ export class SpeechStream extends stt.SpeechStream {
523
741
  protected async run(): Promise<void> {
524
742
  // Avoid fusing an open segment into the next connection attempt after a retry.
525
743
  this.#emitEndOfSpeech();
526
-
527
- _validateRealtimeVad(this.#options.model, this.#options.turnDetection, this.#options.vad);
528
- const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection)
529
- ? await _loadRealtimeVad(this.#options.vad)
530
- : undefined;
531
-
532
- if (vad) {
533
- this.#options.vad = vad;
534
- }
535
-
536
- const vadStream = vad?.stream();
537
- const ws = await this.#connect();
538
- const abort = () => {
539
- if (ws.readyState < WebSocket.CLOSING) {
540
- ws.close();
541
- }
542
- };
543
- this.abortSignal.addEventListener('abort', abort, { once: true });
544
-
744
+ const inputTask = this.#forwardInput();
545
745
  try {
546
- ws.send(JSON.stringify(this.#sessionUpdateEvent()));
547
- const tasks = [
548
- this.#forwardInput(ws, vadStream),
549
- this.#forwardEvents(ws, Boolean(vadStream)),
550
- ];
551
- if (vadStream) {
552
- tasks.push(this.#forwardVadEvents(ws, vadStream));
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();
754
+ 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
+ }
775
+
776
+ if (!this.#reconnectRequested) return;
777
+ this.#reconnectRequested = false;
778
+ this.#emitEndOfSpeech();
553
779
  }
554
- await Promise.all(tasks);
555
780
  } finally {
556
- this.abortSignal.removeEventListener('abort', abort);
557
- vadStream?.close();
558
- if (ws.readyState < WebSocket.CLOSING) {
559
- ws.close();
560
- }
561
781
  this.#onClose();
562
782
  }
563
783
  }
@@ -582,13 +802,7 @@ export class SpeechStream extends stt.SpeechStream {
582
802
  }
583
803
 
584
804
  #sessionUpdateEvent(): api_proto.SessionUpdateEvent {
585
- const transcription: api_proto.InputAudioTranscription = {
586
- model: this.#options.model,
587
- ...(this.#options.prompt ? { prompt: this.#options.prompt } : {}),
588
- ...(!this.#options.detectLanguage && this.#options.language
589
- ? { language: this.#options.language }
590
- : {}),
591
- };
805
+ const transcription = buildRealtimeTranscriptionConfig(this.#options);
592
806
 
593
807
  return {
594
808
  type: 'session.update',
@@ -601,7 +815,9 @@ export class SpeechStream extends stt.SpeechStream {
601
815
  rate: REALTIME_SAMPLE_RATE,
602
816
  },
603
817
  transcription,
604
- turn_detection: this.#options.turnDetection,
818
+ ...(!isRealtimeOnly(this.#options.model)
819
+ ? { turn_detection: this.#options.turnDetection }
820
+ : {}),
605
821
  ...(this.#options.noiseReductionType
606
822
  ? { noise_reduction: { type: this.#options.noiseReductionType } }
607
823
  : {}),
@@ -611,7 +827,7 @@ export class SpeechStream extends stt.SpeechStream {
611
827
  };
612
828
  }
613
829
 
614
- async #forwardInput(ws: WebSocket, vadStream?: VADStream): Promise<void> {
830
+ async #forwardInput(): Promise<void> {
615
831
  const audioStream = new AudioByteStream(
616
832
  REALTIME_SAMPLE_RATE,
617
833
  REALTIME_NUM_CHANNELS,
@@ -619,11 +835,18 @@ export class SpeechStream extends stt.SpeechStream {
619
835
  );
620
836
 
621
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;
622
842
  if (item === SpeechStream.FLUSH_SENTINEL) {
623
843
  for (const frame of audioStream.flush()) {
624
844
  this.#sendAudioFrame(ws, frame);
625
845
  }
626
- if (this.#options.turnDetection === null) {
846
+ if (
847
+ _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) &&
848
+ !this.#options.vad
849
+ ) {
627
850
  ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
628
851
  }
629
852
  continue;
@@ -634,7 +857,7 @@ export class SpeechStream extends stt.SpeechStream {
634
857
  this.#sendAudioFrame(ws, frame);
635
858
  }
636
859
  }
637
- vadStream?.endInput();
860
+ this.#vadStream?.endInput();
638
861
  }
639
862
 
640
863
  async #forwardVadEvents(ws: WebSocket, vadStream: VADStream): Promise<void> {
@@ -643,7 +866,7 @@ export class SpeechStream extends stt.SpeechStream {
643
866
  this.#emitStartOfSpeech();
644
867
  } else if (event.type === VADEventType.END_OF_SPEECH) {
645
868
  this.#emitEndOfSpeech();
646
- if (this.#options.turnDetection === null) {
869
+ if (_requiresRealtimeVad(this.#options.model, this.#options.turnDetection)) {
647
870
  ws.send(JSON.stringify({ type: 'input_audio_buffer.commit' }));
648
871
  }
649
872
  }
@@ -687,7 +910,13 @@ export class SpeechStream extends stt.SpeechStream {
687
910
  const transcript = event.transcript ?? '';
688
911
  if (transcript) {
689
912
  this.#targetTranscript = transcript;
690
- this.queue.put(this.#speechEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, itemId));
913
+ this.queue.put(
914
+ this.#speechEvent(
915
+ stt.SpeechEventType.FINAL_TRANSCRIPT,
916
+ itemId,
917
+ event.languages?.[0]?.code,
918
+ ),
919
+ );
691
920
  }
692
921
  this.#emitRecognitionUsage(event, itemId);
693
922
  this.#targetTranscript = '';
@@ -768,14 +997,20 @@ export class SpeechStream extends stt.SpeechStream {
768
997
  this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
769
998
  }
770
999
 
771
- #speechEvent(type: stt.SpeechEventType, requestId = this.#currentItemId): stt.SpeechEvent {
1000
+ #speechEvent(
1001
+ type: stt.SpeechEventType,
1002
+ requestId = this.#currentItemId,
1003
+ detectedLanguage?: string,
1004
+ ): stt.SpeechEvent {
772
1005
  return {
773
1006
  type,
774
1007
  requestId,
775
1008
  alternatives: [
776
1009
  {
777
1010
  text: this.#targetTranscript,
778
- language: normalizeLanguage(this.#options.language || ''),
1011
+ language: detectedLanguage
1012
+ ? normalizeLanguage(detectedLanguage)
1013
+ : transcriptLanguage(this.#options.languages),
779
1014
  startTime: 0,
780
1015
  endTime: 0,
781
1016
  confidence: 1,