@livekit/agents-plugin-deepgram 0.4.5 → 0.5.0
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/README.md +17 -0
- package/dist/index.cjs +23 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +1 -4
- package/dist/index.js.map +1 -1
- package/dist/models.cjs +17 -0
- package/dist/models.cjs.map +1 -0
- package/dist/models.js +0 -4
- package/dist/models.js.map +1 -1
- package/dist/stt.cjs +272 -0
- package/dist/stt.cjs.map +1 -0
- package/dist/stt.js +232 -243
- package/dist/stt.js.map +1 -1
- package/package.json +23 -7
- package/src/stt.ts +3 -3
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -53
- package/api-extractor.json +0 -20
- package/tsconfig.json +0 -16
- package/tsconfig.tsbuildinfo +0 -1
package/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
<!--
|
|
2
|
+
SPDX-FileCopyrightText: 2024 LiveKit, Inc.
|
|
3
|
+
|
|
4
|
+
SPDX-License-Identifier: Apache-2.0
|
|
5
|
+
-->
|
|
6
|
+
# Deepgram plugin for LiveKit Agents
|
|
7
|
+
|
|
8
|
+
The Agents Framework is designed for building realtime, programmable
|
|
9
|
+
participants that run on servers. Use it to create conversational, multi-modal
|
|
10
|
+
voice agents that can see, hear, and understand.
|
|
11
|
+
|
|
12
|
+
This package contains the Deepgram plugin, which allows for speech recognition.
|
|
13
|
+
Refer to the [documentation](https://docs.livekit.io/agents/overview/) for
|
|
14
|
+
information on how to use it, or browse the [API
|
|
15
|
+
reference](https://docs.livekit.io/agents-js/modules/plugins_agents_plugin_deepgram.html).
|
|
16
|
+
See the [repository](https://github.com/livekit/agents-js) for more information
|
|
17
|
+
about the framework as a whole.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
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 __copyProps = (to, from, except, desc) => {
|
|
7
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
+
for (let key of __getOwnPropNames(from))
|
|
9
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
+
}
|
|
12
|
+
return to;
|
|
13
|
+
};
|
|
14
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
15
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
16
|
+
var src_exports = {};
|
|
17
|
+
module.exports = __toCommonJS(src_exports);
|
|
18
|
+
__reExport(src_exports, require("./stt.cjs"), module.exports);
|
|
19
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
20
|
+
0 && (module.exports = {
|
|
21
|
+
...require("./stt.cjs")
|
|
22
|
+
});
|
|
23
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\n\nexport * from './stt.js';\n"],"mappings":";;;;;;;;;;;;;;;AAAA;AAAA;AAIA,wBAAc,qBAJd;","names":[]}
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\n\nexport * from './stt.js';\n"],"mappings":"AAIA,cAAc;","names":[]}
|
package/dist/models.cjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
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 __copyProps = (to, from, except, desc) => {
|
|
7
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
8
|
+
for (let key of __getOwnPropNames(from))
|
|
9
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
10
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
11
|
+
}
|
|
12
|
+
return to;
|
|
13
|
+
};
|
|
14
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
15
|
+
var models_exports = {};
|
|
16
|
+
module.exports = __toCommonJS(models_exports);
|
|
17
|
+
//# sourceMappingURL=models.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/models.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\n\nexport type STTModels =\n | 'nova-general'\n | 'nova-phonecall'\n | 'nova-meeting'\n | 'nova-2-general'\n | 'nova-2-meeting'\n | 'nova-2-phonecall'\n | 'nova-2-finance'\n | 'nova-2-conversationalai'\n | 'nova-2-voicemail'\n | 'nova-2-video'\n | 'nova-2-medical'\n | 'nova-2-drivethru'\n | 'nova-2-automotive'\n | 'enhanced-general'\n | 'enhanced-meeting'\n | 'enhanced-phonecall'\n | 'enhanced-finance'\n | 'base'\n | 'meeting'\n | 'phonecall'\n | 'finance'\n | 'conversationalai'\n | 'voicemail'\n | 'video'\n | 'whisper-tiny'\n | 'whisper-base'\n | 'whisper-small'\n | 'whisper-medium'\n | 'whisper-large';\n\nexport type STTLanguages =\n | 'da'\n | 'de'\n | 'en'\n | 'en-AU'\n | 'en-GB'\n | 'en-IN'\n | 'en-NZ'\n | 'en-US'\n | 'es'\n | 'es-419'\n | 'es-LATAM'\n | 'fr'\n | 'fr-CA'\n | 'hi'\n | 'hi-Latn'\n | 'id'\n | 'it'\n | 'ja'\n | 'ko'\n | 'nl'\n | 'no'\n | 'pl'\n | 'pt'\n | 'pt-BR'\n | 'ru'\n | 'sv'\n | 'ta'\n | 'taq'\n | 'th'\n | 'tr'\n | 'uk'\n | 'zh'\n | 'zh-CN'\n | 'zh-TW';\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
|
package/dist/models.js
CHANGED
package/dist/models.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/stt.cjs
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
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 API_BASE_URL_V1 = "wss://api.deepgram.com/v1/listen";
|
|
28
|
+
const defaultSTTOptions = {
|
|
29
|
+
apiKey: process.env.DEEPGRAM_API_KEY,
|
|
30
|
+
language: "en-US",
|
|
31
|
+
detectLanguage: false,
|
|
32
|
+
interimResults: true,
|
|
33
|
+
punctuate: true,
|
|
34
|
+
model: "nova-2-general",
|
|
35
|
+
smartFormat: true,
|
|
36
|
+
noDelay: true,
|
|
37
|
+
endpointing: 25,
|
|
38
|
+
fillerWords: false,
|
|
39
|
+
sampleRate: 16e3,
|
|
40
|
+
numChannels: 1,
|
|
41
|
+
keywords: [],
|
|
42
|
+
profanityFilter: false
|
|
43
|
+
};
|
|
44
|
+
class STT extends import_agents.stt.STT {
|
|
45
|
+
#opts;
|
|
46
|
+
#logger = (0, import_agents.log)();
|
|
47
|
+
constructor(opts = defaultSTTOptions) {
|
|
48
|
+
super({
|
|
49
|
+
streaming: true,
|
|
50
|
+
interimResults: opts.interimResults ?? defaultSTTOptions.interimResults
|
|
51
|
+
});
|
|
52
|
+
if (opts.apiKey === void 0 && defaultSTTOptions.apiKey === void 0) {
|
|
53
|
+
throw new Error(
|
|
54
|
+
"Deepgram API key is required, whether as an argument or as $DEEPGRAM_API_KEY"
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
this.#opts = { ...defaultSTTOptions, ...opts };
|
|
58
|
+
if (this.#opts.detectLanguage) {
|
|
59
|
+
this.#opts.language = void 0;
|
|
60
|
+
} else if (this.#opts.language && !["en-US", "en"].includes(this.#opts.language) && [
|
|
61
|
+
"nova-2-meeting",
|
|
62
|
+
"nova-2-phonecall",
|
|
63
|
+
"nova-2-finance",
|
|
64
|
+
"nova-2-conversationalai",
|
|
65
|
+
"nova-2-voicemail",
|
|
66
|
+
"nova-2-video",
|
|
67
|
+
"nova-2-medical",
|
|
68
|
+
"nova-2-drivethru",
|
|
69
|
+
"nova-2-automotive"
|
|
70
|
+
].includes(this.#opts.model)) {
|
|
71
|
+
this.#logger.warn(
|
|
72
|
+
`${this.#opts.model} does not support language ${this.#opts.language}, falling back to nova-2-general`
|
|
73
|
+
);
|
|
74
|
+
this.#opts.model = "nova-2-general";
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
78
|
+
async recognize(_) {
|
|
79
|
+
throw new Error("Recognize is not supported on Deepgram STT");
|
|
80
|
+
}
|
|
81
|
+
stream() {
|
|
82
|
+
return new SpeechStream(this.#opts);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
class SpeechStream extends import_agents.stt.SpeechStream {
|
|
86
|
+
#opts;
|
|
87
|
+
#audioEnergyFilter;
|
|
88
|
+
#logger = (0, import_agents.log)();
|
|
89
|
+
#speaking = false;
|
|
90
|
+
constructor(opts) {
|
|
91
|
+
super();
|
|
92
|
+
this.#opts = opts;
|
|
93
|
+
this.closed = false;
|
|
94
|
+
this.#audioEnergyFilter = new import_agents.AudioEnergyFilter();
|
|
95
|
+
this.#run();
|
|
96
|
+
}
|
|
97
|
+
async #run(maxRetry = 32) {
|
|
98
|
+
let retries = 0;
|
|
99
|
+
let ws;
|
|
100
|
+
while (!this.input.closed) {
|
|
101
|
+
const streamURL = new URL(API_BASE_URL_V1);
|
|
102
|
+
const params = {
|
|
103
|
+
model: this.#opts.model,
|
|
104
|
+
punctuate: this.#opts.punctuate,
|
|
105
|
+
smart_format: this.#opts.smartFormat,
|
|
106
|
+
no_delay: this.#opts.noDelay,
|
|
107
|
+
interim_results: this.#opts.interimResults,
|
|
108
|
+
encoding: "linear16",
|
|
109
|
+
vad_events: true,
|
|
110
|
+
sample_rate: this.#opts.sampleRate,
|
|
111
|
+
channels: this.#opts.numChannels,
|
|
112
|
+
endpointing: this.#opts.endpointing || false,
|
|
113
|
+
filler_words: this.#opts.fillerWords,
|
|
114
|
+
keywords: this.#opts.keywords.map((x) => x.join(":")),
|
|
115
|
+
profanity_filter: this.#opts.profanityFilter,
|
|
116
|
+
language: this.#opts.language
|
|
117
|
+
};
|
|
118
|
+
Object.entries(params).forEach(([k, v]) => {
|
|
119
|
+
if (v !== void 0) {
|
|
120
|
+
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
|
|
121
|
+
streamURL.searchParams.append(k, encodeURIComponent(v));
|
|
122
|
+
} else {
|
|
123
|
+
v.forEach((x) => streamURL.searchParams.append("keywords", encodeURIComponent(x)));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
ws = new import_ws.WebSocket(streamURL, {
|
|
128
|
+
headers: { Authorization: `Token ${this.#opts.apiKey}` }
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
await new Promise((resolve, reject) => {
|
|
132
|
+
ws.on("open", resolve);
|
|
133
|
+
ws.on("error", (error) => reject(error));
|
|
134
|
+
ws.on("close", (code) => reject(`WebSocket returned ${code}`));
|
|
135
|
+
});
|
|
136
|
+
await this.#runWS(ws);
|
|
137
|
+
} catch (e) {
|
|
138
|
+
if (retries >= maxRetry) {
|
|
139
|
+
throw new Error(`failed to connect to Deepgram after ${retries} attempts: ${e}`);
|
|
140
|
+
}
|
|
141
|
+
const delay = Math.min(retries * 5, 10);
|
|
142
|
+
retries++;
|
|
143
|
+
this.#logger.warn(
|
|
144
|
+
`failed to connect to Deepgram, retrying in ${delay} seconds: ${e} (${retries}/${maxRetry})`
|
|
145
|
+
);
|
|
146
|
+
await new Promise((resolve) => setTimeout(resolve, delay * 1e3));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
this.closed = true;
|
|
150
|
+
}
|
|
151
|
+
async #runWS(ws) {
|
|
152
|
+
let closing = false;
|
|
153
|
+
const keepalive = setInterval(() => {
|
|
154
|
+
try {
|
|
155
|
+
ws.send(JSON.stringify({ type: "KeepAlive" }));
|
|
156
|
+
} catch {
|
|
157
|
+
clearInterval(keepalive);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
}, 5e3);
|
|
161
|
+
const sendTask = async () => {
|
|
162
|
+
const samples100Ms = Math.floor(this.#opts.sampleRate / 10);
|
|
163
|
+
const stream = new import_agents.AudioByteStream(
|
|
164
|
+
this.#opts.sampleRate,
|
|
165
|
+
this.#opts.numChannels,
|
|
166
|
+
samples100Ms
|
|
167
|
+
);
|
|
168
|
+
for await (const data of this.input) {
|
|
169
|
+
let frames;
|
|
170
|
+
if (data === SpeechStream.FLUSH_SENTINEL) {
|
|
171
|
+
frames = stream.flush();
|
|
172
|
+
} else if (data.sampleRate === this.#opts.sampleRate || data.channels === this.#opts.numChannels) {
|
|
173
|
+
frames = stream.write(data.data.buffer);
|
|
174
|
+
} else {
|
|
175
|
+
throw new Error(`sample rate or channel count of frame does not match`);
|
|
176
|
+
}
|
|
177
|
+
for await (const frame of frames) {
|
|
178
|
+
if (this.#audioEnergyFilter.pushFrame(frame)) {
|
|
179
|
+
ws.send(frame.data.buffer);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
closing = true;
|
|
184
|
+
ws.send(JSON.stringify({ type: "CloseStream" }));
|
|
185
|
+
};
|
|
186
|
+
const listenTask = async () => {
|
|
187
|
+
new Promise(
|
|
188
|
+
(_, reject) => ws.once("close", (code, reason) => {
|
|
189
|
+
if (!closing) {
|
|
190
|
+
this.#logger.error(`WebSocket closed with code ${code}: ${reason}`);
|
|
191
|
+
reject();
|
|
192
|
+
}
|
|
193
|
+
})
|
|
194
|
+
);
|
|
195
|
+
while (!this.closed) {
|
|
196
|
+
try {
|
|
197
|
+
await new Promise((resolve) => {
|
|
198
|
+
ws.once("message", (data) => resolve(data));
|
|
199
|
+
}).then((msg) => {
|
|
200
|
+
const json = JSON.parse(msg.toString());
|
|
201
|
+
switch (json["type"]) {
|
|
202
|
+
case "SpeechStarted": {
|
|
203
|
+
if (this.#speaking) return;
|
|
204
|
+
this.#speaking = true;
|
|
205
|
+
this.queue.put({ type: import_agents.stt.SpeechEventType.START_OF_SPEECH });
|
|
206
|
+
break;
|
|
207
|
+
}
|
|
208
|
+
// see this page:
|
|
209
|
+
// https://developers.deepgram.com/docs/understand-endpointing-interim-results#using-endpointing-speech_final
|
|
210
|
+
// for more information about the different types of events
|
|
211
|
+
case "Results": {
|
|
212
|
+
const isFinal = json["is_final"];
|
|
213
|
+
const isEndpoint = json["speech_final"];
|
|
214
|
+
const alternatives = liveTranscriptionToSpeechData(this.#opts.language, json);
|
|
215
|
+
if (alternatives[0] && alternatives[0].text) {
|
|
216
|
+
if (!this.#speaking) {
|
|
217
|
+
this.#speaking = true;
|
|
218
|
+
this.queue.put({ type: import_agents.stt.SpeechEventType.START_OF_SPEECH });
|
|
219
|
+
}
|
|
220
|
+
if (isFinal) {
|
|
221
|
+
this.queue.put({
|
|
222
|
+
type: import_agents.stt.SpeechEventType.FINAL_TRANSCRIPT,
|
|
223
|
+
alternatives: [alternatives[0], ...alternatives.slice(1)]
|
|
224
|
+
});
|
|
225
|
+
} else {
|
|
226
|
+
this.queue.put({
|
|
227
|
+
type: import_agents.stt.SpeechEventType.INTERIM_TRANSCRIPT,
|
|
228
|
+
alternatives: [alternatives[0], ...alternatives.slice(1)]
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (isEndpoint && this.#speaking) {
|
|
233
|
+
this.#speaking = false;
|
|
234
|
+
this.queue.put({ type: import_agents.stt.SpeechEventType.END_OF_SPEECH });
|
|
235
|
+
}
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
case "Metadata": {
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
default: {
|
|
242
|
+
this.#logger.child({ msg: json }).warn("received unexpected message from Deepgram");
|
|
243
|
+
break;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
} catch (error) {
|
|
248
|
+
this.#logger.child({ error }).warn("unrecoverable error, exiting");
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
};
|
|
253
|
+
await Promise.all([sendTask(), listenTask()]);
|
|
254
|
+
clearInterval(keepalive);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const liveTranscriptionToSpeechData = (language, data) => {
|
|
258
|
+
const alts = data["channel"]["alternatives"];
|
|
259
|
+
return alts.map((alt) => ({
|
|
260
|
+
language,
|
|
261
|
+
startTime: alt["words"].length ? alt["words"][0]["start"] : 0,
|
|
262
|
+
endTime: alt["words"].length ? alt["words"][alt["words"].length - 1]["end"] : 0,
|
|
263
|
+
confidence: alt["confidence"],
|
|
264
|
+
text: alt["transcript"]
|
|
265
|
+
}));
|
|
266
|
+
};
|
|
267
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
268
|
+
0 && (module.exports = {
|
|
269
|
+
STT,
|
|
270
|
+
SpeechStream
|
|
271
|
+
});
|
|
272
|
+
//# sourceMappingURL=stt.cjs.map
|
package/dist/stt.cjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/stt.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { type AudioBuffer, AudioByteStream, AudioEnergyFilter, log, stt } from '@livekit/agents';\nimport type { AudioFrame } from '@livekit/rtc-node';\nimport { type RawData, WebSocket } from 'ws';\nimport type { STTLanguages, STTModels } from './models.js';\n\nconst API_BASE_URL_V1 = 'wss://api.deepgram.com/v1/listen';\n\nexport interface STTOptions {\n apiKey?: string;\n language?: STTLanguages | string;\n detectLanguage: boolean;\n interimResults: boolean;\n punctuate: boolean;\n model: STTModels;\n smartFormat: boolean;\n noDelay: boolean;\n endpointing: number;\n fillerWords: boolean;\n sampleRate: number;\n numChannels: number;\n keywords: [string, number][];\n profanityFilter: boolean;\n}\n\nconst defaultSTTOptions: STTOptions = {\n apiKey: process.env.DEEPGRAM_API_KEY,\n language: 'en-US',\n detectLanguage: false,\n interimResults: true,\n punctuate: true,\n model: 'nova-2-general',\n smartFormat: true,\n noDelay: true,\n endpointing: 25,\n fillerWords: false,\n sampleRate: 16000,\n numChannels: 1,\n keywords: [],\n profanityFilter: false,\n};\n\nexport class STT extends stt.STT {\n #opts: STTOptions;\n #logger = log();\n\n constructor(opts: Partial<STTOptions> = defaultSTTOptions) {\n super({\n streaming: true,\n interimResults: opts.interimResults ?? defaultSTTOptions.interimResults,\n });\n if (opts.apiKey === undefined && defaultSTTOptions.apiKey === undefined) {\n throw new Error(\n 'Deepgram API key is required, whether as an argument or as $DEEPGRAM_API_KEY',\n );\n }\n\n this.#opts = { ...defaultSTTOptions, ...opts };\n\n if (this.#opts.detectLanguage) {\n this.#opts.language = undefined;\n } else if (\n this.#opts.language &&\n !['en-US', 'en'].includes(this.#opts.language) &&\n [\n 'nova-2-meeting',\n 'nova-2-phonecall',\n 'nova-2-finance',\n 'nova-2-conversationalai',\n 'nova-2-voicemail',\n 'nova-2-video',\n 'nova-2-medical',\n 'nova-2-drivethru',\n 'nova-2-automotive',\n ].includes(this.#opts.model)\n ) {\n this.#logger.warn(\n `${this.#opts.model} does not support language ${this.#opts.language}, falling back to nova-2-general`,\n );\n this.#opts.model = 'nova-2-general';\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async recognize(_: AudioBuffer): Promise<stt.SpeechEvent> {\n throw new Error('Recognize is not supported on Deepgram STT');\n }\n\n stream(): stt.SpeechStream {\n return new SpeechStream(this.#opts);\n }\n}\n\nexport class SpeechStream extends stt.SpeechStream {\n #opts: STTOptions;\n #audioEnergyFilter: AudioEnergyFilter;\n #logger = log();\n #speaking = false;\n\n constructor(opts: STTOptions) {\n super();\n this.#opts = opts;\n this.closed = false;\n this.#audioEnergyFilter = new AudioEnergyFilter();\n\n this.#run();\n }\n\n async #run(maxRetry = 32) {\n let retries = 0;\n let ws: WebSocket;\n while (!this.input.closed) {\n const streamURL = new URL(API_BASE_URL_V1);\n const params = {\n model: this.#opts.model,\n punctuate: this.#opts.punctuate,\n smart_format: this.#opts.smartFormat,\n no_delay: this.#opts.noDelay,\n interim_results: this.#opts.interimResults,\n encoding: 'linear16',\n vad_events: true,\n sample_rate: this.#opts.sampleRate,\n channels: this.#opts.numChannels,\n endpointing: this.#opts.endpointing || false,\n filler_words: this.#opts.fillerWords,\n keywords: this.#opts.keywords.map((x) => x.join(':')),\n profanity_filter: this.#opts.profanityFilter,\n language: this.#opts.language,\n };\n Object.entries(params).forEach(([k, v]) => {\n if (v !== undefined) {\n if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') {\n streamURL.searchParams.append(k, encodeURIComponent(v));\n } else {\n v.forEach((x) => streamURL.searchParams.append('keywords', encodeURIComponent(x)));\n }\n }\n });\n\n ws = new WebSocket(streamURL, {\n headers: { Authorization: `Token ${this.#opts.apiKey}` },\n });\n\n try {\n await new Promise((resolve, reject) => {\n ws.on('open', resolve);\n ws.on('error', (error) => reject(error));\n ws.on('close', (code) => reject(`WebSocket returned ${code}`));\n });\n\n await this.#runWS(ws);\n } catch (e) {\n if (retries >= maxRetry) {\n throw new Error(`failed to connect to Deepgram after ${retries} attempts: ${e}`);\n }\n\n const delay = Math.min(retries * 5, 10);\n retries++;\n\n this.#logger.warn(\n `failed to connect to Deepgram, retrying in ${delay} seconds: ${e} (${retries}/${maxRetry})`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay * 1000));\n }\n }\n\n this.closed = true;\n }\n\n async #runWS(ws: WebSocket) {\n let closing = false;\n\n const keepalive = setInterval(() => {\n try {\n ws.send(JSON.stringify({ type: 'KeepAlive' }));\n } catch {\n clearInterval(keepalive);\n return;\n }\n }, 5000);\n\n const sendTask = async () => {\n const samples100Ms = Math.floor(this.#opts.sampleRate / 10);\n const stream = new AudioByteStream(\n this.#opts.sampleRate,\n this.#opts.numChannels,\n samples100Ms,\n );\n\n for await (const data of this.input) {\n let frames: AudioFrame[];\n if (data === SpeechStream.FLUSH_SENTINEL) {\n frames = stream.flush();\n } else if (\n data.sampleRate === this.#opts.sampleRate ||\n data.channels === this.#opts.numChannels\n ) {\n frames = stream.write(data.data.buffer);\n } else {\n throw new Error(`sample rate or channel count of frame does not match`);\n }\n\n for await (const frame of frames) {\n if (this.#audioEnergyFilter.pushFrame(frame)) {\n ws.send(frame.data.buffer);\n }\n }\n }\n\n closing = true;\n ws.send(JSON.stringify({ type: 'CloseStream' }));\n };\n\n const listenTask = async () => {\n 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();\n }\n }),\n );\n\n while (!this.closed) {\n try {\n await new Promise<RawData>((resolve) => {\n ws.once('message', (data) => resolve(data));\n }).then((msg) => {\n const json = JSON.parse(msg.toString());\n switch (json['type']) {\n case 'SpeechStarted': {\n // This is a normal case. Deepgram's SpeechStarted events\n // are not correlated with speech_final or utterance end.\n // It's possible that we receive two in a row without an endpoint\n // It's also possible we receive a transcript without a SpeechStarted event.\n if (this.#speaking) return;\n this.#speaking = true;\n this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });\n break;\n }\n // see this page:\n // https://developers.deepgram.com/docs/understand-endpointing-interim-results#using-endpointing-speech_final\n // for more information about the different types of events\n case 'Results': {\n const isFinal = json['is_final'];\n const isEndpoint = json['speech_final'];\n\n const alternatives = liveTranscriptionToSpeechData(this.#opts.language!, json);\n\n // If, for some reason, we didn't get a SpeechStarted event but we got\n // a transcript with text, we should start speaking. It's rare but has\n // been observed.\n if (alternatives[0] && alternatives[0].text) {\n if (!this.#speaking) {\n this.#speaking = true;\n this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });\n }\n\n if (isFinal) {\n this.queue.put({\n type: stt.SpeechEventType.FINAL_TRANSCRIPT,\n alternatives: [alternatives[0], ...alternatives.slice(1)],\n });\n } else {\n this.queue.put({\n type: stt.SpeechEventType.INTERIM_TRANSCRIPT,\n alternatives: [alternatives[0], ...alternatives.slice(1)],\n });\n }\n }\n\n // if we receive an endpoint, only end the speech if\n // we either had a SpeechStarted event or we have a seen\n // a non-empty transcript (deepgram doesn't have a SpeechEnded event)\n if (isEndpoint && this.#speaking) {\n this.#speaking = false;\n this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });\n }\n\n break;\n }\n case 'Metadata': {\n break;\n }\n default: {\n this.#logger.child({ msg: json }).warn('received unexpected message from Deepgram');\n break;\n }\n }\n });\n } catch (error) {\n this.#logger.child({ error }).warn('unrecoverable error, exiting');\n break;\n }\n }\n };\n\n await Promise.all([sendTask(), listenTask()]);\n clearInterval(keepalive);\n }\n}\n\nconst liveTranscriptionToSpeechData = (\n language: STTLanguages | string,\n data: { [id: string]: any },\n): stt.SpeechData[] => {\n const alts: any[] = data['channel']['alternatives'];\n\n return alts.map((alt) => ({\n language,\n startTime: alt['words'].length ? alt['words'][0]['start'] : 0,\n endTime: alt['words'].length ? alt['words'][alt['words'].length - 1]['end'] : 0,\n confidence: alt['confidence'],\n text: alt['transcript'],\n }));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAA+E;AAE/E,gBAAwC;AAGxC,MAAM,kBAAkB;AAmBxB,MAAM,oBAAgC;AAAA,EACpC,QAAQ,QAAQ,IAAI;AAAA,EACpB,UAAU;AAAA,EACV,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS;AAAA,EACT,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,UAAU,CAAC;AAAA,EACX,iBAAiB;AACnB;AAEO,MAA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