@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/LICENSE +201 -0
- package/README.md +18 -0
- package/dist/index.cjs +36 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/models.cjs +17 -0
- package/dist/models.cjs.map +1 -0
- package/dist/models.d.cts +4 -0
- package/dist/models.d.ts +4 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +1 -0
- package/dist/models.js.map +1 -0
- package/dist/stt.cjs +472 -0
- package/dist/stt.cjs.map +1 -0
- package/dist/stt.d.cts +86 -0
- package/dist/stt.d.ts +86 -0
- package/dist/stt.d.ts.map +1 -0
- package/dist/stt.js +457 -0
- package/dist/stt.js.map +1 -0
- package/dist/stt.test.cjs +52 -0
- package/dist/stt.test.cjs.map +1 -0
- package/dist/stt.test.d.cts +2 -0
- package/dist/stt.test.d.ts +2 -0
- package/dist/stt.test.d.ts.map +1 -0
- package/dist/stt.test.js +51 -0
- package/dist/stt.test.js.map +1 -0
- package/package.json +53 -0
- package/src/index.ts +19 -0
- package/src/models.ts +18 -0
- package/src/stt.test.ts +62 -0
- package/src/stt.ts +627 -0
package/dist/stt.cjs
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var stt_exports = {};
|
|
20
|
+
__export(stt_exports, {
|
|
21
|
+
STT: () => STT,
|
|
22
|
+
SpeechStream: () => SpeechStream
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(stt_exports);
|
|
25
|
+
var import_agents = require("@livekit/agents");
|
|
26
|
+
var import_ws = require("ws");
|
|
27
|
+
const U3_PRO_MODELS = ["u3-rt-pro", "u3-rt-pro-beta-1", "universal-3-5-pro"];
|
|
28
|
+
function isU3ProModel(model) {
|
|
29
|
+
return U3_PRO_MODELS.includes(model);
|
|
30
|
+
}
|
|
31
|
+
const defaultSTTOptions = {
|
|
32
|
+
apiKey: process.env.ASSEMBLYAI_API_KEY,
|
|
33
|
+
sampleRate: 16e3,
|
|
34
|
+
bufferSizeMs: 50,
|
|
35
|
+
encoding: "pcm_s16le",
|
|
36
|
+
speechModel: "universal-3-5-pro",
|
|
37
|
+
baseUrl: "wss://streaming.assemblyai.com"
|
|
38
|
+
};
|
|
39
|
+
class STT extends import_agents.stt.STT {
|
|
40
|
+
#opts;
|
|
41
|
+
#streams = /* @__PURE__ */ new Set();
|
|
42
|
+
label = "assemblyai.STT";
|
|
43
|
+
get model() {
|
|
44
|
+
return this.#opts.speechModel;
|
|
45
|
+
}
|
|
46
|
+
get provider() {
|
|
47
|
+
return "AssemblyAI";
|
|
48
|
+
}
|
|
49
|
+
constructor(opts = {}) {
|
|
50
|
+
super({
|
|
51
|
+
streaming: true,
|
|
52
|
+
interimResults: true,
|
|
53
|
+
alignedTranscript: "word"
|
|
54
|
+
});
|
|
55
|
+
if (opts.speechModel === "u3-pro") {
|
|
56
|
+
(0, import_agents.log)().warn("'u3-pro' is deprecated, use 'u3-rt-pro' instead.");
|
|
57
|
+
opts.speechModel = "u3-rt-pro";
|
|
58
|
+
}
|
|
59
|
+
const speechModel = opts.speechModel ?? defaultSTTOptions.speechModel;
|
|
60
|
+
if (!isU3ProModel(speechModel)) {
|
|
61
|
+
for (const param of [
|
|
62
|
+
"prompt",
|
|
63
|
+
"agentContext",
|
|
64
|
+
"previousContextNTurns",
|
|
65
|
+
"voiceFocus",
|
|
66
|
+
"voiceFocusThreshold",
|
|
67
|
+
"mode"
|
|
68
|
+
]) {
|
|
69
|
+
if (opts[param] !== void 0) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`The '${param}' parameter is only supported with the ${U3_PRO_MODELS.join(", ")} models.`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
|
|
77
|
+
if (!apiKey) {
|
|
78
|
+
throw new Error(
|
|
79
|
+
"AssemblyAI API key is required. Pass one in via the `apiKey` parameter, or set it as the `ASSEMBLYAI_API_KEY` environment variable"
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
const minTurnSilence = opts.minTurnSilence ?? 100;
|
|
83
|
+
this.#opts = {
|
|
84
|
+
...defaultSTTOptions,
|
|
85
|
+
...opts,
|
|
86
|
+
apiKey,
|
|
87
|
+
minTurnSilence
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
91
|
+
async _recognize(_) {
|
|
92
|
+
throw new Error("Non-streaming recognize is not supported on AssemblyAI STT");
|
|
93
|
+
}
|
|
94
|
+
updateOptions(opts) {
|
|
95
|
+
this.#opts = { ...this.#opts, ...opts };
|
|
96
|
+
for (const ref of this.#streams) {
|
|
97
|
+
const stream = ref.deref();
|
|
98
|
+
if (stream) {
|
|
99
|
+
stream.updateOptions(opts);
|
|
100
|
+
} else {
|
|
101
|
+
this.#streams.delete(ref);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
stream(options) {
|
|
106
|
+
const stream = new SpeechStream(this, this.#opts, options == null ? void 0 : options.connOptions);
|
|
107
|
+
this.#streams.add(new WeakRef(stream));
|
|
108
|
+
return stream;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
class SpeechStream extends import_agents.stt.SpeechStream {
|
|
112
|
+
static CLOSE_MSG = JSON.stringify({ type: "Terminate" });
|
|
113
|
+
#opts;
|
|
114
|
+
#logger = (0, import_agents.log)();
|
|
115
|
+
#speechDurationInS = 0;
|
|
116
|
+
#lastPreflightStartTime = 0;
|
|
117
|
+
#pendingConfigMessages = [];
|
|
118
|
+
#configMessagePending = new import_agents.Future();
|
|
119
|
+
#sessionId = null;
|
|
120
|
+
#expiresAt = null;
|
|
121
|
+
label = "assemblyai.SpeechStream";
|
|
122
|
+
constructor(stt2, opts, connOptions) {
|
|
123
|
+
super(stt2, opts.sampleRate, connOptions);
|
|
124
|
+
this.#opts = opts;
|
|
125
|
+
this.closed = false;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* The AssemblyAI session ID. Set when the WebSocket connection is established
|
|
129
|
+
* (before any speech events). Null until the connection completes.
|
|
130
|
+
* Share this with the AssemblyAI team when reporting issues.
|
|
131
|
+
*/
|
|
132
|
+
get sessionId() {
|
|
133
|
+
return this.#sessionId;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Unix timestamp when the AssemblyAI session expires. Set alongside
|
|
137
|
+
* {@link sessionId} when the WebSocket connection is established.
|
|
138
|
+
*/
|
|
139
|
+
get expiresAt() {
|
|
140
|
+
return this.#expiresAt;
|
|
141
|
+
}
|
|
142
|
+
updateOptions(opts) {
|
|
143
|
+
this.#opts = { ...this.#opts, ...opts };
|
|
144
|
+
const configMsg = { type: "UpdateConfiguration" };
|
|
145
|
+
if (opts.prompt !== void 0) configMsg.prompt = opts.prompt;
|
|
146
|
+
if (opts.agentContext !== void 0) configMsg.agent_context = opts.agentContext;
|
|
147
|
+
if (opts.keytermsPrompt !== void 0) configMsg.keyterms_prompt = opts.keytermsPrompt;
|
|
148
|
+
if (opts.maxTurnSilence !== void 0) configMsg.max_turn_silence = opts.maxTurnSilence;
|
|
149
|
+
if (opts.minTurnSilence !== void 0) configMsg.min_turn_silence = opts.minTurnSilence;
|
|
150
|
+
if (opts.endOfTurnConfidenceThreshold !== void 0) {
|
|
151
|
+
configMsg.end_of_turn_confidence_threshold = opts.endOfTurnConfidenceThreshold;
|
|
152
|
+
}
|
|
153
|
+
if (opts.vadThreshold !== void 0) configMsg.vad_threshold = opts.vadThreshold;
|
|
154
|
+
if (Object.keys(configMsg).length > 1) {
|
|
155
|
+
this.#pendingConfigMessages.push(configMsg);
|
|
156
|
+
if (!this.#configMessagePending.done) this.#configMessagePending.resolve();
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Force-finalize the current turn immediately.
|
|
161
|
+
*/
|
|
162
|
+
forceEndpoint() {
|
|
163
|
+
this.#pendingConfigMessages.push({ type: "ForceEndpoint" });
|
|
164
|
+
if (!this.#configMessagePending.done) this.#configMessagePending.resolve();
|
|
165
|
+
}
|
|
166
|
+
// Deepgram-style reconnect loop around a single websocket lifetime.
|
|
167
|
+
async run() {
|
|
168
|
+
const maxRetry = 32;
|
|
169
|
+
let retries = 0;
|
|
170
|
+
while (!this.input.closed && !this.closed) {
|
|
171
|
+
try {
|
|
172
|
+
const ws = await this.#connectWS();
|
|
173
|
+
await this.#runWS(ws);
|
|
174
|
+
retries = 0;
|
|
175
|
+
} catch (e) {
|
|
176
|
+
if (!this.closed && !this.input.closed) {
|
|
177
|
+
if (retries >= maxRetry) {
|
|
178
|
+
throw new Error(`failed to connect to AssemblyAI after ${retries} attempts: ${e}`);
|
|
179
|
+
}
|
|
180
|
+
const retryDelaySeconds = Math.min(retries * 5, 10);
|
|
181
|
+
retries++;
|
|
182
|
+
this.#logger.warn(
|
|
183
|
+
`failed to connect to AssemblyAI, retrying in ${retryDelaySeconds} seconds: ${e} (${retries}/${maxRetry})`
|
|
184
|
+
);
|
|
185
|
+
await (0, import_agents.delay)(retryDelaySeconds * 1e3);
|
|
186
|
+
} else {
|
|
187
|
+
this.#logger.warn(
|
|
188
|
+
`AssemblyAI disconnected, connection is closed: ${e} (inputClosed: ${this.input.closed}, isClosed: ${this.closed})`
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
this.closed = true;
|
|
194
|
+
}
|
|
195
|
+
async #connectWS() {
|
|
196
|
+
let minSilence = this.#opts.minTurnSilence;
|
|
197
|
+
let maxSilence = this.#opts.maxTurnSilence;
|
|
198
|
+
if (isU3ProModel(this.#opts.speechModel)) {
|
|
199
|
+
if (minSilence === void 0) minSilence = 100;
|
|
200
|
+
if (maxSilence === void 0) maxSilence = minSilence;
|
|
201
|
+
}
|
|
202
|
+
const defaultLanguageDetection = this.#opts.speechModel.includes("multilingual") || isU3ProModel(this.#opts.speechModel);
|
|
203
|
+
const languageDetection = this.#opts.languageDetection ?? defaultLanguageDetection;
|
|
204
|
+
const liveConfig = {
|
|
205
|
+
sample_rate: this.#opts.sampleRate,
|
|
206
|
+
encoding: this.#opts.encoding,
|
|
207
|
+
speech_model: this.#opts.speechModel,
|
|
208
|
+
format_turns: this.#opts.formatTurns,
|
|
209
|
+
end_of_turn_confidence_threshold: this.#opts.endOfTurnConfidenceThreshold,
|
|
210
|
+
min_turn_silence: minSilence,
|
|
211
|
+
max_turn_silence: maxSilence,
|
|
212
|
+
keyterms_prompt: this.#opts.keytermsPrompt !== void 0 ? JSON.stringify(this.#opts.keytermsPrompt) : void 0,
|
|
213
|
+
language_detection: languageDetection,
|
|
214
|
+
prompt: this.#opts.prompt,
|
|
215
|
+
agent_context: this.#opts.agentContext,
|
|
216
|
+
previous_context_n_turns: this.#opts.previousContextNTurns,
|
|
217
|
+
vad_threshold: this.#opts.vadThreshold,
|
|
218
|
+
speaker_labels: this.#opts.speakerLabels,
|
|
219
|
+
max_speakers: this.#opts.maxSpeakers,
|
|
220
|
+
domain: this.#opts.domain,
|
|
221
|
+
voice_focus: this.#opts.voiceFocus,
|
|
222
|
+
voice_focus_threshold: this.#opts.voiceFocusThreshold,
|
|
223
|
+
mode: this.#opts.mode
|
|
224
|
+
};
|
|
225
|
+
const url = new URL(`${this.#opts.baseUrl}/v3/ws`);
|
|
226
|
+
for (const [key, value] of Object.entries(liveConfig)) {
|
|
227
|
+
if (value === void 0 || value === null) continue;
|
|
228
|
+
if (typeof value === "boolean") {
|
|
229
|
+
url.searchParams.append(key, value ? "true" : "false");
|
|
230
|
+
} else {
|
|
231
|
+
url.searchParams.append(key, String(value));
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const ws = new import_ws.WebSocket(url, {
|
|
235
|
+
headers: {
|
|
236
|
+
Authorization: this.#opts.apiKey,
|
|
237
|
+
"Content-Type": "application/json",
|
|
238
|
+
"User-Agent": "AssemblyAI/1.0 (integration=Livekit)"
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
await new Promise((resolve, reject) => {
|
|
242
|
+
ws.on("open", () => resolve());
|
|
243
|
+
ws.on("error", (error) => reject(error));
|
|
244
|
+
ws.on("close", (code) => reject(new Error(`WebSocket returned ${code}`)));
|
|
245
|
+
});
|
|
246
|
+
return ws;
|
|
247
|
+
}
|
|
248
|
+
async #runWS(ws) {
|
|
249
|
+
let closing = false;
|
|
250
|
+
const sessionController = new AbortController();
|
|
251
|
+
const wsMonitor = import_agents.Task.from(async (controller) => {
|
|
252
|
+
const closed = new Promise((_, reject) => {
|
|
253
|
+
ws.once("close", (code, reason) => {
|
|
254
|
+
if (!closing) {
|
|
255
|
+
this.#logger.error(`WebSocket closed with code ${code}: ${reason}`);
|
|
256
|
+
reject(new Error("WebSocket closed"));
|
|
257
|
+
}
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
await Promise.race([closed, (0, import_agents.waitForAbort)(controller.signal)]);
|
|
261
|
+
});
|
|
262
|
+
const sendTask = async () => {
|
|
263
|
+
const samplesPerBuffer = Math.floor(this.#opts.sampleRate * this.#opts.bufferSizeMs / 1e3);
|
|
264
|
+
const audioStream = new import_agents.AudioByteStream(this.#opts.sampleRate, 1, samplesPerBuffer);
|
|
265
|
+
const abortPromise = (0, import_agents.waitForAbort)(this.abortSignal);
|
|
266
|
+
const sessionAbort = (0, import_agents.waitForAbort)(sessionController.signal);
|
|
267
|
+
try {
|
|
268
|
+
while (!this.closed) {
|
|
269
|
+
const result = await Promise.race([this.input.next(), abortPromise, sessionAbort]);
|
|
270
|
+
if (result === void 0) return;
|
|
271
|
+
if (result.done) break;
|
|
272
|
+
const data = result.value;
|
|
273
|
+
let frames;
|
|
274
|
+
if (data === SpeechStream.FLUSH_SENTINEL) {
|
|
275
|
+
frames = audioStream.flush();
|
|
276
|
+
} else if (data.sampleRate === this.#opts.sampleRate && data.channels === 1) {
|
|
277
|
+
frames = audioStream.write(data.data.buffer);
|
|
278
|
+
} else {
|
|
279
|
+
throw new Error("sample rate or channel count of frame does not match");
|
|
280
|
+
}
|
|
281
|
+
for (const frame of frames) {
|
|
282
|
+
this.#speechDurationInS += frame.samplesPerChannel / frame.sampleRate;
|
|
283
|
+
ws.send(frame.data.buffer);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
} finally {
|
|
287
|
+
closing = true;
|
|
288
|
+
try {
|
|
289
|
+
ws.send(SpeechStream.CLOSE_MSG);
|
|
290
|
+
} catch {
|
|
291
|
+
}
|
|
292
|
+
wsMonitor.cancel();
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
let messageHandler = null;
|
|
296
|
+
const listenTask = import_agents.Task.from(async (controller) => {
|
|
297
|
+
const listenMessage = new Promise((resolve, reject) => {
|
|
298
|
+
messageHandler = (msg, isBinary) => {
|
|
299
|
+
if (isBinary) {
|
|
300
|
+
this.#logger.error("unexpected binary message from AssemblyAI");
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
try {
|
|
304
|
+
const json = JSON.parse(msg.toString());
|
|
305
|
+
this.#processStreamEvent(json);
|
|
306
|
+
if (this.closed || closing) {
|
|
307
|
+
resolve();
|
|
308
|
+
}
|
|
309
|
+
} catch (err) {
|
|
310
|
+
this.#logger.error(`AssemblyAI: error processing message: ${msg}`);
|
|
311
|
+
reject(err);
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
ws.on("message", messageHandler);
|
|
315
|
+
});
|
|
316
|
+
await Promise.race([listenMessage, (0, import_agents.waitForAbort)(controller.signal)]);
|
|
317
|
+
});
|
|
318
|
+
const configTask = import_agents.Task.from(async (controller) => {
|
|
319
|
+
while (this.#pendingConfigMessages.length > 0) {
|
|
320
|
+
const msg = this.#pendingConfigMessages.shift();
|
|
321
|
+
ws.send(JSON.stringify(msg));
|
|
322
|
+
}
|
|
323
|
+
while (!controller.signal.aborted) {
|
|
324
|
+
await Promise.race([this.#configMessagePending.await, (0, import_agents.waitForAbort)(controller.signal)]);
|
|
325
|
+
if (controller.signal.aborted) return;
|
|
326
|
+
this.#configMessagePending = new import_agents.Future();
|
|
327
|
+
while (this.#pendingConfigMessages.length > 0) {
|
|
328
|
+
const msg = this.#pendingConfigMessages.shift();
|
|
329
|
+
ws.send(JSON.stringify(msg));
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
try {
|
|
334
|
+
await Promise.all([sendTask(), listenTask.result, wsMonitor.result]);
|
|
335
|
+
} finally {
|
|
336
|
+
closing = true;
|
|
337
|
+
sessionController.abort();
|
|
338
|
+
listenTask.cancel();
|
|
339
|
+
configTask.cancel();
|
|
340
|
+
if (messageHandler) ws.off("message", messageHandler);
|
|
341
|
+
try {
|
|
342
|
+
ws.close();
|
|
343
|
+
} catch {
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
#averageConfidence(words) {
|
|
348
|
+
if (words.length === 0) return 0;
|
|
349
|
+
return words.reduce((sum, w) => sum + (w.confidence ?? 0), 0) / words.length;
|
|
350
|
+
}
|
|
351
|
+
#processStreamEvent(data) {
|
|
352
|
+
const messageType = data.type;
|
|
353
|
+
if (messageType === "Begin") {
|
|
354
|
+
this.#sessionId = data.id ?? null;
|
|
355
|
+
this.#expiresAt = data.expires_at ?? null;
|
|
356
|
+
this.#logger.info(
|
|
357
|
+
`AssemblyAI session started id=${this.#sessionId} expires_at=${this.#expiresAt}`
|
|
358
|
+
);
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (messageType === "SpeechStarted") {
|
|
362
|
+
this.queue.put({ type: import_agents.stt.SpeechEventType.START_OF_SPEECH });
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
if (messageType === "Termination") {
|
|
366
|
+
this.#logger.debug(
|
|
367
|
+
`AssemblyAI session terminated audio_duration=${data.audio_duration_seconds}s session_duration=${data.session_duration_seconds}s`
|
|
368
|
+
);
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
if (messageType !== "Turn") {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const words = data.words ?? [];
|
|
375
|
+
const endOfTurn = Boolean(data.end_of_turn);
|
|
376
|
+
const turnIsFormatted = Boolean(data.turn_is_formatted);
|
|
377
|
+
const utterance = data.utterance ?? "";
|
|
378
|
+
const transcript = data.transcript ?? "";
|
|
379
|
+
const language = (0, import_agents.normalizeLanguage)(data.language_code ?? "en");
|
|
380
|
+
const timedWords = words.map(
|
|
381
|
+
(word) => (0, import_agents.createTimedString)({
|
|
382
|
+
text: word.text ?? "",
|
|
383
|
+
startTime: (word.start ?? 0) / 1e3 + this.startTimeOffset,
|
|
384
|
+
endTime: (word.end ?? 0) / 1e3 + this.startTimeOffset,
|
|
385
|
+
confidence: word.confidence ?? 0,
|
|
386
|
+
startTimeOffset: this.startTimeOffset
|
|
387
|
+
})
|
|
388
|
+
);
|
|
389
|
+
let startTime = 0;
|
|
390
|
+
let endTime = 0;
|
|
391
|
+
let confidence = 0;
|
|
392
|
+
if (timedWords.length > 0) {
|
|
393
|
+
const interimText = timedWords.map((w) => w.text).join(" ");
|
|
394
|
+
startTime = timedWords[0].startTime ?? 0;
|
|
395
|
+
endTime = timedWords[timedWords.length - 1].endTime ?? 0;
|
|
396
|
+
confidence = this.#averageConfidence(timedWords);
|
|
397
|
+
this.queue.put({
|
|
398
|
+
type: import_agents.stt.SpeechEventType.INTERIM_TRANSCRIPT,
|
|
399
|
+
alternatives: [
|
|
400
|
+
{
|
|
401
|
+
language,
|
|
402
|
+
text: interimText,
|
|
403
|
+
startTime,
|
|
404
|
+
endTime,
|
|
405
|
+
confidence,
|
|
406
|
+
words: timedWords
|
|
407
|
+
}
|
|
408
|
+
]
|
|
409
|
+
});
|
|
410
|
+
}
|
|
411
|
+
if (utterance) {
|
|
412
|
+
if (this.#lastPreflightStartTime === 0) {
|
|
413
|
+
this.#lastPreflightStartTime = startTime;
|
|
414
|
+
}
|
|
415
|
+
const utteranceWords = timedWords.filter(
|
|
416
|
+
(w) => w.startTime !== void 0 && w.startTime >= this.#lastPreflightStartTime
|
|
417
|
+
);
|
|
418
|
+
const utteranceConfidence = this.#averageConfidence(utteranceWords);
|
|
419
|
+
this.queue.put({
|
|
420
|
+
type: import_agents.stt.SpeechEventType.PREFLIGHT_TRANSCRIPT,
|
|
421
|
+
alternatives: [
|
|
422
|
+
{
|
|
423
|
+
language,
|
|
424
|
+
text: utterance,
|
|
425
|
+
startTime: this.#lastPreflightStartTime,
|
|
426
|
+
endTime,
|
|
427
|
+
confidence: utteranceConfidence,
|
|
428
|
+
words: utteranceWords
|
|
429
|
+
}
|
|
430
|
+
]
|
|
431
|
+
});
|
|
432
|
+
this.#lastPreflightStartTime = endTime;
|
|
433
|
+
}
|
|
434
|
+
const waitingForFormatted = this.#opts.formatTurns === true && !turnIsFormatted;
|
|
435
|
+
if (endOfTurn && !waitingForFormatted) {
|
|
436
|
+
this.queue.put({
|
|
437
|
+
type: import_agents.stt.SpeechEventType.FINAL_TRANSCRIPT,
|
|
438
|
+
alternatives: [
|
|
439
|
+
{
|
|
440
|
+
language,
|
|
441
|
+
text: transcript,
|
|
442
|
+
startTime,
|
|
443
|
+
endTime,
|
|
444
|
+
confidence,
|
|
445
|
+
words: timedWords
|
|
446
|
+
}
|
|
447
|
+
]
|
|
448
|
+
});
|
|
449
|
+
this.queue.put({ type: import_agents.stt.SpeechEventType.END_OF_SPEECH });
|
|
450
|
+
if (this.#speechDurationInS > 0) {
|
|
451
|
+
this.queue.put({
|
|
452
|
+
type: import_agents.stt.SpeechEventType.RECOGNITION_USAGE,
|
|
453
|
+
// Propagate the AssemblyAI session id as the request id so metrics
|
|
454
|
+
// can be correlated back to a specific connection, mirroring how
|
|
455
|
+
// Deepgram surfaces its `request_id`.
|
|
456
|
+
requestId: this.#sessionId ?? void 0,
|
|
457
|
+
recognitionUsage: {
|
|
458
|
+
audioDuration: this.#speechDurationInS
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
this.#speechDurationInS = 0;
|
|
462
|
+
this.#lastPreflightStartTime = 0;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
468
|
+
0 && (module.exports = {
|
|
469
|
+
STT,
|
|
470
|
+
SpeechStream
|
|
471
|
+
});
|
|
472
|
+
//# sourceMappingURL=stt.cjs.map
|
package/dist/stt.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/stt.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\n//\nimport {\n type APIConnectOptions,\n type AudioBuffer,\n AudioByteStream,\n Future,\n Task,\n createTimedString,\n delay,\n log,\n normalizeLanguage,\n stt,\n waitForAbort,\n} from '@livekit/agents';\nimport type { AudioFrame } from '@livekit/rtc-node';\nimport type { RawData } from 'ws';\nimport { WebSocket } from 'ws';\nimport type { STTEncoding, STTModels, VoiceFocus } from './models.js';\n\nconst U3_PRO_MODELS = ['u3-rt-pro', 'u3-rt-pro-beta-1', 'universal-3-5-pro'] as const;\n\nfunction isU3ProModel(model: STTModels): boolean {\n return U3_PRO_MODELS.includes(model as (typeof U3_PRO_MODELS)[number]);\n}\n\n// AssemblyAI Universal-Streaming (v3) message envelope. All fields are optional\n// since we narrow on `type` before reading anything else.\ninterface StreamEventMessage {\n type?: 'Begin' | 'SpeechStarted' | 'Turn' | 'Termination' | string;\n // Begin\n id?: string;\n expires_at?: number;\n // Turn\n transcript?: string;\n utterance?: string;\n end_of_turn?: boolean;\n end_of_turn_confidence?: number;\n turn_is_formatted?: boolean;\n language_code?: string;\n speaker_label?: string;\n words?: Array<{\n text?: string;\n start?: number;\n end?: number;\n confidence?: number;\n speaker?: string;\n }>;\n // Termination\n audio_duration_seconds?: number;\n session_duration_seconds?: number;\n}\n\nexport interface STTOptions {\n apiKey?: string;\n sampleRate: number;\n /**\n * How large each chunk of audio is before being sent to AssemblyAI, in\n * milliseconds. Corresponds to Python's `buffer_size_seconds` (seconds there,\n * ms here per this repo's time-unit convention).\n */\n bufferSizeMs: number;\n encoding: STTEncoding;\n speechModel: STTModels;\n languageDetection?: boolean;\n endOfTurnConfidenceThreshold?: number;\n /** Minimum silence (ms) before a confident end-of-turn is finalized. */\n minTurnSilence?: number;\n /** Maximum silence (ms) before end-of-turn is forced regardless of confidence. */\n maxTurnSilence?: number;\n formatTurns?: boolean;\n keytermsPrompt?: string[];\n /** Only supported with the `u3-rt-pro` model family. */\n prompt?: string;\n /** Only supported with the `u3-rt-pro` model family. */\n agentContext?: string;\n /** Only supported with the `u3-rt-pro` model family. Set at connection time only. */\n previousContextNTurns?: number;\n vadThreshold?: number;\n /**\n * Enable speaker diarization. Note: AssemblyAI will return per-word speaker\n * labels, but the JS framework's `stt.SpeechData` type does not yet expose\n * a `speakerId` field (unlike the Python framework), so the labels are not\n * currently surfaced on emitted events. Setting this to `true` still has\n * effect server-side. Once the base `SpeechData` interface gains speaker\n * support, `#processStreamEvent` should forward `data.words[].speaker` too.\n */\n speakerLabels?: boolean;\n maxSpeakers?: number;\n domain?: string;\n /** Isolate the primary voice and suppress background noise. Connect-time only. */\n voiceFocus?: VoiceFocus;\n /** Background audio suppression aggressiveness, from 0.0 to 1.0. Connect-time only. */\n voiceFocusThreshold?: number;\n /**\n * Accuracy/latency preset for u3-rt-pro: `min_latency`, `balanced`, or `max_accuracy`.\n * Explicit silence, partials, or VAD options still take precedence over mode defaults.\n */\n mode?: 'min_latency' | 'balanced' | 'max_accuracy';\n baseUrl: string;\n}\n\nconst defaultSTTOptions: STTOptions = {\n apiKey: process.env.ASSEMBLYAI_API_KEY,\n sampleRate: 16000,\n bufferSizeMs: 50,\n encoding: 'pcm_s16le',\n speechModel: 'universal-3-5-pro',\n baseUrl: 'wss://streaming.assemblyai.com',\n};\n\nexport class STT extends stt.STT {\n #opts: STTOptions;\n #streams = new Set<WeakRef<SpeechStream>>();\n label = 'assemblyai.STT';\n\n get model(): string {\n return this.#opts.speechModel;\n }\n\n get provider(): string {\n return 'AssemblyAI';\n }\n\n constructor(opts: Partial<STTOptions> = {}) {\n super({\n streaming: true,\n interimResults: true,\n alignedTranscript: 'word',\n });\n\n if (opts.speechModel === 'u3-pro') {\n log().warn(\"'u3-pro' is deprecated, use 'u3-rt-pro' instead.\");\n opts.speechModel = 'u3-rt-pro';\n }\n\n const speechModel = opts.speechModel ?? defaultSTTOptions.speechModel;\n if (!isU3ProModel(speechModel)) {\n for (const param of [\n 'prompt',\n 'agentContext',\n 'previousContextNTurns',\n 'voiceFocus',\n 'voiceFocusThreshold',\n 'mode',\n ] as const) {\n if (opts[param] !== undefined) {\n throw new Error(\n `The '${param}' parameter is only supported with the ${U3_PRO_MODELS.join(', ')} models.`,\n );\n }\n }\n }\n\n const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;\n if (!apiKey) {\n throw new Error(\n 'AssemblyAI API key is required. Pass one in via the `apiKey` parameter, or set it as the `ASSEMBLYAI_API_KEY` environment variable',\n );\n }\n\n // Minimize latency; matches LK's end-of-turn detector well.\n const minTurnSilence = opts.minTurnSilence ?? 100;\n\n this.#opts = {\n ...defaultSTTOptions,\n ...opts,\n apiKey,\n minTurnSilence,\n };\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _recognize(_: AudioBuffer): Promise<stt.SpeechEvent> {\n throw new Error('Non-streaming recognize is not supported on AssemblyAI STT');\n }\n\n updateOptions(opts: Partial<STTOptions>) {\n this.#opts = { ...this.#opts, ...opts };\n for (const ref of this.#streams) {\n const stream = ref.deref();\n if (stream) {\n stream.updateOptions(opts);\n } else {\n this.#streams.delete(ref);\n }\n }\n }\n\n stream(options?: { connOptions?: APIConnectOptions }): SpeechStream {\n const stream = new SpeechStream(this, this.#opts, options?.connOptions);\n this.#streams.add(new WeakRef(stream));\n return stream;\n }\n}\n\nexport class SpeechStream extends stt.SpeechStream {\n static readonly CLOSE_MSG = JSON.stringify({ type: 'Terminate' });\n\n #opts: STTOptions;\n #logger = log();\n #speechDurationInS = 0;\n #lastPreflightStartTime = 0;\n #pendingConfigMessages: Record<string, unknown>[] = [];\n #configMessagePending = new Future();\n #sessionId: string | null = null;\n #expiresAt: number | null = null;\n label = 'assemblyai.SpeechStream';\n\n constructor(stt: STT, opts: STTOptions, connOptions?: APIConnectOptions) {\n super(stt, opts.sampleRate, connOptions);\n this.#opts = opts;\n this.closed = false;\n }\n\n /**\n * The AssemblyAI session ID. Set when the WebSocket connection is established\n * (before any speech events). Null until the connection completes.\n * Share this with the AssemblyAI team when reporting issues.\n */\n get sessionId(): string | null {\n return this.#sessionId;\n }\n\n /**\n * Unix timestamp when the AssemblyAI session expires. Set alongside\n * {@link sessionId} when the WebSocket connection is established.\n */\n get expiresAt(): number | null {\n return this.#expiresAt;\n }\n\n updateOptions(opts: Partial<STTOptions>) {\n this.#opts = { ...this.#opts, ...opts };\n\n const configMsg: Record<string, unknown> = { type: 'UpdateConfiguration' };\n if (opts.prompt !== undefined) configMsg.prompt = opts.prompt;\n if (opts.agentContext !== undefined) configMsg.agent_context = opts.agentContext;\n if (opts.keytermsPrompt !== undefined) configMsg.keyterms_prompt = opts.keytermsPrompt;\n if (opts.maxTurnSilence !== undefined) configMsg.max_turn_silence = opts.maxTurnSilence;\n if (opts.minTurnSilence !== undefined) configMsg.min_turn_silence = opts.minTurnSilence;\n if (opts.endOfTurnConfidenceThreshold !== undefined) {\n configMsg.end_of_turn_confidence_threshold = opts.endOfTurnConfidenceThreshold;\n }\n if (opts.vadThreshold !== undefined) configMsg.vad_threshold = opts.vadThreshold;\n\n // Only send if any actual fields (besides `type`) were specified.\n if (Object.keys(configMsg).length > 1) {\n this.#pendingConfigMessages.push(configMsg);\n if (!this.#configMessagePending.done) this.#configMessagePending.resolve();\n }\n }\n\n /**\n * Force-finalize the current turn immediately.\n */\n forceEndpoint() {\n this.#pendingConfigMessages.push({ type: 'ForceEndpoint' });\n if (!this.#configMessagePending.done) this.#configMessagePending.resolve();\n }\n\n // Deepgram-style reconnect loop around a single websocket lifetime.\n protected async run() {\n const maxRetry = 32;\n let retries = 0;\n\n while (!this.input.closed && !this.closed) {\n try {\n const ws = await this.#connectWS();\n await this.#runWS(ws);\n retries = 0;\n } catch (e) {\n if (!this.closed && !this.input.closed) {\n if (retries >= maxRetry) {\n throw new Error(`failed to connect to AssemblyAI after ${retries} attempts: ${e}`);\n }\n\n const retryDelaySeconds = Math.min(retries * 5, 10);\n retries++;\n\n this.#logger.warn(\n `failed to connect to AssemblyAI, retrying in ${retryDelaySeconds} seconds: ${e} (${retries}/${maxRetry})`,\n );\n await delay(retryDelaySeconds * 1000);\n } else {\n this.#logger.warn(\n `AssemblyAI disconnected, connection is closed: ${e} (inputClosed: ${this.input.closed}, isClosed: ${this.closed})`,\n );\n }\n }\n }\n\n this.closed = true;\n }\n\n async #connectWS(): Promise<WebSocket> {\n // u3-rt-pro family models default both min and max silence to 100ms when unset.\n let minSilence = this.#opts.minTurnSilence;\n let maxSilence = this.#opts.maxTurnSilence;\n if (isU3ProModel(this.#opts.speechModel)) {\n if (minSilence === undefined) minSilence = 100;\n if (maxSilence === undefined) maxSilence = minSilence;\n }\n\n // Default language_detection to true for multilingual / u3-rt-pro-family models, false otherwise.\n const defaultLanguageDetection =\n this.#opts.speechModel.includes('multilingual') || isU3ProModel(this.#opts.speechModel);\n const languageDetection = this.#opts.languageDetection ?? defaultLanguageDetection;\n\n const liveConfig: Record<string, unknown> = {\n sample_rate: this.#opts.sampleRate,\n encoding: this.#opts.encoding,\n speech_model: this.#opts.speechModel,\n format_turns: this.#opts.formatTurns,\n end_of_turn_confidence_threshold: this.#opts.endOfTurnConfidenceThreshold,\n min_turn_silence: minSilence,\n max_turn_silence: maxSilence,\n keyterms_prompt:\n this.#opts.keytermsPrompt !== undefined\n ? JSON.stringify(this.#opts.keytermsPrompt)\n : undefined,\n language_detection: languageDetection,\n prompt: this.#opts.prompt,\n agent_context: this.#opts.agentContext,\n previous_context_n_turns: this.#opts.previousContextNTurns,\n vad_threshold: this.#opts.vadThreshold,\n speaker_labels: this.#opts.speakerLabels,\n max_speakers: this.#opts.maxSpeakers,\n domain: this.#opts.domain,\n voice_focus: this.#opts.voiceFocus,\n voice_focus_threshold: this.#opts.voiceFocusThreshold,\n mode: this.#opts.mode,\n };\n\n const url = new URL(`${this.#opts.baseUrl}/v3/ws`);\n // Python serializes booleans as the strings \"true\"/\"false\", so we mirror that.\n for (const [key, value] of Object.entries(liveConfig)) {\n if (value === undefined || value === null) continue;\n if (typeof value === 'boolean') {\n url.searchParams.append(key, value ? 'true' : 'false');\n } else {\n url.searchParams.append(key, String(value));\n }\n }\n\n const ws = new WebSocket(url, {\n headers: {\n Authorization: this.#opts.apiKey!,\n 'Content-Type': 'application/json',\n 'User-Agent': 'AssemblyAI/1.0 (integration=Livekit)',\n },\n });\n\n await new Promise<void>((resolve, reject) => {\n ws.on('open', () => resolve());\n ws.on('error', (error) => reject(error));\n ws.on('close', (code) => reject(new Error(`WebSocket returned ${code}`)));\n });\n\n return ws;\n }\n\n async #runWS(ws: WebSocket) {\n let closing = false;\n const sessionController = new AbortController();\n\n // gets cancelled also when sendTask is complete\n const wsMonitor = Task.from(async (controller) => {\n const closed = new Promise<void>((_, reject) => {\n ws.once('close', (code, reason) => {\n if (!closing) {\n this.#logger.error(`WebSocket closed with code ${code}: ${reason}`);\n reject(new Error('WebSocket closed'));\n }\n });\n });\n\n await Promise.race([closed, waitForAbort(controller.signal)]);\n });\n\n const sendTask = async () => {\n const samplesPerBuffer = Math.floor((this.#opts.sampleRate * this.#opts.bufferSizeMs) / 1000);\n const audioStream = new AudioByteStream(this.#opts.sampleRate, 1, samplesPerBuffer);\n\n const abortPromise = waitForAbort(this.abortSignal);\n const sessionAbort = waitForAbort(sessionController.signal);\n\n try {\n while (!this.closed) {\n const result = await Promise.race([this.input.next(), abortPromise, sessionAbort]);\n\n if (result === undefined) return; // aborted\n if (result.done) break;\n\n const data = result.value;\n\n let frames: AudioFrame[];\n if (data === SpeechStream.FLUSH_SENTINEL) {\n frames = audioStream.flush();\n } else if (data.sampleRate === this.#opts.sampleRate && data.channels === 1) {\n // AssemblyAI expects mono PCM. The base SpeechStream only resamples\n // sample rate, so reject any frame that is not already downmixed.\n frames = audioStream.write(data.data.buffer as ArrayBuffer);\n } else {\n throw new Error('sample rate or channel count of frame does not match');\n }\n\n for (const frame of frames) {\n this.#speechDurationInS += frame.samplesPerChannel / frame.sampleRate;\n ws.send(frame.data.buffer);\n }\n }\n } finally {\n closing = true;\n try {\n ws.send(SpeechStream.CLOSE_MSG);\n } catch {\n // ignore — socket may already be closing\n }\n wsMonitor.cancel();\n }\n };\n\n let messageHandler: ((msg: RawData, isBinary: boolean) => void) | null = null;\n const listenTask = Task.from(async (controller) => {\n const listenMessage = new Promise<void>((resolve, reject) => {\n messageHandler = (msg, isBinary) => {\n if (isBinary) {\n this.#logger.error('unexpected binary message from AssemblyAI');\n return;\n }\n try {\n const json = JSON.parse(msg.toString()) as StreamEventMessage;\n this.#processStreamEvent(json);\n if (this.closed || closing) {\n resolve();\n }\n } catch (err) {\n this.#logger.error(`AssemblyAI: error processing message: ${msg}`);\n reject(err);\n }\n };\n ws.on('message', messageHandler);\n });\n\n await Promise.race([listenMessage, waitForAbort(controller.signal)]);\n });\n\n const configTask = Task.from(async (controller) => {\n // Drain any messages queued while the socket was reconnecting.\n while (this.#pendingConfigMessages.length > 0) {\n const msg = this.#pendingConfigMessages.shift()!;\n ws.send(JSON.stringify(msg));\n }\n\n while (!controller.signal.aborted) {\n await Promise.race([this.#configMessagePending.await, waitForAbort(controller.signal)]);\n if (controller.signal.aborted) return;\n\n this.#configMessagePending = new Future();\n while (this.#pendingConfigMessages.length > 0) {\n const msg = this.#pendingConfigMessages.shift()!;\n ws.send(JSON.stringify(msg));\n }\n }\n });\n\n try {\n await Promise.all([sendTask(), listenTask.result, wsMonitor.result]);\n } finally {\n closing = true;\n sessionController.abort();\n listenTask.cancel();\n configTask.cancel();\n if (messageHandler) ws.off('message', messageHandler);\n try {\n ws.close();\n } catch {\n // ignore\n }\n }\n }\n\n #averageConfidence(words: Array<{ confidence?: number }>): number {\n if (words.length === 0) return 0;\n return words.reduce((sum, w) => sum + (w.confidence ?? 0), 0) / words.length;\n }\n\n #processStreamEvent(data: StreamEventMessage) {\n const messageType = data.type;\n\n if (messageType === 'Begin') {\n this.#sessionId = data.id ?? null;\n this.#expiresAt = data.expires_at ?? null;\n this.#logger.info(\n `AssemblyAI session started id=${this.#sessionId} expires_at=${this.#expiresAt}`,\n );\n return;\n }\n\n if (messageType === 'SpeechStarted') {\n this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });\n return;\n }\n\n if (messageType === 'Termination') {\n this.#logger.debug(\n `AssemblyAI session terminated audio_duration=${data.audio_duration_seconds}s session_duration=${data.session_duration_seconds}s`,\n );\n return;\n }\n\n if (messageType !== 'Turn') {\n return;\n }\n\n const words = data.words ?? [];\n const endOfTurn = Boolean(data.end_of_turn);\n const turnIsFormatted = Boolean(data.turn_is_formatted);\n const utterance = data.utterance ?? '';\n const transcript = data.transcript ?? '';\n const language = normalizeLanguage(data.language_code ?? 'en');\n\n // Word timestamps are in milliseconds:\n // https://www.assemblyai.com/docs/api-reference/streaming-api/streaming-api#receive.receiveTurn.words\n const timedWords = words.map((word) =>\n createTimedString({\n text: word.text ?? '',\n startTime: (word.start ?? 0) / 1000 + this.startTimeOffset,\n endTime: (word.end ?? 0) / 1000 + this.startTimeOffset,\n confidence: word.confidence ?? 0,\n startTimeOffset: this.startTimeOffset,\n }),\n );\n\n let startTime = 0;\n let endTime = 0;\n let confidence = 0;\n\n // `words` are cumulative for the turn — emit as an interim transcript.\n if (timedWords.length > 0) {\n const interimText = timedWords.map((w) => w.text).join(' ');\n startTime = timedWords[0]!.startTime ?? 0;\n endTime = timedWords[timedWords.length - 1]!.endTime ?? 0;\n confidence = this.#averageConfidence(timedWords);\n\n this.queue.put({\n type: stt.SpeechEventType.INTERIM_TRANSCRIPT,\n alternatives: [\n {\n language,\n text: interimText,\n startTime,\n endTime,\n confidence,\n words: timedWords,\n },\n ],\n });\n }\n\n // `utterance` is chunk-based (not cumulative) — emit as a preflight transcript\n // covering only the words since the last preflight.\n if (utterance) {\n if (this.#lastPreflightStartTime === 0) {\n this.#lastPreflightStartTime = startTime;\n }\n\n const utteranceWords = timedWords.filter(\n (w) => w.startTime !== undefined && w.startTime >= this.#lastPreflightStartTime,\n );\n const utteranceConfidence = this.#averageConfidence(utteranceWords);\n\n this.queue.put({\n type: stt.SpeechEventType.PREFLIGHT_TRANSCRIPT,\n alternatives: [\n {\n language,\n text: utterance,\n startTime: this.#lastPreflightStartTime,\n endTime,\n confidence: utteranceConfidence,\n words: utteranceWords,\n },\n ],\n });\n this.#lastPreflightStartTime = endTime;\n }\n\n // End-of-turn: emit FINAL_TRANSCRIPT + END_OF_SPEECH.\n // If the user asked for formatted turns, wait for a formatted final.\n const waitingForFormatted = this.#opts.formatTurns === true && !turnIsFormatted;\n if (endOfTurn && !waitingForFormatted) {\n this.queue.put({\n type: stt.SpeechEventType.FINAL_TRANSCRIPT,\n alternatives: [\n {\n language,\n text: transcript,\n startTime,\n endTime,\n confidence,\n words: timedWords,\n },\n ],\n });\n\n this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });\n if (this.#speechDurationInS > 0) {\n this.queue.put({\n type: stt.SpeechEventType.RECOGNITION_USAGE,\n // Propagate the AssemblyAI session id as the request id so metrics\n // can be correlated back to a specific connection, mirroring how\n // Deepgram surfaces its `request_id`.\n requestId: this.#sessionId ?? undefined,\n recognitionUsage: {\n audioDuration: this.#speechDurationInS,\n },\n });\n this.#speechDurationInS = 0;\n this.#lastPreflightStartTime = 0;\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,oBAYO;AAGP,gBAA0B;AAG1B,MAAM,gBAAgB,CAAC,aAAa,oBAAoB,mBAAmB;AAE3E,SAAS,aAAa,OAA2B;AAC/C,SAAO,cAAc,SAAS,KAAuC;AACvE;AA8EA,MAAM,oBAAgC;AAAA,EACpC,QAAQ,QAAQ,IAAI;AAAA,EACpB,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,aAAa;AAAA,EACb,SAAS;AACX;AAEO,MAAM,YAAY,kBAAI,IAAI;AAAA,EAC/B;AAAA,EACA,WAAW,oBAAI,IAA2B;AAAA,EAC1C,QAAQ;AAAA,EAER,IAAI,QAAgB;AAClB,WAAO,KAAK,MAAM;AAAA,EACpB;AAAA,EAEA,IAAI,WAAmB;AACrB,WAAO;AAAA,EACT;AAAA,EAEA,YAAY,OAA4B,CAAC,GAAG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,CAAC,MAAM,EAAE,cAAc,UAAa,EAAE,aAAa,KAAK;AAAA,MAC1D;AACA,YAAM,sBAAsB,KAAK,mBAAmB,cAAc;AAElE,WAAK,MAAM,IAAI;AAAA,QACb,MAAM,kBAAI,gBAAgB;AAAA,QAC1B,cAAc;AAAA,UACZ;AAAA,YACE;AAAA,YACA,MAAM;AAAA,YACN,WAAW,KAAK;AAAA,YAChB;AAAA,YACA,YAAY;AAAA,YACZ,OAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF,CAAC;AACD,WAAK,0BAA0B;AAAA,IACjC;AAIA,UAAM,sBAAsB,KAAK,MAAM,gBAAgB,QAAQ,CAAC;AAChE,QAAI,aAAa,CAAC,qBAAqB;AACrC,WAAK,MAAM,IAAI;AAAA,QACb,MAAM,kBAAI,gBAAgB;AAAA,QAC1B,cAAc;AAAA,UACZ;AAAA,YACE;AAAA,YACA,MAAM;AAAA,YACN;AAAA,YACA;AAAA,YACA;AAAA,YACA,OAAO;AAAA,UACT;AAAA,QACF;AAAA,MACF,CAAC;AAED,WAAK,MAAM,IAAI,EAAE,MAAM,kBAAI,gBAAgB,cAAc,CAAC;AAC1D,UAAI,KAAK,qBAAqB,GAAG;AAC/B,aAAK,MAAM,IAAI;AAAA,UACb,MAAM,kBAAI,gBAAgB;AAAA;AAAA;AAAA;AAAA,UAI1B,WAAW,KAAK,cAAc;AAAA,UAC9B,kBAAkB;AAAA,YAChB,eAAe,KAAK;AAAA,UACtB;AAAA,QACF,CAAC;AACD,aAAK,qBAAqB;AAC1B,aAAK,0BAA0B;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AACF;","names":["stt"]}
|
package/dist/stt.d.cts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type APIConnectOptions, type AudioBuffer, stt } from '@livekit/agents';
|
|
2
|
+
import type { STTEncoding, STTModels, VoiceFocus } from './models.js';
|
|
3
|
+
export interface STTOptions {
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
sampleRate: number;
|
|
6
|
+
/**
|
|
7
|
+
* How large each chunk of audio is before being sent to AssemblyAI, in
|
|
8
|
+
* milliseconds. Corresponds to Python's `buffer_size_seconds` (seconds there,
|
|
9
|
+
* ms here per this repo's time-unit convention).
|
|
10
|
+
*/
|
|
11
|
+
bufferSizeMs: number;
|
|
12
|
+
encoding: STTEncoding;
|
|
13
|
+
speechModel: STTModels;
|
|
14
|
+
languageDetection?: boolean;
|
|
15
|
+
endOfTurnConfidenceThreshold?: number;
|
|
16
|
+
/** Minimum silence (ms) before a confident end-of-turn is finalized. */
|
|
17
|
+
minTurnSilence?: number;
|
|
18
|
+
/** Maximum silence (ms) before end-of-turn is forced regardless of confidence. */
|
|
19
|
+
maxTurnSilence?: number;
|
|
20
|
+
formatTurns?: boolean;
|
|
21
|
+
keytermsPrompt?: string[];
|
|
22
|
+
/** Only supported with the `u3-rt-pro` model family. */
|
|
23
|
+
prompt?: string;
|
|
24
|
+
/** Only supported with the `u3-rt-pro` model family. */
|
|
25
|
+
agentContext?: string;
|
|
26
|
+
/** Only supported with the `u3-rt-pro` model family. Set at connection time only. */
|
|
27
|
+
previousContextNTurns?: number;
|
|
28
|
+
vadThreshold?: number;
|
|
29
|
+
/**
|
|
30
|
+
* Enable speaker diarization. Note: AssemblyAI will return per-word speaker
|
|
31
|
+
* labels, but the JS framework's `stt.SpeechData` type does not yet expose
|
|
32
|
+
* a `speakerId` field (unlike the Python framework), so the labels are not
|
|
33
|
+
* currently surfaced on emitted events. Setting this to `true` still has
|
|
34
|
+
* effect server-side. Once the base `SpeechData` interface gains speaker
|
|
35
|
+
* support, `#processStreamEvent` should forward `data.words[].speaker` too.
|
|
36
|
+
*/
|
|
37
|
+
speakerLabels?: boolean;
|
|
38
|
+
maxSpeakers?: number;
|
|
39
|
+
domain?: string;
|
|
40
|
+
/** Isolate the primary voice and suppress background noise. Connect-time only. */
|
|
41
|
+
voiceFocus?: VoiceFocus;
|
|
42
|
+
/** Background audio suppression aggressiveness, from 0.0 to 1.0. Connect-time only. */
|
|
43
|
+
voiceFocusThreshold?: number;
|
|
44
|
+
/**
|
|
45
|
+
* Accuracy/latency preset for u3-rt-pro: `min_latency`, `balanced`, or `max_accuracy`.
|
|
46
|
+
* Explicit silence, partials, or VAD options still take precedence over mode defaults.
|
|
47
|
+
*/
|
|
48
|
+
mode?: 'min_latency' | 'balanced' | 'max_accuracy';
|
|
49
|
+
baseUrl: string;
|
|
50
|
+
}
|
|
51
|
+
export declare class STT extends stt.STT {
|
|
52
|
+
#private;
|
|
53
|
+
label: string;
|
|
54
|
+
get model(): string;
|
|
55
|
+
get provider(): string;
|
|
56
|
+
constructor(opts?: Partial<STTOptions>);
|
|
57
|
+
_recognize(_: AudioBuffer): Promise<stt.SpeechEvent>;
|
|
58
|
+
updateOptions(opts: Partial<STTOptions>): void;
|
|
59
|
+
stream(options?: {
|
|
60
|
+
connOptions?: APIConnectOptions;
|
|
61
|
+
}): SpeechStream;
|
|
62
|
+
}
|
|
63
|
+
export declare class SpeechStream extends stt.SpeechStream {
|
|
64
|
+
#private;
|
|
65
|
+
static readonly CLOSE_MSG: string;
|
|
66
|
+
label: string;
|
|
67
|
+
constructor(stt: STT, opts: STTOptions, connOptions?: APIConnectOptions);
|
|
68
|
+
/**
|
|
69
|
+
* The AssemblyAI session ID. Set when the WebSocket connection is established
|
|
70
|
+
* (before any speech events). Null until the connection completes.
|
|
71
|
+
* Share this with the AssemblyAI team when reporting issues.
|
|
72
|
+
*/
|
|
73
|
+
get sessionId(): string | null;
|
|
74
|
+
/**
|
|
75
|
+
* Unix timestamp when the AssemblyAI session expires. Set alongside
|
|
76
|
+
* {@link sessionId} when the WebSocket connection is established.
|
|
77
|
+
*/
|
|
78
|
+
get expiresAt(): number | null;
|
|
79
|
+
updateOptions(opts: Partial<STTOptions>): void;
|
|
80
|
+
/**
|
|
81
|
+
* Force-finalize the current turn immediately.
|
|
82
|
+
*/
|
|
83
|
+
forceEndpoint(): void;
|
|
84
|
+
protected run(): Promise<void>;
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=stt.d.ts.map
|