@livekit/agents-plugin-openai 1.3.4 → 1.4.1

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.
package/dist/stt.d.cts CHANGED
@@ -1,6 +1,11 @@
1
- import { type AudioBuffer, stt } from '@livekit/agents';
1
+ import { type APIConnectOptions, type AudioBuffer, type VAD, stt } from '@livekit/agents';
2
2
  import { OpenAI } from 'openai';
3
3
  import type { GroqAudioModels, WhisperModels } from './models.js';
4
+ import type * as api_proto from './realtime/api_proto.js';
5
+ export declare function _loadRealtimeVad(vad?: VAD): Promise<VAD>;
6
+ export declare function _requiresRealtimeVad(model: string, turnDetection: api_proto.TurnDetectionType | null | undefined): boolean;
7
+ export declare function _normalizeRealtimeTurnDetection(model: string, turnDetection: api_proto.TurnDetectionType | null | undefined): api_proto.TurnDetectionType | null | undefined;
8
+ export declare function _validateRealtimeVad(model: string, turnDetection: api_proto.TurnDetectionType | null | undefined, vad: VAD | undefined): void;
4
9
  export interface STTOptions {
5
10
  apiKey?: string;
6
11
  language: string;
@@ -9,11 +14,19 @@ export interface STTOptions {
9
14
  model: WhisperModels | string;
10
15
  baseURL?: string;
11
16
  client?: OpenAI;
17
+ useRealtime: boolean;
18
+ turnDetection?: api_proto.TurnDetectionType | null;
19
+ noiseReductionType?: api_proto.NoiseReductionType;
20
+ vad?: VAD;
12
21
  }
22
+ type ResolvedSTTOptions = Omit<STTOptions, 'apiKey'> & {
23
+ apiKey: string;
24
+ };
13
25
  export declare class STT extends stt.STT {
14
26
  #private;
15
27
  label: string;
16
28
  get model(): string;
29
+ get turnDetection(): api_proto.TurnDetectionType | null | undefined;
17
30
  get provider(): string;
18
31
  /**
19
32
  * Create a new instance of OpenAI STT.
@@ -54,7 +67,20 @@ export declare class STT extends stt.STT {
54
67
  detectLanguage: boolean;
55
68
  }>): STT;
56
69
  _recognize(buffer: AudioBuffer, abortSignal?: AbortSignal): Promise<stt.SpeechEvent>;
57
- /** This method throws an error; streaming is unsupported on OpenAI STT. */
58
- stream(): stt.SpeechStream;
70
+ updateOptions(opts: Partial<STTOptions>): void;
71
+ stream(options?: {
72
+ connOptions?: APIConnectOptions;
73
+ }): stt.SpeechStream;
74
+ close(): Promise<void>;
59
75
  }
76
+ export declare class SpeechStream extends stt.SpeechStream {
77
+ #private;
78
+ label: string;
79
+ constructor(stt: STT, options: ResolvedSTTOptions, connOptions?: APIConnectOptions, onClose?: () => void);
80
+ updateOptions(options: ResolvedSTTOptions): void;
81
+ get isClosed(): boolean;
82
+ close(): void;
83
+ protected run(): Promise<void>;
84
+ }
85
+ export {};
60
86
  //# sourceMappingURL=stt.d.ts.map
package/dist/stt.d.ts CHANGED
@@ -1,6 +1,11 @@
1
- import { type AudioBuffer, stt } from '@livekit/agents';
1
+ import { type APIConnectOptions, type AudioBuffer, type VAD, stt } from '@livekit/agents';
2
2
  import { OpenAI } from 'openai';
3
3
  import type { GroqAudioModels, WhisperModels } from './models.js';
4
+ import type * as api_proto from './realtime/api_proto.js';
5
+ export declare function _loadRealtimeVad(vad?: VAD): Promise<VAD>;
6
+ export declare function _requiresRealtimeVad(model: string, turnDetection: api_proto.TurnDetectionType | null | undefined): boolean;
7
+ export declare function _normalizeRealtimeTurnDetection(model: string, turnDetection: api_proto.TurnDetectionType | null | undefined): api_proto.TurnDetectionType | null | undefined;
8
+ export declare function _validateRealtimeVad(model: string, turnDetection: api_proto.TurnDetectionType | null | undefined, vad: VAD | undefined): void;
4
9
  export interface STTOptions {
5
10
  apiKey?: string;
6
11
  language: string;
@@ -9,11 +14,19 @@ export interface STTOptions {
9
14
  model: WhisperModels | string;
10
15
  baseURL?: string;
11
16
  client?: OpenAI;
17
+ useRealtime: boolean;
18
+ turnDetection?: api_proto.TurnDetectionType | null;
19
+ noiseReductionType?: api_proto.NoiseReductionType;
20
+ vad?: VAD;
12
21
  }
22
+ type ResolvedSTTOptions = Omit<STTOptions, 'apiKey'> & {
23
+ apiKey: string;
24
+ };
13
25
  export declare class STT extends stt.STT {
14
26
  #private;
15
27
  label: string;
16
28
  get model(): string;
29
+ get turnDetection(): api_proto.TurnDetectionType | null | undefined;
17
30
  get provider(): string;
18
31
  /**
19
32
  * Create a new instance of OpenAI STT.
@@ -54,7 +67,20 @@ export declare class STT extends stt.STT {
54
67
  detectLanguage: boolean;
55
68
  }>): STT;
56
69
  _recognize(buffer: AudioBuffer, abortSignal?: AbortSignal): Promise<stt.SpeechEvent>;
57
- /** This method throws an error; streaming is unsupported on OpenAI STT. */
58
- stream(): stt.SpeechStream;
70
+ updateOptions(opts: Partial<STTOptions>): void;
71
+ stream(options?: {
72
+ connOptions?: APIConnectOptions;
73
+ }): stt.SpeechStream;
74
+ close(): Promise<void>;
59
75
  }
76
+ export declare class SpeechStream extends stt.SpeechStream {
77
+ #private;
78
+ label: string;
79
+ constructor(stt: STT, options: ResolvedSTTOptions, connOptions?: APIConnectOptions, onClose?: () => void);
80
+ updateOptions(options: ResolvedSTTOptions): void;
81
+ get isClosed(): boolean;
82
+ close(): void;
83
+ protected run(): Promise<void>;
84
+ }
85
+ export {};
60
86
  //# sourceMappingURL=stt.d.ts.map
package/dist/stt.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"stt.d.ts","sourceRoot":"","sources":["../src/stt.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,WAAW,EAAkC,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAExF,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAChC,OAAO,KAAK,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAElE,MAAM,WAAW,UAAU;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,OAAO,CAAC;IACxB,KAAK,EAAE,aAAa,GAAG,MAAM,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB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AAK,SAAyB;gBAS5B,GAAG,EAAE,GAAG,EACR,OAAO,EAAE,kBAAkB,EAC3B,WAAW,CAAC,EAAE,iBAAiB,EAC/B,OAAO,GAAE,MAAM,IAAe;IAOhC,aAAa,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAIhD,IAAI,QAAQ,IAAI,OAAO,CAEtB;IAEQ,KAAK,IAAI,IAAI;cAKN,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC;CA4RrC"}
package/dist/stt.js CHANGED
@@ -1,18 +1,126 @@
1
- import { mergeFrames, normalizeLanguage, stt } from "@livekit/agents";
1
+ import {
2
+ Event as AsyncEvent,
3
+ AudioByteStream,
4
+ DEFAULT_API_CONNECT_OPTIONS,
5
+ VADEventType,
6
+ mergeFrames,
7
+ normalizeLanguage,
8
+ stt
9
+ } from "@livekit/agents";
2
10
  import { OpenAI } from "openai";
11
+ import { WebSocket } from "ws";
12
+ import { z } from "zod";
13
+ const REALTIME_SAMPLE_RATE = 24e3;
14
+ const REALTIME_NUM_CHANNELS = 1;
15
+ const DEFAULT_REALTIME_MODEL = "gpt-realtime-whisper";
16
+ const DEFAULT_REALTIME_TURN_DETECTION = {
17
+ type: "server_vad",
18
+ threshold: 0.5,
19
+ prefix_padding_ms: 600,
20
+ silence_duration_ms: 350
21
+ };
22
+ const REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION = /* @__PURE__ */ new Set([DEFAULT_REALTIME_MODEL]);
23
+ const realtimeTranscriptionSpeechStartedEventSchema = z.object({
24
+ type: z.literal("input_audio_buffer.speech_started"),
25
+ item_id: z.string().optional(),
26
+ audio_start_ms: z.number().optional()
27
+ });
28
+ const realtimeTranscriptionSpeechStoppedEventSchema = z.object({
29
+ type: z.literal("input_audio_buffer.speech_stopped"),
30
+ item_id: z.string().optional(),
31
+ audio_end_ms: z.number().optional()
32
+ });
33
+ const realtimeTranscriptionDeltaEventSchema = z.object({
34
+ type: z.literal("conversation.item.input_audio_transcription.delta"),
35
+ item_id: z.string().optional(),
36
+ delta: z.string().optional()
37
+ });
38
+ const realtimeTranscriptionCompletedEventSchema = z.object({
39
+ type: z.literal("conversation.item.input_audio_transcription.completed"),
40
+ item_id: z.string().optional(),
41
+ transcript: z.string().optional(),
42
+ usage: z.object({
43
+ input_tokens: z.number().optional(),
44
+ output_tokens: z.number().optional()
45
+ }).passthrough().optional()
46
+ });
47
+ const realtimeTranscriptionErrorEventSchema = z.object({
48
+ type: z.literal("error"),
49
+ error: z.object({
50
+ message: z.string().optional()
51
+ }).passthrough().optional()
52
+ });
53
+ const knownRealtimeTranscriptionServerEventSchema = z.discriminatedUnion("type", [
54
+ realtimeTranscriptionSpeechStartedEventSchema,
55
+ realtimeTranscriptionSpeechStoppedEventSchema,
56
+ realtimeTranscriptionDeltaEventSchema,
57
+ realtimeTranscriptionCompletedEventSchema,
58
+ realtimeTranscriptionErrorEventSchema
59
+ ]);
60
+ const knownRealtimeTranscriptionServerEventTypes = /* @__PURE__ */ new Set([
61
+ "input_audio_buffer.speech_started",
62
+ "input_audio_buffer.speech_stopped",
63
+ "conversation.item.input_audio_transcription.delta",
64
+ "conversation.item.input_audio_transcription.completed",
65
+ "error"
66
+ ]);
67
+ const unknownRealtimeTranscriptionServerEventSchema = z.object({
68
+ type: z.string().refine((type) => !knownRealtimeTranscriptionServerEventTypes.has(type))
69
+ }).passthrough();
70
+ function parseRealtimeTranscriptionServerEvent(data) {
71
+ const event = JSON.parse(data);
72
+ const knownEvent = knownRealtimeTranscriptionServerEventSchema.safeParse(event);
73
+ if (knownEvent.success) {
74
+ return knownEvent.data;
75
+ }
76
+ return {
77
+ type: "unknown",
78
+ event: unknownRealtimeTranscriptionServerEventSchema.parse(event)
79
+ };
80
+ }
81
+ async function _loadRealtimeVad(vad) {
82
+ if (vad) return vad;
83
+ throw new Error(
84
+ "OpenAI realtime STT models without server-side endpointing must provide a VAD via the `vad` option."
85
+ );
86
+ }
87
+ function _requiresRealtimeVad(model, turnDetection) {
88
+ return turnDetection === null || REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model);
89
+ }
90
+ function _normalizeRealtimeTurnDetection(model, turnDetection) {
91
+ if (turnDetection !== null && REALTIME_MODELS_WITHOUT_SERVER_TURN_DETECTION.has(model)) {
92
+ console.warn(
93
+ `Turn detection is not supported for ${model}; ignoring the provided turnDetection and using plugin-side VAD commits instead.`
94
+ );
95
+ return null;
96
+ }
97
+ return turnDetection;
98
+ }
99
+ function _validateRealtimeVad(model, turnDetection, vad) {
100
+ if (_requiresRealtimeVad(model, turnDetection) && !vad) {
101
+ throw new Error(
102
+ `A VAD instance is required for ${model}. Pass a VAD via the \`vad\` option so the plugin can commit audio at end-of-speech.`
103
+ );
104
+ }
105
+ }
3
106
  const defaultSTTOptions = {
4
107
  apiKey: process.env.OPENAI_API_KEY,
5
108
  language: "en",
6
109
  detectLanguage: false,
7
- model: "whisper-1"
110
+ model: DEFAULT_REALTIME_MODEL,
111
+ useRealtime: true
8
112
  };
9
113
  class STT extends stt.STT {
10
114
  #opts;
11
115
  #client;
116
+ #streams = /* @__PURE__ */ new Set();
12
117
  label = "openai.STT";
13
118
  get model() {
14
119
  return this.#opts.model;
15
120
  }
121
+ get turnDetection() {
122
+ return this.#opts.turnDetection;
123
+ }
16
124
  get provider() {
17
125
  try {
18
126
  const url = new URL(this.#client.baseURL);
@@ -29,15 +137,33 @@ class STT extends stt.STT {
29
137
  * `OPENAI_API_KEY` environment variable.
30
138
  */
31
139
  constructor(opts = defaultSTTOptions) {
32
- super({ streaming: false, interimResults: false, alignedTranscript: false });
140
+ const useRealtime = opts.useRealtime ?? defaultSTTOptions.useRealtime;
141
+ const model = opts.model ?? (useRealtime ? DEFAULT_REALTIME_MODEL : "whisper-1");
142
+ super({
143
+ streaming: useRealtime,
144
+ interimResults: useRealtime,
145
+ alignedTranscript: false
146
+ });
147
+ const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
148
+ if (apiKey === void 0) {
149
+ throw new Error("OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY");
150
+ }
151
+ const turnDetection = _normalizeRealtimeTurnDetection(
152
+ model,
153
+ opts.turnDetection !== void 0 ? opts.turnDetection : model === DEFAULT_REALTIME_MODEL ? null : DEFAULT_REALTIME_TURN_DETECTION
154
+ );
155
+ if (useRealtime) {
156
+ _validateRealtimeVad(model, turnDetection, opts.vad);
157
+ }
33
158
  this.#opts = {
34
159
  ...defaultSTTOptions,
35
160
  ...opts,
36
- language: normalizeLanguage(opts.language ?? defaultSTTOptions.language)
161
+ apiKey,
162
+ language: normalizeLanguage(opts.language ?? defaultSTTOptions.language),
163
+ model,
164
+ useRealtime,
165
+ turnDetection
37
166
  };
38
- if (this.#opts.apiKey === void 0) {
39
- throw new Error("OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY");
40
- }
41
167
  this.#client = this.#opts.client || new OpenAI({
42
168
  baseURL: this.#opts.baseURL,
43
169
  apiKey: this.#opts.apiKey
@@ -58,7 +184,8 @@ class STT extends stt.STT {
58
184
  return new STT({
59
185
  model: "whisper-large-v3-turbo",
60
186
  baseURL: "https://api.groq.com/openai/v1",
61
- ...opts
187
+ ...opts,
188
+ useRealtime: false
62
189
  });
63
190
  }
64
191
  /**
@@ -78,7 +205,8 @@ class STT extends stt.STT {
78
205
  return new STT({
79
206
  model: "whisper-large-v3-turbo",
80
207
  baseURL: "https://oai.endpoints.kepler.ai.cloud.ovh.net/v1",
81
- ...opts
208
+ ...opts,
209
+ useRealtime: false
82
210
  });
83
211
  }
84
212
  #sanitizeOptions(language) {
@@ -138,12 +266,331 @@ class STT extends stt.STT {
138
266
  ]
139
267
  };
140
268
  }
141
- /** This method throws an error; streaming is unsupported on OpenAI STT. */
142
- stream() {
143
- throw new Error("Streaming is not supported on OpenAI STT");
269
+ updateOptions(opts) {
270
+ const useRealtime = opts.useRealtime ?? this.#opts.useRealtime;
271
+ const model = opts.model ?? this.#opts.model;
272
+ const turnDetection = _normalizeRealtimeTurnDetection(
273
+ model,
274
+ opts.turnDetection !== void 0 ? opts.turnDetection : opts.model === DEFAULT_REALTIME_MODEL ? null : this.#opts.turnDetection
275
+ );
276
+ if (useRealtime) {
277
+ _validateRealtimeVad(model, turnDetection, opts.vad ?? this.#opts.vad);
278
+ }
279
+ this.#opts = {
280
+ ...this.#opts,
281
+ ...opts,
282
+ apiKey: opts.apiKey ?? this.#opts.apiKey,
283
+ language: opts.language ? normalizeLanguage(opts.language) : this.#opts.language,
284
+ model,
285
+ useRealtime,
286
+ turnDetection
287
+ };
288
+ this.updateCapabilities({
289
+ streaming: useRealtime,
290
+ interimResults: useRealtime
291
+ });
292
+ for (const stream of this.#streams) {
293
+ if (stream.isClosed) {
294
+ this.#streams.delete(stream);
295
+ continue;
296
+ }
297
+ stream.updateOptions(this.#opts);
298
+ }
299
+ }
300
+ stream(options = {}) {
301
+ if (!this.#opts.useRealtime) {
302
+ throw new Error("Streaming is not supported on OpenAI STT unless useRealtime is enabled");
303
+ }
304
+ const stream = new SpeechStream(
305
+ this,
306
+ { ...this.#opts },
307
+ options.connOptions ?? DEFAULT_API_CONNECT_OPTIONS,
308
+ () => this.#streams.delete(stream)
309
+ );
310
+ this.#streams.add(stream);
311
+ return stream;
312
+ }
313
+ async close() {
314
+ for (const stream of this.#streams) {
315
+ stream.close();
316
+ }
317
+ this.#streams.clear();
318
+ }
319
+ }
320
+ class SpeechStream extends stt.SpeechStream {
321
+ label = "openai.SpeechStream";
322
+ #options;
323
+ #onClose;
324
+ #targetTranscript = "";
325
+ #currentItemId = "";
326
+ #itemAudioTiming = /* @__PURE__ */ new Map();
327
+ #speaking = false;
328
+ constructor(stt2, options, connOptions, onClose = () => {
329
+ }) {
330
+ super(stt2, REALTIME_SAMPLE_RATE, connOptions);
331
+ this.#options = options;
332
+ this.#onClose = onClose;
333
+ }
334
+ updateOptions(options) {
335
+ this.#options = { ...options };
336
+ }
337
+ get isClosed() {
338
+ return this.closed;
339
+ }
340
+ close() {
341
+ super.close();
342
+ this.#onClose();
343
+ }
344
+ async run() {
345
+ _validateRealtimeVad(this.#options.model, this.#options.turnDetection, this.#options.vad);
346
+ const vad = _requiresRealtimeVad(this.#options.model, this.#options.turnDetection) ? await _loadRealtimeVad(this.#options.vad) : void 0;
347
+ if (vad) {
348
+ this.#options.vad = vad;
349
+ }
350
+ const vadStream = vad == null ? void 0 : vad.stream();
351
+ const ws = await this.#connect();
352
+ const abort = () => {
353
+ if (ws.readyState < WebSocket.CLOSING) {
354
+ ws.close();
355
+ }
356
+ };
357
+ this.abortSignal.addEventListener("abort", abort, { once: true });
358
+ try {
359
+ ws.send(JSON.stringify(this.#sessionUpdateEvent()));
360
+ const tasks = [this.#forwardInput(ws, vadStream), this.#forwardEvents(ws)];
361
+ if (vadStream) {
362
+ tasks.push(this.#forwardVadEvents(ws, vadStream));
363
+ }
364
+ await Promise.all(tasks);
365
+ } finally {
366
+ this.abortSignal.removeEventListener("abort", abort);
367
+ vadStream == null ? void 0 : vadStream.close();
368
+ if (ws.readyState < WebSocket.CLOSING) {
369
+ ws.close();
370
+ }
371
+ this.#onClose();
372
+ }
373
+ }
374
+ async #connect() {
375
+ const ws = new WebSocket(this.#realtimeUrl(), {
376
+ headers: {
377
+ Authorization: `Bearer ${this.#options.apiKey}`
378
+ }
379
+ });
380
+ await new Promise((resolve, reject) => {
381
+ ws.onopen = () => resolve();
382
+ ws.onerror = (error) => reject(new Error(error.message));
383
+ });
384
+ return ws;
385
+ }
386
+ #realtimeUrl() {
387
+ const url = new URL(this.#options.baseURL || "https://api.openai.com/v1");
388
+ if (url.protocol === "https:") {
389
+ url.protocol = "wss:";
390
+ }
391
+ const path = url.pathname.replace(/\/$/, "");
392
+ if (!path || path === "/v1") {
393
+ url.pathname = `${path}/realtime`;
394
+ } else if (!path.endsWith("/realtime")) {
395
+ url.pathname = `${path}/realtime`;
396
+ }
397
+ url.searchParams.set("intent", "transcription");
398
+ return url.toString();
399
+ }
400
+ #sessionUpdateEvent() {
401
+ const transcription = {
402
+ model: this.#options.model,
403
+ ...this.#options.prompt ? { prompt: this.#options.prompt } : {},
404
+ ...!this.#options.detectLanguage && this.#options.language ? { language: this.#options.language } : {}
405
+ };
406
+ return {
407
+ type: "session.update",
408
+ session: {
409
+ type: "transcription",
410
+ audio: {
411
+ input: {
412
+ format: {
413
+ type: "audio/pcm",
414
+ rate: REALTIME_SAMPLE_RATE
415
+ },
416
+ transcription,
417
+ turn_detection: this.#options.turnDetection,
418
+ ...this.#options.noiseReductionType ? { noise_reduction: { type: this.#options.noiseReductionType } } : {}
419
+ }
420
+ }
421
+ }
422
+ };
423
+ }
424
+ async #forwardInput(ws, vadStream) {
425
+ const audioStream = new AudioByteStream(
426
+ REALTIME_SAMPLE_RATE,
427
+ REALTIME_NUM_CHANNELS,
428
+ REALTIME_SAMPLE_RATE / 20
429
+ );
430
+ for await (const item of this.input) {
431
+ if (item === SpeechStream.FLUSH_SENTINEL) {
432
+ for (const frame of audioStream.flush()) {
433
+ this.#sendAudioFrame(ws, frame);
434
+ }
435
+ if (this.#options.turnDetection === null) {
436
+ ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
437
+ }
438
+ continue;
439
+ }
440
+ vadStream == null ? void 0 : vadStream.pushFrame(item);
441
+ for (const frame of audioStream.write(item.data.buffer)) {
442
+ this.#sendAudioFrame(ws, frame);
443
+ }
444
+ }
445
+ vadStream == null ? void 0 : vadStream.endInput();
446
+ }
447
+ async #forwardVadEvents(ws, vadStream) {
448
+ for await (const event of vadStream) {
449
+ if (event.type === VADEventType.START_OF_SPEECH) {
450
+ this.#emitStartOfSpeech();
451
+ } else if (event.type === VADEventType.END_OF_SPEECH && this.#options.turnDetection === null) {
452
+ ws.send(JSON.stringify({ type: "input_audio_buffer.commit" }));
453
+ }
454
+ }
455
+ }
456
+ async #forwardEvents(ws) {
457
+ var _a;
458
+ for await (const data of this.#messages(ws)) {
459
+ const event = parseRealtimeTranscriptionServerEvent(data);
460
+ switch (event.type) {
461
+ case "input_audio_buffer.speech_started": {
462
+ const itemId = event.item_id ?? "";
463
+ this.#currentItemId = itemId;
464
+ this.#itemAudioTiming.set(itemId, {
465
+ startMs: event.audio_start_ms
466
+ });
467
+ this.#emitStartOfSpeech();
468
+ break;
469
+ }
470
+ case "input_audio_buffer.speech_stopped": {
471
+ const itemId = event.item_id ?? this.#currentItemId;
472
+ const timing = this.#itemAudioTiming.get(itemId) ?? {};
473
+ timing.endMs = event.audio_end_ms;
474
+ this.#itemAudioTiming.set(itemId, timing);
475
+ break;
476
+ }
477
+ case "conversation.item.input_audio_transcription.delta":
478
+ this.#currentItemId = event.item_id ?? this.#currentItemId;
479
+ if (event.delta) {
480
+ this.#targetTranscript += event.delta;
481
+ this.#emitStartOfSpeech();
482
+ this.queue.put(this.#speechEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT));
483
+ }
484
+ break;
485
+ case "conversation.item.input_audio_transcription.completed": {
486
+ const itemId = event.item_id ?? this.#currentItemId;
487
+ const transcript = event.transcript ?? "";
488
+ if (transcript) {
489
+ this.#targetTranscript = transcript;
490
+ this.#emitStartOfSpeech();
491
+ this.queue.put(this.#speechEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, itemId));
492
+ }
493
+ this.#emitRecognitionUsage(event, itemId);
494
+ this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
495
+ this.#targetTranscript = "";
496
+ this.#currentItemId = "";
497
+ this.#speaking = false;
498
+ break;
499
+ }
500
+ case "error": {
501
+ throw new Error(((_a = event.error) == null ? void 0 : _a.message) || "OpenAI realtime transcription error");
502
+ }
503
+ }
504
+ }
505
+ }
506
+ async *#messages(ws) {
507
+ const queue = [];
508
+ const messageEvent = new AsyncEvent();
509
+ let closed = false;
510
+ let error;
511
+ ws.onmessage = (message) => {
512
+ queue.push(
513
+ typeof message.data === "string" ? message.data : Buffer.from(message.data).toString()
514
+ );
515
+ messageEvent.set();
516
+ };
517
+ ws.onclose = () => {
518
+ closed = true;
519
+ messageEvent.set();
520
+ };
521
+ ws.onerror = (event) => {
522
+ error = new Error(event.message);
523
+ closed = true;
524
+ messageEvent.set();
525
+ };
526
+ while (!closed || queue.length > 0) {
527
+ if (queue.length > 0) {
528
+ yield queue.shift();
529
+ continue;
530
+ }
531
+ messageEvent.clear();
532
+ if (closed || queue.length > 0) continue;
533
+ await messageEvent.wait();
534
+ }
535
+ if (error) throw error;
536
+ }
537
+ #sendAudioFrame(ws, frame) {
538
+ if (frame.data.byteLength === 0 || frame.samplesPerChannel === 0) {
539
+ return;
540
+ }
541
+ ws.send(
542
+ JSON.stringify({
543
+ type: "input_audio_buffer.append",
544
+ audio: Buffer.from(
545
+ frame.data.buffer,
546
+ frame.data.byteOffset,
547
+ frame.data.byteLength
548
+ ).toString("base64")
549
+ })
550
+ );
551
+ }
552
+ #emitStartOfSpeech() {
553
+ if (this.#speaking) return;
554
+ this.#speaking = true;
555
+ this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });
556
+ }
557
+ #speechEvent(type, requestId = this.#currentItemId) {
558
+ return {
559
+ type,
560
+ requestId,
561
+ alternatives: [
562
+ {
563
+ text: this.#targetTranscript,
564
+ language: normalizeLanguage(this.#options.language || ""),
565
+ startTime: 0,
566
+ endTime: 0,
567
+ confidence: 1
568
+ }
569
+ ]
570
+ };
571
+ }
572
+ #emitRecognitionUsage(event, itemId) {
573
+ var _a, _b;
574
+ const timing = this.#itemAudioTiming.get(itemId);
575
+ this.#itemAudioTiming.delete(itemId);
576
+ const audioDuration = (timing == null ? void 0 : timing.startMs) !== void 0 && timing.endMs !== void 0 && timing.endMs > timing.startMs ? (timing.endMs - timing.startMs) / 1e3 : 0;
577
+ this.queue.put({
578
+ type: stt.SpeechEventType.RECOGNITION_USAGE,
579
+ requestId: itemId,
580
+ recognitionUsage: {
581
+ audioDuration,
582
+ inputTokens: (_a = event.usage) == null ? void 0 : _a.input_tokens,
583
+ outputTokens: (_b = event.usage) == null ? void 0 : _b.output_tokens
584
+ }
585
+ });
144
586
  }
145
587
  }
146
588
  export {
147
- STT
589
+ STT,
590
+ SpeechStream,
591
+ _loadRealtimeVad,
592
+ _normalizeRealtimeTurnDetection,
593
+ _requiresRealtimeVad,
594
+ _validateRealtimeVad
148
595
  };
149
596
  //# sourceMappingURL=stt.js.map