|
| 1 | +// SPDX-FileCopyrightText: 2026 LiveKit, Inc. |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | +import { |
| 5 | + type APIConnectOptions, |
| 6 | + APIConnectionError, |
| 7 | + APIStatusError, |
| 8 | + AudioByteStream, |
| 9 | + log, |
| 10 | + tts, |
| 11 | +} from '@livekit/agents'; |
| 12 | +import { Mistral } from '@mistralai/mistralai'; |
| 13 | +import type { MistralTTSModels } from './models.js'; |
| 14 | + |
| 15 | +// Confirmed from WAV header: Mistral TTS PCM output is 24000 Hz, mono, 16-bit signed |
| 16 | +const MISTRAL_TTS_SAMPLE_RATE = 24000; |
| 17 | +const MISTRAL_TTS_CHANNELS = 1; |
| 18 | + |
| 19 | +export interface TTSOptions { |
| 20 | + /** |
| 21 | + * Mistral API key. Defaults to the MISTRAL_API_KEY environment variable. |
| 22 | + */ |
| 23 | + apiKey?: string; |
| 24 | + /** |
| 25 | + * TTS model to use. |
| 26 | + * @default 'voxtral-mini-tts-2603' |
| 27 | + */ |
| 28 | + model?: MistralTTSModels | string; |
| 29 | + /** |
| 30 | + * Preset voice ID to use for synthesis. Use `listVoices()` to enumerate available voices. |
| 31 | + * If omitted, the API may select a default voice. |
| 32 | + */ |
| 33 | + voiceId?: string; |
| 34 | + /** |
| 35 | + * Base URL for the Mistral API. |
| 36 | + */ |
| 37 | + baseURL?: string; |
| 38 | +} |
| 39 | + |
| 40 | +const defaultTTSOptions: TTSOptions = { |
| 41 | + apiKey: process.env.MISTRAL_API_KEY, |
| 42 | + model: 'voxtral-mini-tts-2603', |
| 43 | +}; |
| 44 | + |
| 45 | +export class TTS extends tts.TTS { |
| 46 | + #opts: Required<Omit<TTSOptions, 'voiceId' | 'baseURL'>> & |
| 47 | + Pick<TTSOptions, 'voiceId' | 'baseURL'>; |
| 48 | + #client: Mistral; |
| 49 | + #logger = log(); |
| 50 | + |
| 51 | + label = 'mistral.TTS'; |
| 52 | + |
| 53 | + constructor(opts: TTSOptions = {}) { |
| 54 | + super(MISTRAL_TTS_SAMPLE_RATE, MISTRAL_TTS_CHANNELS, { streaming: false }); |
| 55 | + |
| 56 | + this.#opts = { |
| 57 | + ...defaultTTSOptions, |
| 58 | + ...opts, |
| 59 | + } as Required<Omit<TTSOptions, 'voiceId' | 'baseURL'>> & |
| 60 | + Pick<TTSOptions, 'voiceId' | 'baseURL'>; |
| 61 | + |
| 62 | + if (this.#opts.apiKey === undefined) { |
| 63 | + throw new Error( |
| 64 | + 'Mistral API key is required, either as an argument or set the MISTRAL_API_KEY environment variable', |
| 65 | + ); |
| 66 | + } |
| 67 | + |
| 68 | + this.#client = new Mistral({ |
| 69 | + apiKey: this.#opts.apiKey, |
| 70 | + serverURL: this.#opts.baseURL, |
| 71 | + }); |
| 72 | + } |
| 73 | + |
| 74 | + get model(): string { |
| 75 | + return this.#opts.model; |
| 76 | + } |
| 77 | + |
| 78 | + get provider(): string { |
| 79 | + return 'mistral'; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * List all available preset voices. |
| 84 | + */ |
| 85 | + async listVoices(): Promise<{ id: string; name: string; slug: string; languages: string[] }[]> { |
| 86 | + const result = await this.#client.audio.voices.list(); |
| 87 | + return (result.items ?? []).map((v: any) => ({ |
| 88 | + id: v.id, |
| 89 | + name: v.name, |
| 90 | + slug: v.slug, |
| 91 | + languages: v.languages ?? [], |
| 92 | + })); |
| 93 | + } |
| 94 | + |
| 95 | + synthesize(text: string, connOptions?: APIConnectOptions): ChunkedStream { |
| 96 | + return new ChunkedStream(this, text, this.#client, this.#opts, connOptions); |
| 97 | + } |
| 98 | + |
| 99 | + stream(): tts.SynthesizeStream { |
| 100 | + throw new Error('Mistral TTS does not support streaming synthesis — use synthesize() instead'); |
| 101 | + } |
| 102 | + |
| 103 | + async close(): Promise<void> { |
| 104 | + // HTTP-based, no persistent connections to clean up |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +export class ChunkedStream extends tts.ChunkedStream { |
| 109 | + label = 'mistral.ChunkedStream'; |
| 110 | + #client: Mistral; |
| 111 | + #opts: TTSOptions; |
| 112 | + #text: string; |
| 113 | + |
| 114 | + constructor( |
| 115 | + ttsInstance: TTS, |
| 116 | + text: string, |
| 117 | + client: Mistral, |
| 118 | + opts: TTSOptions, |
| 119 | + connOptions?: APIConnectOptions, |
| 120 | + ) { |
| 121 | + super(text, ttsInstance, connOptions); |
| 122 | + this.#client = client; |
| 123 | + this.#opts = opts; |
| 124 | + this.#text = text; |
| 125 | + } |
| 126 | + |
| 127 | + protected async run(): Promise<void> { |
| 128 | + const logger = log(); |
| 129 | + try { |
| 130 | + const eventStream = await this.#client.audio.speech.complete({ |
| 131 | + input: this.#text, |
| 132 | + model: this.#opts.model ?? 'voxtral-mini-tts-2603', |
| 133 | + voiceId: this.#opts.voiceId, |
| 134 | + responseFormat: 'pcm', |
| 135 | + stream: true, |
| 136 | + }); |
| 137 | + |
| 138 | + const requestId = this.#text.slice(0, 8); |
| 139 | + const audioByteStream = new AudioByteStream(MISTRAL_TTS_SAMPLE_RATE, MISTRAL_TTS_CHANNELS); |
| 140 | + |
| 141 | + let lastFrame: import('@livekit/rtc-node').AudioFrame | undefined; |
| 142 | + |
| 143 | + const sendLastFrame = (segmentId: string, final: boolean) => { |
| 144 | + if (lastFrame) { |
| 145 | + this.queue.put({ requestId, segmentId, frame: lastFrame, final }); |
| 146 | + lastFrame = undefined; |
| 147 | + } |
| 148 | + }; |
| 149 | + |
| 150 | + for await (const event of eventStream) { |
| 151 | + if (event.data.type === 'speech.audio.delta') { |
| 152 | + const pcmBytes = Buffer.from(event.data.audioData, 'base64'); |
| 153 | + const frames = audioByteStream.write(pcmBytes); |
| 154 | + for (const frame of frames) { |
| 155 | + sendLastFrame(requestId, false); |
| 156 | + lastFrame = frame; |
| 157 | + } |
| 158 | + } else if (event.data.type === 'speech.audio.done') { |
| 159 | + break; |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + // Flush any remaining buffered audio |
| 164 | + const flushFrames = audioByteStream.flush(); |
| 165 | + for (const frame of flushFrames) { |
| 166 | + sendLastFrame(requestId, false); |
| 167 | + lastFrame = frame; |
| 168 | + } |
| 169 | + |
| 170 | + sendLastFrame(requestId, true); |
| 171 | + this.queue.close(); |
| 172 | + } catch (error: unknown) { |
| 173 | + if (this.abortController?.signal.aborted) return; |
| 174 | + |
| 175 | + if (error instanceof APIStatusError || error instanceof APIConnectionError) { |
| 176 | + throw error; |
| 177 | + } |
| 178 | + |
| 179 | + const err = error as { statusCode?: number; status?: number; message?: string }; |
| 180 | + const statusCode = err.statusCode ?? err.status; |
| 181 | + |
| 182 | + if (statusCode !== undefined) { |
| 183 | + if (statusCode === 429) { |
| 184 | + throw new APIStatusError({ |
| 185 | + message: `Mistral TTS: rate limit - ${err.message ?? 'unknown error'}`, |
| 186 | + options: { statusCode, retryable: true }, |
| 187 | + }); |
| 188 | + } |
| 189 | + if (statusCode >= 400 && statusCode < 500) { |
| 190 | + throw new APIStatusError({ |
| 191 | + message: `Mistral TTS: client error (${statusCode}) - ${err.message ?? 'unknown error'}`, |
| 192 | + options: { statusCode, retryable: false }, |
| 193 | + }); |
| 194 | + } |
| 195 | + if (statusCode >= 500) { |
| 196 | + throw new APIStatusError({ |
| 197 | + message: `Mistral TTS: server error (${statusCode}) - ${err.message ?? 'unknown error'}`, |
| 198 | + options: { statusCode, retryable: true }, |
| 199 | + }); |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + throw new APIConnectionError({ |
| 204 | + message: `Mistral TTS: ${err.message ?? 'unknown error'}`, |
| 205 | + options: { retryable: true }, |
| 206 | + }); |
| 207 | + } finally { |
| 208 | + this.queue.close(); |
| 209 | + } |
| 210 | + } |
| 211 | +} |
0 commit comments