@sathamai/livekit-plugin 0.0.0-stage → 0.1.2

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.
@@ -0,0 +1,556 @@
1
+ /**
2
+ * satham's speech-to-speech model as a LiveKit Agents (agents-js) `RealtimeModel`.
3
+ *
4
+ * satham hears the caller, decides when a turn ends, replies in speech and handles barge-in on the
5
+ * server, so a `voice.AgentSession` given this model needs no STT, LLM, TTS or VAD of its own. One
6
+ * realtime session is one satham call:
7
+ *
8
+ * - the LiveKit agent's instructions are the call's role and its tools the call's tools, handed over
9
+ * when LiveKit creates the session; both can change mid-call. The agent speaks first when the model
10
+ * has a `greeting`, or when LiveKit asks (`session.generateReply()`, sent as `response.create`);
11
+ * - `RealtimeSession.say(text)` speaks fixed words in the call's voice (`response.say`), with no TTS;
12
+ * - every other setting is a control (`Controls` from `@sathamai/sdk`), with OpenAI's names where
13
+ * LiveKit's OpenAI realtime plugin has them, so moving an agent from OpenAI to satham is mostly a
14
+ * one-line change; `updateOptions()` changes any of them mid-call;
15
+ * - caller audio is resampled to 16 kHz mono and streamed; the agent's audio, its text and the caller's
16
+ * transcripts come back as LiveKit generations and transcription events. With `modalities: ['text']`
17
+ * the agent's words go to the session's TTS instead, as with OpenAI's text mode;
18
+ * - the caller speaking over the agent interrupts it; with `turnDetection: null` LiveKit's own turn
19
+ * detection ends each turn instead;
20
+ * - `llm.tool()` tools are sent as OpenAI-style function definitions; each call the agent makes is run
21
+ * by LiveKit, and its result goes back to the server, which then replies unless the tool returned
22
+ * nothing;
23
+ * - a change of language is emitted as `session_updated`.
24
+ */
25
+ import { AudioByteStream, llm, log, stream } from '@livekit/agents';
26
+ import { AudioFrame, AudioResampler } from '@livekit/rtc-node';
27
+ import { Client, responseCreate, responseSay, sessionUpdate, toolResult, toWire, } from '@sathamai/sdk';
28
+ /** Caller audio goes to satham as 16 kHz mono 16-bit PCM. */
29
+ export const INPUT_SAMPLE_RATE = 16_000;
30
+ /** How long `generateReply` and `say` wait for the reply to start. */
31
+ export const REPLY_TIMEOUT_MS = 10_000;
32
+ function toolChoice(choice) {
33
+ if (choice == null || typeof choice === 'string')
34
+ return choice ?? null;
35
+ return { type: 'function', function: { name: choice.function.name } };
36
+ }
37
+ /** LiveKit tools as OpenAI function definitions (provider tools are skipped). */
38
+ function functionSchemas(tools) {
39
+ const out = [];
40
+ for (const tool of tools?.flatten() ?? []) {
41
+ if (!llm.isFunctionTool(tool))
42
+ continue;
43
+ out.push({
44
+ type: 'function',
45
+ function: {
46
+ name: tool.name,
47
+ description: tool.description,
48
+ parameters: llm.toJsonSchema(tool.parameters),
49
+ },
50
+ });
51
+ }
52
+ return out;
53
+ }
54
+ /** The controls alone (not the connection options). */
55
+ function controlsOf(options) {
56
+ const { url: _u, apiKey: _k, toolChoice: _t, connectTimeoutMs: _c, ...controls } = options;
57
+ return controls;
58
+ }
59
+ /** Whether a control group is set to off (`null`, or `enabled: false`). */
60
+ function disabled(value) {
61
+ return value === null || (typeof value === 'object' && value.enabled === false);
62
+ }
63
+ /** satham (satham-1) for `voice.AgentSession({ llm })`. */
64
+ export class RealtimeModel extends llm.RealtimeModel {
65
+ /** @internal */
66
+ controls;
67
+ /** @internal */
68
+ toolChoice;
69
+ /** @internal */
70
+ client;
71
+ #sessions = new Set();
72
+ #limitsLoaded = null;
73
+ constructor(options = {}) {
74
+ const controls = controlsOf(options);
75
+ const modalities = controls.modalities ?? ['text', 'audio'];
76
+ super({
77
+ messageTruncation: false,
78
+ turnDetection: !disabled(controls.turnDetection),
79
+ userTranscription: !disabled(controls.inputAudioTranscription),
80
+ autoToolReplyGeneration: true,
81
+ audioOutput: modalities.includes('audio'),
82
+ manualFunctionCalls: false,
83
+ midSessionChatCtxUpdate: false,
84
+ midSessionInstructionsUpdate: true,
85
+ midSessionToolsUpdate: true,
86
+ perResponseToolChoice: false,
87
+ });
88
+ this.controls = controls;
89
+ this.toolChoice = options.toolChoice ?? null;
90
+ // Fail now, not when the first call starts: the client checks the URL, and the controls.
91
+ this.client = new Client({
92
+ url: options.url,
93
+ apiKey: options.apiKey,
94
+ openTimeoutMs: options.connectTimeoutMs,
95
+ });
96
+ toWire(controls, 'session.start', this.client.limits);
97
+ }
98
+ /** @internal Take the server's control ranges (`GET /v1/info`) once; keep the built-in ones else. */
99
+ loadLimits() {
100
+ this.#limitsLoaded ??= this.client.loadControls().then(() => undefined, () => undefined);
101
+ return this.#limitsLoaded;
102
+ }
103
+ get model() {
104
+ return this.controls.model ?? 'satham-1';
105
+ }
106
+ get provider() {
107
+ return 'satham';
108
+ }
109
+ label() {
110
+ return 'satham.RealtimeModel';
111
+ }
112
+ session(options = {}) {
113
+ if (options.turnDetectionDisabled)
114
+ log().warn('pass turnDetection: null to the model for manual turns');
115
+ const session = new RealtimeSession(this, options);
116
+ this.#sessions.add(session);
117
+ session.once('closed', () => this.#sessions.delete(session));
118
+ return session;
119
+ }
120
+ /** Change controls for new calls and every live one (`session.update`). */
121
+ updateOptions(changes) {
122
+ const controls = controlsOf(changes);
123
+ toWire(controls, 'session.update', this.client.limits);
124
+ Object.assign(this.controls, controls);
125
+ if (changes.toolChoice !== undefined)
126
+ this.toolChoice = changes.toolChoice;
127
+ for (const session of this.#sessions)
128
+ session.updateOptions(changes);
129
+ }
130
+ async close() {
131
+ await Promise.all([...this.#sessions].map((s) => s.close()));
132
+ }
133
+ }
134
+ /**
135
+ * One satham call inside a LiveKit `AgentSession`. Besides the standard realtime events it emits
136
+ * `session_updated` (when the call's language changes) and `satham_server_event_received` (every
137
+ * server event).
138
+ */
139
+ export class RealtimeSession extends llm.RealtimeSession {
140
+ /** The call's language, following `session.updated`. */
141
+ language;
142
+ #model;
143
+ #controls;
144
+ #toolChoice;
145
+ #textOnly;
146
+ #manualTurns;
147
+ #pendingReply = null;
148
+ #instructions;
149
+ #tools;
150
+ #chatCtx = llm.ChatContext.empty();
151
+ #call = null;
152
+ #queued = [];
153
+ #resampler = null;
154
+ #resamplerRate = 0;
155
+ #bstream = new AudioByteStream(INPUT_SAMPLE_RATE, 1, INPUT_SAMPLE_RATE / 50);
156
+ #generation = null;
157
+ #openCalls = new Set();
158
+ #bargedIn = false;
159
+ #closing = false;
160
+ #ended = false;
161
+ #logger = log();
162
+ #started;
163
+ constructor(model, options = {}) {
164
+ super(model);
165
+ this.#model = model;
166
+ this.#controls = { ...model.controls };
167
+ this.#toolChoice = model.toolChoice;
168
+ this.#textOnly = !model.capabilities.audioOutput;
169
+ this.#manualTurns = !model.capabilities.turnDetection;
170
+ this.#instructions = options.instructions;
171
+ this.#tools = options.tools ?? llm.ToolContext.empty();
172
+ const language = this.#controls.language;
173
+ this.language = language && language !== 'auto' ? language : null;
174
+ this.#started = this.#start();
175
+ }
176
+ /** The underlying `@sathamai/sdk` session, once the call has started. */
177
+ get call() {
178
+ return this.#call;
179
+ }
180
+ /** Resolves once the call has started (or failed to). */
181
+ get started() {
182
+ return this.#started;
183
+ }
184
+ async #start() {
185
+ // LiveKit hands over the instructions and tools when it creates the session, and applies them once
186
+ // more right after; let that settle before fixing them in session.start.
187
+ await new Promise((resolve) => setImmediate(resolve));
188
+ await this.#model.loadLimits();
189
+ if (this.#closing)
190
+ return;
191
+ const tools = functionSchemas(this.#tools);
192
+ const instructions = this.#instructions || undefined; // the LiveKit agent's; '' sends none
193
+ if (!instructions && !this.#controls.agent) {
194
+ this.#logger.warn('the LiveKit agent has no instructions: the call starts without a role');
195
+ }
196
+ try {
197
+ this.#call = await this.#model.client.connect({
198
+ ...this.#controls,
199
+ instructions,
200
+ sampleRate: INPUT_SAMPLE_RATE,
201
+ tools,
202
+ toolChoice: tools.length ? toolChoice(this.#toolChoice) : null,
203
+ });
204
+ }
205
+ catch (error) {
206
+ this.#ended = true; // stop queueing audio for a call that will not start
207
+ this.#queued = [];
208
+ if (!this.#closing)
209
+ this.#emitError(error, false);
210
+ return;
211
+ }
212
+ const call = this.#call;
213
+ if (this.#closing) {
214
+ await call.close();
215
+ return;
216
+ }
217
+ if (call.language)
218
+ this.language = call.language;
219
+ call.on('event', (event) => this.#onEvent(event));
220
+ call.on('close', (code) => {
221
+ this.#ended = true;
222
+ this.#closeGeneration();
223
+ if (!this.#closing) {
224
+ const reason = call.endReason ?? `closed (${code})`;
225
+ this.#emitError(new Error(`the satham call ended: ${reason}`), false);
226
+ }
227
+ });
228
+ for (const item of this.#queued.splice(0))
229
+ this.#sendNow(item);
230
+ }
231
+ #send(item) {
232
+ if (this.#closing || this.#ended)
233
+ return;
234
+ if (this.#call)
235
+ this.#sendNow(item);
236
+ else
237
+ this.#queued.push(item);
238
+ }
239
+ #sendNow(item) {
240
+ const call = this.#call;
241
+ if (!call || call.closed)
242
+ return;
243
+ try {
244
+ if (Buffer.isBuffer(item))
245
+ call.sendAudio(item);
246
+ else
247
+ call.send(item);
248
+ }
249
+ catch (error) {
250
+ this.#logger.debug({ error }, 'satham send after the call ended');
251
+ }
252
+ }
253
+ #emitError(error, recoverable) {
254
+ this.emit('error', {
255
+ type: 'realtime_model_error',
256
+ timestamp: Date.now(),
257
+ label: this.#model.label(),
258
+ error,
259
+ recoverable,
260
+ });
261
+ }
262
+ // -- server events -------------------------------------------------------------------------
263
+ #onEvent(event) {
264
+ this.emit('satham_server_event_received', event);
265
+ const gen = this.#generation;
266
+ switch (event.type) {
267
+ case 'response.audio': {
268
+ if (this.#textOnly || !gen || gen.responseId !== event.responseId || !event.data.length)
269
+ return;
270
+ gen.firstAudioAt ??= Date.now();
271
+ const samples = new Int16Array(event.data.buffer.slice(event.data.byteOffset, event.data.byteOffset + event.data.length - (event.data.length % 2)));
272
+ const channels = event.format.channels;
273
+ void gen.audioChannel.write(new AudioFrame(samples, event.format.sampleRate, channels, samples.length / channels));
274
+ return;
275
+ }
276
+ case 'response.text.delta':
277
+ if (gen && gen.responseId === event.responseId) {
278
+ gen.text += event.text;
279
+ void gen.textChannel.write(event.text);
280
+ }
281
+ return;
282
+ case 'input.speech_started':
283
+ if (this.#bargedIn)
284
+ this.#bargedIn = false;
285
+ else
286
+ this.emit('input_speech_started', {});
287
+ return;
288
+ case 'input.speech_stopped':
289
+ this.emit('input_speech_stopped', {
290
+ userTranscriptionEnabled: true,
291
+ });
292
+ return;
293
+ case 'transcript.partial':
294
+ case 'transcript.final': {
295
+ const isFinal = event.type === 'transcript.final';
296
+ if (isFinal && event.text)
297
+ this.#remember(llm.ChatMessage.create({ id: event.turnId, role: 'user', content: event.text }));
298
+ this.emit('input_audio_transcription_completed', {
299
+ itemId: event.turnId,
300
+ transcript: event.text,
301
+ isFinal,
302
+ });
303
+ return;
304
+ }
305
+ case 'response.started':
306
+ this.#startGeneration(event.responseId);
307
+ return;
308
+ case 'response.interrupted':
309
+ case 'response.done':
310
+ if (!gen || gen.responseId !== event.responseId)
311
+ return;
312
+ if (event.type === 'response.interrupted' && event.reason === 'barge_in') {
313
+ // The server stops a reply because the caller is speaking, then says so with
314
+ // input.speech_started. Tell LiveKit first, while the reply is open, so it cuts the playout.
315
+ this.#bargedIn = true;
316
+ this.emit('input_speech_started', {});
317
+ }
318
+ this.#finishGeneration(event.type === 'response.interrupted' ? gen.text : event.text || gen.text, event.type);
319
+ return;
320
+ case 'response.function_call': {
321
+ const call = llm.FunctionCall.create({
322
+ id: event.callId,
323
+ callId: event.callId,
324
+ name: event.name,
325
+ args: event.arguments,
326
+ });
327
+ this.#openCalls.add(event.callId);
328
+ this.#remember(call);
329
+ if (!gen || (event.responseId && gen.responseId !== event.responseId)) {
330
+ this.#logger.warn({ name: event.name }, 'satham tool call outside its reply; answering it as failed');
331
+ this.#openCalls.delete(event.callId);
332
+ this.#send(toolResult(event.callId, 'error: the call came outside a reply'));
333
+ return;
334
+ }
335
+ void gen.functionChannel.write(call);
336
+ return;
337
+ }
338
+ case 'session.updated':
339
+ if (event.language)
340
+ this.language = event.language;
341
+ this.emit('session_updated', event);
342
+ return;
343
+ case 'error':
344
+ if (event.code === 'response_in_progress') {
345
+ // With manual turns the server may already be answering the committed turn: that reply is
346
+ // the one LiveKit asked for. Otherwise nothing will start: say so.
347
+ const pending = this.#pendingReply;
348
+ if (pending && !this.#manualTurns) {
349
+ this.#pendingReply = null;
350
+ clearTimeout(pending.timer);
351
+ pending.reject(new llm.RealtimeError(event.message));
352
+ }
353
+ return;
354
+ }
355
+ this.#logger.warn({ code: event.code }, `satham error: ${event.message}`);
356
+ this.#emitError(new Error(`${event.code}: ${event.message}`), !event.fatal);
357
+ return;
358
+ }
359
+ }
360
+ #remember(item) {
361
+ const items = this.#chatCtx.items;
362
+ const at = items.findIndex((existing) => existing.id === item.id);
363
+ if (at >= 0)
364
+ items[at] = item;
365
+ else
366
+ items.push(item);
367
+ }
368
+ #startGeneration(responseId) {
369
+ this.#closeGeneration();
370
+ const gen = {
371
+ responseId,
372
+ messageChannel: stream.createStreamChannel(),
373
+ functionChannel: stream.createStreamChannel(),
374
+ textChannel: stream.createStreamChannel(),
375
+ audioChannel: stream.createStreamChannel(),
376
+ text: '',
377
+ startedAt: Date.now(),
378
+ };
379
+ // In text mode the words go to the session's TTS, as with OpenAI's text mode.
380
+ if (this.#textOnly)
381
+ void gen.audioChannel.close();
382
+ void gen.messageChannel.write({
383
+ messageId: responseId,
384
+ textStream: gen.textChannel.stream(),
385
+ audioStream: gen.audioChannel.stream(),
386
+ modalities: Promise.resolve(this.#textOnly ? ['text'] : ['audio', 'text']),
387
+ });
388
+ this.#generation = gen;
389
+ const event = {
390
+ messageStream: gen.messageChannel.stream(),
391
+ functionStream: gen.functionChannel.stream(),
392
+ userInitiated: false,
393
+ responseId,
394
+ };
395
+ const pending = this.#pendingReply;
396
+ this.#pendingReply = null;
397
+ if (pending) {
398
+ clearTimeout(pending.timer);
399
+ // A reply LiveKit asked for (generateReply) is handled by LiveKit itself; one asked for with
400
+ // say() outside LiveKit's own say() is played as a server reply.
401
+ event.userInitiated = !pending.played;
402
+ pending.resolve(event);
403
+ }
404
+ this.emit('generation_created', event);
405
+ }
406
+ #finishGeneration(text, how) {
407
+ const gen = this.#generation;
408
+ if (!gen)
409
+ return;
410
+ if (text) {
411
+ this.#remember(llm.ChatMessage.create({
412
+ id: gen.responseId,
413
+ role: 'assistant',
414
+ content: text,
415
+ interrupted: how === 'response.interrupted',
416
+ }));
417
+ }
418
+ this.#closeGeneration();
419
+ }
420
+ #closeGeneration() {
421
+ const gen = this.#generation;
422
+ this.#generation = null;
423
+ if (!gen)
424
+ return;
425
+ for (const channel of [gen.textChannel, gen.audioChannel, gen.functionChannel, gen.messageChannel]) {
426
+ if (!channel.closed)
427
+ void channel.close();
428
+ }
429
+ }
430
+ // -- llm.RealtimeSession -------------------------------------------------------------------
431
+ get chatCtx() {
432
+ return this.#chatCtx.copy();
433
+ }
434
+ get tools() {
435
+ return this.#tools;
436
+ }
437
+ /** The call's instructions: at the start, or mid-call (`session.update`). */
438
+ async updateInstructions(instructions) {
439
+ if (!this.#call) {
440
+ this.#instructions = instructions;
441
+ return;
442
+ }
443
+ if (instructions && instructions !== this.#instructions) {
444
+ this.#instructions = instructions;
445
+ const message = sessionUpdate({ instructions }, this.#model.client.limits);
446
+ if (message)
447
+ this.#send(message);
448
+ }
449
+ }
450
+ async updateChatCtx(chatCtx) {
451
+ // satham keeps the conversation itself; what LiveKit adds that the server needs are the results
452
+ // of the tool calls it ran.
453
+ for (const item of chatCtx.items) {
454
+ if (item instanceof llm.FunctionCallOutput && this.#openCalls.has(item.callId)) {
455
+ this.#openCalls.delete(item.callId);
456
+ this.#remember(item);
457
+ this.#send(toolResult(item.callId, item.output, item.replyRequired));
458
+ }
459
+ }
460
+ }
461
+ async updateTools(tools) {
462
+ const schemas = functionSchemas(tools);
463
+ const before = JSON.stringify(functionSchemas(this.#tools));
464
+ this.#tools = tools;
465
+ if (!this.#call || JSON.stringify(schemas) === before)
466
+ return;
467
+ const message = sessionUpdate({ tools: schemas });
468
+ if (message)
469
+ this.#send(message);
470
+ }
471
+ /** Change the call's controls (`session.update`); before it starts, its start. */
472
+ updateOptions(options) {
473
+ if (options.toolChoice !== undefined) {
474
+ this.#toolChoice = options.toolChoice;
475
+ if (this.#call)
476
+ this.#send({ type: 'session.update', tool_choice: toolChoice(options.toolChoice) });
477
+ }
478
+ const changes = controlsOf(options);
479
+ const message = sessionUpdate(changes, this.#model.client.limits);
480
+ if (!message)
481
+ return;
482
+ if (this.#call)
483
+ this.#send(message);
484
+ else
485
+ Object.assign(this.#controls, changes);
486
+ }
487
+ pushAudio(frame) {
488
+ if (this.#closing)
489
+ return;
490
+ let frames = [frame];
491
+ if (frame.sampleRate !== INPUT_SAMPLE_RATE || frame.channels !== 1) {
492
+ if (!this.#resampler || this.#resamplerRate !== frame.sampleRate) {
493
+ this.#resampler = new AudioResampler(frame.sampleRate, INPUT_SAMPLE_RATE, 1);
494
+ this.#resamplerRate = frame.sampleRate;
495
+ }
496
+ frames = this.#resampler.push(frame);
497
+ }
498
+ for (const f of frames) {
499
+ for (const chunk of this.#bstream.write(f.data)) {
500
+ this.#send(Buffer.from(chunk.data.buffer, chunk.data.byteOffset, chunk.data.byteLength));
501
+ }
502
+ }
503
+ }
504
+ /** A reply now (`response.create`); `instructions` guide this reply alone. */
505
+ async generateReply(instructions) {
506
+ return this.#request(responseCreate(instructions || undefined), false);
507
+ }
508
+ /**
509
+ * Speak `text` as it is, in the call's voice (`response.say`), with no TTS. agents-js 1.10's
510
+ * `AgentSession.say()` needs a TTS for realtime models, so call this on the realtime session; the
511
+ * reply is played like any server reply.
512
+ */
513
+ async say(text) {
514
+ return this.#request(responseSay(text), true);
515
+ }
516
+ #request(message, played) {
517
+ if (this.#pendingReply) {
518
+ clearTimeout(this.#pendingReply.timer);
519
+ this.#pendingReply.reject(new llm.RealtimeError('replaced by a newer request'));
520
+ }
521
+ return new Promise((resolve, reject) => {
522
+ const timer = setTimeout(() => {
523
+ this.#pendingReply = null;
524
+ reject(new llm.RealtimeError('the server started no reply in time'));
525
+ }, REPLY_TIMEOUT_MS);
526
+ this.#pendingReply = { resolve, reject, timer, played };
527
+ this.#send(message);
528
+ });
529
+ }
530
+ async commitAudio() {
531
+ for (const chunk of this.#bstream.flush()) {
532
+ this.#send(Buffer.from(chunk.data.buffer, chunk.data.byteOffset, chunk.data.byteLength));
533
+ }
534
+ this.#send({ type: 'input.commit' });
535
+ }
536
+ async clearAudio() {
537
+ this.#bstream = new AudioByteStream(INPUT_SAMPLE_RATE, 1, INPUT_SAMPLE_RATE / 50);
538
+ }
539
+ async interrupt() {
540
+ if (this.#generation)
541
+ this.#send({ type: 'response.cancel' });
542
+ }
543
+ async truncate() {
544
+ // The server marks a reply cut off by barge-in itself.
545
+ }
546
+ async close() {
547
+ if (this.#closing)
548
+ return;
549
+ this.#closing = true;
550
+ this.#closeGeneration();
551
+ await this.#started;
552
+ await this.#call?.close();
553
+ await super.close();
554
+ this.emit('closed');
555
+ }
556
+ }
package/dist/tts.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ /**
2
+ * kural-1, satham's text-to-speech model, as a LiveKit Agents (agents-js) `TTS`.
3
+ *
4
+ * For a `voice.AgentSession` with its own STT and LLM. The session speaks each reply through satham's
5
+ * speech API (`POST /v1/audio/speech`) a sentence at a time: kural-1 takes whole texts, so the session
6
+ * wraps this TTS in its `tts.StreamAdapter`, which splits the reply into sentences, as it does for any
7
+ * TTS without streaming input. Each sentence comes back streamed, as raw PCM (`stream: true`,
8
+ * `response_format: 'pcm'`), and its frames go out as they arrive, so the audio starts as soon as it
9
+ * is made: 24 kHz, mono.
10
+ *
11
+ * One request runs at a time per `TTS`: the next sentence is asked for once the one before has
12
+ * arrived, which keeps a reply's sentences from queueing up against the server all at once.
13
+ */
14
+ import { type APIConnectOptions, tts } from '@livekit/agents';
15
+ import { type SpeechCreateParams } from '@sathamai/sdk';
16
+ /** The voice and its delivery: every option of `TTS` but the connection's. */
17
+ export interface TTSVoiceOptions {
18
+ /** A named voice (`'naina'`, `'malar'`, ...) or its alias (`'hi-female'`); by default the language's. */
19
+ voice?: SpeechCreateParams['voice'];
20
+ /**
21
+ * `'hi'`, `'ta'`, `'te'`, `'kn'`, `'bn'`, `'pa'` or `'en'`: the accent, and how numbers and amounts are
22
+ * read; by default each sentence's script decides.
23
+ */
24
+ language?: SpeechCreateParams['language'];
25
+ /** The delivery (`SPEECH_TONES`): `'professional'`, `'happy'`, ...; `'conversational'` by default. */
26
+ tone?: SpeechCreateParams['tone'];
27
+ /** `'slow'`, `'steady'` or `'fast'`: a light nudge, not an exact rate. */
28
+ pace?: SpeechCreateParams['pace'];
29
+ /** Free-text direction for the delivery, up to 500 characters, best effort; not with `tone` or `pace`. */
30
+ instructions?: string;
31
+ /** `true` keeps the breaths the voice takes, `false` trims them; by default the server's setting. */
32
+ breaths?: boolean;
33
+ /** `true` keeps the longer pauses inside a sentence, `false` shortens them; by default the server's setting. */
34
+ naturalPauses?: boolean;
35
+ /** `'kural-1'`, the default. */
36
+ model?: SpeechCreateParams['model'];
37
+ }
38
+ export interface TTSOptions extends TTSVoiceOptions {
39
+ /** Your satham endpoint (`https://...`); `$SATHAM_URL`. */
40
+ url?: string;
41
+ /** Your API key; `$SATHAM_API_KEY`. */
42
+ apiKey?: string;
43
+ }
44
+ /**
45
+ * satham's text to speech (kural-1) for `voice.AgentSession({ stt, llm, tts })`. A pause marker in the
46
+ * text, `<break time="0.5s"/>` (0.1 to 3 seconds), is spoken as that much silence.
47
+ */
48
+ export declare class TTS extends tts.TTS {
49
+ #private;
50
+ label: string;
51
+ constructor(options?: TTSOptions);
52
+ get model(): string;
53
+ get provider(): string;
54
+ /**
55
+ * Change the voice, language, tone, pace, instructions, breaths, natural pauses or model, from the next sentence on. Only the
56
+ * given options change; set one to `undefined` to clear it (`{ tone: undefined, instructions: '...' }`).
57
+ */
58
+ updateOptions(options: TTSVoiceOptions): void;
59
+ /** Open a connection to the server before the first sentence (best effort), so it skips the handshake. */
60
+ prewarm(): void;
61
+ synthesize(text: string, connOptions?: APIConnectOptions, abortSignal?: AbortSignal): ChunkedStream;
62
+ /** kural-1 takes whole texts: `AgentSession` wraps this TTS in `tts.StreamAdapter`, as you can. */
63
+ stream(): tts.SynthesizeStream;
64
+ }
65
+ /** One sentence (or any text) spoken by kural-1, as LiveKit audio frames. */
66
+ export declare class ChunkedStream extends tts.ChunkedStream {
67
+ #private;
68
+ label: string;
69
+ constructor(owner: TTS, text: string, voice: TTSVoiceOptions, connOptions?: APIConnectOptions, abortSignal?: AbortSignal);
70
+ protected run(): Promise<void>;
71
+ }