@livekit/agents-plugin-cartesia 1.4.4 → 1.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/models.cjs +3 -0
- package/dist/models.cjs.map +1 -1
- package/dist/models.d.cts +17 -0
- package/dist/models.d.ts +17 -0
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +2 -0
- package/dist/models.js.map +1 -1
- package/dist/stt.cjs +409 -0
- package/dist/stt.cjs.map +1 -0
- package/dist/stt.d.cts +51 -0
- package/dist/stt.d.ts +51 -0
- package/dist/stt.d.ts.map +1 -0
- package/dist/stt.js +392 -0
- package/dist/stt.js.map +1 -0
- package/dist/stt.test.cjs +17 -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 +16 -0
- package/dist/stt.test.js.map +1 -0
- package/dist/tts.cjs +31 -21
- package/dist/tts.cjs.map +1 -1
- package/dist/tts.d.ts.map +1 -1
- package/dist/tts.js +35 -22
- package/dist/tts.js.map +1 -1
- package/package.json +8 -7
- package/src/index.ts +1 -0
- package/src/models.ts +28 -6
- package/src/stt.test.ts +19 -0
- package/src/stt.ts +618 -0
- package/src/tts.ts +41 -24
package/src/models.ts
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
//
|
|
3
3
|
// SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* LiveKit uses this encoding for all audio
|
|
7
|
+
*/
|
|
8
|
+
export const AUDIO_ENCODING = 'pcm_s16le';
|
|
9
|
+
|
|
10
|
+
// ============================================================================
|
|
11
|
+
// TTS
|
|
12
|
+
// ============================================================================
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* See [the docs](https://docs.cartesia.ai/build-with-cartesia/tts-models/latest) for all options.
|
|
16
|
+
*/
|
|
5
17
|
export type TTSModels =
|
|
6
18
|
| 'sonic'
|
|
7
19
|
| 'sonic-2'
|
|
@@ -10,6 +22,9 @@ export type TTSModels =
|
|
|
10
22
|
| 'sonic-preview'
|
|
11
23
|
| 'sonic-turbo';
|
|
12
24
|
|
|
25
|
+
/**
|
|
26
|
+
* See [the docs](https://docs.cartesia.ai/build-with-cartesia/tts-models/latest) for all options.
|
|
27
|
+
*/
|
|
13
28
|
export type TTSLanguages = 'en' | 'es' | 'fr' | 'de' | 'pt' | 'zh' | 'ja';
|
|
14
29
|
|
|
15
30
|
export const TTSDefaultVoiceId = 'f786b574-daa5-4673-aa0c-cbe3e8534c02';
|
|
@@ -45,9 +60,16 @@ export type TTSVoiceEmotion =
|
|
|
45
60
|
| 'curiosity:high'
|
|
46
61
|
| 'curiosity:highest';
|
|
47
62
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
63
|
+
/**
|
|
64
|
+
* @deprecated Encoding should not be parameterized. Only `pcm_s16le`is allowed. Prefer using {@link AUDIO_ENCODING}.
|
|
65
|
+
*/
|
|
66
|
+
export type TTSEncoding = 'pcm_s16le';
|
|
67
|
+
|
|
68
|
+
// ============================================================================
|
|
69
|
+
// STT
|
|
70
|
+
// ============================================================================
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* See [the docs](https://docs.cartesia.ai/build-with-cartesia/stt-models/latest) for all options.
|
|
74
|
+
*/
|
|
75
|
+
export type STTModel = 'ink-2';
|
package/src/stt.test.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import { VAD } from '@livekit/agents-plugin-silero';
|
|
5
|
+
import { stt } from '@livekit/agents-plugins-test';
|
|
6
|
+
import { describe, it } from 'vitest';
|
|
7
|
+
import { STT } from './stt.js';
|
|
8
|
+
|
|
9
|
+
const hasCartesiaApiKey = Boolean(process.env.CARTESIA_API_KEY);
|
|
10
|
+
|
|
11
|
+
if (hasCartesiaApiKey) {
|
|
12
|
+
describe('Cartesia STT', async () => {
|
|
13
|
+
await stt(new STT(), await VAD.load(), { nonStreaming: false });
|
|
14
|
+
});
|
|
15
|
+
} else {
|
|
16
|
+
describe('Cartesia STT', () => {
|
|
17
|
+
it.skip('requires CARTESIA_API_KEY', () => {});
|
|
18
|
+
});
|
|
19
|
+
}
|
package/src/stt.ts
ADDED
|
@@ -0,0 +1,618 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2026 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import {
|
|
5
|
+
type APIConnectOptions,
|
|
6
|
+
APIConnectionError,
|
|
7
|
+
AudioByteStream,
|
|
8
|
+
asLanguageCode,
|
|
9
|
+
calculateAudioDurationSeconds,
|
|
10
|
+
log,
|
|
11
|
+
stt,
|
|
12
|
+
waitForAbort,
|
|
13
|
+
} from '@livekit/agents';
|
|
14
|
+
import type { AudioFrame } from '@livekit/rtc-node';
|
|
15
|
+
import type { IncomingMessage } from 'node:http';
|
|
16
|
+
import { WebSocket } from 'ws';
|
|
17
|
+
import { AUDIO_ENCODING, type STTModel } from './models.js';
|
|
18
|
+
|
|
19
|
+
const AUTHORIZATION_HEADER = 'X-API-Key';
|
|
20
|
+
const VERSION_HEADER = 'Cartesia-Version';
|
|
21
|
+
const REQUEST_ID_HEADER = 'cartesia-request-id';
|
|
22
|
+
const API_VERSION = '2026-03-01';
|
|
23
|
+
const DRAIN_TIMEOUT_MS = 5000;
|
|
24
|
+
const KEEPALIVE_INTERVAL_MS = 30000;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Fires once when the WebSocket connection is established.
|
|
28
|
+
*
|
|
29
|
+
* You do not need to wait for this event before sending audio.
|
|
30
|
+
*/
|
|
31
|
+
type STTConnectedEvent = {
|
|
32
|
+
type: 'connected';
|
|
33
|
+
/**
|
|
34
|
+
* Unique identifier for this connection. Does not change between turns.
|
|
35
|
+
*/
|
|
36
|
+
request_id: string;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Model predicts {@link stt.SpeechEventType.START_OF_SPEECH}.
|
|
41
|
+
*/
|
|
42
|
+
type STTTurnStartEvent = {
|
|
43
|
+
type: 'turn.start';
|
|
44
|
+
/**
|
|
45
|
+
* Unique identifier for this connection. Does not change between turns.
|
|
46
|
+
*/
|
|
47
|
+
request_id: string;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Fires repeatedly as the model transcribes the current user turn.
|
|
52
|
+
*
|
|
53
|
+
* Can be used for {@link stt.SpeechEventType.INTERIM_TRANSCRIPT}.
|
|
54
|
+
*/
|
|
55
|
+
type STTTurnUpdateEvent = {
|
|
56
|
+
type: 'turn.update';
|
|
57
|
+
/**
|
|
58
|
+
* Cumulative text for the current turn, i.e. the full text transcribed so far in this turn, not a delta.
|
|
59
|
+
*/
|
|
60
|
+
transcript: string;
|
|
61
|
+
/**
|
|
62
|
+
* Unique identifier for this connection. Does not change between turns.
|
|
63
|
+
*/
|
|
64
|
+
request_id: string;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Fires when the model predicts that the user might be done speaking.
|
|
69
|
+
*
|
|
70
|
+
* Can be used for {@link stt.SpeechEventType.PREFLIGHT_TRANSCRIPT}.
|
|
71
|
+
*/
|
|
72
|
+
type STTTurnEagerEndEvent = {
|
|
73
|
+
type: 'turn.eager_end';
|
|
74
|
+
/**
|
|
75
|
+
* Cumulative text for the current turn, i.e. the full text transcribed so far in this turn, not a delta.
|
|
76
|
+
*/
|
|
77
|
+
transcript: string;
|
|
78
|
+
/**
|
|
79
|
+
* Unique identifier for this connection. Does not change between turns.
|
|
80
|
+
*/
|
|
81
|
+
request_id: string;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Fires after {@link STTTurnEagerEndEvent} if the user turn has not actually ended.
|
|
86
|
+
*/
|
|
87
|
+
type STTTurnResumeEvent = {
|
|
88
|
+
type: 'turn.resume';
|
|
89
|
+
/**
|
|
90
|
+
* Unique identifier for this connection. Does not change between turns.
|
|
91
|
+
*/
|
|
92
|
+
request_id: string;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Marks the end of a user turn.
|
|
97
|
+
*
|
|
98
|
+
* This is used for {@link stt.SpeechEventType.END_OF_SPEECH} and {@link stt.SpeechEventType.FINAL_TRANSCRIPT}.
|
|
99
|
+
*/
|
|
100
|
+
type STTTurnEndEvent = {
|
|
101
|
+
type: 'turn.end';
|
|
102
|
+
/**
|
|
103
|
+
* Cumulative text for the current turn, i.e. the full text transcribed so far in this turn, not a delta.
|
|
104
|
+
*/
|
|
105
|
+
transcript: string;
|
|
106
|
+
/**
|
|
107
|
+
* Unique identifier for this connection. Does not change between turns.
|
|
108
|
+
*/
|
|
109
|
+
request_id: string;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
type STTErrorEvent = {
|
|
113
|
+
type: 'error';
|
|
114
|
+
error_code?: string;
|
|
115
|
+
status_code?: number;
|
|
116
|
+
title?: string;
|
|
117
|
+
message?: string;
|
|
118
|
+
doc_url?: string;
|
|
119
|
+
request_id?: string;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Server-sent event on the `/stt/turns/websocket` endpoint.
|
|
124
|
+
*
|
|
125
|
+
* See https://docs.cartesia.ai/api-reference/stt/turns/websocket.
|
|
126
|
+
*/
|
|
127
|
+
type STTEventMessage =
|
|
128
|
+
| STTConnectedEvent
|
|
129
|
+
| STTTurnStartEvent
|
|
130
|
+
| STTTurnUpdateEvent
|
|
131
|
+
| STTTurnEagerEndEvent
|
|
132
|
+
| STTTurnResumeEvent
|
|
133
|
+
| STTTurnEndEvent
|
|
134
|
+
| STTErrorEvent;
|
|
135
|
+
|
|
136
|
+
export type STTOptions = {
|
|
137
|
+
apiKey: string;
|
|
138
|
+
// eslint-disable-next-line @typescript-eslint/ban-types
|
|
139
|
+
model: STTModel | (string & {});
|
|
140
|
+
sampleRate: number;
|
|
141
|
+
baseUrl: string;
|
|
142
|
+
audioChunkDurationMS: number;
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const defaultSTTOptions = {
|
|
146
|
+
model: 'ink-2' satisfies STTModel,
|
|
147
|
+
/** recommended default */
|
|
148
|
+
sampleRate: 16_000,
|
|
149
|
+
/** recommended default */
|
|
150
|
+
audioChunkDurationMS: 160,
|
|
151
|
+
baseUrl: 'https://api.cartesia.ai',
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
function mergeSTTOptions(base: STTOptions, override: Partial<STTOptions>): STTOptions {
|
|
155
|
+
return {
|
|
156
|
+
apiKey: override.apiKey ?? base.apiKey,
|
|
157
|
+
baseUrl: override.baseUrl ?? base.baseUrl,
|
|
158
|
+
model: override.model ?? base.model,
|
|
159
|
+
sampleRate: override.sampleRate ?? base.sampleRate,
|
|
160
|
+
audioChunkDurationMS: override.audioChunkDurationMS ?? base.audioChunkDurationMS,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* Cartesia speech to text.
|
|
166
|
+
*
|
|
167
|
+
* Supports:
|
|
168
|
+
* - Streaming
|
|
169
|
+
* - Turn detection
|
|
170
|
+
* - Interim results
|
|
171
|
+
*
|
|
172
|
+
* See https://docs.cartesia.ai/build-with-cartesia/stt-models/latest
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* ```typescript
|
|
176
|
+
* import { voice } from '@livekit/agents';
|
|
177
|
+
* import { STT, TTS } from '@livekit/agents-plugin-cartesia';
|
|
178
|
+
*
|
|
179
|
+
* const session = new voice.AgentSession({
|
|
180
|
+
* stt: new STT(),
|
|
181
|
+
* llm: new LLM(), // choose your favorite LLM
|
|
182
|
+
* tts: new TTS(),
|
|
183
|
+
* turnHandling: { turnDetection: 'stt' },
|
|
184
|
+
* });
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
export class STT extends stt.STT {
|
|
188
|
+
#opts: STTOptions;
|
|
189
|
+
|
|
190
|
+
constructor(opts: Partial<STTOptions> = {}) {
|
|
191
|
+
super({
|
|
192
|
+
streaming: true,
|
|
193
|
+
interimResults: true,
|
|
194
|
+
alignedTranscript: false,
|
|
195
|
+
diarization: false,
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
const apiKey = opts.apiKey ?? process.env.CARTESIA_API_KEY;
|
|
199
|
+
if (!apiKey) {
|
|
200
|
+
throw new Error(
|
|
201
|
+
'Cartesia API key is required, whether as an argument or as $CARTESIA_API_KEY',
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
this.#opts = mergeSTTOptions({ ...defaultSTTOptions, apiKey }, opts);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
override get label(): string {
|
|
209
|
+
return 'cartesia.STT';
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
override get model(): string {
|
|
213
|
+
return this.#opts.model;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
override get provider(): string {
|
|
217
|
+
return 'Cartesia';
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
protected override async _recognize(): Promise<stt.SpeechEvent> {
|
|
221
|
+
throw new Error('Cartesia STT does not support batch recognition, use stream() instead');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
override stream(options?: { connOptions?: APIConnectOptions }): SpeechStream {
|
|
225
|
+
return new SpeechStream(this, this.#opts, options?.connOptions);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export class SpeechStream extends stt.SpeechStream {
|
|
230
|
+
#opts: STTOptions;
|
|
231
|
+
#logger = log();
|
|
232
|
+
#ws: WebSocket | null = null;
|
|
233
|
+
#requestId: string | undefined;
|
|
234
|
+
#speaking = false;
|
|
235
|
+
#currentTranscript = '';
|
|
236
|
+
#speechDuration = 0;
|
|
237
|
+
#closingWs = false;
|
|
238
|
+
|
|
239
|
+
constructor(sttInstance: STT, opts: STTOptions, connOptions?: APIConnectOptions) {
|
|
240
|
+
super(sttInstance, opts.sampleRate, connOptions);
|
|
241
|
+
this.#opts = { ...opts };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
override get label(): string {
|
|
245
|
+
return 'cartesia.SpeechStream';
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
protected override async run() {
|
|
249
|
+
if (this.closed) {
|
|
250
|
+
this.close();
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
this.#speaking = false;
|
|
255
|
+
this.#currentTranscript = '';
|
|
256
|
+
this.#speechDuration = 0;
|
|
257
|
+
this.#closingWs = false;
|
|
258
|
+
|
|
259
|
+
let keepaliveInterval: NodeJS.Timeout | undefined;
|
|
260
|
+
const abortController = new AbortController();
|
|
261
|
+
|
|
262
|
+
try {
|
|
263
|
+
const url = this.#getCartesiaUrl();
|
|
264
|
+
this.#logger.debug(`Connecting to Cartesia STT: ${url}`);
|
|
265
|
+
|
|
266
|
+
const ws = new WebSocket(url, {
|
|
267
|
+
headers: {
|
|
268
|
+
[AUTHORIZATION_HEADER]: this.#opts.apiKey,
|
|
269
|
+
[VERSION_HEADER]: API_VERSION,
|
|
270
|
+
},
|
|
271
|
+
});
|
|
272
|
+
this.#ws = ws;
|
|
273
|
+
|
|
274
|
+
// Cartesia returns the request id on the WS upgrade response, before any
|
|
275
|
+
// turn events are sent. Capture it so logs and metrics emitted on the
|
|
276
|
+
// connection (and any pre-`turn.start` errors) are attributable.
|
|
277
|
+
ws.once('upgrade', (response: IncomingMessage) => {
|
|
278
|
+
const headerValue = response.headers[REQUEST_ID_HEADER];
|
|
279
|
+
const requestId = Array.isArray(headerValue) ? headerValue[0] : headerValue;
|
|
280
|
+
if (requestId) {
|
|
281
|
+
this.#requestId = requestId;
|
|
282
|
+
this.#logger.debug({ cartesiaRequestId: requestId }, 'Cartesia STT WebSocket connected');
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
await new Promise<void>((resolve, reject) => {
|
|
287
|
+
const onOpen = () => {
|
|
288
|
+
ws.off('error', onError);
|
|
289
|
+
resolve();
|
|
290
|
+
};
|
|
291
|
+
const onError = (err: Error) => {
|
|
292
|
+
ws.off('open', onOpen);
|
|
293
|
+
reject(new APIConnectionError({ message: err.message, options: { retryable: true } }));
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
ws.once('open', onOpen);
|
|
297
|
+
ws.once('error', onError);
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
// If one task fails, abort its peer and close the WS so the peer can
|
|
301
|
+
// exit before we re-throw. Otherwise a dangling task would survive
|
|
302
|
+
// into the next retry attempt (sendTask blocked on input.next() would
|
|
303
|
+
// steal frames; recvTask's close handler could still push events to
|
|
304
|
+
// the queue and surface an unhandled rejection).
|
|
305
|
+
let firstError: unknown;
|
|
306
|
+
const stopPeer = (err: unknown) => {
|
|
307
|
+
if (firstError === undefined) firstError = err;
|
|
308
|
+
abortController.abort();
|
|
309
|
+
if (ws.readyState === WebSocket.OPEN) ws.close();
|
|
310
|
+
};
|
|
311
|
+
const sendPromise = this.#sendTask(ws, abortController.signal).catch(stopPeer);
|
|
312
|
+
const recvPromise = this.#recvTask(ws).catch(stopPeer);
|
|
313
|
+
|
|
314
|
+
keepaliveInterval = setInterval(() => {
|
|
315
|
+
try {
|
|
316
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
317
|
+
ws.ping();
|
|
318
|
+
}
|
|
319
|
+
} catch {
|
|
320
|
+
// ignore
|
|
321
|
+
}
|
|
322
|
+
}, KEEPALIVE_INTERVAL_MS);
|
|
323
|
+
await Promise.all([sendPromise, recvPromise]);
|
|
324
|
+
if (firstError !== undefined) throw firstError;
|
|
325
|
+
} catch (error) {
|
|
326
|
+
this.#logger.error('Cartesia STT stream error', { error });
|
|
327
|
+
throw error;
|
|
328
|
+
} finally {
|
|
329
|
+
abortController.abort();
|
|
330
|
+
if (keepaliveInterval) clearInterval(keepaliveInterval);
|
|
331
|
+
if (this.#ws?.readyState === WebSocket.OPEN) {
|
|
332
|
+
this.#ws.close();
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
this.close();
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
async #sendTask(ws: WebSocket, abortSignal: AbortSignal) {
|
|
340
|
+
const samplesPerChunk = Math.floor(
|
|
341
|
+
(this.#opts.sampleRate * this.#opts.audioChunkDurationMS) / 1000,
|
|
342
|
+
);
|
|
343
|
+
const audioBstream = new AudioByteStream(this.#opts.sampleRate, 1, samplesPerChunk);
|
|
344
|
+
|
|
345
|
+
let hasEnded = false;
|
|
346
|
+
const iterator = this.input[Symbol.asyncIterator]();
|
|
347
|
+
const abortPromise = waitForAbort(abortSignal);
|
|
348
|
+
|
|
349
|
+
while (true) {
|
|
350
|
+
const result = await Promise.race([iterator.next(), abortPromise]);
|
|
351
|
+
|
|
352
|
+
if (result === undefined) return; // aborted
|
|
353
|
+
|
|
354
|
+
if (result.done) {
|
|
355
|
+
hasEnded = true;
|
|
356
|
+
} else {
|
|
357
|
+
const data = result.value;
|
|
358
|
+
const frames: AudioFrame[] = [];
|
|
359
|
+
|
|
360
|
+
if (data === SpeechStream.FLUSH_SENTINEL) {
|
|
361
|
+
frames.push(...audioBstream.flush());
|
|
362
|
+
} else {
|
|
363
|
+
// Pass the typed array directly so AudioByteStream uses byteOffset/
|
|
364
|
+
// byteLength — `.buffer` would include foreign bytes when rtc-node
|
|
365
|
+
// hands us a view over a pooled allocator.
|
|
366
|
+
frames.push(...audioBstream.write(data.data));
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
for (const frame of frames) {
|
|
370
|
+
this.#speechDuration += calculateAudioDurationSeconds(frame);
|
|
371
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
372
|
+
ws.send(frame.data);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (hasEnded) break;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
381
|
+
this.#closingWs = true;
|
|
382
|
+
this.#logger.debug('Sending close message to Cartesia STT');
|
|
383
|
+
ws.send(JSON.stringify({ type: 'close' }));
|
|
384
|
+
|
|
385
|
+
// After `close`, the server should flush any pending turn events and
|
|
386
|
+
// close the socket. If it hangs, force the issue rather than letting
|
|
387
|
+
// the stream wait forever.
|
|
388
|
+
const drainTimer = setTimeout(() => {
|
|
389
|
+
this.#logger.warn(
|
|
390
|
+
`Cartesia STT did not close within ${DRAIN_TIMEOUT_MS}ms after done; forcing close`,
|
|
391
|
+
);
|
|
392
|
+
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CLOSING) {
|
|
393
|
+
ws.terminate();
|
|
394
|
+
}
|
|
395
|
+
}, DRAIN_TIMEOUT_MS);
|
|
396
|
+
ws.once('close', () => clearTimeout(drainTimer));
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async #recvTask(ws: WebSocket) {
|
|
401
|
+
let pendingError: Error | undefined = undefined;
|
|
402
|
+
|
|
403
|
+
return new Promise<void>((resolve, reject) => {
|
|
404
|
+
const settle = (err?: Error) => {
|
|
405
|
+
if (err) reject(err);
|
|
406
|
+
else resolve();
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
ws.on('message', (data: Buffer, isBinary: boolean) => {
|
|
410
|
+
if (isBinary) {
|
|
411
|
+
this.#logger.warn('Received unexpected binary message from Cartesia STT');
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
let msg: STTEventMessage;
|
|
415
|
+
try {
|
|
416
|
+
msg = JSON.parse(data.toString());
|
|
417
|
+
} catch (error) {
|
|
418
|
+
this.#logger.error('Failed to parse Cartesia STT message', { error });
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
if (msg.type === 'error') {
|
|
423
|
+
this.#logger.error('Cartesia sent an error', msg);
|
|
424
|
+
|
|
425
|
+
// do not close the websocket on bad requests since that may be caused by invalid messages
|
|
426
|
+
if (msg.status_code === undefined || msg.status_code >= 500) {
|
|
427
|
+
// Defer until the WS is fully closed so we don't race the `close`
|
|
428
|
+
// handler with a rejected `recvTask`. Close the socket explicitly
|
|
429
|
+
// in case the server doesn't, otherwise recv would hang.
|
|
430
|
+
pendingError = new APIConnectionError({
|
|
431
|
+
message: msg.message || msg.title,
|
|
432
|
+
options: {
|
|
433
|
+
retryable: true,
|
|
434
|
+
},
|
|
435
|
+
});
|
|
436
|
+
ws.close();
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
} else {
|
|
440
|
+
this.#processStreamEvent(msg);
|
|
441
|
+
}
|
|
442
|
+
} catch (error) {
|
|
443
|
+
this.#logger.error('Failed to process Cartesia STT message', { error });
|
|
444
|
+
}
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
ws.on('close', (code, reason) => {
|
|
448
|
+
// If a turn was in progress, close it out so consumers see a balanced
|
|
449
|
+
// START_OF_SPEECH/END_OF_SPEECH pair and don't carry stale turn state
|
|
450
|
+
// into the next reconnect.
|
|
451
|
+
if (this.#speaking) {
|
|
452
|
+
if (this.#currentTranscript) {
|
|
453
|
+
this.#sendTranscriptEvent(
|
|
454
|
+
stt.SpeechEventType.FINAL_TRANSCRIPT,
|
|
455
|
+
this.#currentTranscript,
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
if (!this.queue.closed)
|
|
459
|
+
this.queue.put({
|
|
460
|
+
type: stt.SpeechEventType.END_OF_SPEECH,
|
|
461
|
+
requestId: this.#requestId,
|
|
462
|
+
});
|
|
463
|
+
this.#logger.debug('Cartesia STT END_OF_SPEECH');
|
|
464
|
+
if (this.#speechDuration > 0 && !this.queue.closed) {
|
|
465
|
+
this.queue.put({
|
|
466
|
+
type: stt.SpeechEventType.RECOGNITION_USAGE,
|
|
467
|
+
requestId: this.#requestId,
|
|
468
|
+
recognitionUsage: { audioDuration: this.#speechDuration },
|
|
469
|
+
});
|
|
470
|
+
this.#speechDuration = 0;
|
|
471
|
+
}
|
|
472
|
+
this.#speaking = false;
|
|
473
|
+
this.#currentTranscript = '';
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
if (pendingError) {
|
|
477
|
+
settle(pendingError);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
if (this.#closingWs || this.closed) {
|
|
481
|
+
settle();
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
this.#logger.warn(`Cartesia STT WebSocket closed: ${code} ${reason.toString()}`);
|
|
485
|
+
settle(
|
|
486
|
+
new APIConnectionError({
|
|
487
|
+
message: `Cartesia STT connection closed unexpectedly (code=${code})`,
|
|
488
|
+
options: { retryable: true },
|
|
489
|
+
}),
|
|
490
|
+
);
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
ws.on('error', (err) => {
|
|
494
|
+
if (this.closed) {
|
|
495
|
+
settle();
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
settle(new APIConnectionError({ message: err.message, options: { retryable: true } }));
|
|
499
|
+
});
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
#processStreamEvent(data: Exclude<STTEventMessage, { type: 'error' }>) {
|
|
504
|
+
if (data.request_id) {
|
|
505
|
+
this.#requestId = data.request_id;
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
switch (data.type) {
|
|
509
|
+
case 'connected':
|
|
510
|
+
return;
|
|
511
|
+
|
|
512
|
+
case 'turn.start': {
|
|
513
|
+
if (this.#speaking) return;
|
|
514
|
+
this.#speaking = true;
|
|
515
|
+
this.#currentTranscript = '';
|
|
516
|
+
if (!this.queue.closed)
|
|
517
|
+
this.queue.put({
|
|
518
|
+
type: stt.SpeechEventType.START_OF_SPEECH,
|
|
519
|
+
requestId: this.#requestId,
|
|
520
|
+
});
|
|
521
|
+
this.#logger.debug('Cartesia STT START_OF_SPEECH');
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
case 'turn.update': {
|
|
526
|
+
if (!this.#speaking) return;
|
|
527
|
+
const transcript = data.transcript;
|
|
528
|
+
if (!transcript) return;
|
|
529
|
+
// Only emit interim updates when the cumulative transcript actually
|
|
530
|
+
// changed; this avoids canceling preflight generation needlessly.
|
|
531
|
+
if (this.#currentTranscript === transcript) return;
|
|
532
|
+
this.#currentTranscript = transcript;
|
|
533
|
+
this.#sendTranscriptEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT, transcript);
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
case 'turn.eager_end': {
|
|
538
|
+
if (!this.#speaking) return;
|
|
539
|
+
const transcript = data.transcript;
|
|
540
|
+
if (!transcript) return;
|
|
541
|
+
this.#currentTranscript = transcript;
|
|
542
|
+
this.#sendTranscriptEvent(stt.SpeechEventType.PREFLIGHT_TRANSCRIPT, transcript);
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
case 'turn.resume':
|
|
547
|
+
// turn.resume has no transcript; re-emit the latest cumulative transcript
|
|
548
|
+
// as an interim event so the pipeline cancels the pending preflight.
|
|
549
|
+
if (!this.#speaking || !this.#currentTranscript) return;
|
|
550
|
+
this.#sendTranscriptEvent(stt.SpeechEventType.INTERIM_TRANSCRIPT, this.#currentTranscript);
|
|
551
|
+
return;
|
|
552
|
+
|
|
553
|
+
case 'turn.end': {
|
|
554
|
+
if (!this.#speaking) return;
|
|
555
|
+
const transcript = data.transcript;
|
|
556
|
+
|
|
557
|
+
this.#sendTranscriptEvent(stt.SpeechEventType.FINAL_TRANSCRIPT, transcript);
|
|
558
|
+
|
|
559
|
+
this.#speaking = false;
|
|
560
|
+
if (!this.queue.closed)
|
|
561
|
+
this.queue.put({
|
|
562
|
+
type: stt.SpeechEventType.END_OF_SPEECH,
|
|
563
|
+
requestId: this.#requestId,
|
|
564
|
+
});
|
|
565
|
+
this.#logger.debug('Cartesia STT END_OF_SPEECH');
|
|
566
|
+
this.#currentTranscript = '';
|
|
567
|
+
|
|
568
|
+
if (this.#speechDuration > 0 && !this.queue.closed) {
|
|
569
|
+
this.queue.put({
|
|
570
|
+
type: stt.SpeechEventType.RECOGNITION_USAGE,
|
|
571
|
+
requestId: this.#requestId,
|
|
572
|
+
recognitionUsage: { audioDuration: this.#speechDuration },
|
|
573
|
+
});
|
|
574
|
+
this.#speechDuration = 0;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
default:
|
|
581
|
+
this.#logger.warn('received unexpected message from Cartesia STT', { data });
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
#sendTranscriptEvent(eventType: stt.SpeechEventType, transcript: string) {
|
|
586
|
+
if (this.queue.closed) return;
|
|
587
|
+
this.queue.put({
|
|
588
|
+
type: eventType,
|
|
589
|
+
requestId: this.#requestId,
|
|
590
|
+
alternatives: [
|
|
591
|
+
{
|
|
592
|
+
// Cartesia STT only supports English at this time.
|
|
593
|
+
language: asLanguageCode('en'),
|
|
594
|
+
text: transcript,
|
|
595
|
+
startTime: 0,
|
|
596
|
+
endTime: 0,
|
|
597
|
+
confidence: 0,
|
|
598
|
+
},
|
|
599
|
+
],
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
#getCartesiaUrl(): string {
|
|
604
|
+
const params = new URLSearchParams({
|
|
605
|
+
model: this.#opts.model,
|
|
606
|
+
sample_rate: this.#opts.sampleRate.toString(),
|
|
607
|
+
encoding: AUDIO_ENCODING,
|
|
608
|
+
});
|
|
609
|
+
|
|
610
|
+
const wsBase = this.#opts.baseUrl.replace(/^http/, 'ws');
|
|
611
|
+
return `${wsBase}/stt/turns/websocket?${params.toString()}`;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
override close() {
|
|
615
|
+
super.close();
|
|
616
|
+
this.#ws?.close();
|
|
617
|
+
}
|
|
618
|
+
}
|