Skip to content

🤯 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.

✨ feat(tts): add Fish Audio and Doubao Speech TTS providers (#22951)

Rdmclin21afea3e47079
diff --git a/.agents/acceptance/references/multi-instance.md b/.agents/acceptance/references/multi-instance.md
index 09e390f3a2d..19d0663e7f0 100644
--- a/.agents/acceptance/references/multi-instance.md
+++ b/.agents/acceptance/references/multi-instance.md
@@ -255,7 +255,7 @@ electron-dev.sh stop --all # stop every instance
### Round 1 — concurrency, login reuse, isolation (Model A)
-Golden profile `lobehub-desktop-dev` (logged in, user_2gmT…); 3 userData copies
+Golden profile `lobehub-desktop-dev` (logged in, user\_2gmT…); 3 userData copies
(27 MB each), app name constant. inst1 = `electron-vite dev` (CDP 9223, Vite
5173\), inst2/inst3 = raw electron (CDP 9224/9225) sharing Vite.
diff --git a/.agents/acceptance/references/probe-field-notes.md b/.agents/acceptance/references/probe-field-notes.md
index b8dcd25cb2c..3aa0bdec99a 100644
--- a/.agents/acceptance/references/probe-field-notes.md
+++ b/.agents/acceptance/references/probe-field-notes.md
@@ -496,7 +496,7 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to
- **Postgres**: local brew Postgres 17 (pgvector available). Migrations apply clean: the
`pg_search` / BM25 migrations skip themselves without the extension. Set
`FTS_SEARCH_PROVIDER=pg_like` so product search works.
- - **Redis is a hard dependency of Better Auth sign-in** — with a dead REDIS_URL the seed
+ - **Redis is a hard dependency of Better Auth sign-in** — with a dead REDIS\_URL the seed
login 500s (`[Better Auth]: Error: Connection is closed`). `brew install redis`,
`redis-server --port 6380 --daemonize yes`.
- **S3**: `s3rver` (npm) on 29000 with a CORS config for the bucket. Its presigned-URL
@@ -751,7 +751,7 @@ executionTarget: 'local'` in `agencyConfig`) + one message per case asking CC to
- **Read the cause from `async_tasks.error`, not the toast**: `docker exec <pg> psql -U postgres -d postgres -c "select status, error from async_tasks order by created_at desc limit 3;"`.
- **Three separate walls, in the order you hit them**:
1. `start async task error: JWKS_KEY environment variable is not set` → see E22. The bootstrap now exports a persisted `JWKS_KEY`; you only hit this on a server started outside `init-dev-env.sh`.
- 2. `InvalidProviderAPIKey` → the seeded user's stored `ai_providers.key_vaults` may hold a key encrypted with a different `KEY_VAULTS_SECRET`. Clear it (`update ai_providers set key_vaults = null where id = '<provider>'`) so the server env key is used; provide `<PROVIDER>_API_KEY` plus, for a relay endpoint, `<PROVIDER>_PROXY_URL` (`apps/server/src/modules/ModelRuntime/index.ts` reads `process.env[`${UPPER}\_PROXY_URL`]`).
+ 2. `InvalidProviderAPIKey` → the seeded user's stored `ai_providers.key_vaults` may hold a key encrypted with a different `KEY_VAULTS_SECRET`. Clear it (`update ai_providers set key_vaults = null where id = '<provider>'`) so the server env key is used; provide `<PROVIDER>_API_KEY` plus, for a relay endpoint, `<PROVIDER>_PROXY_URL` (`apps/server/src/modules/ModelRuntime/index.ts` reads `process.env[`${UPPER}\_PROXY\_URL`]`).
3. `SSRF blocked: ... is not allowed. Because, It is private IP address.` → any reference image living in the local s3rver is fetched **server-side**. The bootstrap now exports `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`; set it yourself on a server started another way.
- **Then note which model the product actually picked** before attributing quality or format to a model: read the product's own selector rather than assuming (`selectAgentArtworkModel(enabledImageModelList(...))` over CDP). Disabling a provider row is enough to change the pick.
- **Style presets that attach reference images can still fail after all three**: local presigned URLs may return an S3 XML error body, which reaches the model as `Unsupported MIME type: application/xml`. Pick a preset with no reference images to test generation itself.
@@ -794,7 +794,7 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
conclusion. If a run "should" have hit your code and didn't, prove the server is running your
code FIRST — drop a `console.error` on the path and restart — before debugging the code itself.
-### E27. ✅ `source`-ing an unquoted JSON env var silently corrupts it (JWKS_KEY → gateway auth_failed)
+### E27. ✅ `source`-ing an unquoted JSON env var silently corrupts it (JWKS\_KEY → gateway auth\_failed)
- **Situation**: writing an env file for the local gateway loop with
`JWKS_KEY={"keys":[{"kty":"RSA",...}]}` on one line, then `set -a; source that-file`.
@@ -827,10 +827,10 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
and pick one from there. Also: a send that "resolves fine but creates no operation" is a UI-gate
symptom; **screenshot the composer** instead of re-reading your store call.
-### E29. Fresh-worktree `seed-user` dies on `Cannot find module 'bcryptjs'` — NODE_PATH into .pnpm fixes it
+### E29. Fresh-worktree `seed-user` dies on `Cannot find module 'bcryptjs'` — NODE\_PATH into .pnpm fixes it
- **Situation**: in a fresh git-worktree install, `init-dev-env.sh seed-user`
- (which runs `node <<'NODE'` from the repo root) throws MODULE_NOT_FOUND for
+ (which runs `node <<'NODE'` from the repo root) throws MODULE\_NOT\_FOUND for
`bcryptjs`, even though `pnpm install` succeeded.
- **Cause not fully established**: `bcryptjs` exists in `node_modules/.pnpm/`
but is not linked at the repo-root `node_modules` top level in that install
@@ -838,7 +838,7 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, …`). The h
resolve it.
- **Works**: prefix the call with
`NODE_PATH="$PWD/node_modules/.pnpm/bcryptjs@<ver>/node_modules"` (check the
- exact version dir first). CJS stdin scripts honor NODE_PATH; seeding then
+ exact version dir first). CJS stdin scripts honor NODE\_PATH; seeding then
completes normally.
- Same run also (re)confirmed: `init-dev-env.sh dev` ports are DYNAMIC (e.g.
next on 33803, vite on 32459) — never hardcode 3010; re-run
@@ -959,7 +959,7 @@ posix_spawn '<cmd>'` — NOT node's `spawn <cmd> ENOENT`. Any stderr-text patter
Telegram/Slack/Discord. A real bind needs a live bot issuing a `random_id` link token —
unavailable in an isolated env.
- **Works**: take the page's own refresh-after-link path instead. With a signed-in user, seed
- (1) a `messenger_account_links` row for (user, platform, tenant_id='') and (2) an enabled
+ (1) a `messenger_account_links` row for (user, platform, tenant\_id='') and (2) an enabled
`system_bot_providers` row for the platform — `credentials` must be encrypted with
`KeyVaultsGateKeeper.initWithEnvKey()` (same `KEY_VAULTS_SECRET` as the dev server), e.g.
telegram `{ botToken, botUsername }`. Then open
@@ -968,7 +968,7 @@ posix_spawn '<cmd>'` — NOT node's `spawn <cmd> ENOENT`. Any stderr-text patter
(`shouldShowSingleAccountSuccess` — existing link + no active token → success).
- `botUsername` drives the "Open in <platform>" deep-link CTA; re-encrypt the credentials
WITHOUT it to exercise the no-deep-link fallback. Note the platform config is cached
- in-process for 30s (`packages/app-config/src/messenger.ts` CACHE_TTL_MS) — wait out the TTL
+ in-process for 30s (`packages/app-config/src/messenger.ts` CACHE\_TTL\_MS) — wait out the TTL
after editing the row before reloading.
- Locale for evidence shots: `window.__LOBE_STORES.global().switchLocale('zh-CN')` then reload.
@@ -997,7 +997,7 @@ an action against the wrong row. For drag interactions (annotation canvases), di
`MouseEvent`s (`mousedown/mousemove/mouseup` with `bubbles:true` and computed `clientX/Y`) on the
target element.
-### E34. Shell proxy env (HTTP_PROXY=127.0.0.1:7890) inherited by the dev server breaks auth with silent 307 loops
+### E34. Shell proxy env (HTTP\_PROXY=127.0.0.1:7890) inherited by the dev server breaks auth with silent 307 loops
**Situation**: `init-dev-env.sh dev` launched from a shell where a system proxy (Clash etc.) exported
`HTTP_PROXY`/`HTTPS_PROXY`. The server booted fine, pages served, but `POST /api/auth/sign-in/email`
diff --git a/.env.example b/.env.example
index cb02aa43cdf..7fa4e850d5a 100644
--- a/.env.example
+++ b/.env.example
@@ -221,6 +221,19 @@ OPENAI_API_KEY=sk-xxxxxxxxx
# ELEVENLABS_API_KEY=sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
# ELEVENLABS_PROXY_URL=https://api.elevenlabs.io
+# ## Fish Audio (text-to-speech) ###
+
+# FISHAUDIO_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+# FISHAUDIO_PROXY_URL=https://api.fish.audio
+
+# ## Doubao Speech (Volcengine text-to-speech) ###
+
+# DOUBAOSPEECH_API_KEY=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
+# or the legacy console App ID + Access Token:
+# DOUBAOSPEECH_APP_ID=xxxxxxxxxx
+# DOUBAOSPEECH_ACCESS_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+# DOUBAOSPEECH_PROXY_URL=https://openspeech.bytedance.com
+
# #######################################
# ######## AI Image Settings ############
# #######################################
diff --git a/Dockerfile b/Dockerfile
index 8a74e4c32f6..0ecae9e760d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -261,8 +261,12 @@ ENV \
COMFYUI_API_KEY="" COMFYUI_USERNAME="" COMFYUI_PASSWORD="" COMFYUI_CUSTOM_HEADERS="" \
# DeepSeek
DEEPSEEK_API_KEY="" DEEPSEEK_MODEL_LIST="" \
+ # Doubao Speech
+ DOUBAOSPEECH_API_KEY="" DOUBAOSPEECH_APP_ID="" DOUBAOSPEECH_ACCESS_TOKEN="" DOUBAOSPEECH_MODEL_LIST="" DOUBAOSPEECH_PROXY_URL="" \
# ElevenLabs
ELEVENLABS_API_KEY="" ELEVENLABS_MODEL_LIST="" ELEVENLABS_PROXY_URL="" \
+ # Fish Audio
+ FISHAUDIO_API_KEY="" FISHAUDIO_MODEL_LIST="" FISHAUDIO_PROXY_URL="" \
# Fireworks AI
FIREWORKSAI_API_KEY="" FIREWORKSAI_MODEL_LIST="" \
# Gitee AI
diff --git a/apps/server/src/modules/ModelRuntime/index.ts b/apps/server/src/modules/ModelRuntime/index.ts
index 944114c6649..90848187a5f 100644
--- a/apps/server/src/modules/ModelRuntime/index.ts
+++ b/apps/server/src/modules/ModelRuntime/index.ts
@@ -18,6 +18,7 @@ import {
type ClientSecretPayload,
type CloudflareKeyVault,
type ComfyUIKeyVault,
+ type DoubaoSpeechKeyVault,
type GithubCopilotKeyVault,
type OAuthDeviceFlowKeyVault,
type OpenAICompatibleKeyVault,
@@ -58,6 +59,7 @@ type ProviderKeyVaults = OpenAICompatibleKeyVault &
AWSBedrockKeyVault &
CloudflareKeyVault &
ComfyUIKeyVault &
+ DoubaoSpeechKeyVault &
GithubCopilotKeyVault &
OAuthDeviceFlowKeyVault &
SuperGrokKeyVault &
@@ -136,6 +138,16 @@ export const buildPayloadFromKeyVaults = (
};
}
+ case ModelProvider.DoubaoSpeech: {
+ return {
+ apiKey: keyVaults.apiKey,
+ baseURL: keyVaults.baseURL,
+ doubaoSpeechAccessToken: keyVaults.accessToken,
+ doubaoSpeechAppId: keyVaults.appId,
+ runtimeProvider,
+ };
+ }
+
case ModelProvider.ComfyUI: {
return {
apiKey: keyVaults.apiKey,
@@ -297,6 +309,33 @@ const getParamsFromPayload = (provider: string, payload: ClientSecretPayload) =>
return { apiKey, baseURLOrAccountID };
}
+ case ModelProvider.DoubaoSpeech: {
+ const baseURL =
+ payload?.baseURL ||
+ (useServerConfig ? process.env.DOUBAOSPEECH_PROXY_URL : undefined) ||
+ undefined;
+
+ // The user's own credentials, of either console, are never mixed with the server's.
+ const hasUserCredentials = !!(
+ payload.apiKey ||
+ payload.doubaoSpeechAppId ||
+ payload.doubaoSpeechAccessToken
+ );
+ const credentials = hasUserCredentials
+ ? {
+ accessToken: payload.doubaoSpeechAccessToken,
+ apiKey: apiKeyManager.pick(payload.apiKey),
+ appId: payload.doubaoSpeechAppId,
+ }
+ : {
+ accessToken: llmConfig.DOUBAOSPEECH_ACCESS_TOKEN,
+ apiKey: apiKeyManager.pick(llmConfig.DOUBAOSPEECH_API_KEY),
+ appId: llmConfig.DOUBAOSPEECH_APP_ID,
+ };
+
+ return baseURL ? { ...credentials, baseURL } : credentials;
+ }
+
case ModelProvider.GithubCopilot: {
// Support both traditional PAT (apiKey) and OAuth tokens
return {
diff --git a/apps/server/src/modules/ModelRuntime/speechProviders.test.ts b/apps/server/src/modules/ModelRuntime/speechProviders.test.ts
new file mode 100644
index 00000000000..22a4fcae73c
--- /dev/null
+++ b/apps/server/src/modules/ModelRuntime/speechProviders.test.ts
@@ -0,0 +1,88 @@
+// @vitest-environment node
+import { LobeDoubaoSpeechAI, LobeFishAudioAI, ModelRuntime } from '@lobechat/model-runtime';
+import { ModelProvider } from 'model-bank';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { buildPayloadFromKeyVaults, initModelRuntimeWithUserPayload } from './index';
+
+vi.mock('@/server/globalConfig', () => ({ getServerAiProviderConfig: vi.fn() }));
+vi.mock('@/envs/llm', () => ({
+ getLLMConfig: vi.fn(() => ({
+ DOUBAOSPEECH_API_KEY: 'server-doubao-key',
+ FISHAUDIO_API_KEY: 'server-fish-key',
+ })),
+}));
+
+describe('initModelRuntimeWithUserPayload: Fish Audio', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('uses the user API key and endpoint, else FISHAUDIO_API_KEY', () => {
+ const runtime = initModelRuntimeWithUserPayload(ModelProvider.FishAudio, {
+ apiKey: 'user-fish-key',
+ baseURL: 'https://proxy.example.com',
+ });
+
+ expect(runtime).toBeInstanceOf(ModelRuntime);
+ expect(runtime['_runtime']).toBeInstanceOf(LobeFishAudioAI);
+ expect(runtime['_runtime']).toMatchObject({
+ apiKey: 'user-fish-key',
+ baseURL: 'https://proxy.example.com',
+ });
+ expect(initModelRuntimeWithUserPayload(ModelProvider.FishAudio, {})['_runtime']).toMatchObject({
+ apiKey: 'server-fish-key',
+ baseURL: 'https://api.fish.audio',
+ });
+ });
+});
+
+describe('Doubao Speech credentials', () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('forwards the legacy App ID + Access Token from the key vault', () => {
+ expect(
+ buildPayloadFromKeyVaults(
+ { accessToken: 'token', apiKey: undefined, appId: 'app', baseURL: 'https://x.example.com' },
+ ModelProvider.DoubaoSpeech,
+ ),
+ ).toEqual({
+ apiKey: undefined,
+ baseURL: 'https://x.example.com',
+ doubaoSpeechAccessToken: 'token',
+ doubaoSpeechAppId: 'app',
+ runtimeProvider: ModelProvider.DoubaoSpeech,
+ });
+ });
+
+ it('initializes from the user API key or the legacy credentials', () => {
+ const withKey = initModelRuntimeWithUserPayload(ModelProvider.DoubaoSpeech, {
+ apiKey: 'user-key',
+ })['_runtime'];
+ expect(withKey).toBeInstanceOf(LobeDoubaoSpeechAI);
+ expect(withKey['credentials']).toMatchObject({ apiKey: 'user-key' });
+
+ const legacy = initModelRuntimeWithUserPayload(ModelProvider.DoubaoSpeech, {
+ doubaoSpeechAccessToken: 'token',
+ doubaoSpeechAppId: 'app',
+ })['_runtime'];
+ expect(legacy['credentials']).toMatchObject({ accessToken: 'token', appId: 'app' });
+ expect(legacy['credentials'].apiKey).toBeFalsy();
+ });
+
+ it('falls back to DOUBAOSPEECH_API_KEY and DOUBAOSPEECH_PROXY_URL without user credentials', () => {
+ vi.stubEnv('DOUBAOSPEECH_PROXY_URL', 'https://proxy.example.com/api/v3');
+
+ const runtime = initModelRuntimeWithUserPayload(ModelProvider.DoubaoSpeech, {})['_runtime'];
+ expect(runtime['credentials']).toMatchObject({ apiKey: 'server-doubao-key' });
+ expect(runtime.baseURL).toBe('https://proxy.example.com');
+ });
+
+ it('rejects incomplete user credentials instead of mixing in the server key', () => {
+ expect(() =>
+ initModelRuntimeWithUserPayload(ModelProvider.DoubaoSpeech, { doubaoSpeechAppId: 'app' }),
+ ).toThrow(expect.objectContaining({ errorType: 'InvalidProviderAPIKey' }));
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/tts.test.ts b/apps/server/src/routers/lambda/__tests__/tts.test.ts
index 789fc15ad23..2a81a69586e 100644
--- a/apps/server/src/routers/lambda/__tests__/tts.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/tts.test.ts
@@ -281,6 +281,71 @@ describe('ttsRouter.synthesize', () => {
});
});
});
+
+ describe.each([
+ {
+ defaultVoice: 'default',
+ invalid: { speed: 2.5 },
+ invalidMessage: 'params.speed must be between 0.5 and 2',
+ model: 's2.1-pro',
+ name: 'Fish Audio',
+ provider: 'fishaudio',
+ },
+ {
+ defaultVoice: 'zh_female_vv_uranus_bigtts',
+ invalid: { pitch: 13 },
+ invalidMessage: 'params.pitch must be between -12 and 12',
+ model: 'seed-tts-2.0',
+ name: 'Doubao Speech',
+ provider: 'doubaospeech',
+ },
+ ])('provider $provider', ({ defaultVoice, invalid, invalidMessage, model, name, provider }) => {
+ it('routes to its runtime with the card default voice', async () => {
+ textToSpeechMock.mockResolvedValue({
+ audio: new Uint8Array([4, 5]).buffer,
+ format: 'mp3',
+ usage: { inputCharacters: 2 },
+ });
+
+ const res = await caller.synthesize({ input: 'Hi', model, provider });
+
+ expect(initModelRuntimeFromDB).toHaveBeenCalledWith(
+ expect.anything(),
+ 'u1',
+ provider,
+ undefined,
+ );
+ expect(textToSpeechMock).toHaveBeenCalledWith(
+ { input: 'Hi', model, params: {}, voice: defaultVoice, voiceIsDefault: true },
+ { metadata: { trigger: 'tts' }, user: 'u1' },
+ );
+ expect(res).toMatchObject({ format: 'mp3', mimeType: 'audio/mpeg' });
+ });
+
+ it('rejects invalid params before calling the runtime', async () => {
+ await expect(
+ caller.synthesize({ input: 'Hi', model, params: invalid, provider }),
+ ).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining(invalidMessage),
+ });
+ expect(textToSpeechMock).not.toHaveBeenCalled();
+ });
+
+ it('reports missing credentials with the InvalidProviderAPIKey copy', async () => {
+ vi.mocked(initModelRuntimeFromDB).mockRejectedValueOnce({
+ errorType: 'InvalidProviderAPIKey',
+ });
+
+ const error = await caller.synthesize({ input: 'Hi', model, provider }).catch((e) => e);
+
+ expect(error).toMatchObject({
+ code: 'BAD_GATEWAY',
+ message: `${name} API Key is incorrect or empty, please check your ${name} API Key and try again. Set it in Settings → AI Providers → ${name}, or in the server environment.`,
+ });
+ expect(error.cause).toMatchObject({ data: { errorType: 'InvalidProviderAPIKey', provider } });
+ });
+ });
});
describe('ttsRouter.synthesize saved default voice', () => {
diff --git a/apps/server/src/services/tts/doubaospeech.test.ts b/apps/server/src/services/tts/doubaospeech.test.ts
new file mode 100644
index 00000000000..a387fa2ba47
--- /dev/null
+++ b/apps/server/src/services/tts/doubaospeech.test.ts
@@ -0,0 +1,207 @@
+// @vitest-environment node
+/**
+ * TTSService → initModelRuntimeFromDB → ModelRuntime → LobeDoubaoSpeechAI → fetch, with
+ * only the provider row, the server env and the network mocked, so provider='doubaospeech'
+ * runs through the same code a tRPC / OpenAPI request does.
+ */
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const providerRow = vi.hoisted(() => ({ current: undefined as any }));
+const llmConfig = vi.hoisted(() => ({ current: {} as Record<string, string | undefined> }));
+
+vi.mock('@/database/models/aiProvider', () => ({
+ AiProviderModel: class {
+ getAiProviderById = vi.fn(async () => providerRow.current);
+ },
+}));
+vi.mock('@/envs/llm', () => ({ getLLMConfig: () => llmConfig.current }));
+vi.mock('@/business/server/model-runtime', () => ({
+ getBusinessModelRuntimeHooks: () => undefined,
+}));
+vi.mock('@/server/services/llmGenerationTracing/hook', () => ({
+ createLLMGenerationTracingHook: () => undefined,
+}));
+vi.mock('@/server/globalConfig', () => ({ getServerAiProviderConfig: vi.fn() }));
+
+const { INLINE_TTS_MAX_INPUT_CHARACTERS, TTSProviderError, TTSService } = await import('./index');
+
+const DEFAULT_VOICE = 'zh_female_vv_uranus_bigtts';
+
+const service = new TTSService({} as any, 'user-1');
+
+const streamResponse = () =>
+ new Response(
+ [
+ JSON.stringify({ code: 0, data: Buffer.from([0x49, 0x44]).toString('base64') }),
+ JSON.stringify({ code: 0, data: Buffer.from([0x33]).toString('base64') }),
+ JSON.stringify({ code: 20_000_000, message: 'ok', usage: { text_words: 4 } }),
+ ].join('\n'),
+ );
+
+const lastHeaders = (fetchMock: ReturnType<typeof vi.fn>) =>
+ (fetchMock.mock.calls.at(-1) as any)[1].headers as Record<string, string>;
+
+describe('TTSService with provider doubaospeech', () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ providerRow.current = { keyVaults: { apiKey: 'user-doubao-key' } };
+ llmConfig.current = {};
+ fetchMock = vi.fn(async () => streamResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ });
+
+ it('synthesizes with the API key saved in the provider settings', async () => {
+ const result = await service.synthesize({
+ input: '你好世界',
+ model: 'seed-tts-2.0',
+ params: { pitch: 2, speed: 1.2, volume: 0.8 },
+ provider: 'doubaospeech',
+ voice: 'zh_male_m191_uranus_bigtts',
+ });
+
+ const [url, init] = fetchMock.mock.calls[0] as any;
+ expect(url).toBe('https://openspeech.bytedance.com/api/v3/tts/unidirectional');
+ expect(init.headers['X-Api-Key']).toBe('user-doubao-key');
+ expect(init.headers['X-Api-Resource-Id']).toBe('seed-tts-2.0');
+ expect(JSON.parse(init.body).req_params).toEqual({
+ additions: JSON.stringify({ post_process: { pitch: 2 } }),
+ audio_params: { format: 'mp3', loudness_rate: -20, speech_rate: 20 },
+ speaker: 'zh_male_m191_uranus_bigtts',
+ text: '你好世界',
+ });
+
+ expect(new Uint8Array(result.audio)).toEqual(new Uint8Array([0x49, 0x44, 0x33]));
+ expect(result.format).toBe('mp3');
+ expect(result.mimeType).toBe('audio/mpeg');
+ expect(result.usage?.inputCharacters).toBe(4);
+ // 4 characters at 300 CNY / 1M characters, converted to USD
+ expect(result.usage?.cost).toBeGreaterThan(0);
+ });
+
+ it("defaults the voice to the model card's default voice", async () => {
+ await service.synthesize({ input: 'Hi', model: 'seed-tts-2.0', provider: 'doubaospeech' });
+
+ expect(JSON.parse((fetchMock.mock.calls[0] as any)[1].body).req_params.speaker).toBe(
+ DEFAULT_VOICE,
+ );
+ });
+
+ it('authenticates with the legacy App ID + Access Token saved in the settings', async () => {
+ providerRow.current = { keyVaults: { accessToken: 'user-token', appId: 'user-app' } };
+
+ await service.synthesize({ input: 'Hi', model: 'seed-tts-2.0', provider: 'doubaospeech' });
+
+ expect(lastHeaders(fetchMock)).toMatchObject({
+ 'X-Api-Access-Key': 'user-token',
+ 'X-Api-App-Id': 'user-app',
+ });
+ expect(lastHeaders(fetchMock)['X-Api-Key']).toBeUndefined();
+ });
+
+ it('falls back to the server credentials only when the user saved none', async () => {
+ providerRow.current = undefined;
+ llmConfig.current = { DOUBAOSPEECH_ACCESS_TOKEN: 'srv-token', DOUBAOSPEECH_APP_ID: 'srv-app' };
+ vi.stubEnv('DOUBAOSPEECH_PROXY_URL', 'https://proxy.example.com');
+
+ await service.synthesize({ input: 'Hi', model: 'seed-tts-2.0', provider: 'doubaospeech' });
+
+ expect((fetchMock.mock.calls[0] as any)[0]).toBe(
+ 'https://proxy.example.com/api/v3/tts/unidirectional',
+ );
+ expect(lastHeaders(fetchMock)).toMatchObject({
+ 'X-Api-Access-Key': 'srv-token',
+ 'X-Api-App-Id': 'srv-app',
+ });
+
+ // A user App ID without its token is incomplete, not topped up with the server's.
+ providerRow.current = { keyVaults: { appId: 'user-app' } };
+ llmConfig.current = { DOUBAOSPEECH_API_KEY: 'srv-key' };
+ await expect(
+ service.synthesize({ input: 'Hi', model: 'seed-tts-2.0', provider: 'doubaospeech' }),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails with a readable InvalidProviderAPIKey error when no credentials are configured', async () => {
+ providerRow.current = { keyVaults: {} };
+
+ const error = await service
+ .synthesize({ input: 'Hi', model: 'seed-tts-2.0', provider: 'doubaospeech' })
+ .catch((e) => e);
+
+ expect(error).toBeInstanceOf(TTSProviderError);
+ expect(error.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ expect(error.message).toBe(
+ 'Doubao Speech API Key is incorrect or empty, please check your Doubao Speech API Key and try again (Doubao Speech needs an API Key, or an App ID together with its Access Token). Set it in Settings → AI Providers → Doubao Speech, or in the server environment.',
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a rejected key with the InvalidProviderAPIKey copy and the upstream message', async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ code: 45_000_000, message: 'requested grant not found' }), {
+ status: 403,
+ }),
+ );
+
+ const error = await service
+ .synthesize({ input: 'Hi', model: 'seed-tts-2.0', provider: 'doubaospeech' })
+ .catch((e) => e);
+
+ expect(error.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ expect(error.message).toContain('requested grant not found');
+ expect(error.message).toContain('Settings → AI Providers → Doubao Speech');
+ });
+
+ it('surfaces concurrency limits as RateLimitExceeded', async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({ code: 45_000_000, message: 'quota exceeded for types: concurrency' }),
+ { status: 429 },
+ ),
+ );
+
+ await expect(
+ service.synthesize({ input: 'Hi', model: 'seed-tts-2.0', provider: 'doubaospeech' }),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.RateLimitExceeded });
+ });
+
+ it('rejects params the Doubao card does not allow before calling the API', async () => {
+ for (const params of [
+ { speed: 2.5 },
+ { volume: 3 },
+ { pitch: 20 },
+ { sampleRate: 11_025 },
+ { format: 'aac' as const },
+ { emotion: 'happy' },
+ ]) {
+ await expect(
+ service.synthesize({
+ input: 'Hi',
+ model: 'seed-tts-2.0',
+ params,
+ provider: 'doubaospeech',
+ }),
+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });
+ }
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects input over the inline cap before calling the API', async () => {
+ await expect(
+ service.synthesize({
+ input: '字'.repeat(INLINE_TTS_MAX_INPUT_CHARACTERS + 1),
+ model: 'seed-tts-2.0',
+ provider: 'doubaospeech',
+ }),
+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/tts/fishaudio.test.ts b/apps/server/src/services/tts/fishaudio.test.ts
new file mode 100644
index 00000000000..10863590055
--- /dev/null
+++ b/apps/server/src/services/tts/fishaudio.test.ts
@@ -0,0 +1,214 @@
+// @vitest-environment node
+/**
+ * TTSService → initModelRuntimeFromDB → ModelRuntime → LobeFishAudioAI → fetch, with only
+ * the provider row, the server env and the network mocked, so provider='fishaudio' runs
+ * through the same code a tRPC / OpenAPI request does.
+ */
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const providerRow = vi.hoisted(() => ({ current: undefined as any }));
+const llmConfig = vi.hoisted(() => ({ current: {} as Record<string, string | undefined> }));
+
+vi.mock('@/database/models/aiProvider', () => ({
+ AiProviderModel: class {
+ getAiProviderById = vi.fn(async () => providerRow.current);
+ },
+}));
+vi.mock('@/envs/llm', () => ({ getLLMConfig: () => llmConfig.current }));
+vi.mock('@/business/server/model-runtime', () => ({
+ getBusinessModelRuntimeHooks: () => undefined,
+}));
+vi.mock('@/server/services/llmGenerationTracing/hook', () => ({
+ createLLMGenerationTracingHook: () => undefined,
+}));
+vi.mock('@/server/globalConfig', () => ({ getServerAiProviderConfig: vi.fn() }));
+
+const { INLINE_TTS_MAX_INPUT_CHARACTERS, TTSProviderError, TTSRequestError, TTSService } =
+ await import('./index');
+
+const VOICE = '0123456789abcdef0123456789abcdef';
+const AUDIO = new Uint8Array([0x49, 0x44, 0x33, 0x04]);
+
+const service = new TTSService({} as any, 'user-1');
+
+describe('TTSService with provider fishaudio', () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ providerRow.current = { keyVaults: { apiKey: 'user-fish-key' } };
+ llmConfig.current = {};
+ fetchMock = vi.fn(
+ async () => new Response(AUDIO, { headers: { 'content-type': 'audio/mpeg' } }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ });
+
+ it('synthesizes with the key saved in the provider settings', async () => {
+ const result = await service.synthesize({
+ input: '你好 world',
+ model: 's2.1-pro',
+ params: { format: 'opus', instructions: 'cheerful', speed: 1.2 },
+ provider: 'fishaudio',
+ voice: VOICE,
+ });
+
+ const [url, init] = fetchMock.mock.calls[0] as any;
+ expect(url).toBe('https://api.fish.audio/v1/tts');
+ expect(init.headers.Authorization).toBe('Bearer user-fish-key');
+ expect(init.headers.model).toBe('s2.1-pro');
+ expect(JSON.parse(init.body)).toEqual({
+ format: 'opus',
+ prosody: { speed: 1.2 },
+ reference_id: VOICE,
+ text: '[cheerful] 你好 world',
+ });
+
+ expect(new Uint8Array(result.audio)).toEqual(AUDIO);
+ expect(result.format).toBe('opus');
+ expect(result.mimeType).toBe('audio/opus');
+ // "[cheerful] " (11) + 6 bytes for two Han characters + " world" (6) at $15 / 1M bytes
+ expect(result.usage).toEqual({ cost: 0.000_345, inputCharacters: 23 });
+ });
+
+ it("defaults to Fish Audio's own default voice, sending no reference_id", async () => {
+ await service.synthesize({ input: 'Hi', model: 'drama-3', provider: 'fishaudio' });
+
+ const [, init] = fetchMock.mock.calls[0] as any;
+ expect(init.headers.model).toBe('drama-3');
+ expect(JSON.parse(init.body)).toEqual({ format: 'mp3', text: 'Hi' });
+ });
+
+ it('falls back to FISHAUDIO_API_KEY and FISHAUDIO_PROXY_URL when the user saved no key', async () => {
+ providerRow.current = undefined;
+ llmConfig.current = { FISHAUDIO_API_KEY: 'server-fish-key' };
+ vi.stubEnv('FISHAUDIO_PROXY_URL', 'https://proxy.example.com/v1');
+
+ await service.synthesize({ input: 'Hi', model: 's2.1-pro', provider: 'fishaudio' });
+
+ const [url, init] = fetchMock.mock.calls[0] as any;
+ expect(url).toBe('https://proxy.example.com/v1/tts');
+ expect(init.headers.Authorization).toBe('Bearer server-fish-key');
+ });
+
+ it('fails with a readable InvalidProviderAPIKey error when no key is configured', async () => {
+ providerRow.current = { keyVaults: {} };
+
+ const error = await service
+ .synthesize({ input: 'Hi', model: 's2.1-pro', provider: 'fishaudio' })
+ .catch((e) => e);
+
+ expect(error).toBeInstanceOf(TTSProviderError);
+ expect(error.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ expect(error.message).toBe(
+ 'Fish Audio API Key is incorrect or empty, please check your Fish Audio API Key and try again. Set it in Settings → AI Providers → Fish Audio, or in the server environment.',
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('surfaces an upstream 401 with the InvalidProviderAPIKey copy and the Fish message', async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ message: 'Invalid token', status: 401 }), { status: 401 }),
+ );
+
+ const error = await service
+ .synthesize({ input: 'Hi', model: 's2.1-pro', provider: 'fishaudio' })
+ .catch((e) => e);
+
+ expect(error.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);
+ expect(error.message).toBe(
+ 'Fish Audio API Key is incorrect or empty, please check your Fish Audio API Key and try again (Fish Audio API error (401): Invalid token). Set it in Settings → AI Providers → Fish Audio, or in the server environment.',
+ );
+ });
+
+ it('surfaces an upstream 402 as InsufficientQuota', async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ message: 'No API credit', status: 402 }), { status: 402 }),
+ );
+
+ await expect(
+ service.synthesize({ input: 'Hi', model: 's2.1-pro', provider: 'fishaudio' }),
+ ).rejects.toMatchObject({
+ errorType: AgentRuntimeErrorType.InsufficientQuota,
+ message: 'Fish Audio API error (402): No API credit',
+ });
+ });
+
+ it('accepts a sample rate the format offers and forwards it to Fish', async () => {
+ await service.synthesize({
+ input: 'Hi',
+ model: 's2.1-pro',
+ params: { format: 'mp3', sampleRate: 32_000 },
+ provider: 'fishaudio',
+ });
+
+ expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toMatchObject({
+ format: 'mp3',
+ sample_rate: 32_000,
+ });
+ });
+
+ it('rejects a sample rate outside the Fish card before calling the API', async () => {
+ await expect(
+ service.synthesize({
+ input: 'Hi',
+ model: 's2.1-pro',
+ params: { sampleRate: 22_050 },
+ provider: 'fishaudio',
+ }),
+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects params the Fish card does not allow before calling the API', async () => {
+ for (const params of [
+ { speed: 3 },
+ { format: 'aac' as const },
+ { pitch: 2 },
+ { instructions: 'x'.repeat(201) },
+ ]) {
+ await expect(
+ service.synthesize({ input: 'Hi', model: 's2.1-pro', params, provider: 'fishaudio' }),
+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });
+ }
+
+ // S1 takes no directions.
+ await expect(
+ service.synthesize({
+ input: 'Hi',
+ model: 's1',
+ params: { instructions: 'calm' },
+ provider: 'fishaudio',
+ }),
+ ).rejects.toBeInstanceOf(TTSRequestError);
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects input over the inline cap before calling the API', async () => {
+ await expect(
+ service.synthesize({
+ input: 'a'.repeat(INLINE_TTS_MAX_INPUT_CHARACTERS + 1),
+ model: 's2.1-pro',
+ provider: 'fishaudio',
+ }),
+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('caps Fish Audio models routed through the LobeHub provider too', async () => {
+ await expect(
+ service.synthesize({
+ input: 'a'.repeat(INLINE_TTS_MAX_INPUT_CHARACTERS + 1),
+ model: 'drama-3',
+ provider: 'lobehub',
+ }),
+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/tts/index.test.ts b/apps/server/src/services/tts/index.test.ts
index ddc20942010..32ec7099977 100644
--- a/apps/server/src/services/tts/index.test.ts
+++ b/apps/server/src/services/tts/index.test.ts
@@ -3,7 +3,9 @@ import { describe, expect, it, vi } from 'vitest';
vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));
-const { invalidProviderAPIKeyMessage, resolveTTSModelRef } = await import('./index');
+const { findTTSModelCard, invalidProviderAPIKeyMessage, resolveTTSModelRef, TTSService } =
+ await import('./index');
+const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
const { default: modelRuntimeLocale } = await import('@/locales/default/modelRuntime');
describe('resolveTTSModelRef', () => {
@@ -36,6 +38,22 @@ describe('resolveTTSModelRef', () => {
expect(resolveTTSModelRef('tts-1')).toEqual({ model: 'tts-1', provider: 'openai' });
});
+ it('resolves Fish Audio and Doubao Speech model references (lh generate tts -m)', () => {
+ expect(resolveTTSModelRef('fishaudio/s2.1-pro')).toEqual({
+ model: 's2.1-pro',
+ provider: 'fishaudio',
+ });
+ expect(resolveTTSModelRef('doubaospeech/seed-tts-2.0')).toEqual({
+ model: 'seed-tts-2.0',
+ provider: 'doubaospeech',
+ });
+ expect(resolveTTSModelRef('drama-3')).toEqual({ model: 'drama-3', provider: 'fishaudio' });
+ expect(resolveTTSModelRef('seed-tts-2.0')).toEqual({
+ model: 'seed-tts-2.0',
+ provider: 'doubaospeech',
+ });
+ });
+
it('resolves ElevenLabs model references', () => {
expect(resolveTTSModelRef('elevenlabs/eleven_v4')).toEqual({
model: 'eleven_v4',
@@ -70,3 +88,43 @@ describe('invalidProviderAPIKeyMessage', () => {
expect(invalidProviderAPIKeyMessage('my-gateway')).toMatch(/^my-gateway API Key is incorrect/);
});
});
+
+describe('findTTSModelCard', () => {
+ it("returns the provider's own card first", () => {
+ expect(findTTSModelCard('fishaudio', 's1')?.providerId).toBe('fishaudio');
+ });
+
+ it('lets a built-in provider borrow a vendor card for the same model id', () => {
+ expect(findTTSModelCard('lobehub', 's2.1-pro')?.providerId).toBe('fishaudio');
+ });
+
+ it("never lends another vendor's card to a custom provider", () => {
+ expect(findTTSModelCard('my-custom-tts', 's1')).toBeUndefined();
+ expect(findTTSModelCard('my-custom-tts', 'tts-1')).toBeUndefined();
+ });
+});
+
+describe('TTSService with a custom provider whose model shares a Fish id', () => {
+ it('applies no Fish cap, schema or default voice', async () => {
+ const textToSpeech = vi.fn(async () => ({
+ audio: new ArrayBuffer(1),
+ format: 'mp3' as const,
+ usage: { inputCharacters: 5000 },
+ }));
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({ textToSpeech } as any);
+
+ const input = 'a'.repeat(5000);
+ await new TTSService({} as any, 'user-1').synthesize({
+ input,
+ model: 's1',
+ params: { instructions: 'calm' },
+ provider: 'my-custom-tts',
+ });
+
+ // Over the Fish cap, with instructions S1 would reject, and no Fish `default` voice.
+ expect(textToSpeech).toHaveBeenCalledWith(
+ expect.objectContaining({ input, model: 's1', voice: 'alloy', voiceIsDefault: true }),
+ expect.anything(),
+ );
+ });
+});
diff --git a/apps/server/src/services/tts/index.ts b/apps/server/src/services/tts/index.ts
index 72e33237fa7..09a7dc4b8be 100644
--- a/apps/server/src/services/tts/index.ts
+++ b/apps/server/src/services/tts/index.ts
@@ -22,12 +22,17 @@ export const INLINE_TTS_AUDIO_FORMATS = ['mp3', 'opus', 'aac'] as const;
/**
* Input cap for providers whose models accept far more text than fits in one inline
* response. Audio comes back in a single base64 body, so a long ElevenLabs Flash request
- * (up to 40,000 characters) would exceed the serverless response limit only after the
- * synthesis was billed. Matches the OpenAPI `/audio/speech` input limit.
+ * (up to 40,000 characters), or a Fish Audio / Doubao Speech request with no documented
+ * limit, would exceed the serverless response limit only after the synthesis was billed.
+ * Matches the OpenAPI `/audio/speech` input limit.
*/
export const INLINE_TTS_MAX_INPUT_CHARACTERS = 4096;
-const INLINE_INPUT_CAPPED_PROVIDERS = new Set<string>([ModelProvider.ElevenLabs]);
+const INLINE_INPUT_CAPPED_PROVIDERS = new Set<string>([
+ ModelProvider.DoubaoSpeech,
+ ModelProvider.ElevenLabs,
+ ModelProvider.FishAudio,
+]);
export interface TTSSynthesizeParams {
emotion?: string;
@@ -134,22 +139,27 @@ const toProviderError = (error: unknown, provider: string): TTSProviderError =>
return new TTSProviderError(message, errorType, error);
};
+const KNOWN_PROVIDERS = new Set<string>(Object.values(ModelProvider));
+
/**
- * 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).
+ * Built-in card of a TTS model: the provider's own card first, then, for a built-in provider
+ * only, any provider serving the same model id (aggregators reuse upstream cards).
*/
export const findTTSModelCard = (
provider: string,
model: string,
): (AITTSModelCard & { providerId?: string }) | undefined => {
const cards = LOBE_DEFAULT_MODEL_LIST.filter((card) => card.type === 'tts' && card.id === model);
+ const own = cards.find((card) => card.providerId === provider);
+ if (own) return own as AITTSModelCard & { providerId?: string };
- return (cards.find((card) => card.providerId === provider) ?? cards[0]) as
+ // A built-in provider (e.g. the LobeHub provider) serves vendor models under their own ids,
+ // so it borrows the vendor card. A user-created custom provider's `s1` or `tts-1` is its
+ // own model and must not inherit another vendor's limits, params or default voice.
+ return (KNOWN_PROVIDERS.has(provider) ? cards[0] : undefined) as
(AITTSModelCard & { providerId?: string }) | 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,
diff --git a/docs/self-hosting/environment-variables/model-provider.mdx b/docs/self-hosting/environment-variables/model-provider.mdx
index b915a83027e..8c4ce3c816a 100644
--- a/docs/self-hosting/environment-variables/model-provider.mdx
+++ b/docs/self-hosting/environment-variables/model-provider.mdx
@@ -742,6 +742,70 @@ Text-to-speech only. See [Using ElevenLabs in LobeHub](/docs/usage/providers/ele
The example hides all default models and enables only `eleven_v4` and `eleven_flash_v2_5`.
+## Fish Audio
+
+Text-to-speech only. See [Using Fish Audio in LobeHub](/docs/usage/providers/fishaudio) for setup instructions.
+
+### `FISHAUDIO_API_KEY`
+
+- Type: Optional for the deployment; required when providing a shared server key. Users can instead enter their own key in Fish Audio provider settings, which takes precedence.
+- Description: A key created on the [Fish Audio API Keys](https://fish.audio/app/api-keys) page. Setting a non-empty key automatically enables Fish Audio in the server configuration. `ENABLED_FISHAUDIO` is derived from this key, not a separate environment switch. Without a key from either source, speech requests to Fish Audio fail with an `InvalidProviderAPIKey` error.
+- Default: Unset; no shared server key.
+- Example: `xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`
+
+### `FISHAUDIO_PROXY_URL`
+
+- Type: Optional
+- Description: Overrides the Fish Audio API base URL. Only used together with the server key. A trailing `/v1` is accepted.
+- Default: `https://api.fish.audio`
+- Example: `https://fish-proxy.example.com`
+
+### `FISHAUDIO_MODEL_LIST`
+
+- Type: Optional
+- Description: Customizes the Fish Audio model list using the shared [model-list syntax][model-list].
+- Default: Unset; uses the built-in model list.
+- Example: `-all,+s2.1-pro`
+
+## Doubao Speech
+
+Volcengine speech synthesis, text-to-speech only; separate from the Volcengine Ark provider. See [Using Doubao Speech in LobeHub](/docs/usage/providers/doubaospeech) for setup instructions. Configure either `DOUBAOSPEECH_API_KEY`, or `DOUBAOSPEECH_APP_ID` together with `DOUBAOSPEECH_ACCESS_TOKEN`. Credentials a user saves in Doubao Speech provider settings take precedence and are never combined with the server's.
+
+### `DOUBAOSPEECH_API_KEY`
+
+- Type: Optional
+- Description: An API key from the new Volcengine speech console (API Key management), sent as `X-Api-Key`. Used instead of the App ID + Access Token when both are set. `ENABLED_DOUBAOSPEECH` is derived from the configured credentials, not a separate environment switch.
+- Default: Unset
+- Example: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
+
+### `DOUBAOSPEECH_APP_ID`
+
+- Type: Optional
+- Description: Legacy speech console App ID, used together with `DOUBAOSPEECH_ACCESS_TOKEN`.
+- Default: Unset
+- Example: `1234567890`
+
+### `DOUBAOSPEECH_ACCESS_TOKEN`
+
+- Type: Optional
+- Description: Legacy speech console Access Token, used together with `DOUBAOSPEECH_APP_ID`.
+- Default: Unset
+- Example: `xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`
+
+### `DOUBAOSPEECH_PROXY_URL`
+
+- Type: Optional
+- Description: Overrides the Doubao Speech API base URL. Only used together with the server credentials. A trailing `/api/v3` is accepted.
+- Default: `https://openspeech.bytedance.com`
+- Example: `https://doubao-proxy.example.com`
+
+### `DOUBAOSPEECH_MODEL_LIST`
+
+- Type: Optional
+- Description: Customizes the Doubao Speech model list using the shared [model-list syntax][model-list].
+- Default: Unset; uses the built-in model list.
+- Example: `-all,+seed-tts-2.0`
+
## ComfyUI
### `ENABLED_COMFYUI`
diff --git a/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx b/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx
index 5bccbef33f6..5517ce4cda5 100644
--- a/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx
@@ -800,6 +800,70 @@ LobeHub 在部署时提供了丰富的模型服务商相关的环境变量,你
上述示例表示隐藏所有默认模型,只启用 `eleven_v4` 和 `eleven_flash_v2_5`。
+## Fish Audio
+
+仅提供语音合成(TTS)。设置步骤见[在 LobeHub 中使用 Fish Audio](/zh/docs/usage/providers/fishaudio)。
+
+### `FISHAUDIO_API_KEY`
+
+- 类型:部署时可选;提供共享服务端密钥时必填。用户也可以在 Fish Audio 服务商设置中填写自己的密钥,用户密钥优先。
+- 描述:在 [Fish Audio API Keys](https://fish.audio/app/api-keys) 页面创建的密钥。设置非空密钥后,服务端配置会自动启用 Fish Audio。`ENABLED_FISHAUDIO` 由此密钥派生,不是独立的环境变量开关。两处都没有密钥时,调用 Fish Audio 语音合成会返回 `InvalidProviderAPIKey` 错误。
+- 默认值:未设置,不提供共享服务端密钥。
+- 示例:`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`
+
+### `FISHAUDIO_PROXY_URL`
+
+- 类型:可选
+- 描述:覆盖 Fish Audio API 的 Base URL。仅与服务端密钥一起使用。末尾带 `/v1` 也可以。
+- 默认值:`https://api.fish.audio`
+- 示例:`https://fish-proxy.example.com`
+
+### `FISHAUDIO_MODEL_LIST`
+
+- 类型:可选
+- 描述:使用通用的 [模型列表语法][model-list] 自定义 Fish Audio 模型列表。
+- 默认值:未设置,使用内置模型列表。
+- 示例:`-all,+s2.1-pro`
+
+## Doubao Speech
+
+豆包语音(火山引擎语音合成),仅提供语音合成(TTS),与火山方舟服务商相互独立。设置步骤见[在 LobeHub 中使用豆包语音](/zh/docs/usage/providers/doubaospeech)。配置 `DOUBAOSPEECH_API_KEY`,或同时配置 `DOUBAOSPEECH_APP_ID` 与 `DOUBAOSPEECH_ACCESS_TOKEN`。用户在豆包语音服务商设置中保存的凭证优先,且不会与服务端凭证混用。
+
+### `DOUBAOSPEECH_API_KEY`
+
+- 类型:可选
+- 描述:火山引擎新版语音控制台「API Key 管理」中的 API Key,以 `X-Api-Key` 发送。与 App ID + Access Token 同时设置时优先使用。`ENABLED_DOUBAOSPEECH` 由已配置的凭证派生,不是独立的环境变量开关。
+- 默认值:未设置
+- 示例:`xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`
+
+### `DOUBAOSPEECH_APP_ID`
+
+- 类型:可选
+- 描述:旧版语音控制台的 App ID,需与 `DOUBAOSPEECH_ACCESS_TOKEN` 一起使用。
+- 默认值:未设置
+- 示例:`1234567890`
+
+### `DOUBAOSPEECH_ACCESS_TOKEN`
+
+- 类型:可选
+- 描述:旧版语音控制台的 Access Token,需与 `DOUBAOSPEECH_APP_ID` 一起使用。
+- 默认值:未设置
+- 示例:`xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`
+
+### `DOUBAOSPEECH_PROXY_URL`
+
+- 类型:可选
+- 描述:覆盖豆包语音 API 的 Base URL。仅与服务端凭证一起使用。末尾带 `/api/v3` 也可以。
+- 默认值:`https://openspeech.bytedance.com`
+- 示例:`https://doubao-proxy.example.com`
+
+### `DOUBAOSPEECH_MODEL_LIST`
+
+- 类型:可选
+- 描述:使用通用的 [模型列表语法][model-list] 自定义豆包语音模型列表。
+- 默认值:未设置,使用内置模型列表。
+- 示例:`-all,+seed-tts-2.0`
+
## BFL
### `BFL_API_KEY`
diff --git a/docs/usage/providers.mdx b/docs/usage/providers.mdx
index 4700858eb07..f363576bc63 100644
--- a/docs/usage/providers.mdx
+++ b/docs/usage/providers.mdx
@@ -47,7 +47,7 @@ Models, regional access, prices, and API support depend on the provider and your
| **Chinese Providers** | [DeepSeek](/docs/usage/providers/deepseek) (DeepSeek-V4.1-Flash) · [Moonshot](/docs/usage/providers/moonshot) · [Zhipu](/docs/usage/providers/zhipu) · [Qwen](/docs/usage/providers/qwen) (Qwen3.8-Max) · [Baichuan](/docs/usage/providers/baichuan) · [Baidu Wenxin](/docs/usage/providers/wenxin) · [iFlytek Spark](/docs/usage/providers/spark) |
| **Local and Self-Hosted Inference** | [Ollama](/docs/usage/providers/ollama) · [LM Studio](/docs/usage/providers/lmstudio) · [vLLM](/docs/usage/providers/vllm) |
| **Image and Media Services** | [OpenAI](/docs/usage/providers/openai) · [Black Forest Labs](/docs/usage/providers/bfl) · [fal](/docs/usage/providers/fal) · [ComfyUI](/docs/usage/providers/comfyui) · [Google](/docs/usage/providers/google) · [Volcengine](/docs/usage/providers/volcengine) |
-| **Speech Synthesis (TTS)** | [ElevenLabs](/docs/usage/providers/elevenlabs) · [OpenAI](/docs/usage/providers/openai) · [MiniMax](/docs/usage/providers/minimax) · [Google Gemini](/docs/usage/providers/google#text-to-speech-gemini-tts) |
+| **Speech Synthesis (TTS)** | [ElevenLabs](/docs/usage/providers/elevenlabs) · [Fish Audio](/docs/usage/providers/fishaudio) · [Doubao Speech](/docs/usage/providers/doubaospeech) · [OpenAI](/docs/usage/providers/openai) · [MiniMax](/docs/usage/providers/minimax) · [Google Gemini](/docs/usage/providers/google#text-to-speech-gemini-tts) |
An image model name is not a provider name. Select the guide for the provider or local runtime that serves the model.
diff --git a/docs/usage/providers.zh-CN.mdx b/docs/usage/providers.zh-CN.mdx
index dff220a33a1..f06dbf973a0 100644
--- a/docs/usage/providers.zh-CN.mdx
+++ b/docs/usage/providers.zh-CN.mdx
@@ -43,7 +43,7 @@ tags:
| **国内服务商** | [DeepSeek](/zh/docs/usage/providers/deepseek)(DeepSeek-V4.1-Flash) · [Moonshot](/zh/docs/usage/providers/moonshot) · [智谱](/zh/docs/usage/providers/zhipu) · [通义千问](/zh/docs/usage/providers/qwen)(Qwen3.8-Max) · [百川](/zh/docs/usage/providers/baichuan) · [百度文心](/zh/docs/usage/providers/wenxin) · [讯飞星火](/zh/docs/usage/providers/spark) |
| **本地与自托管推理** | [Ollama](/zh/docs/usage/providers/ollama) · [LM Studio](/zh/docs/usage/providers/lmstudio) · [vLLM](/zh/docs/usage/providers/vllm) |
| **图像与多媒体服务** | [OpenAI](/zh/docs/usage/providers/openai) · [Black Forest Labs](/zh/docs/usage/providers/bfl) · [fal](/zh/docs/usage/providers/fal) · [ComfyUI](/zh/docs/usage/providers/comfyui) · [Google](/zh/docs/usage/providers/google) · [火山引擎](/zh/docs/usage/providers/volcengine) |
-| **语音合成(TTS)** | [ElevenLabs](/zh/docs/usage/providers/elevenlabs) · [OpenAI](/zh/docs/usage/providers/openai) · [MiniMax](/zh/docs/usage/providers/minimax) · [Google Gemini](/zh/docs/usage/providers/google#语音合成gemini-tts) |
+| **语音合成(TTS)** | [ElevenLabs](/zh/docs/usage/providers/elevenlabs) · [Fish Audio](/zh/docs/usage/providers/fishaudio) · [豆包语音](/zh/docs/usage/providers/doubaospeech) · [OpenAI](/zh/docs/usage/providers/openai) · [MiniMax](/zh/docs/usage/providers/minimax) · [Google Gemini](/zh/docs/usage/providers/google#语音合成gemini-tts) |
图像模型名称不是服务商名称。请按提供该模型的服务商或本地运行时选择配置教程。
diff --git a/docs/usage/providers/doubaospeech.mdx b/docs/usage/providers/doubaospeech.mdx
new file mode 100644
index 00000000000..8cd0bba9e08
--- /dev/null
+++ b/docs/usage/providers/doubaospeech.mdx
@@ -0,0 +1,69 @@
+---
+title: Using Doubao Speech in LobeHub
+description: >-
+ Configure Doubao Speech (Volcengine speech synthesis) in LobeHub with an API key or App ID + Access Token, and generate speech with Seed-TTS 2.0.
+tags:
+ - Doubao Speech
+ - Volcengine
+ - Text to Speech
+ - TTS
+ - API Key
+---
+
+# Using Doubao Speech in LobeHub
+
+[Doubao Speech](https://www.volcengine.com/product/tts) is ByteDance Volcengine's speech synthesis service. Its Seed-TTS 2.0 model speaks natural Mandarin and English with official voices. In LobeHub, Doubao Speech is a text-to-speech provider only: it has no chat models.
+
+Doubao Speech is a separate service from Volcengine Ark (the **Volcengine** provider for Doubao chat, image and video models), with its own console and credentials.
+
+<Steps>
+ ### Step 1: Obtain your Doubao Speech credentials
+
+ - Sign in to the [Volcengine speech console](https://console.volcengine.com/speech/new) and enable Doubao Speech Synthesis 2.0.
+ - Recommended: in the new console's **API Key management**, create an API key and copy it.
+ - Legacy console accounts: copy the **App ID** and **Access Token** of your application instead.
+
+ ### Step 2: Configure Doubao Speech in LobeHub
+
+ - Open **App Settings → AI Providers** and select **Doubao Speech** (type `Doubao` in the provider search box to find it).
+ - Paste the API key into **API Key**, or fill in **App ID (legacy console)** and **Access Token (legacy console)**. When both are filled in, the API key is used. Changes are saved automatically, and the credentials are encrypted with AES-GCM before they are stored.
+ - Turn on the switch next to the provider name.
+ - Optional: to send requests through a proxy, enter it in **API Proxy URL**. Leave it empty to use `https://openspeech.bytedance.com`.
+
+ ### Step 3: Choose models
+
+ The **Model List** shows **Doubao Speech 2.0** (`seed-tts-2.0`) under the **TTS** tab, enabled by default.
+
+ Doubao Speech has no chat model, so the provider page shows no **Check** button. Verify the credentials by generating speech as described below.
+
+ <Callout type={'warning'}>
+ Doubao Speech Synthesis 2.0 is billed at 3 CNY per 10,000 characters; every character, punctuation mark and space counts as one. Review the [Volcengine speech pricing](https://www.volcengine.com/docs/6561/1359370) before generating large amounts of audio.
+ </Callout>
+</Steps>
+
+## Generate speech
+
+Speech synthesis runs through the LobeHub text-to-speech API, which the LobeHub CLI (`lh`) and the OpenAI-compatible `POST /api/v1/audio/speech` endpoint both use:
+
+```bash
+lh generate tts "你好,LobeHub" -m doubaospeech/seed-tts-2.0 -o hello.mp3
+```
+
+- **Voice** — when no voice is given, Vivi 2.0 (`zh_female_vv_uranus_bigtts`) is used. Pass `--voice <voice_type>` to use another official 2.0 voice, for example `zh_male_m191_uranus_bigtts` (云舟) or `en_male_tim_uranus_bigtts` (Tim), or a voice clone of your own (`S_…`), which is sent to the voice-cloning resource `seed-icl-2.0` automatically and needs Doubao Voice Cloning 2.0 enabled. 1.0 voices (`*_moon_bigtts`, `*_mars_bigtts`) do not work with the 2.0 model.
+- **Length** — each request is limited to 4,096 characters, because the audio is returned in a single response. Split longer text into several requests.
+- **Format** — `mp3` (default) or `opus` (always 48 kHz).
+- **Speed and volume** — `0.5` to `2`.
+- **Pitch** — `-12` to `12` semitones.
+- **Sample rate** — 8000, 16000, 22050, 24000 (default), 32000, 44100 or 48000 Hz.
+
+## Troubleshooting
+
+**"Doubao Speech API Key is incorrect or empty, please check your Doubao Speech API Key and try again."** — No credentials were found, only one of App ID and Access Token was filled in, or Volcengine rejected them. Enter a valid API key (or App ID + Access Token) in **App Settings → AI Providers → Doubao Speech**, or ask the administrator to set `DOUBAOSPEECH_API_KEY` on the server.
+
+**"Enable the voice for this account…"** — The voice is not enabled for your account. Enable it in the Volcengine speech console, or pick another voice.
+
+**"The voice does not belong to this model version…"** — A 1.0 voice was used with the 2.0 model, or Doubao Speech Synthesis 2.0 is not enabled for the account.
+
+**Rate-limit or quota errors** — The account reached its concurrency limit (10 by default) or ran out of balance or trial quota. Check the Volcengine console.
+
+For self-hosted deployments, see `DOUBAOSPEECH_API_KEY` in the [model provider environment variables](/docs/self-hosting/environment-variables/model-provider#doubao-speech).
diff --git a/docs/usage/providers/doubaospeech.zh-CN.mdx b/docs/usage/providers/doubaospeech.zh-CN.mdx
new file mode 100644
index 00000000000..8e26398ad71
--- /dev/null
+++ b/docs/usage/providers/doubaospeech.zh-CN.mdx
@@ -0,0 +1,68 @@
+---
+title: 在 LobeHub 中使用豆包语音
+description: 在 LobeHub 中用 API Key 或 App ID + Access Token 配置豆包语音(火山引擎语音合成),使用 Seed-TTS 2.0 生成语音。
+tags:
+ - 豆包语音
+ - 火山引擎
+ - 语音合成
+ - TTS
+ - API Key
+---
+
+# 在 LobeHub 中使用豆包语音
+
+[豆包语音](https://www.volcengine.com/product/tts) 是字节跳动火山引擎的语音合成服务,Seed-TTS 2.0 模型使用官方音色合成自然的中英文语音。在 LobeHub 中,豆包语音(Doubao Speech)只提供语音合成(TTS),没有对话模型。
+
+豆包语音与火山方舟(**火山引擎** 服务商,提供豆包对话、图像与视频模型)是两套独立的服务,控制台与凭证都不同。
+
+<Steps>
+ ### 步骤一:获取豆包语音凭证
+
+ - 登录 [火山引擎语音控制台](https://console.volcengine.com/speech/new),开通豆包语音合成模型 2.0;
+ - 推荐:在新版控制台的 **API Key 管理** 中创建并复制 API Key;
+ - 旧版控制台账号:改为复制应用的 **App ID** 与 **Access Token**。
+
+ ### 步骤二:在 LobeHub 中配置豆包语音
+
+ - 打开 **应用设置 → AI 服务商**,选择 **Doubao Speech**(可在服务商搜索框中输入 `Doubao` 快速定位);
+ - 将 API Key 粘贴到 **API Key**,或填写 **App ID(旧版控制台)** 与 **Access Token(旧版控制台)**。两者都填写时使用 API Key。修改会自动保存,凭证在存储前会使用 AES-GCM 加密;
+ - 打开服务商名称右侧的开关;
+ - 可选:如需经代理发送请求,可在 **API 代理地址** 中填写。留空则使用 `https://openspeech.bytedance.com`。
+
+ ### 步骤三:选择模型
+
+ **模型列表** 的 **TTS** 标签下列出了 **Doubao Speech 2.0**(`seed-tts-2.0`),默认启用。
+
+ 豆包语音没有对话模型,因此服务商页面不显示 **检查** 按钮。可按下文方式生成一段语音来验证凭证。
+
+ <Callout type={'warning'}>
+ 豆包语音合成模型 2.0 按 3 元 / 万字符计费,汉字、字母、标点和空格都按 1 个字符计。大量生成音频前,请先查看 [火山引擎语音计费说明](https://www.volcengine.com/docs/6561/1359370)。
+ </Callout>
+</Steps>
+
+## 生成语音
+
+语音合成通过 LobeHub 的语音合成接口完成,LobeHub CLI(`lh`)与兼容 OpenAI 的 `POST /api/v1/audio/speech` 接口都使用该接口:
+
+```bash
+lh generate tts "你好,LobeHub" -m doubaospeech/seed-tts-2.0 -o hello.mp3
+```
+
+- **音色**:未指定时使用 Vivi 2.0(`zh_female_vv_uranus_bigtts`)。可用 `--voice <voice_type>` 指定其他官方 2.0 音色,例如 `zh_male_m191_uranus_bigtts`(云舟)、`en_male_tim_uranus_bigtts`(Tim),或你自己的复刻音色(`S_…`,会自动改用声音复刻资源 `seed-icl-2.0`,需要开通豆包声音复刻模型 2.0)。1.0 音色(`*_moon_bigtts`、`*_mars_bigtts`)不能用于 2.0 模型;
+- **长度**:语音以单个响应返回,每次请求最多 4096 个字符,更长的文本请拆成多次请求;
+- **格式**:`mp3`(默认)或 `opus`(固定 48 kHz);
+- **语速与音量**:`0.5` 至 `2`;
+- **音调**:`-12` 至 `12` 个半音;
+- **采样率**:8000、16000、22050、24000(默认)、32000、44100 或 48000 Hz。
+
+## 常见问题
+
+**“Doubao Speech API Key is incorrect or empty, please check your Doubao Speech API Key and try again.”**:没有找到凭证、App ID 与 Access Token 只填了一项,或凭证被火山引擎拒绝。请在 **应用设置 → AI 服务商 → Doubao Speech** 中填写有效的 API Key(或 App ID + Access Token),或请管理员在服务端设置 `DOUBAOSPEECH_API_KEY`。
+
+**“Enable the voice for this account…”**:账号未开通该音色。请在火山引擎语音控制台开通,或换用其他音色。
+
+**“The voice does not belong to this model version…”**:在 2.0 模型上使用了 1.0 音色,或账号未开通豆包语音合成模型 2.0。
+
+**限流或额度错误**:账号达到并发上限(默认 10 路),或余额、试用额度已用完。请在火山引擎控制台查看。
+
+自托管部署请参阅 [模型服务商环境变量](/zh/docs/self-hosting/environment-variables/model-provider#doubao-speech) 中的 `DOUBAOSPEECH_API_KEY`。
diff --git a/docs/usage/providers/fishaudio.mdx b/docs/usage/providers/fishaudio.mdx
new file mode 100644
index 00000000000..5ff86f77756
--- /dev/null
+++ b/docs/usage/providers/fishaudio.mdx
@@ -0,0 +1,69 @@
+---
+title: Using Fish Audio API Key in LobeHub
+description: >-
+ Configure a Fish Audio API key in LobeHub and generate expressive speech with Fish Audio S2.1 Pro and Drama 3.
+tags:
+ - Fish Audio
+ - Text to Speech
+ - TTS
+ - API Key
+---
+
+# Using Fish Audio in LobeHub
+
+[Fish Audio](https://fish.audio) provides expressive multilingual text-to-speech models that follow natural-language delivery directions. In LobeHub, Fish Audio is a text-to-speech provider only: it has no chat models.
+
+<Steps>
+ ### Step 1: Obtain your Fish Audio API key
+
+ - Sign up or sign in at [Fish Audio](https://fish.audio).
+ - Open [API Keys](https://fish.audio/app/api-keys) and create a key. API usage is prepaid and billed separately from the Fish Audio app subscription.
+ - Copy the key and store it securely.
+
+ ### Step 2: Configure Fish Audio in LobeHub
+
+ - Open **App Settings → AI Providers** and select **Fish Audio** (type `Fish` in the provider search box to find it).
+ - Paste your key into **API Key**. Changes are saved automatically, and the key is encrypted with AES-GCM before it is stored.
+ - Turn on the switch next to the provider name.
+ - Optional: to send requests through a proxy, enter it in **API Proxy URL**. Leave it empty to use `https://api.fish.audio`.
+
+ ### Step 3: Choose models
+
+ The **Model List** shows the Fish Audio speech models under the **TTS** tab. Fish Audio S2.1 Pro and Drama 3 are enabled by default; S2 Pro and the deprecated S1 can be turned on in the same list.
+
+ Fish Audio has no chat model, so the provider page shows no **Check** button. Verify the key by generating speech as described below.
+
+ <Callout type={'warning'}>
+ Fish Audio bills per million UTF-8 bytes, so one Chinese character costs as much as three English letters. LobeHub records usage in the same UTF-8 bytes, including when Fish Audio models are reached through an OpenAI-compatible gateway such as OpenRouter. Review the [Fish Audio API pricing](https://docs.fish.audio/developer-guide/models-pricing/pricing-and-rate-limits) before generating large amounts of audio.
+ </Callout>
+</Steps>
+
+## Generate speech
+
+Speech synthesis runs through the LobeHub text-to-speech API, which the LobeHub CLI (`lh`) and the OpenAI-compatible `POST /api/v1/audio/speech` endpoint both use:
+
+```bash
+lh generate tts "Hello from LobeHub" -m fishaudio/s2.1-pro -o hello.mp3
+```
+
+- **Voice** — when no voice is given, Fish Audio's own default voice is used. Pass `--voice <reference_id>` to use another voice: the 32-character id in the voice page URL `fish.audio/m/<reference_id>`.
+- **Length** — each request is limited to 4,096 characters, because the audio is returned in a single response. Split longer text into several requests.
+- **Format** — `mp3` (default) or `opus`.
+- **Speed** — `0.5` to `2`.
+- **Instructions** — S2.1 Pro, S2 Pro and Drama 3 take a delivery direction of up to 200 characters, for example `--instructions "whisper, nervous"`. It is placed in front of the text as a `[direction]` and billed with it. S1 does not accept instructions.
+
+<Callout type={'warning'}>
+ LobeHub does not bundle any voices from the Fish Audio community library, which contains many unlicensed character and real-person clones. Only use voices you cloned yourself or are licensed to use.
+</Callout>
+
+## Troubleshooting
+
+**"Fish Audio API Key is incorrect or empty, please check your Fish Audio API Key and try again."** — No key was found, or Fish Audio rejected the key. Enter a valid key in **App Settings → AI Providers → Fish Audio**, or ask the administrator to set `FISHAUDIO_API_KEY` on the server. When Fish Audio rejected the key, its own message follows in parentheses, for example `Fish Audio API error (401): Invalid token`.
+
+**"Fish Audio API error (402)…"** — The account has no API credit for the selected model. Top up the API balance in Fish Audio.
+
+**"Check the voice id…"** — The `reference_id` does not exist or your account may not use it. Pass a voice you own, or omit `--voice`.
+
+**Rate-limit errors** — The account reached its concurrent request limit, which grows with your total API spend. Retry later.
+
+For self-hosted deployments, see `FISHAUDIO_API_KEY` in the [model provider environment variables](/docs/self-hosting/environment-variables/model-provider#fish-audio).
diff --git a/docs/usage/providers/fishaudio.zh-CN.mdx b/docs/usage/providers/fishaudio.zh-CN.mdx
new file mode 100644
index 00000000000..60bc03cc9d4
--- /dev/null
+++ b/docs/usage/providers/fishaudio.zh-CN.mdx
@@ -0,0 +1,68 @@
+---
+title: 在 LobeHub 中使用 Fish Audio API Key
+description: 在 LobeHub 中配置 Fish Audio API Key,使用 Fish Audio S2.1 Pro、Drama 3 生成富有表现力的语音。
+tags:
+ - Fish Audio
+ - 语音合成
+ - TTS
+ - API Key
+---
+
+# 在 LobeHub 中使用 Fish Audio
+
+[Fish Audio](https://fish.audio) 提供富有表现力的多语种语音合成模型,可以用自然语言指导演绎方式。在 LobeHub 中,Fish Audio 只提供语音合成(TTS),没有对话模型。
+
+<Steps>
+ ### 步骤一:获取 Fish Audio API Key
+
+ - 注册或登录 [Fish Audio](https://fish.audio);
+ - 打开 [API Keys](https://fish.audio/app/api-keys) 页面,创建一个密钥。API 用量为预付费,与 Fish Audio 应用订阅分开计费;
+ - 复制密钥并妥善保存。
+
+ ### 步骤二:在 LobeHub 中配置 Fish Audio
+
+ - 打开 **应用设置 → AI 服务商**,选择 **Fish Audio**(可在服务商搜索框中输入 `Fish` 快速定位);
+ - 将密钥粘贴到 **API Key** 输入框。修改会自动保存,密钥在存储前会使用 AES-GCM 加密;
+ - 打开服务商名称右侧的开关;
+ - 可选:如需经代理发送请求,可在 **API 代理地址** 中填写。留空则使用 `https://api.fish.audio`。
+
+ ### 步骤三:选择模型
+
+ **模型列表** 的 **TTS** 标签下列出了 Fish Audio 语音模型。Fish Audio S2.1 Pro、Drama 3 默认启用;S2 Pro 与已弃用的 S1 可在同一列表中手动开启。
+
+ Fish Audio 没有对话模型,因此服务商页面不显示 **检查** 按钮。可按下文方式生成一段语音来验证密钥。
+
+ <Callout type={'warning'}>
+ Fish Audio 按每百万 UTF-8 字节计费,一个汉字的费用相当于三个英文字母。LobeHub 也按 UTF-8 字节记录用量,通过 OpenRouter 等 OpenAI 兼容网关调用 Fish Audio 模型时同样如此。大量生成音频前,请先查看 [Fish Audio API 定价](https://docs.fish.audio/developer-guide/models-pricing/pricing-and-rate-limits)。
+ </Callout>
+</Steps>
+
+## 生成语音
+
+语音合成通过 LobeHub 的语音合成接口完成,LobeHub CLI(`lh`)与兼容 OpenAI 的 `POST /api/v1/audio/speech` 接口都使用该接口:
+
+```bash
+lh generate tts "你好,LobeHub" -m fishaudio/s2.1-pro -o hello.mp3
+```
+
+- **音色**:未指定时使用 Fish Audio 自带的默认音色。可用 `--voice <reference_id>` 指定其他音色,即音色页面地址 `fish.audio/m/<reference_id>` 中的 32 位 ID;
+- **长度**:语音以单个响应返回,每次请求最多 4096 个字符,更长的文本请拆成多次请求;
+- **格式**:`mp3`(默认)或 `opus`;
+- **语速**:`0.5` 至 `2`;
+- **演绎指令**:S2.1 Pro、S2 Pro 与 Drama 3 支持不超过 200 个字符的演绎指令,例如 `--instructions "小声、紧张"`。指令会以 `[指令]` 的形式放在文本前面,并一同计费。S1 不支持演绎指令。
+
+<Callout type={'warning'}>
+ LobeHub 不内置任何来自 Fish Audio 社区音色库的音色,社区库中有大量未经授权的角色和真人克隆音色。请只使用你自己克隆或有权使用的音色。
+</Callout>
+
+## 常见问题
+
+**“Fish Audio API Key is incorrect or empty, please check your Fish Audio API Key and try again.”**:没有找到密钥,或密钥被 Fish Audio 拒绝。请在 **应用设置 → AI 服务商 → Fish Audio** 中填写有效密钥,或请管理员在服务端设置 `FISHAUDIO_API_KEY`。密钥被拒绝时,括号中会附上 Fish Audio 返回的原始信息,例如 `Fish Audio API error (401): Invalid token`。
+
+**“Fish Audio API error (402)…”**:账号没有所选模型的 API 余额,请在 Fish Audio 充值 API 额度。
+
+**“Check the voice id…”**:该 `reference_id` 不存在或你的账号无权使用。请指定你自己拥有的音色,或不传 `--voice`。
+
+**限流错误**:账号达到并发请求上限,上限会随累计 API 消费提高。请稍后重试。
+
+自托管部署请参阅 [模型服务商环境变量](/zh/docs/self-hosting/environment-variables/model-provider#fish-audio) 中的 `FISHAUDIO_API_KEY`。
diff --git a/locales/en-US/modelProvider.json b/locales/en-US/modelProvider.json
index 5e68dac25cf..da55f7722c2 100644
--- a/locales/en-US/modelProvider.json
+++ b/locales/en-US/modelProvider.json
@@ -114,6 +114,15 @@
"createNewAiProvider.sdkType.required": "Please select SDK type",
"createNewAiProvider.sdkType.title": "Request Format",
"createNewAiProvider.title": "Create Custom AI Provider",
+ "doubaospeech.accessToken.desc": "Legacy speech console only: the Access Token paired with the App ID. Leave empty when using an API Key",
+ "doubaospeech.accessToken.placeholder": "Access Token",
+ "doubaospeech.accessToken.title": "Access Token (legacy console)",
+ "doubaospeech.apiKey.desc": "API Key from the new Volcengine speech console (API Key management). Recommended; it takes precedence over App ID + Access Token",
+ "doubaospeech.apiKey.placeholder": "Doubao Speech API Key",
+ "doubaospeech.apiKey.title": "API Key",
+ "doubaospeech.appId.desc": "Legacy speech console only: the App ID of your application, used together with the Access Token",
+ "doubaospeech.appId.placeholder": "App ID",
+ "doubaospeech.appId.title": "App ID (legacy console)",
"github.personalAccessToken.desc": "Enter your GitHub PAT. Click [here](https://github.com/settings/tokens) to create one.",
"github.personalAccessToken.placeholder": "ghp_xxxxxx",
"github.personalAccessToken.title": "GitHub PAT",
diff --git a/locales/en-US/models.json b/locales/en-US/models.json
index 98003758539..45f0a301b60 100644
--- a/locales/en-US/models.json
+++ b/locales/en-US/models.json
@@ -450,6 +450,7 @@
"doubao-seedream-4-0-250828.description": "Seedream 4.0 is an image generation model from ByteDance Seed, supporting text and image inputs with highly controllable, high-quality image generation. It generates images from text prompts.",
"doubao-seedream-4-5-251128.description": "Seedream 4.5 is ByteDance’s latest multimodal image model, integrating text-to-image, image-to-image, and batch image generation capabilities, while incorporating commonsense and reasoning abilities. Compared to the previous 4.0 version, it delivers significantly improved generation quality, with better editing consistency and multi-image fusion. It offers more precise control over visual details, producing small text and small faces more naturally, and achieves more harmonious layout and color, enhancing overall aesthetics.",
"doubao-seedream-5-0-260128.description": "Doubao-Seedream-5.0-lite is ByteDance’s latest image-generation model. For the first time, it integrates online retrieval capabilities, allowing it to incorporate real-time web information and enhance the timeliness of generated images. The model’s intelligence has also been upgraded, enabling precise interpretation of complex instructions and visual content. Additionally, it offers improved global knowledge coverage, reference consistency, and generation quality in professional scenarios, better meeting enterprise-level visual creation needs.",
+ "drama-3.description": "Fish Audio’s most expressive model: direct each line in natural language, with sound effects, pauses and per-word tags.",
"dreamina-seedance-2-0-260128.description": "Seedance 2.0 by ByteDance is the most powerful video generation model, supporting multimodal reference video generation, video editing, video extension, text-to-video, and image-to-video with synchronized audio.",
"dreamina-seedance-2-0-fast-260128.description": "Seedance 2.0 Fast by ByteDance offers the same capabilities as Seedance 2.0 with faster generation speeds at a more competitive price.",
"eleven_flash_v2.description": "English-only ultra-low-latency (~135 ms) speech model for real-time use. Up to 30,000 characters per request.",
@@ -1308,6 +1309,10 @@
"qwq.description": "QwQ is a reasoning model in the Qwen family. Compared with standard instruction-tuned models, it brings thinking and reasoning abilities that significantly improve downstream performance, especially on hard problems. QwQ-32B is a mid-sized reasoning model that competes well with top reasoning models like DeepSeek-R1 and o1-mini.",
"qwq_32b.description": "Mid-sized reasoning model in the Qwen family. Compared with standard instruction-tuned models, QwQ’s thinking and reasoning abilities significantly boost downstream performance, especially on hard problems.",
"r1-1776.description": "R1-1776 is a post-trained variant of DeepSeek R1 designed to provide uncensored, unbiased factual information.",
+ "s1.description": "Deprecated speech model with 13 languages and (parenthesis) emotion tags. Fish Audio retires it on 2026-12-31 and then serves requests with S2.1 Pro.",
+ "s2-pro.description": "Previous-generation open-weights speech model with 80+ languages and [bracketed] delivery directions.",
+ "s2.1-pro.description": "Fish Audio’s recommended production speech model: 80+ languages, natural-language [directions] for delivery, multi-speaker and voice cloning.",
+ "seed-tts-2.0.description": "Doubao Speech Synthesis 2.0 (Seed-TTS 2.0): natural, expressive Mandarin and English speech with official 2.0 voices.",
"seedance-1-5-pro-251215.description": "Seedance 1.5 Pro by ByteDance supports text-to-video, image-to-video (first frame, first+last frame), and audio generation synchronized with visuals.",
"seedream-5-0-260128.description": "ByteDance-Seedream-5.0-lite by BytePlus features web-retrieval-augmented generation for real-time information, enhanced complex prompt interpretation, and improved reference consistency for professional visual creation.",
"sensenova-6.7-flash-lite.description": "A lightweight multimodal agent model designed for real-world workflows, supporting both text-based conversations and image understanding. Lightweight and efficient, balancing performance, cost, and deployability. Native multimodal architecture with support for image understanding, including OCR and chart interpretation. Enhanced for office and productivity scenarios, with stable support for complex long-chain tasks. Improved token efficiency, enabling better cost control for complex workloads. Context length of 256K tokens (maximum input: 252K, maximum output: 64K)",
diff --git a/locales/en-US/providers.json b/locales/en-US/providers.json
index 4682d144521..4b86225107a 100644
--- a/locales/en-US/providers.json
+++ b/locales/en-US/providers.json
@@ -19,9 +19,11 @@
"cometapi.description": "CometAPI provides access to frontier models from OpenAI, Anthropic, Google, and more, letting users choose the best model and pricing for diverse use cases.",
"comfyui.description": "A powerful open-source workflow engine for image, video, and audio generation, supporting models like SD, FLUX, Qwen, Hunyuan, and WAN with node-based editing and private deployment.",
"deepseek.description": "DeepSeek focuses on AI research and applications. Its latest DeepSeek V4 family ships in Flash and Pro variants with a 1M context window and hybrid thinking — competitive with leading closed frontier models on reasoning and agent benchmarks.",
+ "doubaospeech.description": "Doubao Speech (ByteDance Volcengine) synthesizes natural Mandarin and English speech with the Seed-TTS 2.0 model and official voices.",
"elevenlabs.description": "ElevenLabs is an AI audio company whose text-to-speech models generate lifelike, expressive speech in 90+ languages, with a large voice library and voice cloning.",
"fal.description": "A generative media platform built for developers.",
"fireworksai.description": "Fireworks AI provides advanced language model services with function calling and multimodal processing. Firefunction V2 (based on Llama-3) is optimized for function calls, chat, and instruction following, while FireLLaVA-13B supports mixed image-text inputs. Other notable models include the Llama and Mixtral families.",
+ "fishaudio.description": "Fish Audio offers expressive multilingual text-to-speech (S2.1 Pro, Drama 3) with natural-language delivery directions and voice cloning.",
"giteeai.description": "Gitee AI Serverless APIs provide plug-and-play LLM inference services for developers.",
"github.description": "With GitHub Models, developers can build as AI engineers using industry-leading models.",
"githubcopilot.description": "Access Claude, GPT, and Gemini models through your GitHub Copilot subscription.",
diff --git a/locales/zh-CN/modelProvider.json b/locales/zh-CN/modelProvider.json
index de1080a4b4b..9f800f752a3 100644
--- a/locales/zh-CN/modelProvider.json
+++ b/locales/zh-CN/modelProvider.json
@@ -114,6 +114,15 @@
"createNewAiProvider.sdkType.required": "请选择 SDK 类型",
"createNewAiProvider.sdkType.title": "请求格式",
"createNewAiProvider.title": "创建自定义 AI 服务商",
+ "doubaospeech.accessToken.desc": "仅旧版语音控制台:与 App ID 配套的 Access Token。使用 API Key 时留空",
+ "doubaospeech.accessToken.placeholder": "Access Token",
+ "doubaospeech.accessToken.title": "Access Token(旧版控制台)",
+ "doubaospeech.apiKey.desc": "火山引擎新版语音控制台「API Key 管理」中的 API Key。推荐使用,填写后优先于 App ID + Access Token",
+ "doubaospeech.apiKey.placeholder": "豆包语音 API Key",
+ "doubaospeech.apiKey.title": "API Key",
+ "doubaospeech.appId.desc": "仅旧版语音控制台:应用的 App ID,需与 Access Token 一起填写",
+ "doubaospeech.appId.placeholder": "App ID",
+ "doubaospeech.appId.title": "App ID(旧版控制台)",
"github.personalAccessToken.desc": "填入你的 Github PAT,点击 [这里](https://github.com/settings/tokens) 创建",
"github.personalAccessToken.placeholder": "ghp_xxxxxx",
"github.personalAccessToken.title": "Github PAT",
diff --git a/locales/zh-CN/models.json b/locales/zh-CN/models.json
index b9ceece506a..d61ce776e9a 100644
--- a/locales/zh-CN/models.json
+++ b/locales/zh-CN/models.json
@@ -450,6 +450,7 @@
"doubao-seedream-4-0-250828.description": "Seedream 4.0 是字节跳动 Seed 推出的图像生成模型,支持文本与图像输入,具备高度可控的高质量图像生成能力。可根据文本提示生成图像。",
"doubao-seedream-4-5-251128.description": "Seedream 4.5是字节跳动最新的多模态图像模型,集成了文本生成图像、图像生成图像和批量图像生成功能,同时具备常识和推理能力。与之前的4.0版本相比,生成质量显著提升,编辑一致性和多图融合效果更好。它对视觉细节的控制更加精确,能够更自然地生成小文字和小面部,并实现更和谐的布局和色彩,提升整体美感。",
"doubao-seedream-5-0-260128.description": "Doubao-Seedream-5.0-lite是字节跳动最新的图像生成模型。首次集成在线检索功能,能够结合实时网络信息,提升生成图像的时效性。模型智能性也得到升级,能够精确解析复杂指令和视觉内容。此外,它在专业场景中的全球知识覆盖、参考一致性和生成质量方面均有提升,更好地满足企业级视觉创作需求。",
+ "drama-3.description": "Fish Audio 表现力最强的模型:逐句用自然语言导演表演,可加入音效、停顿和逐词标签。",
"dreamina-seedance-2-0-260128.description": "字节跳动推出的 Seedance 2.0 是最强大的视频生成模型,支持多模态参考视频生成、视频编辑、视频扩展、文本生成视频以及图像生成视频,并同步生成音频。",
"dreamina-seedance-2-0-fast-260128.description": "字节跳动推出的 Seedance 2.0 Fast 提供与 Seedance 2.0 相同的功能,但生成速度更快,价格更具竞争力。",
"eleven_flash_v2.description": "仅支持英语的超低延迟(约 135 ms)语音模型,适用于实时场景。单次请求最多 30,000 个字符。",
@@ -1308,6 +1309,10 @@
"qwq.description": "QwQ 是 Qwen 系列中的推理模型。相比标准指令微调模型,具备更强的思维与推理能力,显著提升下游复杂任务表现。QwQ-32B 是一款中型推理模型,性能可媲美 DeepSeek-R1 和 o1-mini 等顶级模型。",
"qwq_32b.description": "Qwen 系列中的中型推理模型。相比标准指令微调模型,QwQ 的思维与推理能力显著提升下游复杂任务表现。",
"r1-1776.description": "R1-1776 是 DeepSeek R1 的后训练版本,旨在提供无审查、无偏见的真实信息。",
+ "s1.description": "已弃用的语音模型,支持 13 种语言与(圆括号)情绪标签。Fish Audio 将于 2026-12-31 下线,之后改由 S2.1 Pro 处理请求。",
+ "s2-pro.description": "上一代开源权重语音模型,支持 80 多种语言与 [方括号] 演绎指令。",
+ "s2.1-pro.description": "Fish Audio 推荐的生产级语音模型:支持 80 多种语言,可用自然语言 [指令] 控制演绎,支持多说话人与声音克隆。",
+ "seed-tts-2.0.description": "豆包语音合成模型 2.0(Seed-TTS 2.0):使用官方 2.0 音色,合成自然、富有表现力的中英文语音。",
"seedance-1-5-pro-251215.description": "字节跳动推出的 Seedance 1.5 Pro 支持文本生成视频、图像生成视频(首帧、首+尾帧)以及与视觉同步的音频生成。",
"seedream-5-0-260128.description": "字节跳动 BytePlus 推出的 Seedream 5.0-lite,支持基于网络检索增强的实时信息生成,改进复杂提示的解析能力,并提升参考一致性,适用于专业视觉创作。",
"sensenova-6.7-flash-lite.description": "一款为真实工作流设计的轻量级多模态代理模型,支持基于文本的对话和图像理解。轻量高效,平衡性能、成本和可部署性。原生多模态架构,支持图像理解,包括OCR和图表解析。针对办公和生产力场景进行了增强,稳定支持复杂的长链任务。改进了令牌效率,为复杂工作负载提供更好的成本控制。上下文长度为256K令牌(最大输入:252K,最大输出:64K)。",
diff --git a/locales/zh-CN/providers.json b/locales/zh-CN/providers.json
index 52c1de8b328..04a8b755961 100644
--- a/locales/zh-CN/providers.json
+++ b/locales/zh-CN/providers.json
@@ -19,9 +19,11 @@
"cometapi.description": "CometAPI 提供对 OpenAI、Anthropic、Google 等前沿模型的访问,用户可根据不同需求选择最优模型与价格。",
"comfyui.description": "一个强大的开源工作流引擎,支持图像、视频和音频生成,兼容 SD、FLUX、Qwen、混元、WAN 等模型,支持节点式编辑与私有部署。",
"deepseek.description": "DeepSeek 专注于人工智能研究与应用。其最新的 DeepSeek V4 系列包含 Flash 和 Pro 两个版本,具备 100 万上下文窗口和混合式思维能力,在推理与智能体基准测试中可与领先的闭源前沿模型竞争。",
+ "doubaospeech.description": "豆包语音(字节跳动火山引擎)基于 Seed-TTS 2.0 模型与官方音色,合成自然的中英文语音。",
"elevenlabs.description": "ElevenLabs 是一家 AI 音频公司,其文本转语音模型可生成 90 多种语言的逼真、富有表现力的语音,并提供丰富的音色库与声音克隆能力。",
"fal.description": "一个为开发者打造的生成式媒体平台。",
"fireworksai.description": "Fireworks AI 提供先进的语言模型服务,支持函数调用与多模态处理。Firefunction V2(基于 Llama-3)优化了函数调用、对话与指令执行,FireLLaVA-13B 支持图文混合输入,另有 Llama 与 Mixtral 系列模型。",
+ "fishaudio.description": "Fish Audio 提供富有表现力的多语种语音合成(S2.1 Pro、Drama 3),支持用自然语言指导演绎,并支持声音克隆。",
"giteeai.description": "Gitee AI Serverless API 为开发者提供即插即用的大模型推理服务。",
"github.description": "通过 GitHub Models,开发者可使用行业领先模型构建 AI 工程项目。",
"githubcopilot.description": "通过您的 GitHub Copilot 订阅访问 Claude、GPT 和 Gemini 模型。",
diff --git a/packages/env/src/llm.ts b/packages/env/src/llm.ts
index 145fbd47a49..c3d9d309e45 100644
--- a/packages/env/src/llm.ts
+++ b/packages/env/src/llm.ts
@@ -59,6 +59,14 @@ export const getLLMConfig = () => {
ENABLED_ELEVENLABS: z.boolean(),
ELEVENLABS_API_KEY: z.string().optional(),
+ ENABLED_FISHAUDIO: z.boolean(),
+ FISHAUDIO_API_KEY: z.string().optional(),
+
+ ENABLED_DOUBAOSPEECH: z.boolean(),
+ DOUBAOSPEECH_API_KEY: z.string().optional(),
+ DOUBAOSPEECH_APP_ID: z.string().optional(),
+ DOUBAOSPEECH_ACCESS_TOKEN: z.string().optional(),
+
ENABLED_MISTRAL: z.boolean(),
MISTRAL_API_KEY: z.string().optional(),
@@ -309,6 +317,16 @@ export const getLLMConfig = () => {
ENABLED_ELEVENLABS: !!process.env.ELEVENLABS_API_KEY,
ELEVENLABS_API_KEY: process.env.ELEVENLABS_API_KEY,
+ ENABLED_FISHAUDIO: !!process.env.FISHAUDIO_API_KEY,
+ FISHAUDIO_API_KEY: process.env.FISHAUDIO_API_KEY,
+
+ ENABLED_DOUBAOSPEECH:
+ !!process.env.DOUBAOSPEECH_API_KEY ||
+ (!!process.env.DOUBAOSPEECH_APP_ID && !!process.env.DOUBAOSPEECH_ACCESS_TOKEN),
+ DOUBAOSPEECH_API_KEY: process.env.DOUBAOSPEECH_API_KEY,
+ DOUBAOSPEECH_APP_ID: process.env.DOUBAOSPEECH_APP_ID,
+ DOUBAOSPEECH_ACCESS_TOKEN: process.env.DOUBAOSPEECH_ACCESS_TOKEN,
+
ENABLED_MISTRAL: !!process.env.MISTRAL_API_KEY,
MISTRAL_API_KEY: process.env.MISTRAL_API_KEY,
diff --git a/packages/locales/src/default/modelProvider.ts b/packages/locales/src/default/modelProvider.ts
index 0791e8b8aec..c146a5269e4 100644
--- a/packages/locales/src/default/modelProvider.ts
+++ b/packages/locales/src/default/modelProvider.ts
@@ -62,6 +62,18 @@ export default {
'cloudflare.baseURLOrAccountID.desc': 'Enter your Cloudflare account ID or custom API address',
'cloudflare.baseURLOrAccountID.placeholder': 'Cloudflare Account ID / custom API URL',
'cloudflare.baseURLOrAccountID.title': 'Cloudflare Account ID / API Address',
+ 'doubaospeech.accessToken.desc':
+ 'Legacy speech console only: the Access Token paired with the App ID. Leave empty when using an API Key',
+ 'doubaospeech.accessToken.placeholder': 'Access Token',
+ 'doubaospeech.accessToken.title': 'Access Token (legacy console)',
+ 'doubaospeech.apiKey.desc':
+ 'API Key from the new Volcengine speech console (API Key management). Recommended; it takes precedence over App ID + Access Token',
+ 'doubaospeech.apiKey.placeholder': 'Doubao Speech API Key',
+ 'doubaospeech.apiKey.title': 'API Key',
+ 'doubaospeech.appId.desc':
+ 'Legacy speech console only: the App ID of your application, used together with the Access Token',
+ 'doubaospeech.appId.placeholder': 'App ID',
+ 'doubaospeech.appId.title': 'App ID (legacy console)',
'comfyui.apiKey.desc': 'API key for Bearer Token authentication',
'comfyui.apiKey.placeholder': 'Enter API key',
'comfyui.apiKey.required': 'Please enter the API key',
diff --git a/packages/model-bank/package.json b/packages/model-bank/package.json
index 8ba551e4021..bc7bb3b0c50 100644
--- a/packages/model-bank/package.json
+++ b/packages/model-bank/package.json
@@ -32,9 +32,11 @@
"./cometapi": "./src/aiModels/cometapi.ts",
"./comfyui": "./src/aiModels/comfyui.ts",
"./deepseek": "./src/aiModels/deepseek.ts",
+ "./doubaospeech": "./src/aiModels/doubaospeech.ts",
"./elevenlabs": "./src/aiModels/elevenlabs.ts",
"./fal": "./src/aiModels/fal.ts",
"./fireworksai": "./src/aiModels/fireworksai.ts",
+ "./fishaudio": "./src/aiModels/fishaudio.ts",
"./giteeai": "./src/aiModels/giteeai.ts",
"./github": "./src/aiModels/github.ts",
"./githubCopilot": "./src/aiModels/githubCopilot.ts",
diff --git a/packages/model-bank/src/aiModels/doubaospeech.ts b/packages/model-bank/src/aiModels/doubaospeech.ts
new file mode 100644
index 00000000000..4bec55d2964
--- /dev/null
+++ b/packages/model-bank/src/aiModels/doubaospeech.ts
@@ -0,0 +1,28 @@
+import { doubaoSpeech20Voices, doubaoSpeechTTSSchema } from '../const/ttsParameters';
+import type { AITTSModelCard } from '../types/aiModel';
+
+// Pay-as-you-go price of Doubao Speech Synthesis 2.0: 3 CNY per 10,000 characters, every
+// character (Han, letter, punctuation, space) counting as one. The model id is the V3
+// `X-Api-Resource-Id`; 1.0 voices need another resource and are not offered.
+// @see https://www.volcengine.com/docs/6561/1359370
+const doubaoSpeechTTSModels: AITTSModelCard[] = [
+ {
+ description:
+ 'Doubao Speech Synthesis 2.0 (Seed-TTS 2.0): natural, expressive Mandarin and English speech with official 2.0 voices.',
+ displayName: 'Doubao Speech 2.0',
+ enabled: true,
+ id: 'seed-tts-2.0',
+ isOfficial: true,
+ parameters: doubaoSpeechTTSSchema,
+ pricing: {
+ currency: 'CNY',
+ units: [{ name: 'textInput', rate: 300, strategy: 'fixed', unit: 'millionCharacters' }],
+ },
+ type: 'tts',
+ voices: doubaoSpeech20Voices,
+ },
+];
+
+export const allModels = [...doubaoSpeechTTSModels];
+
+export default allModels;
diff --git a/packages/model-bank/src/aiModels/fishaudio.ts b/packages/model-bank/src/aiModels/fishaudio.ts
new file mode 100644
index 00000000000..5da1648dffb
--- /dev/null
+++ b/packages/model-bank/src/aiModels/fishaudio.ts
@@ -0,0 +1,96 @@
+import {
+ fishAudioDirectedTTSSchema,
+ fishAudioTTSSchema,
+ fishAudioTTSVoices,
+} from '../const/ttsParameters';
+import type { AITTSModelCard } from '../types/aiModel';
+
+// API prices per million UTF-8 bytes: $15 for S2.1 Pro, S2 Pro and S1, $50 for Drama 3
+// ($10 launch promotion until 2026-12-01 08:00 UTC, see below). The runtime reports the UTF-8 byte count as
+// `inputCharacters`, so `millionCharacters` here bills exactly what Fish Audio bills.
+// `s2.1-pro-free` is left out: it is free only for a limited time.
+// @see https://docs.fish.audio/developer-guide/models-pricing/pricing-and-rate-limits
+// @see https://docs.fish.audio/developer-guide/models-pricing/models-overview
+
+/** End of the Drama 3 launch promotion: 2026-12-01 08:00 UTC. */
+export const FISH_AUDIO_DRAMA_3_PROMOTION_END = Date.UTC(2026, 11, 1, 8);
+
+/**
+ * Drama 3 price per million UTF-8 bytes at `now`: Fish Audio bills the $10 launch price until
+ * the promotion ends, then the $50 list price. The card reads it on every pricing lookup,
+ * so a long-running process switches to the list price at the cutoff without a code change.
+ */
+export const getFishAudioDrama3Rate = (now = Date.now()) =>
+ now < FISH_AUDIO_DRAMA_3_PROMOTION_END ? 10 : 50;
+
+const fishAudioTTSModels: AITTSModelCard[] = [
+ {
+ description:
+ 'Fish Audio’s recommended production speech model: 80+ languages, natural-language [directions] for delivery, multi-speaker and voice cloning.',
+ displayName: 'Fish Audio S2.1 Pro',
+ enabled: true,
+ id: 's2.1-pro',
+ isOfficial: true,
+ parameters: fishAudioDirectedTTSSchema,
+ pricing: {
+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],
+ },
+ type: 'tts',
+ voices: fishAudioTTSVoices,
+ },
+ {
+ description:
+ 'Fish Audio’s most expressive model: direct each line in natural language, with sound effects, pauses and per-word tags.',
+ displayName: 'Fish Audio Drama 3',
+ enabled: true,
+ id: 'drama-3',
+ isOfficial: true,
+ parameters: fishAudioDirectedTTSSchema,
+ pricing: {
+ units: [
+ {
+ name: 'textInput',
+ // A getter, so a process loaded before the cutoff reads $50 after it.
+ get rate() {
+ return getFishAudioDrama3Rate();
+ },
+ strategy: 'fixed',
+ unit: 'millionCharacters',
+ },
+ ],
+ },
+ type: 'tts',
+ voices: fishAudioTTSVoices,
+ },
+ {
+ description:
+ 'Previous-generation open-weights speech model with 80+ languages and [bracketed] delivery directions.',
+ displayName: 'Fish Audio S2 Pro',
+ id: 's2-pro',
+ isOfficial: true,
+ parameters: fishAudioDirectedTTSSchema,
+ pricing: {
+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],
+ },
+ type: 'tts',
+ voices: fishAudioTTSVoices,
+ },
+ {
+ description:
+ 'Deprecated speech model with 13 languages and (parenthesis) emotion tags. Fish Audio retires it on 2026-12-31 and then serves requests with S2.1 Pro.',
+ displayName: 'Fish Audio S1',
+ id: 's1',
+ isOfficial: true,
+ legacy: true,
+ parameters: fishAudioTTSSchema,
+ pricing: {
+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],
+ },
+ type: 'tts',
+ voices: fishAudioTTSVoices,
+ },
+];
+
+export const allModels = [...fishAudioTTSModels];
+
+export default allModels;
diff --git a/packages/model-bank/src/aiModels/index.ts b/packages/model-bank/src/aiModels/index.ts
index 6cf3f037d66..f70a888a4a1 100644
--- a/packages/model-bank/src/aiModels/index.ts
+++ b/packages/model-bank/src/aiModels/index.ts
@@ -21,9 +21,11 @@ import { default as cohere } from './cohere';
import { default as cometapi } from './cometapi';
import { default as comfyui } from './comfyui';
import { default as deepseek } from './deepseek';
+import { default as doubaospeech } from './doubaospeech';
import { default as elevenlabs } from './elevenlabs';
import { default as fal } from './fal';
import { default as fireworksai } from './fireworksai';
+import { default as fishaudio } from './fishaudio';
import { default as giteeai } from './giteeai';
import { default as github } from './github';
import { default as githubcopilot } from './githubCopilot';
@@ -136,9 +138,11 @@ const staticModelMap: ModelsMap = {
cometapi,
comfyui,
deepseek,
+ doubaospeech,
elevenlabs,
fal,
fireworksai,
+ fishaudio,
giteeai,
github,
githubcopilot,
@@ -257,9 +261,11 @@ export { default as cohere } from './cohere';
export { default as cometapi } from './cometapi';
export { default as comfyui } from './comfyui';
export { default as deepseek } from './deepseek';
+export { default as doubaospeech } from './doubaospeech';
export { default as elevenlabs } from './elevenlabs';
export { default as fal, fluxSchnellParamsSchema } from './fal';
export { default as fireworksai } from './fireworksai';
+export { default as fishaudio } from './fishaudio';
export { default as giteeai } from './giteeai';
export { default as github } from './github';
export { default as githubcopilot } from './githubCopilot';
diff --git a/packages/model-bank/src/const/__tests__/ttsParameters.fishDoubao.test.ts b/packages/model-bank/src/const/__tests__/ttsParameters.fishDoubao.test.ts
new file mode 100644
index 00000000000..b6abf857b5e
--- /dev/null
+++ b/packages/model-bank/src/const/__tests__/ttsParameters.fishDoubao.test.ts
@@ -0,0 +1,168 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { loadModels } from '../../aiModels';
+import doubaospeechModels from '../../aiModels/doubaospeech';
+import fishaudioModels, {
+ FISH_AUDIO_DRAMA_3_PROMOTION_END,
+ getFishAudioDrama3Rate,
+} from '../../aiModels/fishaudio';
+import {
+ TTSVoiceSchema,
+ validateTTSModelParamsSchema,
+ validateTTSParams,
+} from '../../standard-parameters';
+import type { AITTSModelCard } from '../../types/aiModel';
+import {
+ DOUBAO_SPEECH_DEFAULT_VOICE_ID,
+ DOUBAO_SPEECH_VOICE_IDS,
+ FISH_AUDIO_DEFAULT_VOICE_ID,
+} from '../ttsParameters';
+
+const fishCards = fishaudioModels as AITTSModelCard[];
+const doubaoCards = doubaospeechModels as AITTSModelCard[];
+
+describe.each([
+ ['Fish Audio', fishCards],
+ ['Doubao Speech', doubaoCards],
+])('%s TTS model cards', (_, cards) => {
+ it.each(cards.map((card) => [card.id, card]))(
+ '%s declares parameters, a valid voice catalog and per-character pricing',
+ (_id, card) => {
+ expect(card.type).toBe('tts');
+ expect(card.isOfficial).toBe(true);
+ expect(() => validateTTSModelParamsSchema(card.parameters)).not.toThrow();
+
+ expect(card.voices?.length).toBeGreaterThan(0);
+ for (const voice of card.voices!) expect(() => TTSVoiceSchema.parse(voice)).not.toThrow();
+
+ const voiceIds = card.voices!.map((voice) => voice.id);
+ expect(voiceIds).toContain(card.parameters!.voice!.default);
+ expect(new Set(voiceIds).size).toBe(voiceIds.length);
+
+ expect(card.pricing?.units).toEqual([
+ expect.objectContaining({
+ name: 'textInput',
+ strategy: 'fixed',
+ unit: 'millionCharacters',
+ }),
+ ]);
+ // aac and flac are produced by neither vendor.
+ expect(card.parameters!.format!.enum).not.toContain('aac');
+ expect(card.parameters!.format!.enum).not.toContain('flac');
+ },
+ );
+});
+
+describe('Fish Audio TTS model cards', () => {
+ it('lists S2.1 Pro, Drama 3 (enabled), S2 Pro and the legacy S1 at official prices', () => {
+ expect(
+ fishCards.map(({ enabled, id, legacy, pricing }) => ({
+ enabled: !!enabled,
+ id,
+ legacy: !!legacy,
+ rate: (pricing!.units[0] as { rate: number }).rate,
+ })),
+ ).toEqual([
+ { enabled: true, id: 's2.1-pro', legacy: false, rate: 15 },
+ { enabled: true, id: 'drama-3', legacy: false, rate: getFishAudioDrama3Rate() },
+ { enabled: false, id: 's2-pro', legacy: false, rate: 15 },
+ { enabled: false, id: 's1', legacy: true, rate: 15 },
+ ]);
+ expect(fishCards.every((card) => !card.pricing?.currency)).toBe(true);
+ });
+
+ it('prices Drama 3 at the $10 launch promotion until 2026-12-01 08:00 UTC, then $50', () => {
+ expect(FISH_AUDIO_DRAMA_3_PROMOTION_END).toBe(Date.parse('2026-12-01T08:00:00Z'));
+ expect(getFishAudioDrama3Rate(Date.parse('2026-11-13T00:00:00Z'))).toBe(10);
+ expect(getFishAudioDrama3Rate(FISH_AUDIO_DRAMA_3_PROMOTION_END - 1)).toBe(10);
+ expect(getFishAudioDrama3Rate(FISH_AUDIO_DRAMA_3_PROMOTION_END)).toBe(50);
+ expect(getFishAudioDrama3Rate(Date.parse('2027-01-01T00:00:00Z'))).toBe(50);
+ });
+
+ describe('Drama 3 card rate across the promotion cutoff', () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('reads the rate at lookup time, so a catalog loaded before the cutoff bills $50 after it', () => {
+ const unit = fishCards.find((card) => card.id === 'drama-3')!.pricing!.units[0] as {
+ rate: number;
+ };
+
+ vi.useFakeTimers();
+ vi.setSystemTime(FISH_AUDIO_DRAMA_3_PROMOTION_END - 60_000);
+ expect(unit.rate).toBe(10);
+ expect({ ...unit }.rate).toBe(10);
+
+ vi.setSystemTime(FISH_AUDIO_DRAMA_3_PROMOTION_END);
+ expect(unit.rate).toBe(50);
+ expect(JSON.parse(JSON.stringify(unit)).rate).toBe(50);
+ });
+
+ it('keeps the rate live through loadModels()', async () => {
+ const models = await loadModels();
+ const rateOf = () =>
+ (
+ models.find((card) => card.providerId === 'fishaudio' && card.id === 'drama-3')!.pricing!
+ .units[0] as { rate: number }
+ ).rate;
+
+ vi.useFakeTimers();
+ vi.setSystemTime(FISH_AUDIO_DRAMA_3_PROMOTION_END - 1);
+ expect(rateOf()).toBe(10);
+ vi.setSystemTime(FISH_AUDIO_DRAMA_3_PROMOTION_END + 1);
+ expect(rateOf()).toBe(50);
+ });
+ });
+
+ it('bundles no community voices, only the Fish Audio default', () => {
+ for (const card of fishCards) {
+ expect(card.voices!.map((voice) => voice.id)).toEqual([FISH_AUDIO_DEFAULT_VOICE_ID]);
+ }
+ });
+
+ it('accepts speed 0.5–2 and directions only on the S2 family and Drama 3', () => {
+ const byId = Object.fromEntries(fishCards.map((card) => [card.id, card]));
+
+ expect(validateTTSParams(byId['s2.1-pro'].parameters!, { speed: 2 })).toEqual([]);
+ expect(validateTTSParams(byId['s2.1-pro'].parameters!, { speed: 2.5 })).not.toEqual([]);
+ expect(validateTTSParams(byId['drama-3'].parameters!, { instructions: 'calm' })).toEqual([]);
+ expect(validateTTSParams(byId['s1'].parameters!, { instructions: 'calm' })).not.toEqual([]);
+ expect(validateTTSParams(byId['s2.1-pro'].parameters!, { pitch: 1 })).not.toEqual([]);
+ });
+});
+
+describe('Doubao Speech TTS model cards', () => {
+ it('lists Seed-TTS 2.0 priced at 300 CNY per million characters', () => {
+ expect(doubaoCards).toHaveLength(1);
+ expect(doubaoCards[0]).toMatchObject({
+ enabled: true,
+ id: 'seed-tts-2.0',
+ pricing: {
+ currency: 'CNY',
+ units: [{ name: 'textInput', rate: 300, strategy: 'fixed', unit: 'millionCharacters' }],
+ },
+ });
+ });
+
+ it('only bundles official 2.0 voices, which the seed-tts-2.0 resource can speak', () => {
+ const voices = doubaoCards[0].voices!;
+
+ expect(voices.every((voice) => voice.id.endsWith('_uranus_bigtts'))).toBe(true);
+ expect(voices.map((voice) => voice.id)).toEqual([...DOUBAO_SPEECH_VOICE_IDS]);
+ expect(voices[0].id).toBe(DOUBAO_SPEECH_DEFAULT_VOICE_ID);
+ expect(voices.some((voice) => voice.language === 'zh-CN')).toBe(true);
+ expect(voices.some((voice) => voice.language.startsWith('en'))).toBe(true);
+ });
+
+ it('validates speed, volume and pitch ranges before the request', () => {
+ const schema = doubaoCards[0].parameters!;
+
+ expect(validateTTSParams(schema, { pitch: -12, speed: 0.5, volume: 2 })).toEqual([]);
+ expect(validateTTSParams(schema, { speed: 3 })).not.toEqual([]);
+ expect(validateTTSParams(schema, { volume: 0.1 })).not.toEqual([]);
+ expect(validateTTSParams(schema, { pitch: 13 })).not.toEqual([]);
+ expect(validateTTSParams(schema, { sampleRate: 12_345 })).not.toEqual([]);
+ expect(validateTTSParams(schema, { emotion: 'happy' })).not.toEqual([]);
+ });
+});
diff --git a/packages/model-bank/src/const/modelProvider.ts b/packages/model-bank/src/const/modelProvider.ts
index f211be0ee4a..ba23a7728d9 100644
--- a/packages/model-bank/src/const/modelProvider.ts
+++ b/packages/model-bank/src/const/modelProvider.ts
@@ -19,9 +19,11 @@ export enum ModelProvider {
CometAPI = 'cometapi',
ComfyUI = 'comfyui',
DeepSeek = 'deepseek',
+ DoubaoSpeech = 'doubaospeech',
ElevenLabs = 'elevenlabs',
Fal = 'fal',
FireworksAI = 'fireworksai',
+ FishAudio = 'fishaudio',
GiteeAI = 'giteeai',
Github = 'github',
GithubCopilot = 'githubcopilot',
diff --git a/packages/model-bank/src/const/ttsParameters.ts b/packages/model-bank/src/const/ttsParameters.ts
index 35147111a1c..dcf65b32674 100644
--- a/packages/model-bank/src/const/ttsParameters.ts
+++ b/packages/model-bank/src/const/ttsParameters.ts
@@ -364,6 +364,187 @@ export const elevenlabsExpressiveTTSSchema: TTSModelParamsSchema = {
voice: { default: ELEVENLABS_DEFAULT_VOICE },
};
+/**
+ * Sentinel voice id: Fish Audio speaks with its default voice when a request carries no
+ * `reference_id`, so the runtime omits the field for this id.
+ * @see https://docs.fish.audio/developer-guide/getting-started/quickstart
+ */
+export const FISH_AUDIO_DEFAULT_VOICE_ID = 'default';
+
+/**
+ * Fish Audio publishes no catalog of voices it owns: the Voice Library is mostly
+ * community uploads, including unlicensed character and real-person clones, so none of it
+ * is bundled. The built-in entry is Fish Audio's own default voice; callers pass the
+ * `reference_id` of a voice they cloned or are licensed to use as `voice`.
+ */
+export const fishAudioTTSVoices: TTSVoice[] = [
+ {
+ description: 'The voice Fish Audio uses when no reference voice is given',
+ displayName: 'Fish Audio default',
+ gender: 'neutral',
+ id: FISH_AUDIO_DEFAULT_VOICE_ID,
+ language: 'multilingual',
+ },
+];
+
+/**
+ * Sample rates `/v1/tts` accepts per format; omitted, each format uses its own default
+ * (44.1 kHz, or 48 kHz for opus).
+ * @see https://docs.fish.audio/api-reference/endpoint/openapi-v1/text-to-speech
+ */
+export const FISH_AUDIO_SAMPLE_RATES: Record<'mp3' | 'opus' | 'pcm' | 'wav', number[]> = {
+ mp3: [32_000, 44_100],
+ opus: [48_000],
+ pcm: [8000, 16_000, 24_000, 32_000, 44_100],
+ wav: [8000, 16_000, 24_000, 32_000, 44_100],
+};
+
+/** `format`: mp3, wav, pcm and opus; there is no aac or flac output. */
+const FISH_AUDIO_TTS_FORMATS = TTS_AUDIO_FORMATS.filter(
+ (format) => format !== 'aac' && format !== 'flac',
+);
+
+/**
+ * Characters per Fish Audio request. The audio comes back in one inline response, so a
+ * longer request would exceed the serverless response limit only after the synthesis was
+ * billed. Enforced by the Fish Audio runtime and by the OpenAI-compatible path for gateway
+ * routes (`fish-audio/*`), so routed aliases are capped too.
+ */
+export const FISH_AUDIO_MAX_INPUT_CHARACTERS = 4096;
+
+/** Upper bound of the delivery direction placed in front of the text. */
+export const FISH_AUDIO_MAX_INSTRUCTIONS_LENGTH = 200;
+
+/** S1 takes `prosody.speed` from 0.5 to 2 but no bracketed delivery directions. */
+export const fishAudioTTSSchema: TTSModelParamsSchema = {
+ format: { default: 'mp3', enum: FISH_AUDIO_TTS_FORMATS },
+ sampleRate: {
+ default: 44_100,
+ description: 'mp3: 32000 or 44100; opus: 48000; wav and pcm: 8000 to 44100',
+ enum: [...new Set(Object.values(FISH_AUDIO_SAMPLE_RATES).flat())].sort((a, b) => a - b),
+ },
+ speed: { default: 1, max: 2, min: 0.5, step: 0.05 },
+ voice: { default: FISH_AUDIO_DEFAULT_VOICE_ID },
+};
+
+/**
+ * The S2 family and Drama 3 follow natural-language `[directions]` written into the text;
+ * `instructions` is sent that way, in front of the input, and is billed with it.
+ * @see https://docs.fish.audio/features/text-to-speech/drama-3
+ */
+export const fishAudioDirectedTTSSchema: TTSModelParamsSchema = {
+ ...fishAudioTTSSchema,
+ instructions: { default: '', maxLength: FISH_AUDIO_MAX_INSTRUCTIONS_LENGTH },
+};
+
+/**
+ * Official Doubao Speech 2.0 voices (`*_uranus_bigtts`), which only the `seed-tts-2.0`
+ * resource can speak. Voice clones (`S_*`) belong to the account and are passed by id.
+ * @see https://www.volcengine.com/docs/6561/1257544
+ */
+export const doubaoSpeech20Voices: TTSVoice[] = [
+ {
+ description: 'Lively, multilingual',
+ displayName: 'Vivi 2.0',
+ gender: 'female',
+ id: 'zh_female_vv_uranus_bigtts',
+ language: 'multilingual',
+ },
+ {
+ displayName: '小何 2.0',
+ gender: 'female',
+ id: 'zh_female_xiaohe_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ { displayName: '云舟 2.0', gender: 'male', id: 'zh_male_m191_uranus_bigtts', language: 'zh-CN' },
+ {
+ displayName: '小天 2.0',
+ gender: 'male',
+ id: 'zh_male_taocheng_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ {
+ displayName: '团子 2.0',
+ gender: 'female',
+ id: 'zh_female_tuanzi_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ {
+ displayName: '爽快思思 2.0',
+ gender: 'female',
+ id: 'zh_female_shuangkuaisisi_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ {
+ displayName: '知性灿灿 2.0',
+ gender: 'female',
+ id: 'zh_female_cancan_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ {
+ displayName: '清新女声 2.0',
+ gender: 'female',
+ id: 'zh_female_qingxinnvsheng_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ {
+ displayName: '暖阳女声 2.0',
+ gender: 'female',
+ id: 'zh_female_kefunvsheng_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ {
+ displayName: '深夜播客 2.0',
+ gender: 'male',
+ id: 'zh_male_shenyeboke_uranus_bigtts',
+ language: 'zh-CN',
+ },
+ { displayName: 'Tim', gender: 'male', id: 'en_male_tim_uranus_bigtts', language: 'en-US' },
+ {
+ displayName: 'Dacey',
+ gender: 'female',
+ id: 'en_female_dacey_uranus_bigtts',
+ language: 'en-US',
+ },
+ {
+ displayName: 'Stokie',
+ gender: 'female',
+ id: 'en_female_stokie_uranus_bigtts',
+ language: 'en-US',
+ },
+ { displayName: 'Alex', gender: 'male', id: 'en_male_alex_uranus_bigtts', language: 'en-US' },
+ {
+ displayName: 'Charlotte',
+ gender: 'female',
+ id: 'en_female_authoritative-british_uranus_bigtts',
+ language: 'en-GB',
+ },
+ { displayName: 'Ryan', gender: 'male', id: 'en_male_ryan_uranus_bigtts', language: 'en-US' },
+];
+
+/** Vivi 2.0, the voice of the official Seed-TTS 2.0 examples. */
+export const DOUBAO_SPEECH_DEFAULT_VOICE_ID = 'zh_female_vv_uranus_bigtts';
+
+/** Voice ids in the built-in Doubao Speech catalog. */
+export const DOUBAO_SPEECH_VOICE_IDS: ReadonlySet<string> = new Set(
+ doubaoSpeech20Voices.map((voice) => voice.id),
+);
+
+/**
+ * V3 `audio_params`: format mp3 / ogg_opus / pcm / wav (opus is always 48 kHz),
+ * `speech_rate` and `loudness_rate` from -50 to 100 (0.5x to 2x), and
+ * `post_process.pitch` from -12 to 12 semitones.
+ * @see https://www.volcengine.com/docs/6561/2528925
+ */
+export const doubaoSpeechTTSSchema: TTSModelParamsSchema = {
+ format: { default: 'mp3', enum: ['mp3', 'opus', 'wav', 'pcm'] },
+ pitch: { default: 0, max: 12, min: -12, step: 1 },
+ sampleRate: { default: 24_000, enum: [8000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000] },
+ speed: { default: 1, max: 2, min: 0.5, step: 0.05 },
+ voice: { default: DOUBAO_SPEECH_DEFAULT_VOICE_ID },
+ volume: { default: 1, max: 2, min: 0.5, step: 0.05 },
+};
+
/**
* Gemini TTS prebuilt voices, shared by every Gemini TTS model. Descriptions are Google's
* own one-word characterizations; genders follow the matching Chirp 3 HD voices.
diff --git a/packages/model-bank/src/index.ts b/packages/model-bank/src/index.ts
index 3252499080c..70de62996ae 100644
--- a/packages/model-bank/src/index.ts
+++ b/packages/model-bank/src/index.ts
@@ -1,7 +1,16 @@
export * from './aiModels';
export * from './const/knowledgeCutoff';
export * from './const/modelProvider';
-export { ELEVENLABS_DEFAULT_VOICE_ID, ELEVENLABS_VOICE_IDS } from './const/ttsParameters';
+export {
+ DOUBAO_SPEECH_DEFAULT_VOICE_ID,
+ DOUBAO_SPEECH_VOICE_IDS,
+ ELEVENLABS_DEFAULT_VOICE_ID,
+ ELEVENLABS_VOICE_IDS,
+ FISH_AUDIO_DEFAULT_VOICE_ID,
+ FISH_AUDIO_MAX_INPUT_CHARACTERS,
+ FISH_AUDIO_MAX_INSTRUCTIONS_LENGTH,
+ FISH_AUDIO_SAMPLE_RATES,
+} from './const/ttsParameters';
export * from './standard-parameters';
export * from './types';
export * from './utils';
diff --git a/packages/model-bank/src/modelProviders/doubaospeech.ts b/packages/model-bank/src/modelProviders/doubaospeech.ts
new file mode 100644
index 00000000000..82d7d58d591
--- /dev/null
+++ b/packages/model-bank/src/modelProviders/doubaospeech.ts
@@ -0,0 +1,29 @@
+import type { ModelProviderCard } from '../types';
+
+/**
+ * Doubao Speech (Volcengine speech synthesis), text-to-speech only. This is a separate
+ * service from Volcengine Ark (`volcengine`), with its own console and credentials: an
+ * API key from the new speech console, or the legacy console's App ID + Access Token.
+ * @see https://www.volcengine.com/docs/6561/2528925
+ */
+const DoubaoSpeech: ModelProviderCard = {
+ apiKeyUrl: 'https://console.volcengine.com/speech/new',
+ chatModels: [],
+ description:
+ 'Doubao Speech (ByteDance Volcengine) synthesizes natural Mandarin and English speech with the Seed-TTS 2.0 model and official voices.',
+ id: 'doubaospeech',
+ modelsUrl: 'https://www.volcengine.com/docs/6561/1257544',
+ name: 'Doubao Speech',
+ settings: {
+ disableBrowserRequest: true,
+ proxyUrl: {
+ placeholder: 'https://openspeech.bytedance.com',
+ },
+ showAddNewModel: false,
+ showChecker: false,
+ showModelFetcher: false,
+ },
+ url: 'https://www.volcengine.com/product/tts',
+};
+
+export default DoubaoSpeech;
diff --git a/packages/model-bank/src/modelProviders/fishaudio.ts b/packages/model-bank/src/modelProviders/fishaudio.ts
new file mode 100644
index 00000000000..f088be2c8c3
--- /dev/null
+++ b/packages/model-bank/src/modelProviders/fishaudio.ts
@@ -0,0 +1,28 @@
+import type { ModelProviderCard } from '../types';
+
+/**
+ * Text-to-speech only. Requests carry the key as `Authorization: Bearer`, and the model is
+ * chosen with the `model` request header.
+ * @see https://docs.fish.audio/api-reference/endpoint/openapi-v1/text-to-speech
+ */
+const FishAudio: ModelProviderCard = {
+ apiKeyUrl: 'https://fish.audio/app/api-keys',
+ chatModels: [],
+ description:
+ 'Fish Audio offers expressive multilingual text-to-speech (S2.1 Pro, Drama 3) with natural-language delivery directions and voice cloning.',
+ id: 'fishaudio',
+ modelsUrl: 'https://docs.fish.audio/developer-guide/models-pricing/models-overview',
+ name: 'Fish Audio',
+ settings: {
+ disableBrowserRequest: true,
+ proxyUrl: {
+ placeholder: 'https://api.fish.audio',
+ },
+ showAddNewModel: false,
+ showChecker: false,
+ showModelFetcher: false,
+ },
+ url: 'https://fish.audio',
+};
+
+export default FishAudio;
diff --git a/packages/model-bank/src/modelProviders/index.ts b/packages/model-bank/src/modelProviders/index.ts
index d033d6d62dd..53f81a3958b 100644
--- a/packages/model-bank/src/modelProviders/index.ts
+++ b/packages/model-bank/src/modelProviders/index.ts
@@ -21,9 +21,11 @@ import CohereProvider from './cohere';
import CometAPIProvider from './cometapi';
import ComfyUIProvider from './comfyui';
import DeepSeekProvider from './deepseek';
+import DoubaoSpeechProvider from './doubaospeech';
import ElevenLabsProvider from './elevenlabs';
import FalProvider from './fal';
import FireworksAIProvider from './fireworksai';
+import FishAudioProvider from './fishaudio';
import GiteeAIProvider from './giteeai';
import GithubProvider from './github';
import GithubCopilotProvider from './githubCopilot';
@@ -174,6 +176,8 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [
OpenRouterProvider,
FalProvider,
ElevenLabsProvider,
+ FishAudioProvider,
+ DoubaoSpeechProvider,
OllamaProvider,
OllamaCloudProvider,
VLLMProvider,
@@ -327,9 +331,11 @@ export { default as CohereProviderCard } from './cohere';
export { default as CometAPIProviderCard } from './cometapi';
export { default as ComfyUIProviderCard } from './comfyui';
export { default as DeepSeekProviderCard } from './deepseek';
+export { default as DoubaoSpeechProviderCard } from './doubaospeech';
export { default as ElevenLabsProviderCard } from './elevenlabs';
export { default as FalProviderCard } from './fal';
export { default as FireworksAIProviderCard } from './fireworksai';
+export { default as FishAudioProviderCard } from './fishaudio';
export { default as GiteeAIProviderCard } from './giteeai';
export { default as GithubProviderCard } from './github';
export { default as GithubCopilotProviderCard } from './githubCopilot';
diff --git a/packages/model-bank/src/modelProviders/ttsSpeechProviders.test.ts b/packages/model-bank/src/modelProviders/ttsSpeechProviders.test.ts
new file mode 100644
index 00000000000..e70bf8f0417
--- /dev/null
+++ b/packages/model-bank/src/modelProviders/ttsSpeechProviders.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest';
+
+import { LOBE_DEFAULT_MODEL_LIST } from '../aiModels';
+import { ModelProvider } from '../const/modelProvider';
+import DoubaoSpeechProviderCard from './doubaospeech';
+import FishAudioProviderCard from './fishaudio';
+import {
+ DEFAULT_MODEL_PROVIDER_LIST,
+ DoubaoSpeechProviderCard as ExportedDoubaoCard,
+ FishAudioProviderCard as ExportedFishCard,
+ getProviderDisplayName,
+ isProviderDisableBrowserRequest,
+} from './index';
+
+describe.each([
+ {
+ apiKeyUrl: 'https://fish.audio/app/api-keys',
+ card: FishAudioProviderCard,
+ enumValue: ModelProvider.FishAudio,
+ exported: ExportedFishCard,
+ id: 'fishaudio',
+ models: ['s2.1-pro', 'drama-3', 's2-pro', 's1'],
+ name: 'Fish Audio',
+ proxy: 'https://api.fish.audio',
+ },
+ {
+ apiKeyUrl: 'https://console.volcengine.com/speech/new',
+ card: DoubaoSpeechProviderCard,
+ enumValue: ModelProvider.DoubaoSpeech,
+ exported: ExportedDoubaoCard,
+ id: 'doubaospeech',
+ models: ['seed-tts-2.0'],
+ name: 'Doubao Speech',
+ proxy: 'https://openspeech.bytedance.com',
+ },
+])('$name provider', ({ apiKeyUrl, card, enumValue, exported, id, models, name, proxy }) => {
+ it(`is registered under the ${id} id`, () => {
+ expect(enumValue).toBe(id);
+ expect(exported).toBe(card);
+ expect(DEFAULT_MODEL_PROVIDER_LIST.filter((item) => item.id === id)).toEqual([card]);
+ expect(getProviderDisplayName(id)).toBe(name);
+ });
+
+ it('is a server-side TTS provider without checker or model fetcher', () => {
+ expect(card).toMatchObject({ apiKeyUrl, chatModels: [], name });
+ expect(card.description).toBeTruthy();
+ expect(card.settings).toMatchObject({
+ proxyUrl: { placeholder: proxy },
+ showAddNewModel: false,
+ showChecker: false,
+ showModelFetcher: false,
+ });
+ expect(card.settings.sdkType).toBeUndefined();
+ expect(card.checkModel).toBeUndefined();
+ expect(isProviderDisableBrowserRequest(id)).toBe(true);
+ });
+
+ it('contributes only TTS cards to the default model list', () => {
+ const cards = LOBE_DEFAULT_MODEL_LIST.filter((item) => item.providerId === id);
+
+ expect(cards.map((item) => item.id)).toEqual(models);
+ expect(cards.every((item) => item.type === 'tts' && item.source === 'builtin')).toBe(true);
+ });
+});
+
+it('keeps Doubao Speech separate from Volcengine Ark', () => {
+ expect(ModelProvider.DoubaoSpeech).not.toBe(ModelProvider.Volcengine);
+});
diff --git a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
index 49fca31a1cd..ba6a8957672 100644
--- a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts
@@ -7,8 +7,10 @@ export type ApiType =
| 'bedrock'
| 'cloudflare'
| 'deepseek'
+ | 'doubaospeech'
| 'elevenlabs'
| 'fal'
+ | 'fishaudio'
| 'google'
| 'meta'
| 'minimax'
diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.ts
index 333d4876b0e..affa75e5178 100644
--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.ts
@@ -1,6 +1,8 @@
import { describe, expect, it } from 'vitest';
+import { LobeDoubaoSpeechAI } from '../../providers/doubaospeech';
import { LobeElevenLabsAI } from '../../providers/elevenlabs';
+import { LobeFishAudioAI } from '../../providers/fishaudio';
import { LobeTypeSafeAI } from '../../providers/typesafe';
import { baseRuntimeMap } from './baseRuntimeMap';
@@ -12,4 +14,12 @@ describe('baseRuntimeMap', () => {
it('routes the elevenlabs api type through the ElevenLabs speech runtime', () => {
expect(baseRuntimeMap.elevenlabs).toBe(LobeElevenLabsAI);
});
+
+ it('routes the fishaudio api type through the Fish Audio speech runtime', () => {
+ expect(baseRuntimeMap.fishaudio).toBe(LobeFishAudioAI);
+ });
+
+ it('routes the doubaospeech api type through the Doubao Speech runtime', () => {
+ expect(baseRuntimeMap.doubaospeech).toBe(LobeDoubaoSpeechAI);
+ });
});
diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
index c7e449848df..a2e8ffe8bd4 100644
--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts
@@ -4,8 +4,10 @@ import { LobeAzureOpenAI } from '../../providers/azureOpenai';
import { LobeBedrockAI } from '../../providers/bedrock';
import { LobeCloudflareAI } from '../../providers/cloudflare';
import { LobeDeepSeekAI } from '../../providers/deepseek';
+import { LobeDoubaoSpeechAI } from '../../providers/doubaospeech';
import { LobeElevenLabsAI } from '../../providers/elevenlabs';
import { LobeFalAI } from '../../providers/fal';
+import { LobeFishAudioAI } from '../../providers/fishaudio';
import { LobeGoogleAI } from '../../providers/google';
import { LobeMetaAI } from '../../providers/meta';
import { LobeMinimaxAI } from '../../providers/minimax';
@@ -27,8 +29,10 @@ export const baseRuntimeMap = {
bedrock: LobeBedrockAI,
cloudflare: LobeCloudflareAI,
deepseek: LobeDeepSeekAI,
+ doubaospeech: LobeDoubaoSpeechAI,
elevenlabs: LobeElevenLabsAI,
fal: LobeFalAI,
+ fishaudio: LobeFishAudioAI,
google: LobeGoogleAI,
meta: LobeMetaAI,
minimax: LobeMinimaxAI,
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts
index f47c2c027d2..08de4fc9d66 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts
@@ -1,3 +1,4 @@
+// @vitest-environment node
import { RequestTrigger } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -80,4 +81,126 @@ describe('createRouterRuntime textToSpeech', () => {
expect((init.headers as Record<string, string>)['xi-api-key']).toBe('channel-xi-key');
vi.unstubAllGlobals();
});
+
+ it('routes apiType fishaudio through the Fish Audio runtime with the channel key', async () => {
+ const fetchMock = vi.fn(
+ async () => new Response(new Uint8Array([0x49, 0x44, 0x33]), { status: 200 }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ routers: [
+ {
+ apiType: 'fishaudio',
+ models: ['s2.1-pro'],
+ options: { apiKey: 'channel-fish-key' },
+ },
+ ],
+ });
+
+ const result = await new Runtime().textToSpeech(
+ { input: 'Hi', model: 's2.1-pro', voice: 'default' },
+ { metadata: { trigger: RequestTrigger.Tts } },
+ );
+
+ expect(result).toMatchObject({ format: 'mp3' });
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toBe('https://api.fish.audio/v1/tts');
+ const headers = init.headers as Record<string, string>;
+ expect(headers.Authorization).toBe('Bearer channel-fish-key');
+ expect(headers.model).toBe('s2.1-pro');
+ vi.unstubAllGlobals();
+ });
+
+ it('routes Fish Audio through an OpenRouter openai channel: mapped id, no default voice, byte usage', async () => {
+ const fetchMock = vi.fn(
+ async () =>
+ new Response(new Uint8Array([0x49, 0x44, 0x33]), {
+ headers: { 'content-type': 'audio/mpeg' },
+ status: 200,
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ routers: [
+ {
+ apiType: 'openai',
+ models: ['s2.1-pro', 'drama-3', 's2-pro', 's1'],
+ options: {
+ apiKey: 'channel-openrouter-key',
+ baseURL: 'https://openrouter.ai/api/v1',
+ modelIdMapping: {
+ 'drama-3': 'fish-audio/drama-3',
+ 's1': 'fish-audio/s1',
+ 's2-pro': 'fish-audio/s2-pro',
+ 's2.1-pro': 'fish-audio/s2.1-pro',
+ },
+ },
+ },
+ ],
+ });
+
+ const onUsage = vi.fn();
+ const result = await new Runtime().textToSpeech(
+ { input: '你好 Hi', model: 's2.1-pro', params: { speed: 1.2 }, voice: 'default' },
+ { metadata: { trigger: RequestTrigger.Tts }, onUsage },
+ );
+
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string | URL, RequestInit];
+ expect(String(url)).toBe('https://openrouter.ai/api/v1/audio/speech');
+ const body = JSON.parse(init.body as string);
+ expect(body).toEqual({
+ input: '你好 Hi',
+ model: 'fish-audio/s2.1-pro',
+ response_format: 'mp3',
+ speed: 1.2,
+ });
+ // 2 Han × 3 bytes + " Hi" (3) = 9 UTF-8 bytes
+ expect(result).toMatchObject({ format: 'mp3', usage: { inputCharacters: 9 } });
+ expect(onUsage).toHaveBeenCalledWith(
+ expect.objectContaining({ inputCharacters: 9 }),
+ expect.anything(),
+ );
+ vi.unstubAllGlobals();
+ });
+
+ it('routes apiType doubaospeech through the Doubao Speech runtime with the channel key', async () => {
+ const fetchMock = vi.fn(
+ async () =>
+ new Response(
+ [
+ JSON.stringify({ code: 0, data: Buffer.from([1, 2]).toString('base64') }),
+ JSON.stringify({ code: 20_000_000, usage: { text_words: 2 } }),
+ ].join('\n'),
+ ),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+
+ const Runtime = createRouterRuntime({
+ id: 'lobehub',
+ routers: [
+ {
+ apiType: 'doubaospeech',
+ models: ['seed-tts-2.0'],
+ options: { apiKey: 'channel-doubao-key' },
+ },
+ ],
+ });
+
+ const result = await new Runtime().textToSpeech(
+ { input: 'Hi', model: 'seed-tts-2.0', voice: 'zh_female_vv_uranus_bigtts' },
+ { metadata: { trigger: RequestTrigger.Tts } },
+ );
+
+ expect(result).toMatchObject({ format: 'mp3' });
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toBe('https://openspeech.bytedance.com/api/v3/tts/unidirectional');
+ const headers = init.headers as Record<string, string>;
+ expect(headers['X-Api-Key']).toBe('channel-doubao-key');
+ expect(headers['X-Api-Resource-Id']).toBe('seed-tts-2.0');
+ vi.unstubAllGlobals();
+ });
});
diff --git a/packages/model-runtime/src/core/openaiCompatible/textToSpeech.test.ts b/packages/model-runtime/src/core/openaiCompatible/textToSpeech.test.ts
index 45f8eddd6cf..25b138f0e3f 100644
--- a/packages/model-runtime/src/core/openaiCompatible/textToSpeech.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatible/textToSpeech.test.ts
@@ -141,6 +141,250 @@ describe('createOpenAICompatibleSpeech', () => {
expect(result.usage).toEqual({ inputCharacters: 2 });
});
+ it('omits the Fish Audio default voice and bills a gateway Fish model by UTF-8 bytes', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+
+ const result = await createOpenAICompatibleSpeech(
+ client,
+ { input: '你好, hi', model: 's2.1-pro', params: { speed: 1.2 }, voice: 'default' },
+ undefined,
+ { ...context, provider: 'lobehub', requestModel: 'fish-audio/s2.1-pro' },
+ );
+
+ expect(create).toHaveBeenCalledWith(
+ { input: '你好, hi', model: 'fish-audio/s2.1-pro', response_format: 'mp3', speed: 1.2 },
+ { headers: undefined, signal: undefined },
+ );
+ // 2 Han × 3 bytes + ", hi" (4) = 10 billed bytes; 10 × $15/1M
+ expect(result.usage).toEqual({ cost: 0.00015, inputCharacters: 10 });
+ });
+
+ it('sends a Fish Audio reference voice and recognizes Fish by its gateway id alone', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+ const voice = '0123456789abcdef0123456789abcdef';
+
+ const result = await createOpenAICompatibleSpeech(
+ client,
+ { input: '语音', model: 'custom-fish', voice },
+ undefined,
+ { ...context, requestModel: 'fish-audio/drama-3' },
+ );
+
+ expect(create.mock.calls[0][0]).toMatchObject({ model: 'fish-audio/drama-3', voice });
+ expect(result.usage?.inputCharacters).toBe(6);
+ });
+
+ it('bills the instructions a gateway writes in front of a Fish Audio input', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+
+ const result = await createOpenAICompatibleSpeech(
+ client,
+ { input: '你好', model: 's2.1-pro', params: { instructions: 'whisper' }, voice: 'default' },
+ undefined,
+ { ...context, requestModel: 'fish-audio/s2.1-pro' },
+ );
+
+ expect(create.mock.calls[0][0]).toMatchObject({ instructions: 'whisper' });
+ // "[whisper] " (10) + 2 Han × 3 bytes = 16 billed bytes
+ expect(result.usage?.inputCharacters).toBe(16);
+ });
+
+ it("treats a bare Fish-like id on a custom provider as that provider's own model", async () => {
+ create.mockResolvedValue(audioResponse([0]));
+
+ const result = await createOpenAICompatibleSpeech(
+ client,
+ { input: 'a'.repeat(5000) + '你好', model: 's1', voice: 'default' },
+ undefined,
+ { ...context, provider: 'my-custom-tts', requestModel: 's1' },
+ );
+
+ // No Fish cap, the caller's voice is kept, and usage counts code points, not bytes.
+ expect(create.mock.calls[0][0]).toMatchObject({ model: 's1', voice: 'default' });
+ expect(result.usage?.inputCharacters).toBe(5002);
+ });
+
+ it('prices a qualified gateway Fish id by the Fish Audio catalog card', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+ vi.mocked(getModelPricing).mockImplementation(async (model, provider) =>
+ model === 's2.1-pro' && provider === 'fishaudio' ? characterPricing : undefined,
+ );
+
+ const result = await createOpenAICompatibleSpeech(
+ client,
+ { input: 'hi', model: 'fish-audio/s2.1-pro', voice: 'default' },
+ undefined,
+ { ...context, provider: 'openrouter', requestModel: 'fish-audio/s2.1-pro' },
+ );
+
+ expect(getModelPricing).toHaveBeenCalledWith('fish-audio/s2.1-pro', 'openrouter', undefined);
+ expect(getModelPricing).toHaveBeenCalledWith('s2.1-pro', 'fishaudio', undefined);
+ // 2 bytes × $15/1M
+ expect(result.usage).toEqual({ cost: 0.00003, inputCharacters: 2 });
+ });
+
+ it('prices an alias mapped to a Fish route by the mapped model card', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+ vi.mocked(getModelPricing).mockImplementation(async (model, provider) =>
+ model === 'drama-3' && provider === 'fishaudio' ? characterPricing : undefined,
+ );
+
+ const result = await createOpenAICompatibleSpeech(
+ client,
+ { input: 'hi', model: 'custom-fish', voice: 'default' },
+ undefined,
+ { ...context, provider: 'my-gateway', requestModel: 'fish-audio/drama-3' },
+ );
+
+ expect(getModelPricing).toHaveBeenCalledWith('drama-3', 'fishaudio', undefined);
+ expect(result.usage).toEqual({ cost: 0.00003, inputCharacters: 2 });
+ });
+
+ it('validates gateway Fish params against the Fish catalog card before the request', async () => {
+ await expect(
+ createOpenAICompatibleSpeech(
+ client,
+ {
+ input: 'Hi',
+ model: 'fish-audio/s1',
+ params: { instructions: 'whisper' },
+ voice: 'default',
+ },
+ undefined,
+ { ...context, provider: 'openrouter', requestModel: 'fish-audio/s1' },
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('params.instructions') },
+ errorType: 'ProviderBizError',
+ provider: 'openrouter',
+ });
+
+ await expect(
+ createOpenAICompatibleSpeech(
+ client,
+ { input: 'Hi', model: 'custom-fish', params: { speed: 3 }, voice: 'default' },
+ undefined,
+ { ...context, provider: 'my-gateway', requestModel: 'fish-audio/s2.1-pro' },
+ ),
+ ).rejects.toMatchObject({ error: { message: expect.stringContaining('params.speed') } });
+ expect(create).not.toHaveBeenCalled();
+
+ // `/audio/speech` cannot carry a sample rate, so a gateway Fish route refuses it.
+ await expect(
+ createOpenAICompatibleSpeech(
+ client,
+ {
+ input: 'Hi',
+ model: 'fish-audio/s2.1-pro',
+ params: { sampleRate: 44_100 },
+ voice: 'default',
+ },
+ undefined,
+ { ...context, provider: 'openrouter', requestModel: 'fish-audio/s2.1-pro' },
+ ),
+ ).rejects.toMatchObject({ error: { message: expect.stringContaining('params.sampleRate') } });
+ expect(create).not.toHaveBeenCalled();
+
+ // s2.1-pro-free follows the S2.1 Pro schema, and a refused sample rate is a clean error.
+ for (const params of [{ speed: 3 }, { sampleRate: 44_100 }]) {
+ await expect(
+ createOpenAICompatibleSpeech(
+ client,
+ { input: 'Hi', model: 'fish-audio/s2.1-pro-free', params, voice: 'default' },
+ undefined,
+ { ...context, provider: 'openrouter', requestModel: 'fish-audio/s2.1-pro-free' },
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('Fish Audio s2.1-pro-free: params.') },
+ errorType: 'ProviderBizError',
+ });
+ }
+ expect(create).not.toHaveBeenCalled();
+
+ // The directed S2 family accepts instructions through the gateway.
+ create.mockResolvedValue(audioResponse([0]));
+ await createOpenAICompatibleSpeech(
+ client,
+ {
+ input: 'Hi',
+ model: 'fish-audio/s2.1-pro',
+ params: { instructions: 'calm' },
+ voice: 'default',
+ },
+ undefined,
+ { ...context, provider: 'openrouter', requestModel: 'fish-audio/s2.1-pro' },
+ );
+ expect(create).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses a gateway Fish Audio input over the per-request cap before the request', async () => {
+ await expect(
+ createOpenAICompatibleSpeech(
+ client,
+ { input: 'a'.repeat(4097), model: 'fish-audio/s2.1-pro', voice: 'default' },
+ undefined,
+ { ...context, provider: 'openrouter', requestModel: 'fish-audio/s2.1-pro' },
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('the limit is 4096 per request') },
+ errorType: 'ProviderBizError',
+ provider: 'openrouter',
+ });
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it('lets a gateway Fish Audio input at the cap through', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+
+ await createOpenAICompatibleSpeech(
+ client,
+ { input: 'a'.repeat(4096), model: 'fish-audio/s2.1-pro', voice: 'default' },
+ undefined,
+ { ...context, requestModel: 'fish-audio/s2.1-pro' },
+ );
+
+ expect(create).toHaveBeenCalledTimes(1);
+ });
+
+ it('omits a service fallback voice for a fully qualified gateway Fish model', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+
+ await createOpenAICompatibleSpeech(
+ client,
+ { input: 'hi', model: 'fish-audio/s2.1-pro', voice: 'alloy', voiceIsDefault: true },
+ undefined,
+ { ...context, provider: 'openrouter', requestModel: 'fish-audio/s2.1-pro' },
+ );
+
+ expect(create.mock.calls[0][0]).not.toHaveProperty('voice');
+ });
+
+ it('keeps a fallback voice for non-Fish models', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+
+ await createOpenAICompatibleSpeech(
+ client,
+ { input: 'hi', model: 'tts-1', voice: 'alloy', voiceIsDefault: true },
+ undefined,
+ context,
+ );
+
+ expect(create.mock.calls[0][0]).toMatchObject({ voice: 'alloy' });
+ });
+
+ it('keeps a voice named "default" for non-Fish models', async () => {
+ create.mockResolvedValue(audioResponse([0]));
+
+ await createOpenAICompatibleSpeech(
+ client,
+ { input: 'hi', model: 'tts-1', voice: 'default' },
+ undefined,
+ context,
+ );
+
+ expect(create.mock.calls[0][0]).toMatchObject({ voice: 'default' });
+ });
+
it('keeps counting code points for non-MiniMax models', async () => {
create.mockResolvedValue(audioResponse([0]));
diff --git a/packages/model-runtime/src/core/openaiCompatible/textToSpeech.ts b/packages/model-runtime/src/core/openaiCompatible/textToSpeech.ts
index 81bfe79e25c..701c849d4b1 100644
--- a/packages/model-runtime/src/core/openaiCompatible/textToSpeech.ts
+++ b/packages/model-runtime/src/core/openaiCompatible/textToSpeech.ts
@@ -1,6 +1,14 @@
import type { ModelTokensUsage } from '@lobechat/types';
+import { AgentRuntimeErrorType } from '@lobechat/types';
import debug from 'debug';
-import { DEFAULT_TTS_AUDIO_FORMAT } from 'model-bank';
+import {
+ DEFAULT_TTS_AUDIO_FORMAT,
+ FISH_AUDIO_DEFAULT_VOICE_ID,
+ FISH_AUDIO_MAX_INPUT_CHARACTERS,
+ type TTSParamsIssue,
+ validateTTSParams,
+} from 'model-bank';
+import fishAudioModels from 'model-bank/fishaudio';
import type OpenAI from 'openai';
import type { SpeechCreateParams } from 'openai/resources/audio/speech';
@@ -11,13 +19,19 @@ import type {
} 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 {
convertOpenAISpeechTokenUsage,
convertTextToSpeechUsage,
+ countFishAudioBilledBytes,
countMiniMaxSpeechCharacters,
+ countTextToSpeechCharacters,
+ isFishAudioSpeechModel,
+ isFishAudioSpeechRoute,
isMiniMaxSpeechModel,
isTokenBilledTextToSpeech,
+ toFishAudioCatalogModel,
} from '../usageConverters/tts';
export interface CreateOpenAICompatibleSpeechContext {
@@ -80,6 +94,14 @@ const readSpeechEventStream = async (response: Response): Promise<SpeechEventStr
return { audio: audio as ArrayBuffer, tokenUsage };
};
+/**
+ * Text a gateway bills for a Fish Audio model: OpenRouter writes `instructions` into the
+ * input as a leading `[direction]`, the way Fish takes delivery directions, and bills it.
+ * @see https://openrouter.ai/docs/guides/overview/multimodal/tts
+ */
+const fishAudioBilledText = (input: string, params: { instructions?: string }) =>
+ params.instructions ? `[${params.instructions}] ${input}` : input;
+
/**
* `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
@@ -94,9 +116,76 @@ export const createOpenAICompatibleSpeech = async (
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 fishAudio = isFishAudioSpeechRoute(context.provider, payload.model, context.requestModel);
+ // A gateway id (`fish-audio/s2.1-pro` on OpenRouter) or an alias mapped to one has no
+ // card of its own: price it by the Fish Audio catalog card of the model actually called,
+ // preferring the mapped upstream id over the logical alias.
+ const fishCatalogModel = fishAudio
+ ? [context.requestModel, payload.model].find((model) => isFishAudioSpeechModel(model))
+ : undefined;
+ const pricing =
+ (await getModelPricing(payload.model, context.provider, options?.pricingContext)) ??
+ (fishCatalogModel
+ ? await getModelPricing(
+ toFishAudioCatalogModel(fishCatalogModel),
+ 'fishaudio',
+ options?.pricingContext,
+ )
+ : undefined);
const streamUsage = isTokenBilledTextToSpeech(pricing);
+ // Fish Audio returns the whole audio inline; a longer input would be billed and then
+ // exceed the serverless response limit. Gateway ids (`fish-audio/s2.1-pro`) match no
+ // static card, so the TTS service cannot cap them and the cap is enforced here.
+ if (fishAudio) {
+ const inputCharacters = countTextToSpeechCharacters(payload.input);
+ if (inputCharacters > FISH_AUDIO_MAX_INPUT_CHARACTERS) {
+ throw AgentRuntimeError.chat({
+ error: {
+ message: `Fish Audio speech input is ${inputCharacters} characters; the limit is ${FISH_AUDIO_MAX_INPUT_CHARACTERS} per request. Split the text into shorter requests.`,
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: context.provider,
+ });
+ }
+
+ // The TTS service validates params against the static card, which a gateway or mapped
+ // id never matches; check them against the Fish catalog card of the model actually
+ // called, so e.g. S1 refuses `instructions` it would otherwise speak aloud.
+ // `s2.1-pro-free` has no card of its own and follows the S2.1 Pro schema.
+ const catalogId = fishCatalogModel ? toFishAudioCatalogModel(fishCatalogModel) : undefined;
+ const card = catalogId
+ ? (fishAudioModels.find((item) => item.id === catalogId) ??
+ fishAudioModels.find((item) => item.id === catalogId.replace(/-free$/, '')))
+ : undefined;
+ const issues: TTSParamsIssue[] = card?.parameters
+ ? validateTTSParams(card.parameters, params)
+ : [];
+ // `/audio/speech` has no sample-rate field, so a gateway could only drop it silently.
+ if (params.sampleRate !== undefined) {
+ issues.push({
+ key: 'sampleRate',
+ reason: 'is not supported through an OpenAI-compatible gateway; omit it',
+ });
+ }
+ if (issues.length > 0) {
+ throw AgentRuntimeError.chat({
+ error: {
+ message: `Fish Audio ${catalogId ?? payload.model}: ${issues.map(({ key, reason }) => `params.${key} ${reason}`).join('; ')}`,
+ },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ provider: context.provider,
+ });
+ }
+ }
+ // Fish Audio's default voice is "no reference voice": gateways (OpenRouter) reject the
+ // `default` sentinel with 400 but speak the default voice when `voice` is left out. A
+ // service fallback voice (`voiceIsDefault`, e.g. `alloy` for a gateway id with no card)
+ // means the caller gave none, so it is left out too.
+ const omitVoice =
+ fishAudio &&
+ (!payload.voice || payload.voice === FISH_AUDIO_DEFAULT_VOICE_ID || !!payload.voiceIsDefault);
+
log(
'textToSpeech called with input length: %d, voice: %s, format: %s, sse: %s',
payload.input.length,
@@ -105,15 +194,15 @@ export const createOpenAICompatibleSpeech = async (
streamUsage,
);
- const body: SpeechCreateParams = {
+ const body = {
input: payload.input,
model: context.requestModel,
response_format: format,
- voice: payload.voice,
+ ...(!omitVoice && { voice: payload.voice }),
...(params.speed !== undefined && { speed: params.speed }),
...(params.instructions && { instructions: params.instructions }),
...(streamUsage && { stream_format: 'sse' as const }),
- };
+ } as SpeechCreateParams;
let result: SpeechEventStreamResult;
try {
@@ -132,12 +221,15 @@ export const createOpenAICompatibleSpeech = async (
log('generated audio with size: %d bytes', result.audio.byteLength);
- // Gateways bill MiniMax speech models by MiniMax's own count (a Chinese character is 2).
- const billedCharacters =
- !streamUsage &&
- (isMiniMaxSpeechModel(payload.model) || isMiniMaxSpeechModel(context.requestModel))
- ? { inputCharacters: countMiniMaxSpeechCharacters(payload.input) }
- : undefined;
+ // Gateways bill by the vendor's own count: MiniMax counts a Chinese character as 2,
+ // Fish Audio counts UTF-8 bytes (a Chinese character is 3).
+ const billedCharacters = streamUsage
+ ? undefined
+ : fishAudio
+ ? { inputCharacters: countFishAudioBilledBytes(fishAudioBilledText(payload.input, params)) }
+ : isMiniMaxSpeechModel(payload.model) || isMiniMaxSpeechModel(context.requestModel)
+ ? { inputCharacters: countMiniMaxSpeechCharacters(payload.input) }
+ : undefined;
const usage = convertTextToSpeechUsage(
payload.input,
pricing,
diff --git a/packages/model-runtime/src/core/usageConverters/index.ts b/packages/model-runtime/src/core/usageConverters/index.ts
index b08d04fff8e..0192b9d9bbb 100644
--- a/packages/model-runtime/src/core/usageConverters/index.ts
+++ b/packages/model-runtime/src/core/usageConverters/index.ts
@@ -8,10 +8,14 @@ export {
export {
convertOpenAISpeechTokenUsage,
convertTextToSpeechUsage,
+ countFishAudioBilledBytes,
countMiniMaxSpeechCharacters,
countTextToSpeechCharacters,
+ isFishAudioSpeechModel,
+ isFishAudioSpeechRoute,
isMiniMaxSpeechModel,
isTokenBilledTextToSpeech,
+ toFishAudioCatalogModel,
} from './tts';
export {
computeChatCost,
diff --git a/packages/model-runtime/src/core/usageConverters/tts.test.ts b/packages/model-runtime/src/core/usageConverters/tts.test.ts
index 813fd3a8fde..bfdc9863e51 100644
--- a/packages/model-runtime/src/core/usageConverters/tts.test.ts
+++ b/packages/model-runtime/src/core/usageConverters/tts.test.ts
@@ -1,12 +1,16 @@
import type { Pricing } from 'model-bank';
+import fishaudioModels from 'model-bank/fishaudio';
import openaiModels from 'model-bank/openai';
import { describe, expect, it } from 'vitest';
+import { FISH_AUDIO_MODELS } from '../../providers/fishaudio/createSpeech';
import {
convertOpenAISpeechTokenUsage,
convertTextToSpeechUsage,
+ countFishAudioBilledBytes,
countMiniMaxSpeechCharacters,
countTextToSpeechCharacters,
+ isFishAudioSpeechModel,
isMiniMaxSpeechModel,
isTokenBilledTextToSpeech,
} from './tts';
@@ -107,3 +111,32 @@ describe('isMiniMaxSpeechModel', () => {
expect(isMiniMaxSpeechModel(undefined)).toBe(false);
});
});
+
+describe('countFishAudioBilledBytes', () => {
+ it('counts UTF-8 bytes: a Chinese character is 3, an emoji 4', () => {
+ expect(countFishAudioBilledBytes('hello')).toBe(5);
+ expect(countFishAudioBilledBytes('你好,世界')).toBe(15);
+ expect(countFishAudioBilledBytes('hi 👋')).toBe(7);
+ });
+});
+
+describe('isFishAudioSpeechModel', () => {
+ it('matches every Fish Audio card and runtime model, by catalog and gateway id', () => {
+ const ids = [...fishaudioModels.map((model: { id: string }) => model.id), ...FISH_AUDIO_MODELS];
+
+ expect(ids.length).toBeGreaterThan(0);
+ for (const id of ids) {
+ expect(isFishAudioSpeechModel(id)).toBe(true);
+ expect(isFishAudioSpeechModel(`fish-audio/${id}`)).toBe(true);
+ }
+ });
+
+ it('rejects other models and look-alike ids', () => {
+ expect(isFishAudioSpeechModel('tts-1')).toBe(false);
+ expect(isFishAudioSpeechModel('speech-2.8-hd')).toBe(false);
+ expect(isFishAudioSpeechModel('s2')).toBe(false);
+ expect(isFishAudioSpeechModel('s1-mini')).toBe(false);
+ expect(isFishAudioSpeechModel('other/s1')).toBe(false);
+ expect(isFishAudioSpeechModel(undefined)).toBe(false);
+ });
+});
diff --git a/packages/model-runtime/src/core/usageConverters/tts.ts b/packages/model-runtime/src/core/usageConverters/tts.ts
index 0ee04aaa959..0e009220da9 100644
--- a/packages/model-runtime/src/core/usageConverters/tts.ts
+++ b/packages/model-runtime/src/core/usageConverters/tts.ts
@@ -32,6 +32,46 @@ const MINIMAX_SPEECH_MODEL_PATTERN = /^(?:minimax\/)?speech-/i;
export const isMiniMaxSpeechModel = (model?: string) =>
!!model && MINIMAX_SPEECH_MODEL_PATTERN.test(model);
+/**
+ * Fish Audio bills per million UTF-8 bytes, so a Han character costs three times a Latin
+ * letter. Gateways that resell these models (e.g. OpenRouter `fish-audio/s2.1-pro`) bill the
+ * same count. Reported as `inputCharacters` against the per-byte price on the model card.
+ * @see https://docs.fish.audio/developer-guide/models-pricing/pricing-and-rate-limits
+ */
+export const countFishAudioBilledBytes = (text: string) => new TextEncoder().encode(text).length;
+
+/**
+ * Fish Audio speech models: the catalog ids of the `fishaudio` provider (`s2.1-pro`,
+ * `drama-3`, ...) and their gateway ids (`fish-audio/s2.1-pro`).
+ */
+const FISH_AUDIO_SPEECH_MODEL_PATTERN =
+ /^(?:fish-audio\/)?(?:s1|s2-pro|s2\.1-pro(?:-free)?|drama-3)$/i;
+
+/** Whether a model id names a Fish Audio speech model, by catalog or gateway id. */
+export const isFishAudioSpeechModel = (model?: string) =>
+ !!model && FISH_AUDIO_SPEECH_MODEL_PATTERN.test(model);
+
+const FISH_AUDIO_GATEWAY_PREFIX = /^fish-audio\//i;
+
+/**
+ * Whether a request on a generic (OpenAI-compatible) runtime goes to Fish Audio. Only a
+ * gateway id (`fish-audio/s1`) proves it: a bare id such as `s1` may be any custom
+ * provider's own model, so it counts only on the Fish Audio provider itself.
+ */
+export const isFishAudioSpeechRoute = (
+ provider: string | undefined,
+ ...models: (string | undefined)[]
+) =>
+ models.some(
+ (model) =>
+ isFishAudioSpeechModel(model) &&
+ (FISH_AUDIO_GATEWAY_PREFIX.test(model!) || provider === 'fishaudio'),
+ );
+
+/** The Fish Audio catalog id of a model id, without the gateway prefix. */
+export const toFishAudioCatalogModel = (model: string) =>
+ model.replace(FISH_AUDIO_GATEWAY_PREFIX, '');
+
/**
* 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.
diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.ts
index c8e25a04698..8effc5b13cd 100644
--- a/packages/model-runtime/src/index.ts
+++ b/packages/model-runtime/src/index.ts
@@ -57,7 +57,9 @@ export { LobeChatGPTAI } from './providers/chatGPT';
export { LobeCometAPIAI } from './providers/cometapi';
export { LobeComfyUI } from './providers/comfyui';
export { LobeDeepSeekAI } from './providers/deepseek';
+export { LobeDoubaoSpeechAI } from './providers/doubaospeech';
export { LobeElevenLabsAI } from './providers/elevenlabs';
+export { LobeFishAudioAI } from './providers/fishaudio';
export { LobeGLMCodingPlanAI } from './providers/glmCodingPlan';
export { LobeGoogleAI } from './providers/google';
export * from './providers/google/modelId';
diff --git a/packages/model-runtime/src/providers/doubaospeech/createSpeech.test.ts b/packages/model-runtime/src/providers/doubaospeech/createSpeech.test.ts
new file mode 100644
index 00000000000..9cf4c133fdb
--- /dev/null
+++ b/packages/model-runtime/src/providers/doubaospeech/createSpeech.test.ts
@@ -0,0 +1,477 @@
+// @vitest-environment node
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import type { Pricing } from 'model-bank';
+import { DOUBAO_SPEECH_DEFAULT_VOICE_ID } from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getModelPricing } from '../../utils/getModelPricing';
+import {
+ buildDoubaoSpeechAuthHeaders,
+ buildDoubaoSpeechRequest,
+ createDoubaoSpeech,
+ DOUBAO_SPEECH_MAX_INPUT_CHARACTERS,
+ type DoubaoSpeechOptions,
+ normalizeDoubaoSpeechBaseURL,
+ readDoubaoSpeechFrames,
+} from './createSpeech';
+
+vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));
+
+// 3 CNY per 10k characters, as on the seed-tts-2.0 card
+const seed20Pricing: Pricing = {
+ currency: 'CNY',
+ units: [{ name: 'textInput', rate: 300, strategy: 'fixed', unit: 'millionCharacters' }],
+};
+
+const options: DoubaoSpeechOptions = {
+ apiKey: 'doubao-test-key',
+ baseURL: 'https://openspeech.bytedance.com',
+ provider: 'doubaospeech',
+};
+
+const VOICE = 'zh_male_m191_uranus_bigtts';
+
+const b64 = (bytes: number[]) => Buffer.from(Uint8Array.from(bytes)).toString('base64');
+
+/** A V3 chunked response: audio frames, then the 20000000 frame. */
+const streamResponse = (
+ frames: unknown[] = [
+ { code: 0, data: b64([1, 2]), message: '' },
+ { code: 0, data: b64([3]), message: '' },
+ { code: 20_000_000, data: null, message: 'ok', usage: { text_words: 7 } },
+ ],
+ status = 200,
+) =>
+ new Response(frames.map((frame) => JSON.stringify(frame)).join('\n'), {
+ headers: { 'content-type': 'application/json', 'x-tt-logid': 'log-1' },
+ status,
+ });
+
+const lastRequest = (fetchMock: ReturnType<typeof vi.fn>) => {
+ const [url, init] = fetchMock.mock.calls.at(-1) as [string, RequestInit];
+ return {
+ body: JSON.parse(init.body as string),
+ headers: init.headers as Record<string, string>,
+ url,
+ };
+};
+
+describe('createDoubaoSpeech', () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ fetchMock = vi.fn(async () => streamResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ vi.mocked(getModelPricing).mockResolvedValue(seed20Pricing);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ it('posts a V3 request with the API key and the model as resource id', async () => {
+ const result = await createDoubaoSpeech(
+ { input: '你好', model: 'seed-tts-2.0', voice: VOICE },
+ { ...options, user: 'user_1' },
+ );
+
+ const { body, headers, url } = lastRequest(fetchMock);
+ expect(url).toBe('https://openspeech.bytedance.com/api/v3/tts/unidirectional');
+ expect(headers['X-Api-Key']).toBe('doubao-test-key');
+ expect(headers['X-Api-App-Id']).toBeUndefined();
+ expect(headers['X-Api-Resource-Id']).toBe('seed-tts-2.0');
+ expect(headers['X-Api-Request-Id']).toMatch(/^[\da-f-]{36}$/);
+ expect(headers['X-Control-Require-Usage-Tokens-Return']).toBe('text_words');
+ expect(body).toEqual({
+ req_params: { audio_params: { format: 'mp3' }, speaker: VOICE, text: '你好' },
+ user: { uid: expect.stringMatching(/^[\da-f]{32}$/) },
+ });
+ // The raw user id never leaves the server.
+ expect(JSON.stringify(body)).not.toContain('user_1');
+ expect(new Uint8Array(result.audio)).toEqual(new Uint8Array([1, 2, 3]));
+ expect(result.format).toBe('mp3');
+ });
+
+ it('authenticates with the legacy App ID + Access Token', async () => {
+ await createDoubaoSpeech(
+ { input: 'Hi', model: 'seed-tts-2.0', voice: VOICE },
+ { ...options, accessToken: 'token-1', apiKey: undefined, appId: 'app-1' },
+ );
+
+ const { headers } = lastRequest(fetchMock);
+ expect(headers['X-Api-App-Id']).toBe('app-1');
+ expect(headers['X-Api-Access-Key']).toBe('token-1');
+ expect(headers['X-Api-Key']).toBeUndefined();
+ });
+
+ it('maps speed, volume, pitch, sample rate and format', async () => {
+ await createDoubaoSpeech(
+ {
+ input: 'Hi',
+ model: 'seed-tts-2.0',
+ params: { format: 'wav', pitch: 3, sampleRate: 16_000, speed: 1.5, volume: 0.5 },
+ voice: VOICE,
+ },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body.req_params).toEqual({
+ additions: JSON.stringify({ post_process: { pitch: 3 } }),
+ audio_params: { format: 'wav', loudness_rate: -50, sample_rate: 16_000, speech_rate: 50 },
+ speaker: VOICE,
+ text: 'Hi',
+ });
+ });
+
+ it('sends opus as ogg_opus at 48 kHz', async () => {
+ for (const sampleRate of [undefined, 48_000]) {
+ const result = await createDoubaoSpeech(
+ {
+ input: 'Hi',
+ model: 'seed-tts-2.0',
+ params: { format: 'opus', sampleRate },
+ voice: VOICE,
+ },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body.req_params.audio_params).toEqual({
+ format: 'ogg_opus',
+ sample_rate: 48_000,
+ });
+ expect(result.format).toBe('opus');
+ }
+ });
+
+ it('refuses an opus request at a rate other than 48 kHz before calling Doubao', async () => {
+ await expect(
+ createDoubaoSpeech(
+ {
+ input: 'Hi',
+ model: 'seed-tts-2.0',
+ params: { format: 'opus', sampleRate: 24_000 },
+ voice: VOICE,
+ },
+ options,
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('only produced at 48000 Hz') },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('replaces a service-filled default voice of another vendor with the Doubao default', async () => {
+ await createDoubaoSpeech(
+ { input: 'Hi', model: 'seed-tts-2.0', voice: 'alloy', voiceIsDefault: true },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body.req_params.speaker).toBe(DOUBAO_SPEECH_DEFAULT_VOICE_ID);
+ });
+
+ it('speaks a voice clone through the voice-cloning resource, priced as the model', async () => {
+ await createDoubaoSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: 'S_abc123' }, options);
+
+ const { body, headers } = lastRequest(fetchMock);
+ expect(body.req_params.speaker).toBe('S_abc123');
+ expect(headers['X-Api-Resource-Id']).toBe('seed-icl-2.0');
+ expect(getModelPricing).toHaveBeenCalledWith('seed-tts-2.0', 'doubaospeech', undefined);
+ });
+
+ it('keeps the synthesis resource for official voices', async () => {
+ await createDoubaoSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: VOICE }, options);
+
+ expect(lastRequest(fetchMock).headers['X-Api-Resource-Id']).toBe('seed-tts-2.0');
+ });
+
+ it('bills the billed text_words in CNY, converted to USD', async () => {
+ const onUsage = vi.fn();
+ const result = await createDoubaoSpeech(
+ { input: 'Hello', model: 'seed-tts-2.0', voice: VOICE },
+ { ...options, onUsage },
+ );
+
+ expect(result.usage?.inputCharacters).toBe(7);
+ expect(result.usage?.cost).toBeGreaterThan(0);
+ expect(onUsage).toHaveBeenCalledWith(result.usage);
+ });
+
+ it('falls back to the local character count without usage', async () => {
+ fetchMock.mockResolvedValueOnce(
+ streamResponse([
+ { code: 0, data: b64([9]) },
+ { code: 20_000_000, message: 'ok' },
+ ]),
+ );
+
+ const result = await createDoubaoSpeech(
+ { input: '你好呀', model: 'seed-tts-2.0', voice: VOICE },
+ options,
+ );
+
+ expect(result.usage?.inputCharacters).toBe(3);
+ });
+
+ it('honours the model id mapping and normalizes the base URL', async () => {
+ await createDoubaoSpeech(
+ { input: 'Hi', model: 'doubao-tts', voice: VOICE },
+ {
+ ...options,
+ baseURL: 'https://proxy.example.com/api/v3/',
+ modelIdMapping: { 'doubao-tts': 'seed-tts-2.0' },
+ },
+ );
+
+ const { headers, url } = lastRequest(fetchMock);
+ expect(url).toBe('https://proxy.example.com/api/v3/tts/unidirectional');
+ expect(headers['X-Api-Resource-Id']).toBe('seed-tts-2.0');
+ expect(getModelPricing).toHaveBeenCalledWith('doubao-tts', 'doubaospeech', undefined);
+ });
+
+ it('prices an unpriced alias by the model it maps to', async () => {
+ vi.mocked(getModelPricing).mockImplementation(async (model) =>
+ model === 'seed-tts-2.0' ? seed20Pricing : undefined,
+ );
+
+ const result = await createDoubaoSpeech(
+ { input: 'Hi', model: 'doubao-tts', voice: VOICE },
+ { ...options, modelIdMapping: { 'doubao-tts': 'seed-tts-2.0' } },
+ );
+
+ expect(getModelPricing).toHaveBeenCalledWith('seed-tts-2.0', 'doubaospeech', undefined);
+ expect(result.usage?.cost).toBeGreaterThan(0);
+ });
+
+ it("validates a mapped alias against the resolved model's card", async () => {
+ await expect(
+ createDoubaoSpeech(
+ { input: 'Hi', model: 'doubao-tts', params: { speed: 100 }, voice: VOICE },
+ { ...options, modelIdMapping: { 'doubao-tts': 'seed-tts-2.0' } },
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('params.speed') },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ describe('rejects before calling Doubao Speech', () => {
+ it('without credentials', async () => {
+ await expect(
+ createDoubaoSpeech(
+ { input: 'Hi', model: 'seed-tts-2.0', voice: VOICE },
+ { ...options, apiKey: undefined, appId: 'app-only' },
+ ),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['an unsupported format', { params: { format: 'aac' as const } }],
+ ['an empty voice', { voice: ' ' }],
+ ['empty input', { input: ' ' }],
+ ['input over the limit', { input: 'a'.repeat(DOUBAO_SPEECH_MAX_INPUT_CHARACTERS + 1) }],
+ ['an unknown model', { model: 'seed-tts-9.9' }],
+ ])('%s', async (_, override) => {
+ await expect(
+ createDoubaoSpeech(
+ { input: 'Hi', model: 'seed-tts-2.0', voice: VOICE, ...override },
+ options,
+ ),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBizError });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ });
+
+ it.each(['seed-tts-1.0', 'seed-tts-1.0-concurr', 'seed-icl-2.0'])(
+ 'passes the documented resource %s through',
+ async (model) => {
+ await createDoubaoSpeech({ input: 'Hi', model, voice: VOICE }, options);
+
+ expect(lastRequest(fetchMock).headers['X-Api-Resource-Id']).toBe(model);
+ },
+ );
+
+ describe('maps upstream errors', () => {
+ it.each([
+ [
+ 401,
+ { code: 45_000_010, message: 'invalid api key' },
+ AgentRuntimeErrorType.InvalidProviderAPIKey,
+ ],
+ [
+ 403,
+ { code: 45_000_000, message: 'requested grant not found' },
+ AgentRuntimeErrorType.InvalidProviderAPIKey,
+ ],
+ [
+ 403,
+ { code: 45_000_000, message: 'speaker permission denied: access denied' },
+ AgentRuntimeErrorType.PermissionDenied,
+ ],
+ [
+ 429,
+ { code: 45_000_000, message: 'quota exceeded for types: concurrency' },
+ AgentRuntimeErrorType.RateLimitExceeded,
+ ],
+ [
+ 403,
+ { code: 45_000_000, message: 'quota exceeded for types: tts_lifetime' },
+ AgentRuntimeErrorType.InsufficientQuota,
+ ],
+ [
+ 400,
+ { code: 40_402_003, message: 'TTSExceededTextLimit' },
+ AgentRuntimeErrorType.ProviderBizError,
+ ],
+ [
+ 500,
+ { code: 55_000_000, message: 'internal error' },
+ AgentRuntimeErrorType.ProviderBizError,
+ ],
+ ])('HTTP %d %o → %s', async (status, frame, errorType) => {
+ fetchMock.mockResolvedValueOnce(streamResponse([frame], status));
+
+ await expect(
+ createDoubaoSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: VOICE }, options),
+ ).rejects.toMatchObject({
+ error: {
+ code: frame.code,
+ logId: 'log-1',
+ message: expect.stringContaining(frame.message),
+ status,
+ },
+ errorType,
+ provider: 'doubaospeech',
+ });
+ });
+
+ it('falls back to the HTTP status for a non-JSON error body', async () => {
+ fetchMock.mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }));
+
+ await expect(
+ createDoubaoSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: VOICE }, options),
+ ).rejects.toMatchObject({
+ error: { message: 'Doubao Speech API error (401): Unauthorized' },
+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ });
+ });
+
+ it('explains a voice that does not match the model version', async () => {
+ fetchMock.mockResolvedValueOnce(
+ streamResponse(
+ [{ code: 55_000_000, message: 'resource ID is mismatched with speaker' }],
+ 400,
+ ),
+ );
+
+ await expect(
+ createDoubaoSpeech(
+ { input: 'Hi', model: 'seed-tts-2.0', voice: 'zh_x_moon_bigtts' },
+ options,
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('does not belong to this model version') },
+ });
+ });
+
+ it('fails on an error frame inside a 200 stream', async () => {
+ fetchMock.mockResolvedValueOnce(
+ streamResponse([
+ { code: 0, data: b64([1]) },
+ { code: 45_002_001, message: 'no valid text' },
+ ]),
+ );
+
+ await expect(
+ createDoubaoSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: VOICE }, options),
+ ).rejects.toMatchObject({
+ error: { code: 45_002_001, message: expect.stringContaining('no valid text') },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ });
+ });
+
+ it('fails on a stream cut before the final frame instead of billing it', async () => {
+ const onUsage = vi.fn();
+ fetchMock.mockResolvedValueOnce(streamResponse([{ code: 0, data: b64([1]) }]));
+
+ await expect(
+ createDoubaoSpeech(
+ { input: 'Hi', model: 'seed-tts-2.0', voice: VOICE },
+ { ...options, onUsage },
+ ),
+ ).rejects.toMatchObject({
+ error: { message: 'Doubao Speech response ended before the synthesis finished' },
+ });
+ expect(onUsage).not.toHaveBeenCalled();
+ });
+
+ it('fails on a finished stream without audio', async () => {
+ fetchMock.mockResolvedValueOnce(streamResponse([{ code: 20_000_000, message: 'ok' }]));
+
+ await expect(
+ createDoubaoSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: VOICE }, options),
+ ).rejects.toMatchObject({ error: { message: 'Doubao Speech returned empty audio' } });
+ });
+
+ it('rethrows aborts as is', async () => {
+ const abort = Object.assign(new Error('aborted'), { name: 'AbortError' });
+ fetchMock.mockRejectedValueOnce(abort);
+
+ await expect(
+ createDoubaoSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: VOICE }, options),
+ ).rejects.toBe(abort);
+ });
+ });
+});
+
+describe('Doubao Speech helpers', () => {
+ it('prefers the API key over the legacy credentials', () => {
+ expect(buildDoubaoSpeechAuthHeaders({ accessToken: 't', apiKey: ' k ', appId: 'a' })).toEqual({
+ 'X-Api-Key': 'k',
+ });
+ expect(buildDoubaoSpeechAuthHeaders({ accessToken: 't', appId: 'a' })).toEqual({
+ 'X-Api-Access-Key': 't',
+ 'X-Api-App-Id': 'a',
+ });
+ expect(buildDoubaoSpeechAuthHeaders({ appId: 'a' })).toBeUndefined();
+ expect(buildDoubaoSpeechAuthHeaders({ apiKey: ' ' })).toBeUndefined();
+ });
+
+ it('normalizes the base URL', () => {
+ expect(normalizeDoubaoSpeechBaseURL()).toBe('https://openspeech.bytedance.com');
+ expect(normalizeDoubaoSpeechBaseURL('https://x.example.com/api/v3')).toBe(
+ 'https://x.example.com',
+ );
+ });
+
+ it('sends no pitch addition at the neutral pitch', () => {
+ const { body } = buildDoubaoSpeechRequest(
+ { input: 'Hi', model: 'seed-tts-2.0', params: { pitch: 0 }, voice: VOICE },
+ 'uid',
+ );
+
+ expect(body.req_params).not.toHaveProperty('additions');
+ });
+
+ it('reads frames written back to back', () => {
+ const body = `${JSON.stringify({ code: 0, data: b64([7]) })}${JSON.stringify({ code: 20_000_000 })}`;
+
+ expect(new Uint8Array(readDoubaoSpeechFrames(body, 200).audio)).toEqual(new Uint8Array([7]));
+ });
+
+ it('does not split a frame on braces inside a string', () => {
+ const body = [
+ JSON.stringify({ code: 0, data: b64([7]) }),
+ JSON.stringify({ code: 45_000_001, message: 'bad req_params}{"x":1}' }),
+ ].join('');
+
+ expect(() => readDoubaoSpeechFrames(body, 200)).toThrow('bad req_params}{"x":1}');
+ });
+
+ it('rejects an unreadable frame', () => {
+ expect(() => readDoubaoSpeechFrames('not json', 200)).toThrow('unreadable response frame');
+ });
+});
diff --git a/packages/model-runtime/src/providers/doubaospeech/createSpeech.ts b/packages/model-runtime/src/providers/doubaospeech/createSpeech.ts
new file mode 100644
index 00000000000..57f247df435
--- /dev/null
+++ b/packages/model-runtime/src/providers/doubaospeech/createSpeech.ts
@@ -0,0 +1,507 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import createDebug from 'debug';
+import type { TTSAudioFormat } from 'model-bank';
+import {
+ DEFAULT_TTS_AUDIO_FORMAT,
+ DOUBAO_SPEECH_DEFAULT_VOICE_ID,
+ DOUBAO_SPEECH_VOICE_IDS,
+ validateTTSParams,
+} from 'model-bank';
+import doubaoSpeechModels from 'model-bank/doubaospeech';
+
+import {
+ convertTextToSpeechUsage,
+ countTextToSpeechCharacters,
+} 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:doubaospeech');
+
+export const DEFAULT_DOUBAO_SPEECH_BASE_URL = 'https://openspeech.bytedance.com';
+
+/**
+ * Characters per request. The audio comes back in one inline response, so a longer request
+ * would exceed the serverless response limit only after the synthesis was billed. Enforced
+ * here as well as in the TTS service, so routed aliases are capped too.
+ */
+export const DOUBAO_SPEECH_MAX_INPUT_CHARACTERS = 4096;
+
+/** Final frame of a successful V3 synthesis. */
+const DOUBAO_SPEECH_DONE_CODE = 20_000_000;
+
+/** `audio_params.format` per standard format; `ogg_opus` is always 48 kHz. */
+const DOUBAO_SPEECH_FORMATS: Partial<Record<TTSAudioFormat, string>> = {
+ mp3: 'mp3',
+ opus: 'ogg_opus',
+ pcm: 'pcm',
+ wav: 'wav',
+};
+
+/** Credentials of either console: a new-console API key, or a legacy App ID + Access Token. */
+export interface DoubaoSpeechCredentials {
+ accessToken?: string;
+ apiKey?: string;
+ appId?: string;
+}
+
+export interface DoubaoSpeechOptions
+ extends DoubaoSpeechCredentials, ModelIdMappingOptions, TextToSpeechOptions {
+ /** API host, e.g. `https://openspeech.bytedance.com`. */
+ baseURL: string;
+ /** Provider id used for pricing lookup and error payloads. */
+ provider: string;
+}
+
+/** Thrown inside the request flow and unwrapped into a runtime error payload. */
+class DoubaoSpeechError extends Error {
+ constructor(
+ message: string,
+ readonly errorType: ILobeAgentRuntimeErrorType,
+ readonly detail?: Record<string, unknown>,
+ ) {
+ super(message);
+ }
+}
+
+/** Strip trailing `char`s with a linear scan (a `/x+$/` regex backtracks quadratically). */
+const trimTrailing = (value: string, char: string) => {
+ let end = value.length;
+ while (end > 0 && value[end - 1] === char) end--;
+ return value.slice(0, end);
+};
+
+/** Accepts the host with or without a trailing `/api/v3`, since users often paste either. */
+export const normalizeDoubaoSpeechBaseURL = (baseURL?: string | null) => {
+ const url = trimTrailing(baseURL?.trim() || DEFAULT_DOUBAO_SPEECH_BASE_URL, '/');
+ return url.endsWith('/api/v3') ? url.slice(0, -7) : url;
+};
+
+/**
+ * Auth headers: the new console's `X-Api-Key`, or the legacy console's App ID + Access
+ * Token. An API key wins when both are configured.
+ * @see https://www.volcengine.com/docs/6561/2528925
+ * @see https://www.volcengine.com/docs/6561/1598757
+ */
+export const buildDoubaoSpeechAuthHeaders = ({
+ accessToken,
+ apiKey,
+ appId,
+}: DoubaoSpeechCredentials): Record<string, string> | undefined => {
+ if (apiKey?.trim()) return { 'X-Api-Key': apiKey.trim() };
+ if (appId?.trim() && accessToken?.trim()) {
+ return { 'X-Api-Access-Key': accessToken.trim(), 'X-Api-App-Id': appId.trim() };
+ }
+};
+
+/**
+ * Voice clones (`S_*`) are spoken by the voice-cloning resource of the same generation,
+ * not the synthesis one; a mismatched resource is rejected upstream. Both 2.0 resources
+ * are billed at the same per-character price.
+ * @see https://www.volcengine.com/docs/6561/1359370
+ */
+const DOUBAO_SPEECH_CLONE_RESOURCES: Record<string, string> = {
+ 'seed-tts-1.0': 'seed-icl-1.0',
+ 'seed-tts-1.0-concurr': 'seed-icl-1.0-concurr',
+ 'seed-tts-2.0': 'seed-icl-2.0',
+};
+
+/**
+ * Documented `X-Api-Resource-Id` values. Anything else is a typo or an invented id, so it is
+ * refused before the request instead of spending a round trip on an upstream rejection.
+ * @see https://www.volcengine.com/docs/6561/1598757
+ */
+export const DOUBAO_SPEECH_RESOURCES: ReadonlySet<string> = new Set([
+ ...Object.keys(DOUBAO_SPEECH_CLONE_RESOURCES),
+ ...Object.values(DOUBAO_SPEECH_CLONE_RESOURCES),
+]);
+
+/** `X-Api-Resource-Id` for a model and voice: the cloning resource for a voice clone. */
+export const resolveDoubaoSpeechResource = (model: string, speaker: string) =>
+ speaker.startsWith('S_') ? (DOUBAO_SPEECH_CLONE_RESOURCES[model] ?? model) : model;
+
+export const DOUBAO_SPEECH_MISSING_CREDENTIALS_MESSAGE =
+ 'Doubao Speech needs an API Key, or an App ID together with its Access Token';
+
+/** Standard 0.5x–2x multiplier onto the V3 -50..100 percentage scale. */
+const toRate = (value: number) => Math.round((value - 1) * 100);
+
+/**
+ * Map the standard TTS payload onto a V3 `req_params`. Only parameters the caller set are
+ * sent, so the voice keeps its own defaults otherwise.
+ */
+export const buildDoubaoSpeechRequest = (
+ payload: TextToSpeechPayload,
+ uid: string,
+): { body: Record<string, unknown>; format: TTSAudioFormat } => {
+ const speaker = payload.voice?.trim();
+ if (!speaker) {
+ throw new DoubaoSpeechError(
+ 'Doubao Speech requires a voice id',
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const params = resolveTextToSpeechParams(payload);
+ const format = params.format ?? DEFAULT_TTS_AUDIO_FORMAT;
+ const upstreamFormat = DOUBAO_SPEECH_FORMATS[format];
+ if (!upstreamFormat) {
+ throw new DoubaoSpeechError(
+ `Doubao Speech does not support the "${format}" format`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const audioParams: Record<string, unknown> = { format: upstreamFormat };
+ // Opus is only produced at 48 kHz: refuse another explicit rate rather than silently
+ // returning audio at a rate the caller did not ask for.
+ if (format === 'opus') {
+ if (params.sampleRate !== undefined && params.sampleRate !== 48_000) {
+ throw new DoubaoSpeechError(
+ `Doubao Speech opus is only produced at 48000 Hz; ${params.sampleRate} Hz is not supported`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+ audioParams.sample_rate = 48_000;
+ } else if (params.sampleRate !== undefined) audioParams.sample_rate = params.sampleRate;
+ if (params.speed !== undefined) audioParams.speech_rate = toRate(params.speed);
+ if (params.volume !== undefined) audioParams.loudness_rate = toRate(params.volume);
+
+ const reqParams: Record<string, unknown> = {
+ audio_params: audioParams,
+ speaker,
+ text: payload.input,
+ };
+ // `additions` is a JSON string, not an object.
+ if (params.pitch !== undefined && params.pitch !== 0) {
+ reqParams.additions = JSON.stringify({ post_process: { pitch: Math.round(params.pitch) } });
+ }
+
+ return { body: { req_params: reqParams, user: { uid } }, format };
+};
+
+interface DoubaoSpeechFrame {
+ code?: number;
+ data?: string | null;
+ header?: { code?: number; message?: string };
+ message?: string;
+ usage?: { text_words?: number };
+}
+
+/**
+ * Error type for a V3 failure. The 8-digit codes are coarse (45000000 covers bad input,
+ * concurrency and voice permission alike), so the message decides first.
+ * @see https://www.volcengine.com/docs/6561/2534853
+ */
+const classifyDoubaoSpeechError = (
+ httpStatus: number,
+ message: string,
+): ILobeAgentRuntimeErrorType => {
+ if (/quota exceeded for types:\s*concurrency|too many requests|rate limit/i.test(message))
+ return AgentRuntimeErrorType.RateLimitExceeded;
+ if (/quota exceeded|insufficient|balance|arrear|欠费|余额/i.test(message))
+ return AgentRuntimeErrorType.InsufficientQuota;
+ if (/speaker permission denied|access denied/i.test(message))
+ return AgentRuntimeErrorType.PermissionDenied;
+ if (
+ /grant not found|invalid (?:api[\s_-]?key|x-api-key|token|app[\s_-]?id|access[\s_-]?key)|authenticat|unauthori[sz]ed|api key (?:is )?(?:invalid|not found)/i.test(
+ message,
+ )
+ )
+ return AgentRuntimeErrorType.InvalidProviderAPIKey;
+
+ if (httpStatus === 401) return AgentRuntimeErrorType.InvalidProviderAPIKey;
+ if (httpStatus === 403) return AgentRuntimeErrorType.PermissionDenied;
+ if (httpStatus === 429) return AgentRuntimeErrorType.RateLimitExceeded;
+ return AgentRuntimeErrorType.ProviderBizError;
+};
+
+/** Extra guidance for errors whose upstream wording is not actionable on its own. */
+const errorHint = (errorType: ILobeAgentRuntimeErrorType, message: string) => {
+ if (/mismatched with speaker/i.test(message))
+ return 'The voice does not belong to this model version, or the Doubao Speech 2.0 service is not enabled for the account.';
+ if (errorType === AgentRuntimeErrorType.PermissionDenied)
+ return 'Enable the voice for this account in the Volcengine speech console, or pick another voice.';
+};
+
+const toSpeechError = (
+ httpStatus: number,
+ frame: DoubaoSpeechFrame | undefined,
+ fallbackMessage: string,
+ logId?: string | null,
+): DoubaoSpeechError => {
+ const code = frame?.code ?? frame?.header?.code;
+ const message = frame?.message || frame?.header?.message || fallbackMessage;
+ const errorType = classifyDoubaoSpeechError(httpStatus, message);
+ const hint = errorHint(errorType, message);
+ const label = code ? `${httpStatus}, code ${code}` : `${httpStatus}`;
+
+ return new DoubaoSpeechError(
+ `Doubao Speech API error (${label}): ${hint ? `${trimTrailing(message, '.')}. ${hint}` : message}`,
+ errorType,
+ { code, logId: logId ?? undefined, status: httpStatus },
+ );
+};
+
+const parseFrame = (line: string): DoubaoSpeechFrame | undefined => {
+ try {
+ const frame = JSON.parse(line);
+ return frame && typeof frame === 'object' ? (frame as DoubaoSpeechFrame) : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Split a V3 response into its top-level JSON frames. Frames are newline-delimited, but
+ * frames written back to back are tolerated too; braces inside strings (e.g. an error
+ * message) do not split a frame. Text outside any object is kept as its own chunk so it
+ * fails to parse instead of being dropped.
+ */
+export const splitDoubaoSpeechFrames = (body: string): string[] => {
+ const frames: string[] = [];
+ let depth = 0;
+ let inString = false;
+ let escaped = false;
+ let start = 0;
+
+ const push = (end: number) => {
+ const frame = body.slice(start, end).trim();
+ if (frame) frames.push(frame);
+ start = end;
+ };
+
+ for (let i = 0; i < body.length; i++) {
+ const char = body[i];
+ if (inString) {
+ if (escaped) escaped = false;
+ else if (char === '\\') escaped = true;
+ else if (char === '"') inString = false;
+ continue;
+ }
+ if (char === '"') inString = true;
+ else if (char === '{') {
+ if (depth === 0) push(i);
+ depth++;
+ } else if (char === '}' && depth > 0) {
+ depth--;
+ if (depth === 0) push(i + 1);
+ }
+ }
+ push(body.length);
+
+ return frames;
+};
+
+/**
+ * Read the V3 chunked response: each frame carries a base64 audio chunk (`code` 0) until
+ * the `20000000` frame, which may report the billed `usage.text_words`. A response that
+ * ends without that frame or without audio is an error, so a cut stream is never billed
+ * as a success.
+ */
+export const readDoubaoSpeechFrames = (
+ body: string,
+ httpStatus: number,
+ logId?: string | null,
+): { audio: ArrayBuffer; textWords?: number } => {
+ const chunks: Uint8Array[] = [];
+ let done = false;
+ let textWords: number | undefined;
+
+ for (const line of splitDoubaoSpeechFrames(body)) {
+ const frame = parseFrame(line);
+ if (!frame) {
+ throw new DoubaoSpeechError(
+ 'Doubao Speech returned an unreadable response frame',
+ AgentRuntimeErrorType.ProviderBizError,
+ { logId: logId ?? undefined },
+ );
+ }
+
+ const code = frame.code ?? frame.header?.code ?? 0;
+ if (code === DOUBAO_SPEECH_DONE_CODE) {
+ done = true;
+ if (typeof frame.usage?.text_words === 'number') textWords = frame.usage.text_words;
+ break;
+ }
+ if (code !== 0) throw toSpeechError(httpStatus, frame, 'synthesis failed', logId);
+ if (frame.data) chunks.push(Uint8Array.from(Buffer.from(frame.data, 'base64')));
+ }
+
+ const byteLength = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
+ if (!done || byteLength === 0) {
+ throw new DoubaoSpeechError(
+ done
+ ? 'Doubao Speech returned empty audio'
+ : 'Doubao Speech response ended before the synthesis finished',
+ AgentRuntimeErrorType.ProviderBizError,
+ { logId: logId ?? undefined },
+ );
+ }
+
+ const audio = new Uint8Array(byteLength);
+ let offset = 0;
+ for (const chunk of chunks) {
+ audio.set(chunk, offset);
+ offset += chunk.byteLength;
+ }
+
+ return { audio: audio.buffer, textWords };
+};
+
+/** Opaque per-user id for `user.uid`, so the raw LobeHub user id never leaves the server. */
+const hashUid = async (user?: string) => {
+ if (!user) return 'lobehub';
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(user));
+ return Array.from(new Uint8Array(digest).slice(0, 16), (byte) =>
+ byte.toString(16).padStart(2, '0'),
+ ).join('');
+};
+
+/**
+ * Synthesize speech with Doubao Speech's V3 `POST /api/v3/tts/unidirectional`. The model id
+ * is the `X-Api-Resource-Id`; usage is the billed `usage.text_words` when the final frame
+ * reports it, otherwise the input character count (Doubao bills one per character).
+ * @see https://www.volcengine.com/docs/6561/2528925
+ */
+export async function createDoubaoSpeech(
+ request: TextToSpeechPayload,
+ options: DoubaoSpeechOptions,
+): Promise<TextToSpeechResponse> {
+ const { provider } = options;
+ const baseURL = normalizeDoubaoSpeechBaseURL(options.baseURL);
+
+ // A caller-omitted voice may have been filled from another vendor's default (e.g. a routed
+ // alias without a static card gets `alloy`); use the Doubao Speech default instead.
+ const payload: TextToSpeechPayload =
+ request.voiceIsDefault && !DOUBAO_SPEECH_VOICE_IDS.has(request.voice)
+ ? { ...request, voice: DOUBAO_SPEECH_DEFAULT_VOICE_ID }
+ : request;
+ const requestModel = resolveMappedModelId(payload.model, options);
+
+ let result: TextToSpeechResponse;
+ try {
+ const authHeaders = buildDoubaoSpeechAuthHeaders(options);
+ if (!authHeaders) {
+ throw new DoubaoSpeechError(
+ DOUBAO_SPEECH_MISSING_CREDENTIALS_MESSAGE,
+ AgentRuntimeErrorType.InvalidProviderAPIKey,
+ );
+ }
+
+ if (!DOUBAO_SPEECH_RESOURCES.has(requestModel)) {
+ throw new DoubaoSpeechError(
+ `Unknown Doubao Speech model "${requestModel}"; expected one of ${[...DOUBAO_SPEECH_RESOURCES].join(', ')}`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ // A mapped alias matches no card in the TTS service, so validate against the resolved
+ // model's card before anything reaches Doubao.
+ const card = doubaoSpeechModels.find((model) => model.id === requestModel);
+ const issues = card?.parameters
+ ? validateTTSParams(card.parameters, resolveTextToSpeechParams(payload))
+ : [];
+ if (issues.length > 0) {
+ throw new DoubaoSpeechError(
+ `Doubao Speech ${requestModel}: ${issues.map(({ key, reason }) => `params.${key} ${reason}`).join('; ')}`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const inputCharacters = countTextToSpeechCharacters(payload.input);
+ if (inputCharacters > DOUBAO_SPEECH_MAX_INPUT_CHARACTERS) {
+ throw new DoubaoSpeechError(
+ `Doubao Speech input is ${inputCharacters} characters; the limit is ${DOUBAO_SPEECH_MAX_INPUT_CHARACTERS} per request. Split the text into shorter requests.`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+ if (!payload.input.trim()) {
+ throw new DoubaoSpeechError(
+ 'Doubao Speech input is empty',
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const { body, format } = buildDoubaoSpeechRequest(payload, await hashUid(options.user));
+ const speaker = (body.req_params as { speaker: string }).speaker;
+ const resource = resolveDoubaoSpeechResource(requestModel, speaker);
+ // Alias-specific pricing wins; an unpriced alias falls back to the model actually called.
+ const pricing =
+ (await getModelPricing(payload.model, provider, options.pricingContext)) ??
+ (requestModel !== payload.model
+ ? await getModelPricing(requestModel, provider, options.pricingContext)
+ : undefined);
+
+ log('tts request: resource=%s speaker=%s format=%s', resource, speaker, format);
+
+ const response = await fetch(`${baseURL}/api/v3/tts/unidirectional`, {
+ body: JSON.stringify(body),
+ headers: {
+ ...options.headers,
+ ...authHeaders,
+ 'Content-Type': 'application/json',
+ 'X-Api-Request-Id': crypto.randomUUID(),
+ 'X-Api-Resource-Id': resource,
+ 'X-Control-Require-Usage-Tokens-Return': 'text_words',
+ },
+ method: 'POST',
+ signal: options.signal,
+ });
+
+ const logId = response.headers.get('x-tt-logid');
+ const text = await response.text();
+
+ if (!response.ok) {
+ const [firstLine] = splitDoubaoSpeechFrames(text);
+ throw toSpeechError(
+ response.status,
+ firstLine ? parseFrame(firstLine) : undefined,
+ text.slice(0, 500) || response.statusText || 'request failed',
+ logId,
+ );
+ }
+
+ const { audio, textWords } = readDoubaoSpeechFrames(text, response.status, logId);
+
+ log('tts done: %d bytes, text_words=%s, logid=%s', audio.byteLength, textWords, logId);
+
+ const usage = convertTextToSpeechUsage(
+ payload.input,
+ pricing,
+ textWords === undefined ? undefined : { inputCharacters: textWords },
+ );
+
+ result = { audio, format, usage };
+ } catch (error) {
+ log('createDoubaoSpeech error: %O', error);
+
+ if ((error as Error)?.name === 'AbortError') throw error;
+
+ const errorType =
+ error instanceof DoubaoSpeechError ? error.errorType : AgentRuntimeErrorType.ProviderBizError;
+
+ throw AgentRuntimeError.chat({
+ error: {
+ message: (error as Error)?.message ?? String(error),
+ ...(error instanceof DoubaoSpeechError ? error.detail : undefined),
+ },
+ errorType,
+ provider,
+ } satisfies ChatCompletionErrorPayload);
+ }
+
+ await options.onUsage?.(result.usage!);
+
+ return result;
+}
diff --git a/packages/model-runtime/src/providers/doubaospeech/index.test.ts b/packages/model-runtime/src/providers/doubaospeech/index.test.ts
new file mode 100644
index 00000000000..1abe8eff0bb
--- /dev/null
+++ b/packages/model-runtime/src/providers/doubaospeech/index.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment node
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ModelRuntime } from '../../core/ModelRuntime';
+import { providerRuntimeMap } from '../../runtimeMap';
+import { getModelPricing } from '../../utils/getModelPricing';
+import { LobeDoubaoSpeechAI } from './index';
+
+vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));
+
+const VOICE = 'zh_female_vv_uranus_bigtts';
+
+const streamResponse = () =>
+ new Response(
+ [
+ JSON.stringify({ code: 0, data: Buffer.from([1, 2, 3]).toString('base64') }),
+ JSON.stringify({ code: 20_000_000, message: 'ok', usage: { text_words: 5 } }),
+ ].join('\n'),
+ );
+
+describe('LobeDoubaoSpeechAI', () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ fetchMock = vi.fn(async () => streamResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ vi.mocked(getModelPricing).mockResolvedValue({
+ currency: 'CNY',
+ units: [{ name: 'textInput', rate: 300, strategy: 'fixed', unit: 'millionCharacters' }],
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ describe('constructor', () => {
+ it.each([
+ ['no options', undefined],
+ ['an empty key', { apiKey: ' ' }],
+ ['an App ID without its Access Token', { appId: 'app' }],
+ ['an Access Token without its App ID', { accessToken: 'token' }],
+ ])('throws InvalidProviderAPIKey with %s', (_, params) => {
+ expect(() => new LobeDoubaoSpeechAI(params)).toThrow(
+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),
+ );
+ });
+
+ it('accepts either console credentials', () => {
+ expect(() => new LobeDoubaoSpeechAI({ apiKey: 'k' })).not.toThrow();
+ expect(() => new LobeDoubaoSpeechAI({ accessToken: 't', appId: 'a' })).not.toThrow();
+ });
+
+ it('defaults to the openspeech host and accepts an override', () => {
+ expect(new LobeDoubaoSpeechAI({ apiKey: 'k' }).baseURL).toBe(
+ 'https://openspeech.bytedance.com',
+ );
+ expect(
+ new LobeDoubaoSpeechAI({ apiKey: 'k', baseURL: 'https://proxy.example.com/' }).baseURL,
+ ).toBe('https://proxy.example.com');
+ });
+ });
+
+ it('synthesizes with the legacy credentials through the configured host', async () => {
+ const runtime = new LobeDoubaoSpeechAI({
+ accessToken: 'token',
+ appId: 'app',
+ baseURL: 'https://proxy.example.com',
+ });
+
+ const result = await runtime.textToSpeech({
+ input: 'Hello',
+ model: 'seed-tts-2.0',
+ voice: VOICE,
+ });
+
+ const [url, init] = fetchMock.mock.calls[0] as any;
+ expect(url).toBe('https://proxy.example.com/api/v3/tts/unidirectional');
+ expect(init.headers['X-Api-App-Id']).toBe('app');
+ expect(init.headers['X-Api-Access-Key']).toBe('token');
+ expect(result.format).toBe('mp3');
+ expect(result.usage?.inputCharacters).toBe(5);
+ });
+
+ it('uses its provider id for pricing, overridable for custom providers', async () => {
+ await new LobeDoubaoSpeechAI({ apiKey: 'k', id: 'my-doubao' }).textToSpeech({
+ input: 'Hi',
+ model: 'seed-tts-2.0',
+ voice: VOICE,
+ });
+
+ expect(getModelPricing).toHaveBeenCalledWith('seed-tts-2.0', 'my-doubao', undefined);
+ });
+
+ describe('via ModelRuntime', () => {
+ it("is registered in the runtime map under 'doubaospeech'", () => {
+ expect(providerRuntimeMap.doubaospeech).toBe(LobeDoubaoSpeechAI);
+ });
+
+ it("initializes from the provider id 'doubaospeech' instead of falling back to OpenAI", () => {
+ const runtime = ModelRuntime.initializeWithProvider('doubaospeech', { apiKey: 'k' });
+
+ expect(runtime['_runtime']).toBeInstanceOf(LobeDoubaoSpeechAI);
+ });
+
+ it('rejects initialization without credentials', () => {
+ expect(() => ModelRuntime.initializeWithProvider('doubaospeech', {})).toThrow(
+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),
+ );
+ });
+
+ it('runs textToSpeech end to end and reports usage to the final hook', async () => {
+ const onTextToSpeechFinal = vi.fn();
+ const runtime = ModelRuntime.initializeWithProvider(
+ 'doubaospeech',
+ { apiKey: 'k' },
+ { onTextToSpeechFinal },
+ );
+
+ const result = await runtime.textToSpeech(
+ { input: 'Hello', model: 'seed-tts-2.0', voice: VOICE },
+ { metadata: { trigger: 'tts' } },
+ );
+
+ expect(new Uint8Array(result!.audio)).toEqual(new Uint8Array([1, 2, 3]));
+ expect(onTextToSpeechFinal).toHaveBeenCalledWith(
+ expect.objectContaining({ usage: expect.objectContaining({ inputCharacters: 5 }) }),
+ expect.anything(),
+ );
+ });
+
+ it('surfaces upstream errors through the error hook instead of failing silently', async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ code: 45_000_000, message: 'requested grant not found' }), {
+ status: 401,
+ }),
+ );
+ const onTextToSpeechError = vi.fn();
+ const runtime = ModelRuntime.initializeWithProvider(
+ 'doubaospeech',
+ { apiKey: 'bad' },
+ { onTextToSpeechError },
+ );
+
+ await expect(
+ runtime.textToSpeech({ input: 'Hi', model: 'seed-tts-2.0', voice: VOICE }),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey });
+ expect(onTextToSpeechError).toHaveBeenCalledWith(
+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),
+ expect.anything(),
+ );
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/doubaospeech/index.ts b/packages/model-runtime/src/providers/doubaospeech/index.ts
new file mode 100644
index 00000000000..01fc7de9a4e
--- /dev/null
+++ b/packages/model-runtime/src/providers/doubaospeech/index.ts
@@ -0,0 +1,64 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { ModelProvider } from 'model-bank';
+
+import type { LobeRuntimeAI } from '../../core/BaseAI';
+import type { TextToSpeechOptions, TextToSpeechPayload } from '../../types/tts';
+import { AgentRuntimeError } from '../../utils/createError';
+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
+import type { DoubaoSpeechCredentials } from './createSpeech';
+import {
+ buildDoubaoSpeechAuthHeaders,
+ createDoubaoSpeech,
+ DOUBAO_SPEECH_MISSING_CREDENTIALS_MESSAGE,
+ normalizeDoubaoSpeechBaseURL,
+} from './createSpeech';
+
+export interface LobeDoubaoSpeechAIParams extends DoubaoSpeechCredentials, ModelIdMappingOptions {
+ baseURL?: string | null;
+ /** Provider id for pricing and error payloads; custom providers pass their own id. */
+ id?: string;
+}
+
+/**
+ * Doubao Speech is text-to-speech only, so the runtime implements `textToSpeech` alone;
+ * chat, image and other calls resolve to `undefined` through `ModelRuntime`.
+ */
+export class LobeDoubaoSpeechAI implements LobeRuntimeAI {
+ baseURL: string;
+ private credentials: DoubaoSpeechCredentials;
+ private id: string;
+ private modelIdMapping?: ModelIdMappingOptions['modelIdMapping'];
+
+ constructor({
+ accessToken,
+ apiKey,
+ appId,
+ baseURL,
+ id,
+ modelIdMapping,
+ }: LobeDoubaoSpeechAIParams = {}) {
+ const credentials = { accessToken, apiKey, appId };
+ // Says which credentials are missing, e.g. an App ID saved without its Access Token.
+ if (!buildDoubaoSpeechAuthHeaders(credentials))
+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey, {
+ message: DOUBAO_SPEECH_MISSING_CREDENTIALS_MESSAGE,
+ });
+
+ this.credentials = credentials;
+ this.baseURL = normalizeDoubaoSpeechBaseURL(baseURL);
+ this.id = id || ModelProvider.DoubaoSpeech;
+ this.modelIdMapping = modelIdMapping;
+ }
+
+ textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {
+ return createDoubaoSpeech(payload, {
+ ...options,
+ ...this.credentials,
+ baseURL: this.baseURL,
+ modelIdMapping: this.modelIdMapping,
+ provider: this.id,
+ });
+ }
+}
+
+export default LobeDoubaoSpeechAI;
diff --git a/packages/model-runtime/src/providers/fishaudio/createSpeech.test.ts b/packages/model-runtime/src/providers/fishaudio/createSpeech.test.ts
new file mode 100644
index 00000000000..f13c0e5182c
--- /dev/null
+++ b/packages/model-runtime/src/providers/fishaudio/createSpeech.test.ts
@@ -0,0 +1,358 @@
+// @vitest-environment node
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import type { Pricing } from 'model-bank';
+import { FISH_AUDIO_DEFAULT_VOICE_ID } from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getModelPricing } from '../../utils/getModelPricing';
+import {
+ buildFishAudioSpeechRequest,
+ buildFishAudioText,
+ countFishAudioBilledBytes,
+ createFishAudioSpeech,
+ FISH_AUDIO_MAX_INPUT_CHARACTERS,
+ FISH_AUDIO_VOICE_HINT,
+ type FishAudioSpeechOptions,
+ normalizeFishAudioBaseURL,
+} from './createSpeech';
+
+vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));
+
+// $15 per million UTF-8 bytes, as on the s2.1-pro card
+const s21Pricing: Pricing = {
+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],
+};
+
+const options: FishAudioSpeechOptions = {
+ apiKey: 'fish-test-key',
+ baseURL: 'https://api.fish.audio',
+ provider: 'fishaudio',
+};
+
+const VOICE = '0123456789abcdef0123456789abcdef';
+const AUDIO_BYTES = new Uint8Array([0x49, 0x44, 0x33, 0x04, 0x00]);
+
+const audioResponse = () =>
+ new Response(AUDIO_BYTES, { headers: { 'content-type': 'audio/mpeg' }, status: 200 });
+
+const errorResponse = (status: number, body: unknown, statusText = '') =>
+ new Response(typeof body === 'string' ? body : JSON.stringify(body), {
+ headers: { 'content-type': typeof body === 'string' ? 'text/plain' : 'application/json' },
+ status,
+ statusText,
+ });
+
+const lastRequest = (fetchMock: ReturnType<typeof vi.fn>) => {
+ const [url, init] = fetchMock.mock.calls.at(-1) as [string, RequestInit];
+ return {
+ body: JSON.parse(init.body as string),
+ headers: init.headers as Record<string, string>,
+ url,
+ };
+};
+
+describe('createFishAudioSpeech', () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ fetchMock = vi.fn(async () => audioResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ vi.mocked(getModelPricing).mockResolvedValue(s21Pricing);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ it('posts to /v1/tts with the bearer key and always sends the model header', async () => {
+ const result = await createFishAudioSpeech(
+ { input: 'Hello', model: 's2.1-pro', voice: VOICE },
+ options,
+ );
+
+ const { body, headers, url } = lastRequest(fetchMock);
+ expect(url).toBe('https://api.fish.audio/v1/tts');
+ expect(headers['Authorization']).toBe('Bearer fish-test-key');
+ expect(headers['model']).toBe('s2.1-pro');
+ expect(headers['Content-Type']).toBe('application/json');
+ expect(body).toEqual({ format: 'mp3', reference_id: VOICE, text: 'Hello' });
+ expect(new Uint8Array(result.audio)).toEqual(AUDIO_BYTES);
+ expect(result.format).toBe('mp3');
+ });
+
+ it('omits reference_id for the built-in default voice', async () => {
+ await createFishAudioSpeech(
+ { input: 'Hi', model: 's2.1-pro', voice: FISH_AUDIO_DEFAULT_VOICE_ID },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body).not.toHaveProperty('reference_id');
+ });
+
+ it('replaces a service-filled default voice of another vendor with the Fish default', async () => {
+ await createFishAudioSpeech(
+ { input: 'Hi', model: 's2.1-pro', voice: 'alloy', voiceIsDefault: true },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body).not.toHaveProperty('reference_id');
+ });
+
+ it('keeps a card default that is a Fish reference id', async () => {
+ await createFishAudioSpeech(
+ { input: 'Hi', model: 's2.1-pro', voice: VOICE, voiceIsDefault: true },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body.reference_id).toBe(VOICE);
+ });
+
+ it('maps speed, format and sample rate', async () => {
+ const result = await createFishAudioSpeech(
+ {
+ input: 'Hi',
+ model: 's2-pro',
+ params: { format: 'opus', sampleRate: 48_000, speed: 1.5 },
+ voice: VOICE,
+ },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body).toEqual({
+ format: 'opus',
+ prosody: { speed: 1.5 },
+ reference_id: VOICE,
+ sample_rate: 48_000,
+ text: 'Hi',
+ });
+ expect(result.format).toBe('opus');
+ });
+
+ it('reads the deprecated top-level speed', async () => {
+ await createFishAudioSpeech(
+ { input: 'Hi', model: 's2.1-pro', speed: 0.8, voice: VOICE },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body.prosody).toEqual({ speed: 0.8 });
+ });
+
+ it('writes instructions as a leading direction and bills it with the text', async () => {
+ const result = await createFishAudioSpeech(
+ {
+ input: '你好',
+ model: 'drama-3',
+ params: { instructions: 'whisper softly' },
+ voice: VOICE,
+ },
+ options,
+ );
+
+ expect(lastRequest(fetchMock).body.text).toBe('[whisper softly] 你好');
+ // 17 ASCII bytes for "[whisper softly] " + 3 bytes per Han character
+ expect(result.usage?.inputCharacters).toBe(23);
+ });
+
+ it('bills UTF-8 bytes: a Han character costs three', async () => {
+ const onUsage = vi.fn();
+ const result = await createFishAudioSpeech(
+ { input: '你好 ok', model: 's2.1-pro', voice: VOICE },
+ { ...options, onUsage },
+ );
+
+ expect(result.usage).toEqual({ cost: 0.000135, inputCharacters: 9 });
+ expect(onUsage).toHaveBeenCalledWith(result.usage);
+ });
+
+ it('honours the model id mapping and prices by the public model id', async () => {
+ await createFishAudioSpeech(
+ { input: 'Hi', model: 'fish-pro', voice: VOICE },
+ { ...options, modelIdMapping: { 'fish-pro': 's2.1-pro' } },
+ );
+
+ expect(lastRequest(fetchMock).headers['model']).toBe('s2.1-pro');
+ expect(getModelPricing).toHaveBeenCalledWith('fish-pro', 'fishaudio', undefined);
+ });
+
+ it('prices an unpriced alias by the model it maps to', async () => {
+ vi.mocked(getModelPricing).mockImplementation(async (model) =>
+ model === 's2.1-pro' ? s21Pricing : undefined,
+ );
+
+ const result = await createFishAudioSpeech(
+ { input: 'Hi', model: 'fish-pro', voice: VOICE },
+ { ...options, modelIdMapping: { 'fish-pro': 's2.1-pro' } },
+ );
+
+ expect(getModelPricing).toHaveBeenCalledWith('fish-pro', 'fishaudio', undefined);
+ expect(getModelPricing).toHaveBeenCalledWith('s2.1-pro', 'fishaudio', undefined);
+ expect(result.usage?.cost).toBeGreaterThan(0);
+ });
+
+ it("validates a mapped alias against the resolved model's card", async () => {
+ await expect(
+ createFishAudioSpeech(
+ { input: 'Hi', model: 'fish-pro', params: { speed: 100 }, voice: VOICE },
+ { ...options, modelIdMapping: { 'fish-pro': 's2.1-pro' } },
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('params.speed') },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ });
+ // S1 takes no instructions; s2.1-pro-free follows the S2.1 Pro schema.
+ await expect(
+ createFishAudioSpeech(
+ { input: 'Hi', model: 'fish-s1', params: { instructions: 'calm' }, voice: VOICE },
+ { ...options, modelIdMapping: { 'fish-s1': 's1' } },
+ ),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBizError });
+ await expect(
+ createFishAudioSpeech(
+ { input: 'Hi', model: 'free', params: { speed: 3 }, voice: VOICE },
+ { ...options, modelIdMapping: { free: 's2.1-pro-free' } },
+ ),
+ ).rejects.toMatchObject({ error: { message: expect.stringContaining('params.speed') } });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ describe('rejects before calling Fish Audio', () => {
+ it.each([
+ ['an unknown model, which Fish would silently serve as S2.1 Pro', { model: 's3-ultra' }],
+ ['an unsupported format', { params: { format: 'aac' as const } }],
+ [
+ 'instructions on S1, which would speak them',
+ { model: 's1', params: { instructions: 'x' } },
+ ],
+ ['empty input', { input: ' ' }],
+ ['a voice id that is not a Fish model id', { voice: 'not_a_real_voice_xyz' }],
+ [
+ 'a sample rate the format does not offer (opus is 48 kHz only)',
+ { params: { format: 'opus' as const, sampleRate: 44_100 } },
+ ],
+ [
+ 'a sample rate mp3 does not offer',
+ { params: { format: 'mp3' as const, sampleRate: 16_000 } },
+ ],
+ ])('%s', async (_, override) => {
+ await expect(
+ createFishAudioSpeech(
+ { input: 'Hi', model: 's2.1-pro', voice: VOICE, ...override },
+ options,
+ ),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBizError });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it(`input over ${FISH_AUDIO_MAX_INPUT_CHARACTERS} characters`, async () => {
+ await expect(
+ createFishAudioSpeech(
+ {
+ input: 'a'.repeat(FISH_AUDIO_MAX_INPUT_CHARACTERS + 1),
+ model: 's2.1-pro',
+ voice: VOICE,
+ },
+ options,
+ ),
+ ).rejects.toMatchObject({
+ error: { message: expect.stringContaining('the limit is 4096') },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('maps upstream errors', () => {
+ it.each([
+ [401, AgentRuntimeErrorType.InvalidProviderAPIKey],
+ [402, AgentRuntimeErrorType.InsufficientQuota],
+ [403, AgentRuntimeErrorType.PermissionDenied],
+ [429, AgentRuntimeErrorType.RateLimitExceeded],
+ [500, AgentRuntimeErrorType.ProviderBizError],
+ ])('HTTP %d → %s with the Fish message', async (status, errorType) => {
+ fetchMock.mockResolvedValueOnce(errorResponse(status, { message: 'nope', status }));
+
+ await expect(
+ createFishAudioSpeech({ input: 'Hi', model: 's2.1-pro', voice: VOICE }, options),
+ ).rejects.toMatchObject({
+ error: { message: `Fish Audio API error (${status}): nope`, status },
+ errorType,
+ provider: 'fishaudio',
+ });
+ });
+
+ it('explains a rejected voice', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(404, { message: 'Reference not found' }));
+
+ await expect(
+ createFishAudioSpeech({ input: 'Hi', model: 's2.1-pro', voice: VOICE }, options),
+ ).rejects.toMatchObject({
+ error: {
+ message: `Fish Audio API error (404): Reference not found. ${FISH_AUDIO_VOICE_HINT}`,
+ },
+ });
+ });
+
+ it('reads plain-text bodies from the edge', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(503, 'upstream overloaded'));
+
+ await expect(
+ createFishAudioSpeech({ input: 'Hi', model: 's2.1-pro', voice: VOICE }, options),
+ ).rejects.toMatchObject({
+ error: { message: 'Fish Audio API error (503): upstream overloaded' },
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ });
+ });
+
+ it('fails on an empty 200 instead of returning silent audio', async () => {
+ fetchMock.mockResolvedValueOnce(new Response(new Uint8Array(), { status: 200 }));
+
+ await expect(
+ createFishAudioSpeech({ input: 'Hi', model: 's2.1-pro', voice: VOICE }, options),
+ ).rejects.toMatchObject({ error: { message: 'Fish Audio returned empty audio' } });
+ });
+
+ it('fails on a JSON 200 body', async () => {
+ fetchMock.mockResolvedValueOnce(errorResponse(200, { message: 'queue full' }));
+
+ await expect(
+ createFishAudioSpeech({ input: 'Hi', model: 's2.1-pro', voice: VOICE }, options),
+ ).rejects.toMatchObject({ error: { message: 'Fish Audio returned no audio: queue full' } });
+ });
+
+ it('rethrows aborts as is', async () => {
+ const abort = Object.assign(new Error('aborted'), { name: 'AbortError' });
+ fetchMock.mockRejectedValueOnce(abort);
+
+ await expect(
+ createFishAudioSpeech({ input: 'Hi', model: 's2.1-pro', voice: VOICE }, options),
+ ).rejects.toBe(abort);
+ });
+ });
+});
+
+describe('Fish Audio request helpers', () => {
+ it('normalizes the base URL', () => {
+ expect(normalizeFishAudioBaseURL()).toBe('https://api.fish.audio');
+ expect(normalizeFishAudioBaseURL('https://proxy.example.com/v1/')).toBe(
+ 'https://proxy.example.com',
+ );
+ });
+
+ it('counts UTF-8 bytes', () => {
+ expect(countFishAudioBilledBytes('abc')).toBe(3);
+ expect(countFishAudioBilledBytes('语音')).toBe(6);
+ expect(countFishAudioBilledBytes('😀')).toBe(4);
+ });
+
+ it('keeps brackets inside a direction from closing it early', () => {
+ expect(buildFishAudioText('Hi', 's2.1-pro', ' [loud] then ')).toBe('[loud then] Hi');
+ expect(buildFishAudioText('Hi', 's1', ' ')).toBe('Hi');
+ });
+
+ it('builds the body for the default voice without prosody', () => {
+ expect(
+ buildFishAudioSpeechRequest({ input: 'Hi', model: 's1', voice: 'default' }, 's1').body,
+ ).toEqual({ format: 'mp3', text: 'Hi' });
+ });
+});
diff --git a/packages/model-runtime/src/providers/fishaudio/createSpeech.ts b/packages/model-runtime/src/providers/fishaudio/createSpeech.ts
new file mode 100644
index 00000000000..0816f3ca613
--- /dev/null
+++ b/packages/model-runtime/src/providers/fishaudio/createSpeech.ts
@@ -0,0 +1,379 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import createDebug from 'debug';
+import type { TTSAudioFormat } from 'model-bank';
+import {
+ DEFAULT_TTS_AUDIO_FORMAT,
+ FISH_AUDIO_DEFAULT_VOICE_ID,
+ FISH_AUDIO_MAX_INPUT_CHARACTERS,
+ FISH_AUDIO_MAX_INSTRUCTIONS_LENGTH,
+ FISH_AUDIO_SAMPLE_RATES,
+ validateTTSParams,
+} from 'model-bank';
+import fishAudioModels from 'model-bank/fishaudio';
+
+import {
+ convertTextToSpeechUsage,
+ countFishAudioBilledBytes,
+ countTextToSpeechCharacters,
+} 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:fishaudio');
+
+export const DEFAULT_FISH_AUDIO_BASE_URL = 'https://api.fish.audio';
+
+export { FISH_AUDIO_MAX_INPUT_CHARACTERS };
+
+/**
+ * Values of the `model` header. Fish Audio does not reject an unknown value: it silently
+ * synthesizes (and bills) with S2.1 Pro, so anything else is refused before the request.
+ * @see https://docs.fish.audio/api-reference/endpoint/openapi-v1/text-to-speech
+ */
+export const FISH_AUDIO_MODELS: ReadonlySet<string> = new Set([
+ 's1',
+ 's2-pro',
+ 's2.1-pro',
+ 's2.1-pro-free',
+ 'drama-3',
+]);
+
+/** Voice model ids are 32 hex characters, as in `fish.audio/m/<id>`. */
+const FISH_AUDIO_REFERENCE_ID = /^[\da-f]{32}$/i;
+
+/** Models that read a leading `[direction]`; S1 would speak it aloud. */
+const DIRECTED_MODELS = new Set(['s2-pro', 's2.1-pro', 's2.1-pro-free', 'drama-3']);
+
+/** Formats `/v1/tts` produces; there is no aac or flac output. */
+const FISH_AUDIO_FORMATS = new Set<TTSAudioFormat>(['mp3', 'opus', 'pcm', 'wav']);
+
+export interface FishAudioSpeechOptions extends ModelIdMappingOptions, TextToSpeechOptions {
+ apiKey: string;
+ /** API host, e.g. `https://api.fish.audio`. */
+ baseURL: string;
+ /** Provider id used for pricing lookup and error payloads. */
+ provider: string;
+}
+
+const HTTP_ERROR_TYPES: Record<number, ILobeAgentRuntimeErrorType> = {
+ 401: AgentRuntimeErrorType.InvalidProviderAPIKey,
+ 402: AgentRuntimeErrorType.InsufficientQuota,
+ 403: AgentRuntimeErrorType.PermissionDenied,
+ 429: AgentRuntimeErrorType.RateLimitExceeded,
+};
+
+/**
+ * Appended when Fish Audio rejects the voice: a `reference_id` that does not exist or that
+ * the account may not use.
+ */
+export const FISH_AUDIO_VOICE_HINT =
+ 'Check the voice id: pass the reference_id of a voice you own or are licensed to use with --voice, or omit --voice for the Fish Audio default voice.';
+
+/** Thrown inside the request flow and unwrapped into a runtime error payload. */
+class FishAudioSpeechError extends Error {
+ constructor(
+ message: string,
+ readonly errorType: ILobeAgentRuntimeErrorType,
+ readonly detail?: Record<string, unknown>,
+ ) {
+ super(message);
+ }
+}
+
+/** Strip trailing `char`s with a linear scan (a `/x+$/` regex backtracks quadratically). */
+const trimTrailing = (value: string, char: string) => {
+ let end = value.length;
+ while (end > 0 && value[end - 1] === char) end--;
+ return value.slice(0, end);
+};
+
+/** Accepts the host with or without a trailing `/v1`, since users often paste either. */
+export const normalizeFishAudioBaseURL = (baseURL?: string | null) => {
+ const url = trimTrailing(baseURL?.trim() || DEFAULT_FISH_AUDIO_BASE_URL, '/');
+ return url.endsWith('/v1') ? url.slice(0, -3) : url;
+};
+
+/** Shared with the OpenAI-compatible path, where gateways bill Fish models the same way. */
+export { countFishAudioBilledBytes };
+
+/**
+ * Text sent to Fish Audio: the S2 family and Drama 3 take a natural-language `[direction]`
+ * written into the text, so `instructions` goes in front of the input.
+ */
+export const buildFishAudioText = (input: string, model: string, instructions?: string) => {
+ const direction = instructions?.trim();
+ if (!direction) return input;
+
+ if (!DIRECTED_MODELS.has(model)) {
+ throw new FishAudioSpeechError(
+ `Fish Audio ${model} does not take instructions`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+ if (direction.length > FISH_AUDIO_MAX_INSTRUCTIONS_LENGTH) {
+ throw new FishAudioSpeechError(
+ `Fish Audio instructions are limited to ${FISH_AUDIO_MAX_INSTRUCTIONS_LENGTH} characters`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ // A bracket inside the direction would close it early and speak the rest.
+ const sanitized = direction.replaceAll(/[[\]]/g, ' ').replaceAll(/\s+/g, ' ').trim();
+ return `[${sanitized}] ${input}`;
+};
+
+/**
+ * Map the standard TTS payload onto a `/v1/tts` request. The built-in default voice sends
+ * no `reference_id`, which makes Fish Audio use its own default voice.
+ */
+export const buildFishAudioSpeechRequest = (
+ payload: TextToSpeechPayload,
+ requestModel: string,
+): { body: Record<string, unknown>; format: TTSAudioFormat; text: string } => {
+ if (!FISH_AUDIO_MODELS.has(requestModel)) {
+ throw new FishAudioSpeechError(
+ `Unknown Fish Audio model "${requestModel}"; expected one of ${[...FISH_AUDIO_MODELS].join(', ')}`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const params = resolveTextToSpeechParams(payload);
+
+ // The TTS service validates against the card of the id it was given; a mapped alias
+ // (`fish-pro` -> `s2.1-pro`) matches none, so check the resolved model's card here.
+ // `s2.1-pro-free` has no card of its own and takes the S2.1 Pro schema.
+ const card =
+ fishAudioModels.find((model) => model.id === requestModel) ??
+ fishAudioModels.find((model) => model.id === requestModel.replace(/-free$/, ''));
+ const issues = card?.parameters ? validateTTSParams(card.parameters, params) : [];
+ if (issues.length > 0) {
+ throw new FishAudioSpeechError(
+ `Fish Audio ${requestModel}: ${issues.map(({ key, reason }) => `params.${key} ${reason}`).join('; ')}`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const format = params.format ?? DEFAULT_TTS_AUDIO_FORMAT;
+ if (!FISH_AUDIO_FORMATS.has(format)) {
+ throw new FishAudioSpeechError(
+ `Fish Audio speech does not support the "${format}" format`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const voice = payload.voice?.trim();
+ // Every Fish voice is a 32-hex model id, so a malformed one can only fail upstream.
+ if (voice && voice !== FISH_AUDIO_DEFAULT_VOICE_ID && !FISH_AUDIO_REFERENCE_ID.test(voice)) {
+ throw new FishAudioSpeechError(
+ `"${voice}" is not a Fish Audio voice id (32 hex characters, as in fish.audio/m/<id>). ${FISH_AUDIO_VOICE_HINT}`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+ // The model card lists every rate Fish accepts; which ones apply depends on the format.
+ if (params.sampleRate !== undefined) {
+ const rates = FISH_AUDIO_SAMPLE_RATES[format as keyof typeof FISH_AUDIO_SAMPLE_RATES] ?? [];
+ if (!rates.includes(params.sampleRate)) {
+ throw new FishAudioSpeechError(
+ `Fish Audio ${format} does not support a ${params.sampleRate} Hz sample rate; use one of ${rates.join(', ')}`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+ }
+ const text = buildFishAudioText(payload.input, requestModel, params.instructions);
+
+ return {
+ body: {
+ format,
+ text,
+ ...(voice && voice !== FISH_AUDIO_DEFAULT_VOICE_ID && { reference_id: voice }),
+ ...(params.sampleRate !== undefined && { sample_rate: params.sampleRate }),
+ ...(params.speed !== undefined && { prosody: { speed: params.speed } }),
+ },
+ format,
+ text,
+ };
+};
+
+interface FishAudioErrorBody {
+ detail?: unknown;
+ message?: string;
+ reason?: string;
+ status?: number;
+}
+
+const readErrorBody = async (response: Response): Promise<FishAudioErrorBody | undefined> => {
+ const text = await response.text().catch(() => '');
+ if (!text) return;
+
+ try {
+ const body = JSON.parse(text);
+ return body && typeof body === 'object' ? (body as FishAudioErrorBody) : { message: text };
+ } catch {
+ // Edge proxies answer 413 / 5xx in plain text.
+ return { message: text.slice(0, 500) };
+ }
+};
+
+const readableMessage = (body?: FishAudioErrorBody): string | undefined => {
+ if (!body) return;
+ if (typeof body.message === 'string' && body.message) return body.message;
+ if (typeof body.detail === 'string' && body.detail) return body.detail;
+ if (Array.isArray(body.detail)) {
+ // FastAPI-style validation errors `[{ loc, msg }]`.
+ const message = body.detail
+ .map((item) => (item && typeof item === 'object' ? (item as { msg?: string }).msg : ''))
+ .filter(Boolean)
+ .join('; ');
+ return message || undefined;
+ }
+ if (typeof body.reason === 'string' && body.reason) return body.reason;
+};
+
+/** Turn a failed `/v1/tts` response into a typed error with a readable message. */
+const toSpeechError = async (
+ response: Response,
+ sentReferenceId: boolean,
+): Promise<FishAudioSpeechError> => {
+ const body = await readErrorBody(response);
+ const reason = readableMessage(body) || response.statusText || 'request failed';
+ // 400 covers a missing reference_id as well as bad parameters; 404 a missing voice or model.
+ const voiceRejected =
+ sentReferenceId &&
+ (response.status === 404 || (response.status === 400 && /reference|voice|model/i.test(reason)));
+
+ return new FishAudioSpeechError(
+ voiceRejected
+ ? `Fish Audio API error (${response.status}): ${trimTrailing(reason, '.')}. ${FISH_AUDIO_VOICE_HINT}`
+ : `Fish Audio API error (${response.status}): ${reason}`,
+ HTTP_ERROR_TYPES[response.status] ?? AgentRuntimeErrorType.ProviderBizError,
+ { detail: body, status: response.status },
+ );
+};
+
+/**
+ * Synthesize speech with Fish Audio's `POST /v1/tts`, which returns the audio bytes
+ * directly. Usage is the UTF-8 byte count of the text sent (including a direction), which
+ * is what the per-byte API price applies to.
+ * @see https://docs.fish.audio/api-reference/endpoint/openapi-v1/text-to-speech
+ */
+export async function createFishAudioSpeech(
+ request: TextToSpeechPayload,
+ options: FishAudioSpeechOptions,
+): Promise<TextToSpeechResponse> {
+ const { apiKey, provider } = options;
+ const baseURL = normalizeFishAudioBaseURL(options.baseURL);
+
+ // A caller-omitted voice may have been filled from another vendor's default (e.g. a routed
+ // alias without a static card gets `alloy`); use the Fish Audio default voice instead.
+ const payload: TextToSpeechPayload =
+ request.voiceIsDefault && !FISH_AUDIO_REFERENCE_ID.test(request.voice)
+ ? { ...request, voice: FISH_AUDIO_DEFAULT_VOICE_ID }
+ : request;
+ const requestModel = resolveMappedModelId(payload.model, options);
+
+ let result: TextToSpeechResponse;
+ try {
+ const inputCharacters = countTextToSpeechCharacters(payload.input);
+ if (inputCharacters > FISH_AUDIO_MAX_INPUT_CHARACTERS) {
+ throw new FishAudioSpeechError(
+ `Fish Audio speech input is ${inputCharacters} characters; the limit is ${FISH_AUDIO_MAX_INPUT_CHARACTERS} per request. Split the text into shorter requests.`,
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+ if (!payload.input.trim()) {
+ throw new FishAudioSpeechError(
+ 'Fish Audio speech input is empty',
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ const { body, format, text } = buildFishAudioSpeechRequest(payload, requestModel);
+ // Alias-specific pricing wins; an unpriced alias falls back to the model actually called.
+ const pricing =
+ (await getModelPricing(payload.model, provider, options.pricingContext)) ??
+ (requestModel !== payload.model
+ ? await getModelPricing(requestModel, provider, options.pricingContext)
+ : undefined);
+
+ log(
+ 'tts request: model=%s reference_id=%s format=%s',
+ requestModel,
+ body.reference_id ?? '(default)',
+ format,
+ );
+
+ const response = await fetch(`${baseURL}/v1/tts`, {
+ body: JSON.stringify(body),
+ headers: {
+ ...options.headers,
+ 'Authorization': `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ // Always sent: a missing header silently falls back to S2.1 Pro.
+ 'model': requestModel,
+ },
+ method: 'POST',
+ signal: options.signal,
+ });
+
+ if (!response.ok) throw await toSpeechError(response, 'reference_id' in body);
+
+ // A 200 carries raw audio; a JSON body would be an error the gateway passed through.
+ if (response.headers.get('content-type')?.includes('application/json')) {
+ const errorBody = await readErrorBody(response);
+ throw new FishAudioSpeechError(
+ `Fish Audio returned no audio: ${readableMessage(errorBody) ?? 'unexpected JSON response'}`,
+ AgentRuntimeErrorType.ProviderBizError,
+ { detail: errorBody },
+ );
+ }
+
+ const audio = await response.arrayBuffer();
+
+ if (audio.byteLength === 0) {
+ throw new FishAudioSpeechError(
+ 'Fish Audio returned empty audio',
+ AgentRuntimeErrorType.ProviderBizError,
+ );
+ }
+
+ log('tts done: %d bytes', audio.byteLength);
+
+ const usage = convertTextToSpeechUsage(text, pricing, {
+ inputCharacters: countFishAudioBilledBytes(text),
+ });
+
+ result = { audio, format, usage };
+ } catch (error) {
+ log('createFishAudioSpeech error: %O', error);
+
+ if ((error as Error)?.name === 'AbortError') throw error;
+
+ const errorType =
+ error instanceof FishAudioSpeechError
+ ? error.errorType
+ : AgentRuntimeErrorType.ProviderBizError;
+
+ throw AgentRuntimeError.chat({
+ error: {
+ message: (error as Error)?.message ?? String(error),
+ ...(error instanceof FishAudioSpeechError ? error.detail : undefined),
+ },
+ errorType,
+ provider,
+ } satisfies ChatCompletionErrorPayload);
+ }
+
+ await options.onUsage?.(result.usage!);
+
+ return result;
+}
diff --git a/packages/model-runtime/src/providers/fishaudio/index.test.ts b/packages/model-runtime/src/providers/fishaudio/index.test.ts
new file mode 100644
index 00000000000..02307f5dbd2
--- /dev/null
+++ b/packages/model-runtime/src/providers/fishaudio/index.test.ts
@@ -0,0 +1,139 @@
+// @vitest-environment node
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ModelRuntime } from '../../core/ModelRuntime';
+import { providerRuntimeMap } from '../../runtimeMap';
+import { getModelPricing } from '../../utils/getModelPricing';
+import { LobeFishAudioAI } from './index';
+
+vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));
+
+describe('LobeFishAudioAI', () => {
+ let fetchMock: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ fetchMock = vi.fn(
+ async () =>
+ new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'audio/mpeg' } }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ vi.mocked(getModelPricing).mockResolvedValue({
+ units: [{ name: 'textInput', rate: 15, strategy: 'fixed', unit: 'millionCharacters' }],
+ });
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+ });
+
+ describe('constructor', () => {
+ it.each([undefined, '', ' '])('throws InvalidProviderAPIKey when the key is %j', (apiKey) => {
+ expect(() => new LobeFishAudioAI({ apiKey })).toThrow(
+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),
+ );
+ });
+
+ it('throws InvalidProviderAPIKey when constructed with no options', () => {
+ expect(() => new LobeFishAudioAI()).toThrow(
+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),
+ );
+ });
+
+ it('defaults to the Fish Audio API host and accepts an override', () => {
+ expect(new LobeFishAudioAI({ apiKey: 'k' }).baseURL).toBe('https://api.fish.audio');
+ expect(
+ new LobeFishAudioAI({ apiKey: 'k', baseURL: 'https://proxy.example.com/' }).baseURL,
+ ).toBe('https://proxy.example.com');
+ });
+ });
+
+ it('synthesizes through the configured host with the trimmed key', async () => {
+ const runtime = new LobeFishAudioAI({
+ apiKey: ' fish-key ',
+ baseURL: 'https://proxy.example.com',
+ });
+
+ const result = await runtime.textToSpeech({
+ input: 'Hello',
+ model: 's2.1-pro',
+ voice: 'default',
+ });
+
+ const [url, init] = fetchMock.mock.calls[0] as any;
+ expect(url).toBe('https://proxy.example.com/v1/tts');
+ expect(init.headers.Authorization).toBe('Bearer fish-key');
+ expect(result.format).toBe('mp3');
+ expect(result.usage).toEqual({ cost: 0.000075, inputCharacters: 5 });
+ });
+
+ it('uses its provider id for pricing, overridable for custom providers', async () => {
+ await new LobeFishAudioAI({ apiKey: 'k', id: 'my-fish' }).textToSpeech({
+ input: 'Hi',
+ model: 's2.1-pro',
+ voice: 'default',
+ });
+
+ expect(getModelPricing).toHaveBeenCalledWith('s2.1-pro', 'my-fish', undefined);
+ });
+
+ describe('via ModelRuntime', () => {
+ it("is registered in the runtime map under 'fishaudio'", () => {
+ expect(providerRuntimeMap.fishaudio).toBe(LobeFishAudioAI);
+ });
+
+ it("initializes from the provider id 'fishaudio' instead of falling back to OpenAI", () => {
+ const runtime = ModelRuntime.initializeWithProvider('fishaudio', { apiKey: 'fish-key' });
+
+ expect(runtime['_runtime']).toBeInstanceOf(LobeFishAudioAI);
+ });
+
+ it('rejects initialization without an API key', () => {
+ expect(() => ModelRuntime.initializeWithProvider('fishaudio', {})).toThrow(
+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),
+ );
+ });
+
+ it('runs textToSpeech end to end and reports usage to the final hook', async () => {
+ const onTextToSpeechFinal = vi.fn();
+ const runtime = ModelRuntime.initializeWithProvider(
+ 'fishaudio',
+ { apiKey: 'fish-key' },
+ { onTextToSpeechFinal },
+ );
+
+ const result = await runtime.textToSpeech(
+ { input: 'Hello', model: 's2.1-pro', params: { format: 'opus' }, voice: 'default' },
+ { metadata: { trigger: 'tts' } },
+ );
+
+ expect(new Uint8Array(result!.audio)).toEqual(new Uint8Array([1, 2, 3]));
+ expect(result!.format).toBe('opus');
+ expect(onTextToSpeechFinal).toHaveBeenCalledWith(
+ expect.objectContaining({ usage: { cost: 0.000075, inputCharacters: 5 } }),
+ expect.anything(),
+ );
+ });
+
+ it('surfaces upstream errors through the error hook instead of failing silently', async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(JSON.stringify({ message: 'Invalid token', status: 401 }), { status: 401 }),
+ );
+ const onTextToSpeechError = vi.fn();
+ const runtime = ModelRuntime.initializeWithProvider(
+ 'fishaudio',
+ { apiKey: 'bad' },
+ { onTextToSpeechError },
+ );
+
+ await expect(
+ runtime.textToSpeech({ input: 'Hi', model: 's2.1-pro', voice: 'default' }),
+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey });
+ expect(onTextToSpeechError).toHaveBeenCalledWith(
+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),
+ expect.anything(),
+ );
+ });
+ });
+});
diff --git a/packages/model-runtime/src/providers/fishaudio/index.ts b/packages/model-runtime/src/providers/fishaudio/index.ts
new file mode 100644
index 00000000000..e44673e0123
--- /dev/null
+++ b/packages/model-runtime/src/providers/fishaudio/index.ts
@@ -0,0 +1,48 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
+import { ModelProvider } from 'model-bank';
+
+import type { LobeRuntimeAI } from '../../core/BaseAI';
+import type { TextToSpeechOptions, TextToSpeechPayload } from '../../types/tts';
+import { AgentRuntimeError } from '../../utils/createError';
+import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
+import { createFishAudioSpeech, normalizeFishAudioBaseURL } from './createSpeech';
+
+export interface LobeFishAudioAIParams extends ModelIdMappingOptions {
+ apiKey?: string;
+ baseURL?: string | null;
+ /** Provider id for pricing and error payloads; custom providers pass their own id. */
+ id?: string;
+}
+
+/**
+ * Fish Audio is text-to-speech only, so the runtime implements `textToSpeech` alone; chat,
+ * image and other calls resolve to `undefined` through `ModelRuntime`.
+ */
+export class LobeFishAudioAI implements LobeRuntimeAI {
+ baseURL: string;
+ private apiKey: string;
+ private id: string;
+ private modelIdMapping?: ModelIdMappingOptions['modelIdMapping'];
+
+ constructor({ apiKey, baseURL, id, modelIdMapping }: LobeFishAudioAIParams = {}) {
+ if (!apiKey?.trim())
+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);
+
+ this.apiKey = apiKey.trim();
+ this.baseURL = normalizeFishAudioBaseURL(baseURL);
+ this.id = id || ModelProvider.FishAudio;
+ this.modelIdMapping = modelIdMapping;
+ }
+
+ textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {
+ return createFishAudioSpeech(payload, {
+ ...options,
+ apiKey: this.apiKey,
+ baseURL: this.baseURL,
+ modelIdMapping: this.modelIdMapping,
+ provider: this.id,
+ });
+ }
+}
+
+export default LobeFishAudioAI;
diff --git a/packages/model-runtime/src/runtimeMap.ts b/packages/model-runtime/src/runtimeMap.ts
index b8ed245f40b..e79ecf73eb3 100644
--- a/packages/model-runtime/src/runtimeMap.ts
+++ b/packages/model-runtime/src/runtimeMap.ts
@@ -18,9 +18,11 @@ import { LobeCohereAI } from './providers/cohere';
import { LobeCometAPIAI } from './providers/cometapi';
import { LobeComfyUI } from './providers/comfyui';
import { LobeDeepSeekAI } from './providers/deepseek';
+import { LobeDoubaoSpeechAI } from './providers/doubaospeech';
import { LobeElevenLabsAI } from './providers/elevenlabs';
import { LobeFalAI } from './providers/fal';
import { LobeFireworksAI } from './providers/fireworksai';
+import { LobeFishAudioAI } from './providers/fishaudio';
import { LobeGiteeAI } from './providers/giteeai';
import { LobeGithubAI } from './providers/github';
import { LobeGithubCopilotAI } from './providers/githubCopilot';
@@ -108,9 +110,11 @@ export const providerRuntimeMap = {
cometapi: LobeCometAPIAI,
comfyui: LobeComfyUI,
deepseek: LobeDeepSeekAI,
+ doubaospeech: LobeDoubaoSpeechAI,
elevenlabs: LobeElevenLabsAI,
fal: LobeFalAI,
fireworksai: LobeFireworksAI,
+ fishaudio: LobeFishAudioAI,
giteeai: LobeGiteeAI,
github: LobeGithubAI,
githubcopilot: LobeGithubCopilotAI,
diff --git a/packages/openapi/src/controllers/audio.controller.test.ts b/packages/openapi/src/controllers/audio.controller.test.ts
index cfe7454f092..44611971cb2 100644
--- a/packages/openapi/src/controllers/audio.controller.test.ts
+++ b/packages/openapi/src/controllers/audio.controller.test.ts
@@ -200,6 +200,21 @@ describe('AudioController.handleSpeech', () => {
});
});
+ it.each([
+ { model: 's2.1-pro', provider: 'fishaudio', voice: '0123456789abcdef0123456789abcdef' },
+ { model: 'seed-tts-2.0', provider: 'doubaospeech', voice: 'zh_male_m191_uranus_bigtts' },
+ ])('passes a $provider request through with its voice, model and format', async (request) => {
+ const res = await speech({ ...request, input: 'Hello', response_format: 'mp3', speed: 1.2 });
+
+ expect(res.status).toBe(200);
+ expect(res.headers.get('X-LobeHub-Provider')).toBe(request.provider);
+ expect(synthesizeMock).toHaveBeenCalledWith({
+ ...request,
+ input: 'Hello',
+ params: { format: 'mp3', speed: 1.2 },
+ });
+ });
+
it('surfaces upstream failures as 502 with a readable message', async () => {
synthesizeMock.mockRejectedValue(
new TTSProviderError('voice id not exist', 'ProviderBizError'),
diff --git a/packages/types/src/auth.ts b/packages/types/src/auth.ts
index 33deb8ca7f1..e38ed13f5c2 100644
--- a/packages/types/src/auth.ts
+++ b/packages/types/src/auth.ts
@@ -30,6 +30,11 @@ export interface ClientSecretPayload {
chatgptAccountId?: string;
cloudflareBaseURLOrAccountID?: string;
customHeaders?: Record<string, string>;
+ /**
+ * Doubao Speech legacy console credentials (App ID + Access Token)
+ */
+ doubaoSpeechAccessToken?: string;
+ doubaoSpeechAppId?: string;
/**
* GitHub Copilot OAuth fields
*/
diff --git a/packages/types/src/user/settings/keyVaults.ts b/packages/types/src/user/settings/keyVaults.ts
index a55af38bcfd..eafe39a74bc 100644
--- a/packages/types/src/user/settings/keyVaults.ts
+++ b/packages/types/src/user/settings/keyVaults.ts
@@ -35,6 +35,20 @@ export interface CloudflareKeyVault {
baseURLOrAccountID?: string;
}
+/**
+ * Doubao Speech (Volcengine speech synthesis): an API key from the new speech console, or
+ * the legacy console's App ID + Access Token.
+ */
+export interface DoubaoSpeechKeyVault {
+ /** Legacy console Access Token, sent as `X-Api-Access-Key` with `appId`. */
+ accessToken?: string;
+ /** New-console API key, sent as `X-Api-Key`. */
+ apiKey?: string;
+ /** Legacy console App ID, sent as `X-Api-App-Id` with `accessToken`. */
+ appId?: string;
+ baseURL?: string;
+}
+
export interface ComfyUIKeyVault {
apiKey?: string;
authType?: 'none' | 'basic' | 'bearer' | 'custom';
diff --git a/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx b/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx
index bd22d30b79e..ebaf0e35271 100644
--- a/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx
+++ b/src/features/Settings/provider/(list)/ProviderGrid/Card.tsx
@@ -18,9 +18,10 @@ const isCodingPlanProvider = (id: string) => id.endsWith('codingplan');
* ChatGPT is an OpenAI subscription, so its icon config points at the OpenAI
* mark — ProviderCombine renders the OpenAI wordmark and the card reads as a
* duplicate of the OpenAI one right beside it. Name these providers after the
- * plan instead, the way the detail page header does.
+ * plan instead, the way the detail page header does. Doubao Speech borrows the Doubao
+ * mark, whose wordmark reads 豆包大模型 (the Ark models), so it is named too.
*/
-const sharesVendorMark = (id: string) => id === 'chatgpt';
+const sharesVendorMark = (id: string) => id === 'chatgpt' || id === 'doubaospeech';
interface ProviderCardProps extends AiProviderListItem {
loading?: boolean;
diff --git a/src/features/Settings/provider/detail/doubaospeech/index.tsx b/src/features/Settings/provider/detail/doubaospeech/index.tsx
new file mode 100644
index 00000000000..b9c20e4c634
--- /dev/null
+++ b/src/features/Settings/provider/detail/doubaospeech/index.tsx
@@ -0,0 +1,91 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { DoubaoSpeechProviderCard } from 'model-bank/modelProviders';
+import { useTranslation } from 'react-i18next';
+
+import { FormInput, FormPassword } from '@/components/FormInput';
+import { ProviderIcon } from '@/components/LobeIcons';
+import { SkeletonInput } from '@/components/Skeleton';
+import { aiProviderSelectors, useAiInfraStore } from '@/store/aiInfra';
+import { type GlobalLLMProviderKey } from '@/types/user/settings';
+
+import { KeyVaultsConfigKey } from '../../const';
+import { type ProviderItem } from '../../type';
+import ProviderDetail from '../default';
+
+const providerKey: GlobalLLMProviderKey = 'doubaospeech';
+
+/**
+ * Doubao Speech accepts either console's credentials: the new console's API key, or the
+ * legacy console's App ID + Access Token. The runtime prefers the API key.
+ */
+const useProviderCard = (): ProviderItem => {
+ const { t } = useTranslation('modelProvider');
+
+ const isLoading = useAiInfraStore(aiProviderSelectors.isAiProviderConfigLoading(providerKey));
+
+ return {
+ ...DoubaoSpeechProviderCard,
+ // The Doubao combined logo reads 豆包大模型 (the Ark chat models), so show the
+ // Doubao mark with this provider's own name instead.
+ title: (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <ProviderIcon
+ provider={providerKey}
+ shape={'square'}
+ size={24}
+ style={{ borderRadius: 6 }}
+ type={'avatar'}
+ />
+ {DoubaoSpeechProviderCard.name}
+ </Flexbox>
+ ),
+ apiKeyItems: [
+ {
+ children: isLoading ? (
+ <SkeletonInput />
+ ) : (
+ <FormPassword
+ autoComplete={'new-password'}
+ placeholder={t(`${providerKey}.apiKey.placeholder`)}
+ />
+ ),
+ desc: t(`${providerKey}.apiKey.desc`),
+ label: t(`${providerKey}.apiKey.title`),
+ name: `${KeyVaultsConfigKey}.apiKey`,
+ },
+ {
+ children: isLoading ? (
+ <SkeletonInput />
+ ) : (
+ <FormInput allowClear placeholder={t(`${providerKey}.appId.placeholder`)} />
+ ),
+ desc: t(`${providerKey}.appId.desc`),
+ label: t(`${providerKey}.appId.title`),
+ name: `${KeyVaultsConfigKey}.appId`,
+ },
+ {
+ children: isLoading ? (
+ <SkeletonInput />
+ ) : (
+ <FormPassword
+ autoComplete={'new-password'}
+ placeholder={t(`${providerKey}.accessToken.placeholder`)}
+ />
+ ),
+ desc: t(`${providerKey}.accessToken.desc`),
+ label: t(`${providerKey}.accessToken.title`),
+ name: `${KeyVaultsConfigKey}.accessToken`,
+ },
+ ],
+ };
+};
+
+const Page = () => {
+ const card = useProviderCard();
+
+ return <ProviderDetail {...card} />;
+};
+
+export default Page;
diff --git a/src/features/Settings/provider/detail/index.tsx b/src/features/Settings/provider/detail/index.tsx
index 48e484579cf..819d86050f6 100644
--- a/src/features/Settings/provider/detail/index.tsx
+++ b/src/features/Settings/provider/detail/index.tsx
@@ -33,6 +33,10 @@ const Cloudflare = dynamic(() => import('./cloudflare'), {
loading: () => <SurfaceSkeleton header={false} variant={'form'} />,
ssr: false,
});
+const DoubaoSpeech = dynamic(() => import('./doubaospeech'), {
+ loading: () => <SurfaceSkeleton header={false} variant={'form'} />,
+ ssr: false,
+});
const Bedrock = dynamic(() => import('./bedrock'), {
loading: () => <SurfaceSkeleton header={false} variant={'form'} />,
ssr: false,
@@ -81,6 +85,9 @@ const ProviderDetailPage = (props: ProviderDetailPageProps) => {
case 'comfyui': {
return <ComfyUI />;
}
+ case 'doubaospeech': {
+ return <DoubaoSpeech />;
+ }
case 'github': {
return <GitHub />;
}
diff --git a/src/libs/lobeIconMappings.ts b/src/libs/lobeIconMappings.ts
index c2f153816f3..0dc949ffe31 100644
--- a/src/libs/lobeIconMappings.ts
+++ b/src/libs/lobeIconMappings.ts
@@ -1,18 +1,24 @@
-import { ElevenLabs, modelMappings, providerMappings } from '@lobehub/icons';
+import { Doubao, ElevenLabs, FishAudio, modelMappings, providerMappings } from '@lobehub/icons';
/**
* Brands @lobehub/icons ships artwork for but does not map to an id yet (checked against
- * 6.14.0). `ProviderIcon`, `ProviderCombine` and `ModelIcon` all look ids up in these
+ * 6.15.0). `ProviderIcon`, `ProviderCombine` and `ModelIcon` all look ids up in these
* shared tables, so appending here covers every surface. Each entry names an id it must
* resolve and is skipped once the package maps that id itself.
*/
const LOCAL_PROVIDER_MAPPINGS = [
{ Icon: ElevenLabs, keywords: ['elevenlabs'], probe: 'elevenlabs' },
+ { Icon: FishAudio, keywords: ['fishaudio'], probe: 'fishaudio' },
+ // Doubao Speech is Volcengine's speech service; its models are Doubao's.
+ { Icon: Doubao, keywords: ['doubaospeech'], probe: 'doubaospeech' },
];
/** `ModelIcon` tests each keyword as a case-insensitive regex against the model id. */
const LOCAL_MODEL_MAPPINGS = [
{ Icon: ElevenLabs, keywords: ['^eleven_'], probe: 'eleven_multilingual_v2' },
+ { Icon: FishAudio, keywords: ['^s2(\\.1)?-pro', '^drama-\\d', '^s1$'], probe: 's2.1-pro' },
+ // The package's OpenAI `tts-` keyword would claim these ids otherwise.
+ { Icon: Doubao, keywords: ['^seed-(tts|icl)-'], probe: 'seed-tts-2.0' },
];
let registered = false;
@@ -28,10 +34,13 @@ export const registerLocalIconMappings = () => {
if (!mapped) providerMappings.push(mapping);
}
+ // `ModelIcon` takes the first matching entry, so a model id another brand's broad keyword
+ // already claims (e.g. OpenAI's `tts-`) needs its entry in front of that one.
for (const { probe, ...mapping } of LOCAL_MODEL_MAPPINGS) {
- const mapped = modelMappings.some((item) =>
+ const match = modelMappings.find((item) =>
item.keywords.some((keyword) => new RegExp(keyword, 'i').test(probe)),
);
- if (!mapped) modelMappings.push(mapping);
+ if (!match) modelMappings.push(mapping);
+ else if (match.Icon !== mapping.Icon) modelMappings.unshift(mapping);
}
};
diff --git a/src/libs/modelIcon.test.ts b/src/libs/modelIcon.test.ts
index 454d90002fd..0ea21aab271 100644
--- a/src/libs/modelIcon.test.ts
+++ b/src/libs/modelIcon.test.ts
@@ -16,6 +16,32 @@ describe('local icon mappings', () => {
},
);
+ it.each(['s2.1-pro', 's2-pro', 'drama-3', 's1'])(
+ 'renders the Fish Audio avatar for the %s model',
+ (model) => {
+ const avatar = renderToStaticMarkup(createElement(ModelIcon, { model, type: 'avatar' }));
+
+ expect(avatar).toContain('<title>FishAudio</title>');
+ },
+ );
+
+ it.each(['seed-tts-2.0', 'seed-icl-2.0'])(
+ 'renders the Doubao avatar for %s instead of the OpenAI tts- mark',
+ (model) => {
+ const avatar = renderToStaticMarkup(createElement(ModelIcon, { model, type: 'avatar' }));
+
+ expect(avatar).toContain('<title>Doubao</title>');
+ },
+ );
+
+ it('keeps the OpenAI mark for OpenAI tts models', () => {
+ const avatar = renderToStaticMarkup(
+ createElement(ModelIcon, { model: 'tts-1', type: 'avatar' }),
+ );
+
+ expect(avatar).not.toContain('Doubao');
+ });
+
it('leaves models of other vendors alone', () => {
const avatar = renderToStaticMarkup(
createElement(ModelIcon, { model: 'speech-2.8-hd', type: 'avatar' }),
diff --git a/src/libs/providerIcon.test.ts b/src/libs/providerIcon.test.ts
index 5a24b05fec3..3d142887151 100644
--- a/src/libs/providerIcon.test.ts
+++ b/src/libs/providerIcon.test.ts
@@ -37,4 +37,16 @@ describe('provider artwork', () => {
expect(wordmark).not.toContain('lucide-provider');
},
);
+
+ it.each([
+ ['fishaudio', 'FishAudio'],
+ ['doubaospeech', 'Doubao'],
+ ])('renders the %s avatar from the %s artwork', (provider, title) => {
+ const avatar = renderToStaticMarkup(createElement(ProviderIcon, { provider, type: 'avatar' }));
+ const wordmark = renderToStaticMarkup(createElement(ProviderCombine, { provider }));
+
+ expect(avatar).toContain(`<title>${title}</title>`);
+ expect(avatar).not.toContain('lucide-provider');
+ expect(wordmark).not.toContain('lucide-provider');
+ });
});