🤯 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): generic TTS model type, MiniMax t2a_v2 speech and TTS spend label (#21942)
Rdmclin2a2f84ebc5f23
diff --git a/.agents/skills/cli/references/generate.md b/.agents/skills/cli/references/generate.mdindex 31363462374..9e6dd08355a 100644--- a/.agents/skills/cli/references/generate.md+++ b/.agents/skills/cli/references/generate.md@@ -237,16 +237,29 @@ Text-to-speech generation.**Source**: `apps/cli/src/commands/generate/tts.ts````bash-lh gen tts <text> [-o <file>] [--voice <voice>] [--speed <n>] [-m <model>] [-p <provider>]+lh gen tts <text> [-o <file>] [--voice <voice>] [-m <model>] [-p <provider>] \+ [--speed <n>] [--pitch <n>] [--volume <n>] [--emotion <e>] [--format <f>] \+ [--sample-rate <hz>] [--instructions <text>] [--params <json>]```-| Option | Description | Default |-| --------------------------- | ---------------------------------------- | ------------ |-| `-o, --output <file>` | Output audio file path | `output.mp3` |-| `--voice <voice>` | Voice name | `alloy` |-| `--speed <n>` | Speed multiplier (0.25-4.0) | `1` |-| `-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` | 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` |++Params are standard TTS parameters (`TTSModelParamsMetaSchema` in model-bank). The server+rejects params the model card does not declare or values outside its range. On success the+command prints the file size plus usage (characters, tokens, cost) when the provider reports it.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.tsnew file mode 100644index 00000000000..6861af7a2cd--- /dev/null+++ b/apps/cli/src/commands/generate/tts.test.ts@@ -0,0 +1,152 @@+import { readFile, rm } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { log } from '../../utils/logger';+import { buildTtsParams, registerTtsCommand } from './tts';++const { synthesize } = vi.hoisted(() => ({ synthesize: vi.fn() }));++vi.mock('../../api/client', () => ({+ getTrpcClient: vi.fn(async () => ({ tts: { synthesize: { mutate: synthesize } } })),+}));++describe('generate tts', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let errorSpy: ReturnType<typeof vi.spyOn>;+ let output: string;++ const run = async (...args: string[]) => {+ const program = new Command();+ program.exitOverride();+ registerTtsCommand(program);+ await program.parseAsync(['node', 'test', 'tts', ...args]);+ };++ beforeEach(() => {+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});+ output = path.join(os.tmpdir(), `lh-tts-test-${process.pid}-${Date.now()}.wav`);+ synthesize.mockResolvedValue({+ audioBase64: Buffer.from('RIFF-audio').toString('base64'),+ format: 'wav',+ mimeType: 'audio/wav',+ usage: { cost: 0.000_075, inputCharacters: 5 },+ });+ });++ afterEach(async () => {+ exitSpy.mockRestore();+ consoleSpy.mockRestore();+ errorSpy.mockRestore();+ synthesize.mockReset();+ await rm(output, { force: true });+ });++ it('sends provider/model/voice/params and writes the decoded audio', async () => {+ await run(+ 'hello',+ '-m',+ 'minimax/speech-02-hd',+ '--voice',+ 'female-shaonv',+ '--speed',+ '1.2',+ '--pitch',+ '-2',+ '--emotion',+ 'happy',+ '--format',+ 'wav',+ '--sample-rate',+ '32000',+ '-o',+ output,+ );++ expect(synthesize).toHaveBeenCalledWith({+ input: 'hello',+ model: 'speech-02-hd',+ params: { emotion: 'happy', format: 'wav', pitch: -2, sampleRate: 32_000, speed: 1.2 },+ provider: 'minimax',+ speed: 1.2,+ voice: 'female-shaonv',+ });+ expect(await readFile(output, 'utf8')).toBe('RIFF-audio');+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining('5 chars, $0.000075'));+ });++ it("omits params and voice so the server applies the model's defaults", async () => {+ await run('hello', '-o', output);++ expect(synthesize).toHaveBeenCalledWith({+ input: 'hello',+ model: 'tts-1',+ params: undefined,+ provider: 'openai',+ speed: undefined,+ voice: undefined,+ });+ });++ it('names the default output file after the returned format', async () => {+ const cwd = process.cwd();+ const dir = path.dirname(output);+ process.chdir(dir);+ try {+ await run('hello');+ expect(await readFile(path.join(dir, 'output.wav'), 'utf8')).toBe('RIFF-audio');+ } finally {+ process.chdir(cwd);+ await rm(path.join(dir, 'output.wav'), { force: true });+ }+ });++ it('falls back to output.mp3 when an older server returns no format', async () => {+ synthesize.mockResolvedValue({ audioBase64: Buffer.from('ID3').toString('base64') });+ const cwd = process.cwd();+ const dir = path.dirname(output);+ process.chdir(dir);+ try {+ await run('hello');+ expect(await readFile(path.join(dir, 'output.mp3'), 'utf8')).toBe('ID3');+ } finally {+ process.chdir(cwd);+ await rm(path.join(dir, 'output.mp3'), { force: true });+ }+ });++ it('exits with an error on invalid --params JSON', async () => {+ await run('hello', '--params', '{not json', '-o', output);++ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--params must be a JSON'));+ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(synthesize).not.toHaveBeenCalled();+ });+});++describe('buildTtsParams', () => {+ it('lets dedicated flags override the same key in --params', () => {+ expect(+ buildTtsParams({+ model: 'tts-1',+ params: '{"speed":0.8,"volume":2,"emotion":"calm"}',+ speed: '1.5',+ }),+ ).toEqual({ emotion: 'calm', speed: 1.5, volume: 2 });+ });++ it('rejects non-numeric numbers and non-object params', () => {+ expect(() => buildTtsParams({ model: 'tts-1', speed: 'fast' })).toThrow(+ '--speed must be a number',+ );+ expect(() => buildTtsParams({ model: 'tts-1', params: '[1]' })).toThrow(+ '--params must be a JSON object',+ );+ });+});diff --git a/apps/cli/src/commands/generate/tts.ts b/apps/cli/src/commands/generate/tts.tsindex 3f80e1fc733..0ea00b53254 100644--- a/apps/cli/src/commands/generate/tts.ts+++ b/apps/cli/src/commands/generate/tts.ts@@ -4,45 +4,125 @@ import type { Command } from 'commander';import pc from 'picocolors';import { getTrpcClient } from '../../api/client';+import { log } from '../../utils/logger';++interface TtsCommandOptions {+ emotion?: string;+ format?: string;+ instructions?: string;+ model: string;+ output?: string;+ params?: string;+ pitch?: string;+ provider?: string;+ sampleRate?: string;+ speed?: string;+ voice?: string;+ volume?: string;+}++const parseNumber = (name: string, value: string | undefined) => {+ if (value === undefined) return undefined;++ const parsed = Number(value);+ if (!Number.isFinite(parsed)) throw new Error(`--${name} must be a number, got "${value}"`);++ return parsed;+};++/**+ * Merge `--params` JSON with the dedicated flags; a dedicated flag wins over the same key+ * in the JSON.+ */+export const buildTtsParams = (options: TtsCommandOptions): Record<string, unknown> => {+ let base: Record<string, unknown> = {};+ if (options.params) {+ try {+ base = JSON.parse(options.params);+ } catch {+ throw new Error('--params must be a JSON object, e.g. \'{"speed":1.2,"emotion":"happy"}\'');+ }+ if (!base || typeof base !== 'object' || Array.isArray(base)) {+ throw new Error('--params must be a JSON object');+ }+ }++ const flags: Record<string, unknown> = {+ emotion: options.emotion,+ format: options.format,+ instructions: options.instructions,+ pitch: parseNumber('pitch', options.pitch),+ sampleRate: parseNumber('sample-rate', options.sampleRate),+ speed: parseNumber('speed', options.speed),+ volume: parseNumber('volume', options.volume),+ };++ return {+ ...base,+ ...Object.fromEntries(Object.entries(flags).filter(([, value]) => value !== undefined)),+ };+};export function registerTtsCommand(parent: Command) {parent.command('tts <text>').description('Convert text to speech')- .option('-o, --output <file>', 'Output audio file path', 'output.mp3')- .option('--voice <voice>', 'Voice name', 'alloy')- .option('--speed <n>', 'Speed multiplier (0.25-4.0)', '1')+ .option('-o, --output <file>', 'Output audio file path (default: output.<format>)')+ .option('--voice <voice>', "Voice id (default: the model's default voice)")+ .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('--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)')- .action(- async (- text: string,- options: {- model: string;- output: string;- provider?: string;- speed: string;- voice: string;- },- ) => {- const parts = options.model.split('/');- const provider = options.provider || (parts.length > 1 ? parts[0] : 'openai');- const model = parts.length > 1 ? parts.slice(1).join('/') : options.model;- const client = await getTrpcClient();-- const result = await client.tts.synthesize.mutate({- input: text,- model,- provider,- speed: Number.parseFloat(options.speed),- voice: options.voice,- });-- const buffer = Buffer.from(result.audioBase64, 'base64');- await writeFile(options.output, buffer);- console.log(- `${pc.green('✓')} Audio saved to ${pc.bold(options.output)} (${Math.round(buffer.length / 1024)}KB)`,- );- },- );+ .action(async (text: string, options: TtsCommandOptions) => {+ const parts = options.model.split('/');+ const provider = options.provider || (parts.length > 1 ? parts[0] : 'openai');+ const model = parts.length > 1 ? parts.slice(1).join('/') : options.model;++ let params: Record<string, unknown>;+ try {+ params = buildTtsParams(options);+ } catch (error) {+ log.error(error instanceof Error ? error.message : String(error));+ process.exit(1);+ return;+ }++ const client = await getTrpcClient();+ type SynthesizeParams = Parameters<typeof client.tts.synthesize.mutate>[0]['params'];+ // The server validates the values against the model's declared params.+ const result = await client.tts.synthesize.mutate({+ input: text,+ model,+ params: Object.keys(params).length > 0 ? (params as SynthesizeParams) : undefined,+ provider,+ // Also sent as the deprecated top-level field so servers that strip `params` keep+ // the requested speed; newer servers give `params.speed` precedence.+ speed: typeof params.speed === 'number' ? params.speed : undefined,+ voice: options.voice,+ });++ // Servers that predate standard TTS params return no `format`; they always sent mp3.+ const output = options.output || `output.${result.format ?? 'mp3'}`;+ const buffer = Buffer.from(result.audioBase64, 'base64');+ await writeFile(output, buffer);++ const usage = result.usage;+ const usageText = [+ usage?.inputCharacters !== undefined && `${usage.inputCharacters} chars`,+ usage?.totalTokens !== undefined && `${usage.totalTokens} tokens`,+ usage?.cost !== undefined && `$${usage.cost}`,+ ]+ .filter(Boolean)+ .join(', ');++ console.log(+ `${pc.green('✓')} Audio saved to ${pc.bold(output)} (${Math.round(buffer.length / 1024)}KB${usageText ? `, ${usageText}` : ''})`,+ );+ });}diff --git a/apps/server/src/routers/lambda/__tests__/tts.test.ts b/apps/server/src/routers/lambda/__tests__/tts.test.tsnew file mode 100644index 00000000000..3647f3824ea--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/tts.test.ts@@ -0,0 +1,175 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';++import { ttsRouter } from '../tts';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++const textToSpeechMock = vi.fn();+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(async () => ({ textToSpeech: textToSpeechMock })),+}));++const caller = ttsRouter.createCaller({ jwtPayload: { userId: 'u1' }, userId: 'u1' } as any);++const usage = { cost: 0.000_075, inputCharacters: 5 };++beforeEach(() => {+ textToSpeechMock.mockResolvedValue({+ audio: new Uint8Array([1, 2, 3]).buffer,+ format: 'opus',+ usage,+ });+});++afterEach(() => {+ vi.clearAllMocks();+});++describe('ttsRouter.synthesize', () => {+ it('passes provider/model/voice/params to the runtime and returns audio, format and usage', async () => {+ const res = await caller.synthesize({+ input: 'hello',+ model: 'tts-1',+ params: { format: 'opus', speed: 1.5 },+ provider: 'openai',+ voice: 'nova',+ });++ expect(initModelRuntimeFromDB).toHaveBeenCalledWith(+ expect.anything(),+ 'u1',+ 'openai',+ undefined,+ );+ expect(textToSpeechMock).toHaveBeenCalledWith(+ { input: 'hello', model: 'tts-1', params: { format: 'opus', speed: 1.5 }, voice: 'nova' },+ { metadata: { trigger: 'tts' }, user: 'u1' },+ );+ expect(res).toEqual({+ audioBase64: Buffer.from([1, 2, 3]).toString('base64'),+ format: 'opus',+ mimeType: 'audio/opus',+ usage,+ });+ });++ it("defaults the voice to the model card's default voice", async () => {+ await caller.synthesize({ input: 'hello', model: 'gpt-4o-mini-tts', provider: 'openai' });++ expect(textToSpeechMock.mock.calls[0][0]).toMatchObject({ voice: 'alloy' });+ });++ it('maps the legacy top-level speed into params', async () => {+ await caller.synthesize({ input: 'hello', model: 'tts-1', speed: 2, voice: 'alloy' });++ expect(textToSpeechMock.mock.calls[0][0].params).toEqual({ speed: 2 });+ });++ it('drops the legacy speed for models that declare no speed instead of rejecting', async () => {+ await caller.synthesize({ input: 'hello', model: 'gpt-4o-mini-tts', speed: 1, voice: 'marin' });++ expect(textToSpeechMock.mock.calls[0][0].params).toEqual({});+ });++ it('rejects params the model card does not declare', async () => {+ await expect(+ caller.synthesize({+ input: 'hello',+ model: 'tts-1',+ params: { emotion: 'happy', speed: 9 },+ provider: 'openai',+ }),+ ).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ message:+ 'params.emotion not supported by this model; params.speed must be between 0.25 and 4',+ });+ expect(textToSpeechMock).not.toHaveBeenCalled();+ });++ it('passes params through unchecked for models without a built-in card', async () => {+ await caller.synthesize({+ input: 'hello',+ model: 'custom-tts',+ params: { emotion: 'happy', pitch: 3 },+ provider: 'my-gateway',+ voice: 'v1',+ });++ expect(textToSpeechMock.mock.calls[0][0].params).toEqual({ emotion: 'happy', pitch: 3 });+ });++ it.each(['wav', 'pcm', 'flac'])(+ 'rejects uncompressed %s before synthesizing, since inline audio would outgrow the response',+ async (format) => {+ await expect(+ caller.synthesize({ input: 'hello', model: 'tts-1', params: { format } as any }),+ ).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ message: expect.stringContaining('params.format must be one of mp3, opus, aac'),+ });+ expect(textToSpeechMock).not.toHaveBeenCalled();+ },+ );++ it('rejects unknown param keys at the input boundary', async () => {+ await expect(+ caller.synthesize({+ input: 'hello',+ model: 'tts-1',+ params: { tone: 'warm' } as any,+ }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ });++ it('throws NOT_IMPLEMENTED when the provider has no text-to-speech', async () => {+ textToSpeechMock.mockResolvedValue(undefined);++ await expect(+ caller.synthesize({ input: 'hello', model: 'tts-1', voice: 'alloy' }),+ ).rejects.toMatchObject({ code: 'NOT_IMPLEMENTED' });+ });++ it('surfaces a readable message when the runtime rejects with an error payload', async () => {+ // Runtimes reject with plain `{ errorType, error }` objects, which tRPC used to flatten+ // into an INTERNAL_SERVER_ERROR without any message.+ textToSpeechMock.mockRejectedValue({+ error: { base_resp: { status_code: 2054, status_msg: 'voice id not exist' } },+ errorType: 'ProviderBizError',+ });++ await expect(+ caller.synthesize({+ input: 'hello',+ model: 'speech-2.8-hd',+ provider: 'minimax',+ voice: 'x',+ }),+ ).rejects.toMatchObject({ code: 'BAD_GATEWAY', message: 'voice id not exist' });+ });++ it('maps provider rate limits to TOO_MANY_REQUESTS', async () => {+ textToSpeechMock.mockRejectedValue(+ Object.assign(new Error('MiniMax API error: rate limit'), { errorType: 'RateLimitExceeded' }),+ );++ await expect(+ caller.synthesize({+ input: 'hello',+ model: 'speech-2.8-hd',+ provider: 'minimax',+ voice: 'x',+ }),+ ).rejects.toMatchObject({+ code: 'TOO_MANY_REQUESTS',+ message: 'MiniMax API error: rate limit',+ });+ });+});diff --git a/apps/server/src/routers/lambda/tts.ts b/apps/server/src/routers/lambda/tts.tsindex f8e8da84f0a..cfe58a986b2 100644--- a/apps/server/src/routers/lambda/tts.ts+++ b/apps/server/src/routers/lambda/tts.ts@@ -1,4 +1,6 @@+import type { ModelUsage } from '@lobechat/types';import { TRPCError } from '@trpc/server';+import type { TTSAudioFormat } from 'model-bank';import { z } from 'zod';import {@@ -7,14 +9,39 @@ import {} from '@/business/server/trpc-middlewares/workspaceAuth';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';-import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';+import {+ INLINE_TTS_AUDIO_FORMATS,+ TTSProviderError,+ TTSRequestError,+ TTSService,+} from '@/server/services/tts';++const ttsParamsInput = z+ .object({+ emotion: z.string().min(1).optional(),+ format: z+ .enum(INLINE_TTS_AUDIO_FORMATS, {+ message: `params.format must be one of ${INLINE_TTS_AUDIO_FORMATS.join(', ')} for inline audio`,+ })+ .optional(),+ instructions: z.string().optional(),+ pitch: z.number().optional(),+ sampleRate: z.number().int().positive().optional(),+ speed: z.number().positive().optional(),+ volume: z.number().optional(),+ })+ .strict();const synthesizeInput = z.object({input: z.string().min(1),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'),+ /** @deprecated Use `params.speed`. */speed: z.number().min(0.25).max(4).optional(),- voice: z.string().min(1).default('alloy'),+ /** Defaults to the model card's default voice. */+ voice: z.string().min(1).optional(),});const ttsProcedure = wsCompatProcedure@@ -22,24 +49,43 @@ const ttsProcedure = wsCompatProcedure.use(requireWorkspaceRoleWhenScoped('member'));export const ttsRouter = router({- synthesize: ttsProcedure.input(synthesizeInput).mutation(async ({ ctx, input }) => {- const { provider, ...payload } = input;- const runtime = await initModelRuntimeFromDB(- ctx.serverDB,- ctx.userId,- provider,- ctx.workspaceId ?? undefined,- );-- const audio = await runtime.textToSpeech(payload, { user: ctx.userId });+ synthesize: ttsProcedure.input(synthesizeInput).mutation(+ async ({+ ctx,+ input,+ }): Promise<{+ audioBase64: string;+ format: TTSAudioFormat;+ mimeType: string;+ usage?: ModelUsage;+ }> => {+ const service = new TTSService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);- if (!audio) {- throw new TRPCError({- code: 'NOT_IMPLEMENTED',- message: `Provider "${provider}" does not support text-to-speech.`,- });- }+ try {+ const result = await service.synthesize(input);- return { audioBase64: Buffer.from(audio).toString('base64') };- }),+ return {+ audioBase64: Buffer.from(result.audio).toString('base64'),+ format: result.format,+ mimeType: result.mimeType,+ usage: result.usage,+ };+ } catch (error) {+ if (error instanceof TTSRequestError) {+ throw new TRPCError({+ code: error.reason === 'invalid_params' ? 'BAD_REQUEST' : 'NOT_IMPLEMENTED',+ message: error.message,+ });+ }+ if (error instanceof TTSProviderError) {+ throw new TRPCError({+ cause: error.detail,+ code: error.errorType === 'RateLimitExceeded' ? 'TOO_MANY_REQUESTS' : 'BAD_GATEWAY',+ message: error.message,+ });+ }+ throw error;+ }+ },+ ),});diff --git a/apps/server/src/services/tts/index.test.ts b/apps/server/src/services/tts/index.test.tsnew file mode 100644index 00000000000..85aa0b1fc8c--- /dev/null+++ b/apps/server/src/services/tts/index.test.ts@@ -0,0 +1,37 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));++const { resolveTTSModelRef } = await import('./index');++describe('resolveTTSModelRef', () => {+ it('takes a leading known provider id as the provider', () => {+ expect(resolveTTSModelRef('lobehub/speech-2.8-hd')).toEqual({+ model: 'speech-2.8-hd',+ provider: 'lobehub',+ });+ });++ it('keeps model ids that contain a slash whole', () => {+ expect(resolveTTSModelRef('FunAudioLLM/CosyVoice2-0.5B')).toEqual({+ model: 'FunAudioLLM/CosyVoice2-0.5B',+ provider: 'openai',+ });+ });++ it('lets an explicit provider win over the model reference', () => {+ expect(resolveTTSModelRef('speech-2.8-hd', 'lobehub')).toEqual({+ model: 'speech-2.8-hd',+ provider: 'lobehub',+ });+ });++ it("falls back to the built-in card's provider for a bare model id", () => {+ expect(resolveTTSModelRef('speech-2.8-turbo')).toEqual({+ model: 'speech-2.8-turbo',+ provider: 'minimax',+ });+ expect(resolveTTSModelRef('tts-1')).toEqual({ model: 'tts-1', provider: 'openai' });+ });+});diff --git a/apps/server/src/services/tts/index.ts b/apps/server/src/services/tts/index.tsnew file mode 100644index 00000000000..8829e396e81--- /dev/null+++ b/apps/server/src/services/tts/index.ts@@ -0,0 +1,190 @@+import type { ModelUsage } from '@lobechat/types';+import { RequestTrigger } from '@lobechat/types';+import type { AITTSModelCard, TTSAudioFormat } from 'model-bank';+import { LOBE_DEFAULT_MODEL_LIST, TTS_AUDIO_MIME_TYPES, validateTTSParams } from 'model-bank';+import { ModelProvider } from 'model-bank/modelProvider';++import type { LobeChatDatabase } from '@/database/type';+import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';++/**+ * The audio goes back inside one buffered response (≈4.5MB on serverless deploys), as+ * base64 over tRPC or as the raw body over the public API. Uncompressed `wav` / `pcm`+ * (and lossless `flac`) outgrow that within about a minute of speech, after the provider+ * has already billed the synthesis, so only compressed formats are offered.+ */+export const INLINE_TTS_AUDIO_FORMATS = ['mp3', 'opus', 'aac'] as const;++export interface TTSSynthesizeParams {+ emotion?: string;+ format?: (typeof INLINE_TTS_AUDIO_FORMATS)[number];+ instructions?: string;+ pitch?: number;+ sampleRate?: number;+ speed?: number;+ volume?: number;+}++export interface TTSSynthesizeRequest {+ input: string;+ model: string;+ params?: TTSSynthesizeParams;+ provider: string;+ /** @deprecated Top-level speed sent by older CLIs; `params.speed` wins. */+ speed?: number;+ /** Defaults to the model card's default voice. */+ voice?: string;+}++export interface TTSSynthesizeResult {+ audio: ArrayBuffer;+ format: TTSAudioFormat;+ mimeType: string;+ usage?: ModelUsage;+}++/** The request itself is invalid: a bad parameter, or a provider without TTS. */+export class TTSRequestError extends Error {+ readonly name = 'TTSRequestError';++ constructor(+ message: string,+ readonly reason: 'invalid_params' | 'unsupported_provider',+ ) {+ super(message);+ }+}++/**+ * The provider refused or failed the synthesis. Runtimes reject with plain+ * `{ errorType, error }` payloads as well as `Error`s; this carries a readable+ * message for both, so callers never surface an empty 500.+ */+export class TTSProviderError extends Error {+ readonly name = 'TTSProviderError';++ constructor(+ message: string,+ readonly errorType: string | undefined,+ readonly detail?: unknown,+ ) {+ super(message);+ }+}++const isRecord = (value: unknown): value is Record<string, any> =>+ typeof value === 'object' && value !== null;++const toProviderError = (error: unknown, provider: string): TTSProviderError => {+ if (!isRecord(error)) return new TTSProviderError(String(error), undefined, error);++ const errorType = typeof error.errorType === 'string' ? error.errorType : undefined;+ const detail = isRecord(error.error) ? error.error : undefined;+ const message =+ (typeof error.message === 'string' && error.message) ||+ (typeof detail?.message === 'string' && detail.message) ||+ (typeof detail?.base_resp?.status_msg === 'string' && detail.base_resp.status_msg) ||+ (errorType ? `${provider} text-to-speech failed: ${errorType}` : '') ||+ `${provider} text-to-speech failed`;++ return new TTSProviderError(message, errorType, error);+};++/**+ * Built-in card of a TTS model: the provider's own card first, then any provider+ * serving the same model id (aggregators reuse upstream cards).+ */+export const findTTSModelCard = (provider: string, model: string): AITTSModelCard | undefined => {+ const cards = LOBE_DEFAULT_MODEL_LIST.filter((card) => card.type === 'tts' && card.id === model);++ return (cards.find((card) => card.providerId === provider) ?? cards[0]) as+ AITTSModelCard | undefined;+};++const KNOWN_PROVIDERS = new Set<string>(Object.values(ModelProvider));++/**+ * Splits a public-API model reference into provider and model. An explicit provider wins;+ * otherwise a leading known provider id (`lobehub/speech-2.8-hd`) is taken as the provider,+ * so model ids that contain a slash themselves (`FunAudioLLM/CosyVoice2-0.5B`) stay whole.+ * A bare id falls back to the provider of its built-in card, then to OpenAI.+ */+export const resolveTTSModelRef = (+ modelRef: string,+ provider?: string,+): { model: string; provider: string } => {+ if (provider) return { model: modelRef, provider };++ const slash = modelRef.indexOf('/');+ if (slash > 0 && KNOWN_PROVIDERS.has(modelRef.slice(0, slash))) {+ return { model: modelRef.slice(slash + 1), provider: modelRef.slice(0, slash) };+ }++ const card = LOBE_DEFAULT_MODEL_LIST.find((item) => item.type === 'tts' && item.id === modelRef);+ return { model: modelRef, provider: card?.providerId ?? ModelProvider.OpenAI };+};++/**+ * Text-to-speech shared by the tRPC router and the public OpenAPI route: validates the+ * params against the model card, then synthesizes through the user's model runtime, whose+ * hooks reserve, settle and release the spend.+ */+export class TTSService {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ async synthesize(request: TTSSynthesizeRequest): Promise<TTSSynthesizeResult> {+ const { input, model, provider } = request;+ const card = findTTSModelCard(provider, model);+ const params: TTSSynthesizeParams = { ...request.params };+ // Older CLIs always send the deprecated top-level `speed`; drop it for models that+ // declare no speed instead of failing validation they never opted into.+ const acceptsLegacySpeed = !card?.parameters || 'speed' in card.parameters;+ if (params.speed === undefined && request.speed !== undefined && acceptsLegacySpeed) {+ params.speed = request.speed;+ }++ if (card?.parameters) {+ const issues = validateTTSParams(card.parameters, params);+ if (issues.length > 0) {+ throw new TTSRequestError(+ issues.map(({ key, reason }) => `params.${key} ${reason}`).join('; '),+ 'invalid_params',+ );+ }+ }++ const voice = request.voice ?? card?.parameters?.voice?.default ?? 'alloy';++ const runtime = await initModelRuntimeFromDB(this.db, this.userId, provider, this.workspaceId);++ let result: Awaited<ReturnType<typeof runtime.textToSpeech>>;+ try {+ result = await runtime.textToSpeech(+ { input, model, params, voice },+ { metadata: { trigger: RequestTrigger.Tts }, user: this.userId },+ );+ } catch (error) {+ // Budget refusals and other server-side guards already carry their own status.+ if (error instanceof Error && error.name === 'TRPCError') throw error;+ throw toProviderError(error, provider);+ }++ if (!result) {+ throw new TTSRequestError(+ `Provider "${provider}" does not support text-to-speech.`,+ 'unsupported_provider',+ );+ }++ return {+ audio: result.audio,+ format: result.format,+ mimeType: TTS_AUDIO_MIME_TYPES[result.format],+ usage: result.usage,+ };+ }+}diff --git a/locales/en-US/modelProvider.json b/locales/en-US/modelProvider.jsonindex 10c3f8243fd..c7969ea3bdb 100644--- a/locales/en-US/modelProvider.json+++ b/locales/en-US/modelProvider.json@@ -302,6 +302,7 @@"providerModels.item.modelConfig.video.title": "Supports Video Recognition","providerModels.item.modelConfig.vision.extra": "This configuration will only enable image upload capabilities in the application. Whether recognition is supported depends entirely on the model itself. Please test the visual recognition capabilities of the model yourself.","providerModels.item.modelConfig.vision.title": "Support Vision",+ "providerModels.item.pricing.audioOutputTokens": "Audio output ${{amount}}/M","providerModels.item.pricing.image": "${{amount}}/Image","providerModels.item.pricing.inputCharts": "${{amount}}/M Characters","providerModels.item.pricing.inputMinutes": "${{amount}}/Minutes",diff --git a/locales/en-US/models.json b/locales/en-US/models.jsonindex fcadfdefd35..c454c4ac076 100644--- a/locales/en-US/models.json+++ b/locales/en-US/models.json@@ -646,7 +646,7 @@"gpt-4o-2024-11-20.description": "ChatGPT-4o is a dynamic model updated in real time, combining strong understanding and generation for large-scale use cases like customer support, education, and technical support.","gpt-4o-mini-realtime-preview.description": "GPT-4o-mini realtime variant with audio and text real-time I/O.","gpt-4o-mini-transcribe.description": "GPT-4o Mini Transcribe is a speech-to-text model that transcribes audio with GPT-4o, improving word error rate, language ID, and accuracy over the original Whisper model.",- "gpt-4o-mini-tts.description": "GPT-4o mini TTS is a text-to-speech model built on GPT-4o mini, converting text into natural-sounding speech with a max input of 2000 tokens.",+ "gpt-4o-mini-tts.description": "GPT-4o mini TTS is a text-to-speech model built on GPT-4o mini, converting text into natural-sounding speech with a max input of 2000 tokens. OpenAI has deprecated it and shuts it down on 2027-01-06.","gpt-4o-mini.description": "GPT-4o mini is OpenAI’s latest model after GPT-4 Omni, supporting text+image input with text output. It is their most advanced small model, far cheaper than recent frontier models and over 60% cheaper than GPT-3.5 Turbo, while maintaining top-tier intelligence (82% MMLU).","gpt-4o-realtime-preview-2024-10-01.description": "GPT-4o realtime variant with audio and text real-time I/O.","gpt-4o-realtime-preview-2025-06-03.description": "GPT-4o realtime variant with audio and text real-time I/O.",@@ -1309,6 +1309,12 @@"spark-x1.5.description": "X1.5 updates: (1) adds dynamic thinking mode controlled by the `thinking` field; (2) larger context length with 64K input and 64K output; (3) supports FunctionCall.","spark-x2-flash.description": "Spark X2-Flash adopts an MoE (Mixture of Experts) architecture with 30 billion total parameters and supports up to a 256K context window. It claims significant improvements in agentic and coding capabilities, and was trained on a cluster of Ascend 910B AI processors.","spark-x2.description": "X2 Capabilities Overview: 1. Introduces dynamic adjustment of reasoning mode, controlled via the `thinking` field. 2. Expanded context length: 64K input tokens and 128K output tokens. 3. Supports Function Call functionality.",+ "speech-02-hd.description": "High-fidelity speech model with strong rhythm, stable timbre and high similarity.",+ "speech-02-turbo.description": "Low-latency speech model with improved multilingual performance.",+ "speech-2.6-hd.description": "High-fidelity speech model with expressive emotion control, including fluent and whisper styles.",+ "speech-2.6-turbo.description": "Low-latency speech model with expressive emotion control, including fluent and whisper styles.",+ "speech-2.8-hd.description": "The latest high-fidelity speech model with natural prosody, rich emotion and precise timbre reproduction.",+ "speech-2.8-turbo.description": "The latest low-latency speech model, balancing synthesis speed with natural expression.","stable-diffusion-3-medium.description": "The latest text-to-image model from Stability AI. This version significantly improves image quality, text understanding, and style diversity, interpreting complex natural-language prompts more accurately and generating more precise, diverse images.","stable-diffusion-3.5-large-turbo.description": "Stable Diffusion 3.5 Large Turbo focuses on high-quality image generation with strong detail rendering and scene fidelity.","stable-diffusion-xl-base-1.0.description": "An open-source text-to-image model from Stability AI with industry-leading creative image generation. It has strong instruction understanding and supports reverse prompt definitions for precise generation.",@@ -1350,8 +1356,8 @@"text-embedding-3-small.description": "An efficient, cost-effective next-generation embedding model for retrieval and RAG scenarios.","thudm/glm-4-9b-chat.description": "The open-source release of Zhipu AI’s latest GLM-4 pretraining model.","togethercomputer/StripedHyena-Nous-7B.description": "StripedHyena Nous (7B) delivers enhanced compute efficiency through its architecture and strategy.",- "tts-1-hd.description": "The latest text-to-speech model optimized for quality.",- "tts-1.description": "The latest text-to-speech model optimized for real-time speed.",+ "tts-1-hd.description": "Legacy text-to-speech model optimized for quality. OpenAI has deprecated it and shuts it down on 2027-01-06.",+ "tts-1.description": "Legacy text-to-speech model optimized for real-time speed. OpenAI has deprecated it and shuts it down on 2027-01-06.","typesafe/jev-1.13.description": "TypeSafe Jev is a System One decision model: it answers yes/no, choice, and score questions with calibrated probabilities instead of generating text.","unsloth/Qwen3-1.7B-GGUF.description": "Qwen3 is the latest generation of the Qwen series, supporting seamless switching between thinking and non-thinking modes.","unsloth/gemma-3-4b-it-GGUF.description": "Gemma 3 is a lightweight open model family from Google, supporting multimodal input and strong instruction following.",diff --git a/locales/en-US/spend.json b/locales/en-US/spend.jsonindex 026bdc66583..fc5c54969d0 100644--- a/locales/en-US/spend.json+++ b/locales/en-US/spend.json@@ -52,6 +52,7 @@"table.columns.trigger.enums.topic_summary": "Topic Summary","table.columns.trigger.enums.topic_title": "Topic Title","table.columns.trigger.enums.translate": "Translation",+ "table.columns.trigger.enums.tts": "Voice Synthesis","table.columns.trigger.enums.verify": "Acceptance Check","table.columns.trigger.enums.video": "Video Generation","table.columns.trigger.title": "Trigger",@@ -59,6 +60,7 @@"table.columns.type.enums.embedding": "Embedding","table.columns.type.enums.imageGeneration": "Image Generation","table.columns.type.enums.speechRecognition": "Voice Transcription",+ "table.columns.type.enums.textToSpeech": "Speech Synthesis","table.columns.type.enums.videoGeneration": "Video Generation","table.columns.type.title": "Type","table.desc": "Details of credit usage for text generation, embedding, image generation, etc.",diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.jsonindex 08196c5292f..8ead8bc0150 100644--- a/locales/zh-CN/modelProvider.json+++ b/locales/zh-CN/modelProvider.json@@ -302,6 +302,7 @@"providerModels.item.modelConfig.video.title": "支持视频识别","providerModels.item.modelConfig.vision.extra": "此配置将仅开启应用中的图片上传配置,是否支持识别完全取决于模型本身,请自行测试该模型的视觉识别能力可用性","providerModels.item.modelConfig.vision.title": "支持视觉识别",+ "providerModels.item.pricing.audioOutputTokens": "音频输出 ${{amount}}/M","providerModels.item.pricing.image": "${{amount}}/图片","providerModels.item.pricing.inputCharts": "${{amount}}/M 字符","providerModels.item.pricing.inputMinutes": "${{amount}}/分钟",diff --git a/locales/zh-CN/models.json b/locales/zh-CN/models.jsonindex 2e15610467d..99e22533f55 100644--- a/locales/zh-CN/models.json+++ b/locales/zh-CN/models.json@@ -646,7 +646,7 @@"gpt-4o-2024-11-20.description": "ChatGPT-4o 是一款实时更新的动态模型,结合强大的理解与生成能力,适用于客户支持、教育与技术支持等大规模应用场景。","gpt-4o-mini-realtime-preview.description": "GPT-4o-mini 实时变体,支持音频与文本的实时输入输出。","gpt-4o-mini-transcribe.description": "GPT-4o Mini 转录模型是一款语音转文本模型,使用 GPT-4o 进行音频转录,在词错误率、语言识别与准确性方面优于原始 Whisper 模型。",- "gpt-4o-mini-tts.description": "GPT-4o mini TTS 是一款基于 GPT-4o mini 的文本转语音模型,可将文本转换为自然语音,最大输入为 2000 个 token。",+ "gpt-4o-mini-tts.description": "GPT-4o mini TTS 是一款基于 GPT-4o mini 的文本转语音模型,可将文本转换为自然语音,最大输入为 2000 个 token。OpenAI 已宣布弃用,将于 2027-01-06 停止服务。","gpt-4o-mini.description": "GPT-4o mini 是 OpenAI 在 GPT-4 Omni 之后推出的最新模型,支持文本+图像输入与文本输出。作为最先进的小型模型,其价格远低于前沿模型,比 GPT-3.5 Turbo 便宜 60% 以上,同时保持顶级智能水平(MMLU 达 82%)。","gpt-4o-realtime-preview-2024-10-01.description": "GPT-4o 实时变体,支持音频与文本的实时输入输出。","gpt-4o-realtime-preview-2025-06-03.description": "GPT-4o 实时变体,支持音频与文本的实时输入输出。",@@ -1309,6 +1309,12 @@"spark-x1.5.description": "X1.5 更新内容:1. 增加了由 `thinking` 字段控制的动态思维模式;2. 扩展了上下文长度,支持 64K 输入和 64K 输出;3. 支持 FunctionCall 功能。","spark-x2-flash.description": "Spark X2-Flash 采用 MoE(专家混合)架构,拥有 300 亿总参数,支持高达 256K 的上下文窗口。它在代理性和编程能力方面取得了显著提升,并在 Ascend 910B AI 处理器集群上进行训练。","spark-x2.description": "X2 功能概览:1. 引入了由 `thinking` 字段控制的推理模式动态调整;2. 扩展了上下文长度:支持 64K 输入标记和 128K 输出标记;3. 支持 Function Call 功能。",+ "speech-02-hd.description": "高保真语音模型,节奏感强、音色稳定、相似度高。",+ "speech-02-turbo.description": "低延迟语音模型,多语种表现进一步提升。",+ "speech-2.6-hd.description": "高保真语音模型,情绪控制表现力强,支持生动与低语风格。",+ "speech-2.6-turbo.description": "低延迟语音模型,情绪控制表现力强,支持生动与低语风格。",+ "speech-2.8-hd.description": "最新高保真语音模型,韵律自然、情感丰富,音色还原精准。",+ "speech-2.8-turbo.description": "最新低延迟语音模型,兼顾合成速度与自然表达。","stable-diffusion-3-medium.description": "Stability AI 最新的文本生成图像模型。该版本显著提升图像质量、文本理解与风格多样性,能更准确地解析复杂自然语言提示并生成更精确多样的图像。","stable-diffusion-3.5-large-turbo.description": "Stable Diffusion 3.5 Large Turbo 专注于高质量图像生成,具备强大的细节渲染与场景还原能力。","stable-diffusion-xl-base-1.0.description": "Stability AI 开源的文本生成图像模型,具备行业领先的创意图像生成能力。具备强指令理解能力,支持反向提示定义,实现精确生成。",@@ -1350,8 +1356,8 @@"text-embedding-3-small.description": "高效、低成本的下一代嵌入模型,适用于检索与 RAG 场景。","thudm/glm-4-9b-chat.description": "智谱 AI 最新 GLM-4 预训练模型的开源版本。","togethercomputer/StripedHyena-Nous-7B.description": "StripedHyena Nous(7B)通过架构与策略提升计算效率。",- "tts-1-hd.description": "最新文本转语音模型,优化音质表现。",- "tts-1.description": "最新文本转语音模型,优化实时速度。",+ "tts-1-hd.description": "旧版文本转语音模型,优化音质表现。OpenAI 已宣布弃用,将于 2027-01-06 停止服务。",+ "tts-1.description": "旧版文本转语音模型,优化实时速度。OpenAI 已宣布弃用,将于 2027-01-06 停止服务。","typesafe/jev-1.13.description": "TypeSafe Jev 是一个 System One 决策模型:它通过校准概率回答是/否、选择和评分问题,而不是生成文本。","unsloth/Qwen3-1.7B-GGUF.description": "Qwen3 是 Qwen 系列的最新一代,支持在思考模式和非思考模式之间无缝切换。","unsloth/gemma-3-4b-it-GGUF.description": "Gemma 3 是 Google 推出的轻量级开放模型系列,支持多模态输入和强大的指令跟随能力。",diff --git a/locales/zh-CN/spend.json b/locales/zh-CN/spend.jsonindex fc72a9cda19..7ae3277ec51 100644--- a/locales/zh-CN/spend.json+++ b/locales/zh-CN/spend.json@@ -52,6 +52,7 @@"table.columns.trigger.enums.topic_summary": "话题摘要","table.columns.trigger.enums.topic_title": "话题标题","table.columns.trigger.enums.translate": "翻译",+ "table.columns.trigger.enums.tts": "语音合成","table.columns.trigger.enums.verify": "验收","table.columns.trigger.enums.video": "视频生成","table.columns.trigger.title": "触发方式",@@ -59,6 +60,7 @@"table.columns.type.enums.embedding": "嵌入","table.columns.type.enums.imageGeneration": "图像生成","table.columns.type.enums.speechRecognition": "语音转写",+ "table.columns.type.enums.textToSpeech": "语音合成","table.columns.type.enums.videoGeneration": "视频生成","table.columns.type.title": "类型","table.desc": "展示文本生成、嵌入、图像生成等功能的计算积分使用详情。",diff --git a/packages/locales/src/default/modelProvider.ts b/packages/locales/src/default/modelProvider.tsindex 18ecc4c776b..55432761d37 100644--- a/packages/locales/src/default/modelProvider.ts+++ b/packages/locales/src/default/modelProvider.ts@@ -392,6 +392,7 @@ export default {'providerModels.item.modelConfig.vision.extra':'This configuration will only enable image upload capabilities in the application. Whether recognition is supported depends entirely on the model itself. Please test the visual recognition capabilities of the model yourself.','providerModels.item.modelConfig.vision.title': 'Support Vision',+ 'providerModels.item.pricing.audioOutputTokens': 'Audio output ${{amount}}/M','providerModels.item.pricing.image': '${{amount}}/Image','providerModels.item.pricing.inputCharts': '${{amount}}/M Characters','providerModels.item.pricing.inputMinutes': '${{amount}}/Minutes',diff --git a/packages/locales/src/default/spend.ts b/packages/locales/src/default/spend.tsindex 82ec5884b7e..37d1df594d1 100644--- a/packages/locales/src/default/spend.ts+++ b/packages/locales/src/default/spend.ts@@ -51,6 +51,7 @@ export default {'table.columns.trigger.enums.topic_summary': 'Topic Summary','table.columns.trigger.enums.topic_title': 'Topic Title','table.columns.trigger.enums.translate': 'Translation',+ 'table.columns.trigger.enums.tts': 'Voice Synthesis','table.columns.trigger.enums.verify': 'Acceptance Check','table.columns.trigger.enums.video': 'Video Generation','table.columns.trigger.title': 'Trigger',@@ -58,6 +59,7 @@ export default {'table.columns.type.enums.embedding': 'Embedding','table.columns.type.enums.imageGeneration': 'Image Generation','table.columns.type.enums.speechRecognition': 'Voice Transcription',+ 'table.columns.type.enums.textToSpeech': 'Speech Synthesis','table.columns.type.enums.videoGeneration': 'Video Generation','table.columns.type.title': 'Type','table.agentShareDesc':diff --git a/packages/model-bank/src/aiModels/minimax.ts b/packages/model-bank/src/aiModels/minimax.tsindex 66f43aade9c..08f55ea7676 100644--- a/packages/model-bank/src/aiModels/minimax.ts+++ b/packages/model-bank/src/aiModels/minimax.ts@@ -1,6 +1,13 @@+import {+ minimaxSpeech02Schema,+ minimaxSpeech26Schema,+ minimaxSpeech28Schema,+ minimaxTTSVoices,+} from '../const/ttsParameters';import {type AIChatModelCard,type AIImageModelCard,+ type AITTSModelCard,type AIVideoModelCard,} from '../types/aiModel';@@ -637,6 +644,95 @@ const minimaxVideoModels: AIVideoModelCard[] = [},];-export const allModels = [...minimaxChatModels, ...minimaxImageModels, ...minimaxVideoModels];+// Prices are ¥3.5 (HD) and ¥2 (Turbo) per 10k characters, billed on `usage_characters`.+// @see https://platform.minimaxi.com/docs/guides/pricing-paygo+const minimaxTTSModels: AITTSModelCard[] = [+ {+ description:+ 'The latest high-fidelity speech model with natural prosody, rich emotion and precise timbre reproduction.',+ displayName: 'Speech 2.8 HD',+ enabled: true,+ id: 'speech-2.8-hd',+ parameters: minimaxSpeech28Schema,+ pricing: {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 350, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: minimaxTTSVoices,+ },+ {+ description:+ 'The latest low-latency speech model, balancing synthesis speed with natural expression.',+ displayName: 'Speech 2.8 Turbo',+ enabled: true,+ id: 'speech-2.8-turbo',+ parameters: minimaxSpeech28Schema,+ pricing: {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 200, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: minimaxTTSVoices,+ },+ {+ description:+ 'High-fidelity speech model with expressive emotion control, including fluent and whisper styles.',+ displayName: 'Speech 2.6 HD',+ id: 'speech-2.6-hd',+ parameters: minimaxSpeech26Schema,+ pricing: {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 350, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: minimaxTTSVoices,+ },+ {+ description:+ 'Low-latency speech model with expressive emotion control, including fluent and whisper styles.',+ displayName: 'Speech 2.6 Turbo',+ id: 'speech-2.6-turbo',+ parameters: minimaxSpeech26Schema,+ pricing: {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 200, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: minimaxTTSVoices,+ },+ {+ description:+ 'High-fidelity speech model with strong rhythm, stable timbre and high similarity.',+ displayName: 'Speech 02 HD',+ id: 'speech-02-hd',+ parameters: minimaxSpeech02Schema,+ pricing: {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 350, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: minimaxTTSVoices,+ },+ {+ description: 'Low-latency speech model with improved multilingual performance.',+ displayName: 'Speech 02 Turbo',+ id: 'speech-02-turbo',+ parameters: minimaxSpeech02Schema,+ pricing: {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 200, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: minimaxTTSVoices,+ },+];++export const allModels = [+ ...minimaxChatModels,+ ...minimaxImageModels,+ ...minimaxVideoModels,+ ...minimaxTTSModels,+];export default allModels;diff --git a/packages/model-bank/src/aiModels/openai/nonChat.ts b/packages/model-bank/src/aiModels/openai/nonChat.tsindex f91eab1fbf3..36483b8f2dd 100644--- a/packages/model-bank/src/aiModels/openai/nonChat.ts+++ b/packages/model-bank/src/aiModels/openai/nonChat.ts@@ -1,4 +1,10 @@import { gptImage1Schema, gptImage2Schema } from '../../const/imageParameters';+import {+ openaiGpt4oMiniTTSSchema,+ openaiGpt4oTTSVoices,+ openaiTTS1Schema,+ openaiTTS1Voices,+} from '../../const/ttsParameters';import type {AIASRModelCard,AIEmbeddingModelCard,@@ -43,28 +49,38 @@ export const openaiEmbeddingModels: AIEmbeddingModelCard[] = [// Text-to-speech modelsexport const openaiTTSModels: AITTSModelCard[] = [{- description: 'The latest text-to-speech model optimized for real-time speed.',+ description:+ 'Legacy text-to-speech model optimized for real-time speed. OpenAI has deprecated it and shuts it down on 2027-01-06.',displayName: 'TTS-1',id: 'tts-1',+ legacy: true,+ parameters: openaiTTS1Schema,pricing: {units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],},type: 'tts',+ voices: openaiTTS1Voices,},{- description: 'The latest text-to-speech model optimized for quality.',+ description:+ 'Legacy text-to-speech model optimized for quality. OpenAI has deprecated it and shuts it down on 2027-01-06.',displayName: 'TTS-1 HD',id: 'tts-1-hd',+ legacy: true,+ parameters: openaiTTS1Schema,pricing: {units: [{ name: 'textInput', rate: 30, strategy: 'fixed', unit: 'millionCharacters' }],},type: 'tts',+ voices: openaiTTS1Voices,},{description:- 'GPT-4o mini TTS is a text-to-speech model built on GPT-4o mini, converting text into natural-sounding speech with a max input of 2000 tokens.',+ 'GPT-4o mini TTS is a text-to-speech model built on GPT-4o mini, converting text into natural-sounding speech with a max input of 2000 tokens. OpenAI has deprecated it and shuts it down on 2027-01-06.',displayName: 'GPT-4o Mini TTS',id: 'gpt-4o-mini-tts',+ legacy: true,+ parameters: openaiGpt4oMiniTTSSchema,pricing: {units: [{ name: 'textInput', rate: 0.6, strategy: 'fixed', unit: 'millionTokens' },@@ -72,6 +88,7 @@ export const openaiTTSModels: AITTSModelCard[] = [],},type: 'tts',+ voices: openaiGpt4oTTSVoices,},];diff --git a/packages/model-bank/src/const/__tests__/ttsParameters.test.ts b/packages/model-bank/src/const/__tests__/ttsParameters.test.tsnew file mode 100644index 00000000000..87589ba5069--- /dev/null+++ b/packages/model-bank/src/const/__tests__/ttsParameters.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest';++import minimaxModels from '../../aiModels/minimax';+import { openaiTTSModels } from '../../aiModels/openai/nonChat';+import { TTSVoiceSchema, validateTTSModelParamsSchema } from '../../standard-parameters';+import type { AITTSModelCard } from '../../types/aiModel';++describe('OpenAI TTS model cards', () => {+ it.each(openaiTTSModels.map((card) => [card.id, card]))(+ '%s declares parameters and a valid voice catalog',+ (_id, card) => {+ expect(card.parameters).toBeDefined();+ expect(() => validateTTSModelParamsSchema(card.parameters)).not.toThrow();++ expect(card.voices?.length).toBeGreaterThan(0);+ for (const voice of card.voices!) expect(() => TTSVoiceSchema.parse(voice)).not.toThrow();++ // The default voice must be one the model actually offers.+ const voiceIds = card.voices!.map((voice) => voice.id);+ expect(voiceIds).toContain(card.parameters!.voice!.default);+ expect(new Set(voiceIds).size).toBe(voiceIds.length);+ },+ );++ it('keeps tts-1 voices to the classic set and adds the GPT-4o voices to gpt-4o-mini-tts', () => {+ const voicesOf = (id: string) =>+ openaiTTSModels.find((card) => card.id === id)!.voices!.map((voice) => voice.id);++ expect(voicesOf('tts-1')).toContain('nova');+ expect(voicesOf('tts-1')).not.toContain('marin');+ expect(voicesOf('gpt-4o-mini-tts')).toEqual(expect.arrayContaining(['alloy', 'nova', 'marin']));+ });++ it('only lets gpt-4o-mini-tts take style instructions', () => {+ const tts1 = openaiTTSModels.find((card) => card.id === 'tts-1')!;+ const mini = openaiTTSModels.find((card) => card.id === 'gpt-4o-mini-tts')!;++ expect(tts1.parameters).toHaveProperty('speed');+ expect(tts1.parameters).not.toHaveProperty('instructions');+ expect(mini.parameters).toHaveProperty('instructions');+ });+});++describe('MiniMax TTS model cards', () => {+ const minimaxTTSModels = minimaxModels.filter(+ (card): card is AITTSModelCard => card.type === 'tts',+ );++ it('lists the speech-2.8 / 2.6 / 02 HD and Turbo models', () => {+ expect(minimaxTTSModels.map((card) => card.id)).toEqual([+ 'speech-2.8-hd',+ 'speech-2.8-turbo',+ 'speech-2.6-hd',+ 'speech-2.6-turbo',+ 'speech-02-hd',+ 'speech-02-turbo',+ ]);+ });++ it.each(minimaxTTSModels.map((card) => [card.id, card]))(+ '%s declares valid params, voices and CNY per-character pricing',+ (id, card) => {+ const params = validateTTSModelParamsSchema(card.parameters);+ expect(params.speed).toMatchObject({ max: 2, min: 0.5 });+ expect(params.pitch).toMatchObject({ max: 12, min: -12 });+ expect(params.volume).toMatchObject({ max: 10 });+ expect(params.format?.enum).not.toContain('aac');+ expect(params).not.toHaveProperty('instructions');++ const voiceIds = card.voices!.map((voice) => voice.id);+ expect(voiceIds).toContain(params.voice!.default);+ // The default must also exist on the global endpoint, which lacks e.g. `female-shaonv`.+ expect(params.voice!.default).toBe('Chinese (Mandarin)_Warm_Girl');+ expect(new Set(voiceIds).size).toBe(voiceIds.length);+ for (const voice of card.voices!) expect(() => TTSVoiceSchema.parse(voice)).not.toThrow();++ // ¥3.5 (HD) / ¥2 (Turbo) per 10k characters+ expect(card.pricing).toEqual({+ currency: 'CNY',+ units: [+ {+ name: 'textInput',+ rate: id.endsWith('-hd') ? 350 : 200,+ strategy: 'fixed',+ unit: 'millionCharacters',+ },+ ],+ });+ },+ );++ it('offers at least 10 Mandarin character voices across styles', () => {+ const voices = minimaxTTSModels[0].voices!;+ const ids = voices.map((voice) => voice.id);++ expect(voices.filter((voice) => voice.language === 'zh-CN').length).toBeGreaterThanOrEqual(10);+ // 少女 / 御姐 / 少年 styles+ expect(ids).toEqual(+ expect.arrayContaining(['female-shaonv', 'female-yujie', 'male-qn-qingse', 'clever_boy']),+ );+ });++ it('only exposes the emotions each generation supports', () => {+ const emotionsOf = (id: string) =>+ validateTTSModelParamsSchema(minimaxTTSModels.find((card) => card.id === id)!.parameters)+ .emotion!.enum;++ expect(emotionsOf('speech-2.8-hd')).toContain('fluent');+ expect(emotionsOf('speech-2.8-hd')).not.toContain('whisper');+ expect(emotionsOf('speech-2.6-hd')).toContain('whisper');+ expect(emotionsOf('speech-02-hd')).not.toContain('fluent');+ });+});diff --git a/packages/model-bank/src/const/ttsParameters.ts b/packages/model-bank/src/const/ttsParameters.tsnew file mode 100644index 00000000000..8f3d3cd3c26--- /dev/null+++ b/packages/model-bank/src/const/ttsParameters.ts@@ -0,0 +1,174 @@+import type { TTSModelParamsSchema, TTSVoice } from '../standard-parameters';+import { TTS_AUDIO_FORMATS } from '../standard-parameters';++/**+ * Built-in OpenAI voices.+ * @see https://platform.openai.com/docs/guides/text-to-speech#voice-options+ */+const OPENAI_TTS_1_VOICES: TTSVoice[] = [+ { displayName: 'Alloy', gender: 'neutral', id: 'alloy', language: 'multilingual' },+ { displayName: 'Ash', gender: 'male', id: 'ash', language: 'multilingual' },+ { displayName: 'Coral', gender: 'female', id: 'coral', language: 'multilingual' },+ { displayName: 'Echo', gender: 'male', id: 'echo', language: 'multilingual' },+ { displayName: 'Fable', gender: 'male', id: 'fable', language: 'multilingual' },+ { displayName: 'Nova', gender: 'female', id: 'nova', language: 'multilingual' },+ { displayName: 'Onyx', gender: 'male', id: 'onyx', language: 'multilingual' },+ { displayName: 'Sage', gender: 'female', id: 'sage', language: 'multilingual' },+ { displayName: 'Shimmer', gender: 'female', id: 'shimmer', language: 'multilingual' },+];++/** `ballad`, `verse`, `marin` and `cedar` are only available on the GPT-4o TTS family. */+export const openaiGpt4oTTSVoices: TTSVoice[] = (+ [+ ...OPENAI_TTS_1_VOICES,+ { displayName: 'Ballad', gender: 'male', id: 'ballad', language: 'multilingual' },+ { displayName: 'Cedar', gender: 'male', id: 'cedar', language: 'multilingual' },+ { displayName: 'Marin', gender: 'female', id: 'marin', language: 'multilingual' },+ { displayName: 'Verse', gender: 'male', id: 'verse', language: 'multilingual' },+ ] satisfies TTSVoice[]+).sort((a, b) => a.id.localeCompare(b.id));++export const openaiTTS1Voices: TTSVoice[] = OPENAI_TTS_1_VOICES;++export const openaiTTS1Schema: TTSModelParamsSchema = {+ format: { default: 'mp3', enum: [...TTS_AUDIO_FORMATS] },+ speed: { default: 1, max: 4, min: 0.25, step: 0.05 },+ voice: { default: 'alloy' },+};++/** GPT-4o mini TTS takes style `instructions` but ignores `speed`. */+export const openaiGpt4oMiniTTSSchema: TTSModelParamsSchema = {+ format: { default: 'mp3', enum: [...TTS_AUDIO_FORMATS] },+ instructions: { default: '' },+ voice: { default: 'alloy' },+};++/**+ * MiniMax Mandarin system voices suited to character voice-over.+ * @see https://platform.minimaxi.com/docs/faq/system-voice-id+ */+export const minimaxTTSVoices: TTSVoice[] = [+ { displayName: '少女', gender: 'female', id: 'female-shaonv', language: 'zh-CN' },+ { displayName: '御姐', gender: 'female', id: 'female-yujie', language: 'zh-CN' },+ { displayName: '成熟女性', gender: 'female', id: 'female-chengshu', language: 'zh-CN' },+ { displayName: '甜美女性', gender: 'female', id: 'female-tianmei', language: 'zh-CN' },+ { displayName: '青涩青年', gender: 'male', id: 'male-qn-qingse', language: 'zh-CN' },+ { displayName: '精英青年', gender: 'male', id: 'male-qn-jingying', language: 'zh-CN' },+ { displayName: '霸道青年', gender: 'male', id: 'male-qn-badao', language: 'zh-CN' },+ { displayName: '青年大学生', gender: 'male', id: 'male-qn-daxuesheng', language: 'zh-CN' },+ { displayName: '聪明男童', gender: 'male', id: 'clever_boy', language: 'zh-CN' },+ { displayName: '可爱男童', gender: 'male', id: 'cute_boy', language: 'zh-CN' },+ { displayName: '萌萌女童', gender: 'female', id: 'lovely_girl', language: 'zh-CN' },+ { displayName: '病娇弟弟', gender: 'male', id: 'bingjiao_didi', language: 'zh-CN' },+ { displayName: '俊朗男友', gender: 'male', id: 'junlang_nanyou', language: 'zh-CN' },+ { displayName: '纯真学弟', gender: 'male', id: 'chunzhen_xuedi', language: 'zh-CN' },+ { displayName: '冷淡学长', gender: 'male', id: 'lengdan_xiongzhang', language: 'zh-CN' },+ { displayName: '霸道少爷', gender: 'male', id: 'badao_shaoye', language: 'zh-CN' },+ { displayName: '甜心小玲', gender: 'female', id: 'tianxin_xiaoling', language: 'zh-CN' },+ { displayName: '俏皮萌妹', gender: 'female', id: 'qiaopi_mengmei', language: 'zh-CN' },+ { displayName: '妩媚御姐', gender: 'female', id: 'wumei_yujie', language: 'zh-CN' },+ { displayName: '嗲嗲学妹', gender: 'female', id: 'diadia_xuemei', language: 'zh-CN' },+ { displayName: '淡雅学姐', gender: 'female', id: 'danya_xuejie', language: 'zh-CN' },+ {+ displayName: '傲娇御姐',+ gender: 'female',+ id: 'Chinese (Mandarin)_Mature_Woman',+ language: 'zh-CN',+ },+ {+ displayName: '不羁青年',+ gender: 'male',+ id: 'Chinese (Mandarin)_Unrestrained_Young_Man',+ language: 'zh-CN',+ },+ {+ displayName: '温暖少女',+ gender: 'female',+ id: 'Chinese (Mandarin)_Warm_Girl',+ language: 'zh-CN',+ },+ {+ displayName: '温柔学姐',+ gender: 'female',+ id: 'Chinese (Mandarin)_Gentle_Senior',+ language: 'zh-CN',+ },+ {+ displayName: '嘴硬竹马',+ gender: 'male',+ id: 'Chinese (Mandarin)_Stubborn_Friend',+ language: 'zh-CN',+ },+ {+ displayName: '清脆少女',+ gender: 'female',+ id: 'Chinese (Mandarin)_Crisp_Girl',+ language: 'zh-CN',+ },+ {+ displayName: '清澈邻家弟弟',+ gender: 'male',+ id: 'Chinese (Mandarin)_Pure-hearted_Boy',+ language: 'zh-CN',+ },+ {+ displayName: '柔和少女',+ gender: 'female',+ id: 'Chinese (Mandarin)_Soft_Girl',+ language: 'zh-CN',+ },+ {+ displayName: '温润男声',+ gender: 'male',+ id: 'Chinese (Mandarin)_Gentleman',+ language: 'zh-CN',+ },+ {+ displayName: '新闻女声',+ gender: 'female',+ id: 'Chinese (Mandarin)_News_Anchor',+ language: 'zh-CN',+ },+ {+ displayName: '播报男声',+ gender: 'male',+ id: 'Chinese (Mandarin)_Male_Announcer',+ language: 'zh-CN',+ },+];++/** Emotions every MiniMax speech model accepts. */+const MINIMAX_BASE_EMOTIONS = [+ 'happy',+ 'sad',+ 'angry',+ 'fearful',+ 'disgusted',+ 'surprised',+ 'calm',+];++/** `aac` is the only standard format t2a_v2 does not produce. */+const MINIMAX_TTS_FORMATS = TTS_AUDIO_FORMATS.filter((format) => format !== 'aac');++const createMiniMaxTTSSchema = (emotions: string[]): TTSModelParamsSchema => ({+ emotion: { default: 'calm', enum: emotions },+ format: { default: 'mp3', enum: MINIMAX_TTS_FORMATS },+ pitch: { default: 0, max: 12, min: -12, step: 1 },+ sampleRate: { default: 32_000, enum: [8000, 16_000, 22_050, 24_000, 32_000, 44_100] },+ speed: { default: 1, max: 2, min: 0.5, step: 0.05 },+ // Offered by both the China and the global endpoint; most catalog ids are China-only.+ voice: { default: 'Chinese (Mandarin)_Warm_Girl' },+ volume: { default: 1, max: 10, min: 0.1, step: 0.1 },+});++/** speech-2.8 adds `fluent` but drops `whisper`. */+export const minimaxSpeech28Schema = createMiniMaxTTSSchema([...MINIMAX_BASE_EMOTIONS, 'fluent']);++export const minimaxSpeech26Schema = createMiniMaxTTSSchema([+ ...MINIMAX_BASE_EMOTIONS,+ 'fluent',+ 'whisper',+]);++export const minimaxSpeech02Schema = createMiniMaxTTSSchema(MINIMAX_BASE_EMOTIONS);diff --git a/packages/model-bank/src/standard-parameters/index.ts b/packages/model-bank/src/standard-parameters/index.tsindex 9eab3ef6de0..5fe0bc17c94 100644--- a/packages/model-bank/src/standard-parameters/index.ts+++ b/packages/model-bank/src/standard-parameters/index.ts@@ -337,4 +337,5 @@ export function extractDefaultValues(paramsSchema: ModelParamsSchema) {) as RuntimeImageGenParams;}+export * from './tts';export * from './video';diff --git a/packages/model-bank/src/standard-parameters/tts.test.ts b/packages/model-bank/src/standard-parameters/tts.test.tsnew file mode 100644index 00000000000..7bd67785dbf--- /dev/null+++ b/packages/model-bank/src/standard-parameters/tts.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from 'vitest';++import { openaiGpt4oMiniTTSSchema, openaiTTS1Schema } from '../const/ttsParameters';+import {+ extractTTSDefaultValues,+ TTS_AUDIO_FORMATS,+ TTS_AUDIO_MIME_TYPES,+ TTSModelParamsMetaSchema,+ type TTSModelParamsSchema,+ TTSVoiceSchema,+ validateTTSModelParamsSchema,+ validateTTSParams,+} from './tts';++const fullSchema: TTSModelParamsSchema = {+ emotion: { default: 'neutral', enum: ['neutral', 'happy', 'sad'] },+ format: { default: 'mp3', enum: ['mp3', 'wav', 'pcm'] },+ instructions: { maxLength: 20 },+ pitch: { default: 0, max: 12, min: -12, step: 1 },+ sampleRate: { default: 32_000, enum: [16_000, 24_000, 32_000] },+ speed: { default: 1, max: 2, min: 0.5, step: 0.1 },+ voice: { default: 'female-shaonv' },+ volume: { default: 1, max: 10, min: 0.1 },+};++describe('tts standard-parameters', () => {+ describe('TTSModelParamsMetaSchema', () => {+ it('validates a schema declaring every standard param', () => {+ expect(() => validateTTSModelParamsSchema(fullSchema)).not.toThrow();+ });++ it('accepts an empty schema since every param is optional', () => {+ expect(TTSModelParamsMetaSchema.parse({})).toEqual({});+ });++ it('rejects a format outside the standard list', () => {+ expect(() =>+ TTSModelParamsMetaSchema.parse({ format: { default: 'ogg', enum: ['ogg'] } }),+ ).toThrow();+ });++ it('requires numeric ranges to declare min and max', () => {+ expect(() => TTSModelParamsMetaSchema.parse({ speed: { default: 1 } })).toThrow();+ });++ it('validates the built-in OpenAI schemas', () => {+ expect(() => validateTTSModelParamsSchema(openaiTTS1Schema)).not.toThrow();+ expect(() => validateTTSModelParamsSchema(openaiGpt4oMiniTTSSchema)).not.toThrow();+ });+ });++ describe('extractTTSDefaultValues', () => {+ it('returns the declared defaults without voice', () => {+ expect(extractTTSDefaultValues(fullSchema)).toEqual({+ emotion: 'neutral',+ format: 'mp3',+ instructions: '',+ pitch: 0,+ sampleRate: 32_000,+ speed: 1,+ volume: 1,+ });+ });+ });++ describe('validateTTSParams', () => {+ it('accepts values inside the declared ranges and enums', () => {+ expect(+ validateTTSParams(fullSchema, {+ emotion: 'happy',+ format: 'wav',+ pitch: -3,+ sampleRate: 24_000,+ speed: 1.5,+ }),+ ).toEqual([]);+ });++ it('reports params the model does not declare', () => {+ expect(validateTTSParams(openaiTTS1Schema, { emotion: 'happy', pitch: 2 })).toEqual([+ { key: 'emotion', reason: 'not supported by this model' },+ { key: 'pitch', reason: 'not supported by this model' },+ ]);+ });++ it('reports out-of-range numbers and unknown enum values', () => {+ expect(+ validateTTSParams(fullSchema, { emotion: 'angry', sampleRate: 44_100, speed: 3 }),+ ).toEqual([+ { key: 'emotion', reason: 'must be one of neutral, happy, sad' },+ { key: 'sampleRate', reason: 'must be one of 16000, 24000, 32000' },+ { key: 'speed', reason: 'must be between 0.5 and 2' },+ ]);+ });++ it('reports instructions over the declared max length', () => {+ expect(validateTTSParams(fullSchema, { instructions: 'x'.repeat(21) })).toEqual([+ { key: 'instructions', reason: 'must be at most 20 characters' },+ ]);+ });++ it('ignores undefined values', () => {+ expect(validateTTSParams(openaiTTS1Schema, { emotion: undefined })).toEqual([]);+ });+ });++ describe('voices', () => {+ it('requires id, displayName, language and gender', () => {+ expect(() =>+ TTSVoiceSchema.parse({ displayName: 'Alloy', gender: 'neutral', id: 'alloy' }),+ ).toThrow();+ expect(+ TTSVoiceSchema.parse({+ displayName: 'Alloy',+ gender: 'neutral',+ id: 'alloy',+ language: 'multilingual',+ previewUrl: 'https://example.com/alloy.mp3',+ }),+ ).toMatchObject({ id: 'alloy' });+ });+ });++ it('maps every audio format to a mime type', () => {+ for (const format of TTS_AUDIO_FORMATS) {+ expect(TTS_AUDIO_MIME_TYPES[format]).toMatch(/^audio\//);+ }+ });+});diff --git a/packages/model-bank/src/standard-parameters/tts.ts b/packages/model-bank/src/standard-parameters/tts.tsnew file mode 100644index 00000000000..f148dcb7172--- /dev/null+++ b/packages/model-bank/src/standard-parameters/tts.ts@@ -0,0 +1,189 @@+import type { Simplify } from 'type-fest';+import { z } from 'zod';++/**+ * Audio container formats a TTS model can return. Providers map these onto their own+ * request field (`response_format` for OpenAI, `audio_setting.format` for MiniMax, ...).+ */+export const TTS_AUDIO_FORMATS = ['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm'] as const;++export type TTSAudioFormat = (typeof TTS_AUDIO_FORMATS)[number];++export const DEFAULT_TTS_AUDIO_FORMAT: TTSAudioFormat = 'mp3';++export const TTS_AUDIO_MIME_TYPES: Record<TTSAudioFormat, string> = {+ aac: 'audio/aac',+ flac: 'audio/flac',+ mp3: 'audio/mpeg',+ opus: 'audio/opus',+ pcm: 'audio/pcm',+ wav: 'audio/wav',+};++const numberRangeParamSchema = z.object({+ default: z.number(),+ description: z.string().optional(),+ max: z.number(),+ min: z.number(),+ step: z.number().optional(),+ type: z.literal('number').optional(),+});++const enumParamSchema = <T extends z.ZodTypeAny>(value: T) =>+ z.object({+ default: value,+ description: z.string().optional(),+ enum: z.array(value),+ });++/**+ * Declares which standard TTS parameters a model accepts and their allowed values.+ * A key that is absent means the model does not support that parameter.+ */+export const TTSModelParamsMetaSchema = z.object({+ /**+ * Default voice id; the full catalog lives on `AITTSModelCard.voices`.+ */+ voice: z+ .object({+ default: z.string(),+ description: z.string().optional(),+ type: z.literal('string').optional(),+ })+ .optional(),++ /** Playback speed multiplier, 1 is normal speed. */+ speed: numberRangeParamSchema.optional(),++ /** Pitch shift; the unit is provider-specific (semitones for MiniMax). */+ pitch: numberRangeParamSchema.optional(),++ /** Output loudness; the unit is provider-specific. */+ volume: numberRangeParamSchema.optional(),++ emotion: enumParamSchema(z.string())+ .extend({ type: z.literal('string').optional() })+ .optional(),++ format: enumParamSchema(z.enum(TTS_AUDIO_FORMATS))+ .extend({ type: z.literal('string').optional() })+ .optional(),++ /** Output sample rate in Hz. */+ sampleRate: enumParamSchema(z.number())+ .extend({ type: z.literal('number').optional() })+ .optional(),++ /** Free-form style instructions (e.g. "speak cheerfully"), for models that accept them. */+ instructions: z+ .object({+ default: z.string().optional().default(''),+ description: z.string().optional(),+ maxLength: z.number().optional(),+ type: z.literal('string').optional(),+ })+ .optional(),+});++export type TTSModelParamsSchema = z.input<typeof TTSModelParamsMetaSchema>;+export type TTSModelParamsOutputSchema = z.output<typeof TTSModelParamsMetaSchema>;+export type TTSModelParamsKeys = Simplify<keyof TTSModelParamsOutputSchema>;++/**+ * Standard TTS parameters sent to the runtime. `voice` is a top-level payload field,+ * so it is not part of `params`.+ */+export interface RuntimeTTSParams {+ emotion?: string;+ format?: TTSAudioFormat;+ instructions?: string;+ pitch?: number;+ sampleRate?: number;+ speed?: number;+ volume?: number;+}++export type RuntimeTTSParamsKeys = keyof RuntimeTTSParams;++export const TTSVoiceGenderSchema = z.enum(['female', 'male', 'neutral']);++export type TTSVoiceGender = z.infer<typeof TTSVoiceGenderSchema>;++export const TTSVoiceSchema = z.object({+ /** Short description of the timbre, e.g. "warm, calm narrator". */+ description: z.string().optional(),+ displayName: z.string(),+ gender: TTSVoiceGenderSchema,+ /** Provider voice id sent as `payload.voice`. */+ id: z.string(),+ /** BCP 47 language tag the voice is tuned for (`zh-CN`, `en-US`), or `multilingual`. */+ language: z.string(),+ previewUrl: z.string().optional(),+});++export type TTSVoice = z.infer<typeof TTSVoiceSchema>;++export function validateTTSModelParamsSchema(paramsSchema: unknown): TTSModelParamsOutputSchema {+ return TTSModelParamsMetaSchema.parse(paramsSchema);+}++/**+ * Extract the default value of every declared parameter, excluding `voice`.+ */+export function extractTTSDefaultValues(paramsSchema: TTSModelParamsSchema): RuntimeTTSParams {+ const { voice: _voice, ...schemaWithDefault } = TTSModelParamsMetaSchema.parse(paramsSchema);++ return Object.fromEntries(+ Object.entries(schemaWithDefault)+ .filter(([, value]) => value !== undefined && value.default !== undefined)+ .map(([key, value]) => [key, value!.default]),+ ) as RuntimeTTSParams;+}++export type TTSParamsIssue = { key: RuntimeTTSParamsKeys; reason: string };++/**+ * Check requested params against a model's declared schema. Returns one issue per+ * unsupported key or out-of-range value; an empty array means the request is valid.+ */+export function validateTTSParams(+ paramsSchema: TTSModelParamsSchema,+ params: RuntimeTTSParams,+): TTSParamsIssue[] {+ const schema = TTSModelParamsMetaSchema.parse(paramsSchema);+ const issues: TTSParamsIssue[] = [];++ for (const [rawKey, value] of Object.entries(params)) {+ const key = rawKey as RuntimeTTSParamsKeys;+ if (value === undefined) continue;++ const definition = schema[key];+ if (!definition) {+ issues.push({ key, reason: 'not supported by this model' });+ continue;+ }++ if ('enum' in definition && !(definition.enum as unknown[]).includes(value)) {+ issues.push({ key, reason: `must be one of ${definition.enum.join(', ')}` });+ continue;+ }++ if ('min' in definition && typeof value === 'number') {+ if (value < definition.min || value > definition.max) {+ issues.push({ key, reason: `must be between ${definition.min} and ${definition.max}` });+ }+ continue;+ }++ if (+ 'maxLength' in definition &&+ typeof definition.maxLength === 'number' &&+ typeof value === 'string' &&+ value.length > definition.maxLength+ ) {+ issues.push({ key, reason: `must be at most ${definition.maxLength} characters` });+ }+ }++ return issues;+}diff --git a/packages/model-bank/src/types/aiModel.ts b/packages/model-bank/src/types/aiModel.tsindex af36f2a112a..5d242f008d2 100644--- a/packages/model-bank/src/types/aiModel.ts+++ b/packages/model-bank/src/types/aiModel.ts@@ -1,6 +1,11 @@import { z } from 'zod';-import { type ModelParamsSchema, type VideoModelParamsSchema } from '../standard-parameters';+import {+ type ModelParamsSchema,+ type TTSModelParamsSchema,+ type TTSVoice,+ type VideoModelParamsSchema,+} from '../standard-parameters';export type ModelPriceCurrency = 'CNY' | 'USD';@@ -668,8 +673,16 @@ export interface AIVideoModelCard extends AIBaseModelCard {}export interface AITTSModelCard extends AIBaseModelCard {+ /**+ * Standard TTS parameters the model accepts and their allowed values.+ */+ parameters?: TTSModelParamsSchema;pricing?: Pricing;type: 'tts';+ /**+ * Voice catalog. `payload.voice` takes one of these ids.+ */+ voices?: TTSVoice[];}export interface AIASRModelCard extends AIBaseModelCard {@@ -723,10 +736,12 @@ export interface AiFullModelCard extends AIBaseModelCard {displayName?: string;id: string;maxDimension?: number;- parameters?: ModelParamsSchema;+ /** Image generation params, or standard TTS params for `tts` models. */+ parameters?: ModelParamsSchema | TTSModelParamsSchema;pricing?: Pricing;settings?: AiModelSettings;type: AiModelType;+ voices?: TTSVoice[];}export interface LobeDefaultAiModelListItem extends AiFullModelCard {@@ -851,7 +866,8 @@ export interface EnabledAiModel {id: string;knowledgeCutoff?: string;maxOutput?: number;- parameters?: ModelParamsSchema;+ /** Image generation params, or standard TTS params for `tts` models. */+ parameters?: ModelParamsSchema | TTSModelParamsSchema;pricing?: Pricing;providerId: string;releasedAt?: string;diff --git a/packages/model-runtime/src/core/BaseAI.ts b/packages/model-runtime/src/core/BaseAI.tsindex 6317332f389..707b1bbc23f 100644--- a/packages/model-runtime/src/core/BaseAI.ts+++ b/packages/model-runtime/src/core/BaseAI.ts@@ -29,6 +29,7 @@ import type {PullModelParams,TextToSpeechOptions,TextToSpeechPayload,+ TextToSpeechResponse,VideoGenerationCapabilities,VideoPollingRoute,} from '../types';@@ -87,7 +88,7 @@ export interface LobeRuntimeAI {textToSpeech?: (payload: TextToSpeechPayload,options?: TextToSpeechOptions,- ) => Promise<ArrayBuffer>;+ ) => Promise<TextToSpeechResponse>;transcribe?: (payload: ASRPayload, options?: ASROptions) => Promise<ASRResponse>;}@@ -113,5 +114,8 @@ export abstract class LobeOpenAICompatibleRuntime {transcribe?(payload: ASRPayload, options?: ASROptions): Promise<ASRResponse>;- textToSpeech?(payload: TextToSpeechPayload, options?: TextToSpeechOptions): Promise<ArrayBuffer>;+ textToSpeech?(+ payload: TextToSpeechPayload,+ options?: TextToSpeechOptions,+ ): Promise<TextToSpeechResponse>;}diff --git a/packages/model-runtime/src/core/ModelRuntime.test.ts b/packages/model-runtime/src/core/ModelRuntime.test.tsindex 5b32080f694..eaed77fab88 100644--- a/packages/model-runtime/src/core/ModelRuntime.test.ts+++ b/packages/model-runtime/src/core/ModelRuntime.test.ts@@ -444,64 +444,6 @@ describe('ModelRuntime', () => {});});- describe('ModelRuntime textToSpeech method', () => {- it('should run correctly', async () => {- const payload = {- model: 'tts-1',- input: 'Hello world',- voice: 'alloy',- };-- const mockResponse = new ArrayBuffer(8);-- vi.spyOn(LobeOpenAI.prototype, 'textToSpeech').mockResolvedValue(mockResponse);-- const result = await mockModelRuntime.textToSpeech(payload);-- expect(LobeOpenAI.prototype.textToSpeech).toHaveBeenCalledWith(payload, undefined);- expect(result).toBe(mockResponse);- });-- it('should handle options correctly', async () => {- const payload = {- model: 'tts-1',- input: 'Hello world',- voice: 'alloy',- };-- const options = {};-- const mockResponse = new ArrayBuffer(8);-- vi.spyOn(LobeOpenAI.prototype, 'textToSpeech').mockResolvedValue(mockResponse);-- const result = await mockModelRuntime.textToSpeech(payload, options);-- expect(LobeOpenAI.prototype.textToSpeech).toHaveBeenCalledWith(payload, options);- expect(result).toBe(mockResponse);- });-- it('should handle undefined textToSpeech method gracefully', async () => {- const payload = {- model: 'tts-1',- input: 'Hello world',- voice: 'alloy',- };-- // Mock runtime without textToSpeech method- const runtimeWithoutTextToSpeech = {- textToSpeech: undefined,- };-- // @ts-ignore - testing edge case- mockModelRuntime['_runtime'] = runtimeWithoutTextToSpeech;-- const result = await mockModelRuntime.textToSpeech(payload);-- expect(result).toBeUndefined();- });- });-describe('ModelRuntime pullModel method', () => {it('should run correctly', async () => {const params = {diff --git a/packages/model-runtime/src/core/ModelRuntime.textToSpeech.test.ts b/packages/model-runtime/src/core/ModelRuntime.textToSpeech.test.tsnew file mode 100644index 00000000000..9b77a258889--- /dev/null+++ b/packages/model-runtime/src/core/ModelRuntime.textToSpeech.test.ts@@ -0,0 +1,155 @@+// @vitest-environment node+import { describe, expect, it, vi } from 'vitest';++import type { TextToSpeechResponse } from '../types';+import { ModelRuntime, type ModelRuntimeHooks } from './ModelRuntime';++vi.mock('../providers/lobehub', () => ({+ LobeHubAI: class LobeHubAI {},+}));++const createMockRuntime = (hooks?: ModelRuntimeHooks) => {+ const mockRuntimeAI = { textToSpeech: vi.fn() } as any;+ return { runtime: new ModelRuntime(mockRuntimeAI, hooks), mockRuntimeAI };+};++const ttsPayload = {+ input: '你好,我是 Claude 娘',+ model: 'tts-1',+ params: { format: 'mp3' as const, speed: 1.2 },+ voice: 'nova',+};++const speech = (usage?: TextToSpeechResponse['usage']): TextToSpeechResponse => ({+ audio: new ArrayBuffer(8),+ format: 'mp3',+ usage,+});++describe('ModelRuntime textToSpeech', () => {+ it('passes payload and options through to the provider and returns its response', async () => {+ const { runtime, mockRuntimeAI } = createMockRuntime();+ const response = speech({ inputCharacters: 13 });+ mockRuntimeAI.textToSpeech.mockResolvedValue(response);++ const options = { user: 'u1' };+ const result = await runtime.textToSpeech(ttsPayload, options);++ expect(mockRuntimeAI.textToSpeech).toHaveBeenCalledWith(ttsPayload, options);+ expect(result).toBe(response);+ });++ it('resolves to undefined when the provider has no textToSpeech', async () => {+ const runtime = new ModelRuntime({} as any);++ await expect(runtime.textToSpeech(ttsPayload)).resolves.toBeUndefined();+ });++ describe('hooks', () => {+ it('passes provider usage to onTextToSpeechFinal after beforeTextToSpeech', async () => {+ const usage = { cost: 0.000_195, inputCharacters: 13 };+ const callerOnUsage = vi.fn();+ const beforeTextToSpeech = vi.fn();+ const onTextToSpeechFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({+ beforeTextToSpeech,+ onTextToSpeechFinal,+ });+ mockRuntimeAI.textToSpeech.mockImplementation(async (_payload: any, options: any) => {+ await options.onUsage(usage);+ return speech(usage);+ });++ const options = { onUsage: callerOnUsage, user: 'u1' };+ const result = await runtime.textToSpeech(ttsPayload, options);++ expect(result?.usage).toEqual(usage);+ expect(beforeTextToSpeech).toHaveBeenCalledWith(ttsPayload, options);+ expect(beforeTextToSpeech.mock.invocationCallOrder[0]).toBeLessThan(+ mockRuntimeAI.textToSpeech.mock.invocationCallOrder[0],+ );+ // The caller's own onUsage still fires alongside the hook's capture.+ expect(callerOnUsage).toHaveBeenCalledWith(usage);+ expect(onTextToSpeechFinal).toHaveBeenCalledWith(+ { latencyMs: expect.any(Number), usage },+ { options, payload: ttsPayload },+ );+ });++ it('forwards beforeTextToSpeech option mutations to the provider', async () => {+ const pricingContext = { plan: 'premium', scope: 'personal' } as const;+ const beforeTextToSpeech: ModelRuntimeHooks['beforeTextToSpeech'] = async (_p, options) => {+ if (options) options.pricingContext = pricingContext;+ };+ const { runtime, mockRuntimeAI } = createMockRuntime({ beforeTextToSpeech });+ mockRuntimeAI.textToSpeech.mockResolvedValue(speech());++ await runtime.textToSpeech(ttsPayload);++ expect(mockRuntimeAI.textToSpeech.mock.calls[0][1]).toMatchObject({ pricingContext });+ });++ it('still fires onTextToSpeechFinal without usage so reservations can be released', async () => {+ const onTextToSpeechFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({ onTextToSpeechFinal });+ mockRuntimeAI.textToSpeech.mockResolvedValue(speech());++ await runtime.textToSpeech(ttsPayload);++ expect(onTextToSpeechFinal).toHaveBeenCalledWith(+ { latencyMs: expect.any(Number), usage: undefined },+ { options: undefined, payload: ttsPayload },+ );+ });++ it('calls onTextToSpeechError and re-throws when the provider fails', async () => {+ const providerError = { errorType: 'ProviderBizError', error: { message: 'boom' } };+ const onTextToSpeechError = vi.fn();+ const onTextToSpeechFinal = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({+ onTextToSpeechError,+ onTextToSpeechFinal,+ });+ mockRuntimeAI.textToSpeech.mockRejectedValue(providerError);++ await expect(runtime.textToSpeech(ttsPayload)).rejects.toBe(providerError);+ expect(onTextToSpeechFinal).not.toHaveBeenCalled();+ expect(onTextToSpeechError).toHaveBeenCalledWith(providerError, {+ options: undefined,+ payload: ttsPayload,+ });+ });++ it('aborts before the provider call when beforeTextToSpeech throws', async () => {+ const budgetError = new Error('insufficient budget');+ const onTextToSpeechError = vi.fn();+ const { runtime, mockRuntimeAI } = createMockRuntime({+ beforeTextToSpeech: vi.fn().mockRejectedValue(budgetError),+ onTextToSpeechError,+ });++ await expect(runtime.textToSpeech(ttsPayload)).rejects.toBe(budgetError);+ expect(mockRuntimeAI.textToSpeech).not.toHaveBeenCalled();+ expect(onTextToSpeechError).toHaveBeenCalledWith(budgetError, {+ options: undefined,+ payload: ttsPayload,+ });+ });++ it('swallows onTextToSpeechFinal failures so the audio is still returned', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const { runtime, mockRuntimeAI } = createMockRuntime({+ onTextToSpeechFinal: vi.fn().mockRejectedValue(new Error('settle failed')),+ });+ const response = speech();+ mockRuntimeAI.textToSpeech.mockResolvedValue(response);++ await expect(runtime.textToSpeech(ttsPayload)).resolves.toBe(response);+ expect(consoleError).toHaveBeenCalledWith(+ '[ModelRuntime] onTextToSpeechFinal hook error:',+ expect.any(Error),+ );+ consoleError.mockRestore();+ });+ });+});diff --git a/packages/model-runtime/src/core/ModelRuntime.ts b/packages/model-runtime/src/core/ModelRuntime.tsindex 861e6468dbd..7ab654b46c0 100644--- a/packages/model-runtime/src/core/ModelRuntime.ts+++ b/packages/model-runtime/src/core/ModelRuntime.ts@@ -1,5 +1,4 @@import type { ModelPerformance, ModelUsage, TracePayload } from '@lobechat/types';-import { createTimingHelpers, getDurationMs } from '../utils/timing';import type { ClientOptions } from 'openai';import type { LobeBedrockAIParams } from '../providers/bedrock';@@ -23,6 +22,7 @@ import type {ModelRequestOptions,OnFinishData,PullModelParams,+ TextToSpeechOptions,TextToSpeechPayload,} from '../types';import { AgentRuntimeErrorType } from '../types/error';@@ -39,6 +39,7 @@ import type {VideoPollingRoute,} from '../types/video';import { AgentRuntimeError } from '../utils/createError';+import { createTimingHelpers, getDurationMs } from '../utils/timing';import { createVideoWithCompletionMode } from '../utils/videoCompletionMode';import type { LobeRuntimeAI } from './BaseAI';@@ -120,6 +121,10 @@ export interface ModelRuntimeHooks {payload: GenerateObjectPayload,options?: GenerateObjectOptions,) => Promise<void>;+ beforeTextToSpeech?: (+ payload: TextToSpeechPayload,+ options?: TextToSpeechOptions,+ ) => Promise<void>;beforeTranscribe?: (payload: ASRPayload, options?: ASROptions) => Promise<void>;/*** Called when chat() throws. Handle side effects (sanitize, log, DB record).@@ -215,6 +220,21 @@ export interface ModelRuntimeHooks {context: { options?: GenerateObjectOptions; payload: GenerateObjectPayload },) => void | Promise<void>;+ onTextToSpeechError?: (+ error: ChatCompletionErrorPayload,+ context: { options?: TextToSpeechOptions; payload: TextToSpeechPayload },+ ) => void | Promise<void>;++ /**+ * Fires once after a successful synthesis. `usage` is undefined when the provider+ * reports none, so consumers can still settle or release anything taken in+ * `beforeTextToSpeech`.+ */+ onTextToSpeechFinal?: (+ data: { latencyMs: number; usage?: ModelUsage },+ context: { options?: TextToSpeechOptions; payload: TextToSpeechPayload },+ ) => void | Promise<void>;+onTranscribeError?: (error: ChatCompletionErrorPayload,context: { options?: ASROptions; payload: ASRPayload },@@ -578,8 +598,46 @@ export class ModelRuntime {throw error;}}- async textToSpeech(payload: TextToSpeechPayload, options?: EmbeddingsOptions) {- return this._runtime.textToSpeech?.(payload, options);+ async textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {+ try {+ const hookOptions = this._hooks?.beforeTextToSpeech && !options ? {} : options;+ await this._hooks?.beforeTextToSpeech?.(payload, hookOptions);++ const startTime = Date.now();+ let usage: ModelUsage | undefined;+ const finalOptions = this._hooks?.onTextToSpeechFinal+ ? {+ ...hookOptions,+ onUsage: async (reported: ModelUsage) => {+ usage = reported;+ await hookOptions?.onUsage?.(reported);+ },+ }+ : hookOptions;++ const result = await this._runtime.textToSpeech?.(payload, finalOptions);++ if (this._hooks?.onTextToSpeechFinal) {+ try {+ await this._hooks.onTextToSpeechFinal(+ { latencyMs: Date.now() - startTime, usage },+ { options, payload },+ );+ } catch (e) {+ console.error('[ModelRuntime] onTextToSpeechFinal hook error:', e);+ }+ }++ return result;+ } catch (error) {+ if (this._hooks?.onTextToSpeechError) {+ await this._hooks.onTextToSpeechError(error as ChatCompletionErrorPayload, {+ options,+ payload,+ });+ }+ throw error;+ }}async transcribe(payload: ASRPayload, options?: ASROptions) {diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.tsnew file mode 100644index 00000000000..8a738ea4a8d--- /dev/null+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts@@ -0,0 +1,47 @@+import { RequestTrigger } from '@lobechat/types';+import { afterEach, describe, expect, it, vi } from 'vitest';++import type { TextToSpeechOptions, TextToSpeechPayload, TextToSpeechResponse } from '../../types';+import type { LobeRuntimeAI } from '../BaseAI';+import { createRouterRuntime } from './createRuntime';++const payload: TextToSpeechPayload = {+ input: '你好',+ model: 'tts-1',+ params: { format: 'wav', speed: 1.1 },+ voice: 'nova',+};++describe('createRouterRuntime textToSpeech', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ });++ it('returns the routed response with format and usage, and forwards onUsage', async () => {+ const usage = { cost: 0.00003, inputCharacters: 2 };+ const textToSpeech = vi.fn(+ async (_payload: TextToSpeechPayload, options?: TextToSpeechOptions) => {+ await options?.onUsage?.(usage);+ return { audio: new ArrayBuffer(4), format: 'wav', usage } as TextToSpeechResponse;+ },+ );++ class MockRuntime implements LobeRuntimeAI {+ textToSpeech = textToSpeech;+ }++ const Runtime = createRouterRuntime({+ id: 'test-runtime',+ routers: [{ apiType: 'openai', models: ['tts-1'], options: {}, runtime: MockRuntime as any }],+ });++ const onUsage = vi.fn();+ const options = { metadata: { trigger: RequestTrigger.Tts }, onUsage };+ const result = await new Runtime().textToSpeech(payload, options);++ expect(textToSpeech).toHaveBeenCalledWith(payload, options);+ expect(result).toMatchObject({ format: 'wav', usage });+ expect(onUsage).toHaveBeenCalledWith(usage);+ });+});diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.tsindex d80177d4b2d..fbd303d8b6f 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts@@ -1,10 +1,7 @@-/**- * @see https://github.com/lobehub/lobe-chat/discussions/6563- */+/** @see https://github.com/lobehub/lobe-chat/discussions/6563 */import type { GoogleGenAIOptions } from '@google/genai';import type { ModelPricingContext, RouterRuntimeRequestContext } from '@lobechat/types';import { AgentRuntimeErrorType } from '@lobechat/types';-import { createTimingHelpers, getDurationMs } from '../../utils/timing';import debug from 'debug';import { nanoid } from 'nanoid';@@ -27,6 +24,7 @@ import type {GenerateObjectOptions,GenerateObjectPayload,HandleCreateVideoWebhookPayload,+ TextToSpeechOptions,TextToSpeechPayload,VideoPollingRoute,} from '../../types';@@ -36,6 +34,7 @@ import { postProcessModelList } from '../../utils/postProcessModelList';import { isImageDecodingRequestError, shouldStopFallbackForError } from '../../utils/routeFallback';import { safeParseJSON } from '../../utils/safeParseJSON';import { setRuntimeSignatureScopeSource } from '../../utils/signatureScope';+import { createTimingHelpers, getDurationMs } from '../../utils/timing';import { createVideoWithCompletionMode } from '../../utils/videoCompletionMode';import type { LobeRuntimeAI } from '../BaseAI';import type { ApiType } from './apiTypes';@@ -1195,7 +1194,7 @@ export const createRouterRuntime = ({);}- async textToSpeech(payload: TextToSpeechPayload, options?: EmbeddingsOptions) {+ async textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {return this.runWithFallback(payload.model,(runtime) => runtime.textToSpeech!(payload, options),diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.tsindex 02f8cb7c455..8d365b7a31f 100644--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts@@ -102,6 +102,7 @@ import {parseStructuredToolArguments,StructuredOutputError,} from './structuredOutput';+import { createOpenAICompatibleSpeech } from './textToSpeech';export type { PollVideoStatusResult };export * from './createVideo';@@ -1168,25 +1169,12 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an}async textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {- const log = debug(`${this.logPrefix}:textToSpeech`);- const requestPayload = withMappedModelId(payload, this.modelIdMappingOptions);- log(- 'textToSpeech called with input length: %d, voice: %s',- payload.input?.length || 0,- payload.voice,- );-- try {- const mp3 = await this.client.audio.speech.create(requestPayload as any, {- headers: options?.headers,- signal: options?.signal,- });- const buffer = await mp3.arrayBuffer();- log('generated audio with size: %d bytes', buffer.byteLength);- return buffer;- } catch (error) {- throw this.handleError(error);- }+ return createOpenAICompatibleSpeech(this.client, payload, options, {+ handleError: (error) => this.handleError(error),+ logPrefix: this.logPrefix,+ provider: this.id,+ requestModel: resolveMappedModelId(payload.model, this.modelIdMappingOptions),+ });}/**diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/textToSpeech.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/textToSpeech.test.tsnew file mode 100644index 00000000000..fd6e3273b2c--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/textToSpeech.test.ts@@ -0,0 +1,202 @@+// @vitest-environment node+import type { Pricing } from 'model-bank';+import type OpenAI from 'openai';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getModelPricing } from '../../utils/getModelPricing';+import {+ createOpenAICompatibleSpeech,+ type CreateOpenAICompatibleSpeechContext,+} from './textToSpeech';++vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));++const characterPricing: Pricing = {+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],+};+const tokenPricing: Pricing = {+ units: [+ { name: 'textInput', rate: 0.6, strategy: 'fixed', unit: 'millionTokens' },+ { name: 'audioOutput', rate: 12, strategy: 'fixed', unit: 'millionTokens' },+ ],+};++const audioResponse = (bytes: number[]) =>+ new Response(new Uint8Array(bytes), { headers: { 'content-type': 'audio/mpeg' } });++const sseResponse = (events: object[]) =>+ new Response(events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(''), {+ headers: { 'content-type': 'text/event-stream' },+ });++const context: CreateOpenAICompatibleSpeechContext = {+ handleError: (error: unknown) => ({ error, errorType: 'ProviderBizError', provider: 'openai' }),+ logPrefix: 'test',+ provider: 'openai',+ requestModel: 'tts-1',+};++describe('createOpenAICompatibleSpeech', () => {+ let create: ReturnType<typeof vi.fn>;+ let client: OpenAI;++ beforeEach(() => {+ create = vi.fn();+ client = { audio: { speech: { create } } } as unknown as OpenAI;+ vi.mocked(getModelPricing).mockResolvedValue(characterPricing);+ });++ it('maps standard params onto /audio/speech and prices by characters', async () => {+ create.mockResolvedValue(audioResponse([1, 2, 3]));+ const onUsage = vi.fn();++ const result = await createOpenAICompatibleSpeech(+ client,+ {+ input: 'hello',+ model: 'tts-1',+ params: { emotion: 'happy', format: 'wav', pitch: 2, speed: 1.25 },+ voice: 'nova',+ },+ { onUsage, user: 'u1' },+ context,+ );++ expect(create).toHaveBeenCalledWith(+ { input: 'hello', model: 'tts-1', response_format: 'wav', speed: 1.25, voice: 'nova' },+ { headers: undefined, signal: undefined },+ );+ expect(new Uint8Array(result.audio)).toEqual(new Uint8Array([1, 2, 3]));+ expect(result.format).toBe('wav');+ // 5 chars × $15/1M rounds up to the smallest credit+ expect(result.usage).toEqual({ cost: 0.000075, inputCharacters: 5 });+ expect(onUsage).toHaveBeenCalledWith(result.usage);+ });++ it('defaults to mp3 and still reads the legacy top-level speed', async () => {+ create.mockResolvedValue(audioResponse([0]));++ const result = await createOpenAICompatibleSpeech(+ client,+ { input: 'hi', model: 'tts-1', speed: 0.5, voice: 'alloy' },+ undefined,+ context,+ );++ expect(create.mock.calls[0][0]).toMatchObject({ response_format: 'mp3', speed: 0.5 });+ expect(result.format).toBe('mp3');+ });++ it('sends the mapped upstream model id', async () => {+ create.mockResolvedValue(audioResponse([0]));++ await createOpenAICompatibleSpeech(+ client,+ { input: 'hi', model: 'tts-1', voice: 'alloy' },+ undefined,+ { ...context, requestModel: 'openai/tts-1' },+ );++ expect(create.mock.calls[0][0].model).toBe('openai/tts-1');+ });++ it('requests SSE for token-billed models and reads audio and token usage from events', async () => {+ vi.mocked(getModelPricing).mockResolvedValue(tokenPricing);+ create.mockResolvedValue(+ sseResponse([+ { audio: Buffer.from([1, 2]).toString('base64'), type: 'speech.audio.delta' },+ { audio: Buffer.from([3]).toString('base64'), type: 'speech.audio.delta' },+ {+ type: 'speech.audio.done',+ usage: { input_tokens: 1000, output_tokens: 10_000, total_tokens: 11_000 },+ },+ ]),+ );++ const result = await createOpenAICompatibleSpeech(+ client,+ {+ input: 'hello',+ model: 'gpt-4o-mini-tts',+ params: { instructions: 'Speak cheerfully' },+ voice: 'marin',+ },+ undefined,+ { ...context, requestModel: 'gpt-4o-mini-tts' },+ );++ expect(create.mock.calls[0][0]).toEqual({+ input: 'hello',+ instructions: 'Speak cheerfully',+ model: 'gpt-4o-mini-tts',+ response_format: 'mp3',+ stream_format: 'sse',+ voice: 'marin',+ });+ expect(new Uint8Array(result.audio)).toEqual(new Uint8Array([1, 2, 3]));+ expect(result.usage).toMatchObject({+ cost: 0.1206,+ inputCharacters: 5,+ inputTextTokens: 1000,+ outputAudioTokens: 10_000,+ });+ });++ it.each([+ [+ 'ends without audio',+ [{ type: 'speech.audio.done', usage: { input_tokens: 1, output_tokens: 1 } }],+ ],+ ['carries an error event', [{ error: { message: 'quota' }, type: 'error' }]],+ [+ 'closes before speech.audio.done',+ [{ audio: Buffer.from([1]).toString('base64'), type: 'speech.audio.delta' }],+ ],+ ])('fails instead of reporting usage when the SSE stream %s', async (_label, events) => {+ vi.mocked(getModelPricing).mockResolvedValue(tokenPricing);+ create.mockResolvedValue(sseResponse(events));+ const onUsage = vi.fn();++ await expect(+ createOpenAICompatibleSpeech(+ client,+ { input: 'hello', model: 'gpt-4o-mini-tts', voice: 'alloy' },+ { onUsage },+ context,+ ),+ ).rejects.toMatchObject({ errorType: 'ProviderBizError' });+ expect(onUsage).not.toHaveBeenCalled();+ });++ it('falls back to the raw body when a gateway ignores stream_format', async () => {+ vi.mocked(getModelPricing).mockResolvedValue(tokenPricing);+ create.mockResolvedValue(audioResponse([9, 9]));++ const result = await createOpenAICompatibleSpeech(+ client,+ { input: 'hello', model: 'gpt-4o-mini-tts', voice: 'alloy' },+ undefined,+ context,+ );++ expect(new Uint8Array(result.audio)).toEqual(new Uint8Array([9, 9]));+ // No token counts: cost stays unset instead of pricing to 0+ expect(result.usage).toEqual({ inputCharacters: 5 });+ });++ it('normalizes provider errors through handleError and reports no usage', async () => {+ const upstream = Object.assign(new Error('bad voice'), { status: 400 });+ create.mockRejectedValue(upstream);+ const onUsage = vi.fn();++ await expect(+ createOpenAICompatibleSpeech(+ client,+ { input: 'hi', model: 'tts-1', voice: 'nope' },+ { onUsage },+ context,+ ),+ ).rejects.toEqual({ error: upstream, errorType: 'ProviderBizError', provider: 'openai' });+ expect(onUsage).not.toHaveBeenCalled();+ });+});diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/textToSpeech.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/textToSpeech.tsnew file mode 100644index 00000000000..5d34a698ba9--- /dev/null+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/textToSpeech.ts@@ -0,0 +1,137 @@+import type { ModelTokensUsage } from '@lobechat/types';+import debug from 'debug';+import { DEFAULT_TTS_AUDIO_FORMAT } from 'model-bank';+import type OpenAI from 'openai';+import type { SpeechCreateParams } from 'openai/resources/audio/speech';++import type {+ TextToSpeechOptions,+ TextToSpeechPayload,+ TextToSpeechResponse,+} from '../../types/tts';+import { resolveTextToSpeechParams } from '../../types/tts';+import type { ChatCompletionErrorPayload } from '../../types/type';+import { getModelPricing } from '../../utils/getModelPricing';+import {+ convertOpenAISpeechTokenUsage,+ convertTextToSpeechUsage,+ isTokenBilledTextToSpeech,+} from '../usageConverters/tts';++export interface CreateOpenAICompatibleSpeechContext {+ handleError: (error: unknown) => ChatCompletionErrorPayload;+ logPrefix: string;+ provider: string;+ /** Upstream model id after model-id mapping. */+ requestModel: string;+}++interface SpeechEventStreamResult {+ audio: ArrayBuffer;+ tokenUsage?: ModelTokensUsage;+}++const isEventStream = (response: Response) =>+ response.headers.get('content-type')?.includes('text/event-stream') ?? false;++/**+ * Collect `speech.audio.delta` chunks and the `speech.audio.done` usage of an SSE response.+ */+const readSpeechEventStream = async (response: Response): Promise<SpeechEventStreamResult> => {+ const text = await response.text();+ const chunks: Buffer[] = [];+ let tokenUsage: ModelTokensUsage | undefined;+ let completed = false;++ for (const line of text.split('\n')) {+ if (!line.startsWith('data:')) continue;++ const data = line.slice('data:'.length).trim();+ if (!data || data === '[DONE]') continue;++ let event: { audio?: string; error?: unknown; type?: string; usage?: unknown };+ try {+ event = JSON.parse(data);+ } catch {+ continue;+ }++ if (event.type === 'speech.audio.delta' && event.audio) {+ chunks.push(Buffer.from(event.audio, 'base64'));+ } else if (event.type === 'speech.audio.done') {+ completed = true;+ tokenUsage = convertOpenAISpeechTokenUsage(event.usage);+ } else if (event.type === 'error' || event.error) {+ throw Object.assign(new Error('Speech stream returned an error event'), {+ error: event.error ?? event,+ });+ }+ }++ // An empty or truncated stream must not settle as a successful (billable) synthesis.+ if (chunks.length === 0) throw new Error('Speech stream ended without audio');+ if (!completed) throw new Error('Speech stream ended before speech.audio.done');++ const merged = Buffer.concat(chunks);+ const audio = merged.buffer.slice(merged.byteOffset, merged.byteOffset + merged.byteLength);++ return { audio: audio as ArrayBuffer, tokenUsage };+};++/**+ * `POST /audio/speech` with the standard TTS params. Token-billed models (e.g.+ * `gpt-4o-mini-tts`) are requested as SSE because only the `speech.audio.done` event+ * reports token usage; character-billed models (`tts-1`) return the raw audio body.+ */+export const createOpenAICompatibleSpeech = async (+ client: OpenAI,+ payload: TextToSpeechPayload,+ options: TextToSpeechOptions | undefined,+ context: CreateOpenAICompatibleSpeechContext,+): Promise<TextToSpeechResponse> => {+ const log = debug(`${context.logPrefix}:textToSpeech`);+ const params = resolveTextToSpeechParams(payload);+ const format = params.format ?? DEFAULT_TTS_AUDIO_FORMAT;+ const pricing = await getModelPricing(payload.model, context.provider, options?.pricingContext);+ const streamUsage = isTokenBilledTextToSpeech(pricing);++ log(+ 'textToSpeech called with input length: %d, voice: %s, format: %s, sse: %s',+ payload.input.length,+ payload.voice,+ format,+ streamUsage,+ );++ const body: SpeechCreateParams = {+ input: payload.input,+ model: context.requestModel,+ response_format: format,+ voice: payload.voice,+ ...(params.speed !== undefined && { speed: params.speed }),+ ...(params.instructions && { instructions: params.instructions }),+ ...(streamUsage && { stream_format: 'sse' as const }),+ };++ let result: SpeechEventStreamResult;+ try {+ const response = await client.audio.speech.create(body, {+ headers: options?.headers,+ signal: options?.signal,+ });++ // OpenAI-compatible gateways may ignore `stream_format` and answer with raw audio.+ result = isEventStream(response)+ ? await readSpeechEventStream(response)+ : { audio: await response.arrayBuffer() };+ } catch (error) {+ throw context.handleError(error);+ }++ log('generated audio with size: %d bytes', result.audio.byteLength);++ const usage = convertTextToSpeechUsage(payload.input, pricing, result.tokenUsage);+ await options?.onUsage?.(usage);++ return { audio: result.audio, format, usage };+};diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.tsindex 694f983b04d..9e41d4033e1 100644--- a/packages/model-runtime/src/core/usageConverters/index.ts+++ b/packages/model-runtime/src/core/usageConverters/index.ts@@ -5,6 +5,12 @@ export {convertOpenAITranscriptionUsage,convertOpenAIUsage,} from './openai';+export {+ convertOpenAISpeechTokenUsage,+ convertTextToSpeechUsage,+ countTextToSpeechCharacters,+ isTokenBilledTextToSpeech,+} from './tts';export {computeChatCost,type ComputeChatCostOptions,diff --git a/packages/model-runtime/src/core/usageConverters/tts.test.ts b/packages/model-runtime/src/core/usageConverters/tts.test.tsnew file mode 100644index 00000000000..64b6c4d093c--- /dev/null+++ b/packages/model-runtime/src/core/usageConverters/tts.test.ts@@ -0,0 +1,89 @@+import type { Pricing } from 'model-bank';+import openaiModels from 'model-bank/openai';+import { describe, expect, it } from 'vitest';++import {+ convertOpenAISpeechTokenUsage,+ convertTextToSpeechUsage,+ countTextToSpeechCharacters,+ isTokenBilledTextToSpeech,+} from './tts';++const pricingOf = (id: string) =>+ openaiModels.find((model: { id: string }) => model.id === id)?.pricing as Pricing;++describe('countTextToSpeechCharacters', () => {+ it('counts code points so CJK characters and emoji are one character each', () => {+ expect(countTextToSpeechCharacters('hello')).toBe(5);+ expect(countTextToSpeechCharacters('你好,世界')).toBe(5);+ expect(countTextToSpeechCharacters('hi 👋')).toBe(4);+ });+});++describe('isTokenBilledTextToSpeech', () => {+ it('tells token-billed from character-billed pricing', () => {+ expect(isTokenBilledTextToSpeech(pricingOf('tts-1'))).toBe(false);+ expect(isTokenBilledTextToSpeech(pricingOf('gpt-4o-mini-tts'))).toBe(true);+ expect(isTokenBilledTextToSpeech(undefined)).toBe(false);+ });+});++describe('convertTextToSpeechUsage', () => {+ it('prices tts-1 by input characters ($15 / 1M characters)', () => {+ const input = 'a'.repeat(1000);++ expect(convertTextToSpeechUsage(input, pricingOf('tts-1'))).toEqual({+ cost: 0.015,+ inputCharacters: 1000,+ });+ });++ it('prices tts-1-hd at its own rate ($30 / 1M characters)', () => {+ expect(convertTextToSpeechUsage('你'.repeat(1000), pricingOf('tts-1-hd'))).toEqual({+ cost: 0.03,+ inputCharacters: 1000,+ });+ });++ it('prices gpt-4o-mini-tts by reported text input and audio output tokens', () => {+ const tokenUsage = convertOpenAISpeechTokenUsage({+ input_tokens: 1000,+ output_tokens: 10_000,+ total_tokens: 11_000,+ });++ // 1000 × $0.6/1M + 10000 × $12/1M = $0.0006 + $0.12+ expect(convertTextToSpeechUsage('hello', pricingOf('gpt-4o-mini-tts'), tokenUsage)).toEqual({+ cost: 0.1206,+ inputCharacters: 5,+ inputTextTokens: 1000,+ outputAudioTokens: 10_000,+ totalInputTokens: 1000,+ totalOutputTokens: 10_000,+ totalTokens: 11_000,+ });+ });++ it('leaves cost unset for a token-billed model without reported tokens', () => {+ expect(convertTextToSpeechUsage('hello', pricingOf('gpt-4o-mini-tts'))).toEqual({+ inputCharacters: 5,+ });+ });++ it('reports characters without cost when the model has no pricing', () => {+ expect(convertTextToSpeechUsage('hello')).toEqual({ inputCharacters: 5 });+ });+});++describe('convertOpenAISpeechTokenUsage', () => {+ it('derives totalTokens when the provider omits it', () => {+ expect(convertOpenAISpeechTokenUsage({ input_tokens: 3, output_tokens: 7 })).toMatchObject({+ totalTokens: 10,+ });+ });++ it('returns undefined for missing or partial usage', () => {+ expect(convertOpenAISpeechTokenUsage(undefined)).toBeUndefined();+ expect(convertOpenAISpeechTokenUsage({ input_tokens: 3 })).toBeUndefined();+ });+});diff --git a/packages/model-runtime/src/core/usageConverters/tts.ts b/packages/model-runtime/src/core/usageConverters/tts.tsnew file mode 100644index 00000000000..3a3041c6afb--- /dev/null+++ b/packages/model-runtime/src/core/usageConverters/tts.ts@@ -0,0 +1,70 @@+import type { ModelTokensUsage, ModelUsage } from '@lobechat/types';+import debug from 'debug';+import type { Pricing } from 'model-bank';++import { withUsageCost } from './utils/withUsageCost';++const log = debug('lobe-cost:convertTextToSpeechUsage');++/**+ * Characters billed for a TTS input. Counts Unicode code points, so a CJK character or+ * an emoji is one character, matching how OpenAI meters `millionCharacters` models.+ */+export const countTextToSpeechCharacters = (input: string) => [...input].length;++/**+ * Whether the model is billed per token (e.g. `gpt-4o-mini-tts`) rather than per input+ * character (e.g. `tts-1`). Token-billed models need provider-reported token usage.+ */+export const isTokenBilledTextToSpeech = (pricing?: Pricing) =>+ !!pricing?.units.some((unit) => unit.unit === 'millionTokens');++/**+ * Build the usage of one synthesis. `inputCharacters` is always reported, counted locally+ * unless the provider reports its own billed count; provider token usage is merged in when+ * available. Cost follows the same `computeChatCost` rules as chat: `millionCharacters`+ * units bill `inputCharacters`, `millionTokens` units bill tokens.+ */+export const convertTextToSpeechUsage = (+ input: string,+ pricing?: Pricing,+ tokenUsage?: ModelTokensUsage,+): ModelUsage => {+ const data: ModelTokensUsage = {+ inputCharacters: countTextToSpeechCharacters(input),+ ...tokenUsage,+ };++ log('convertTextToSpeechUsage data: %O', data);++ // Without provider token counts a token-billed model would price to 0; leave `cost`+ // unset so billing consumers settle from their own estimate instead.+ if (isTokenBilledTextToSpeech(pricing) && !tokenUsage) return data;++ return withUsageCost(data, pricing);+};++/**+ * `usage` of the `speech.audio.done` SSE event of `POST /audio/speech`. Input tokens are+ * the text prompt (input + instructions); output tokens are the generated audio.+ */+interface OpenAISpeechTokenUsage {+ input_tokens?: number;+ output_tokens?: number;+ total_tokens?: number;+}++export const convertOpenAISpeechTokenUsage = (usage: unknown): ModelTokensUsage | undefined => {+ if (!usage || typeof usage !== 'object') return;++ const { input_tokens, output_tokens, total_tokens } = usage as OpenAISpeechTokenUsage;+ if (typeof input_tokens !== 'number' || typeof output_tokens !== 'number') return;++ return {+ inputTextTokens: input_tokens,+ outputAudioTokens: output_tokens,+ totalInputTokens: input_tokens,+ totalOutputTokens: output_tokens,+ totalTokens: total_tokens ?? input_tokens + output_tokens,+ };+};diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.millionCharacters.test.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.millionCharacters.test.tsnew file mode 100644index 00000000000..888c43bc63d--- /dev/null+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.millionCharacters.test.ts@@ -0,0 +1,60 @@+import type { Pricing } from 'model-bank';+import { describe, expect, it } from 'vitest';++import { computeChatCost } from './computeChatCost';++describe('computeChatCost with millionCharacters units', () => {+ it('bills textInput by inputCharacters for a fixed character rate', () => {+ const pricing: Pricing = {+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],+ };++ const result = computeChatCost(pricing, { inputCharacters: 2000 });++ expect(result?.breakdown).toHaveLength(1);+ expect(result?.breakdown[0]).toMatchObject({ quantity: 2000 });+ expect(result?.totalCost).toBe(0.03);+ });++ it('ignores token counts for character-billed units', () => {+ const pricing: Pricing = {+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],+ };++ const result = computeChatCost(pricing, { inputTextTokens: 5000, totalInputTokens: 5000 });++ expect(result?.breakdown).toHaveLength(0);+ expect(result?.totalCost).toBe(0);+ });++ it('converts CNY character rates to USD', () => {+ const pricing: Pricing = {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 2, strategy: 'fixed', unit: 'millionCharacters' }],+ };++ // 1M chars × ¥2 = ¥2 = $1 at a 2:1 rate+ const result = computeChatCost(pricing, { inputCharacters: 1_000_000 }, { usdToCnyRate: 2 });++ expect(result?.totalCost).toBe(1);+ });++ it('supports tiered character pricing', () => {+ const pricing: Pricing = {+ units: [+ {+ name: 'textInput',+ strategy: 'tiered',+ tiers: [+ { rate: 10, upTo: 1000 },+ { rate: 20, upTo: 'infinity' },+ ],+ unit: 'millionCharacters',+ },+ ],+ };++ expect(computeChatCost(pricing, { inputCharacters: 500 })?.totalCredits).toBe(5000);+ expect(computeChatCost(pricing, { inputCharacters: 2000 })?.totalCredits).toBe(40_000);+ });+});diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.tsindex 13768cdf8db..548986318e2 100644--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts@@ -1,4 +1,3 @@-import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '../../../const/currency';import type { ModelTokensUsage } from '@lobechat/types';import debug from 'debug';import type {@@ -10,6 +9,7 @@ import type {TieredPricingUnit,} from 'model-bank';+import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '../../../const/currency';import { DEFAULT_CACHE_TTL } from '../../anthropicCompatibleFactory/resolveCacheTTL';const log = debug('lobe-cost:computeChatPricing');@@ -382,6 +382,11 @@ const resolveQuantity = (usage: ModelTokensUsage,context: UnitQuantityResolverContext,) => {+ // Character-billed units (e.g. TTS) count input characters instead of tokens.+ if (unit.unit === 'millionCharacters') {+ return unit.name === 'textInput' ? usage.inputCharacters : undefined;+ }+const resolver = UNIT_QUANTITY_RESOLVERS[unit.name as PricingUnitName];const quantity = resolver?.(usage, context);return typeof quantity === 'number' ? quantity : undefined;@@ -433,7 +438,7 @@ export const computeChatCost = (if (quantity === undefined) continue;if (unit.strategy === 'fixed') {- if (unit.unit !== 'millionTokens')+ if (unit.unit !== 'millionTokens' && unit.unit !== 'millionCharacters')throw new Error(`Unsupported chat pricing unit: ${unit.unit}`);const fixedUnit = unit as FixedPricingUnit;diff --git a/packages/model-runtime/src/providers/minimax/createSpeech.test.ts b/packages/model-runtime/src/providers/minimax/createSpeech.test.tsnew file mode 100644index 00000000000..11376a9024c--- /dev/null+++ b/packages/model-runtime/src/providers/minimax/createSpeech.test.ts@@ -0,0 +1,380 @@+// @vitest-environment node+import { AgentRuntimeErrorType } from '@lobechat/types';+import type { Pricing } from 'model-bank';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { USD_TO_CNY } from '../../const/currency';+import { getModelPricing } from '../../utils/getModelPricing';+import {+ buildMiniMaxSpeechRequest,+ countMiniMaxSpeechCharacters,+ createMiniMaxSpeech,+ decodeMiniMaxHexAudio,+ getMiniMaxSpeechErrorType,+ LobeMinimaxSpeechAI,+ type MiniMaxSpeechOptions,+} from './createSpeech';+import { LobeMinimaxAI } from './index';++vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));++const hdPricing: Pricing = {+ currency: 'CNY',+ units: [{ name: 'textInput', rate: 350, strategy: 'fixed', unit: 'millionCharacters' }],+};++const options: MiniMaxSpeechOptions = {+ apiKey: 'test-key',+ baseURL: 'https://api.minimaxi.com/v1',+ provider: 'minimax',+};++const okResponse = (overrides: Record<string, unknown> = {}) =>+ new Response(+ JSON.stringify({+ base_resp: { status_code: 0, status_msg: 'success' },+ data: { audio: '49443303', status: 2 },+ extra_info: { audio_format: 'mp3', audio_length: 1200, usage_characters: 12 },+ trace_id: 'trace-1',+ ...overrides,+ }),+ { headers: { 'content-type': 'application/json' } },+ );++describe('createMiniMaxSpeech', () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ vi.mocked(getModelPricing).mockResolvedValue(hdPricing);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ });++ describe('parameter mapping', () => {+ it('maps the standard params onto voice_setting and audio_setting', () => {+ const { body, format } = buildMiniMaxSpeechRequest(+ {+ input: '你好,世界',+ model: 'speech-2.8-hd',+ params: {+ emotion: 'happy',+ format: 'wav',+ pitch: -3,+ sampleRate: 24_000,+ speed: 1.2,+ volume: 2,+ },+ voice: 'female-shaonv',+ },+ 'speech-2.8-hd',+ );++ expect(format).toBe('wav');+ expect(body).toEqual({+ audio_setting: { channel: 1, format: 'wav', sample_rate: 24_000 },+ model: 'speech-2.8-hd',+ output_format: 'hex',+ stream: false,+ text: '你好,世界',+ voice_setting: {+ emotion: 'happy',+ pitch: -3,+ speed: 1.2,+ vol: 2,+ voice_id: 'female-shaonv',+ },+ });+ });++ it('omits unset params so MiniMax applies its defaults, and reads the legacy speed', () => {+ const { body, format } = buildMiniMaxSpeechRequest(+ { input: 'hi', model: 'speech-2.8-turbo', speed: 0.8, voice: 'female-yujie' },+ 'speech-2.8-turbo',+ );++ expect(format).toBe('mp3');+ expect(body.audio_setting).toEqual({ channel: 1, format: 'mp3' });+ expect(body.voice_setting).toEqual({ speed: 0.8, voice_id: 'female-yujie' });+ });++ it('rejects formats t2a_v2 cannot produce', async () => {+ await expect(+ createMiniMaxSpeech(+ { input: 'hi', model: 'speech-2.8-hd', params: { format: 'aac' }, voice: 'x' },+ options,+ ),+ ).rejects.toMatchObject({+ error: { message: 'MiniMax speech does not support the "aac" format' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider: 'minimax',+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('posts to /t2a_v2 with the mapped model id, auth header and abort signal', async () => {+ fetchMock.mockResolvedValue(okResponse());+ const controller = new AbortController();++ await createMiniMaxSpeech(+ { input: '你好', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ {+ ...options,+ headers: { 'X-Trace': '1' },+ modelIdMapping: { 'speech-2.8-hd': 'speech-2.8-hd-upstream' },+ signal: controller.signal,+ },+ );++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://api.minimaxi.com/v1/t2a_v2');+ expect(init.method).toBe('POST');+ expect(init.signal).toBe(controller.signal);+ expect(init.headers).toMatchObject({+ 'Authorization': 'Bearer test-key',+ 'Content-Type': 'application/json',+ 'X-Trace': '1',+ });+ expect(JSON.parse(init.body).model).toBe('speech-2.8-hd-upstream');+ });+ });++ describe('hex decoding', () => {+ it('decodes the hex audio into bytes', () => {+ expect(new Uint8Array(decodeMiniMaxHexAudio('494433ff00'))).toEqual(+ new Uint8Array([0x49, 0x44, 0x33, 0xff, 0x00]),+ );+ });++ it.each([[undefined], [''], ['abc'], ['zz11']])('rejects invalid hex %j', (hex) => {+ expect(() => decodeMiniMaxHexAudio(hex)).toThrow('MiniMax returned no valid hex audio');+ });++ it('returns the decoded audio with the requested format', async () => {+ fetchMock.mockResolvedValue(okResponse());++ const result = await createMiniMaxSpeech(+ { input: '你好', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ options,+ );++ expect(new Uint8Array(result.audio)).toEqual(new Uint8Array([0x49, 0x44, 0x33, 0x03]));+ expect(result.format).toBe('mp3');+ });++ it('fails a successful status without audio instead of returning empty bytes', async () => {+ fetchMock.mockResolvedValue(okResponse({ data: null }));+ const onUsage = vi.fn();++ await expect(+ createMiniMaxSpeech(+ { input: '你好', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ { ...options, onUsage },+ ),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBizError });+ expect(onUsage).not.toHaveBeenCalled();+ });+ });++ describe('usage', () => {+ it('bills extra_info.usage_characters and prices it in CNY', async () => {+ fetchMock.mockResolvedValue(okResponse());+ const onUsage = vi.fn();++ const result = await createMiniMaxSpeech(+ { input: '你好', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ { ...options, onUsage, pricingContext: { channelId: 'c1' } as any },+ );++ // The provider-billed count (12) wins over the local count (2).+ expect(result.usage?.inputCharacters).toBe(12);+ expect(result.usage?.cost).toBeGreaterThan(0);+ expect(onUsage).toHaveBeenCalledWith(result.usage);+ expect(getModelPricing).toHaveBeenCalledWith('speech-2.8-hd', 'minimax', {+ channelId: 'c1',+ });+ });++ it('prices 10k billed characters at ¥3.5 for HD', async () => {+ fetchMock.mockResolvedValue(okResponse({ extra_info: { usage_characters: 10_000 } }));++ const result = await createMiniMaxSpeech(+ { input: 'x', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ options,+ );++ // Cost is reported in USD: ¥350 per 1M characters → ¥3.5 for 10k.+ expect(result.usage?.inputCharacters).toBe(10_000);+ expect(result.usage?.cost).toBeCloseTo(3.5 / USD_TO_CNY, 4);+ });++ it('falls back to MiniMax billing rules when usage_characters is missing', async () => {+ fetchMock.mockResolvedValue(okResponse({ extra_info: {} }));++ const result = await createMiniMaxSpeech(+ { input: '你好, hi😀', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ options,+ );++ // 2 Chinese characters × 2 + ", hi😀" (5 code points) × 1+ expect(result.usage?.inputCharacters).toBe(9);+ });++ it('counts Chinese characters twice', () => {+ expect(countMiniMaxSpeechCharacters('你好')).toBe(4);+ expect(countMiniMaxSpeechCharacters('hello, world')).toBe(12);+ expect(countMiniMaxSpeechCharacters('')).toBe(0);+ });+ });++ describe('error mapping', () => {+ it.each([+ [1004, AgentRuntimeErrorType.InvalidProviderAPIKey],+ [2049, AgentRuntimeErrorType.InvalidProviderAPIKey],+ [1002, AgentRuntimeErrorType.RateLimitExceeded],+ // 1039 is a token limit the request must be adjusted for, not a retryable rate limit+ [1039, AgentRuntimeErrorType.ProviderBizError],+ [1045, AgentRuntimeErrorType.RateLimitExceeded],+ [2045, AgentRuntimeErrorType.RateLimitExceeded],+ [2062, AgentRuntimeErrorType.RateLimitExceeded],+ [1008, AgentRuntimeErrorType.InsufficientQuota],+ [2053, AgentRuntimeErrorType.InsufficientQuota],+ [2056, AgentRuntimeErrorType.InsufficientQuota],+ [2067, AgentRuntimeErrorType.InsufficientQuota],+ [2013, AgentRuntimeErrorType.ProviderBizError],+ [1000, AgentRuntimeErrorType.ProviderBizError],+ ])('maps status_code %d to %s', async (statusCode, errorType) => {+ expect(getMiniMaxSpeechErrorType(statusCode)).toBe(errorType);++ fetchMock.mockResolvedValue(+ okResponse({ base_resp: { status_code: statusCode, status_msg: 'boom' }, data: null }),+ );++ await expect(+ createMiniMaxSpeech(+ { input: '你好', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ options,+ ),+ ).rejects.toEqual({+ error: {+ base_resp: { status_code: statusCode, status_msg: 'boom' },+ message: 'MiniMax API error: boom',+ trace_id: 'trace-1',+ },+ errorType,+ provider: 'minimax',+ });+ });++ it('maps HTTP failures by status', async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ base_resp: { status_code: 1004, status_msg: 'bad key' } }), {+ status: 401,+ statusText: 'Unauthorized',+ }),+ );++ await expect(+ createMiniMaxSpeech(+ { input: '你好', model: 'speech-2.8-hd', voice: 'female-shaonv' },+ options,+ ),+ ).rejects.toMatchObject({+ error: { message: 'MiniMax API error (401): bad key', status: 401 },+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,+ });+ });++ it('wraps network failures as provider errors and passes aborts through', async () => {+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'));+ await expect(+ createMiniMaxSpeech({ input: 'a', model: 'speech-2.8-hd', voice: 'v' }, options),+ ).rejects.toMatchObject({+ error: { message: 'fetch failed' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ });++ const abort = Object.assign(new Error('aborted'), { name: 'AbortError' });+ fetchMock.mockRejectedValueOnce(abort);+ await expect(+ createMiniMaxSpeech({ input: 'a', model: 'speech-2.8-hd', voice: 'v' }, options),+ ).rejects.toBe(abort);+ });+ });++ describe('LobeMinimaxAI routing', () => {+ it.each([+ ['default base URL', {}, 'https://api.minimaxi.com/v1/t2a_v2'],+ [+ 'global Anthropic base URL',+ { baseURL: 'https://api.minimax.io/anthropic' },+ 'https://api.minimax.io/v1/t2a_v2',+ ],+ [+ 'Anthropic SDK type and /v1/messages URL',+ { baseURL: 'https://api.minimax.io/anthropic/v1/messages', sdkType: 'anthropic' },+ 'https://api.minimax.io/v1/t2a_v2',+ ],+ [+ 'China Anthropic base URL',+ { baseURL: 'https://api.minimaxi.com/anthropic' },+ 'https://api.minimaxi.com/v1/t2a_v2',+ ],+ ])('sends speech models to t2a_v2 with the %s', async (_name, runtimeOptions, expectedURL) => {+ fetchMock.mockResolvedValue(okResponse());+ const runtime = new LobeMinimaxAI({ apiKey: 'test-key', ...runtimeOptions });++ const result = await runtime.textToSpeech!({+ input: '你好',+ model: 'speech-2.8-hd',+ params: { emotion: 'calm' },+ voice: 'female-shaonv',+ });++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(expectedURL);+ expect(JSON.parse(init.body).voice_setting).toEqual({+ emotion: 'calm',+ voice_id: 'female-shaonv',+ });+ expect(result.usage?.inputCharacters).toBe(12);+ });++ it('routes an alias mapped onto a speech model to t2a_v2', async () => {+ fetchMock.mockResolvedValue(okResponse());+ const runtime = new LobeMinimaxAI({+ apiKey: 'test-key',+ baseURL: 'https://api.minimax.io/anthropic',+ modelIdMapping: { 'voice-prod': 'speech-2.8-hd' },+ } as any);++ await runtime.textToSpeech!({ input: 'hi', model: 'voice-prod', voice: 'female-yujie' });++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://api.minimax.io/v1/t2a_v2');+ expect(JSON.parse(init.body).model).toBe('speech-2.8-hd');+ });++ it('requires an API key', () => {+ expect(+ () => new LobeMinimaxSpeechAI({ baseURL: 'https://api.minimaxi.com/v1', id: 'minimax' }),+ ).toThrow();+ });++ it('keeps a custom OpenAI-style base URL without doubling its trailing slash', async () => {+ fetchMock.mockResolvedValue(okResponse());+ const runtime = new LobeMinimaxAI({+ apiKey: 'test-key',+ baseURL: 'https://api.minimax.io/v1/',+ });++ await runtime.textToSpeech!({ input: 'hi', model: 'speech-02-turbo', voice: 'female-yujie' });++ expect(fetchMock.mock.calls[0][0]).toBe('https://api.minimax.io/v1/t2a_v2');+ });+ });+});diff --git a/packages/model-runtime/src/providers/minimax/createSpeech.ts b/packages/model-runtime/src/providers/minimax/createSpeech.tsnew file mode 100644index 00000000000..306092812b7--- /dev/null+++ b/packages/model-runtime/src/providers/minimax/createSpeech.ts@@ -0,0 +1,311 @@+import { AgentRuntimeErrorType } from '@lobechat/types';+import createDebug from 'debug';+import type { TTSAudioFormat } from 'model-bank';+import { DEFAULT_TTS_AUDIO_FORMAT } from 'model-bank';++import type { LobeRuntimeAI } from '../../core/BaseAI';+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 type { ModelIdMappingOptions } from '../../utils/modelIdMapping';+import { resolveMappedModelId } from '../../utils/modelIdMapping';++const log = createDebug('lobe-tts:minimax');++export interface MiniMaxSpeechOptions extends ModelIdMappingOptions, TextToSpeechOptions {+ apiKey: string;+ /** OpenAI-style API root, e.g. `https://api.minimaxi.com/v1`. */+ baseURL: string;+ /** Provider id used for pricing lookup and error payloads. */+ provider: string;+}++/** Formats t2a_v2 returns for the standard TTS formats; MiniMax has no `aac` output. */+const MINIMAX_AUDIO_FORMATS: Partial<Record<TTSAudioFormat, string>> = {+ flac: 'flac',+ mp3: 'mp3',+ opus: 'opus',+ pcm: 'pcm',+ wav: 'wav',+};++const HEX_PATTERN = /^(?:[\da-f]{2})+$/i;++const HAN_PATTERN = /\p{Script=Han}/u;++/**+ * Billed characters when MiniMax omits `usage_characters`: a Chinese character counts+ * as 2, every other character (letters, punctuation, spaces, emoji) as 1.+ * @see https://platform.minimaxi.com/docs/guides/pricing-paygo+ */+export const countMiniMaxSpeechCharacters = (input: string) =>+ [...input].reduce((count, char) => count + (HAN_PATTERN.test(char) ? 2 : 1), 0);++/**+ * `base_resp.status_code` values that map onto a specific runtime error type; everything+ * else is a provider business error.+ * @see https://platform.minimaxi.com/docs/api-reference/errorcode+ */+const MINIMAX_ERROR_TYPES: Record<number, ILobeAgentRuntimeErrorType> = {+ 1002: AgentRuntimeErrorType.RateLimitExceeded, // rate limit+ 1004: AgentRuntimeErrorType.InvalidProviderAPIKey, // not authorized+ 1008: AgentRuntimeErrorType.InsufficientQuota, // insufficient balance+ 1045: AgentRuntimeErrorType.RateLimitExceeded, // task concurrency limit+ 2045: AgentRuntimeErrorType.RateLimitExceeded, // rate growth limit+ 2049: AgentRuntimeErrorType.InvalidProviderAPIKey, // invalid API key+ 2053: AgentRuntimeErrorType.InsufficientQuota, // insufficient credit+ 2056: AgentRuntimeErrorType.InsufficientQuota, // usage limit exceeded+ 2062: AgentRuntimeErrorType.RateLimitExceeded, // M Plan rate limit+ 2067: AgentRuntimeErrorType.InsufficientQuota, // usage limit reached, auto credit off+};++const HTTP_ERROR_TYPES: Record<number, ILobeAgentRuntimeErrorType> = {+ 401: AgentRuntimeErrorType.InvalidProviderAPIKey,+ 403: AgentRuntimeErrorType.PermissionDenied,+ 429: AgentRuntimeErrorType.RateLimitExceeded,+};++interface MiniMaxBaseResp {+ status_code: number;+ status_msg?: string;+}++interface MiniMaxSpeechResponse {+ base_resp?: MiniMaxBaseResp;+ data?: {+ audio?: string;+ status?: number;+ } | null;+ extra_info?: {+ audio_format?: string;+ audio_length?: number;+ audio_size?: number;+ usage_characters?: number;+ };+ trace_id?: string;+}++/** Thrown inside the request flow and unwrapped into a runtime error payload. */+class MiniMaxSpeechError extends Error {+ constructor(+ message: string,+ readonly errorType: ILobeAgentRuntimeErrorType,+ readonly detail?: Record<string, unknown>,+ ) {+ super(message);+ }+}++export const getMiniMaxSpeechErrorType = (statusCode: number): ILobeAgentRuntimeErrorType =>+ MINIMAX_ERROR_TYPES[statusCode] ?? AgentRuntimeErrorType.ProviderBizError;++/**+ * Decode the hex-encoded audio returned by t2a_v2 (`output_format: 'hex'`).+ */+export const decodeMiniMaxHexAudio = (hex: unknown): ArrayBuffer => {+ if (typeof hex !== 'string' || !HEX_PATTERN.test(hex)) {+ throw new MiniMaxSpeechError(+ 'MiniMax returned no valid hex audio',+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ const buffer = Buffer.from(hex, 'hex');++ return buffer.buffer.slice(+ buffer.byteOffset,+ buffer.byteOffset + buffer.byteLength,+ ) as ArrayBuffer;+};++/**+ * Map the standard TTS payload onto a t2a_v2 request body. Params the caller did not set+ * are omitted so MiniMax applies its own defaults (e.g. automatic emotion).+ */+export const buildMiniMaxSpeechRequest = (+ payload: TextToSpeechPayload,+ requestModel: string,+): { body: Record<string, unknown>; format: TTSAudioFormat } => {+ const params = resolveTextToSpeechParams(payload);+ const format = params.format ?? DEFAULT_TTS_AUDIO_FORMAT;+ const minimaxFormat = MINIMAX_AUDIO_FORMATS[format];++ if (!minimaxFormat) {+ throw new MiniMaxSpeechError(+ `MiniMax speech does not support the "${format}" format`,+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ return {+ body: {+ audio_setting: {+ channel: 1,+ format: minimaxFormat,+ ...(params.sampleRate !== undefined && { sample_rate: params.sampleRate }),+ },+ model: requestModel,+ output_format: 'hex',+ stream: false,+ text: payload.input,+ voice_setting: {+ voice_id: payload.voice,+ ...(params.speed !== undefined && { speed: params.speed }),+ ...(params.volume !== undefined && { vol: params.volume }),+ ...(params.pitch !== undefined && { pitch: params.pitch }),+ ...(params.emotion && { emotion: params.emotion }),+ },+ },+ format,+ };+};++const readErrorBody = async (response: Response) => {+ try {+ return (await response.json()) as MiniMaxSpeechResponse;+ } catch {+ return undefined;+ }+};++/**+ * Synthesize speech with MiniMax's native `POST /t2a_v2` (not the OpenAI-style+ * `/audio/speech`). Usage is the billed `extra_info.usage_characters`.+ * @see https://platform.minimaxi.com/docs/api-reference/speech-t2a-http+ */+export async function createMiniMaxSpeech(+ payload: TextToSpeechPayload,+ options: MiniMaxSpeechOptions,+): Promise<TextToSpeechResponse> {+ const { apiKey, baseURL, provider } = options;+ const requestModel = resolveMappedModelId(payload.model, options);++ let result: TextToSpeechResponse;+ try {+ const { body, format } = buildMiniMaxSpeechRequest(payload, requestModel);+ const pricing = await getModelPricing(payload.model, provider, options.pricingContext);++ log('t2a_v2 request: model=%s voice=%s format=%s', requestModel, payload.voice, format);++ const response = await fetch(`${baseURL.replace(/\/+$/, '')}/t2a_v2`, {+ body: JSON.stringify(body),+ headers: {+ ...options.headers,+ 'Authorization': `Bearer ${apiKey}`,+ 'Content-Type': 'application/json',+ },+ method: 'POST',+ signal: options.signal,+ });++ if (!response.ok) {+ const errorBody = await readErrorBody(response);+ const statusCode = errorBody?.base_resp?.status_code;++ throw new MiniMaxSpeechError(+ `MiniMax API error (${response.status}): ${errorBody?.base_resp?.status_msg || response.statusText}`,+ HTTP_ERROR_TYPES[response.status] ??+ (statusCode ? getMiniMaxSpeechErrorType(statusCode) : undefined) ??+ AgentRuntimeErrorType.ProviderBizError,+ { base_resp: errorBody?.base_resp, status: response.status },+ );+ }++ const data = (await response.json()) as MiniMaxSpeechResponse;+ const baseResp = data.base_resp;++ if (baseResp && baseResp.status_code !== 0) {+ throw new MiniMaxSpeechError(+ `MiniMax API error: ${baseResp.status_msg || baseResp.status_code}`,+ getMiniMaxSpeechErrorType(baseResp.status_code),+ { base_resp: baseResp, trace_id: data.trace_id },+ );+ }++ const audio = decodeMiniMaxHexAudio(data.data?.audio);+ const usageCharacters = data.extra_info?.usage_characters;++ log(+ 't2a_v2 done: %d bytes, %d ms, usage_characters=%s, trace_id=%s',+ audio.byteLength,+ data.extra_info?.audio_length,+ usageCharacters,+ data.trace_id,+ );++ const usage = convertTextToSpeechUsage(payload.input, pricing, {+ inputCharacters:+ typeof usageCharacters === 'number'+ ? usageCharacters+ : countMiniMaxSpeechCharacters(payload.input),+ });++ result = { audio, format, usage };+ } catch (error) {+ log('createMiniMaxSpeech error: %O', error);++ if ((error as Error)?.name === 'AbortError') throw error;++ const errorType =+ error instanceof MiniMaxSpeechError+ ? error.errorType+ : AgentRuntimeErrorType.ProviderBizError;++ throw AgentRuntimeError.chat({+ error: {+ message: (error as Error)?.message ?? String(error),+ ...(error instanceof MiniMaxSpeechError ? error.detail : undefined),+ },+ errorType,+ provider,+ } satisfies ChatCompletionErrorPayload);+ }++ await options.onUsage?.(result.usage!);++ return result;+}++/**+ * Speech-only runtime the MiniMax router uses for `speech-*` models, so synthesis never+ * goes through the OpenAI-compatible `/audio/speech` or the Anthropic-compatible runtime.+ */+export class LobeMinimaxSpeechAI implements LobeRuntimeAI {+ baseURL: string;+ private apiKey: string;+ private id: string;+ private modelIdMapping?: ModelIdMappingOptions['modelIdMapping'];++ constructor({+ apiKey,+ baseURL,+ id,+ modelIdMapping,+ }: ModelIdMappingOptions & { apiKey?: string; baseURL: string; id: string }) {+ if (!apiKey?.trim())+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);++ this.apiKey = apiKey.trim();+ this.baseURL = baseURL;+ this.id = id;+ this.modelIdMapping = modelIdMapping;+ }++ textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {+ return createMiniMaxSpeech(payload, {+ ...options,+ apiKey: this.apiKey,+ baseURL: this.baseURL,+ modelIdMapping: this.modelIdMapping,+ provider: this.id,+ });+ }+}diff --git a/packages/model-runtime/src/providers/minimax/index.ts b/packages/model-runtime/src/providers/minimax/index.tsindex 1228a0f7d77..ad74420fe22 100644--- a/packages/model-runtime/src/providers/minimax/index.ts+++ b/packages/model-runtime/src/providers/minimax/index.ts@@ -13,9 +13,11 @@ import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';import { createRouterRuntime } from '../../core/RouterRuntime';import type { ChatStreamPayload, OpenAIChatMessage } from '../../types';import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';+import { resolveMappedModelId } from '../../utils/modelIdMapping';import { resolveSafeMaxTokens } from '../../utils/resolveSafeMaxTokens';import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';import { createMiniMaxImage } from './createImage';+import { LobeMinimaxSpeechAI } from './createSpeech';import { createMiniMaxVideo } from './createVideo';const DEFAULT_MINIMAX_BASE_URL = 'https://api.minimaxi.com/v1';@@ -24,6 +26,9 @@ const MINIMAX_ANTHROPIC_BASE_URL_PATTERN = /\/anthropic\/?$/;const MINIMAX_ANTHROPIC_MODEL_BASE_URL_PATTERN = /\/anthropic(?:\/v1\/messages)?\/?$/;const MINIMAX_ANTHROPIC_MESSAGES_PATH_PATTERN = /\/v1\/messages\/?$/;+// All MiniMax speech models (`speech-2.8-hd`, `speech-02-turbo`, ...) share the t2a_v2 API.+const MINIMAX_SPEECH_MODEL_PATTERN = /^speech-/i;+const isMiniMaxM3Model = (model: string) => model.toLowerCase() === 'minimax-m3';// M3.1 Flash always thinks: it rejects disabled thinking and takes `reasoning_effort` instead.const isMiniMaxM3FlashModel = (model: string) => model.toLowerCase() === 'minimax-m3.1-flash';@@ -436,10 +441,41 @@ const createOpenAIRouter = () => ({runtime: LobeMinimaxOpenAI,});+// Speech uses the OpenAI-style `/v1` root on the configured host: global (`api.minimax.io`)+// and China (`api.minimaxi.com`) keys only work on their own region's endpoint.+const normalizeMiniMaxSpeechBaseURL = (baseURL?: string | null) =>+ baseURL+ ? baseURL+ .replace(MINIMAX_ANTHROPIC_MODEL_BASE_URL_PATTERN, '/v1')+ .replace(MINIMAX_ANTHROPIC_MESSAGES_PATH_PATTERN, '/v1')+ : DEFAULT_MINIMAX_BASE_URL;++// Speech always goes to the native t2a_v2 API, whatever SDK type serves chat; the+// Anthropic-compatible runtime has no speech support.+const createSpeechRouter = (baseURL?: string | null) => ({+ apiType: 'openai' as const,+ id: 'speech',+ options: {+ baseURL: normalizeMiniMaxSpeechBaseURL(baseURL),+ remark: 'speech',+ },+ runtime: LobeMinimaxSpeechAI,+});+export const params: CreateRouterRuntimeOptions = {id: ModelProvider.Minimax,models: fetchMiniMaxModelsWithOpenAI,- routers: (options) => {+ routers: (options, context) => {+ // Match the upstream id too, so an alias mapped onto `speech-*` still reaches t2a_v2.+ if (+ context?.model &&+ MINIMAX_SPEECH_MODEL_PATTERN.test(+ resolveMappedModelId(context.model, { modelIdMapping: options.modelIdMapping }),+ )+ ) {+ return [createSpeechRouter(options.baseURL)];+ }+const sdkType = resolveMiniMaxSDKType(options.sdkType);if (sdkType === 'anthropic') {diff --git a/packages/model-runtime/src/types/tts.ts b/packages/model-runtime/src/types/tts.tsindex a49b0046901..d1d0dd1df74 100644--- a/packages/model-runtime/src/types/tts.ts+++ b/packages/model-runtime/src/types/tts.ts@@ -1,15 +1,53 @@+import type { ModelUsage } from '@lobechat/types';+import type { RuntimeTTSParams, TTSAudioFormat } from 'model-bank';++import type { ModelPricingContext } from './pricing';+export interface TextToSpeechPayload {input: string;model: string;+ /**+ * Standard TTS parameters; see `TTSModelParamsMetaSchema` in model-bank for what each+ * model declares. Providers map them onto their own request shape.+ */+ params?: RuntimeTTSParams;+ /**+ * @deprecated Use `params.speed`. Still read when `params.speed` is absent.+ */speed?: number;voice: string;}export interface TextToSpeechOptions {headers?: Record<string, any>;+ /** Metadata passed to hooks (billing, tracing, route attempts), e.g. `trigger`. */+ metadata?: Record<string, unknown>;+ /**+ * Receives the synthesis usage (with `cost` when the model has pricing) after a+ * successful request.+ */+ onUsage?: (usage: ModelUsage) => void | Promise<void>;+ pricingContext?: ModelPricingContext;signal?: AbortSignal;/**- * userId for the embeddings+ * userId for the request*/user?: string;}++export interface TextToSpeechResponse {+ audio: ArrayBuffer;+ format: TTSAudioFormat;+ /** Same value reported through `options.onUsage`; undefined when unknown. */+ usage?: ModelUsage;+}++/**+ * Merge the legacy top-level `speed` into the standard params; `params.speed` wins.+ */+export const resolveTextToSpeechParams = (payload: TextToSpeechPayload): RuntimeTTSParams => {+ const params = { ...payload.params };+ if (params.speed === undefined && payload.speed !== undefined) params.speed = payload.speed;++ return params;+};diff --git a/packages/model-runtime/src/utils/getModelPricing.ts b/packages/model-runtime/src/utils/getModelPricing.tsindex a3effce9808..ef261f4a8ab 100644--- a/packages/model-runtime/src/utils/getModelPricing.ts+++ b/packages/model-runtime/src/utils/getModelPricing.ts@@ -2,6 +2,7 @@ import type {LobeDefaultAiModelListItem,ModelParamsSchema,Pricing,+ TTSModelParamsSchema,VideoModelParamsSchema,} from 'model-bank';@@ -57,7 +58,7 @@ export async function getModelParameters(model: string,provider?: string,pricingContext?: ModelPricingContext,-): Promise<ModelParamsSchema | VideoModelParamsSchema | undefined> {+): Promise<ModelParamsSchema | TTSModelParamsSchema | VideoModelParamsSchema | undefined> {const card = await findModelCard(model,provider,diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex 497a1b364c6..78b3b4970a8 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -3291,6 +3291,174 @@ paths:description: Internal server errortags:- api-keys+ /api/v1/audio/speech:+ post:+ operationId: postApiV1AudioSpeech+ description: "OpenAI-compatible text-to-speech. Point an OpenAI SDK at `/api/v1`+ and call `audio.speech.create`. `model` takes `provider/model` (for+ example `lobehub/speech-2.8-hd`) or a bare model id; the optional+ `provider` and `params` (emotion, pitch, volume, sampleRate) are LobeHub+ extensions. Returns the audio bytes; usage is reported in `X-LobeHub-*`+ headers. Synthesis errors use OpenAI's `{ error: { message, type, code,+ param } }` body; authentication and permission errors use the platform+ `ApiError` envelope."+ responses:+ "200":+ content:+ audio/aac:+ schema:+ format: binary+ type: string+ audio/mpeg:+ schema:+ format: binary+ type: string+ audio/opus:+ schema:+ format: binary+ type: string+ description: Synthesized audio+ "400":+ content:+ application/json:+ schema:+ properties:+ error:+ properties:+ code:+ type:+ - string+ - "null"+ message:+ type: string+ param:+ type:+ - string+ - "null"+ type:+ type: string+ required:+ - message+ - type+ type: object+ required:+ - error+ type: object+ description: Invalid request, unsupported format or invalid params+ "401":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Authentication required+ "402":+ content:+ application/json:+ schema:+ properties:+ error:+ properties:+ code:+ type:+ - string+ - "null"+ message:+ type: string+ param:+ type:+ - string+ - "null"+ type:+ type: string+ required:+ - message+ - type+ type: object+ required:+ - error+ type: object+ description: Insufficient credits+ "403":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Insufficient permission+ "404":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource not found+ "409":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Resource conflict+ "429":+ content:+ application/json:+ schema:+ properties:+ error:+ properties:+ code:+ type:+ - string+ - "null"+ message:+ type: string+ param:+ type:+ - string+ - "null"+ type:+ type: string+ required:+ - message+ - type+ type: object+ required:+ - error+ type: object+ description: Upstream provider rate limit+ "500":+ content:+ application/json:+ schema:+ $ref: "#/components/schemas/ApiError"+ description: Internal server error+ "502":+ content:+ application/json:+ schema:+ properties:+ error:+ properties:+ code:+ type:+ - string+ - "null"+ message:+ type: string+ param:+ type:+ - string+ - "null"+ type:+ type: string+ required:+ - message+ - type+ type: object+ required:+ - error+ type: object+ description: Upstream provider error+ summary: Create speech+ tags:+ - audio/api/v1/chat:post:operationId: postApiV1Chatdiff --git a/packages/openapi/src/common/base.controller.ts b/packages/openapi/src/common/base.controller.tsindex 6a43233f6ec..1f4f930288b 100644--- a/packages/openapi/src/common/base.controller.ts+++ b/packages/openapi/src/common/base.controller.ts@@ -18,7 +18,7 @@ import type { ApiResponse } from '../types';* `@trpc/server` keeps the package free of that dependency — `TRPCError` sets* `name` to `'TRPCError'`, which is part of its own public shape.*/-const TRPC_CODE_TO_STATUS: Record<string, number> = {+export const TRPC_CODE_TO_STATUS: Record<string, number> = {BAD_REQUEST: 400,CLIENT_CLOSED_REQUEST: 499,CONFLICT: 409,diff --git a/packages/openapi/src/controllers/audio.controller.test.ts b/packages/openapi/src/controllers/audio.controller.test.tsnew file mode 100644index 00000000000..843fc171b38--- /dev/null+++ b/packages/openapi/src/controllers/audio.controller.test.ts@@ -0,0 +1,202 @@+import { Hono } from 'hono';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const synthesizeMock = vi.fn();++vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(async () => ({})) }));+vi.mock('@/server/services/tts', async () => {+ class TTSRequestError extends Error {+ readonly name = 'TTSRequestError';+ constructor(+ message: string,+ readonly reason: string,+ ) {+ super(message);+ }+ }+ class TTSProviderError extends Error {+ readonly name = 'TTSProviderError';+ constructor(+ message: string,+ readonly errorType?: string,+ readonly detail?: unknown,+ ) {+ super(message);+ }+ }+ return {+ INLINE_TTS_AUDIO_FORMATS: ['mp3', 'opus', 'aac'],+ resolveTTSModelRef: (model: string, provider?: string) =>+ provider+ ? { model, provider }+ : model.startsWith('lobehub/')+ ? { model: model.slice('lobehub/'.length), provider: 'lobehub' }+ : { model, provider: 'openai' },+ TTSProviderError,+ TTSRequestError,+ TTSService: class {+ constructor(+ readonly db: unknown,+ readonly userId: string,+ readonly workspaceId?: string,+ ) {}+ synthesize = synthesizeMock;+ },+ };+});++const { AudioController } = await import('./audio.controller');+const { TTSProviderError, TTSRequestError } = await import('@/server/services/tts');++const app = new Hono();+app.use('*', async (c, next) => {+ c.set('userId' as never, 'user-1' as never);+ await next();+});+app.post('/speech', (c) => new AudioController().handleSpeech(c));++const speech = (body: unknown) =>+ app.request('/speech', {+ body: typeof body === 'string' ? body : JSON.stringify(body),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });++beforeEach(() => {+ synthesizeMock.mockReset();+ synthesizeMock.mockResolvedValue({+ audio: new Uint8Array([7, 8, 9]).buffer,+ format: 'mp3',+ mimeType: 'audio/mpeg',+ usage: { cost: 0.004_524, inputCharacters: 39 },+ });+});++describe('AudioController.handleSpeech', () => {+ it('returns the audio bytes with usage headers for an OpenAI SDK request', async () => {+ const res = await speech({+ input: '主人,今天也要元气满满哦!',+ model: 'lobehub/speech-2.8-hd',+ params: { emotion: 'happy', pitch: 2 },+ response_format: 'mp3',+ speed: 1.1,+ voice: 'Chinese (Mandarin)_Warm_Girl',+ });++ expect(res.status).toBe(200);+ expect(res.headers.get('Content-Type')).toBe('audio/mpeg');+ expect(res.headers.get('X-LobeHub-Usage-Characters')).toBe('39');+ expect(res.headers.get('X-LobeHub-Cost')).toBe('0.004524');+ expect(res.headers.get('X-LobeHub-Provider')).toBe('lobehub');+ expect(res.headers.get('Access-Control-Expose-Headers')).toContain('X-LobeHub-Cost');+ expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([7, 8, 9]));+ expect(synthesizeMock).toHaveBeenCalledWith({+ input: '主人,今天也要元气满满哦!',+ model: 'speech-2.8-hd',+ params: { emotion: 'happy', format: 'mp3', pitch: 2, speed: 1.1 },+ provider: 'lobehub',+ voice: 'Chinese (Mandarin)_Warm_Girl',+ });+ });++ it("accepts OpenAI's { id } voice form and an explicit provider", async () => {+ await speech({+ input: 'hi',+ model: 'speech-2.8-turbo',+ provider: 'minimax',+ voice: { id: 'v1' },+ });++ expect(synthesizeMock).toHaveBeenCalledWith(+ expect.objectContaining({ model: 'speech-2.8-turbo', provider: 'minimax', voice: 'v1' }),+ );+ });++ it.each(['wav', 'pcm', 'flac'])(+ 'refuses %s before synthesizing, with an OpenAI-style error',+ async (format) => {+ const res = await speech({ input: 'hi', model: 'tts-1', response_format: format });++ expect(res.status).toBe(400);+ expect(await res.json()).toMatchObject({+ error: {+ message: expect.stringContaining('use one of mp3, opus, aac'),+ param: 'response_format',+ type: 'invalid_request_error',+ },+ });+ expect(synthesizeMock).not.toHaveBeenCalled();+ },+ );++ it('rejects an invalid body without synthesizing', async () => {+ const res = await speech({ model: 'tts-1' });++ expect(res.status).toBe(400);+ expect((await res.json()).error.param).toBe('input');+ expect(synthesizeMock).not.toHaveBeenCalled();+ });++ it('rejects SSE streaming, which is not supported', async () => {+ const res = await speech({ input: 'hi', model: 'tts-1', stream_format: 'sse' });++ expect(res.status).toBe(400);+ expect(synthesizeMock).not.toHaveBeenCalled();+ });++ it('maps invalid params to 400 with the validation message', async () => {+ synthesizeMock.mockRejectedValue(+ new TTSRequestError('params.pitch must be between -12 and 12', 'invalid_params'),+ );++ const res = await speech({+ input: 'hi',+ model: 'lobehub/speech-2.8-hd',+ params: { pitch: 13 },+ });++ expect(res.status).toBe(400);+ expect((await res.json()).error).toMatchObject({+ code: 'invalid_params',+ message: 'params.pitch must be between -12 and 12',+ });+ });++ it('surfaces upstream failures as 502 with a readable message', async () => {+ synthesizeMock.mockRejectedValue(+ new TTSProviderError('voice id not exist', 'ProviderBizError'),+ );++ const res = await speech({ input: 'hi', model: 'lobehub/speech-2.8-hd', voice: 'nope' });++ expect(res.status).toBe(502);+ expect((await res.json()).error).toMatchObject({+ code: 'ProviderBizError',+ message: 'voice id not exist',+ type: 'upstream_error',+ });+ });++ it('maps upstream rate limits to 429', async () => {+ synthesizeMock.mockRejectedValue(new TTSProviderError('slow down', 'RateLimitExceeded'));++ const res = await speech({ input: 'hi', model: 'tts-1' });++ expect(res.status).toBe(429);+ expect((await res.json()).error.type).toBe('rate_limit_error');+ });++ it('keeps the status of server-side refusals such as an exhausted budget', async () => {+ synthesizeMock.mockRejectedValue(+ Object.assign(new Error('Insufficient credits'), {+ code: 'PAYMENT_REQUIRED',+ name: 'TRPCError',+ }),+ );++ const res = await speech({ input: 'hi', model: 'tts-1' });++ expect(res.status).toBe(402);+ expect((await res.json()).error.message).toBe('Insufficient credits');+ });+});diff --git a/packages/openapi/src/controllers/audio.controller.ts b/packages/openapi/src/controllers/audio.controller.tsnew file mode 100644index 00000000000..28d2685205d--- /dev/null+++ b/packages/openapi/src/controllers/audio.controller.ts@@ -0,0 +1,164 @@+import type { Context } from 'hono';+import { HTTPException } from 'hono/http-exception';++import {+ INLINE_TTS_AUDIO_FORMATS,+ resolveTTSModelRef,+ TTSProviderError,+ TTSRequestError,+ TTSService,+} from '@/server/services/tts';++import { BaseController, TRPC_CODE_TO_STATUS } from '../common/base.controller';+import type { SpeechRequest } from '../types/audio.type';+import { SpeechRequestSchema } from '../types/audio.type';++type OpenAIErrorType =+ | 'authentication_error'+ | 'invalid_request_error'+ | 'permission_error'+ | 'rate_limit_error'+ | 'server_error'+ | 'upstream_error';++/** Usage headers are custom, so browsers only expose them when listed here. */+const USAGE_HEADERS = [+ 'X-LobeHub-Audio-Format',+ 'X-LobeHub-Cost',+ 'X-LobeHub-Provider',+ 'X-LobeHub-Usage-Characters',+ 'X-LobeHub-Usage-Tokens',+];++const isInlineFormat = (format: string): format is (typeof INLINE_TTS_AUDIO_FORMATS)[number] =>+ (INLINE_TTS_AUDIO_FORMATS as readonly string[]).includes(format);++const errorTypeForStatus = (status: number): OpenAIErrorType => {+ if (status === 401) return 'authentication_error';+ if (status === 403) return 'permission_error';+ if (status === 429) return 'rate_limit_error';+ if (status === 502) return 'upstream_error';+ if (status >= 400 && status < 500) return 'invalid_request_error';+ return 'server_error';+};++/**+ * OpenAI-compatible text-to-speech, so external apps (desktop pets, bots) can call+ * LobeHub with an OpenAI SDK pointed at `/api/v1`.+ */+export class AudioController extends BaseController {+ /**+ * POST /api/v1/audio/speech+ * Body: SpeechRequest. Returns the audio bytes, or an OpenAI-style `{ error }` body.+ */+ async handleSpeech(c: Context): Promise<Response> {+ try {+ const parsed = SpeechRequestSchema.safeParse(await c.req.json().catch(() => undefined));+ if (!parsed.success) {+ const issue = parsed.error.issues[0];+ return this.openAIError(+ c,+ 400,+ issue ? `${issue.path.join('.') || 'body'}: ${issue.message}` : 'Invalid JSON body',+ issue?.path.join('.'),+ );+ }++ const body: SpeechRequest = parsed.data;+ if (body.stream_format === 'sse') {+ return this.openAIError(c, 400, 'stream_format "sse" is not supported', 'stream_format');+ }+ if (body.response_format && !isInlineFormat(body.response_format)) {+ return this.openAIError(+ c,+ 400,+ `response_format "${body.response_format}" is not supported; use one of ${INLINE_TTS_AUDIO_FORMATS.join(', ')}`,+ 'response_format',+ );+ }++ const { model, provider } = resolveTTSModelRef(body.model, body.provider);+ const params = {+ ...body.params,+ ...(body.response_format && { format: body.response_format as 'mp3' | 'opus' | 'aac' }),+ ...(body.speed !== undefined && { speed: body.speed }),+ ...(body.instructions !== undefined && { instructions: body.instructions }),+ };++ const db = await this.getDatabase();+ const service = new TTSService(db, this.getUserId(c)!, this.getWorkspaceId(c));+ const result = await service.synthesize({+ input: body.input,+ model,+ params,+ provider,+ voice: typeof body.voice === 'string' ? body.voice : body.voice?.id,+ });++ const headers: Record<string, string> = {+ 'Access-Control-Expose-Headers': USAGE_HEADERS.join(', '),+ 'Content-Type': result.mimeType,+ 'X-LobeHub-Audio-Format': result.format,+ 'X-LobeHub-Provider': provider,+ };+ const { usage } = result;+ if (usage?.inputCharacters !== undefined) {+ headers['X-LobeHub-Usage-Characters'] = String(usage.inputCharacters);+ }+ if (usage?.totalTokens !== undefined) {+ headers['X-LobeHub-Usage-Tokens'] = String(usage.totalTokens);+ }+ if (usage?.cost !== undefined) headers['X-LobeHub-Cost'] = String(usage.cost);++ return new Response(result.audio, { headers, status: 200 });+ } catch (error) {+ return this.handleSpeechError(c, error);+ }+ }++ private handleSpeechError(c: Context, error: unknown): Response {+ if (error instanceof TTSRequestError) {+ return this.openAIError(c, 400, error.message, undefined, error.reason);+ }+ if (error instanceof TTSProviderError) {+ console.error('[audio/speech] provider error:', error.detail ?? error);+ const status = error.errorType === 'RateLimitExceeded' ? 429 : 502;+ return this.openAIError(c, status, error.message, undefined, error.errorType);+ }+ if (error instanceof HTTPException) return this.openAIError(c, error.status, error.message);+ if (error instanceof Error && error.name === 'TRPCError') {+ // Server-side guards (budget, workspace access) refuse with tRPC codes.+ const code = (error as Error & { code?: string }).code;+ const status =+ (code && TRPC_CODE_TO_STATUS[code]) || (code === 'PAYMENT_REQUIRED' ? 402 : 500);+ return this.openAIError(c, status, error.message, undefined, code);+ }++ console.error('[audio/speech] unexpected error:', error);+ return this.openAIError(+ c,+ 500,+ error instanceof Error && error.message ? error.message : 'Text-to-speech failed',+ );+ }++ private openAIError(+ c: Context,+ status: number,+ message: string,+ param?: string,+ code?: string,+ ): Response {+ return c.json(+ {+ error: {+ code: code ?? null,+ message,+ param: param || null,+ type: errorTypeForStatus(status),+ },+ },+ status as any,+ );+ }+}diff --git a/packages/openapi/src/routes/audio.route.test.ts b/packages/openapi/src/routes/audio.route.test.tsnew file mode 100644index 00000000000..8831bcd2d7f--- /dev/null+++ b/packages/openapi/src/routes/audio.route.test.ts@@ -0,0 +1,62 @@+import { Hono } from 'hono';+import { describe, expect, it, vi } from 'vitest';++// The route checks both the issuer's RBAC invoke permission and the key's scope.+let rbacAllows = true;+vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn() }));+vi.mock('@/database/models/rbac', () => ({+ RbacModel: class {+ hasAnyPermission = async () => rbacAllows;+ },+}));+vi.mock('../middleware/auth', () => ({+ requireAuth: async (_c: any, next: any) => next(),+}));+vi.mock('../controllers/audio.controller', () => ({+ AudioController: class {+ handleSpeech() {+ return new Response(new Uint8Array([1]), { headers: { 'Content-Type': 'audio/mpeg' } });+ }+ },+}));++const { default: AudioRoutes } = await import('./audio.route');++const requestAs = (apiKeyScopes: string[], allowRbac = true) => {+ rbacAllows = allowRbac;+ const app = new Hono();+ app.use('*', async (c, next) => {+ c.set('userId' as never, 'user-1' as never);+ c.set('authType' as never, 'apikey' as never);+ c.set('apiKeyScopes' as never, apiKeyScopes as never);+ await next();+ });+ app.route('/', AudioRoutes);++ return app.request('/speech', {+ body: JSON.stringify({ input: 'hi', model: 'tts-1' }),+ headers: { 'Content-Type': 'application/json' },+ method: 'POST',+ });+};++describe('POST /audio/speech access', () => {+ it('accepts a key holding model:invoke', async () => {+ const res = await requestAs(['model:invoke']);++ expect(res.status).toBe(200);+ expect(res.headers.get('Content-Type')).toBe('audio/mpeg');+ });++ it('rejects a key without model:invoke', async () => {+ const res = await requestAs(['chat:read']);++ expect(res.status).toBe(403);+ });++ it('rejects an issuer without the model invoke permission, whatever the key scope', async () => {+ const res = await requestAs(['model:invoke'], false);++ expect(res.status).toBe(403);+ });+});diff --git a/packages/openapi/src/routes/audio.route.ts b/packages/openapi/src/routes/audio.route.tsnew file mode 100644index 00000000000..0b0352de9e1--- /dev/null+++ b/packages/openapi/src/routes/audio.route.ts@@ -0,0 +1,74 @@+import { Hono } from 'hono';+import type { DescribeRouteOptions } from 'hono-openapi';+import { describeRoute } from 'hono-openapi';++import { getAllScopePermissions } from '@/utils/rbac';++import { AudioController } from '../controllers/audio.controller';+import { requireAuth } from '../middleware/auth';+import { requireAnyPermission } from '../middleware/permission-check';++type RouteResponse = NonNullable<DescribeRouteOptions['responses']>[string];++/** Synthesis errors use OpenAI's error body, so OpenAI SDKs surface the message. */+const openAIError = (description: string): RouteResponse => ({+ content: {+ 'application/json': {+ schema: {+ properties: {+ error: {+ properties: {+ code: { type: ['string', 'null'] },+ message: { type: 'string' },+ param: { type: ['string', 'null'] },+ type: { type: 'string' },+ },+ required: ['message', 'type'],+ type: 'object',+ },+ },+ required: ['error'],+ type: 'object',+ },+ },+ },+ description,+});++const app = new Hono();+// Synthesis spends model credits: API keys need `model:invoke`, members the invoke permission.+const requireModelInvoke = requireAnyPermission(getAllScopePermissions('AI_MODEL_INVOKE'));++app.post(+ '/speech',+ describeRoute({+ description:+ 'OpenAI-compatible text-to-speech. Point an OpenAI SDK at `/api/v1` and call `audio.speech.create`. ' ++ '`model` takes `provider/model` (for example `lobehub/speech-2.8-hd`) or a bare model id; ' ++ 'the optional `provider` and `params` (emotion, pitch, volume, sampleRate) are LobeHub extensions. ' ++ 'Returns the audio bytes; usage is reported in `X-LobeHub-*` headers. ' ++ "Synthesis errors use OpenAI's `{ error: { message, type, code, param } }` body; " ++ 'authentication and permission errors use the platform `ApiError` envelope.',+ responses: {+ 200: {+ content: {+ 'audio/aac': { schema: { format: 'binary', type: 'string' } },+ 'audio/mpeg': { schema: { format: 'binary', type: 'string' } },+ 'audio/opus': { schema: { format: 'binary', type: 'string' } },+ },+ description: 'Synthesized audio',+ },+ 400: openAIError('Invalid request, unsupported format or invalid params'),+ 402: openAIError('Insufficient credits'),+ 429: openAIError('Upstream provider rate limit'),+ 502: openAIError('Upstream provider error'),+ },+ summary: 'Create speech',+ tags: ['audio'],+ }),+ requireAuth,+ requireModelInvoke,+ async (c) => new AudioController().handleSpeech(c),+);++export default app;diff --git a/packages/openapi/src/routes/index.ts b/packages/openapi/src/routes/index.tsindex 5d4bc20a986..022c80b342f 100644--- a/packages/openapi/src/routes/index.ts+++ b/packages/openapi/src/routes/index.ts@@ -2,6 +2,7 @@ import AgentGroupsRoutes from './agent-groups.route';import AgentsRoutes from './agents.route';import AnthropicRoutes from './anthropic.route';import ApiKeysRoutes from './api-keys.route';+import AudioRoutes from './audio.route';import ChatRoutes from './chat.route';import ChatGroupsRoutes from './chat-groups.route';import EvalRoutes from './eval.route';@@ -33,6 +34,7 @@ export default {'agents': AgentsRoutes,'anthropic': AnthropicRoutes,'api-keys': ApiKeysRoutes,+ 'audio': AudioRoutes,'chat': ChatRoutes,'chat-groups': ChatGroupsRoutes,'eval': EvalRoutes,diff --git a/packages/openapi/src/types/audio.type.ts b/packages/openapi/src/types/audio.type.tsnew file mode 100644index 00000000000..77758c59220--- /dev/null+++ b/packages/openapi/src/types/audio.type.ts@@ -0,0 +1,39 @@+import { z } from 'zod';++/** Formats an OpenAI client may ask for; only the compressed ones are served inline. */+export const OPENAI_SPEECH_FORMATS = ['mp3', 'opus', 'aac', 'flac', 'wav', 'pcm'] as const;++/** LobeHub's standard TTS params, checked against the model card before synthesis. */+export const SpeechParamsSchema = z+ .object({+ emotion: z.string().min(1).optional(),+ pitch: z.number().optional(),+ sampleRate: z.number().int().positive().optional(),+ volume: z.number().optional(),+ })+ .strict();++/**+ * Body of `POST /api/v1/audio/speech`: OpenAI's `audio.speech.create` request, plus the+ * optional LobeHub `provider` and `params` extensions.+ */+export const SpeechRequestSchema = z.object({+ /**+ * OpenAI caps one request at 4096 characters. Keeping the same bound keeps a single+ * response well under the serverless body limit.+ */+ input: z.string().min(1).max(4096),+ instructions: z.string().optional(),+ /** `provider/model` (for example `lobehub/speech-2.8-hd`), or a bare model id. */+ model: z.string().min(1),+ params: SpeechParamsSchema.optional(),+ /** Explicit provider; wins over a `provider/` prefix in `model`. */+ provider: z.string().min(1).optional(),+ response_format: z.enum(OPENAI_SPEECH_FORMATS).optional(),+ speed: z.number().min(0.25).max(4).optional(),+ stream_format: z.enum(['audio', 'sse']).optional(),+ /** A voice id, or OpenAI's `{ id }` form. Defaults to the model's default voice. */+ voice: z.union([z.string().min(1), z.object({ id: z.string().min(1) })]).optional(),+});++export type SpeechRequest = z.infer<typeof SpeechRequestSchema>;diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex 6b4b7bfbe72..114a82935e2 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -74,6 +74,8 @@ export enum RequestTrigger {TopicTitle = 'topic_title',/** Translation of a chat message or a generation prompt, including language detection. */Translate = 'translate',+ /** Text-to-speech synthesis, e.g. `lh generate tts`. */+ Tts = 'tts',/** Acceptance verification: plan generation, judging, review prediction and reports. */Verify = 'verify',Video = 'video',diff --git a/packages/types/src/message/common/metadata.ts b/packages/types/src/message/common/metadata.tsindex 4b12e4dcd0f..c8e8214f092 100644--- a/packages/types/src/message/common/metadata.ts+++ b/packages/types/src/message/common/metadata.ts@@ -66,6 +66,11 @@ export interface ModelTokensUsage {inputCachedVideoTokens?: number;inputCacheMissTokens?: number;+ /**+ * Input text characters, billed through `millionCharacters` pricing units+ * (e.g. character-billed text-to-speech models).+ */+ inputCharacters?: number;/*** currently only pplx has citation_tokens*/@@ -125,6 +130,7 @@ export const ModelUsageSchema = z.object({inputVideoTokens: z.number().optional(),inputCitationTokens: z.number().optional(),inputToolTokens: z.number().optional(),+ inputCharacters: z.number().optional(),// Output tokens breakdownoutputTextTokens: z.number().optional(),diff --git a/src/components/SpendType/index.test.tsx b/src/components/SpendType/index.test.tsxnew file mode 100644index 00000000000..1a63ce61e7d--- /dev/null+++ b/src/components/SpendType/index.test.tsx@@ -0,0 +1,19 @@+import { render } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import SpendType from './index';++const renderIconClass = (type: Parameters<typeof SpendType>[0]['type']) =>+ render(<SpendType type={type} />)+ .container.querySelector('svg')+ ?.getAttribute('class');++describe('SpendType', () => {+ it('renders the audio-lines icon for text-to-speech spend', () => {+ expect(renderIconClass('textToSpeech')).toContain('lucide-audio-lines');+ });++ it('keeps the microphone icon for speech recognition spend', () => {+ expect(renderIconClass('speechRecognition')).toContain('lucide-mic');+ });+});diff --git a/src/components/SpendType/index.tsx b/src/components/SpendType/index.tsxindex e52784c2480..f2a9eec0bcb 100644--- a/src/components/SpendType/index.tsx+++ b/src/components/SpendType/index.tsx@@ -1,5 +1,13 @@import { createStaticStyles, Icon, Tooltip } from '@lobehub/ui';-import { CircleDotDashed, Database, ImagePlus, MessageSquareText, Mic, Video } from 'lucide-react';+import {+ AudioLines,+ CircleDotDashed,+ Database,+ ImagePlus,+ MessageSquareText,+ Mic,+ Video,+} from 'lucide-react';import { memo, type ReactNode } from 'react';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -15,13 +23,21 @@ const styles = createStaticStyles(({ css, cssVar }) => ({speechRecognition: css`color: ${cssVar.colorInfo};`,+ textToSpeech: css`+ color: ${cssVar.cyan};+ `,videoGeneration: css`color: ${cssVar.colorWarning};`,}));export type SpendTypeValue =- 'chat' | 'embedding' | 'imageGeneration' | 'speechRecognition' | 'videoGeneration';+ | 'chat'+ | 'embedding'+ | 'imageGeneration'+ | 'speechRecognition'+ | 'textToSpeech'+ | 'videoGeneration';interface SpendTypeProps {/** The readable label — shown on hover, since the cell itself is icon-only. */@@ -43,6 +59,9 @@ const getIcon = (type: string) => {case 'speechRecognition': {return Mic;}+ case 'textToSpeech': {+ return AudioLines;+ }case 'videoGeneration': {return Video;}diff --git a/src/features/Settings/provider/features/ModelList/ModelItem.tsx b/src/features/Settings/provider/features/ModelList/ModelItem.tsxindex c4496ded48d..d716c76f84a 100644--- a/src/features/Settings/provider/features/ModelList/ModelItem.tsx+++ b/src/features/Settings/provider/features/ModelList/ModelItem.tsx@@ -23,14 +23,9 @@ import RoutingBadge from '@/components/ModelSelect/RoutingBadge';import { useIsMobile } from '@/hooks/useIsMobile';import { usePermission } from '@/hooks/usePermission';import { aiModelSelectors, useAiInfraStore } from '@/store/aiInfra';-import { formatPriceByCurrency } from '@/utils/format';-import {- getAudioInputUnitRate,- getTextInputUnitRate,- getTextOutputUnitRate,-} from '@/utils/pricing';import { createModelConfigModal } from './ModelConfigModal';+import { formatModelPricingLabels } from './pricingLabels';import { ProviderSettingsContext } from './ProviderSettingsContext';const styles = createStaticStyles(({ css, cx }) => {@@ -104,67 +99,9 @@ const ModelItem = memo<ModelItemProps>(const [checked, setChecked] = useState(enabled);- const formatPricing = (): string[] => {- if (!pricing) return [];-- switch (type) {- case 'chat': {- const inputRate = getTextInputUnitRate(pricing);- const outputRate = getTextOutputUnitRate(pricing);- return [- typeof inputRate === 'number' &&- t('providerModels.item.pricing.inputTokens', {- amount: formatPriceByCurrency(inputRate, pricing?.currency),- }),- typeof outputRate === 'number' &&- t('providerModels.item.pricing.outputTokens', {- amount: formatPriceByCurrency(outputRate, pricing?.currency),- }),- ].filter(Boolean) as string[];- }- // Decision models bill input tokens only.- case 'decision':- case 'embedding': {- const inputRate = getTextInputUnitRate(pricing);- return [- typeof inputRate === 'number' &&- t('providerModels.item.pricing.inputTokens', {- amount: formatPriceByCurrency(inputRate, pricing?.currency),- }),- ].filter(Boolean) as string[];- }- case 'tts': {- const inputRate = getAudioInputUnitRate(pricing);- return [- typeof inputRate === 'number' &&- t('providerModels.item.pricing.inputCharts', {- amount: formatPriceByCurrency(inputRate, pricing?.currency),- }),- ].filter(Boolean) as string[];- }- case 'asr': {- const inputRate = getAudioInputUnitRate(pricing);- return [- typeof inputRate === 'number' &&- t('providerModels.item.pricing.inputMinutes', {- amount: formatPriceByCurrency(inputRate, pricing?.currency),- }),- ].filter(Boolean) as string[];- }-- case 'image': {- return [];- }-- default: {- return [];- }- }- };-const content = [releasedAt && t('providerModels.item.releasedAt', { releasedAt }),- ...formatPricing(),+ ...formatModelPricingLabels(type, pricing, t),].filter(Boolean) as string[];const copyModelId = async () => {diff --git a/src/features/Settings/provider/features/ModelList/pricingLabels.test.ts b/src/features/Settings/provider/features/ModelList/pricingLabels.test.tsnew file mode 100644index 00000000000..cc0d13f8316--- /dev/null+++ b/src/features/Settings/provider/features/ModelList/pricingLabels.test.ts@@ -0,0 +1,69 @@+import type { AIChatModelCard, AITTSModelCard } from 'model-bank';+import minimaxModels from 'model-bank/minimax';+import { openaiTTSModels } from 'model-bank/openai';+import { describe, expect, it } from 'vitest';++import { formatModelPricingLabels } from './pricingLabels';++const t = (key: string, { amount }: { amount: string }) =>+ `${key.replace('providerModels.item.pricing.', '')}:${amount}`;++const findModel = <T extends { id: string }>(models: T[], id: string) => {+ const model = models.find((item) => item.id === id);+ if (!model) throw new Error(`model ${id} not found`);+ return model;+};++describe('formatModelPricingLabels', () => {+ describe('tts', () => {+ it('shows the per-character price of MiniMax speech models', () => {+ const model = findModel(minimaxModels as AITTSModelCard[], 'speech-2.8-hd');++ const labels = formatModelPricingLabels('tts', model.pricing, t);++ // 350 CNY per million characters, displayed in USD like the other CNY-priced models.+ expect(labels).toHaveLength(1);+ expect(labels[0]).toMatch(/^inputCharts:\d/);+ });++ it('shows the per-character price of OpenAI tts-1', () => {+ const model = findModel(openaiTTSModels, 'tts-1');++ expect(formatModelPricingLabels('tts', model.pricing, t)).toEqual(['inputCharts:15.00']);+ });++ it('shows token input and audio output prices for gpt-4o-mini-tts', () => {+ const model = findModel(openaiTTSModels, 'gpt-4o-mini-tts');++ expect(formatModelPricingLabels('tts', model.pricing, t)).toEqual([+ 'inputTokens:0.60',+ 'audioOutputTokens:12.00',+ ]);+ });++ it('keeps showing legacy custom models priced as audioInput', () => {+ const labels = formatModelPricingLabels(+ 'tts',+ { units: [{ name: 'audioInput', rate: 20, strategy: 'fixed', unit: 'millionCharacters' }] },+ t,+ );++ expect(labels).toEqual(['inputCharts:20.00']);+ });+ });++ it('shows input and output token prices for chat models', () => {+ const chat = (minimaxModels as AIChatModelCard[]).find(+ (item) => item.type === 'chat' && item.pricing,+ )!;++ const labels = formatModelPricingLabels('chat', chat.pricing, t);++ expect(labels[0]).toMatch(/^inputTokens:/);+ expect(labels[1]).toMatch(/^outputTokens:/);+ });++ it('returns nothing without pricing', () => {+ expect(formatModelPricingLabels('tts', undefined, t)).toEqual([]);+ });+});diff --git a/src/features/Settings/provider/features/ModelList/pricingLabels.ts b/src/features/Settings/provider/features/ModelList/pricingLabels.tsnew file mode 100644index 00000000000..02a9584844d--- /dev/null+++ b/src/features/Settings/provider/features/ModelList/pricingLabels.ts@@ -0,0 +1,106 @@+import type { AiModelType, Pricing, PricingUnitName } from 'model-bank';++import { formatPriceByCurrency } from '@/utils/format';+import {+ getAudioInputUnitRate,+ getAudioOutputUnitRate,+ getTextInputUnitRate,+ getTextOutputUnitRate,+} from '@/utils/pricing';++type PricingLabelKey =+ | 'providerModels.item.pricing.audioOutputTokens'+ | 'providerModels.item.pricing.inputCharts'+ | 'providerModels.item.pricing.inputMinutes'+ | 'providerModels.item.pricing.inputTokens'+ | 'providerModels.item.pricing.outputTokens';++type Translate = (key: PricingLabelKey, options: { amount: string }) => string;++const findUnit = (pricing: Pricing, name: PricingUnitName) =>+ pricing.units?.find((unit) => unit.name === name);++const formatTTSPricing = (pricing: Pricing, t: Translate): (string | false)[] => {+ const format = (rate: number) => formatPriceByCurrency(rate, pricing.currency);++ // TTS bills the input text, per million characters (tts-1, MiniMax speech) or per+ // million tokens (gpt-4o-mini-tts, which also bills the generated audio tokens).+ const textInputRate = getTextInputUnitRate(pricing);+ if (typeof textInputRate === 'number') {+ const audioOutputRate = getAudioOutputUnitRate(pricing);+ const charBased = findUnit(pricing, 'textInput')?.unit === 'millionCharacters';++ return [+ t(+ charBased+ ? 'providerModels.item.pricing.inputCharts'+ : 'providerModels.item.pricing.inputTokens',+ { amount: format(textInputRate) },+ ),+ typeof audioOutputRate === 'number' &&+ t('providerModels.item.pricing.audioOutputTokens', { amount: format(audioOutputRate) }),+ ];+ }++ // Legacy custom models stored their per-character price as audioInput.+ const legacyRate = getAudioInputUnitRate(pricing);+ return [+ typeof legacyRate === 'number' &&+ t('providerModels.item.pricing.inputCharts', { amount: format(legacyRate) }),+ ];+};++/**+ * Price lines shown under a model in the provider model list.+ */+export const formatModelPricingLabels = (+ type: AiModelType | undefined,+ pricing: Pricing | undefined,+ t: Translate,+): string[] => {+ if (!pricing) return [];++ const format = (rate: number) => formatPriceByCurrency(rate, pricing.currency);+ let labels: (string | false)[];++ switch (type) {+ case 'chat': {+ const inputRate = getTextInputUnitRate(pricing);+ const outputRate = getTextOutputUnitRate(pricing);+ labels = [+ typeof inputRate === 'number' &&+ t('providerModels.item.pricing.inputTokens', { amount: format(inputRate) }),+ typeof outputRate === 'number' &&+ t('providerModels.item.pricing.outputTokens', { amount: format(outputRate) }),+ ];+ break;+ }+ // Decision models bill input tokens only.+ case 'decision':+ case 'embedding': {+ const inputRate = getTextInputUnitRate(pricing);+ labels = [+ typeof inputRate === 'number' &&+ t('providerModels.item.pricing.inputTokens', { amount: format(inputRate) }),+ ];+ break;+ }+ case 'tts': {+ labels = formatTTSPricing(pricing, t);+ break;+ }+ case 'asr': {+ const inputRate = getAudioInputUnitRate(pricing);+ labels = [+ typeof inputRate === 'number' &&+ t('providerModels.item.pricing.inputMinutes', { amount: format(inputRate) }),+ ];+ break;+ }+ default: {+ labels = [];+ }+ }++ return labels.filter(Boolean) as string[];+};diff --git a/src/store/aiInfra/slices/aiProvider/action.ts b/src/store/aiInfra/slices/aiProvider/action.tsindex 9b95c9ba7ed..67c619d38ee 100644--- a/src/store/aiInfra/slices/aiProvider/action.ts+++ b/src/store/aiInfra/slices/aiProvider/action.ts@@ -118,9 +118,9 @@ const getModelProperty = async <T>(return getModelPropertyWithFallback<T | undefined>(model.id, propertyName, model.providerId);};-const hasParameters = (parameters?: ModelParamsSchema): parameters is ModelParamsSchema =>- !!parameters && Object.keys(parameters).length > 0;+const hasParameters = (parameters?: object) => !!parameters && Object.keys(parameters).length > 0;+/** Only image and video models reach here, so `parameters` is a generation schema. */const resolveModelParameters = async (model: EnabledAiModel,): Promise<ModelParamsSchema | undefined> => {@@ -128,7 +128,7 @@ const resolveModelParameters = async (// populates it. An empty object is truthy, so a naive truthy check would skip// the fallback and leave required fields (e.g. `prompt`) missing, which later// fails schema validation. Treat an empty object as "no inline parameters".- if (hasParameters(model.parameters)) return model.parameters;+ if (hasParameters(model.parameters)) return model.parameters as ModelParamsSchema;return getModelPropertyWithFallback<ModelParamsSchema | undefined>(model.id,