🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(tts): Gemini text-to-speech on the Google provider, with a default voice in settings (#22977)
Rdmclin211a57dc4c0f0
diff --git a/.agents/skills/cli/references/generate.md b/.agents/skills/cli/references/generate.mdindex 4aff792d2b8..39c613a790d 100644--- a/.agents/skills/cli/references/generate.md+++ b/.agents/skills/cli/references/generate.md@@ -268,25 +268,34 @@ lh gen tts <text> [-o <file>] [--voice <voice>] [-m <model>] [-p <provider>] \[--sample-rate <hz>] [--instructions <text>] [--params <json>]```-| Option | Description | Default |-| --------------------------- | ------------------------------------------------------------ | --------------------- |-| `-o, --output <file>` | Output audio file path | `output.<format>` |-| `--voice <voice>` | Voice id from the model card's `voices` | model's default voice |-| `--speed <n>` | Speed multiplier | model default |-| `--pitch <n>` | Pitch adjustment (provider-specific unit) | model default |-| `--volume <n>` | Volume adjustment (provider-specific unit) | model default |-| `--emotion <emotion>` | Emotion, e.g. `happy` | model default |-| `--format <format>` | `mp3`, `opus`, `aac` (compressed only: audio returns inline) | `mp3` |-| `--sample-rate <hz>` | Output sample rate | model default |-| `--instructions <text>` | Style instructions (e.g. `gpt-4o-mini-tts`) | — |-| `--params <json>` | Standard TTS params as JSON; dedicated flags override it | — |-| `-m, --model <model>` | Model ID (`provider/model` supported) | `tts-1` |-| `-p, --provider <provider>` | Provider (derived from model if omitted) | `openai` |+| Option | Description | Default |+| --------------------------- | ------------------------------------------------------------ | ------------------- |+| `-o, --output <file>` | Output audio file path | `output.<format>` |+| `--voice <voice>` | Voice id from the model card's `voices` | saved default voice |+| `--speed <n>` | Speed multiplier | model default |+| `--pitch <n>` | Pitch adjustment (provider-specific unit) | model default |+| `--volume <n>` | Volume adjustment (provider-specific unit) | model default |+| `--emotion <emotion>` | Emotion, e.g. `happy` | model default |+| `--format <format>` | `mp3`, `opus`, `aac` (compressed only: audio returns inline) | `mp3` |+| `--sample-rate <hz>` | Output sample rate | model default |+| `--instructions <text>` | Style instructions (e.g. `gpt-4o-mini-tts`) | — |+| `--params <json>` | Standard TTS params as JSON; dedicated flags override it | — |+| `-m, --model <model>` | Model ID (`provider/model` supported) | `tts-1` |+| `-p, --provider <provider>` | Provider (model prefix, else the built-in card's provider) | card's provider |Params are standard TTS parameters (`TTSModelParamsMetaSchema` in model-bank). The serverrejects params the model card does not declare or values outside its range. On success thecommand prints the file size plus usage (characters, tokens, cost) when the provider reports it.+Without `--voice`, the server uses the **Default Voice** saved for the model in+Settings → AI Providers (model config dialog), then the card's default voice. Without a+provider or a `provider/` prefix, the server takes the provider of the model's built-in card+(`gemini-3.8-flash-tts` → `google`, `speech-2.8-hd` → `minimax`), then `openai`.++Gemini TTS (`-p google`, models `gemini-3.8-flash-tts`, `gemini-3.8-flash-lite-tts`, legacy+`gemini-2.5-flash-preview-tts` / `gemini-2.5-pro-preview-tts`): 30 prebuilt voices (default+`Kore`), style through `--instructions`, no speed/pitch/volume/emotion, output MP3 24 kHz mono.+Uses the selected provider's saved configuration through ModelRuntime, with the sameauthenticated tRPC client as `lh gen asr`.diff --git a/apps/cli/src/commands/generate/tts.test.ts b/apps/cli/src/commands/generate/tts.test.tsindex 6861af7a2cd..89223b58e77 100644--- a/apps/cli/src/commands/generate/tts.test.ts+++ b/apps/cli/src/commands/generate/tts.test.ts@@ -88,12 +88,43 @@ describe('generate tts', () => {input: 'hello',model: 'tts-1',params: undefined,- provider: 'openai',+ provider: undefined,speed: undefined,voice: undefined,});});+ it('lets the server pick the provider of a bare Gemini TTS model id', async () => {+ await run(+ '你好,Gemini',+ '-m',+ 'gemini-3.8-flash-tts',+ '--voice',+ 'Kore',+ '--instructions',+ 'Say cheerfully',+ '-o',+ output,+ );++ expect(synthesize).toHaveBeenCalledWith({+ input: '你好,Gemini',+ model: 'gemini-3.8-flash-tts',+ params: { instructions: 'Say cheerfully' },+ provider: undefined,+ speed: undefined,+ voice: 'Kore',+ });+ });++ it('sends an explicit provider for a Gemini TTS model', async () => {+ await run('hello', '-p', 'google', '-m', 'gemini-2.5-flash-preview-tts', '-o', output);++ expect(synthesize).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'gemini-2.5-flash-preview-tts', provider: 'google' }),+ );+ });+it('names the default output file after the returned format', async () => {const cwd = process.cwd();const dir = path.dirname(output);diff --git a/apps/cli/src/commands/generate/tts.ts b/apps/cli/src/commands/generate/tts.tsindex 0ea00b53254..c562c86427d 100644--- a/apps/cli/src/commands/generate/tts.ts+++ b/apps/cli/src/commands/generate/tts.ts@@ -68,20 +68,28 @@ export function registerTtsCommand(parent: Command) {.command('tts <text>').description('Convert text to speech').option('-o, --output <file>', 'Output audio file path (default: output.<format>)')- .option('--voice <voice>', "Voice id (default: the model's default voice)")+ .option(+ '--voice <voice>',+ "Voice id (default: the voice saved for the model in provider settings, else the model's default)",+ ).option('--speed <n>', 'Speed multiplier').option('--pitch <n>', 'Pitch adjustment').option('--volume <n>', 'Volume adjustment').option('--emotion <emotion>', 'Emotion, e.g. happy, sad')- .option('--format <format>', 'Audio format: mp3, opus, aac')+ .option('--format <format>', 'Audio format: mp3, opus, aac (as the model supports)').option('--sample-rate <hz>', 'Output sample rate in Hz').option('--instructions <text>', 'Style instructions, for models that accept them').option('--params <json>', 'Extra standard TTS params as a JSON object').option('-m, --model <model>', 'Model ID (provider/model format)', 'tts-1')- .option('-p, --provider <provider>', 'Provider name (derived from model if omitted)')+ .option(+ '-p, --provider <provider>',+ "Provider name (default: the model prefix, else the built-in model's provider)",+ ).action(async (text: string, options: TtsCommandOptions) => {const parts = options.model.split('/');- const provider = options.provider || (parts.length > 1 ? parts[0] : 'openai');+ // Without a provider the server picks the one of the model's built-in card+ // (`gemini-3.8-flash-tts` → google), then OpenAI.+ const provider = options.provider || (parts.length > 1 ? parts[0] : undefined);const model = parts.length > 1 ? parts.slice(1).join('/') : options.model;let params: Record<string, unknown>;diff --git a/apps/server/src/routers/lambda/__tests__/tts.test.ts b/apps/server/src/routers/lambda/__tests__/tts.test.tsindex 280e2f21cb1..789fc15ad23 100644--- a/apps/server/src/routers/lambda/__tests__/tts.test.ts+++ b/apps/server/src/routers/lambda/__tests__/tts.test.ts@@ -16,6 +16,13 @@ vi.mock('@/server/modules/ModelRuntime', () => ({initModelRuntimeFromDB: vi.fn(async () => ({ textToSpeech: textToSpeechMock })),}));+const findByIdAndProviderMock = vi.fn();+vi.mock('@/database/models/aiModel', () => ({+ AiModelModel: vi.fn(function () {+ return { findByIdAndProvider: findByIdAndProviderMock };+ }),+}));+const caller = ttsRouter.createCaller({ jwtPayload: { userId: 'u1' }, userId: 'u1' } as any);const usage = { cost: 0.000_075, inputCharacters: 5 };@@ -275,3 +282,102 @@ describe('ttsRouter.synthesize', () => {});});});++describe('ttsRouter.synthesize saved default voice', () => {+ it('uses the default voice saved in the model settings when the request names none', async () => {+ findByIdAndProviderMock.mockResolvedValueOnce({ settings: { ttsVoice: 'Puck' } });++ await caller.synthesize({ input: '你好', model: 'gemini-3.8-flash-tts', provider: 'google' });++ expect(findByIdAndProviderMock).toHaveBeenCalledWith('gemini-3.8-flash-tts', 'google');+ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({+ voice: 'Puck',+ voiceIsDefault: false,+ });+ });++ it('lets an explicit request voice win without reading the saved one', async () => {+ await caller.synthesize({+ input: 'hello',+ model: 'gemini-3.8-flash-tts',+ provider: 'google',+ voice: 'Zephyr',+ });++ expect(findByIdAndProviderMock).not.toHaveBeenCalled();+ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({ voice: 'Zephyr' });+ });++ it('falls back to the card default when nothing is saved', async () => {+ findByIdAndProviderMock.mockResolvedValueOnce(undefined);++ await caller.synthesize({ input: 'hello', model: 'gemini-3.8-flash-tts', provider: 'google' });++ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({+ voice: 'Kore',+ voiceIsDefault: true,+ });+ });++ it("ignores a saved voice that is not in the model's catalog", async () => {+ findByIdAndProviderMock.mockResolvedValueOnce({ settings: { ttsVoice: 'RetiredVoice' } });++ await caller.synthesize({ input: 'hello', model: 'gemini-3.8-flash-tts', provider: 'google' });++ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({ voice: 'Kore' });+ });++ it('accepts any saved voice for a model without a built-in catalog', async () => {+ findByIdAndProviderMock.mockResolvedValueOnce({ settings: { ttsVoice: 'my-clone' } });++ await caller.synthesize({ input: 'hello', model: 'my-custom-tts', provider: 'openai' });++ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({ voice: 'my-clone' });+ });++ it('still synthesizes with the card default when reading the preference fails', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ findByIdAndProviderMock.mockRejectedValueOnce(new Error('db down'));++ await caller.synthesize({ input: 'hello', model: 'gemini-3.8-flash-tts', provider: 'google' });++ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({ voice: 'Kore' });+ consoleError.mockRestore();+ });+});++describe('ttsRouter.synthesize provider resolution', () => {+ it("uses the built-in card's provider when the request names none", async () => {+ await caller.synthesize({ input: 'hello', model: 'gemini-3.8-flash-tts' });++ expect(initModelRuntimeFromDB).toHaveBeenCalledWith(+ expect.anything(),+ 'u1',+ 'google',+ undefined,+ );+ });++ it('splits a provider-prefixed model reference', async () => {+ await caller.synthesize({ input: 'hello', model: 'google/gemini-3.8-flash-tts' });++ expect(initModelRuntimeFromDB).toHaveBeenCalledWith(+ expect.anything(),+ 'u1',+ 'google',+ undefined,+ );+ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({ model: 'gemini-3.8-flash-tts' });+ });++ it('keeps OpenAI as the fallback for an unknown bare model id', async () => {+ await caller.synthesize({ input: 'hello', model: 'my-custom-tts' });++ expect(initModelRuntimeFromDB).toHaveBeenCalledWith(+ expect.anything(),+ 'u1',+ 'openai',+ undefined,+ );+ });+});diff --git a/apps/server/src/routers/lambda/tts.ts b/apps/server/src/routers/lambda/tts.tsindex 30c0feccb0c..b99c072dae1 100644--- a/apps/server/src/routers/lambda/tts.ts+++ b/apps/server/src/routers/lambda/tts.ts@@ -11,6 +11,7 @@ import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import {INLINE_TTS_AUDIO_FORMATS,+ resolveTTSModelRef,TTSProviderError,TTSRequestError,TTSService,@@ -37,7 +38,8 @@ const synthesizeInput = z.object({model: z.string().min(1),/** Standard TTS params, checked against the model card when it declares them. */params: ttsParamsInput.optional(),- provider: z.string().min(1).default('openai'),+ /** Defaults to the provider of the model's built-in card, then OpenAI. */+ provider: z.string().min(1).optional(),/** @deprecated Use `params.speed`. */speed: z.number().min(0.25).max(4).optional(),/** Defaults to the model card's default voice. */@@ -62,7 +64,10 @@ export const ttsRouter = router({const service = new TTSService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);try {- const result = await service.synthesize(input);+ // Without a provider, `lobehub/speech-2.8-hd` splits into provider and model, and a+ // bare id takes the provider of its built-in card (`gemini-3.8-flash-tts` → google).+ const ref = resolveTTSModelRef(input.model, input.provider);+ const result = await service.synthesize({ ...input, ...ref });return {audioBase64: Buffer.from(result.audio).toString('base64'),diff --git a/apps/server/src/services/tts/index.ts b/apps/server/src/services/tts/index.tsindex fefb6432e42..72e33237fa7 100644--- a/apps/server/src/services/tts/index.ts+++ b/apps/server/src/services/tts/index.ts@@ -7,6 +7,7 @@ import { LOBE_DEFAULT_MODEL_LIST, TTS_AUDIO_MIME_TYPES, validateTTSParams } fromimport { ModelProvider } from 'model-bank/modelProvider';import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';+import { AiModelModel } from '@/database/models/aiModel';import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';@@ -217,7 +218,9 @@ export class TTSService {}}- const voice = request.voice ?? card?.parameters?.voice?.default ?? 'alloy';+ const savedVoice =+ request.voice === undefined ? await this.findSavedVoice(provider, model, card) : undefined;+ const voice = request.voice ?? savedVoice ?? card?.parameters?.voice?.default ?? 'alloy';let runtime: ModelRuntime;try {@@ -235,7 +238,13 @@ export class TTSService {let result: Awaited<ReturnType<typeof runtime.textToSpeech>>;try {result = await runtime.textToSpeech(- { input, model, params, voice, voiceIsDefault: request.voice === undefined },+ {+ input,+ model,+ params,+ voice,+ voiceIsDefault: request.voice === undefined && savedVoice === undefined,+ },{ metadata: { trigger: RequestTrigger.Tts }, user: this.userId },);} catch (error) {@@ -258,4 +267,32 @@ export class TTSService {usage: result.usage,};}++ /**+ * The default voice the user saved for this model in Settings → AI Providers. A voice that+ * is no longer in the card's catalog (renamed or retired upstream) is ignored, so a stale+ * preference falls back to the card default instead of failing every request. Reading the+ * preference never blocks synthesis.+ */+ private async findSavedVoice(+ provider: string,+ model: string,+ card: AITTSModelCard | undefined,+ ): Promise<string | undefined> {+ try {+ const row = await new AiModelModel(+ this.db,+ this.userId,+ this.workspaceId,+ ).findByIdAndProvider(model, provider);+ const saved = row?.settings?.ttsVoice?.trim();+ if (!saved) return undefined;+ if (card?.voices?.length && !card.voices.some((item) => item.id === saved)) return undefined;++ return saved;+ } catch (error) {+ console.error('[TTSService] failed to read the saved default voice:', error);+ return undefined;+ }+ }}diff --git a/docs/usage/providers.mdx b/docs/usage/providers.mdxindex 802687e70b7..4700858eb07 100644--- a/docs/usage/providers.mdx+++ b/docs/usage/providers.mdx@@ -47,7 +47,7 @@ Models, regional access, prices, and API support depend on the provider and your| **Chinese Providers** | [DeepSeek](/docs/usage/providers/deepseek) (DeepSeek-V4.1-Flash) · [Moonshot](/docs/usage/providers/moonshot) · [Zhipu](/docs/usage/providers/zhipu) · [Qwen](/docs/usage/providers/qwen) (Qwen3.8-Max) · [Baichuan](/docs/usage/providers/baichuan) · [Baidu Wenxin](/docs/usage/providers/wenxin) · [iFlytek Spark](/docs/usage/providers/spark) || **Local and Self-Hosted Inference** | [Ollama](/docs/usage/providers/ollama) · [LM Studio](/docs/usage/providers/lmstudio) · [vLLM](/docs/usage/providers/vllm) || **Image and Media Services** | [OpenAI](/docs/usage/providers/openai) · [Black Forest Labs](/docs/usage/providers/bfl) · [fal](/docs/usage/providers/fal) · [ComfyUI](/docs/usage/providers/comfyui) · [Google](/docs/usage/providers/google) · [Volcengine](/docs/usage/providers/volcengine) |-| **Speech Synthesis (TTS)** | [ElevenLabs](/docs/usage/providers/elevenlabs) · [OpenAI](/docs/usage/providers/openai) · [MiniMax](/docs/usage/providers/minimax) |+| **Speech Synthesis (TTS)** | [ElevenLabs](/docs/usage/providers/elevenlabs) · [OpenAI](/docs/usage/providers/openai) · [MiniMax](/docs/usage/providers/minimax) · [Google Gemini](/docs/usage/providers/google#text-to-speech-gemini-tts) |An image model name is not a provider name. Select the guide for the provider or local runtime that serves the model.diff --git a/docs/usage/providers.zh-CN.mdx b/docs/usage/providers.zh-CN.mdxindex 9cd11673a66..dff220a33a1 100644--- a/docs/usage/providers.zh-CN.mdx+++ b/docs/usage/providers.zh-CN.mdx@@ -43,7 +43,7 @@ tags:| **国内服务商** | [DeepSeek](/zh/docs/usage/providers/deepseek)(DeepSeek-V4.1-Flash) · [Moonshot](/zh/docs/usage/providers/moonshot) · [智谱](/zh/docs/usage/providers/zhipu) · [通义千问](/zh/docs/usage/providers/qwen)(Qwen3.8-Max) · [百川](/zh/docs/usage/providers/baichuan) · [百度文心](/zh/docs/usage/providers/wenxin) · [讯飞星火](/zh/docs/usage/providers/spark) || **本地与自托管推理** | [Ollama](/zh/docs/usage/providers/ollama) · [LM Studio](/zh/docs/usage/providers/lmstudio) · [vLLM](/zh/docs/usage/providers/vllm) || **图像与多媒体服务** | [OpenAI](/zh/docs/usage/providers/openai) · [Black Forest Labs](/zh/docs/usage/providers/bfl) · [fal](/zh/docs/usage/providers/fal) · [ComfyUI](/zh/docs/usage/providers/comfyui) · [Google](/zh/docs/usage/providers/google) · [火山引擎](/zh/docs/usage/providers/volcengine) |-| **语音合成(TTS)** | [ElevenLabs](/zh/docs/usage/providers/elevenlabs) · [OpenAI](/zh/docs/usage/providers/openai) · [MiniMax](/zh/docs/usage/providers/minimax) |+| **语音合成(TTS)** | [ElevenLabs](/zh/docs/usage/providers/elevenlabs) · [OpenAI](/zh/docs/usage/providers/openai) · [MiniMax](/zh/docs/usage/providers/minimax) · [Google Gemini](/zh/docs/usage/providers/google#语音合成gemini-tts) |图像模型名称不是服务商名称。请按提供该模型的服务商或本地运行时选择配置教程。diff --git a/docs/usage/providers/google.mdx b/docs/usage/providers/google.mdxindex adf41e608e7..fad1a896a4a 100644--- a/docs/usage/providers/google.mdx+++ b/docs/usage/providers/google.mdx@@ -52,3 +52,42 @@ This guide will show you how to use Google Gemini in LobeHub:</Steps>And that’s it — you’re now ready to use Google Gemini in LobeHub!++## Text to speech (Gemini TTS)++The Google provider also turns text into speech with Gemini TTS. It uses the same API key as the chat models.++### Choose a model and a default voice++- Open **App Settings → AI Providers → Google**. The **TTS** tab of the model list shows the Gemini speech models:++ | Model | Notes |+ | ------------------------------ | ------------------------------------------------------------------- |+ | `gemini-3.8-flash-tts` | Enabled by default. Recommended. |+ | `gemini-3.8-flash-lite-tts` | Enabled by default. Lower cost and latency. |+ | `gemini-2.5-flash-preview-tts` | Legacy preview. Google shuts it down on 2026-11-17 at the earliest. |+ | `gemini-2.5-pro-preview-tts` | Legacy preview. Google shuts it down on 2026-11-17 at the earliest. |++- Turn a model on or off with its switch.++- To change the voice used when a request names none, select the model's **Configure** button and pick a **Default Voice**. All 30 Gemini prebuilt voices are listed with their style (for example `Kore · Firm`, `Puck · Upbeat`). Leave it empty to use the model default, `Kore`. The setting is saved per model and applies to the LobeHub CLI and the `/api/v1/audio/speech` endpoint.++### Generate speech++```bash+lh generate tts "Hello from LobeHub" -m gemini-3.8-flash-tts -o hello.mp3+lh generate tts "你好,欢迎使用 LobeHub。" -m google/gemini-3.8-flash-tts --voice Puck \+ --instructions "Say it slowly and warmly" -o hello-zh.mp3+```++- **Voice**: one of the 30 prebuilt voices, for example `Kore`, `Puck`, `Zephyr` or `Charon`. Every voice speaks all supported languages, including Chinese and English.+- **Style**: Gemini has no numeric speed, pitch or volume. Use `--instructions` to describe pace and tone in natural language, for example "speak slowly in a calm voice". `--speed`, `--pitch`, `--volume` and `--emotion` are rejected for Gemini models.+- **Format**: Gemini returns 24 kHz, 16-bit mono PCM. LobeHub encodes it to MP3 (24 kHz mono, 40 kbps), which is the only format returned through the CLI and the speech endpoint (`audio/mpeg`).+- **Length**: one request returns up to about 11 minutes of audio. Split long text into several requests.+- **Billing**: Gemini TTS bills the input text tokens and the generated audio tokens (about 25 tokens per second of audio). See [Gemini API pricing](https://ai.google.dev/gemini-api/docs/pricing).++### Troubleshooting++- **"Google API Key is incorrect or empty…"**: no key is set, or Google rejected it. Check the key in **App Settings → AI Providers → Google**, or `GOOGLE_API_KEY` on a self-hosted server.+- **Rate-limit errors**: the request exceeded the TTS rate limit of your Gemini API tier. Wait and retry, or raise the tier of the Google Cloud project.+- **Content blocked**: Gemini refused the text for safety reasons. Rephrase the text.diff --git a/docs/usage/providers/google.zh-CN.mdx b/docs/usage/providers/google.zh-CN.mdxindex 8b2edda8f01..29c55be7138 100644--- a/docs/usage/providers/google.zh-CN.mdx+++ b/docs/usage/providers/google.zh-CN.mdx@@ -50,3 +50,42 @@ Gemini AI 是由 Google AI 创建的一组大型语言模型(LLM),以其</Steps>至此,你已经可以在 LobeHub 中使用 Google Gemini 啦。++## 语音合成(Gemini TTS)++Google 服务商还可以通过 Gemini TTS 把文字转成语音,使用与对话模型相同的 API Key。++### 选择模型与默认音色++- 打开 **应用设置 → AI 服务商 → Google**,模型列表的 **TTS** 标签页会列出 Gemini 语音模型:++ | 模型 | 说明 |+ | ------------------------------ | -------------------------------- |+ | `gemini-3.8-flash-tts` | 默认启用,推荐使用。 |+ | `gemini-3.8-flash-lite-tts` | 默认启用,成本与延迟更低。 |+ | `gemini-2.5-flash-preview-tts` | 旧版预览模型,Google 最早于 2026-11-17 下线。 |+ | `gemini-2.5-pro-preview-tts` | 旧版预览模型,Google 最早于 2026-11-17 下线。 |++- 用模型右侧的开关启用或停用模型。++- 如需修改请求未指定音色时使用的音色,点击模型的 **配置** 按钮,在 **默认音色** 中选择。列表包含 Gemini 全部 30 个预置音色及其风格(如 `Kore · Firm`、`Puck · Upbeat`)。留空则使用模型默认音色 `Kore`。该设置按模型保存,对 LobeHub CLI 和 `/api/v1/audio/speech` 接口生效。++### 生成语音++```bash+lh generate tts "Hello from LobeHub" -m gemini-3.8-flash-tts -o hello.mp3+lh generate tts "你好,欢迎使用 LobeHub。" -m google/gemini-3.8-flash-tts --voice Puck \+ --instructions "Say it slowly and warmly" -o hello-zh.mp3+```++- **音色**:30 个预置音色之一,如 `Kore`、`Puck`、`Zephyr`、`Charon`。每个音色都支持全部语言,包括中文和英文。+- **风格**:Gemini 没有数值化的语速、音调和音量参数,请用 `--instructions` 以自然语言描述语速和语气,例如「用平静的语气慢慢说」。Gemini 模型会拒绝 `--speed`、`--pitch`、`--volume` 和 `--emotion`。+- **格式**:Gemini 返回 24 kHz、16 位单声道 PCM,LobeHub 将其编码为 MP3(24 kHz 单声道,40 kbps)。通过 CLI 和语音接口只返回这一种格式(`audio/mpeg`)。+- **长度**:单次请求最多返回约 11 分钟音频,更长的文本请拆成多次请求。+- **计费**:Gemini TTS 按输入文本 Token 与生成的音频 Token(每秒音频约 25 个 Token)计费,详见 [Gemini API 价格](https://ai.google.dev/gemini-api/docs/pricing)。++### 常见问题++- **「Google API Key 不正确或为空……」**:未设置 API Key,或 Google 拒绝了该 Key。请在 **应用设置 → AI 服务商 → Google** 中检查,自部署服务请检查 `GOOGLE_API_KEY`。+- **限流错误**:请求超出了当前 Gemini API 档位的 TTS 速率限制。请稍后重试,或提升 Google Cloud 项目的档位。+- **内容被拦截**:Gemini 出于安全原因拒绝了该文本,请调整措辞。diff --git a/locales/en-US/modelProvider.json b/locales/en-US/modelProvider.jsonindex 11f3f9b1d87..0627d4e4464 100644--- a/locales/en-US/modelProvider.json+++ b/locales/en-US/modelProvider.json@@ -287,6 +287,10 @@"providerModels.item.modelConfig.tokens.extra": "Set the maximum number of tokens supported by the model","providerModels.item.modelConfig.tokens.title": "Maximum Context Window","providerModels.item.modelConfig.tokens.unlimited": "Unlimited",+ "providerModels.item.modelConfig.ttsVoice.extra": "Used when a speech request does not name a voice. Leave empty to use the model default.",+ "providerModels.item.modelConfig.ttsVoice.placeholder": "Model default ({{voice}})",+ "providerModels.item.modelConfig.ttsVoice.placeholderCustom": "Enter a voice ID",+ "providerModels.item.modelConfig.ttsVoice.title": "Default Voice","providerModels.item.modelConfig.type.extra": "Different model types have distinct use cases and capabilities","providerModels.item.modelConfig.type.options.asr": "Speech-to-Text","providerModels.item.modelConfig.type.options.chat": "Chat",diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.jsonindex 276462aad06..8850e6e34f6 100644--- a/locales/zh-CN/modelProvider.json+++ b/locales/zh-CN/modelProvider.json@@ -287,6 +287,10 @@"providerModels.item.modelConfig.tokens.extra": "设置模型支持的最大 Token 数","providerModels.item.modelConfig.tokens.title": "最大上下文窗口","providerModels.item.modelConfig.tokens.unlimited": "无限制",+ "providerModels.item.modelConfig.ttsVoice.extra": "语音合成请求未指定音色时使用。留空则使用模型默认音色。",+ "providerModels.item.modelConfig.ttsVoice.placeholder": "模型默认({{voice}})",+ "providerModels.item.modelConfig.ttsVoice.placeholderCustom": "输入音色 ID",+ "providerModels.item.modelConfig.ttsVoice.title": "默认音色","providerModels.item.modelConfig.type.extra": "不同模型类型拥有差异化的使用场景与能力","providerModels.item.modelConfig.type.options.asr": "语音转文本","providerModels.item.modelConfig.type.options.chat": "对话",diff --git a/package.json b/package.jsonindex 5471fece7ac..c70a26fbf09 100644--- a/package.json+++ b/package.json@@ -223,7 +223,7 @@"@fal-ai/client": "^1.10.1","@floating-ui/react": "^0.27.20","@formkit/auto-animate": "^0.9.0",- "@google/genai": "^2.13.0",+ "@google/genai": "^2.24.0","@henrygd/queue": "^1.2.0","@huggingface/inference": "^4.13.25","@icons-pack/react-simple-icons": "^13.15.1",diff --git a/packages/builtin-skills/src/lobehub/references/generate.ts b/packages/builtin-skills/src/lobehub/references/generate.tsindex 593a7ae9a22..d9fe59dd77b 100644--- a/packages/builtin-skills/src/lobehub/references/generate.ts+++ b/packages/builtin-skills/src/lobehub/references/generate.ts@@ -33,6 +33,19 @@ lh gen json "Extract the person" --schema ./person.json --schema-name person --s- It is a single request: \`--stream\`, \`--temperature\` and \`--max-tokens\` are not accepted options- Use \`lh gen text\` when you want prose+## Text-to-Speech++\`lh gen tts\` synthesizes with the provider's saved API key. A bare model id picks the provider of its built-in card.++\`\`\`bash+lh gen tts "Hello" -m gemini-3.8-flash-tts --voice Kore -o hello.mp3+lh gen tts "你好" -m minimax/speech-2.8-hd -o hello-zh.mp3+\`\`\`++- Without \`--voice\`, the server uses the Default Voice saved for the model in Settings → AI Providers, then the model's default voice+- Gemini TTS (Google provider): 30 prebuilt voices such as \`Kore\`, \`Puck\`, \`Zephyr\`; control pace and tone with \`--instructions\` (no \`--speed\`); output is MP3+- The server rejects params the model does not support, e.g. \`--speed\` on Gemini models+## Tips- Image/video generation is async; use \`status\` or \`download\` to get resultsdiff --git a/packages/locales/src/default/modelProvider.ts b/packages/locales/src/default/modelProvider.tsindex 60e9e2b9a56..0630e39c7d6 100644--- a/packages/locales/src/default/modelProvider.ts+++ b/packages/locales/src/default/modelProvider.ts@@ -375,6 +375,11 @@ export default {'Set the maximum number of tokens supported by the model','providerModels.item.modelConfig.tokens.title': 'Maximum Context Window','providerModels.item.modelConfig.tokens.unlimited': 'Unlimited',+ 'providerModels.item.modelConfig.ttsVoice.extra':+ 'Used when a speech request does not name a voice. Leave empty to use the model default.',+ 'providerModels.item.modelConfig.ttsVoice.placeholder': 'Model default ({{voice}})',+ 'providerModels.item.modelConfig.ttsVoice.placeholderCustom': 'Enter a voice ID',+ 'providerModels.item.modelConfig.ttsVoice.title': 'Default Voice','providerModels.item.modelConfig.type.extra':'Different model types have distinct use cases and capabilities','providerModels.item.modelConfig.type.options.asr': 'Speech-to-Text',diff --git a/packages/model-bank/src/aiModels/google/index.ts b/packages/model-bank/src/aiModels/google/index.tsindex fd61d40f12d..da096de1620 100644--- a/packages/model-bank/src/aiModels/google/index.ts+++ b/packages/model-bank/src/aiModels/google/index.ts@@ -7,6 +7,7 @@ import {import type { ModelParamsSchema } from '../../standard-parameters';import type { AIChatModelCard, AIImageModelCard, AIVideoModelCard } from '../../types';import { gemini25ChatModels } from './gemini25';+import { googleTTSModels } from './tts';/*** gemini implicit caching not extra cost@@ -1168,6 +1169,11 @@ const googleVideoModels: AIVideoModelCard[] = [},];-export const allModels = [...googleChatModels, ...googleImageModels, ...googleVideoModels];+export const allModels = [+ ...googleChatModels,+ ...googleImageModels,+ ...googleVideoModels,+ ...googleTTSModels,+];export default allModels;diff --git a/packages/model-bank/src/aiModels/google/tts.ts b/packages/model-bank/src/aiModels/google/tts.tsnew file mode 100644index 00000000000..63856426bb9--- /dev/null+++ b/packages/model-bank/src/aiModels/google/tts.ts@@ -0,0 +1,90 @@+import { googleTTSSchema, googleTTSVoices } from '../../const/ttsParameters';+import type { AITTSModelCard } from '../../types';++/**+ * Gemini TTS through `generateContent`. Billed per token: text input and audio output+ * (about 25 audio tokens per second of speech). Google halves the 3.8 TTS rates through+ * 2026-12-31; `originalRate` keeps the list price from 2027-01-01.+ * Gemini 2.5 preview TTS is listed as legacy: Google shuts it down on 2026-11-17 at the+ * earliest and recommends the 3.8 models instead.+ * @see https://ai.google.dev/gemini-api/docs/pricing+ * @see https://ai.google.dev/gemini-api/docs/deprecations+ */+export const googleTTSModels: AITTSModelCard[] = [+ {+ description:+ 'Gemini 3.8 Flash TTS turns text into natural, controllable speech with 30 prebuilt voices; style, pace and tone follow natural-language instructions.',+ displayName: 'Gemini 3.8 Flash TTS',+ enabled: true,+ id: 'gemini-3.8-flash-tts',+ parameters: googleTTSSchema,+ pricing: {+ units: [+ { name: 'textInput', originalRate: 1, rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ {+ name: 'audioOutput',+ originalRate: 18,+ rate: 9,+ strategy: 'fixed',+ unit: 'millionTokens',+ },+ ],+ },+ type: 'tts',+ voices: googleTTSVoices,+ },+ {+ description:+ 'Gemini 3.8 Flash-Lite TTS is the low-cost, low-latency Gemini speech model with the same 30 prebuilt voices and instruction-driven style control.',+ displayName: 'Gemini 3.8 Flash-Lite TTS',+ enabled: true,+ id: 'gemini-3.8-flash-lite-tts',+ parameters: googleTTSSchema,+ pricing: {+ units: [+ { name: 'textInput', originalRate: 1, rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ {+ name: 'audioOutput',+ originalRate: 12,+ rate: 6,+ strategy: 'fixed',+ unit: 'millionTokens',+ },+ ],+ },+ type: 'tts',+ voices: googleTTSVoices,+ },+ {+ description:+ 'Gemini 2.5 Flash Preview TTS is the earlier low-latency Gemini speech model. Google shuts it down on 2026-11-17; use Gemini 3.8 Flash TTS instead.',+ displayName: 'Gemini 2.5 Flash Preview TTS',+ id: 'gemini-2.5-flash-preview-tts',+ legacy: true,+ parameters: googleTTSSchema,+ pricing: {+ units: [+ { name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 10, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ type: 'tts',+ voices: googleTTSVoices,+ },+ {+ description:+ 'Gemini 2.5 Pro Preview TTS is the earlier high-quality Gemini speech model. Google shuts it down on 2026-11-17; use Gemini 3.8 Flash TTS instead.',+ displayName: 'Gemini 2.5 Pro Preview TTS',+ id: 'gemini-2.5-pro-preview-tts',+ legacy: true,+ parameters: googleTTSSchema,+ pricing: {+ units: [+ { name: 'textInput', rate: 1, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 20, strategy: 'fixed', unit: 'millionTokens' },+ ],+ },+ type: 'tts',+ voices: googleTTSVoices,+ },+];diff --git a/packages/model-bank/src/const/__tests__/ttsParameters.test.ts b/packages/model-bank/src/const/__tests__/ttsParameters.test.tsindex f9e604f3a06..e0b2c5956c7 100644--- a/packages/model-bank/src/const/__tests__/ttsParameters.test.ts+++ b/packages/model-bank/src/const/__tests__/ttsParameters.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import elevenlabsModels from '../../aiModels/elevenlabs';+import googleModels from '../../aiModels/google';import minimaxModels from '../../aiModels/minimax';import { openaiTTSModels } from '../../aiModels/openai/nonChat';import {@@ -213,3 +214,82 @@ describe('ElevenLabs TTS model cards', () => {expect(ids).not.toContain(legacyId);});});++describe('Google Gemini TTS model cards', () => {+ const googleTTSModels = googleModels.filter(+ (card): card is AITTSModelCard => card.type === 'tts',+ );++ it('lists the Gemini 3.8 TTS models, and 2.5 preview TTS as legacy', () => {+ expect(googleTTSModels.map((card) => [card.id, !!card.enabled, !!card.legacy])).toEqual([+ ['gemini-3.8-flash-tts', true, false],+ ['gemini-3.8-flash-lite-tts', true, false],+ ['gemini-2.5-flash-preview-tts', false, true],+ ['gemini-2.5-pro-preview-tts', false, true],+ ]);+ });++ it.each(googleTTSModels.map((card) => [card.id, card]))(+ '%s offers the 30 prebuilt voices with Kore as the default',+ (_id, card) => {+ expect(() => validateTTSModelParamsSchema(card.parameters)).not.toThrow();+ for (const voice of card.voices!) expect(() => TTSVoiceSchema.parse(voice)).not.toThrow();++ const voiceIds = card.voices!.map((voice) => voice.id);+ expect(voiceIds).toHaveLength(30);+ expect(new Set(voiceIds).size).toBe(30);+ expect(voiceIds).toEqual(+ expect.arrayContaining(['Zephyr', 'Puck', 'Charon', 'Kore', 'Fenrir', 'Sulafat']),+ );+ expect(card.parameters!.voice!.default).toBe('Kore');+ expect(voiceIds).toContain(card.parameters!.voice!.default);+ },+ );++ it('declares only the params the runtime honors: format and style instructions', () => {+ for (const card of googleTTSModels) {+ expect(Object.keys(card.parameters!).sort()).toEqual(['format', 'instructions', 'voice']);+ expect(card.parameters!.format).toEqual({ default: 'mp3', enum: ['mp3', 'wav', 'pcm'] });+ expect(extractTTSDefaultValues(card.parameters!)).toEqual({+ format: 'mp3',+ instructions: '',+ });+ // Gemini has no numeric speed: a legacy speed must be reported, not silently dropped.+ expect(validateTTSParams(card.parameters!, { speed: 1.5 })).toEqual([+ { key: 'speed', reason: 'not supported by this model' },+ ]);+ expect(validateTTSParams(card.parameters!, { format: 'opus' })).toHaveLength(1);+ expect(+ validateTTSParams(card.parameters!, { format: 'mp3', instructions: 'speak slowly' }),+ ).toEqual([]);+ }+ });++ it('bills text input and audio output per million tokens', () => {+ const units = Object.fromEntries(+ googleTTSModels.map((card) => [+ card.id,+ card.pricing!.units.map((unit) => [unit.name, unit.unit, (unit as any).rate]),+ ]),+ );++ expect(units).toEqual({+ 'gemini-3.8-flash-lite-tts': [+ ['textInput', 'millionTokens', 0.5],+ ['audioOutput', 'millionTokens', 6],+ ],+ 'gemini-3.8-flash-tts': [+ ['textInput', 'millionTokens', 0.5],+ ['audioOutput', 'millionTokens', 9],+ ],+ 'gemini-2.5-flash-preview-tts': [+ ['textInput', 'millionTokens', 0.5],+ ['audioOutput', 'millionTokens', 10],+ ],+ 'gemini-2.5-pro-preview-tts': [+ ['textInput', 'millionTokens', 1],+ ['audioOutput', 'millionTokens', 20],+ ],+ });+ });+});diff --git a/packages/model-bank/src/const/ttsParameters.ts b/packages/model-bank/src/const/ttsParameters.tsindex efef7dbe89f..35147111a1c 100644--- a/packages/model-bank/src/const/ttsParameters.ts+++ b/packages/model-bank/src/const/ttsParameters.ts@@ -363,3 +363,63 @@ export const elevenlabsExpressiveTTSSchema: TTSModelParamsSchema = {format: { default: 'mp3', enum: ELEVENLABS_TTS_FORMATS },voice: { default: ELEVENLABS_DEFAULT_VOICE },};++/**+ * Gemini TTS prebuilt voices, shared by every Gemini TTS model. Descriptions are Google's+ * own one-word characterizations; genders follow the matching Chirp 3 HD voices.+ * @see https://ai.google.dev/gemini-api/docs/speech-generation#voices+ */+export const googleTTSVoices: TTSVoice[] = (+ [+ ['Achernar', 'female', 'Soft'],+ ['Achird', 'male', 'Friendly'],+ ['Algenib', 'male', 'Gravelly'],+ ['Algieba', 'male', 'Smooth'],+ ['Alnilam', 'male', 'Firm'],+ ['Aoede', 'female', 'Breezy'],+ ['Autonoe', 'female', 'Bright'],+ ['Callirrhoe', 'female', 'Easy-going'],+ ['Charon', 'male', 'Informative'],+ ['Despina', 'female', 'Smooth'],+ ['Enceladus', 'male', 'Breathy'],+ ['Erinome', 'female', 'Clear'],+ ['Fenrir', 'male', 'Excitable'],+ ['Gacrux', 'female', 'Mature'],+ ['Iapetus', 'male', 'Clear'],+ ['Kore', 'female', 'Firm'],+ ['Laomedeia', 'female', 'Upbeat'],+ ['Leda', 'female', 'Youthful'],+ ['Orus', 'male', 'Firm'],+ ['Puck', 'male', 'Upbeat'],+ ['Pulcherrima', 'female', 'Forward'],+ ['Rasalgethi', 'male', 'Informative'],+ ['Sadachbia', 'male', 'Lively'],+ ['Sadaltager', 'male', 'Knowledgeable'],+ ['Schedar', 'male', 'Even'],+ ['Sulafat', 'female', 'Warm'],+ ['Umbriel', 'male', 'Easy-going'],+ ['Vindemiatrix', 'female', 'Gentle'],+ ['Zephyr', 'female', 'Bright'],+ ['Zubenelgenubi', 'male', 'Casual'],+ ] as const+).map(([id, gender, description]) => ({+ description,+ displayName: id,+ gender,+ id,+ language: 'multilingual',+}));++/**+ * Gemini returns 16-bit PCM, which the runtime encodes to MP3 or wraps as WAV. Gemini has no+ * numeric speed, pitch or volume control: pace and tone come from the style `instructions`+ * (e.g. "speak slowly and calmly"), so only those are declared.+ */+export const googleTTSSchema: TTSModelParamsSchema = {+ format: { default: 'mp3', enum: ['mp3', 'wav', 'pcm'] },+ instructions: {+ default: '',+ description: 'Style, tone or pace, e.g. "speak slowly in a warm, calm voice"',+ },+ voice: { default: 'Kore' },+};diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.tsindex 33904f04f5c..9a7329dbc0d 100644--- a/packages/model-bank/src/types/aiModel.ts+++ b/packages/model-bank/src/types/aiModel.ts@@ -589,6 +589,11 @@ export interface AiModelSettings {*/searchImpl?: ModelSearchImplementType;searchProvider?: string;+ /**+ * The user's default voice for a `tts` model, used when a speech request names no voice.+ * Takes precedence over the card's `parameters.voice.default`.+ */+ ttsVoice?: string;}export const ExtendParamsTypeSchema = z.enum([@@ -653,6 +658,7 @@ export const AiModelSettingsSchema = z.object({extendParams: z.array(ExtendParamsTypeSchema).optional(),searchImpl: ModelSearchImplementTypeSchema.optional(),searchProvider: z.string().optional(),+ ttsVoice: z.string().optional(),});export interface AIChatModelCard extends AIBaseModelCard {@@ -800,6 +806,8 @@ export interface AiProviderModelListItem {source?: AiModelSourceType;type: AiModelType;visible?: boolean;+ /** Voice catalog of a built-in `tts` model, carried over from its card. */+ voices?: TTSVoice[];}// Updatediff --git a/packages/model-runtime/package.json b/packages/model-runtime/package.jsonindex b387a2a5444..a385ebf9255 100644--- a/packages/model-runtime/package.json+++ b/packages/model-runtime/package.json@@ -2,6 +2,8 @@"name": "@lobechat/model-runtime","version": "1.0.0","private": true,+ "homepage": "https://github.com/lobehub/lobehub/tree/canary/packages/model-runtime",+ "license": "MIT","exports": {".": "./src/index.ts","./errors": "./src/errors/index.ts",@@ -31,8 +33,9 @@"@aws-sdk/client-bedrock-runtime": "^3.1076.0","@azure-rest/ai-inference": "1.0.0-beta.5","@azure/core-auth": "^1.10.1",+ "@breezystack/lamejs": "^1.2.7","@fal-ai/client": "^1.10.1",- "@google/genai": "^2.13.0",+ "@google/genai": "^2.24.0","@huggingface/inference": "^4.13.21","@lobechat/business-model-bank": "workspace:*","@lobechat/business-model-runtime": "workspace:*",@@ -59,7 +62,5 @@},"peerDependencies": {"zod": "^4.4.3"- },- "license": "MIT",- "homepage": "https://github.com/lobehub/lobehub/tree/canary/packages/model-runtime"+ }}diff --git a/packages/model-runtime/src/providers/google/createSpeech.test.ts b/packages/model-runtime/src/providers/google/createSpeech.test.tsnew file mode 100644index 00000000000..c4ac478171d--- /dev/null+++ b/packages/model-runtime/src/providers/google/createSpeech.test.ts@@ -0,0 +1,494 @@+// @vitest-environment node+import type { GenerateContentResponse, GoogleGenAI } from '@google/genai';+import { ApiError } from '@google/genai';+import { AgentRuntimeErrorType } from '@lobechat/types';+import type { Pricing } from 'model-bank';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getModelPricing } from '../../utils/getModelPricing';+import {+ buildGeminiSpeechRequest,+ convertGeminiSpeechTokenUsage,+ createGeminiSpeech,+ extractGeminiSpeechAudio,+ getGeminiSpeechErrorType,+ isPromptStyledGeminiTTSModel,+} from './createSpeech';+import { LobeGoogleAI } from './index';+import { encodeWav } from './speechAudio';++vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));++const flashPricing: Pricing = {+ units: [+ { name: 'textInput', rate: 0.5, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 9, strategy: 'fixed', unit: 'millionTokens' },+ ],+};++/** One second of 24 kHz mono 16-bit PCM (a quiet ramp). */+const pcmSecond = () => {+ const data = Buffer.alloc(48_000);+ for (let i = 0; i < 24_000; i++) data.writeInt16LE((i % 200) * 20 - 2000, i * 2);+ return data;+};++const audioResponse = (+ data: Buffer,+ mimeType = 'audio/L16;codec=pcm;rate=24000',+ overrides: Partial<GenerateContentResponse> = {},+) =>+ ({+ candidates: [+ {+ content: { parts: [{ inlineData: { data: data.toString('base64'), mimeType } }] },+ finishReason: 'STOP',+ },+ ],+ usageMetadata: {+ candidatesTokenCount: 25,+ candidatesTokensDetails: [{ modality: 'AUDIO', tokenCount: 25 }],+ promptTokenCount: 8,+ promptTokensDetails: [{ modality: 'TEXT', tokenCount: 8 }],+ totalTokenCount: 33,+ },+ ...overrides,+ }) as unknown as GenerateContentResponse;++const createClient = (generateContent: ReturnType<typeof vi.fn>) =>+ ({ models: { generateContent } }) as unknown as GoogleGenAI;++const payload = { input: 'Hello there', model: 'gemini-3.8-flash-tts', voice: 'Kore' };++describe('buildGeminiSpeechRequest', () => {+ it('requests AUDIO with the prebuilt voice and the text as the only part', () => {+ const { format, request } = buildGeminiSpeechRequest(payload, 'gemini-3.8-flash-tts');++ expect(format).toBe('mp3');+ expect(request).toEqual({+ config: {+ responseModalities: ['AUDIO'],+ speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } } },+ },+ contents: [{ parts: [{ text: 'Hello there' }], role: 'user' }],+ model: 'gemini-3.8-flash-tts',+ });+ });++ it('sends style instructions as speechMetadata on current models', () => {+ const { request } = buildGeminiSpeechRequest(+ { ...payload, params: { instructions: ' speak slowly and warmly ' } },+ 'gemini-3.8-flash-tts',+ );++ expect(request.contents).toEqual([+ {+ parts: [{ speechMetadata: { style: 'speak slowly and warmly' }, text: 'Hello there' }],+ role: 'user',+ },+ ]);+ });++ it('prefixes style instructions into the prompt on Gemini 2.5 / 3.1 preview TTS', () => {+ for (const model of ['gemini-2.5-flash-preview-tts', 'gemini-3.1-flash-tts-preview']) {+ const { request } = buildGeminiSpeechRequest(+ { ...payload, model, params: { instructions: 'Say cheerfully' } },+ model,+ );+ expect(request.contents).toEqual([+ { parts: [{ text: 'Say cheerfully: Hello there' }], role: 'user' },+ ]);+ }+ });++ it('classifies legacy TTS ids, including gateway-prefixed ones, without backtracking', () => {+ expect(isPromptStyledGeminiTTSModel('gemini-2.5-pro-preview-tts')).toBe(true);+ expect(isPromptStyledGeminiTTSModel('google/gemini-3.1-flash-tts-preview')).toBe(true);+ expect(isPromptStyledGeminiTTSModel('gemini-3.8-flash-tts')).toBe(false);+ expect(isPromptStyledGeminiTTSModel('gemini-2.5-flash')).toBe(false);++ // CodeQL js/polynomial-redos: a backtracking pattern stalls on many prefix repetitions+ // until the test times out; the string checks return immediately.+ expect(isPromptStyledGeminiTTSModel('gemini-2.5-'.repeat(50_000))).toBe(false);+ });++ it('passes the abort signal and per-request headers to the SDK', () => {+ const signal = new AbortController().signal;+ const { request } = buildGeminiSpeechRequest(payload, 'gemini-3.8-flash-tts', {+ headers: { 'x-trace': '1' },+ signal,+ });++ expect(request.config).toMatchObject({+ abortSignal: signal,+ httpOptions: { headers: { 'x-trace': '1' } },+ });+ });++ it('rejects formats it cannot produce from PCM', () => {+ expect(() =>+ buildGeminiSpeechRequest({ ...payload, params: { format: 'opus' } }, payload.model),+ ).toThrow(/does not support the "opus" format/);+ });+});++describe('extractGeminiSpeechAudio', () => {+ it('parses the sample rate from the mime type and joins every audio part', () => {+ const first = pcmSecond();+ const response = audioResponse(first, 'audio/L16;codec=pcm;rate=16000');+ response.candidates![0].content!.parts!.push({+ inlineData: { data: first.toString('base64'), mimeType: 'audio/L16;codec=pcm;rate=16000' },+ });++ const pcm = extractGeminiSpeechAudio(response);+ expect(pcm.sampleRate).toBe(16_000);+ expect(pcm.data.length).toBe(first.length * 2);+ });++ it('maps a blocked prompt and a SAFETY finish to ContentModeration', () => {+ expect(() =>+ extractGeminiSpeechAudio({+ promptFeedback: { blockReason: 'PROHIBITED_CONTENT' },+ } as unknown as GenerateContentResponse),+ ).toThrow(expect.objectContaining({ errorType: AgentRuntimeErrorType.ContentModeration }));++ expect(() =>+ extractGeminiSpeechAudio({+ candidates: [{ content: { parts: [] }, finishReason: 'SAFETY' }],+ } as unknown as GenerateContentResponse),+ ).toThrow(expect.objectContaining({ errorType: AgentRuntimeErrorType.ContentModeration }));+ });++ it('treats a text-only answer as a provider error, not a billable synthesis', () => {+ expect(() =>+ extractGeminiSpeechAudio({+ candidates: [{ content: { parts: [{ text: 'I cannot' }] }, finishReason: 'STOP' }],+ } as unknown as GenerateContentResponse),+ ).toThrow(+ expect.objectContaining({+ errorType: AgentRuntimeErrorType.ProviderBizError,+ message: 'Gemini returned no audio (finishReason: STOP)',+ }),+ );+ });+});++describe('getGeminiSpeechErrorType', () => {+ it.each([+ [+ 400,+ { details: [{ reason: 'API_KEY_INVALID' }], status: 'INVALID_ARGUMENT' },+ 'InvalidProviderAPIKey',+ ],+ [400, { message: 'API key not valid. Please pass a valid API key.' }, 'InvalidProviderAPIKey'],+ [401, { status: 'UNAUTHENTICATED' }, 'InvalidProviderAPIKey'],+ [403, { status: 'PERMISSION_DENIED' }, 'PermissionDenied'],+ [404, { status: 'NOT_FOUND' }, 'ModelNotFound'],+ [429, { status: 'RESOURCE_EXHAUSTED' }, 'RateLimitExceeded'],+ [+ 400,+ { status: 'INVALID_ARGUMENT', message: 'Voice name xyz is not supported' },+ 'ProviderBizError',+ ],+ [+ 400,+ { message: 'User location is not supported for the API use.', status: 'FAILED_PRECONDITION' },+ 'LocationNotSupportError',+ ],+ [503, { status: 'UNAVAILABLE' }, 'ProviderServiceUnavailable'],+ [undefined, { status: 'RESOURCE_EXHAUSTED' }, 'RateLimitExceeded'],+ [undefined, { status: 'PERMISSION_DENIED' }, 'PermissionDenied'],+ [418, undefined, 'ProviderBizError'],+ ] as const)('HTTP %s %j -> %s', (status, body, expected) => {+ expect(getGeminiSpeechErrorType(status, body as any)).toBe(expected);+ });+});++describe('convertGeminiSpeechTokenUsage', () => {+ it('bills prompt tokens as text input and AUDIO candidate tokens as audio output', () => {+ expect(+ convertGeminiSpeechTokenUsage({+ candidatesTokenCount: 30,+ candidatesTokensDetails: [{ modality: 'AUDIO' as any, tokenCount: 28 }],+ promptTokenCount: 10,+ totalTokenCount: 40,+ }),+ ).toEqual({+ inputTextTokens: 10,+ outputAudioTokens: 28,+ totalInputTokens: 10,+ totalOutputTokens: 28,+ totalTokens: 40,+ });+ });++ it('falls back to candidatesTokenCount and returns undefined without counts', () => {+ expect(+ convertGeminiSpeechTokenUsage({ candidatesTokenCount: 5, promptTokenCount: 2 }),+ ).toMatchObject({ outputAudioTokens: 5, totalTokens: 7 });+ expect(convertGeminiSpeechTokenUsage({ promptTokenCount: 2 })).toBeUndefined();+ expect(convertGeminiSpeechTokenUsage(undefined)).toBeUndefined();+ });+});++describe('createGeminiSpeech', () => {+ beforeEach(() => {+ vi.mocked(getModelPricing).mockResolvedValue(flashPricing);+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it('returns playable MP3 by default and reports token usage with cost', async () => {+ const generateContent = vi.fn().mockResolvedValue(audioResponse(pcmSecond()));+ const onUsage = vi.fn();++ const result = await createGeminiSpeech(createClient(generateContent), payload, {+ onUsage,+ provider: 'google',+ });++ const audio = Buffer.from(result.audio);+ expect(result.format).toBe('mp3');+ expect(audio[0] === 0xff || audio.toString('ascii', 0, 3) === 'ID3').toBe(true);+ expect(audio.length).toBeLessThan(48_000 / 4);++ // 8 * $0.5/M + 25 * $9/M+ const expectedCost = (8 * 0.5 + 25 * 9) / 1_000_000;+ expect(result.usage).toMatchObject({+ inputCharacters: 11,+ inputTextTokens: 8,+ outputAudioTokens: 25,+ totalTokens: 33,+ });+ expect(result.usage?.cost).toBeCloseTo(expectedCost, 10);+ expect(onUsage).toHaveBeenCalledWith(result.usage);+ expect(getModelPricing).toHaveBeenCalledWith('gemini-3.8-flash-tts', 'google', undefined);+ });++ it('wraps PCM in a WAV header with the parsed sample rate', async () => {+ const pcm = pcmSecond();+ const generateContent = vi+ .fn()+ .mockResolvedValue(audioResponse(pcm, 'audio/L16;codec=pcm;rate=16000'));++ const result = await createGeminiSpeech(+ createClient(generateContent),+ { ...payload, params: { format: 'wav' } },+ { provider: 'google' },+ );++ const wav = Buffer.from(result.audio);+ expect(result.format).toBe('wav');+ expect(wav.toString('ascii', 0, 4)).toBe('RIFF');+ expect(wav.readUInt32LE(24)).toBe(16_000);+ expect(wav.subarray(44).equals(pcm)).toBe(true);+ });++ it('returns the raw PCM for format pcm, also when Gemini answers with WAV', async () => {+ const pcm = pcmSecond();+ const wav = encodeWav({ bitsPerSample: 16, channels: 1, data: pcm, sampleRate: 24_000 });+ const generateContent = vi.fn().mockResolvedValue(audioResponse(wav, 'audio/wav'));++ const result = await createGeminiSpeech(+ createClient(generateContent),+ { ...payload, params: { format: 'pcm' } },+ { provider: 'google' },+ );++ expect(result.format).toBe('pcm');+ expect(Buffer.from(result.audio).equals(pcm)).toBe(true);+ });++ it('sends the mapped upstream model id but prices the catalog id', async () => {+ const generateContent = vi.fn().mockResolvedValue(audioResponse(pcmSecond()));++ await createGeminiSpeech(createClient(generateContent), payload, {+ modelIdMapping: { 'gemini-3.8-flash-tts': 'gemini-3.8-flash-tts-001' },+ provider: 'google',+ });++ expect(generateContent.mock.calls[0][0].model).toBe('gemini-3.8-flash-tts-001');+ expect(getModelPricing).toHaveBeenCalledWith('gemini-3.8-flash-tts', 'google', undefined);+ });++ it('turns an SDK ApiError into a readable runtime error payload', async () => {+ const generateContent = vi.fn().mockRejectedValue(+ new ApiError({+ message: JSON.stringify({+ error: {+ code: 400,+ details: [+ { '@type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'API_KEY_INVALID' },+ ],+ message: 'API key not valid. Please pass a valid API key.',+ status: 'INVALID_ARGUMENT',+ },+ }),+ status: 400,+ }),+ );+ const onUsage = vi.fn();++ await expect(+ createGeminiSpeech(createClient(generateContent), payload, { onUsage, provider: 'google' }),+ ).rejects.toEqual({+ error: {+ code: 400,+ httpStatus: 400,+ message:+ 'Gemini API error (INVALID_ARGUMENT): API key not valid. Please pass a valid API key.',+ status: 'INVALID_ARGUMENT',+ },+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,+ provider: 'google',+ });+ expect(onUsage).not.toHaveBeenCalled();+ });++ it('maps a quota error and keeps the upstream message', async () => {+ const generateContent = vi.fn().mockRejectedValue(+ new ApiError({+ message: JSON.stringify({+ error: {+ code: 429,+ message: 'You exceeded your current quota.',+ status: 'RESOURCE_EXHAUSTED',+ },+ }),+ status: 429,+ }),+ );++ await expect(+ createGeminiSpeech(createClient(generateContent), payload, { provider: 'google' }),+ ).rejects.toMatchObject({+ error: { message: 'Gemini API error (RESOURCE_EXHAUSTED): You exceeded your current quota.' },+ errorType: AgentRuntimeErrorType.RateLimitExceeded,+ });+ });++ it('maps an over-long input to ExceededContextWindow through the shared Google parser', async () => {+ const generateContent = vi.fn().mockRejectedValue(+ new ApiError({+ message: JSON.stringify({+ error: {+ code: 400,+ message:+ 'The input token count (9000) exceeds the maximum number of tokens allowed (8192).',+ status: 'INVALID_ARGUMENT',+ },+ }),+ status: 400,+ }),+ );++ await expect(+ createGeminiSpeech(createClient(generateContent), payload, { provider: 'google' }),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ExceededContextWindow });+ });++ it('rejects an empty audio payload without billing', async () => {+ const wav = encodeWav({+ bitsPerSample: 16,+ channels: 1,+ data: Buffer.alloc(0),+ sampleRate: 24_000,+ });+ const generateContent = vi.fn().mockResolvedValue(audioResponse(wav, 'audio/wav'));+ const onUsage = vi.fn();++ await expect(+ createGeminiSpeech(createClient(generateContent), payload, { onUsage, provider: 'google' }),+ ).rejects.toMatchObject({+ error: { message: 'Gemini returned empty audio' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ });+ expect(onUsage).not.toHaveBeenCalled();+ });++ it('reports a safety block without billing', async () => {+ const generateContent = vi.fn().mockResolvedValue({+ candidates: [{ content: { parts: [] }, finishReason: 'PROHIBITED_CONTENT' }],+ usageMetadata: { promptTokenCount: 8, totalTokenCount: 8 },+ });+ const onUsage = vi.fn();++ await expect(+ createGeminiSpeech(createClient(generateContent), payload, { onUsage, provider: 'google' }),+ ).rejects.toMatchObject({+ error: { finishReason: 'PROHIBITED_CONTENT' },+ errorType: AgentRuntimeErrorType.ContentModeration,+ });+ expect(onUsage).not.toHaveBeenCalled();+ });++ it('rethrows aborts untouched', async () => {+ const controller = new AbortController();+ controller.abort();+ const abortError = Object.assign(new Error('aborted'), { name: 'AbortError' });+ const generateContent = vi.fn().mockRejectedValue(abortError);++ await expect(+ createGeminiSpeech(createClient(generateContent), payload, {+ provider: 'google',+ signal: controller.signal,+ }),+ ).rejects.toBe(abortError);+ });+});++describe('LobeGoogleAI.textToSpeech', () => {+ beforeEach(() => {+ vi.mocked(getModelPricing).mockResolvedValue(flashPricing);+ });++ it('synthesizes through the provider client under the runtime provider id', async () => {+ const generateContent = vi.fn().mockResolvedValue(audioResponse(pcmSecond()));+ const runtime = new LobeGoogleAI({+ apiKey: 'test-key',+ client: createClient(generateContent),+ id: 'google',+ });++ const result = await runtime.textToSpeech(payload);++ expect(result.format).toBe('mp3');+ expect(generateContent).toHaveBeenCalledOnce();+ expect(getModelPricing).toHaveBeenCalledWith('gemini-3.8-flash-tts', 'google', undefined);+ });++ it('sends generateContent to the custom base URL with the provider API key', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(audioResponse(pcmSecond())), {+ headers: { 'content-type': 'application/json' },+ }),+ );+ vi.stubGlobal('fetch', fetchMock);++ try {+ const runtime = new LobeGoogleAI({+ apiKey: 'test-key',+ baseURL: 'https://proxy.example.com',+ });+ const result = await runtime.textToSpeech(payload);++ expect(result.format).toBe('mp3');+ const [url, init] = fetchMock.mock.calls[0];+ expect(String(url)).toBe(+ 'https://proxy.example.com/v1beta/models/gemini-3.8-flash-tts:generateContent',+ );+ expect(new Headers(init.headers).get('x-goog-api-key')).toBe('test-key');+ expect(JSON.parse(init.body)).toMatchObject({+ contents: [{ parts: [{ text: 'Hello there' }], role: 'user' }],+ generationConfig: {+ responseModalities: ['AUDIO'],+ speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: 'Kore' } } },+ },+ });+ } finally {+ vi.unstubAllGlobals();+ }+ });+});diff --git a/packages/model-runtime/src/providers/google/createSpeech.ts b/packages/model-runtime/src/providers/google/createSpeech.tsnew file mode 100644index 00000000000..bff0a003762--- /dev/null+++ b/packages/model-runtime/src/providers/google/createSpeech.ts@@ -0,0 +1,385 @@+import type {+ GenerateContentConfig,+ GenerateContentParameters,+ GenerateContentResponse,+ GenerateContentResponseUsageMetadata,+ GoogleGenAI,+ Part,+} from '@google/genai';+import { AgentRuntimeErrorType } from '@lobechat/types';+import createDebug from 'debug';+import type { TTSAudioFormat } from 'model-bank';+import { DEFAULT_TTS_AUDIO_FORMAT } from 'model-bank';++import { convertTextToSpeechUsage } from '../../core/usageConverters/tts';+import type { ILobeAgentRuntimeErrorType } from '../../types/error';+import type {+ TextToSpeechOptions,+ TextToSpeechPayload,+ TextToSpeechResponse,+} from '../../types/tts';+import { resolveTextToSpeechParams } from '../../types/tts';+import type { ChatCompletionErrorPayload } from '../../types/type';+import { AgentRuntimeError } from '../../utils/createError';+import { getModelPricing } from '../../utils/getModelPricing';+import { parseGoogleErrorMessage } from '../../utils/googleErrorParser';+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import { resolveMappedModelId } from '../../utils/modelIdMapping';+import type { PcmAudio } from './speechAudio';+import {+ decodeGeminiAudio,+ encodeMp3,+ encodeWav,+ SpeechAudioError,+ toArrayBuffer,+} from './speechAudio';++const log = createDebug('lobe-tts:google');++/** Formats the runtime can produce from Gemini's PCM output. */+export const GEMINI_TTS_FORMATS = ['mp3', 'wav', 'pcm'] as const satisfies TTSAudioFormat[];++/**+ * Gemini 2.5 and 3.1 TTS read style from the prompt itself ("Say cheerfully: ..."); later+ * models treat the text strictly as a transcript and take style from `speechMetadata`.+ * @see https://ai.google.dev/gemini-api/docs/speech-generation+ */+const PROMPT_STYLED_TTS_PREFIXES = ['gemini-2.5-', 'gemini-3.1-'];++/** Plain string checks: a model id comes from the caller, so no backtracking pattern runs on it. */+export const isPromptStyledGeminiTTSModel = (model: string) => {+ const id = model.toLowerCase().split('/').pop() ?? '';++ return id.includes('tts') && PROMPT_STYLED_TTS_PREFIXES.some((prefix) => id.startsWith(prefix));+};++const HTTP_ERROR_TYPES: Record<number, ILobeAgentRuntimeErrorType> = {+ 401: AgentRuntimeErrorType.InvalidProviderAPIKey,+ 403: AgentRuntimeErrorType.PermissionDenied,+ 404: AgentRuntimeErrorType.ModelNotFound,+ 429: AgentRuntimeErrorType.RateLimitExceeded,+ 500: AgentRuntimeErrorType.ProviderServiceUnavailable,+ 503: AgentRuntimeErrorType.ProviderServiceUnavailable,+ 504: AgentRuntimeErrorType.ProviderServiceUnavailable,+};++/**+ * Canonical Google RPC `error.status` values.+ * @see https://ai.google.dev/gemini-api/docs/troubleshooting#error-codes+ */+const GOOGLE_STATUS_ERROR_TYPES: Record<string, ILobeAgentRuntimeErrorType> = {+ DEADLINE_EXCEEDED: AgentRuntimeErrorType.ProviderServiceUnavailable,+ INTERNAL: AgentRuntimeErrorType.ProviderServiceUnavailable,+ INVALID_ARGUMENT: AgentRuntimeErrorType.ProviderBizError,+ NOT_FOUND: AgentRuntimeErrorType.ModelNotFound,+ PERMISSION_DENIED: AgentRuntimeErrorType.PermissionDenied,+ RESOURCE_EXHAUSTED: AgentRuntimeErrorType.RateLimitExceeded,+ UNAUTHENTICATED: AgentRuntimeErrorType.InvalidProviderAPIKey,+ UNAVAILABLE: AgentRuntimeErrorType.ProviderServiceUnavailable,+};++/** Finish / block reasons that mean the content was refused rather than failed. */+const MODERATION_REASONS = new Set(['BLOCKLIST', 'PROHIBITED_CONTENT', 'SAFETY', 'SPII']);++interface GoogleErrorBody {+ code?: number;+ details?: Array<{ reason?: string }>;+ message?: string;+ status?: string;+}++/** Thrown inside the request flow and unwrapped into a runtime error payload. */+class GeminiSpeechError extends Error {+ constructor(+ message: string,+ readonly errorType: ILobeAgentRuntimeErrorType,+ readonly detail?: Record<string, unknown>,+ ) {+ super(message);+ }+}++/** The JSON error body the SDK puts in `ApiError.message`, possibly after a text prefix. */+const parseGoogleErrorBody = (message: string): GoogleErrorBody | undefined => {+ const start = message.indexOf('{');+ if (start === -1) return;++ try {+ const parsed = JSON.parse(message.slice(start));+ return parsed?.error && typeof parsed.error === 'object' ? parsed.error : undefined;+ } catch {+ return;+ }+};++/**+ * Map an SDK / HTTP failure to a runtime error type. A rejected key comes back as+ * `400 INVALID_ARGUMENT` with reason `API_KEY_INVALID`, so it is checked before the+ * generic status mapping.+ */+export const getGeminiSpeechErrorType = (+ httpStatus: number | undefined,+ body: GoogleErrorBody | undefined,+): ILobeAgentRuntimeErrorType => {+ const message = body?.message ?? '';++ if (+ body?.details?.some((detail) => detail.reason === 'API_KEY_INVALID') ||+ message.includes('API key not valid') ||+ message.includes('API key expired')+ ) {+ return AgentRuntimeErrorType.InvalidProviderAPIKey;+ }+ if (message.includes('location is not supported')) {+ return AgentRuntimeErrorType.LocationNotSupportError;+ }++ return (+ (httpStatus !== undefined ? HTTP_ERROR_TYPES[httpStatus] : undefined) ??+ (body?.status ? GOOGLE_STATUS_ERROR_TYPES[body.status] : undefined) ??+ AgentRuntimeErrorType.ProviderBizError+ );+};++const toGeminiSpeechError = (error: unknown): GeminiSpeechError => {+ if (error instanceof GeminiSpeechError) return error;+ if (error instanceof SpeechAudioError) {+ return new GeminiSpeechError(error.message, AgentRuntimeErrorType.ProviderBizError);+ }++ const rawMessage = (error as Error)?.message ?? String(error);+ const status = (error as { status?: unknown })?.status;+ const httpStatus = typeof status === 'number' ? status : undefined;+ const body = parseGoogleErrorBody(rawMessage);++ const statusLabel = body?.status ?? httpStatus;+ const message = body?.message+ ? `Gemini API error${statusLabel ? ` (${statusLabel})` : ''}: ${body.message}`+ : rawMessage;++ let errorType = getGeminiSpeechErrorType(httpStatus, body);+ if (errorType === AgentRuntimeErrorType.ProviderBizError) {+ // Fall back to the provider-wide parser for classes such as an exceeded context window.+ const shared = parseGoogleErrorMessage(rawMessage).errorType;+ if (shared === AgentRuntimeErrorType.ExceededContextWindow) errorType = shared;+ }++ return new GeminiSpeechError(message, errorType, {+ ...(body?.code !== undefined && { code: body.code }),+ ...(body?.status && { status: body.status }),+ ...(httpStatus !== undefined && { httpStatus }),+ });+};++/**+ * Map the standard TTS payload onto a `generateContent` request. Style instructions go to+ * `speechMetadata.style` on current models and into the prompt on older ones.+ */+export const buildGeminiSpeechRequest = (+ payload: TextToSpeechPayload,+ requestModel: string,+ options?: Pick<TextToSpeechOptions, 'headers' | 'signal'>,+): { format: TTSAudioFormat; request: GenerateContentParameters } => {+ const params = resolveTextToSpeechParams(payload);+ const format = params.format ?? DEFAULT_TTS_AUDIO_FORMAT;++ if (!(GEMINI_TTS_FORMATS as readonly string[]).includes(format)) {+ throw new GeminiSpeechError(+ `Gemini speech does not support the "${format}" format; use one of ${GEMINI_TTS_FORMATS.join(', ')}`,+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ const instructions = params.instructions?.trim();+ let part: Part = { text: payload.input };+ if (instructions) {+ part = isPromptStyledGeminiTTSModel(requestModel)+ ? { text: `${instructions}: ${payload.input}` }+ : { speechMetadata: { style: instructions }, text: payload.input };+ }++ const config: GenerateContentConfig = {+ responseModalities: ['AUDIO'],+ speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: payload.voice } } },+ ...(options?.signal && { abortSignal: options.signal }),+ ...(options?.headers && { httpOptions: { headers: options.headers } }),+ };++ return {+ format,+ request: { config, contents: [{ parts: [part], role: 'user' }], model: requestModel },+ };+};++/**+ * Collect every audio `inlineData` part of the first candidate. A response without audio+ * is a refusal (safety block) or an upstream failure and must not settle as billable.+ */+export const extractGeminiSpeechAudio = (response: GenerateContentResponse): PcmAudio => {+ const blockReason = response.promptFeedback?.blockReason;+ if (blockReason) {+ throw new GeminiSpeechError(+ `Gemini blocked the speech request (${blockReason})${response.promptFeedback?.blockReasonMessage ? `: ${response.promptFeedback.blockReasonMessage}` : ''}`,+ AgentRuntimeErrorType.ContentModeration,+ { blockReason },+ );+ }++ const candidate = response.candidates?.[0];+ const audioParts =+ candidate?.content?.parts?.filter((part) =>+ part.inlineData?.mimeType?.toLowerCase().startsWith('audio/'),+ ) ?? [];++ if (audioParts.length === 0) {+ const finishReason = candidate?.finishReason;+ const moderated = !!finishReason && MODERATION_REASONS.has(finishReason);++ throw new GeminiSpeechError(+ `Gemini returned no audio${finishReason ? ` (finishReason: ${finishReason})` : ''}${+ candidate?.finishMessage ? `: ${candidate.finishMessage}` : ''+ }`,+ moderated ? AgentRuntimeErrorType.ContentModeration : AgentRuntimeErrorType.ProviderBizError,+ finishReason ? { finishReason } : undefined,+ );+ }++ const decoded = audioParts.map((part) =>+ decodeGeminiAudio(part.inlineData!.data ?? '', part.inlineData!.mimeType),+ );+ const [first] = decoded;+ const mismatched = decoded.some(+ (audio) =>+ audio.sampleRate !== first.sampleRate ||+ audio.channels !== first.channels ||+ audio.bitsPerSample !== first.bitsPerSample,+ );+ if (mismatched) {+ throw new GeminiSpeechError(+ 'Gemini returned audio parts with different encodings',+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ const data = Buffer.concat(decoded.map((audio) => audio.data));+ if (data.length === 0) {+ throw new GeminiSpeechError(+ 'Gemini returned empty audio',+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ return { ...first, data };+};++/**+ * Token usage of one synthesis: the prompt is text, the candidates are audio. Audio token+ * details are preferred when Gemini reports them per modality.+ */+export const convertGeminiSpeechTokenUsage = (+ usageMetadata?: GenerateContentResponseUsageMetadata,+) => {+ if (!usageMetadata) return;++ const inputTokens = usageMetadata.promptTokenCount;+ const audioDetail = usageMetadata.candidatesTokensDetails?.find(+ (detail) => detail.modality === 'AUDIO',+ )?.tokenCount;+ const outputTokens = audioDetail ?? usageMetadata.candidatesTokenCount;++ if (typeof inputTokens !== 'number' || typeof outputTokens !== 'number') return;++ return {+ inputTextTokens: inputTokens,+ outputAudioTokens: outputTokens,+ totalInputTokens: inputTokens,+ totalOutputTokens: outputTokens,+ totalTokens: usageMetadata.totalTokenCount ?? inputTokens + outputTokens,+ };+};++export const encodeGeminiSpeechAudio = async (+ pcm: PcmAudio,+ format: TTSAudioFormat,+): Promise<ArrayBuffer> => {+ switch (format) {+ case 'mp3': {+ return toArrayBuffer(await encodeMp3(pcm));+ }+ case 'wav': {+ return toArrayBuffer(encodeWav(pcm));+ }+ default: {+ return toArrayBuffer(pcm.data);+ }+ }+};++export interface GeminiSpeechOptions extends ModelIdMappingOptions, TextToSpeechOptions {+ /** Provider id used for pricing lookup and error payloads. */+ provider: string;+}++/**+ * Synthesize speech with Gemini's native `generateContent` (`responseModalities: AUDIO`),+ * through the provider's own SDK client so the API key and custom base URL apply.+ * @see https://ai.google.dev/gemini-api/docs/speech-generation+ */+export async function createGeminiSpeech(+ client: GoogleGenAI,+ payload: TextToSpeechPayload,+ options: GeminiSpeechOptions,+): Promise<TextToSpeechResponse> {+ const { provider } = options;+ const requestModel = resolveMappedModelId(payload.model, options);++ let result: TextToSpeechResponse;+ try {+ const { format, request } = buildGeminiSpeechRequest(payload, requestModel, options);+ const pricing = await getModelPricing(payload.model, provider, options.pricingContext);++ log(+ 'generateContent request: model=%s voice=%s format=%s',+ requestModel,+ payload.voice,+ format,+ );++ const response = await client.models.generateContent(request);+ const pcm = extractGeminiSpeechAudio(response);+ const audio = await encodeGeminiSpeechAudio(pcm, format);++ log(+ 'generateContent done: %d PCM bytes @ %d Hz -> %d %s bytes, usage=%o',+ pcm.data.length,+ pcm.sampleRate,+ audio.byteLength,+ format,+ response.usageMetadata,+ );++ const usage = convertTextToSpeechUsage(+ payload.input,+ pricing,+ convertGeminiSpeechTokenUsage(response.usageMetadata),+ );++ result = { audio, format, usage };+ } catch (error) {+ log('createGeminiSpeech error: %O', error);++ if ((error as Error)?.name === 'AbortError' || options.signal?.aborted) throw error;++ const speechError = toGeminiSpeechError(error);++ throw AgentRuntimeError.chat({+ error: { message: speechError.message, ...speechError.detail },+ errorType: speechError.errorType,+ provider,+ } satisfies ChatCompletionErrorPayload);+ }++ await options.onUsage?.(result.usage!);++ return result;+}diff --git a/packages/model-runtime/src/providers/google/index.ts b/packages/model-runtime/src/providers/google/index.tsindex f533291dc51..942eacaec7c 100644--- a/packages/model-runtime/src/providers/google/index.ts+++ b/packages/model-runtime/src/providers/google/index.ts@@ -32,6 +32,7 @@ import type {import { AgentRuntimeErrorType } from '../../types/error';import type { CreateImagePayload, CreateImageResponse } from '../../types/image';import type { ProviderResponseDiagnostics } from '../../types/providerDiagnostics';+import type { TextToSpeechOptions, TextToSpeechPayload } from '../../types/tts';import type {CreateVideoPayload,CreateVideoResult,@@ -50,6 +51,7 @@ import {getRuntimeSignatureScopeSource,} from '../../utils/signatureScope';import { createGoogleImage } from './createImage';+import { createGeminiSpeech } from './createSpeech';import { createGoogleVideo, isGeminiOmniVideoModel, pollGoogleVideoOperation } from './createVideo';import { createGoogleGenerateObject, createGoogleGenerateObjectWithTools } from './generateObject';import { handleGoogleVideoWebhook } from './handleCreateVideoWebhook';@@ -415,6 +417,19 @@ export class LobeGoogleAI implements LobeRuntimeAI {}}+ /**+ * Text-to-speech with Gemini TTS models (`responseModalities: AUDIO`). Gemini returns+ * 16-bit PCM, which is encoded to the requested `mp3` / `wav` / `pcm` output.+ * @see https://ai.google.dev/gemini-api/docs/speech-generation+ */+ textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {+ return createGeminiSpeech(this.client, payload, {+ ...options,+ ...this.modelIdMappingOptions,+ provider: this.provider,+ });+ }+async handlePollVideoStatus(inferenceId: string) {return pollGoogleVideoOperation(this.client, inferenceId, this.provider, this.apiKey!);}diff --git a/packages/model-runtime/src/providers/google/speechAudio.test.ts b/packages/model-runtime/src/providers/google/speechAudio.test.tsnew file mode 100644index 00000000000..12baab64fd3--- /dev/null+++ b/packages/model-runtime/src/providers/google/speechAudio.test.ts@@ -0,0 +1,183 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import {+ createWavHeader,+ decodeGeminiAudio,+ encodeMp3,+ encodeWav,+ GEMINI_DEFAULT_SAMPLE_RATE,+ parseWav,+ type PcmAudio,+ SpeechAudioError,+} from './speechAudio';++/** `frames` of a 440 Hz sine as 16-bit LE mono PCM. */+const sinePcm = (frames: number, sampleRate = 24_000) => {+ const data = Buffer.alloc(frames * 2);+ for (let i = 0; i < frames; i++) {+ data.writeInt16LE(Math.round(8000 * Math.sin((2 * Math.PI * 440 * i) / sampleRate)), i * 2);+ }+ return data;+};++const pcmAudio = (data: Buffer, overrides: Partial<PcmAudio> = {}): PcmAudio => ({+ bitsPerSample: 16,+ channels: 1,+ data,+ sampleRate: 24_000,+ ...overrides,+});++/** An MP3 stream starts with an ID3 tag or an MPEG frame sync (11 set bits). */+const looksLikeMp3 = (buffer: Buffer) =>+ buffer.toString('ascii', 0, 3) === 'ID3' || (buffer[0] === 0xff && (buffer[1] & 0xe0) === 0xe0);++describe('decodeGeminiAudio', () => {+ it('reads the sample rate from an audio/L16 mime type', () => {+ const pcm = sinePcm(240);+ const audio = decodeGeminiAudio(pcm.toString('base64'), 'audio/L16;codec=pcm;rate=16000');++ expect(audio).toMatchObject({ bitsPerSample: 16, channels: 1, sampleRate: 16_000 });+ expect(audio.data.equals(pcm)).toBe(true);+ });++ it('accepts spaces, case and a channels parameter', () => {+ const audio = decodeGeminiAudio(+ sinePcm(4).toString('base64'),+ 'audio/l16; rate=48000; channels=2',+ );++ expect(audio).toMatchObject({ channels: 2, sampleRate: 48_000 });+ });++ it('falls back to 24 kHz mono when the mime type has no rate', () => {+ const audio = decodeGeminiAudio(sinePcm(4).toString('base64'), 'audio/pcm');++ expect(audio).toMatchObject({ channels: 1, sampleRate: GEMINI_DEFAULT_SAMPLE_RATE });+ });++ it('unwraps WAV output (the Gemini 3.8 default) by mime type or RIFF magic', () => {+ const pcm = sinePcm(100);+ const wav = encodeWav(pcmAudio(pcm, { sampleRate: 16_000 }));++ for (const mimeType of ['audio/wav', 'application/octet-stream', '']) {+ const audio =+ mimeType === 'application/octet-stream'+ ? parseWav(wav)+ : decodeGeminiAudio(wav.toString('base64'), mimeType);+ expect(audio).toMatchObject({ bitsPerSample: 16, channels: 1, sampleRate: 16_000 });+ expect(audio.data.equals(pcm)).toBe(true);+ }+ });++ it('rejects non-16-bit PCM, unknown audio types and empty audio', () => {+ expect(() => decodeGeminiAudio('AAAA', 'audio/L24;rate=24000')).toThrow(/24-bit/);+ expect(() => decodeGeminiAudio('AAAA', 'audio/ogg')).toThrow(SpeechAudioError);+ expect(() => decodeGeminiAudio('', 'audio/L16;rate=24000')).toThrow(/empty audio/);+ });+});++describe('parseWav', () => {+ it('skips extra chunks and clamps a streaming (oversized) data length', () => {+ const pcm = sinePcm(10);+ const header = createWavHeader({+ bitsPerSample: 16,+ channels: 1,+ dataLength: 0,+ sampleRate: 24_000,+ });+ header.writeUInt32LE(0xff_ff_ff_ff, 40); // unknown length, as a streaming writer leaves it+ // Insert an odd-sized LIST chunk (with its pad byte) between fmt and data.+ const list = Buffer.concat([+ Buffer.from('LIST'),+ Buffer.from([3, 0, 0, 0]),+ Buffer.from('abc\0'),+ ]);+ const wav = Buffer.concat([header.subarray(0, 36), list, header.subarray(36), pcm]);++ const audio = parseWav(wav);+ expect(audio.data.equals(pcm)).toBe(true);+ });++ it('reads a zero data length (streaming writer) to the end of the file', () => {+ const pcm = sinePcm(10);+ const wav = encodeWav(pcmAudio(pcm));+ wav.writeUInt32LE(0, 40);++ expect(parseWav(wav).data.equals(pcm)).toBe(true);+ });++ it('rejects non-PCM and malformed files', () => {+ const wav = encodeWav(pcmAudio(sinePcm(4)));+ const float = Buffer.from(wav);+ float.writeUInt16LE(3, 20); // IEEE float++ expect(() => parseWav(float)).toThrow(/unsupported WAV encoding 3/);+ expect(() => parseWav(Buffer.from('not a wav file'))).toThrow(/invalid WAV/);+ expect(() => parseWav(wav.subarray(0, 36))).toThrow(/without audio data/);+ });+});++describe('encodeWav', () => {+ it('writes a canonical 44-byte header for the PCM', () => {+ const pcm = sinePcm(24_000);+ const wav = encodeWav(pcmAudio(pcm));++ expect(wav.length).toBe(44 + pcm.length);+ expect(wav.toString('ascii', 0, 4)).toBe('RIFF');+ expect(wav.readUInt32LE(4)).toBe(36 + pcm.length);+ expect(wav.toString('ascii', 8, 16)).toBe('WAVEfmt ');+ expect(wav.readUInt16LE(20)).toBe(1); // PCM+ expect(wav.readUInt16LE(22)).toBe(1); // mono+ expect(wav.readUInt32LE(24)).toBe(24_000);+ expect(wav.readUInt32LE(28)).toBe(48_000); // byte rate+ expect(wav.readUInt16LE(32)).toBe(2); // block align+ expect(wav.readUInt16LE(34)).toBe(16);+ expect(wav.toString('ascii', 36, 40)).toBe('data');+ expect(wav.readUInt32LE(40)).toBe(pcm.length);+ });+});++describe('encodeMp3', () => {+ it('encodes 24 kHz mono PCM into a much smaller MP3 stream', async () => {+ const pcm = sinePcm(24_000); // 1 second = 48,000 bytes+ const mp3 = await encodeMp3(pcmAudio(pcm));++ expect(looksLikeMp3(mp3)).toBe(true);+ // 40 kbps for one second is ~5 KB; allow encoder padding frames.+ expect(mp3.length).toBeGreaterThan(3000);+ expect(mp3.length).toBeLessThan(9000);+ });++ it('yields to the event loop while encoding long audio', async () => {+ let ticks = 0;+ const timer = setInterval(() => ticks++, 0);+ try {+ await encodeMp3(pcmAudio(sinePcm(24_000 * 5)));+ } finally {+ clearInterval(timer);+ }++ expect(ticks).toBeGreaterThan(0);+ });++ it('encodes interleaved stereo PCM', async () => {+ const mono = sinePcm(4800);+ const stereo = Buffer.alloc(mono.length * 2);+ for (let i = 0; i < mono.length / 2; i++) {+ stereo.writeInt16LE(mono.readInt16LE(i * 2), i * 4);+ stereo.writeInt16LE(mono.readInt16LE(i * 2), i * 4 + 2);+ }++ const mp3 = await encodeMp3(pcmAudio(stereo, { channels: 2 }));+ expect(looksLikeMp3(mp3)).toBe(true);+ });++ it('rejects sample rates and layouts MP3 cannot carry', async () => {+ await expect(encodeMp3(pcmAudio(sinePcm(4), { sampleRate: 96_000 }))).rejects.toThrow(+ /96000 Hz/,+ );+ await expect(encodeMp3(pcmAudio(sinePcm(4), { channels: 6 }))).rejects.toThrow(/6-channel/);+ });+});diff --git a/packages/model-runtime/src/providers/google/speechAudio.ts b/packages/model-runtime/src/providers/google/speechAudio.tsnew file mode 100644index 00000000000..ede98fefe61--- /dev/null+++ b/packages/model-runtime/src/providers/google/speechAudio.ts@@ -0,0 +1,222 @@+/**+ * Audio helpers for Gemini speech generation. Gemini returns 16-bit linear PCM, either+ * headerless (`audio/L16;codec=pcm;rate=24000`) or wrapped in a RIFF/WAV container+ * (`audio/wav`, the Gemini 3.8 TTS default), so the runtime decodes both into raw PCM+ * and re-encodes it into the format the caller asked for.+ */++/** Gemini TTS output when the mime type carries no rate (24 kHz, mono, 16-bit). */+export const GEMINI_DEFAULT_SAMPLE_RATE = 24_000;++/**+ * Bitrate of the MP3 encoding. A full 16,384-token output (about 11 minutes) is about 3.3 MB+ * (4.4 MB as base64), inside the ~4.5 MB inline response limit; the raw PCM would be ~31 MB.+ * Below 40 kbps LAME resamples 24 kHz input first, which is ~8x slower in pure JS.+ */+export const GEMINI_MP3_KBPS = 40;++/** Sample rates the LAME MP3 encoder accepts (MPEG-1, MPEG-2 and MPEG-2.5). */+const MP3_SAMPLE_RATES = new Set([+ 8000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000,+]);++/** Samples per MP3 frame for MPEG-2 / 2.5 Layer III; multiples keep the encoder's buffers small. */+const MP3_FRAME_SAMPLES = 1152;++/**+ * Frames encoded between yields to the event loop: about one second of 24 kHz audio, ~12 ms+ * of CPU, so a long synthesis never stalls other requests on the same server.+ */+const MP3_FRAMES_PER_YIELD = 21;++const yieldToEventLoop = () => new Promise<void>((resolve) => setTimeout(resolve, 0));++export interface PcmAudio {+ bitsPerSample: number;+ channels: number;+ /** Little-endian signed PCM samples, channels interleaved. */+ data: Buffer;+ sampleRate: number;+}++export class SpeechAudioError extends Error {}++const parseMimeParams = (mimeType: string) => {+ const [type, ...rest] = mimeType.split(';').map((part) => part.trim());+ const params: Record<string, string> = {};++ for (const part of rest) {+ const eq = part.indexOf('=');+ if (eq > 0) params[part.slice(0, eq).trim().toLowerCase()] = part.slice(eq + 1).trim();+ }++ return { params, type: (type ?? '').toLowerCase() };+};++const parsePositiveInt = (value: string | undefined): number | undefined => {+ if (!value) return;+ const parsed = Number.parseInt(value, 10);+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;+};++const isRiff = (data: Buffer) =>+ data.length >= 12 &&+ data.toString('ascii', 0, 4) === 'RIFF' &&+ data.toString('ascii', 8, 12) === 'WAVE';++/**+ * Read the `fmt ` and `data` chunks of a RIFF/WAV buffer. Only integer PCM is accepted;+ * a streaming writer may leave the data size as 0 or 0xFFFFFFFF, so the chunk is clamped+ * to the bytes actually present.+ */+export const parseWav = (data: Buffer): PcmAudio => {+ if (!isRiff(data)) throw new SpeechAudioError('Gemini returned an invalid WAV file');++ let offset = 12;+ let format: Omit<PcmAudio, 'data'> | undefined;++ while (offset + 8 <= data.length) {+ const id = data.toString('ascii', offset, offset + 4);+ const size = data.readUInt32LE(offset + 4);+ const body = offset + 8;++ if (id === 'fmt ') {+ const audioFormat = data.readUInt16LE(body);+ // 1 = integer PCM, 0xFFFE = WAVE_FORMAT_EXTENSIBLE (PCM sub-format for 16-bit output)+ if (audioFormat !== 1 && audioFormat !== 0xff_fe) {+ throw new SpeechAudioError(`Gemini returned unsupported WAV encoding ${audioFormat}`);+ }+ format = {+ bitsPerSample: data.readUInt16LE(body + 14),+ channels: data.readUInt16LE(body + 2),+ sampleRate: data.readUInt32LE(body + 4),+ };+ } else if (id === 'data') {+ if (!format) throw new SpeechAudioError('Gemini returned a WAV file without a fmt chunk');+ // A streaming writer leaves the size as 0 or 0xFFFFFFFF; then the data runs to the end.+ const end = size === 0 ? data.length : Math.min(data.length, body + size);+ return { ...format, data: data.subarray(body, end) };+ }++ // Chunks are word-aligned: an odd-sized chunk is followed by one pad byte.+ offset = body + size + (size % 2);+ }++ throw new SpeechAudioError('Gemini returned a WAV file without audio data');+};++/**+ * Decode one Gemini `inlineData` audio part into PCM. `audio/L16` / `audio/pcm` carry the+ * rate (and optionally channels) as mime parameters; WAV is detected by mime type or by its+ * RIFF magic, since some gateways relabel the payload.+ */+export const decodeGeminiAudio = (base64: string, mimeType = ''): PcmAudio => {+ const data = Buffer.from(base64, 'base64');+ if (data.length === 0) throw new SpeechAudioError('Gemini returned empty audio');++ const { params, type } = parseMimeParams(mimeType);++ if (isRiff(data) || type === 'audio/wav' || type === 'audio/x-wav' || type === 'audio/wave') {+ return parseWav(data);+ }++ const bitsMatch = /^audio\/l(\d+)$/.exec(type);+ if (!bitsMatch && type !== 'audio/pcm' && type !== '') {+ throw new SpeechAudioError(`Gemini returned unsupported audio type "${mimeType}"`);+ }++ const bitsPerSample = bitsMatch ? Number(bitsMatch[1]) : 16;+ if (bitsPerSample !== 16) {+ throw new SpeechAudioError(`Gemini returned unsupported ${bitsPerSample}-bit PCM audio`);+ }++ return {+ bitsPerSample,+ channels: parsePositiveInt(params.channels) ?? 1,+ data,+ sampleRate: parsePositiveInt(params.rate) ?? GEMINI_DEFAULT_SAMPLE_RATE,+ };+};++/** 44-byte canonical RIFF/WAV header for little-endian integer PCM. */+export const createWavHeader = ({+ bitsPerSample,+ channels,+ dataLength,+ sampleRate,+}: Omit<PcmAudio, 'data'> & { dataLength: number }): Buffer => {+ const blockAlign = channels * (bitsPerSample / 8);+ const header = Buffer.alloc(44);++ header.write('RIFF', 0, 'ascii');+ header.writeUInt32LE(36 + dataLength, 4);+ header.write('WAVE', 8, 'ascii');+ header.write('fmt ', 12, 'ascii');+ header.writeUInt32LE(16, 16); // fmt chunk size+ header.writeUInt16LE(1, 20); // integer PCM+ header.writeUInt16LE(channels, 22);+ header.writeUInt32LE(sampleRate, 24);+ header.writeUInt32LE(sampleRate * blockAlign, 28); // byte rate+ header.writeUInt16LE(blockAlign, 32);+ header.writeUInt16LE(bitsPerSample, 34);+ header.write('data', 36, 'ascii');+ header.writeUInt32LE(dataLength, 40);++ return header;+};++export const encodeWav = (pcm: PcmAudio): Buffer =>+ Buffer.concat([createWavHeader({ ...pcm, dataLength: pcm.data.length }), pcm.data]);++/** Copy 16-bit LE PCM into aligned Int16Arrays, one per channel (at most stereo). */+const splitChannels = (pcm: PcmAudio): Int16Array[] => {+ const frameCount = Math.floor(pcm.data.length / (2 * pcm.channels));+ const channels = Array.from({ length: pcm.channels }, () => new Int16Array(frameCount));++ for (let frame = 0; frame < frameCount; frame++) {+ for (let channel = 0; channel < pcm.channels; channel++) {+ channels[channel][frame] = pcm.data.readInt16LE((frame * pcm.channels + channel) * 2);+ }+ }++ return channels;+};++/**+ * Encode 16-bit PCM to MP3 with the pure-JS LAME port, so the audio fits the inline+ * response of every caller and plays everywhere. The encoder is loaded on first use.+ */+export const encodeMp3 = async (pcm: PcmAudio): Promise<Buffer> => {+ if (pcm.bitsPerSample !== 16) {+ throw new SpeechAudioError(`Cannot encode ${pcm.bitsPerSample}-bit PCM to MP3`);+ }+ if (pcm.channels < 1 || pcm.channels > 2) {+ throw new SpeechAudioError(`Cannot encode ${pcm.channels}-channel audio to MP3`);+ }+ if (!MP3_SAMPLE_RATES.has(pcm.sampleRate)) {+ throw new SpeechAudioError(`Cannot encode ${pcm.sampleRate} Hz audio to MP3`);+ }++ const { Mp3Encoder } = await import('@breezystack/lamejs');+ const encoder = new Mp3Encoder(pcm.channels, pcm.sampleRate, GEMINI_MP3_KBPS);+ const [left, right] = splitChannels(pcm);+ const chunks: Buffer[] = [];+ // The encoder hands back Int8Array views despite its typings; copy-free wrap as bytes.+ const push = (chunk: ArrayBufferView) => {+ if (chunk.byteLength > 0)+ chunks.push(Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength));+ };++ for (let frame = 0, start = 0; start < left.length; frame++, start += MP3_FRAME_SAMPLES) {+ if (frame > 0 && frame % MP3_FRAMES_PER_YIELD === 0) await yieldToEventLoop();++ const end = start + MP3_FRAME_SAMPLES;+ push(encoder.encodeBuffer(left.subarray(start, end), right?.subarray(start, end)));+ }+ push(encoder.flush());++ return Buffer.concat(chunks);+};++export const toArrayBuffer = (buffer: Buffer): ArrayBuffer =>+ buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength) as ArrayBuffer;diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsx b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsxindex a63d7c78de4..6f07ac0a0aa 100644--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsx+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/Form.tsx@@ -1,6 +1,6 @@import { Checkbox, Input, Select } from '@lobehub/ui';-import { Form, type FormInstance, type FormValues, useForm } from '@lobehub/ui/form';-import type { AiModelType } from 'model-bank';+import { Form, type FormInstance, type FormValues, useForm, useWatch } from '@lobehub/ui/form';+import type { AiModelType, AiProviderModelListItem } from 'model-bank';import { memo, useEffect, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -8,13 +8,14 @@ import MaxTokenSlider from '@/components/MaxTokenSlider';import { type ChatModelCard } from '@/types/llm';import ExtendParamsSelect from './ExtendParamsSelect';+import TTSVoiceSelect from './TTSVoiceSelect';import { CUSTOM_MODEL_TYPES, hasDuplicateModelId } from './utils';interface ModelConfigFormProps {disabled?: boolean;existingModelIds?: string[];idEditable?: boolean;- initialValues?: ChatModelCard;+ initialValues?: ChatModelCard & Pick<AiProviderModelListItem, 'parameters' | 'voices'>;onFormInstanceReady: (instance: FormInstance) => void;showDeployName?: boolean;type?: AiModelType;@@ -28,10 +29,14 @@ const ModelConfigForm = memo<ModelConfigFormProps>(initialValues,disabled,existingModelIds = [],+ type,}) => {const { t } = useTranslation('modelProvider');const formInstance = useForm<FormValues>({ initialValues });+ // Follow the type picked in the form, so choosing `tts` while creating or editing a+ // model shows the voice field right away.+ const currentType = (useWatch(formInstance, 'type') as AiModelType | undefined) ?? type;const modelTypeOptions = useMemo(() =>@@ -97,6 +102,22 @@ const ModelConfigForm = memo<ModelConfigFormProps>(placeholder={t('providerModels.item.modelConfig.displayName.placeholder')}/></Form.Field>+ {currentType === 'tts' && (+ <Form.Field+ extra={t('providerModels.item.modelConfig.ttsVoice.extra')}+ label={t('providerModels.item.modelConfig.ttsVoice.title')}+ name={'settings.ttsVoice'}+ >+ <TTSVoiceSelect+ disabled={disabled}+ voices={initialValues?.voices}+ defaultVoice={+ (initialValues?.parameters as { voice?: { default?: string } } | undefined)?.voice+ ?.default+ }+ />+ </Form.Field>+ )}<Form.Fieldextra={t('providerModels.item.modelConfig.tokens.extra')}label={t('providerModels.item.modelConfig.tokens.title')}diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/TTSVoiceSelect.tsx b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/TTSVoiceSelect.tsxnew file mode 100644index 00000000000..8f120afe74c--- /dev/null+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/TTSVoiceSelect.tsx@@ -0,0 +1,53 @@+import { Input, Select } from '@lobehub/ui';+import type { TTSVoice } from 'model-bank';+import { memo, useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { buildTTSVoiceOptions } from './utils';++interface TTSVoiceSelectProps {+ /** The card's own default voice, shown as the placeholder of an empty value. */+ defaultVoice?: string;+ disabled?: boolean;+ onChange?: (value: string | undefined) => void;+ value?: string;+ /** Voice catalog of a built-in model; a custom model without one takes a free voice id. */+ voices?: TTSVoice[];+}++const TTSVoiceSelect = memo<TTSVoiceSelectProps>(+ ({ defaultVoice, disabled, onChange, value, voices }) => {+ const { t } = useTranslation('modelProvider');++ const placeholder = defaultVoice+ ? t('providerModels.item.modelConfig.ttsVoice.placeholder', { voice: defaultVoice })+ : t('providerModels.item.modelConfig.ttsVoice.placeholderCustom');++ const options = useMemo(() => buildTTSVoiceOptions(voices), [voices]);++ if (options.length === 0)+ return (+ <Input+ allowClear+ disabled={disabled}+ placeholder={placeholder}+ value={value}+ onChange={(e) => onChange?.(e.target.value || undefined)}+ />+ );++ return (+ <Select+ allowClear+ showSearch+ disabled={disabled}+ options={options}+ placeholder={placeholder}+ value={value}+ onChange={(next) => onChange?.((next as string | null | undefined) ?? undefined)}+ />+ );+ },+);++export default TTSVoiceSelect;diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/__tests__/utils.test.ts b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/__tests__/utils.test.tsindex c5bd565b687..53c36bc55c1 100644--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/__tests__/utils.test.ts+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/__tests__/utils.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { CUSTOM_MODEL_TYPES, hasDuplicateModelId } from '../utils';+import { buildTTSVoiceOptions, CUSTOM_MODEL_TYPES, hasDuplicateModelId } from '../utils';describe('CUSTOM_MODEL_TYPES', () => {it('should not offer image or video, which require a parameters schema', () => {@@ -26,3 +26,27 @@ describe('hasDuplicateModelId', () => {expect(hasDuplicateModelId('claude-sonnet-4-6', ['claude-opus-4-8'])).toBe(false);});});++describe('buildTTSVoiceOptions', () => {+ it('labels each catalog voice with its style and submits the voice id', () => {+ expect(+ buildTTSVoiceOptions([+ {+ description: 'Firm',+ displayName: 'Kore',+ gender: 'female',+ id: 'Kore',+ language: 'multilingual',+ },+ { displayName: 'Roger', gender: 'male', id: 'CwhRBWXzGAHq8TQ4Fs17', language: 'en-US' },+ ]),+ ).toEqual([+ { label: 'Kore · Firm', value: 'Kore' },+ { label: 'Roger', value: 'CwhRBWXzGAHq8TQ4Fs17' },+ ]);+ });++ it('returns no options for a model without a catalog, so the free voice id input is shown', () => {+ expect(buildTTSVoiceOptions(undefined)).toEqual([]);+ });+});diff --git a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.ts b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.tsindex e0870701945..e7f2c12a6f0 100644--- a/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.ts+++ b/src/features/Settings/provider/features/ModelList/CreateNewModelModal/utils.ts@@ -1,4 +1,4 @@-import type { AiModelType } from 'model-bank';+import type { AiModelType, TTSVoice } from 'model-bank';/*** Model types selectable when creating or editing a custom model.@@ -23,3 +23,10 @@ export const hasDuplicateModelId = (id: string | undefined, existingModelIds: streturn existingModelIds.includes(modelId);};++/** Options of the default-voice select: `Kore · Firm`, or the bare name without a description. */+export const buildTTSVoiceOptions = (voices: TTSVoice[] | undefined) =>+ voices?.map((voice) => ({+ label: voice.description ? `${voice.displayName} · ${voice.description}` : voice.displayName,+ value: voice.id,+ })) ?? [];diff --git a/src/features/Settings/provider/features/ModelList/ModelConfigModal/__tests__/utils.test.ts b/src/features/Settings/provider/features/ModelList/ModelConfigModal/__tests__/utils.test.tsindex fbe51cafe41..e52133a4d3a 100644--- a/src/features/Settings/provider/features/ModelList/ModelConfigModal/__tests__/utils.test.ts+++ b/src/features/Settings/provider/features/ModelList/ModelConfigModal/__tests__/utils.test.ts@@ -60,4 +60,31 @@ describe('pickModelConfigFormValues', () => {expect(UpdateAiModelSchema.safeParse(payload).success).toBe(true);});++ it('submits the TTS default voice and drops an empty one', () => {+ const ttsValues = {+ ...formValues,+ settings: { ttsVoice: 'Kore' },+ type: 'tts',+ };++ const payload = pickModelConfigFormValues(ttsValues);+ expect(payload.settings?.ttsVoice).toBe('Kore');+ expect(UpdateAiModelSchema.safeParse(payload).success).toBe(true);++ expect(+ pickModelConfigFormValues({ ...ttsValues, settings: { ttsVoice: ' ' } }).settings?.ttsVoice,+ ).toBeUndefined();+ expect(+ pickModelConfigFormValues({ ...ttsValues, settings: { ttsVoice: ' my voice ' } }).settings+ ?.ttsVoice,+ ).toBe('my voice');+ });++ it('drops the TTS default voice once the model is no longer a TTS model', () => {+ expect(+ pickModelConfigFormValues({ ...formValues, settings: { ttsVoice: 'Kore' }, type: 'chat' })+ .settings?.ttsVoice,+ ).toBeUndefined();+ });});diff --git a/src/features/Settings/provider/features/ModelList/ModelConfigModal/utils.ts b/src/features/Settings/provider/features/ModelList/ModelConfigModal/utils.tsindex 59887b40d4c..b9718501d92 100644--- a/src/features/Settings/provider/features/ModelList/ModelConfigModal/utils.ts+++ b/src/features/Settings/provider/features/ModelList/ModelConfigModal/utils.ts@@ -39,6 +39,11 @@ export const pickModelConfigFormValues = (extendParams: (settings.extendParams ?? undefined) as NonNullable<UpdateAiModelParams['settings']>['extendParams'],+ // Only a TTS model has a voice; switching the type away drops a leftover value.+ ttsVoice:+ values.type === 'tts'+ ? (settings.ttsVoice as string | undefined)?.trim() || undefined+ : undefined,},type: values.type as UpdateAiModelParams['type'],};