@sathamai/livekit-plugin 0.1.1 → 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.
package/README.md CHANGED
@@ -1,10 +1,11 @@
1
1
  # @sathamai/livekit-plugin
2
2
 
3
- Satham's realtime speech-to-speech model (satham-1) as a `RealtimeModel` for LiveKit Agents in Node.js
4
- (agents-js). Your LiveKit agent keeps its own instructions and tools; Satham hears the caller, ends
3
+ satham's realtime speech-to-speech model (satham-1) as a `RealtimeModel` for LiveKit Agents in Node.js
4
+ (agents-js). Your LiveKit agent keeps its own instructions and tools; satham hears the caller, ends
5
5
  turns, replies in speech and handles barge-in, so the `voice.AgentSession` needs no STT, LLM, TTS or
6
- VAD. The options follow LiveKit's OpenAI `RealtimeModel`, so moving an agent from OpenAI to Satham is
7
- mostly a one-line change.
6
+ VAD. The options follow LiveKit's OpenAI `RealtimeModel`, so moving an agent from OpenAI to satham is
7
+ mostly a one-line change. For a session with its own STT and LLM, `TTS` speaks with kural-1, satham's
8
+ text-to-speech model ([Text to speech](#text-to-speech)).
8
9
 
9
10
  Works with `@livekit/agents` 1.10 and `@livekit/rtc-node` 1.2; Node.js 20+.
10
11
 
@@ -14,7 +15,7 @@ npm install @sathamai/livekit-plugin @livekit/agents @livekit/rtc-node
14
15
 
15
16
  ## Use
16
17
 
17
- You pass your Satham endpoint and API key (or set `SATHAM_URL` and `SATHAM_API_KEY`); there is no
18
+ You pass your satham endpoint and API key (or set `SATHAM_URL` and `SATHAM_API_KEY`); there is no
18
19
  default server.
19
20
 
20
21
  ```ts
@@ -45,7 +46,7 @@ export default defineAgent({
45
46
  languageSwitch: 'auto',
46
47
  }),
47
48
  });
48
- // The agent's role and tools are Satham's instructions and tools, as they stand.
49
+ // The agent's role and tools are satham's instructions and tools, as they stand.
49
50
  const agent = new voice.Agent({
50
51
  instructions: 'You are Asha, who books site visits for Example Homes.',
51
52
  tools: { end_call: endCall },
@@ -60,7 +61,7 @@ cli.runApp(new ServerOptions({ agent: fileURLToPath(import.meta.url) }));
60
61
  - **Instructions and tools.** The LiveKit agent's instructions become the call's instructions and its
61
62
  `llm.tool()`s the call's tools, with nothing else to set. Both can change mid-call.
62
63
  - **The opening and fixed words.** With `greeting`, the agent says it first. Otherwise
63
- `session.generateReply({ instructions })` asks for a reply now (Satham's `response.create`), and the
64
+ `session.generateReply({ instructions })` asks for a reply now (satham's `response.create`), and the
64
65
  realtime session's `say(text)` speaks fixed words in the call's voice (`response.say`) with no TTS.
65
66
  agents-js 1.10's `AgentSession.say()` needs a TTS for realtime models, so call `say()` on the realtime
66
67
  session itself. With neither, the caller speaks first.
@@ -69,23 +70,23 @@ cli.runApp(new ServerOptions({ agent: fileURLToPath(import.meta.url) }));
69
70
  - **Language changes** are emitted as `session_updated` (`{ language, reason }`, the reason being
70
71
  `caller`, `reply` or `client`).
71
72
 
72
- ## From OpenAI RealtimeModel to Satham
73
+ ## From OpenAI RealtimeModel to satham
73
74
 
74
75
  <!-- openai -->
75
- | OpenAI `RealtimeModel` | Satham `RealtimeModel` | Supported | Notes |
76
+ | OpenAI `RealtimeModel` | satham `RealtimeModel` | Supported | Notes |
76
77
  | --- | --- | --- | --- |
77
78
  | `model` | `model` | yes | default `"satham-1"` |
78
- | `voice` | `voice` | yes | a Satham voice name, or a cloned voice's id |
79
+ | `voice` | `voice` | yes | a satham voice name, or a cloned voice's id |
79
80
  | `modalities` | `modalities` | yes | `["audio", "text"]`, `["audio"]`, or `["text"]`, which hands the words to the session's TTS as OpenAI's text mode does |
80
81
  | `temperature` | `temperature` | yes | |
81
- | `turnDetection` | `turnDetection` | yes | `server_vad` and `semantic_vad` are both Satham's endpointing; `None`/`null` leaves turns to LiveKit; Satham adds `barge_in`, `continue_within_ms`, ... |
82
- | `inputAudioNoiseReduction` | `inputAudioNoiseReduction` | yes | `near_field` or `far_field`; `"none"` turns it off, and null keeps the server's default (on); Satham adds `strength_db` and `apply_to_transcription` |
83
- | `inputAudioTranscription` | `inputAudioTranscription` | partly | `enabled` and `code_mixed`; Satham transcribes with its own models, so OpenAI's `model` and `prompt` are ignored |
82
+ | `turnDetection` | `turnDetection` | yes | `server_vad` and `semantic_vad` are both satham's endpointing; `None`/`null` leaves turns to LiveKit; satham adds `barge_in`, `continue_within_ms`, ... |
83
+ | `inputAudioNoiseReduction` | `inputAudioNoiseReduction` | yes | `near_field` or `far_field`; `"none"` turns it off, and null keeps the server's default (on); satham adds `strength_db` and `apply_to_transcription` |
84
+ | `inputAudioTranscription` | `inputAudioTranscription` | partly | `enabled` and `code_mixed`; satham transcribes with its own models, so OpenAI's `model` and `prompt` are ignored |
84
85
  | `maxResponseOutputTokens` | `maxResponseOutputTokens` | yes | or `"inf"` |
85
86
  | `speed` | `speed` | yes | |
86
87
  | `toolChoice` | `toolChoice` | yes | preview: needs a server with tool support |
87
- | `apiKey` | `apiKey` | yes | your Satham key |
88
- | `baseURL` | `url` | yes | your Satham endpoint |
88
+ | `apiKey` | `apiKey` | yes | your satham key |
89
+ | `baseURL` | `url` | yes | your satham endpoint |
89
90
  | Agent instructions | Agent instructions | yes | can change mid-call |
90
91
  | `generateReply()` | `generateReply()` | yes | `response.create`; `instructions` guide that reply alone |
91
92
  | `say()` | `RealtimeSession.say()` | yes | `response.say`, no TTS needed (agents-js: call it on the realtime session) |
@@ -101,7 +102,7 @@ Every option of `new RealtimeModel({...})` and `updateOptions({...})` besides `u
101
102
  model tells LiveKit it does, so they are fixed for a model once made. Controls you leave out are not
102
103
  sent; values are checked against these ranges, or the server's from `GET /v1/info`.
103
104
 
104
- The controls marked "needs session controls" need a Satham server with session controls (its
105
+ The controls marked "needs session controls" need a satham server with session controls (its
105
106
  `GET /v1/info` lists `controls`, as the server does since 2026-11-16); an older server refuses them
106
107
  when the call starts. `greeting` and `agent` belong to the start of a call. Setting
107
108
  `input_audio_noise_reduction`'s `mode` alone resets `strength_db` to that mode's preset, so send both
@@ -165,7 +166,7 @@ preset on the server and is not needed.
165
166
  mode; give the session a `tts`.
166
167
  - **`turnDetection: null`.** LiveKit's own turn detection ends each turn: the plugin commits the
167
168
  caller's audio, and `generateReply()` returns the reply.
168
- - **Tools (preview: they need a Satham server with tool support).** Each call the agent makes runs
169
+ - **Tools (preview: they need a satham server with tool support).** Each call the agent makes runs
169
170
  your tool; its result goes back to the server, which replies unless the tool returned nothing.
170
171
  agents-js writes a returned value as JSON.
171
172
  - **Interruptions.** The caller speaking over the agent interrupts it and the playout stops at once.
@@ -173,3 +174,36 @@ preset on the server and is not needed.
173
174
  SIP calls); set it to `null` where echo cancellation is good.
174
175
  - **Not supported:** video, and reconnection (a dropped connection ends the call with an
175
176
  unrecoverable error).
177
+
178
+ ## Text to speech
179
+
180
+ `TTS` gives an `AgentSession` with its own STT and LLM satham's voices, spoken by kural-1, satham's
181
+ text-to-speech model:
182
+
183
+ ```ts
184
+ import { voice } from '@livekit/agents';
185
+ import * as satham from '@sathamai/livekit-plugin';
186
+
187
+ const session = new voice.AgentSession({
188
+ stt,
189
+ llm,
190
+ // SATHAM_URL and SATHAM_API_KEY, or url and apiKey here
191
+ tts: new satham.TTS({ voice: 'malar', language: 'ta', tone: 'professional' }),
192
+ });
193
+ ```
194
+
195
+ - **Streamed, a sentence at a time.** kural-1 takes whole texts, so the session splits each reply into
196
+ sentences (its `tts.StreamAdapter`, as for any TTS without streaming input), and the plugin asks for
197
+ them one at a time. Each comes back streamed as raw PCM and goes out frame by frame as it arrives,
198
+ so the audio starts as soon as it is made. 24 kHz, mono.
199
+ - **Options:** `url`, `apiKey`, `voice` (a named voice such as `naina`, `malar` or `vikram`, or an
200
+ alias such as `hi-female`), `language`, `tone`, `pace`, `instructions`, `breaths`, `naturalPauses` and `model`, as in
201
+ `@sathamai/sdk`'s `audio.speech` (its README lists the values). `tts.updateOptions({...})` changes
202
+ them from the next sentence on; set one to `undefined` to clear it. A pause marker in the text
203
+ (`<break time="0.5s"/>`, 0.1 to 3 seconds) is spoken as that much silence. `instructions` cannot be combined
204
+ with `tone` or `pace`.
205
+ - **Errors** reach the session as LiveKit's own: `APIStatusError` for a refusal (401 and 400 are not
206
+ retried; 429 and 5xx are, as the session's `connOptions.ttsConnOptions` say), `APIConnectionError`
207
+ for a failed connection, and `APITimeoutError` when no audio comes within `timeoutMs`. A sentence cut
208
+ off part-way is not retried, so no one hears its start twice.
209
+ - **On its own:** `await tts.synthesize('வணக்கம்!').collect()` is one `AudioFrame`.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Satham speech-to-speech (satham-1) for LiveKit Agents (agents-js).
2
+ * satham for LiveKit Agents (agents-js): speech-to-speech (satham-1) as a `RealtimeModel`, and text
3
+ * to speech (kural-1, satham's text-to-speech model) as a `TTS`.
3
4
  *
4
5
  * ```ts
5
6
  * import { voice } from '@livekit/agents';
@@ -7,6 +8,11 @@
7
8
  *
8
9
  * const session = new voice.AgentSession({ llm: new satham.RealtimeModel({ greeting: 'Hello!' }) });
9
10
  * await session.start({ agent: new voice.Agent({ instructions: role, tools }), room: ctx.room });
11
+ *
12
+ * // Or your own STT and LLM, with satham's voices:
13
+ * const tts = new satham.TTS({ voice: 'malar', language: 'ta' });
14
+ * const pipeline = new voice.AgentSession({ stt, llm, tts });
10
15
  * ```
11
16
  */
12
17
  export { INPUT_SAMPLE_RATE, type OptionsUpdate, RealtimeModel, type RealtimeModelOptions, RealtimeSession, } from './realtime.js';
18
+ export { ChunkedStream, TTS, type TTSOptions, type TTSVoiceOptions } from './tts.js';
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
- * Satham speech-to-speech (satham-1) for LiveKit Agents (agents-js).
2
+ * satham for LiveKit Agents (agents-js): speech-to-speech (satham-1) as a `RealtimeModel`, and text
3
+ * to speech (kural-1, satham's text-to-speech model) as a `TTS`.
3
4
  *
4
5
  * ```ts
5
6
  * import { voice } from '@livekit/agents';
@@ -7,6 +8,11 @@
7
8
  *
8
9
  * const session = new voice.AgentSession({ llm: new satham.RealtimeModel({ greeting: 'Hello!' }) });
9
10
  * await session.start({ agent: new voice.Agent({ instructions: role, tools }), room: ctx.room });
11
+ *
12
+ * // Or your own STT and LLM, with satham's voices:
13
+ * const tts = new satham.TTS({ voice: 'malar', language: 'ta' });
14
+ * const pipeline = new voice.AgentSession({ stt, llm, tts });
10
15
  * ```
11
16
  */
12
17
  export { INPUT_SAMPLE_RATE, RealtimeModel, RealtimeSession, } from './realtime.js';
18
+ export { ChunkedStream, TTS } from './tts.js';
@@ -1,16 +1,16 @@
1
1
  /**
2
- * Satham's speech-to-speech model as a LiveKit Agents (agents-js) `RealtimeModel`.
2
+ * satham's speech-to-speech model as a LiveKit Agents (agents-js) `RealtimeModel`.
3
3
  *
4
- * Satham hears the caller, decides when a turn ends, replies in speech and handles barge-in on the
4
+ * satham hears the caller, decides when a turn ends, replies in speech and handles barge-in on the
5
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:
6
+ * realtime session is one satham call:
7
7
  *
8
8
  * - the LiveKit agent's instructions are the call's role and its tools the call's tools, handed over
9
9
  * when LiveKit creates the session; both can change mid-call. The agent speaks first when the model
10
10
  * has a `greeting`, or when LiveKit asks (`session.generateReply()`, sent as `response.create`);
11
11
  * - `RealtimeSession.say(text)` speaks fixed words in the call's voice (`response.say`), with no TTS;
12
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
13
+ * LiveKit's OpenAI realtime plugin has them, so moving an agent from OpenAI to satham is mostly a
14
14
  * one-line change; `updateOptions()` changes any of them mid-call;
15
15
  * - caller audio is resampled to 16 kHz mono and streamed; the agent's audio, its text and the caller's
16
16
  * transcripts come back as LiveKit generations and transcription events. With `modalities: ['text']`
@@ -25,21 +25,21 @@
25
25
  import { llm } from '@livekit/agents';
26
26
  import { AudioFrame } from '@livekit/rtc-node';
27
27
  import { type Controls, type Session as SathamSession } from '@sathamai/sdk';
28
- /** Caller audio goes to Satham as 16 kHz mono 16-bit PCM. */
28
+ /** Caller audio goes to satham as 16 kHz mono 16-bit PCM. */
29
29
  export declare const INPUT_SAMPLE_RATE = 16000;
30
30
  /** How long `generateReply` and `say` wait for the reply to start. */
31
31
  export declare const REPLY_TIMEOUT_MS = 10000;
32
32
  /**
33
- * Every Satham control (see `Controls` in `@sathamai/sdk`): OpenAI's names (`model`, `voice`,
33
+ * Every satham control (see `Controls` in `@sathamai/sdk`): OpenAI's names (`model`, `voice`,
34
34
  * `modalities`, `turnDetection`, `temperature`, `inputAudioNoiseReduction`, `inputAudioTranscription`,
35
- * `maxResponseOutputTokens`, `speed`, `toolChoice`) and Satham's own (`greeting`, `language`,
35
+ * `maxResponseOutputTokens`, `speed`, `toolChoice`) and satham's own (`greeting`, `language`,
36
36
  * `languageSwitch`, `voiceOnLanguageSwitch`, `breaths`, `naturalPauses`, `continuation`, `phrasing`,
37
37
  * `normaliseNumbers`, `pronunciations`, `topP`, `tone`, `repeatGuard`, `driftGuard`, and `agent`, an
38
38
  * optional preset agent on the server). `modalities`, `turnDetection` and `inputAudioTranscription` also
39
39
  * decide what the model tells LiveKit it does, so they are fixed for a model once made.
40
40
  */
41
41
  export interface RealtimeModelOptions extends Controls {
42
- /** Your Satham endpoint (`wss://...` or `https://...`); `$SATHAM_URL`. */
42
+ /** Your satham endpoint (`wss://...` or `https://...`); `$SATHAM_URL`. */
43
43
  url?: string;
44
44
  /** Your API key; `$SATHAM_API_KEY`. */
45
45
  apiKey?: string;
@@ -52,7 +52,7 @@ export interface RealtimeModelOptions extends Controls {
52
52
  export type OptionsUpdate = Controls & {
53
53
  toolChoice?: llm.ToolChoice | null;
54
54
  };
55
- /** Satham (satham-1) for `voice.AgentSession({ llm })`. */
55
+ /** satham (satham-1) for `voice.AgentSession({ llm })`. */
56
56
  export declare class RealtimeModel extends llm.RealtimeModel {
57
57
  #private;
58
58
  constructor(options?: RealtimeModelOptions);
@@ -65,7 +65,7 @@ export declare class RealtimeModel extends llm.RealtimeModel {
65
65
  close(): Promise<void>;
66
66
  }
67
67
  /**
68
- * One Satham call inside a LiveKit `AgentSession`. Besides the standard realtime events it emits
68
+ * One satham call inside a LiveKit `AgentSession`. Besides the standard realtime events it emits
69
69
  * `session_updated` (when the call's language changes) and `satham_server_event_received` (every
70
70
  * server event).
71
71
  */
package/dist/realtime.js CHANGED
@@ -1,16 +1,16 @@
1
1
  /**
2
- * Satham's speech-to-speech model as a LiveKit Agents (agents-js) `RealtimeModel`.
2
+ * satham's speech-to-speech model as a LiveKit Agents (agents-js) `RealtimeModel`.
3
3
  *
4
- * Satham hears the caller, decides when a turn ends, replies in speech and handles barge-in on the
4
+ * satham hears the caller, decides when a turn ends, replies in speech and handles barge-in on the
5
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:
6
+ * realtime session is one satham call:
7
7
  *
8
8
  * - the LiveKit agent's instructions are the call's role and its tools the call's tools, handed over
9
9
  * when LiveKit creates the session; both can change mid-call. The agent speaks first when the model
10
10
  * has a `greeting`, or when LiveKit asks (`session.generateReply()`, sent as `response.create`);
11
11
  * - `RealtimeSession.say(text)` speaks fixed words in the call's voice (`response.say`), with no TTS;
12
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
13
+ * LiveKit's OpenAI realtime plugin has them, so moving an agent from OpenAI to satham is mostly a
14
14
  * one-line change; `updateOptions()` changes any of them mid-call;
15
15
  * - caller audio is resampled to 16 kHz mono and streamed; the agent's audio, its text and the caller's
16
16
  * transcripts come back as LiveKit generations and transcription events. With `modalities: ['text']`
@@ -25,7 +25,7 @@
25
25
  import { AudioByteStream, llm, log, stream } from '@livekit/agents';
26
26
  import { AudioFrame, AudioResampler } from '@livekit/rtc-node';
27
27
  import { Client, responseCreate, responseSay, sessionUpdate, toolResult, toWire, } from '@sathamai/sdk';
28
- /** Caller audio goes to Satham as 16 kHz mono 16-bit PCM. */
28
+ /** Caller audio goes to satham as 16 kHz mono 16-bit PCM. */
29
29
  export const INPUT_SAMPLE_RATE = 16_000;
30
30
  /** How long `generateReply` and `say` wait for the reply to start. */
31
31
  export const REPLY_TIMEOUT_MS = 10_000;
@@ -60,7 +60,7 @@ function controlsOf(options) {
60
60
  function disabled(value) {
61
61
  return value === null || (typeof value === 'object' && value.enabled === false);
62
62
  }
63
- /** Satham (satham-1) for `voice.AgentSession({ llm })`. */
63
+ /** satham (satham-1) for `voice.AgentSession({ llm })`. */
64
64
  export class RealtimeModel extends llm.RealtimeModel {
65
65
  /** @internal */
66
66
  controls;
@@ -132,7 +132,7 @@ export class RealtimeModel extends llm.RealtimeModel {
132
132
  }
133
133
  }
134
134
  /**
135
- * One Satham call inside a LiveKit `AgentSession`. Besides the standard realtime events it emits
135
+ * One satham call inside a LiveKit `AgentSession`. Besides the standard realtime events it emits
136
136
  * `session_updated` (when the call's language changes) and `satham_server_event_received` (every
137
137
  * server event).
138
138
  */
@@ -222,7 +222,7 @@ export class RealtimeSession extends llm.RealtimeSession {
222
222
  this.#closeGeneration();
223
223
  if (!this.#closing) {
224
224
  const reason = call.endReason ?? `closed (${code})`;
225
- this.#emitError(new Error(`the Satham call ended: ${reason}`), false);
225
+ this.#emitError(new Error(`the satham call ended: ${reason}`), false);
226
226
  }
227
227
  });
228
228
  for (const item of this.#queued.splice(0))
@@ -247,7 +247,7 @@ export class RealtimeSession extends llm.RealtimeSession {
247
247
  call.send(item);
248
248
  }
249
249
  catch (error) {
250
- this.#logger.debug({ error }, 'Satham send after the call ended');
250
+ this.#logger.debug({ error }, 'satham send after the call ended');
251
251
  }
252
252
  }
253
253
  #emitError(error, recoverable) {
@@ -327,7 +327,7 @@ export class RealtimeSession extends llm.RealtimeSession {
327
327
  this.#openCalls.add(event.callId);
328
328
  this.#remember(call);
329
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');
330
+ this.#logger.warn({ name: event.name }, 'satham tool call outside its reply; answering it as failed');
331
331
  this.#openCalls.delete(event.callId);
332
332
  this.#send(toolResult(event.callId, 'error: the call came outside a reply'));
333
333
  return;
@@ -352,7 +352,7 @@ export class RealtimeSession extends llm.RealtimeSession {
352
352
  }
353
353
  return;
354
354
  }
355
- this.#logger.warn({ code: event.code }, `Satham error: ${event.message}`);
355
+ this.#logger.warn({ code: event.code }, `satham error: ${event.message}`);
356
356
  this.#emitError(new Error(`${event.code}: ${event.message}`), !event.fatal);
357
357
  return;
358
358
  }
@@ -448,7 +448,7 @@ export class RealtimeSession extends llm.RealtimeSession {
448
448
  }
449
449
  }
450
450
  async updateChatCtx(chatCtx) {
451
- // Satham keeps the conversation itself; what LiveKit adds that the server needs are the results
451
+ // satham keeps the conversation itself; what LiveKit adds that the server needs are the results
452
452
  // of the tool calls it ran.
453
453
  for (const item of chatCtx.items) {
454
454
  if (item instanceof llm.FunctionCallOutput && this.#openCalls.has(item.callId)) {
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
+ }
package/dist/tts.js ADDED
@@ -0,0 +1,204 @@
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 { APIConnectionError, APIStatusError, APITimeoutError, AudioByteStream, DEFAULT_API_CONNECT_OPTIONS, shortuuid, tts, } from '@livekit/agents';
15
+ import { Client, SathamError, SPEECH_SAMPLE_RATE } from '@sathamai/sdk';
16
+ /** Frames of 50 ms go to LiveKit. */
17
+ const FRAME_SAMPLES = SPEECH_SAMPLE_RATE / 20;
18
+ function checked(voice) {
19
+ if (voice.instructions != null && (voice.tone != null || voice.pace != null)) {
20
+ throw new TypeError('satham.TTS: instructions cannot be combined with tone or pace');
21
+ }
22
+ return voice;
23
+ }
24
+ /** One request at a time, first come first served. */
25
+ class Turns {
26
+ #busy = false;
27
+ #queue = [];
28
+ /** Resolves to the release once it is this caller's turn; rejects if `signal` aborts first. */
29
+ take(signal) {
30
+ return new Promise((resolve, reject) => {
31
+ if (signal.aborted)
32
+ return reject(signal.reason);
33
+ const grant = () => {
34
+ signal.removeEventListener('abort', onAbort);
35
+ let released = false;
36
+ resolve(() => {
37
+ if (released)
38
+ return;
39
+ released = true;
40
+ const next = this.#queue.shift();
41
+ if (next)
42
+ next();
43
+ else
44
+ this.#busy = false;
45
+ });
46
+ };
47
+ const onAbort = () => {
48
+ const at = this.#queue.indexOf(grant);
49
+ if (at >= 0)
50
+ this.#queue.splice(at, 1);
51
+ reject(signal.reason);
52
+ };
53
+ if (!this.#busy) {
54
+ this.#busy = true;
55
+ grant();
56
+ return;
57
+ }
58
+ this.#queue.push(grant);
59
+ signal.addEventListener('abort', onAbort, { once: true });
60
+ });
61
+ }
62
+ }
63
+ /**
64
+ * satham's text to speech (kural-1) for `voice.AgentSession({ stt, llm, tts })`. A pause marker in the
65
+ * text, `<break time="0.5s"/>` (0.1 to 3 seconds), is spoken as that much silence.
66
+ */
67
+ export class TTS extends tts.TTS {
68
+ label = 'satham.TTS';
69
+ /** @internal */
70
+ client;
71
+ #voice;
72
+ #turns = new Turns();
73
+ constructor(options = {}) {
74
+ super(SPEECH_SAMPLE_RATE, 1, { streaming: false });
75
+ const { url, apiKey, ...voice } = options;
76
+ this.#voice = checked(voice);
77
+ // Fail now, not at the first sentence: the client checks the URL.
78
+ this.client = new Client({ url, apiKey });
79
+ }
80
+ get model() {
81
+ return this.#voice.model ?? 'kural-1';
82
+ }
83
+ get provider() {
84
+ return 'satham';
85
+ }
86
+ /**
87
+ * Change the voice, language, tone, pace, instructions, breaths, natural pauses or model, from the next sentence on. Only the
88
+ * given options change; set one to `undefined` to clear it (`{ tone: undefined, instructions: '...' }`).
89
+ */
90
+ updateOptions(options) {
91
+ this.#voice = checked({ ...this.#voice, ...options });
92
+ }
93
+ /** Open a connection to the server before the first sentence (best effort), so it skips the handshake. */
94
+ prewarm() {
95
+ this.client.info().catch(() => undefined);
96
+ }
97
+ synthesize(text, connOptions, abortSignal) {
98
+ return new ChunkedStream(this, text, { ...this.#voice }, connOptions, abortSignal);
99
+ }
100
+ /** kural-1 takes whole texts: `AgentSession` wraps this TTS in `tts.StreamAdapter`, as you can. */
101
+ stream() {
102
+ throw new Error('satham.TTS takes whole texts: call synthesize(), or wrap it in tts.StreamAdapter');
103
+ }
104
+ /** @internal Wait for this TTS's turn to send a request; resolves to the release. */
105
+ turn(signal) {
106
+ return this.#turns.take(signal);
107
+ }
108
+ }
109
+ /**
110
+ * A failed request as the framework's API error, which the framework retries when `retryable`: an HTTP
111
+ * refusal as `APIStatusError` (retryable for 408, 429 and 5xx, as `APIStatusError` itself decides),
112
+ * anything else as `APIConnectionError`. Once part of the sentence has gone out, a retry would say it
113
+ * again from its start, so then it is not retried.
114
+ */
115
+ function apiError(error, played) {
116
+ if (!(error instanceof SathamError))
117
+ return error instanceof Error ? error : new Error(String(error));
118
+ const message = `satham speech: ${error.message}`;
119
+ if (error.status !== null) {
120
+ return new APIStatusError({
121
+ message,
122
+ options: {
123
+ statusCode: error.status,
124
+ requestId: error.requestId,
125
+ body: { code: error.code, param: error.param, retry_after: error.retryAfter },
126
+ // Speech switched off on the server does not come back on in a retry.
127
+ retryable: error.code === 'tts_unavailable' ? false : undefined,
128
+ },
129
+ });
130
+ }
131
+ return new APIConnectionError({ message, options: { retryable: !played } });
132
+ }
133
+ /** One sentence (or any text) spoken by kural-1, as LiveKit audio frames. */
134
+ export class ChunkedStream extends tts.ChunkedStream {
135
+ label = 'satham.ChunkedStream';
136
+ #tts;
137
+ #voice;
138
+ #connOptions;
139
+ constructor(owner, text, voice, connOptions, abortSignal) {
140
+ super(text, owner, connOptions, abortSignal);
141
+ this.#tts = owner;
142
+ this.#voice = voice;
143
+ this.#connOptions = connOptions ?? DEFAULT_API_CONNECT_OPTIONS;
144
+ }
145
+ async run() {
146
+ if (!this.inputText.trim())
147
+ return; // nothing to say (the server would refuse it)
148
+ const signal = this.abortSignal;
149
+ let release;
150
+ try {
151
+ release = await this.#tts.turn(signal);
152
+ }
153
+ catch {
154
+ return; // closed while it waited
155
+ }
156
+ if (signal.aborted)
157
+ return release();
158
+ // The request stops when LiveKit closes this stream (an interruption), or when no audio has come
159
+ // within the connection timeout.
160
+ const request = new AbortController();
161
+ const stop = () => request.abort(signal.reason);
162
+ signal.addEventListener('abort', stop, { once: true });
163
+ let timedOut = false;
164
+ const timer = setTimeout(() => {
165
+ timedOut = true;
166
+ request.abort();
167
+ }, this.#connOptions.timeoutMs);
168
+ let played = false;
169
+ try {
170
+ const audio = this.#tts.client.audio.speech.stream({ ...this.#voice, input: this.inputText, responseFormat: 'pcm' }, { signal: request.signal });
171
+ const frames = new AudioByteStream(SPEECH_SAMPLE_RATE, 1, FRAME_SAMPLES);
172
+ let requestId = '';
173
+ const put = (frame) => {
174
+ played = true;
175
+ this.queue.put({ requestId, segmentId: requestId, frame, final: false });
176
+ };
177
+ for await (const chunk of audio) {
178
+ if (!requestId) {
179
+ clearTimeout(timer);
180
+ requestId = audio.requestId ?? shortuuid('satham_');
181
+ }
182
+ for (const frame of frames.write(chunk))
183
+ put(frame);
184
+ }
185
+ for (const frame of frames.flush())
186
+ put(frame);
187
+ }
188
+ catch (error) {
189
+ if (signal.aborted)
190
+ return; // closed by LiveKit: not an error
191
+ if (timedOut) {
192
+ throw new APITimeoutError({
193
+ message: `satham speech: no audio within ${this.#connOptions.timeoutMs} ms`,
194
+ });
195
+ }
196
+ throw apiError(error, played);
197
+ }
198
+ finally {
199
+ clearTimeout(timer);
200
+ signal.removeEventListener('abort', stop);
201
+ release();
202
+ }
203
+ }
204
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@sathamai/livekit-plugin",
3
- "version": "0.1.1",
4
- "description": "Satham realtime speech-to-speech for LiveKit Agents (Node.js)",
3
+ "version": "0.1.2",
4
+ "description": "satham realtime speech-to-speech for LiveKit Agents (Node.js)",
5
5
  "keywords": [
6
6
  "satham",
7
7
  "livekit",
@@ -19,7 +19,7 @@
19
19
  "directory": "integrations/node/packages/livekit-plugin"
20
20
  },
21
21
  "license": "Apache-2.0",
22
- "author": "Satham",
22
+ "author": "satham",
23
23
  "type": "module",
24
24
  "main": "./dist/index.js",
25
25
  "types": "./dist/index.d.ts",
@@ -40,7 +40,7 @@
40
40
  "prepack": "npm run build"
41
41
  },
42
42
  "dependencies": {
43
- "@sathamai/sdk": "^0.1.1"
43
+ "@sathamai/sdk": "^0.1.2"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "@livekit/agents": "~1.10.0",