@livekit/agents-plugin-openai 1.6.2 → 1.6.3

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/dist/stt.js CHANGED
@@ -3,6 +3,8 @@ import {
3
3
  AudioByteStream,
4
4
  DEFAULT_API_CONNECT_OPTIONS,
5
5
  VADEventType,
6
+ getBaseLanguage,
7
+ inference,
6
8
  mergeFrames,
7
9
  normalizeLanguage,
8
10
  stt
@@ -13,6 +15,8 @@ import { z } from "zod";
13
15
  const REALTIME_SAMPLE_RATE = 24e3;
14
16
  const REALTIME_NUM_CHANNELS = 1;
15
17
  const DEFAULT_REALTIME_MODEL = "gpt-realtime-whisper";
18
+ const REALTIME_ONLY_MODELS = ["gpt-realtime-whisper", "gpt-live-transcribe"];
19
+ const CONTEXT_HINT_MODELS = ["gpt-transcribe", "gpt-live-transcribe"];
16
20
  function buildRealtimeSttUrl(baseURL, model) {
17
21
  const url = new URL(baseURL || "https://api.openai.com/v1");
18
22
  if (url.protocol === "https:") {
@@ -38,7 +42,43 @@ const DEFAULT_REALTIME_TURN_DETECTION = {
38
42
  prefix_padding_ms: 600,
39
43
  silence_duration_ms: 350
40
44
  };
41
- const REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION = /* @__PURE__ */ new Set([DEFAULT_REALTIME_MODEL]);
45
+ function isRealtimeOnly(model) {
46
+ return REALTIME_ONLY_MODELS.some((candidate) => model.startsWith(candidate));
47
+ }
48
+ function supportsContextHints(model) {
49
+ return CONTEXT_HINT_MODELS.some((candidate) => model.startsWith(candidate));
50
+ }
51
+ function asLanguages(language) {
52
+ return (typeof language === "string" ? [language] : language).filter(Boolean);
53
+ }
54
+ function normalizedLanguages(languages) {
55
+ return [...new Set(languages.map(getBaseLanguage))];
56
+ }
57
+ function transcriptLanguage(languages) {
58
+ return normalizeLanguage(languages.length === 1 ? languages[0] : "");
59
+ }
60
+ function validateContext(model, languages, keywords) {
61
+ if (supportsContextHints(model)) return;
62
+ const supported = CONTEXT_HINT_MODELS.join(" and ");
63
+ if (keywords.length > 0) {
64
+ throw new Error(`keywords are only supported by ${supported}, not ${model}`);
65
+ }
66
+ if (languages.length > 1) {
67
+ throw new Error(`${model} accepts a single language; only ${supported} accept a list`);
68
+ }
69
+ }
70
+ function buildRealtimeTranscriptionConfig(options) {
71
+ const supportsHints = supportsContextHints(options.model);
72
+ const languages = normalizedLanguages(options.languages);
73
+ return {
74
+ model: options.model,
75
+ ...options.prompt !== void 0 ? { prompt: options.prompt } : {},
76
+ ...supportsHints ? {
77
+ keywords: options.keywords ?? [],
78
+ ...languages.length > 0 ? { languages } : {}
79
+ } : languages.length > 0 ? { language: languages[0] } : {}
80
+ };
81
+ }
42
82
  const realtimeTranscriptionSpeechStartedEventSchema = z.object({
43
83
  type: z.literal("input_audio_buffer.speech_started"),
44
84
  item_id: z.string().optional(),
@@ -58,6 +98,7 @@ const realtimeTranscriptionCompletedEventSchema = z.object({
58
98
  type: z.literal("conversation.item.input_audio_transcription.completed"),
59
99
  item_id: z.string().optional(),
60
100
  transcript: z.string().optional(),
101
+ languages: z.array(z.object({ code: z.string() })).optional(),
61
102
  usage: z.object({
62
103
  input_tokens: z.number().optional(),
63
104
  output_tokens: z.number().optional()
@@ -104,16 +145,16 @@ async function _loadRealtimeVad(vad) {
104
145
  );
105
146
  }
106
147
  function _requiresRealtimeVad(model, turnDetection) {
107
- return turnDetection === null || REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model);
148
+ return turnDetection === null || isRealtimeOnly(model);
108
149
  }
109
150
  function _normalizeRealtimeTurnDetection(model, turnDetection) {
110
- if (turnDetection !== null && REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model)) {
151
+ if (turnDetection !== null && isRealtimeOnly(model)) {
111
152
  console.warn(
112
153
  `Turn detection is not supported for ${model}; ignoring the provided turnDetection and using plugin-side VAD commits instead.`
113
154
  );
114
155
  return null;
115
156
  }
116
- return turnDetection;
157
+ return turnDetection ? { type: "server_vad", ...turnDetection } : turnDetection;
117
158
  }
118
159
  function _validateRealtimeVad(model, turnDetection, vad) {
119
160
  if (_requiresRealtimeVad(model, turnDetection) && !vad) {
@@ -133,6 +174,10 @@ class STT extends stt.STT {
133
174
  #opts;
134
175
  #client;
135
176
  #streams = /* @__PURE__ */ new Set();
177
+ #specifiedLanguages;
178
+ #userKeywords;
179
+ #sessionKeyterms = [];
180
+ #vadOptedOut;
136
181
  label = "openai.STT";
137
182
  get model() {
138
183
  return this.#opts.model;
@@ -161,7 +206,8 @@ class STT extends stt.STT {
161
206
  super({
162
207
  streaming: useRealtime,
163
208
  interimResults: useRealtime,
164
- alignedTranscript: false
209
+ alignedTranscript: false,
210
+ keyterms: supportsContextHints(model)
165
211
  });
166
212
  const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
167
213
  if (apiKey === void 0) {
@@ -169,19 +215,39 @@ class STT extends stt.STT {
169
215
  }
170
216
  const turnDetection = _normalizeRealtimeTurnDetection(
171
217
  model,
172
- opts.turnDetection !== void 0 ? opts.turnDetection : model === DEFAULT_REALTIME_MODEL ? null : DEFAULT_REALTIME_TURN_DETECTION
218
+ opts.turnDetection !== void 0 ? opts.turnDetection : isRealtimeOnly(model) ? null : DEFAULT_REALTIME_TURN_DETECTION
173
219
  );
174
- if (useRealtime) {
175
- _validateRealtimeVad(model, turnDetection, opts.vad);
220
+ let resolvedVad = opts.vad;
221
+ this.#vadOptedOut = opts.vad === null;
222
+ if (useRealtime && isRealtimeOnly(model) && opts.vad === void 0) {
223
+ resolvedVad = new inference.VAD();
224
+ }
225
+ if (useRealtime && !this.#vadOptedOut) {
226
+ _validateRealtimeVad(model, turnDetection, resolvedVad ?? void 0);
227
+ }
228
+ this.#specifiedLanguages = asLanguages(opts.language ?? defaultSTTOptions.language);
229
+ const languages = opts.detectLanguage ? [] : this.#specifiedLanguages;
230
+ const keywords = [...opts.keywords ?? []];
231
+ validateContext(model, languages, keywords);
232
+ this.#userKeywords = keywords;
233
+ let temperature = opts.temperature;
234
+ if (useRealtime && temperature !== void 0) {
235
+ console.warn(
236
+ "temperature is not supported for realtime transcription; ignoring the provided value"
237
+ );
238
+ temperature = void 0;
176
239
  }
177
240
  this.#opts = {
178
241
  ...defaultSTTOptions,
179
242
  ...opts,
180
243
  apiKey,
181
- language: normalizeLanguage(opts.language ?? defaultSTTOptions.language),
244
+ languages,
245
+ keywords,
182
246
  model,
183
247
  useRealtime,
184
- turnDetection
248
+ turnDetection,
249
+ vad: resolvedVad,
250
+ temperature
185
251
  };
186
252
  this.#client = this.#opts.client || new OpenAI({
187
253
  baseURL: this.#opts.baseURL,
@@ -229,13 +295,6 @@ class STT extends stt.STT {
229
295
  useRealtime: false
230
296
  });
231
297
  }
232
- #sanitizeOptions(language) {
233
- if (language) {
234
- return { ...this.#opts, language: normalizeLanguage(language) };
235
- } else {
236
- return this.#opts;
237
- }
238
- }
239
298
  #createWav(frame) {
240
299
  const bitsPerSample = 16;
241
300
  const byteRate = frame.sampleRate * frame.channels * bitsPerSample / 8;
@@ -257,28 +316,30 @@ class STT extends stt.STT {
257
316
  return Buffer.concat([header, Buffer.from(frame.data.buffer)]);
258
317
  }
259
318
  async _recognize(buffer, abortSignal) {
260
- const config = this.#sanitizeOptions();
319
+ var _a, _b;
320
+ const config = this.#opts;
261
321
  buffer = mergeFrames(buffer);
262
322
  const wavBuffer = this.#createWav(buffer);
263
323
  const file = new File([new Uint8Array(wavBuffer)], "audio.wav", { type: "audio/wav" });
264
- const resp = await this.#client.audio.transcriptions.create(
265
- {
266
- file,
267
- model: this.#opts.model,
268
- language: config.language,
269
- prompt: config.prompt,
270
- response_format: "json"
271
- },
272
- {
273
- signal: abortSignal
274
- }
275
- );
324
+ const contextHints = supportsContextHints(config.model);
325
+ const languages = normalizedLanguages(config.languages);
326
+ const transcriptionParams = {
327
+ file,
328
+ model: config.model,
329
+ ...contextHints ? { languages: languages.length > 0 ? languages : void 0, keywords: config.keywords } : { language: languages[0] },
330
+ prompt: config.prompt,
331
+ response_format: "json",
332
+ temperature: config.temperature
333
+ };
334
+ const resp = await this.#client.audio.transcriptions.create(transcriptionParams, {
335
+ signal: abortSignal
336
+ });
276
337
  return {
277
338
  type: stt.SpeechEventType.FINAL_TRANSCRIPT,
278
339
  alternatives: [
279
340
  {
280
341
  text: resp.text || "",
281
- language: normalizeLanguage(config.language || ""),
342
+ language: ((_b = (_a = resp.languages) == null ? void 0 : _a[0]) == null ? void 0 : _b.code) ? normalizeLanguage(resp.languages[0].code) : transcriptLanguage(config.languages),
282
343
  startTime: 0,
283
344
  endTime: 0,
284
345
  confidence: 0
@@ -289,41 +350,100 @@ class STT extends stt.STT {
289
350
  updateOptions(opts) {
290
351
  const useRealtime = opts.useRealtime ?? this.#opts.useRealtime;
291
352
  const model = opts.model ?? this.#opts.model;
353
+ const languages = opts.language !== void 0 ? asLanguages(opts.language) : opts.detectLanguage ? [] : opts.detectLanguage === false && this.#opts.languages.length === 0 ? (console.warn(
354
+ `detectLanguage: false names no language; falling back to ${this.#specifiedLanguages.join(", ")}`
355
+ ), this.#specifiedLanguages) : this.#opts.languages;
356
+ const userKeywords = opts.keywords !== void 0 ? [...opts.keywords] : this.#userKeywords;
357
+ const vad = opts.vad !== void 0 ? opts.vad : this.#opts.vad;
358
+ const vadOptedOut = opts.vad === null || opts.vad === void 0 && this.#vadOptedOut;
359
+ validateContext(model, languages, userKeywords);
360
+ if (opts.language === void 0) {
361
+ for (const stream of this.#streams) {
362
+ validateContext(model, stream.languages, userKeywords);
363
+ }
364
+ }
365
+ if (opts.model !== void 0 && isRealtimeOnly(opts.model)) {
366
+ if (!useRealtime) {
367
+ throw new Error(
368
+ `${model} is served only over the realtime API, and this STT was created for the transcriptions endpoint; pass useRealtime: true to the constructor to reach it`
369
+ );
370
+ }
371
+ if (!vad && !vadOptedOut) {
372
+ throw new Error(
373
+ `${model} has no server-side endpointing, so it needs a vad to commit the audio buffer`
374
+ );
375
+ }
376
+ }
292
377
  const turnDetection = _normalizeRealtimeTurnDetection(
293
378
  model,
294
- opts.turnDetection !== void 0 ? opts.turnDetection : opts.model === DEFAULT_REALTIME_MODEL ? null : this.#opts.turnDetection
379
+ opts.turnDetection !== void 0 ? opts.turnDetection : isRealtimeOnly(model) ? null : opts.model !== void 0 && isRealtimeOnly(this.#opts.model) ? DEFAULT_REALTIME_TURN_DETECTION : this.#opts.turnDetection
295
380
  );
296
- if (useRealtime) {
297
- _validateRealtimeVad(model, turnDetection, opts.vad ?? this.#opts.vad);
381
+ if (useRealtime && !vadOptedOut) {
382
+ _validateRealtimeVad(model, turnDetection, vad ?? void 0);
298
383
  }
384
+ let temperature = opts.temperature ?? this.#opts.temperature;
385
+ if (useRealtime && temperature !== void 0) {
386
+ console.warn(
387
+ "temperature is not supported for realtime transcription; ignoring the provided value"
388
+ );
389
+ temperature = void 0;
390
+ }
391
+ const languagesChanged = languages.some((value, index) => value !== this.#opts.languages[index]) || languages.length !== this.#opts.languages.length;
392
+ const languageGiven = opts.language !== void 0 || languagesChanged;
393
+ if (languages.length > 0) this.#specifiedLanguages = languages;
394
+ this.#userKeywords = userKeywords;
395
+ this.#vadOptedOut = vadOptedOut;
396
+ const keywords = supportsContextHints(model) ? [.../* @__PURE__ */ new Set([...userKeywords, ...this.#sessionKeyterms])] : [];
299
397
  this.#opts = {
300
398
  ...this.#opts,
301
399
  ...opts,
302
400
  apiKey: opts.apiKey ?? this.#opts.apiKey,
303
- language: opts.language ? normalizeLanguage(opts.language) : this.#opts.language,
401
+ languages,
402
+ keywords,
304
403
  model,
305
404
  useRealtime,
306
- turnDetection
405
+ turnDetection,
406
+ temperature,
407
+ vad
307
408
  };
308
409
  this.updateCapabilities({
309
410
  streaming: useRealtime,
310
- interimResults: useRealtime
411
+ interimResults: useRealtime,
412
+ keyterms: supportsContextHints(model)
311
413
  });
312
414
  for (const stream of this.#streams) {
313
415
  if (stream.isClosed) {
314
416
  this.#streams.delete(stream);
315
417
  continue;
316
418
  }
317
- stream.updateOptions(this.#opts);
419
+ stream._updateOptions(this.#opts, languageGiven ? languages : void 0);
318
420
  }
319
421
  }
422
+ _updateSessionKeyterms(keyterms) {
423
+ if (!this.capabilities.keyterms) {
424
+ super._updateSessionKeyterms(keyterms);
425
+ return;
426
+ }
427
+ if (keyterms.length === this.#sessionKeyterms.length && keyterms.every((term, index) => term === this.#sessionKeyterms[index])) {
428
+ return;
429
+ }
430
+ this.#sessionKeyterms = [...keyterms];
431
+ this.#opts.keywords = [.../* @__PURE__ */ new Set([...this.#userKeywords, ...keyterms])];
432
+ for (const stream of this.#streams) stream._updateOptions(this.#opts);
433
+ }
320
434
  stream(options = {}) {
321
435
  if (!this.#opts.useRealtime) {
322
436
  throw new Error("Streaming is not supported on OpenAI STT unless useRealtime is enabled");
323
437
  }
438
+ const streamOptions = {
439
+ ...this.#opts,
440
+ languages: options.language !== void 0 ? asLanguages(options.language) : [...this.#opts.languages],
441
+ keywords: [...this.#opts.keywords]
442
+ };
443
+ validateContext(streamOptions.model, streamOptions.languages, streamOptions.keywords);
324
444
  const stream = new SpeechStream(
325
445
  this,
326
- { ...this.#opts },
446
+ streamOptions,
327
447
  options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS,
328
448
  () => this.#streams.delete(stream)
329
449
  );
@@ -345,14 +465,51 @@ class SpeechStream extends stt.SpeechStream {
345
465
  #currentItemId = "";
346
466
  #itemAudioTiming = /* @__PURE__ */ new Map();
347
467
  #speaking = false;
468
+ #ws;
469
+ #wsReady = new AsyncEvent();
470
+ #vadStream;
471
+ #reconnectRequested = false;
348
472
  constructor(stt2, options, connOptions, onClose = () => {
349
473
  }) {
350
474
  super(stt2, REALTIME_SAMPLE_RATE, connOptions);
351
475
  this.#options = options;
352
476
  this.#onClose = onClose;
353
477
  }
478
+ get languages() {
479
+ return this.#options.languages;
480
+ }
354
481
  updateOptions(options) {
355
- this.#options = { ...options };
482
+ const languages = options.language !== void 0 ? asLanguages(options.language) : this.#options.languages;
483
+ validateContext(this.#options.model, languages, this.#options.keywords);
484
+ this.#applyOptions(this.#options, languages);
485
+ }
486
+ /** @internal */
487
+ _updateOptions(options, languages) {
488
+ this.#applyOptions(options, languages ?? this.#options.languages);
489
+ }
490
+ #applyOptions(options, languages) {
491
+ const previous = this.#options;
492
+ this.#options = {
493
+ ...options,
494
+ languages: [...languages],
495
+ keywords: [...options.keywords]
496
+ };
497
+ const modelChanged = previous.model !== this.#options.model;
498
+ const clearedLanguage = previous.languages.length > 0 && this.#options.languages.length === 0;
499
+ if (!this.#ws) return;
500
+ if (modelChanged || clearedLanguage) {
501
+ this.#reconnectRequested = true;
502
+ const ws = this.#ws;
503
+ this.#ws = void 0;
504
+ this.#wsReady.clear();
505
+ ws.close();
506
+ return;
507
+ }
508
+ try {
509
+ this.#ws.send(JSON.stringify(this.#sessionUpdateEvent()));
510
+ } catch (error) {
511
+ console.warn("failed to update the OpenAI transcription session", error);
512
+ }
356
513
  }
357
514
  get isClosed() {
358
515
  return this.closed;
@@ -363,35 +520,37 @@ class SpeechStream extends stt.SpeechStream {
363
520
  }
364
521
  async run() {
365
522
  this.#emitEndOfSpeech();
366
- _validateRealtimeVad(this.#options.model, this.#options.turnDetection, this.#options.vad);
367
- const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) ? await _loadRealtimeVad(this.#options.vad) : void 0;
368
- if (vad) {
369
- this.#options.vad = vad;
370
- }
371
- const vadStream = vad == null ? void 0 : vad.stream();
372
- const ws = await this.#connect();
373
- const abort = () => {
374
- if (ws.readyState < WebSocket.CLOSING) {
375
- ws.close();
376
- }
377
- };
378
- this.abortSignal.addEventListener("abort", abort, { once: true });
523
+ const inputTask = this.#forwardInput();
379
524
  try {
380
- ws.send(JSON.stringify(this.#sessionUpdateEvent()));
381
- const tasks = [
382
- this.#forwardInput(ws, vadStream),
383
- this.#forwardEvents(ws, Boolean(vadStream))
384
- ];
385
- if (vadStream) {
386
- tasks.push(this.#forwardVadEvents(ws, vadStream));
525
+ while (!this.abortSignal.aborted) {
526
+ const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) ? this.#options.vad ? await _loadRealtimeVad(this.#options.vad) : void 0 : void 0;
527
+ const vadStream = vad == null ? void 0 : vad.stream();
528
+ const ws = await this.#connect();
529
+ this.#ws = ws;
530
+ this.#vadStream = vadStream;
531
+ this.#wsReady.set();
532
+ const abort = () => {
533
+ if (ws.readyState < WebSocket.CLOSING) ws.close();
534
+ };
535
+ this.abortSignal.addEventListener("abort", abort, { once: true });
536
+ try {
537
+ ws.send(JSON.stringify(this.#sessionUpdateEvent()));
538
+ const connectionTasks = [this.#forwardEvents(ws, Boolean(vadStream))];
539
+ if (vadStream) connectionTasks.push(this.#forwardVadEvents(ws, vadStream));
540
+ await Promise.race([inputTask, ...connectionTasks]);
541
+ } finally {
542
+ this.#ws = void 0;
543
+ this.#vadStream = void 0;
544
+ this.#wsReady.clear();
545
+ this.abortSignal.removeEventListener("abort", abort);
546
+ vadStream == null ? void 0 : vadStream.close();
547
+ if (ws.readyState < WebSocket.CLOSING) ws.close();
548
+ }
549
+ if (!this.#reconnectRequested) return;
550
+ this.#reconnectRequested = false;
551
+ this.#emitEndOfSpeech();
387
552
  }
388
- await Promise.all(tasks);
389
553
  } finally {
390
- this.abortSignal.removeEventListener("abort", abort);
391
- vadStream == null ? void 0 : vadStream.close();
392
- if (ws.readyState < WebSocket.CLOSING) {
393
- ws.close();
394
- }
395
554
  this.#onClose();
396
555
  }
397
556
  }
@@ -411,11 +570,7 @@ class SpeechStream extends stt.SpeechStream {
411
570
  return buildRealtimeSttUrl(this.#options.baseURL, this.#options.model);
412
571
  }
413
572
  #sessionUpdateEvent() {
414
- const transcription = {
415
- model: this.#options.model,
416
- ...this.#options.prompt ? { prompt: this.#options.prompt } : {},
417
- ...!this.#options.detectLanguage && this.#options.language ? { language: this.#options.language } : {}
418
- };
573
+ const transcription = buildRealtimeTranscriptionConfig(this.#options);
419
574
  return {
420
575
  type: "session.update",
421
576
  session: {
@@ -427,25 +582,30 @@ class SpeechStream extends stt.SpeechStream {
427
582
  rate: REALTIME_SAMPLE_RATE
428
583
  },
429
584
  transcription,
430
- turn_detection: this.#options.turnDetection,
585
+ ...!isRealtimeOnly(this.#options.model) ? { turn_detection: this.#options.turnDetection } : {},
431
586
  ...this.#options.noiseReductionType ? { noise_reduction: { type: this.#options.noiseReductionType } } : {}
432
587
  }
433
588
  }
434
589
  }
435
590
  };
436
591
  }
437
- async #forwardInput(ws, vadStream) {
592
+ async #forwardInput() {
593
+ var _a;
438
594
  const audioStream = new AudioByteStream(
439
595
  REALTIME_SAMPLE_RATE,
440
596
  REALTIME_NUM_CHANNELS,
441
597
  REALTIME_SAMPLE_RATE / 20
442
598
  );
443
599
  for await (const item of this.input) {
600
+ while (!this.#ws && !this.abortSignal.aborted) await this.#wsReady.wait();
601
+ const ws = this.#ws;
602
+ if (!ws) return;
603
+ const vadStream = this.#vadStream;
444
604
  if (item === SpeechStream.FLUSH_SENTINEL) {
445
605
  for (const frame of audioStream.flush()) {
446
606
  this.#sendAudioFrame(ws, frame);
447
607
  }
448
- if (this.#options.turnDetection === null) {
608
+ if (_requiresRealtimeVad(this.#options.model, this.#options.turnDetection) && !this.#options.vad) {
449
609
  ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
450
610
  }
451
611
  continue;
@@ -455,7 +615,7 @@ class SpeechStream extends stt.SpeechStream {
455
615
  this.#sendAudioFrame(ws, frame);
456
616
  }
457
617
  }
458
- vadStream == null ? void 0 : vadStream.endInput();
618
+ (_a = this.#vadStream) == null ? void 0 : _a.endInput();
459
619
  }
460
620
  async #forwardVadEvents(ws, vadStream) {
461
621
  for await (const event of vadStream) {
@@ -463,14 +623,14 @@ class SpeechStream extends stt.SpeechStream {
463
623
  this.#emitStartOfSpeech();
464
624
  } else if (event.type === VADEventType.END_OF_SPEECH) {
465
625
  this.#emitEndOfSpeech();
466
- if (this.#options.turnDetection === null) {
626
+ if (_requiresRealtimeVad(this.#options.model, this.#options.turnDetection)) {
467
627
  ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
468
628
  }
469
629
  }
470
630
  }
471
631
  }
472
632
  async #forwardEvents(ws, hasClientVad) {
473
- var _a;
633
+ var _a, _b, _c;
474
634
  for await (const data of this.#messages(ws)) {
475
635
  const event = parseRealtimeTranscriptionServerEvent(data);
476
636
  switch (event.type) {
@@ -507,7 +667,13 @@ class SpeechStream extends stt.SpeechStream {
507
667
  const transcript = event.transcript ?? "";
508
668
  if (transcript) {
509
669
  this.#targetTranscript = transcript;
510
- this.queue.put(this.#speechEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, itemId));
670
+ this.queue.put(
671
+ this.#speechEvent(
672
+ stt.SpeechEventType.FINAL_TRANSCRIPT,
673
+ itemId,
674
+ (_b = (_a = event.languages) == null ? void 0 : _a[0]) == null ? void 0 : _b.code
675
+ )
676
+ );
511
677
  }
512
678
  this.#emitRecognitionUsage(event, itemId);
513
679
  this.#targetTranscript = "";
@@ -515,7 +681,7 @@ class SpeechStream extends stt.SpeechStream {
515
681
  break;
516
682
  }
517
683
  case "error": {
518
- throw new Error(((_a = event.error) == null ? void 0 : _a.message) || "OpenAI realtime transcription error");
684
+ throw new Error(((_c = event.error) == null ? void 0 : _c.message) || "OpenAI realtime transcription error");
519
685
  }
520
686
  }
521
687
  }
@@ -576,14 +742,14 @@ class SpeechStream extends stt.SpeechStream {
576
742
  this.#speaking = false;
577
743
  this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
578
744
  }
579
- #speechEvent(type, requestId = this.#currentItemId) {
745
+ #speechEvent(type, requestId = this.#currentItemId, detectedLanguage) {
580
746
  return {
581
747
  type,
582
748
  requestId,
583
749
  alternatives: [
584
750
  {
585
751
  text: this.#targetTranscript,
586
- language: normalizeLanguage(this.#options.language || ""),
752
+ language: detectedLanguage ? normalizeLanguage(detectedLanguage) : transcriptLanguage(this.#options.languages),
587
753
  startTime: 0,
588
754
  endTime: 0,
589
755
  confidence: 1
@@ -614,6 +780,7 @@ export {
614
780
  _normalizeRealtimeTurnDetection,
615
781
  _requiresRealtimeVad,
616
782
  _validateRealtimeVad,
617
- buildRealtimeSttUrl
783
+ buildRealtimeSttUrl,
784
+ buildRealtimeTranscriptionConfig
618
785
  };
619
786
  //# sourceMappingURL=stt.js.map