Open History to see the last commit
1import { BaseTTSAdapter } from '@tanstack/ai/adapters'
2import {
3 createGeminiClient,
4 generateId,
5 getGeminiApiKeyFromEnv,
6} from '../utils'
7import { GEMINI_TTS_VOICES } from '../model-meta'
8import { buildGeminiUsage } from '../usage'
9import type { GEMINI_TTS_MODELS, GeminiTTSVoice } from '../model-meta'
10import type { TTSCapabilities, TTSOptions, TTSResult } from '@tanstack/ai'
11import type { GoogleGenAI, SpeechConfig } from '@google/genai'
12import type { GeminiClientConfig } from '../utils/client'
13
14/**
15 * Configuration for a single speaker in a multi-speaker dialogue.
16 * Supported by Gemini 3.1 Flash TTS Preview and the 2.5 TTS models.
17 */
18export interface GeminiSpeakerVoiceConfig {
19 /** A name used in the prompt to refer to this speaker */
20 speaker: string
21 /** Voice configuration for this speaker */
22 voiceConfig: {
23 prebuiltVoiceConfig: {
24 voiceName: GeminiTTSVoice
25 }
26 }
27}
28
29/**
30 * Provider-specific options for Gemini TTS
31 *
32 * @experimental Gemini TTS is an experimental feature.
33 * @see https://ai.google.dev/gemini-api/docs/speech-generation
34 * @see https://ai.google.dev/gemini-api/docs/models/gemini-3.1-flash-tts-preview
35 */
36export interface GeminiTTSProviderOptions {
37 /**
38 * Voice configuration for single-speaker TTS.
39 * Choose from 30 available voices with different characteristics.
40 *
41 * Use `multiSpeakerVoiceConfig` instead for dialogues.
42 */
43 voiceConfig?: {
44 prebuiltVoiceConfig?: {
45 /**
46 * The voice name to use for speech synthesis.
47 * @see https://ai.google.dev/gemini-api/docs/speech-generation#voices
48 */
49 voiceName?: GeminiTTSVoice
50 }
51 }
52
53 /**
54 * Multi-speaker voice configuration (up to 2 speakers).
55 * Supported by Gemini 3.1 Flash TTS Preview and the 2.5 TTS models.
56 *
57 * Each speaker's lines in the prompt are prefixed with the name defined
58 * here, e.g.:
59 *
60 * ```text
61 * Joe: Hey, how's it going?
62 * Jane: Not bad, you?
63 * ```
64 */
65 multiSpeakerVoiceConfig?: {
66 speakerVoiceConfigs: Array<GeminiSpeakerVoiceConfig>
67 }
68
69 /**
70 * System instruction for controlling speech style.
71 * Use natural language to describe the desired speaking style,
72 * pace, tone, accent, or other characteristics.
73 *
74 * With Gemini 3.1 Flash TTS, you can also use inline audio tags like
75 * `[whispering]`, `[laughs]`, `[excited]` directly in the input text
76 * to control delivery.
77 *
78 * @example "Speak slowly and calmly, as if telling a bedtime story"
79 * @example "Use an upbeat, enthusiastic tone with moderate pace"
80 * @example "Speak with a British accent"
81 */
82 systemInstruction?: string
83
84 /**
85 * Language code hint for the speech synthesis.
86 * Gemini 3.1 Flash TTS supports 70+ languages with auto-detection;
87 * the 2.5 TTS models support 24 languages.
88 *
89 * @example "en-US" for American English
90 * @example "es-ES" for Spanish (Spain)
91 * @example "ja-JP" for Japanese
92 */
93 languageCode?: string
94}
95
96/**
97 * Configuration for Gemini TTS adapter
98 *
99 * @experimental Gemini TTS is an experimental feature.
100 */
101export interface GeminiTTSConfig extends GeminiClientConfig {}
102
103/** Model type for Gemini TTS */
104export type GeminiTTSModel = (typeof GEMINI_TTS_MODELS)[number]
105
106/**
107 * Gemini Text-to-Speech Adapter
108 *
109 * Tree-shakeable adapter for Gemini TTS functionality.
110 *
111 * **IMPORTANT**: Gemini TTS uses the Live API (WebSocket-based) which requires
112 * different handling than traditional REST APIs. This adapter provides a
113 * simplified interface but may have limitations.
114 *
115 * @experimental Gemini TTS is an experimental feature and may change.
116 *
117 * Models:
118 * - gemini-2.5-flash-preview-tts
119 */
120export class GeminiTTSAdapter<
121 TModel extends GeminiTTSModel,
122> extends BaseTTSAdapter<TModel, GeminiTTSProviderOptions> {
123 readonly name = 'gemini' as const
124
125 /**
126 * Gemini multi-speaker TTS tops out at 2 voices, and reports no timings.
127 */
128 override readonly capabilities: TTSCapabilities = { maxSpeakers: 2 }
129
130 private readonly client: GoogleGenAI
131
132 constructor(config: GeminiTTSConfig, model: TModel) {
133 super(model, config)
134 this.client = createGeminiClient(config)
135 }
136
137 /**
138 * Generate speech from text using Gemini's TTS model.
139 *
140 * @experimental This implementation is experimental and may change.
141 * @see https://ai.google.dev/gemini-api/docs/speech-generation
142 */
143 async generateSpeech(
144 options: TTSOptions<GeminiTTSProviderOptions>,
145 ): Promise<TTSResult> {
146 const { model, modelOptions, voice, logger, turns } = options
147
148 logger.request(`activity=generateSpeech provider=gemini model=${model}`, {
149 provider: 'gemini',
150 model,
151 })
152
153 const speechConfig: SpeechConfig = {}
154 // Gemini has no turn structure on the wire: speakers are named in the
155 // prompt and mapped to voices in the config. `turns` carries voice names,
156 // so the voice name doubles as the speaker label.
157 const text = turns
158 ? turns.map((turn) => `${turn.voice}: ${turn.text}`).join('\n')
159 : options.text
160
161 if (turns) {
162 const voiceNames = [...new Set(turns.map((turn) => turn.voice))].map(
163 toGeminiVoice,
164 )
165 speechConfig.multiSpeakerVoiceConfig = {
166 speakerVoiceConfigs: voiceNames.map((voiceName) => ({
167 speaker: voiceName,
168 voiceConfig: { prebuiltVoiceConfig: { voiceName } },
169 })),
170 }
171 } else if (modelOptions?.multiSpeakerVoiceConfig) {
172 // Validate multi-speaker config: 1 or 2 speakers allowed.
173 const speakerConfigs =
174 modelOptions.multiSpeakerVoiceConfig.speakerVoiceConfigs
175 if (
176 !Array.isArray(speakerConfigs) ||
177 speakerConfigs.length < 1 ||
178 speakerConfigs.length > 2
179 ) {
180 throw new Error(
181 `Gemini TTS multiSpeakerVoiceConfig.speakerVoiceConfigs must contain 1 or 2 speakers; received ${Array.isArray(speakerConfigs) ? speakerConfigs.length : 'non-array'}.`,
182 )
183 }
184 speechConfig.multiSpeakerVoiceConfig =
185 modelOptions.multiSpeakerVoiceConfig
186 } else {
187 // Honor the standard TTSOptions.voice (used by every other TTS adapter)
188 // as a fallback for the prebuilt voice name. If an explicit
189 // modelOptions.voiceConfig is supplied its values win — but we still
190 // fall back to `voice` / 'Kore' if the supplied voiceConfig is missing
191 // prebuiltVoiceConfig.voiceName.
192 const defaultVoiceName =
193 voice !== undefined ? toGeminiVoice(voice) : 'Kore'
194 const supplied = modelOptions?.voiceConfig
195 const resolvedVoiceName =
196 supplied?.prebuiltVoiceConfig?.voiceName ?? defaultVoiceName
197 speechConfig.voiceConfig = {
198 prebuiltVoiceConfig: { voiceName: resolvedVoiceName },
199 }
200 }
201
202 if (modelOptions?.languageCode) {
203 speechConfig.languageCode = modelOptions.languageCode
204 }
205
206 try {
207 const response = await this.client.models.generateContent({
208 model,
209 contents: [
210 {
211 role: 'user',
212 parts: [{ text }],
213 },
214 ],
215 config: {
216 responseModalities: ['AUDIO'],
217 speechConfig,
218 // systemInstruction belongs inside `config` per the @google/genai
219 // contract — matches sibling Gemini adapters (summarize, text).
220 ...(modelOptions?.systemInstruction && {
221 systemInstruction: modelOptions.systemInstruction,
222 }),
223 },
224 })
225
226 // Extract audio data from response
227 const candidate = response.candidates?.[0]
228 const parts = candidate?.content?.parts
229
230 if (!parts || parts.length === 0) {
231 throw new Error('No audio output received from Gemini TTS')
232 }
233
234 // Look for inline data (audio)
235 const audioPart = parts.find((part: any) =>
236 part.inlineData?.mimeType?.startsWith('audio/'),
237 )
238
239 if (!audioPart || !audioPart.inlineData || !audioPart.inlineData.data) {
240 throw new Error('No audio data in Gemini TTS response')
241 }
242
243 const audioBase64 = audioPart.inlineData.data
244 // mime is guaranteed by the `startsWith('audio/')` find predicate above.
245 const mimeType = audioPart.inlineData.mimeType as string
246
247 // Surface token usage (with per-modality breakdown) when Gemini reports
248 // it. Spread conditionally for exactOptionalPropertyTypes — shared by both
249 // the PCM→WAV and pass-through return paths below.
250 const usageField = response.usageMetadata
251 ? { usage: buildGeminiUsage(response.usageMetadata) }
252 : {}
253
254 // Gemini TTS models return raw 16-bit LE PCM with a mime type like
255 // `audio/L16;codec=pcm;rate=24000`. That isn't playable in an <audio>
256 // element and the bare string isn't a usable file extension, so we
257 // prepend a RIFF/WAV header here and normalize the result to audio/wav.
258 const pcm = parsePcmMimeType(mimeType)
259 if (pcm) {
260 const wavBase64 = wrapPcmBase64AsWav(
261 audioBase64,
262 pcm.sampleRate,
263 pcm.channels,
264 pcm.bitsPerSample,
265 )
266 return {
267 id: generateId(this.name),
268 model,
269 audio: wavBase64,
270 format: 'wav',
271 contentType: 'audio/wav',
272 ...usageField,
273 }
274 }
275
276 // Strip any mime parameters (e.g. `audio/ogg;codec=opus`) before pulling
277 // the subtype out as the file format. `String.split` always returns at
278 // least one element, so [0] is defined.
279 const format = (mimeType.split(';')[0] ?? '').split('/')[1] || 'wav'
280
281 return {
282 id: generateId(this.name),
283 model,
284 audio: audioBase64,
285 format,
286 contentType: mimeType,
287 ...usageField,
288 }
289 } catch (error) {
290 logger.errors('gemini.generateSpeech fatal', {
291 error,
292 source: 'gemini.generateSpeech',
293 })
294 throw error
295 }
296 }
297}
298
299/** Narrow a caller-supplied voice string to a known Gemini voice, or throw. */
300function toGeminiVoice(voice: string): GeminiTTSVoice {
301 const match = GEMINI_TTS_VOICES.find((known) => known === voice)
302 if (!match) {
303 throw new Error(
304 `Invalid Gemini TTS voice "${voice}". Valid voices are: ${GEMINI_TTS_VOICES.join(', ')}.`,
305 )
306 }
307 return match
308}
309
310function parsePcmMimeType(
311 mimeType: string,
312): { sampleRate: number; channels: number; bitsPerSample: number } | undefined {
313 const normalized = mimeType.toLowerCase()
314 const subtype = (normalized.split(';')[0] ?? '').split('/')[1] ?? ''
315 // Exclude containerized wav (e.g. `audio/wav;codec=pcm`) — those already
316 // carry a RIFF header and must not be re-wrapped.
317 if (subtype.includes('wav')) return undefined
318
319 // Accept the variants Gemini and other providers actually emit:
320 // - audio/L16;codec=pcm;rate=24000 (IANA PCM with bit depth in the type)
321 // - audio/L24 and friends
322 // - audio/pcm and audio/x-pcm
323 // - anything else that explicitly tags codec=pcm and isn't wav-containered
324 const bitDepthMatch = /^audio\/l(\d+)/.exec(normalized)
325 const isPcm =
326 bitDepthMatch !== null ||
327 normalized.startsWith('audio/pcm') ||
328 normalized.startsWith('audio/x-pcm') ||
329 normalized.includes('codec=pcm')
330 if (!isPcm) return undefined
331
332 const rateMatch = /rate=(\d+)/.exec(normalized)
333 const channelsMatch = /channels=(\d+)/.exec(normalized)
334 // Default to 16-bit when the mime type doesn't specify — matches Gemini's
335 // audio/L16;codec=pcm;rate=24000 response.
336 const bitsPerSample = bitDepthMatch ? Number(bitDepthMatch[1]) : 16
337 return {
338 sampleRate: rateMatch ? Number(rateMatch[1]) : 24000,
339 channels: channelsMatch ? Number(channelsMatch[1]) : 1,
340 bitsPerSample,
341 }
342}
343
344function wrapPcmBase64AsWav(
345 pcmBase64: string,
346 sampleRate: number,
347 channels = 1,
348 bitsPerSample = 16,
349): string {
350 // The WAV writer below emits a 16-bit PCM fmt chunk. If the source claims a
351 // different bit depth we'd be lying about the payload, so bail out loudly
352 // rather than producing a corrupt file.
353 if (bitsPerSample !== 16) {
354 throw new Error(
355 `Unsupported PCM bit depth ${bitsPerSample}: only 16-bit PCM can be wrapped as WAV.`,
356 )
357 }
358
359 const pcmBytes =
360 typeof Buffer !== 'undefined'
361 ? new Uint8Array(Buffer.from(pcmBase64, 'base64'))
362 : decodeBase64(pcmBase64)
363
364 const byteRate = (sampleRate * channels * bitsPerSample) / 8
365 const blockAlign = (channels * bitsPerSample) / 8
366 const dataSize = pcmBytes.byteLength
367 const buffer = new ArrayBuffer(44 + dataSize)
368 const view = new DataView(buffer)
369
370 writeAscii(view, 0, 'RIFF')
371 view.setUint32(4, 36 + dataSize, true)
372 writeAscii(view, 8, 'WAVE')
373 writeAscii(view, 12, 'fmt ')
374 view.setUint32(16, 16, true)
375 view.setUint16(20, 1, true)
376 view.setUint16(22, channels, true)
377 view.setUint32(24, sampleRate, true)
378 view.setUint32(28, byteRate, true)
379 view.setUint16(32, blockAlign, true)
380 view.setUint16(34, bitsPerSample, true)
381 writeAscii(view, 36, 'data')
382 view.setUint32(40, dataSize, true)
383 new Uint8Array(buffer, 44).set(pcmBytes)
384
385 if (typeof Buffer !== 'undefined') {
386 return Buffer.from(buffer).toString('base64')
387 }
388 let binary = ''
389 const bytes = new Uint8Array(buffer)
390 for (const byte of bytes) {
391 binary += String.fromCharCode(byte)
392 }
393 return btoa(binary)
394}
395
396function decodeBase64(b64: string): Uint8Array {
397 const binary = atob(b64)
398 const out = new Uint8Array(binary.length)
399 for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i)
400 return out
401}
402
403function writeAscii(view: DataView, offset: number, text: string): void {
404 for (let i = 0; i < text.length; i += 1) {
405 view.setUint8(offset + i, text.charCodeAt(i))
406 }
407}
408
409/**
410 * Creates a Gemini TTS adapter with explicit API key.
411 * Type resolution happens here at the call site.
412 *
413 * @experimental Gemini TTS is an experimental feature and may change.
414 *
415 * @param model - The model name (e.g., 'gemini-2.5-flash-preview-tts')
416 * @param apiKey - Your Google API key
417 * @param config - Optional additional configuration
418 * @returns Configured Gemini TTS adapter instance with resolved types
419 *
420 * @example
421 * ```typescript
422 * const adapter = createGeminiSpeech('gemini-2.5-flash-preview-tts', "your-api-key");
423 *
424 * const result = await generateSpeech({
425 * adapter,
426 * text: 'Hello, world!'
427 * });
428 * ```
429 */
430export function createGeminiSpeech<TModel extends GeminiTTSModel>(
431 model: TModel,
432 apiKey: string,
433 config?: Omit<GeminiTTSConfig, 'apiKey'>,
434): GeminiTTSAdapter<TModel> {
435 // Put apiKey LAST so caller-supplied config can't silently override the
436 // explicit argument.
437 return new GeminiTTSAdapter({ ...config, apiKey }, model)
438}
439
440/**
441 * Creates a Gemini speech adapter with automatic API key detection from environment variables.
442 * Type resolution happens here at the call site.
443 *
444 * @experimental Gemini TTS is an experimental feature and may change.
445 *
446 * Looks for `GOOGLE_API_KEY` or `GEMINI_API_KEY` in:
447 * - `process.env` (Node.js)
448 * - `window.env` (Browser with injected env)
449 *
450 * @param model - The model name (e.g., 'gemini-2.5-flash-preview-tts')
451 * @param config - Optional configuration (excluding apiKey which is auto-detected)
452 * @returns Configured Gemini speech adapter instance with resolved types
453 * @throws Error if GOOGLE_API_KEY or GEMINI_API_KEY is not found in environment
454 *
455 * @example
456 * ```typescript
457 * // Automatically uses GOOGLE_API_KEY from environment
458 * const adapter = geminiSpeech('gemini-2.5-flash-preview-tts');
459 *
460 * const result = await generateSpeech({
461 * adapter,
462 * text: 'Welcome to TanStack AI!'
463 * });
464 * ```
465 */
466export function geminiSpeech<TModel extends GeminiTTSModel>(
467 model: TModel,
468 config?: Omit<GeminiTTSConfig, 'apiKey'>,
469): GeminiTTSAdapter<TModel> {
470 const apiKey = getGeminiApiKeyFromEnv()
471 return createGeminiSpeech(model, apiKey, config)
472}