@livekit/agents-plugin-baseten 0.0.0-next-20260624041820

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +92 -0
  3. package/dist/index.cjs +48 -0
  4. package/dist/index.cjs.map +1 -0
  5. package/dist/index.d.cts +5 -0
  6. package/dist/index.d.ts +5 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +21 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/llm.cjs +156 -0
  11. package/dist/llm.cjs.map +1 -0
  12. package/dist/llm.d.cts +47 -0
  13. package/dist/llm.d.ts +47 -0
  14. package/dist/llm.d.ts.map +1 -0
  15. package/dist/llm.js +130 -0
  16. package/dist/llm.js.map +1 -0
  17. package/dist/llm.test.cjs +22 -0
  18. package/dist/llm.test.cjs.map +1 -0
  19. package/dist/llm.test.d.cts +2 -0
  20. package/dist/llm.test.d.ts +2 -0
  21. package/dist/llm.test.d.ts.map +1 -0
  22. package/dist/llm.test.js +21 -0
  23. package/dist/llm.test.js.map +1 -0
  24. package/dist/stt.cjs +287 -0
  25. package/dist/stt.cjs.map +1 -0
  26. package/dist/stt.d.cts +18 -0
  27. package/dist/stt.d.ts +18 -0
  28. package/dist/stt.d.ts.map +1 -0
  29. package/dist/stt.js +269 -0
  30. package/dist/stt.js.map +1 -0
  31. package/dist/stt.test.cjs +19 -0
  32. package/dist/stt.test.cjs.map +1 -0
  33. package/dist/stt.test.d.cts +2 -0
  34. package/dist/stt.test.d.ts +2 -0
  35. package/dist/stt.test.d.ts.map +1 -0
  36. package/dist/stt.test.js +18 -0
  37. package/dist/stt.test.js.map +1 -0
  38. package/dist/tts.cjs +162 -0
  39. package/dist/tts.cjs.map +1 -0
  40. package/dist/tts.d.cts +45 -0
  41. package/dist/tts.d.ts +45 -0
  42. package/dist/tts.d.ts.map +1 -0
  43. package/dist/tts.js +142 -0
  44. package/dist/tts.js.map +1 -0
  45. package/dist/tts.test.cjs +19 -0
  46. package/dist/tts.test.cjs.map +1 -0
  47. package/dist/tts.test.d.cts +2 -0
  48. package/dist/tts.test.d.ts +2 -0
  49. package/dist/tts.test.d.ts.map +1 -0
  50. package/dist/tts.test.js +18 -0
  51. package/dist/tts.test.js.map +1 -0
  52. package/dist/types.cjs +17 -0
  53. package/dist/types.cjs.map +1 -0
  54. package/dist/types.d.cts +69 -0
  55. package/dist/types.d.ts +69 -0
  56. package/dist/types.d.ts.map +1 -0
  57. package/dist/types.js +1 -0
  58. package/dist/types.js.map +1 -0
  59. package/package.json +68 -0
  60. package/src/index.ts +20 -0
  61. package/src/llm.test.ts +24 -0
  62. package/src/llm.ts +195 -0
  63. package/src/stt.test.ts +22 -0
  64. package/src/stt.ts +335 -0
  65. package/src/tts.test.ts +21 -0
  66. package/src/tts.ts +205 -0
  67. package/src/types.ts +70 -0
package/src/tts.ts ADDED
@@ -0,0 +1,205 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import {
5
+ type APIConnectOptions,
6
+ AudioByteStream,
7
+ shortuuid,
8
+ tts,
9
+ waitForAbort,
10
+ } from '@livekit/agents';
11
+ import type { AudioFrame } from '@livekit/rtc-node';
12
+ import type { BasetenTTSOptions } from './types.js';
13
+
14
+ const defaultTTSOptions: Partial<BasetenTTSOptions> = {
15
+ voice: 'tara',
16
+ language: 'en',
17
+ temperature: 0.6,
18
+ };
19
+
20
+ /**
21
+ * Baseten TTS implementation (streaming, 24kHz mono)
22
+ */
23
+ export class TTS extends tts.TTS {
24
+ private opts: BasetenTTSOptions;
25
+ label = 'baseten.TTS';
26
+ private abortController = new AbortController();
27
+ constructor(opts: Partial<BasetenTTSOptions> = {}) {
28
+ /**
29
+ * Baseten audio is 24kHz mono.
30
+ * The Orpheus model generates audio chunks that are processed as they arrive,
31
+ * which reduces latency and improves agent responsiveness.
32
+ */
33
+ super(24000, 1, { streaming: false });
34
+
35
+ // Apply defaults and environment fallbacks.
36
+ const apiKey = opts.apiKey ?? process.env.BASETEN_API_KEY;
37
+ const modelEndpoint = opts.modelEndpoint ?? process.env.BASETEN_MODEL_ENDPOINT;
38
+
39
+ if (!apiKey) {
40
+ throw new Error(
41
+ 'Baseten API key is required, either pass it as `apiKey` or set $BASETEN_API_KEY',
42
+ );
43
+ }
44
+ if (!modelEndpoint) {
45
+ throw new Error(
46
+ 'Baseten model endpoint is required, either pass it as `modelEndpoint` or set $BASETEN_MODEL_ENDPOINT',
47
+ );
48
+ }
49
+
50
+ this.opts = {
51
+ ...defaultTTSOptions,
52
+ ...opts,
53
+ apiKey,
54
+ modelEndpoint,
55
+ } as BasetenTTSOptions;
56
+ }
57
+
58
+ updateOptions(opts: Partial<Omit<BasetenTTSOptions, 'apiKey' | 'modelEndpoint'>>) {
59
+ this.opts = {
60
+ ...this.opts,
61
+ ...opts,
62
+ } as BasetenTTSOptions;
63
+ }
64
+
65
+ /**
66
+ * Synthesize speech for a given piece of text. Returns a `ChunkedStream`
67
+ * which will asynchronously fetch audio from Baseten and push frames into
68
+ * LiveKit's playback pipeline. If you need to cancel synthesis you can
69
+ * call {@link ChunkedStream.stop} on the returned object.
70
+ */
71
+ synthesize(
72
+ text: string,
73
+ connOptions?: APIConnectOptions,
74
+ abortSignal?: AbortSignal,
75
+ ): ChunkedStream {
76
+ const signal = abortSignal
77
+ ? AbortSignal.any([abortSignal, this.abortController.signal])
78
+ : this.abortController.signal;
79
+ return new ChunkedStream(this, text, this.opts, connOptions, signal);
80
+ }
81
+
82
+ stream(): tts.SynthesizeStream {
83
+ throw new Error('Streaming is not supported on Baseten TTS');
84
+ }
85
+
86
+ async close(): Promise<void> {
87
+ this.abortController.abort();
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Internal helper that performs the actual HTTP request and converts the
93
+ * response into audio frames. It inherits from `tts.ChunkedStream` to
94
+ * integrate with LiveKit's event and cancellation framework.
95
+ *
96
+ * This implementation streams audio chunks as they arrive from the Baseten
97
+ * model endpoint, processing them incrementally instead of waiting for the
98
+ * complete response.
99
+ */
100
+ export class ChunkedStream extends tts.ChunkedStream {
101
+ label = 'baseten.ChunkedStream';
102
+ private readonly opts: BasetenTTSOptions;
103
+
104
+ constructor(
105
+ tts: TTS,
106
+ text: string,
107
+ opts: BasetenTTSOptions,
108
+ connOptions?: APIConnectOptions,
109
+ abortSignal?: AbortSignal,
110
+ ) {
111
+ super(text, tts, connOptions, abortSignal);
112
+ this.opts = opts;
113
+ }
114
+
115
+ /**
116
+ * Execute the synthesis request. This method is automatically invoked
117
+ * by the base class when the stream starts. It performs a POST request
118
+ * to the configured `modelEndpoint` with the input text and optional
119
+ * parameters. Audio chunks are streamed as they arrive and transformed
120
+ * into a sequence of `AudioFrame` objects that are enqueued immediately
121
+ * for playback.
122
+ */
123
+ protected async run() {
124
+ const { apiKey, modelEndpoint, voice, language, temperature, maxTokens } = this.opts;
125
+ const payload: Record<string, unknown> = {
126
+ prompt: this.inputText,
127
+ };
128
+ if (voice) payload.voice = voice;
129
+ if (language) payload.language = language;
130
+ if (temperature !== undefined) payload.temperature = temperature;
131
+ if (maxTokens !== undefined) payload.max_tokens = maxTokens;
132
+
133
+ const headers: Record<string, string> = {
134
+ Authorization: `Api-Key ${apiKey}`,
135
+ 'Content-Type': 'application/json',
136
+ };
137
+
138
+ const response = await fetch(modelEndpoint, {
139
+ method: 'POST',
140
+ headers,
141
+ body: JSON.stringify(payload),
142
+ signal: this.abortSignal,
143
+ });
144
+
145
+ if (!response.ok) {
146
+ let errText: string;
147
+ try {
148
+ errText = await response.text();
149
+ } catch {
150
+ errText = response.statusText;
151
+ }
152
+ throw new Error(`Baseten TTS request failed: ${response.status} ${errText}`);
153
+ }
154
+
155
+ // Stream the response body as chunks arrive
156
+ if (!response.body) {
157
+ throw new Error('Response body is not available for streaming');
158
+ }
159
+
160
+ const requestId = shortuuid();
161
+ const audioByteStream = new AudioByteStream(24000, 1);
162
+ const reader = response.body.getReader();
163
+
164
+ try {
165
+ let lastFrame: AudioFrame | undefined;
166
+ const sendLastFrame = (segmentId: string, final: boolean) => {
167
+ if (lastFrame) {
168
+ this.queue.put({ requestId, segmentId, frame: lastFrame, final });
169
+ lastFrame = undefined;
170
+ }
171
+ };
172
+
173
+ // waitForAbort internally sets up an abort listener on the abort signal
174
+ // we need to put it outside loop to avoid constant re-registration of the listener
175
+ const abortPromise = waitForAbort(this.abortSignal);
176
+
177
+ while (!this.abortSignal.aborted) {
178
+ const result = await Promise.race([reader.read(), abortPromise]);
179
+
180
+ if (result === undefined) break; // aborted
181
+
182
+ const { done, value } = result;
183
+
184
+ if (done) {
185
+ break;
186
+ }
187
+
188
+ // Process the chunk and convert to audio frames
189
+ // Convert Uint8Array to ArrayBuffer for AudioByteStream
190
+ const frames = audioByteStream.write(value.buffer);
191
+
192
+ for (const frame of frames) {
193
+ sendLastFrame(requestId, false);
194
+ lastFrame = frame;
195
+ }
196
+ }
197
+
198
+ // Send the final frame
199
+ sendLastFrame(requestId, true);
200
+ } finally {
201
+ reader.releaseLock();
202
+ this.queue.close();
203
+ }
204
+ }
205
+ }
package/src/types.ts ADDED
@@ -0,0 +1,70 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * Baseten plugin types and interfaces
7
+ */
8
+
9
+ /**
10
+ * Options for configuring the Baseten LLM
11
+ * Since Baseten provides an OpenAI-compatible API, these options
12
+ * map to standard OpenAI parameters.
13
+ */
14
+ export interface BasetenLLMOptions {
15
+ apiKey?: string;
16
+ model: string;
17
+ temperature?: number;
18
+ /** Nucleus sampling parameter. Forwarded to Baseten as `top_p`. */
19
+ topP?: number;
20
+ maxTokens?: number;
21
+ /**
22
+ * Penalty for new tokens based on whether they appear in the text so far.
23
+ * Forwarded to Baseten as `presence_penalty`.
24
+ */
25
+ presencePenalty?: number;
26
+ /**
27
+ * Penalty for new tokens based on their frequency in the text so far.
28
+ * Forwarded to Baseten as `frequency_penalty`.
29
+ */
30
+ frequencyPenalty?: number;
31
+ user?: string;
32
+ toolChoice?: 'none' | 'auto' | 'required' | { type: 'function'; function: { name: string } };
33
+ parallelToolCalls?: boolean;
34
+ }
35
+
36
+ /**
37
+ * Options for configuring the Baseten STT service
38
+ */
39
+ export interface BasetenSttOptions {
40
+ apiKey: string;
41
+ /** @deprecated Use modelEndpoint instead */
42
+ modelId?: string;
43
+ /** Full WebSocket endpoint URL (e.g., from Baseten dashboard). Takes priority over modelId. */
44
+ modelEndpoint?: string;
45
+ environment?: string;
46
+ encoding?: string;
47
+ sampleRate?: number;
48
+ bufferSizeSeconds?: number;
49
+ vadThreshold?: number;
50
+ vadMinSilenceDurationMs?: number;
51
+ vadSpeechPadMs?: number;
52
+ enablePartialTranscripts?: boolean;
53
+ partialTranscriptIntervalS?: number;
54
+ finalTranscriptMaxDurationS?: number;
55
+ audioLanguage?: string;
56
+ prompt?: string;
57
+ languageDetectionOnly?: boolean;
58
+ }
59
+
60
+ /**
61
+ * Options for configuring the Baseten TTS service
62
+ */
63
+ export interface BasetenTTSOptions {
64
+ apiKey: string;
65
+ modelEndpoint: string;
66
+ voice?: string;
67
+ language?: string;
68
+ temperature?: number;
69
+ maxTokens?: number;
70
+ }