@livekit/agents-plugin-assemblyai 0.0.0-next-20260624041820

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/src/stt.ts ADDED
@@ -0,0 +1,627 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ //
5
+ import {
6
+ type APIConnectOptions,
7
+ type AudioBuffer,
8
+ AudioByteStream,
9
+ Future,
10
+ Task,
11
+ createTimedString,
12
+ delay,
13
+ log,
14
+ normalizeLanguage,
15
+ stt,
16
+ waitForAbort,
17
+ } from '@livekit/agents';
18
+ import type { AudioFrame } from '@livekit/rtc-node';
19
+ import type { RawData } from 'ws';
20
+ import { WebSocket } from 'ws';
21
+ import type { STTEncoding, STTModels, VoiceFocus } from './models.js';
22
+
23
+ const U3_PRO_MODELS = ['u3-rt-pro', 'u3-rt-pro-beta-1', 'universal-3-5-pro'] as const;
24
+
25
+ function isU3ProModel(model: STTModels): boolean {
26
+ return U3_PRO_MODELS.includes(model as (typeof U3_PRO_MODELS)[number]);
27
+ }
28
+
29
+ // AssemblyAI Universal-Streaming (v3) message envelope. All fields are optional
30
+ // since we narrow on `type` before reading anything else.
31
+ interface StreamEventMessage {
32
+ type?: 'Begin' | 'SpeechStarted' | 'Turn' | 'Termination' | string;
33
+ // Begin
34
+ id?: string;
35
+ expires_at?: number;
36
+ // Turn
37
+ transcript?: string;
38
+ utterance?: string;
39
+ end_of_turn?: boolean;
40
+ end_of_turn_confidence?: number;
41
+ turn_is_formatted?: boolean;
42
+ language_code?: string;
43
+ speaker_label?: string;
44
+ words?: Array<{
45
+ text?: string;
46
+ start?: number;
47
+ end?: number;
48
+ confidence?: number;
49
+ speaker?: string;
50
+ }>;
51
+ // Termination
52
+ audio_duration_seconds?: number;
53
+ session_duration_seconds?: number;
54
+ }
55
+
56
+ export interface STTOptions {
57
+ apiKey?: string;
58
+ sampleRate: number;
59
+ /**
60
+ * How large each chunk of audio is before being sent to AssemblyAI, in
61
+ * milliseconds. Corresponds to Python's `buffer_size_seconds` (seconds there,
62
+ * ms here per this repo's time-unit convention).
63
+ */
64
+ bufferSizeMs: number;
65
+ encoding: STTEncoding;
66
+ speechModel: STTModels;
67
+ languageDetection?: boolean;
68
+ endOfTurnConfidenceThreshold?: number;
69
+ /** Minimum silence (ms) before a confident end-of-turn is finalized. */
70
+ minTurnSilence?: number;
71
+ /** Maximum silence (ms) before end-of-turn is forced regardless of confidence. */
72
+ maxTurnSilence?: number;
73
+ formatTurns?: boolean;
74
+ keytermsPrompt?: string[];
75
+ /** Only supported with the `u3-rt-pro` model family. */
76
+ prompt?: string;
77
+ /** Only supported with the `u3-rt-pro` model family. */
78
+ agentContext?: string;
79
+ /** Only supported with the `u3-rt-pro` model family. Set at connection time only. */
80
+ previousContextNTurns?: number;
81
+ vadThreshold?: number;
82
+ /**
83
+ * Enable speaker diarization. Note: AssemblyAI will return per-word speaker
84
+ * labels, but the JS framework's `stt.SpeechData` type does not yet expose
85
+ * a `speakerId` field (unlike the Python framework), so the labels are not
86
+ * currently surfaced on emitted events. Setting this to `true` still has
87
+ * effect server-side. Once the base `SpeechData` interface gains speaker
88
+ * support, `#processStreamEvent` should forward `data.words[].speaker` too.
89
+ */
90
+ speakerLabels?: boolean;
91
+ maxSpeakers?: number;
92
+ domain?: string;
93
+ /** Isolate the primary voice and suppress background noise. Connect-time only. */
94
+ voiceFocus?: VoiceFocus;
95
+ /** Background audio suppression aggressiveness, from 0.0 to 1.0. Connect-time only. */
96
+ voiceFocusThreshold?: number;
97
+ /**
98
+ * Accuracy/latency preset for u3-rt-pro: `min_latency`, `balanced`, or `max_accuracy`.
99
+ * Explicit silence, partials, or VAD options still take precedence over mode defaults.
100
+ */
101
+ mode?: 'min_latency' | 'balanced' | 'max_accuracy';
102
+ baseUrl: string;
103
+ }
104
+
105
+ const defaultSTTOptions: STTOptions = {
106
+ apiKey: process.env.ASSEMBLYAI_API_KEY,
107
+ sampleRate: 16000,
108
+ bufferSizeMs: 50,
109
+ encoding: 'pcm_s16le',
110
+ speechModel: 'universal-3-5-pro',
111
+ baseUrl: 'wss://streaming.assemblyai.com',
112
+ };
113
+
114
+ export class STT extends stt.STT {
115
+ #opts: STTOptions;
116
+ #streams = new Set<WeakRef<SpeechStream>>();
117
+ label = 'assemblyai.STT';
118
+
119
+ get model(): string {
120
+ return this.#opts.speechModel;
121
+ }
122
+
123
+ get provider(): string {
124
+ return 'AssemblyAI';
125
+ }
126
+
127
+ constructor(opts: Partial<STTOptions> = {}) {
128
+ super({
129
+ streaming: true,
130
+ interimResults: true,
131
+ alignedTranscript: 'word',
132
+ });
133
+
134
+ if (opts.speechModel === 'u3-pro') {
135
+ log().warn("'u3-pro' is deprecated, use 'u3-rt-pro' instead.");
136
+ opts.speechModel = 'u3-rt-pro';
137
+ }
138
+
139
+ const speechModel = opts.speechModel ?? defaultSTTOptions.speechModel;
140
+ if (!isU3ProModel(speechModel)) {
141
+ for (const param of [
142
+ 'prompt',
143
+ 'agentContext',
144
+ 'previousContextNTurns',
145
+ 'voiceFocus',
146
+ 'voiceFocusThreshold',
147
+ 'mode',
148
+ ] as const) {
149
+ if (opts[param] !== undefined) {
150
+ throw new Error(
151
+ `The '${param}' parameter is only supported with the ${U3_PRO_MODELS.join(', ')} models.`,
152
+ );
153
+ }
154
+ }
155
+ }
156
+
157
+ const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
158
+ if (!apiKey) {
159
+ throw new Error(
160
+ 'AssemblyAI API key is required. Pass one in via the `apiKey` parameter, or set it as the `ASSEMBLYAI_API_KEY` environment variable',
161
+ );
162
+ }
163
+
164
+ // Minimize latency; matches LK's end-of-turn detector well.
165
+ const minTurnSilence = opts.minTurnSilence ?? 100;
166
+
167
+ this.#opts = {
168
+ ...defaultSTTOptions,
169
+ ...opts,
170
+ apiKey,
171
+ minTurnSilence,
172
+ };
173
+ }
174
+
175
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
176
+ async _recognize(_: AudioBuffer): Promise<stt.SpeechEvent> {
177
+ throw new Error('Non-streaming recognize is not supported on AssemblyAI STT');
178
+ }
179
+
180
+ updateOptions(opts: Partial<STTOptions>) {
181
+ this.#opts = { ...this.#opts, ...opts };
182
+ for (const ref of this.#streams) {
183
+ const stream = ref.deref();
184
+ if (stream) {
185
+ stream.updateOptions(opts);
186
+ } else {
187
+ this.#streams.delete(ref);
188
+ }
189
+ }
190
+ }
191
+
192
+ stream(options?: { connOptions?: APIConnectOptions }): SpeechStream {
193
+ const stream = new SpeechStream(this, this.#opts, options?.connOptions);
194
+ this.#streams.add(new WeakRef(stream));
195
+ return stream;
196
+ }
197
+ }
198
+
199
+ export class SpeechStream extends stt.SpeechStream {
200
+ static readonly CLOSE_MSG = JSON.stringify({ type: 'Terminate' });
201
+
202
+ #opts: STTOptions;
203
+ #logger = log();
204
+ #speechDurationInS = 0;
205
+ #lastPreflightStartTime = 0;
206
+ #pendingConfigMessages: Record<string, unknown>[] = [];
207
+ #configMessagePending = new Future();
208
+ #sessionId: string | null = null;
209
+ #expiresAt: number | null = null;
210
+ label = 'assemblyai.SpeechStream';
211
+
212
+ constructor(stt: STT, opts: STTOptions, connOptions?: APIConnectOptions) {
213
+ super(stt, opts.sampleRate, connOptions);
214
+ this.#opts = opts;
215
+ this.closed = false;
216
+ }
217
+
218
+ /**
219
+ * The AssemblyAI session ID. Set when the WebSocket connection is established
220
+ * (before any speech events). Null until the connection completes.
221
+ * Share this with the AssemblyAI team when reporting issues.
222
+ */
223
+ get sessionId(): string | null {
224
+ return this.#sessionId;
225
+ }
226
+
227
+ /**
228
+ * Unix timestamp when the AssemblyAI session expires. Set alongside
229
+ * {@link sessionId} when the WebSocket connection is established.
230
+ */
231
+ get expiresAt(): number | null {
232
+ return this.#expiresAt;
233
+ }
234
+
235
+ updateOptions(opts: Partial<STTOptions>) {
236
+ this.#opts = { ...this.#opts, ...opts };
237
+
238
+ const configMsg: Record<string, unknown> = { type: 'UpdateConfiguration' };
239
+ if (opts.prompt !== undefined) configMsg.prompt = opts.prompt;
240
+ if (opts.agentContext !== undefined) configMsg.agent_context = opts.agentContext;
241
+ if (opts.keytermsPrompt !== undefined) configMsg.keyterms_prompt = opts.keytermsPrompt;
242
+ if (opts.maxTurnSilence !== undefined) configMsg.max_turn_silence = opts.maxTurnSilence;
243
+ if (opts.minTurnSilence !== undefined) configMsg.min_turn_silence = opts.minTurnSilence;
244
+ if (opts.endOfTurnConfidenceThreshold !== undefined) {
245
+ configMsg.end_of_turn_confidence_threshold = opts.endOfTurnConfidenceThreshold;
246
+ }
247
+ if (opts.vadThreshold !== undefined) configMsg.vad_threshold = opts.vadThreshold;
248
+
249
+ // Only send if any actual fields (besides `type`) were specified.
250
+ if (Object.keys(configMsg).length > 1) {
251
+ this.#pendingConfigMessages.push(configMsg);
252
+ if (!this.#configMessagePending.done) this.#configMessagePending.resolve();
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Force-finalize the current turn immediately.
258
+ */
259
+ forceEndpoint() {
260
+ this.#pendingConfigMessages.push({ type: 'ForceEndpoint' });
261
+ if (!this.#configMessagePending.done) this.#configMessagePending.resolve();
262
+ }
263
+
264
+ // Deepgram-style reconnect loop around a single websocket lifetime.
265
+ protected async run() {
266
+ const maxRetry = 32;
267
+ let retries = 0;
268
+
269
+ while (!this.input.closed && !this.closed) {
270
+ try {
271
+ const ws = await this.#connectWS();
272
+ await this.#runWS(ws);
273
+ retries = 0;
274
+ } catch (e) {
275
+ if (!this.closed && !this.input.closed) {
276
+ if (retries >= maxRetry) {
277
+ throw new Error(`failed to connect to AssemblyAI after ${retries} attempts: ${e}`);
278
+ }
279
+
280
+ const retryDelaySeconds = Math.min(retries * 5, 10);
281
+ retries++;
282
+
283
+ this.#logger.warn(
284
+ `failed to connect to AssemblyAI, retrying in ${retryDelaySeconds} seconds: ${e} (${retries}/${maxRetry})`,
285
+ );
286
+ await delay(retryDelaySeconds * 1000);
287
+ } else {
288
+ this.#logger.warn(
289
+ `AssemblyAI disconnected, connection is closed: ${e} (inputClosed: ${this.input.closed}, isClosed: ${this.closed})`,
290
+ );
291
+ }
292
+ }
293
+ }
294
+
295
+ this.closed = true;
296
+ }
297
+
298
+ async #connectWS(): Promise<WebSocket> {
299
+ // u3-rt-pro family models default both min and max silence to 100ms when unset.
300
+ let minSilence = this.#opts.minTurnSilence;
301
+ let maxSilence = this.#opts.maxTurnSilence;
302
+ if (isU3ProModel(this.#opts.speechModel)) {
303
+ if (minSilence === undefined) minSilence = 100;
304
+ if (maxSilence === undefined) maxSilence = minSilence;
305
+ }
306
+
307
+ // Default language_detection to true for multilingual / u3-rt-pro-family models, false otherwise.
308
+ const defaultLanguageDetection =
309
+ this.#opts.speechModel.includes('multilingual') || isU3ProModel(this.#opts.speechModel);
310
+ const languageDetection = this.#opts.languageDetection ?? defaultLanguageDetection;
311
+
312
+ const liveConfig: Record<string, unknown> = {
313
+ sample_rate: this.#opts.sampleRate,
314
+ encoding: this.#opts.encoding,
315
+ speech_model: this.#opts.speechModel,
316
+ format_turns: this.#opts.formatTurns,
317
+ end_of_turn_confidence_threshold: this.#opts.endOfTurnConfidenceThreshold,
318
+ min_turn_silence: minSilence,
319
+ max_turn_silence: maxSilence,
320
+ keyterms_prompt:
321
+ this.#opts.keytermsPrompt !== undefined
322
+ ? JSON.stringify(this.#opts.keytermsPrompt)
323
+ : undefined,
324
+ language_detection: languageDetection,
325
+ prompt: this.#opts.prompt,
326
+ agent_context: this.#opts.agentContext,
327
+ previous_context_n_turns: this.#opts.previousContextNTurns,
328
+ vad_threshold: this.#opts.vadThreshold,
329
+ speaker_labels: this.#opts.speakerLabels,
330
+ max_speakers: this.#opts.maxSpeakers,
331
+ domain: this.#opts.domain,
332
+ voice_focus: this.#opts.voiceFocus,
333
+ voice_focus_threshold: this.#opts.voiceFocusThreshold,
334
+ mode: this.#opts.mode,
335
+ };
336
+
337
+ const url = new URL(`${this.#opts.baseUrl}/v3/ws`);
338
+ // Python serializes booleans as the strings "true"/"false", so we mirror that.
339
+ for (const [key, value] of Object.entries(liveConfig)) {
340
+ if (value === undefined || value === null) continue;
341
+ if (typeof value === 'boolean') {
342
+ url.searchParams.append(key, value ? 'true' : 'false');
343
+ } else {
344
+ url.searchParams.append(key, String(value));
345
+ }
346
+ }
347
+
348
+ const ws = new WebSocket(url, {
349
+ headers: {
350
+ Authorization: this.#opts.apiKey!,
351
+ 'Content-Type': 'application/json',
352
+ 'User-Agent': 'AssemblyAI/1.0 (integration=Livekit)',
353
+ },
354
+ });
355
+
356
+ await new Promise<void>((resolve, reject) => {
357
+ ws.on('open', () => resolve());
358
+ ws.on('error', (error) => reject(error));
359
+ ws.on('close', (code) => reject(new Error(`WebSocket returned ${code}`)));
360
+ });
361
+
362
+ return ws;
363
+ }
364
+
365
+ async #runWS(ws: WebSocket) {
366
+ let closing = false;
367
+ const sessionController = new AbortController();
368
+
369
+ // gets cancelled also when sendTask is complete
370
+ const wsMonitor = Task.from(async (controller) => {
371
+ const closed = new Promise<void>((_, reject) => {
372
+ ws.once('close', (code, reason) => {
373
+ if (!closing) {
374
+ this.#logger.error(`WebSocket closed with code ${code}: ${reason}`);
375
+ reject(new Error('WebSocket closed'));
376
+ }
377
+ });
378
+ });
379
+
380
+ await Promise.race([closed, waitForAbort(controller.signal)]);
381
+ });
382
+
383
+ const sendTask = async () => {
384
+ const samplesPerBuffer = Math.floor((this.#opts.sampleRate * this.#opts.bufferSizeMs) / 1000);
385
+ const audioStream = new AudioByteStream(this.#opts.sampleRate, 1, samplesPerBuffer);
386
+
387
+ const abortPromise = waitForAbort(this.abortSignal);
388
+ const sessionAbort = waitForAbort(sessionController.signal);
389
+
390
+ try {
391
+ while (!this.closed) {
392
+ const result = await Promise.race([this.input.next(), abortPromise, sessionAbort]);
393
+
394
+ if (result === undefined) return; // aborted
395
+ if (result.done) break;
396
+
397
+ const data = result.value;
398
+
399
+ let frames: AudioFrame[];
400
+ if (data === SpeechStream.FLUSH_SENTINEL) {
401
+ frames = audioStream.flush();
402
+ } else if (data.sampleRate === this.#opts.sampleRate && data.channels === 1) {
403
+ // AssemblyAI expects mono PCM. The base SpeechStream only resamples
404
+ // sample rate, so reject any frame that is not already downmixed.
405
+ frames = audioStream.write(data.data.buffer as ArrayBuffer);
406
+ } else {
407
+ throw new Error('sample rate or channel count of frame does not match');
408
+ }
409
+
410
+ for (const frame of frames) {
411
+ this.#speechDurationInS += frame.samplesPerChannel / frame.sampleRate;
412
+ ws.send(frame.data.buffer);
413
+ }
414
+ }
415
+ } finally {
416
+ closing = true;
417
+ try {
418
+ ws.send(SpeechStream.CLOSE_MSG);
419
+ } catch {
420
+ // ignore — socket may already be closing
421
+ }
422
+ wsMonitor.cancel();
423
+ }
424
+ };
425
+
426
+ let messageHandler: ((msg: RawData, isBinary: boolean) => void) | null = null;
427
+ const listenTask = Task.from(async (controller) => {
428
+ const listenMessage = new Promise<void>((resolve, reject) => {
429
+ messageHandler = (msg, isBinary) => {
430
+ if (isBinary) {
431
+ this.#logger.error('unexpected binary message from AssemblyAI');
432
+ return;
433
+ }
434
+ try {
435
+ const json = JSON.parse(msg.toString()) as StreamEventMessage;
436
+ this.#processStreamEvent(json);
437
+ if (this.closed || closing) {
438
+ resolve();
439
+ }
440
+ } catch (err) {
441
+ this.#logger.error(`AssemblyAI: error processing message: ${msg}`);
442
+ reject(err);
443
+ }
444
+ };
445
+ ws.on('message', messageHandler);
446
+ });
447
+
448
+ await Promise.race([listenMessage, waitForAbort(controller.signal)]);
449
+ });
450
+
451
+ const configTask = Task.from(async (controller) => {
452
+ // Drain any messages queued while the socket was reconnecting.
453
+ while (this.#pendingConfigMessages.length > 0) {
454
+ const msg = this.#pendingConfigMessages.shift()!;
455
+ ws.send(JSON.stringify(msg));
456
+ }
457
+
458
+ while (!controller.signal.aborted) {
459
+ await Promise.race([this.#configMessagePending.await, waitForAbort(controller.signal)]);
460
+ if (controller.signal.aborted) return;
461
+
462
+ this.#configMessagePending = new Future();
463
+ while (this.#pendingConfigMessages.length > 0) {
464
+ const msg = this.#pendingConfigMessages.shift()!;
465
+ ws.send(JSON.stringify(msg));
466
+ }
467
+ }
468
+ });
469
+
470
+ try {
471
+ await Promise.all([sendTask(), listenTask.result, wsMonitor.result]);
472
+ } finally {
473
+ closing = true;
474
+ sessionController.abort();
475
+ listenTask.cancel();
476
+ configTask.cancel();
477
+ if (messageHandler) ws.off('message', messageHandler);
478
+ try {
479
+ ws.close();
480
+ } catch {
481
+ // ignore
482
+ }
483
+ }
484
+ }
485
+
486
+ #averageConfidence(words: Array<{ confidence?: number }>): number {
487
+ if (words.length === 0) return 0;
488
+ return words.reduce((sum, w) => sum + (w.confidence ?? 0), 0) / words.length;
489
+ }
490
+
491
+ #processStreamEvent(data: StreamEventMessage) {
492
+ const messageType = data.type;
493
+
494
+ if (messageType === 'Begin') {
495
+ this.#sessionId = data.id ?? null;
496
+ this.#expiresAt = data.expires_at ?? null;
497
+ this.#logger.info(
498
+ `AssemblyAI session started id=${this.#sessionId} expires_at=${this.#expiresAt}`,
499
+ );
500
+ return;
501
+ }
502
+
503
+ if (messageType === 'SpeechStarted') {
504
+ this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });
505
+ return;
506
+ }
507
+
508
+ if (messageType === 'Termination') {
509
+ this.#logger.debug(
510
+ `AssemblyAI session terminated audio_duration=${data.audio_duration_seconds}s session_duration=${data.session_duration_seconds}s`,
511
+ );
512
+ return;
513
+ }
514
+
515
+ if (messageType !== 'Turn') {
516
+ return;
517
+ }
518
+
519
+ const words = data.words ?? [];
520
+ const endOfTurn = Boolean(data.end_of_turn);
521
+ const turnIsFormatted = Boolean(data.turn_is_formatted);
522
+ const utterance = data.utterance ?? '';
523
+ const transcript = data.transcript ?? '';
524
+ const language = normalizeLanguage(data.language_code ?? 'en');
525
+
526
+ // Word timestamps are in milliseconds:
527
+ // https://www.assemblyai.com/docs/api-reference/streaming-api/streaming-api#receive.receiveTurn.words
528
+ const timedWords = words.map((word) =>
529
+ createTimedString({
530
+ text: word.text ?? '',
531
+ startTime: (word.start ?? 0) / 1000 + this.startTimeOffset,
532
+ endTime: (word.end ?? 0) / 1000 + this.startTimeOffset,
533
+ confidence: word.confidence ?? 0,
534
+ startTimeOffset: this.startTimeOffset,
535
+ }),
536
+ );
537
+
538
+ let startTime = 0;
539
+ let endTime = 0;
540
+ let confidence = 0;
541
+
542
+ // `words` are cumulative for the turn — emit as an interim transcript.
543
+ if (timedWords.length > 0) {
544
+ const interimText = timedWords.map((w) => w.text).join(' ');
545
+ startTime = timedWords[0]!.startTime ?? 0;
546
+ endTime = timedWords[timedWords.length - 1]!.endTime ?? 0;
547
+ confidence = this.#averageConfidence(timedWords);
548
+
549
+ this.queue.put({
550
+ type: stt.SpeechEventType.INTERIM_TRANSCRIPT,
551
+ alternatives: [
552
+ {
553
+ language,
554
+ text: interimText,
555
+ startTime,
556
+ endTime,
557
+ confidence,
558
+ words: timedWords,
559
+ },
560
+ ],
561
+ });
562
+ }
563
+
564
+ // `utterance` is chunk-based (not cumulative) — emit as a preflight transcript
565
+ // covering only the words since the last preflight.
566
+ if (utterance) {
567
+ if (this.#lastPreflightStartTime === 0) {
568
+ this.#lastPreflightStartTime = startTime;
569
+ }
570
+
571
+ const utteranceWords = timedWords.filter(
572
+ (w) => w.startTime !== undefined && w.startTime >= this.#lastPreflightStartTime,
573
+ );
574
+ const utteranceConfidence = this.#averageConfidence(utteranceWords);
575
+
576
+ this.queue.put({
577
+ type: stt.SpeechEventType.PREFLIGHT_TRANSCRIPT,
578
+ alternatives: [
579
+ {
580
+ language,
581
+ text: utterance,
582
+ startTime: this.#lastPreflightStartTime,
583
+ endTime,
584
+ confidence: utteranceConfidence,
585
+ words: utteranceWords,
586
+ },
587
+ ],
588
+ });
589
+ this.#lastPreflightStartTime = endTime;
590
+ }
591
+
592
+ // End-of-turn: emit FINAL_TRANSCRIPT + END_OF_SPEECH.
593
+ // If the user asked for formatted turns, wait for a formatted final.
594
+ const waitingForFormatted = this.#opts.formatTurns === true && !turnIsFormatted;
595
+ if (endOfTurn && !waitingForFormatted) {
596
+ this.queue.put({
597
+ type: stt.SpeechEventType.FINAL_TRANSCRIPT,
598
+ alternatives: [
599
+ {
600
+ language,
601
+ text: transcript,
602
+ startTime,
603
+ endTime,
604
+ confidence,
605
+ words: timedWords,
606
+ },
607
+ ],
608
+ });
609
+
610
+ this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
611
+ if (this.#speechDurationInS > 0) {
612
+ this.queue.put({
613
+ type: stt.SpeechEventType.RECOGNITION_USAGE,
614
+ // Propagate the AssemblyAI session id as the request id so metrics
615
+ // can be correlated back to a specific connection, mirroring how
616
+ // Deepgram surfaces its `request_id`.
617
+ requestId: this.#sessionId ?? undefined,
618
+ recognitionUsage: {
619
+ audioDuration: this.#speechDurationInS,
620
+ },
621
+ });
622
+ this.#speechDurationInS = 0;
623
+ this.#lastPreflightStartTime = 0;
624
+ }
625
+ }
626
+ }
627
+ }