🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(tts): add ElevenLabs text-to-speech provider (#22168)
Rdmclin2d7f6fbccd730
diff --git a/.env.example b/.env.exampleindex dfc9ba2a1cc..cb02aa43cdf 100644--- a/.env.example+++ b/.env.example@@ -216,6 +216,11 @@ OPENAI_API_KEY=sk-xxxxxxxxx# FAL_API_KEY=fal-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+# ## ElevenLabs (text-to-speech) ###++# ELEVENLABS_API_KEY=sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+# ELEVENLABS_PROXY_URL=https://api.elevenlabs.io+# ######################################## ######## AI Image Settings ############# #######################################diff --git a/Dockerfile b/Dockerfileindex 924acdc3eb7..8a74e4c32f6 100644--- a/Dockerfile+++ b/Dockerfile@@ -261,6 +261,8 @@ ENV \COMFYUI_API_KEY="" COMFYUI_USERNAME="" COMFYUI_PASSWORD="" COMFYUI_CUSTOM_HEADERS="" \# DeepSeekDEEPSEEK_API_KEY="" DEEPSEEK_MODEL_LIST="" \+ # ElevenLabs+ ELEVENLABS_API_KEY="" ELEVENLABS_MODEL_LIST="" ELEVENLABS_PROXY_URL="" \# Fireworks AIFIREWORKSAI_API_KEY="" FIREWORKSAI_MODEL_LIST="" \# Gitee AIdiff --git a/apps/server/src/modules/ModelRuntime/elevenlabs.test.ts b/apps/server/src/modules/ModelRuntime/elevenlabs.test.tsnew file mode 100644index 00000000000..3c9b3dc7f8b--- /dev/null+++ b/apps/server/src/modules/ModelRuntime/elevenlabs.test.ts@@ -0,0 +1,48 @@+// @vitest-environment node+import { LobeElevenLabsAI, ModelRuntime } from '@lobechat/model-runtime';+import { ModelProvider } from 'model-bank';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { initModelRuntimeWithUserPayload } from './index';++vi.mock('@/server/globalConfig', () => ({ getServerAiProviderConfig: vi.fn() }));+vi.mock('@/envs/llm', () => ({+ getLLMConfig: vi.fn(() => ({ ELEVENLABS_API_KEY: 'test-elevenlabs-key' })),+}));++describe('initModelRuntimeWithUserPayload: ElevenLabs', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('uses the user API key and endpoint', () => {+ const runtime = initModelRuntimeWithUserPayload(ModelProvider.ElevenLabs, {+ apiKey: 'user-elevenlabs-key',+ baseURL: 'https://api.eu.residency.elevenlabs.io',+ });++ expect(runtime).toBeInstanceOf(ModelRuntime);+ expect(runtime['_runtime']).toBeInstanceOf(LobeElevenLabsAI);+ expect(runtime['_runtime']['apiKey']).toBe('user-elevenlabs-key');+ expect(runtime['_runtime'].baseURL).toBe('https://api.eu.residency.elevenlabs.io');+ });++ it('falls back to ELEVENLABS_API_KEY and ELEVENLABS_PROXY_URL without a user key', () => {+ expect(initModelRuntimeWithUserPayload(ModelProvider.ElevenLabs, {})['_runtime']).toMatchObject(+ { apiKey: 'test-elevenlabs-key', baseURL: 'https://api.elevenlabs.io' },+ );++ vi.stubEnv('ELEVENLABS_PROXY_URL', 'https://proxy.example.com/v1');+ expect(initModelRuntimeWithUserPayload(ModelProvider.ElevenLabs, {})['_runtime'].baseURL).toBe(+ 'https://proxy.example.com',+ );+ });++ it('rejects a user endpoint without a key instead of sending the server key there', () => {+ expect(() =>+ initModelRuntimeWithUserPayload(ModelProvider.ElevenLabs, {+ baseURL: 'https://proxy.example.com',+ }),+ ).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.tsindex 3647f3824ea..280e2f21cb1 100644--- a/apps/server/src/routers/lambda/__tests__/tts.test.ts+++ b/apps/server/src/routers/lambda/__tests__/tts.test.ts@@ -49,7 +49,13 @@ describe('ttsRouter.synthesize', () => {undefined,);expect(textToSpeechMock).toHaveBeenCalledWith(- { input: 'hello', model: 'tts-1', params: { format: 'opus', speed: 1.5 }, voice: 'nova' },+ {+ input: 'hello',+ model: 'tts-1',+ params: { format: 'opus', speed: 1.5 },+ voice: 'nova',+ voiceIsDefault: false,+ },{ metadata: { trigger: 'tts' }, user: 'u1' },);expect(res).toEqual({@@ -172,4 +178,100 @@ describe('ttsRouter.synthesize', () => {message: 'MiniMax API error: rate limit',});});+ describe('provider elevenlabs', () => {+ it('routes provider elevenlabs to its runtime with the card default voice', async () => {+ textToSpeechMock.mockResolvedValue({+ audio: new Uint8Array([4, 5]).buffer,+ format: 'mp3',+ usage: { cost: 0.000_16, inputCharacters: 2 },+ });++ const res = await caller.synthesize({+ input: 'Hi',+ model: 'eleven_multilingual_v2',+ params: { speed: 1.1 },+ provider: 'elevenlabs',+ });++ expect(initModelRuntimeFromDB).toHaveBeenCalledWith(+ expect.anything(),+ 'u1',+ 'elevenlabs',+ undefined,+ );+ expect(textToSpeechMock).toHaveBeenCalledWith(+ {+ input: 'Hi',+ model: 'eleven_multilingual_v2',+ params: { speed: 1.1 },+ voice: 'CwhRBWXzGAHq8TQ4Fs17',+ voiceIsDefault: true,+ },+ { metadata: { trigger: 'tts' }, user: 'u1' },+ );+ expect(res).toEqual({+ audioBase64: Buffer.from([4, 5]).toString('base64'),+ format: 'mp3',+ mimeType: 'audio/mpeg',+ usage: { cost: 0.000_16, inputCharacters: 2 },+ });+ });++ it('validates params against the ElevenLabs card', async () => {+ await expect(+ caller.synthesize({+ input: 'Hi',+ model: 'eleven_multilingual_v2',+ params: { format: 'aac', speed: 2 },+ provider: 'elevenlabs',+ }),+ ).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ message: expect.stringContaining('params.speed must be between 0.7 and 1.2'),+ });+ expect(textToSpeechMock).not.toHaveBeenCalled();+ });++ it('reports a missing API key with the InvalidProviderAPIKey copy instead of a bare 500', async () => {+ // what a runtime constructor throws when neither the user nor the server has a key+ vi.mocked(initModelRuntimeFromDB).mockRejectedValueOnce({+ errorType: 'InvalidProviderAPIKey',+ });++ const error = await caller+ .synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' })+ .catch((e) => e);++ expect(error).toMatchObject({+ code: 'BAD_GATEWAY',+ message:+ 'ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again. Set it in Settings → AI Providers → ElevenLabs, or in the server environment.',+ });+ // the lambda errorFormatter exposes `cause.data` to clients as `data.errorData`+ expect(error.cause).toMatchObject({+ data: { errorType: 'InvalidProviderAPIKey', provider: 'elevenlabs' },+ });+ });++ it('reports a rejected key with the InvalidProviderAPIKey copy and the upstream message', async () => {+ textToSpeechMock.mockRejectedValue({+ error: {+ detail: { message: 'Invalid API key', status: 'invalid_api_key' },+ message: 'ElevenLabs API error (401): Invalid API key',+ status: 401,+ },+ errorType: 'InvalidProviderAPIKey',+ provider: 'elevenlabs',+ });++ await expect(+ caller.synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' }),+ ).rejects.toMatchObject({+ cause: { data: { errorType: 'InvalidProviderAPIKey', provider: 'elevenlabs' } },+ code: 'BAD_GATEWAY',+ message:+ 'ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again (ElevenLabs API error (401): Invalid API key). Set it in Settings → AI Providers → ElevenLabs, or in the server environment.',+ });+ });+ });});diff --git a/apps/server/src/routers/lambda/tts.ts b/apps/server/src/routers/lambda/tts.tsindex cfe58a986b2..30c0feccb0c 100644--- a/apps/server/src/routers/lambda/tts.ts+++ b/apps/server/src/routers/lambda/tts.ts@@ -79,7 +79,12 @@ export const ttsRouter = router({}if (error instanceof TTSProviderError) {throw new TRPCError({- cause: error.detail,+ // Exposed to clients as `error.data.errorData`, so they can show the localized+ // runtime error (e.g. `modelRuntime:InvalidProviderAPIKey`) for `errorType`.+ cause: {+ data: { errorType: error.errorType, provider: input.provider },+ detail: error.detail,+ },code: error.errorType === 'RateLimitExceeded' ? 'TOO_MANY_REQUESTS' : 'BAD_GATEWAY',message: error.message,});diff --git a/apps/server/src/services/tts/elevenlabs.test.ts b/apps/server/src/services/tts/elevenlabs.test.tsnew file mode 100644index 00000000000..7ba096d70b7--- /dev/null+++ b/apps/server/src/services/tts/elevenlabs.test.ts@@ -0,0 +1,244 @@+// @vitest-environment node+/**+ * TTSService → initModelRuntimeFromDB → ModelRuntime → LobeElevenLabsAI → fetch, with only+ * the provider row, the server env and the network mocked, so provider='elevenlabs' 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 DEFAULT_VOICE = 'CwhRBWXzGAHq8TQ4Fs17';+const AUDIO = new Uint8Array([0x49, 0x44, 0x33, 0x04]);++const service = new TTSService({} as any, 'user-1');++describe('TTSService with provider elevenlabs', () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ providerRow.current = { keyVaults: { apiKey: 'user-xi-key' } };+ llmConfig.current = {};+ fetchMock = vi.fn(+ async () =>+ new Response(AUDIO, {+ headers: { 'content-type': 'audio/mpeg', 'character-cost': '4' },+ }),+ );+ 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: 'Hello world',+ model: 'eleven_multilingual_v2',+ params: { format: 'opus', speed: 1.1 },+ provider: 'elevenlabs',+ voice: 'gOupLcAkjEnguROwi4oS',+ });++ const [url, init] = fetchMock.mock.calls[0] as any;+ expect(url).toBe(+ 'https://api.elevenlabs.io/v1/text-to-speech/gOupLcAkjEnguROwi4oS?output_format=opus_48000_128',+ );+ expect(init.headers['xi-api-key']).toBe('user-xi-key');+ expect(JSON.parse(init.body)).toEqual({+ model_id: 'eleven_multilingual_v2',+ text: 'Hello world',+ voice_settings: { speed: 1.1 },+ });++ expect(new Uint8Array(result.audio)).toEqual(AUDIO);+ expect(result.format).toBe('opus');+ expect(result.mimeType).toBe('audio/opus');+ // 11 billed characters at the card's $80 / 1M characters+ expect(result.usage).toEqual({ cost: 0.000_88, inputCharacters: 11 });+ });++ it("defaults the voice to the model card's default voice", async () => {+ await service.synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' });++ expect(fetchMock.mock.calls[0][0]).toContain(`/v1/text-to-speech/${DEFAULT_VOICE}?`);+ expect(JSON.parse((fetchMock.mock.calls[0] as any)[1].body).model_id).toBe('eleven_v4');+ });++ it('falls back to ELEVENLABS_API_KEY when the user saved no key', async () => {+ providerRow.current = undefined;+ llmConfig.current = { ELEVENLABS_API_KEY: 'server-xi-key' };++ await service.synthesize({ input: 'Hi', model: 'eleven_flash_v2_5', provider: 'elevenlabs' });++ expect((fetchMock.mock.calls[0] as any)[1].headers['xi-api-key']).toBe('server-xi-key');+ });++ it('uses the user base URL, and ELEVENLABS_PROXY_URL with the server key', async () => {+ providerRow.current = {+ keyVaults: { apiKey: 'user-xi-key', baseURL: 'https://api.eu.residency.elevenlabs.io' },+ };+ await service.synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' });+ expect(fetchMock.mock.calls[0][0]).toMatch(+ /^https:\/\/api\.eu\.residency\.elevenlabs\.io\/v1\/text-to-speech\//,+ );++ providerRow.current = undefined;+ llmConfig.current = { ELEVENLABS_API_KEY: 'server-xi-key' };+ vi.stubEnv('ELEVENLABS_PROXY_URL', 'https://proxy.example.com/v1');+ await service.synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' });+ expect(fetchMock.mock.calls[1][0]).toMatch(+ /^https:\/\/proxy\.example\.com\/v1\/text-to-speech\//,+ );+ });++ it('fails with a readable InvalidProviderAPIKey error when no key is configured', async () => {+ providerRow.current = { keyVaults: {} };++ const error = await service+ .synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' })+ .catch((e) => e);++ expect(error).toBeInstanceOf(TTSProviderError);+ expect(error.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);+ expect(error.message).toBe(+ 'ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again. Set it in Settings → AI Providers → ElevenLabs, or in the server environment.',+ );+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('surfaces an upstream 401 with the InvalidProviderAPIKey copy and the ElevenLabs message', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({ detail: { message: 'Invalid API key', status: 'invalid_api_key' } }),+ { status: 401 },+ ),+ );++ const error = await service+ .synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' })+ .catch((e) => e);++ expect(error).toBeInstanceOf(TTSProviderError);+ expect(error.errorType).toBe(AgentRuntimeErrorType.InvalidProviderAPIKey);+ expect(error.message).toBe(+ 'ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again (ElevenLabs API error (401): Invalid API key). Set it in Settings → AI Providers → ElevenLabs, or in the server environment.',+ );+ });++ it('surfaces an upstream 429 as RateLimitExceeded', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ detail: { message: 'busy', status: 'system_busy' } }), {+ status: 429,+ }),+ );++ await expect(+ service.synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs' }),+ ).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.RateLimitExceeded,+ message: 'ElevenLabs API error (429): busy',+ });+ });++ it('rejects params the ElevenLabs card does not allow before calling the API', async () => {+ await expect(+ service.synthesize({+ input: 'Hi',+ model: 'eleven_multilingual_v2',+ params: { speed: 1.5 },+ provider: 'elevenlabs',+ }),+ ).rejects.toBeInstanceOf(TTSRequestError);++ await expect(+ service.synthesize({+ input: 'Hi',+ model: 'eleven_multilingual_v2',+ params: { format: 'aac' },+ provider: 'elevenlabs',+ }),+ ).rejects.toMatchObject({ reason: 'invalid_params' });++ // v3 / v4 declare no speed+ await expect(+ service.synthesize({+ input: 'Hi',+ model: 'eleven_v4',+ params: { speed: 1 },+ provider: 'elevenlabs',+ }),+ ).rejects.toMatchObject({ message: 'params.speed not supported by this model' });++ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('caps ElevenLabs models routed through the LobeHub provider too', async () => {+ await expect(+ service.synthesize({+ input: 'a'.repeat(INLINE_TTS_MAX_INPUT_CHARACTERS + 1),+ model: 'eleven_flash_v2_5',+ provider: 'lobehub',+ }),+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('counts the inline cap in Unicode characters, so emoji at the limit pass', async () => {+ // Each emoji is two UTF-16 units but one billed character.+ await service.synthesize({+ input: '🎙'.repeat(INLINE_TTS_MAX_INPUT_CHARACTERS),+ model: 'eleven_flash_v2_5',+ provider: 'elevenlabs',+ });+ expect(fetchMock).toHaveBeenCalledTimes(1);++ await expect(+ service.synthesize({+ input: '🎙'.repeat(INLINE_TTS_MAX_INPUT_CHARACTERS + 1),+ model: 'eleven_flash_v2_5',+ provider: 'elevenlabs',+ }),+ ).rejects.toMatchObject({ reason: 'invalid_params' });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ 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: 'eleven_flash_v2_5',+ provider: 'elevenlabs',+ }),+ ).rejects.toMatchObject({ name: 'TTSRequestError', reason: 'invalid_params' });++ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('drops the legacy top-level speed for v4, which declares none', async () => {+ await service.synthesize({ input: 'Hi', model: 'eleven_v4', provider: 'elevenlabs', speed: 1 });++ expect(JSON.parse((fetchMock.mock.calls[0] as any)[1].body).voice_settings).toBeUndefined();+ });+});diff --git a/apps/server/src/services/tts/index.test.ts b/apps/server/src/services/tts/index.test.tsindex 85aa0b1fc8c..ddc20942010 100644--- a/apps/server/src/services/tts/index.test.ts+++ b/apps/server/src/services/tts/index.test.ts@@ -3,7 +3,8 @@ import { describe, expect, it, vi } from 'vitest';vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));-const { resolveTTSModelRef } = await import('./index');+const { invalidProviderAPIKeyMessage, resolveTTSModelRef } = await import('./index');+const { default: modelRuntimeLocale } = await import('@/locales/default/modelRuntime');describe('resolveTTSModelRef', () => {it('takes a leading known provider id as the provider', () => {@@ -34,4 +35,38 @@ describe('resolveTTSModelRef', () => {});expect(resolveTTSModelRef('tts-1')).toEqual({ model: 'tts-1', provider: 'openai' });});++ it('resolves ElevenLabs model references', () => {+ expect(resolveTTSModelRef('elevenlabs/eleven_v4')).toEqual({+ model: 'eleven_v4',+ provider: 'elevenlabs',+ });+ expect(resolveTTSModelRef('eleven_multilingual_v2')).toEqual({+ model: 'eleven_multilingual_v2',+ provider: 'elevenlabs',+ });+ });+});++describe('invalidProviderAPIKeyMessage', () => {+ it("matches the modelRuntime InvalidProviderAPIKey source copy with the provider's display name", () => {+ const copy = modelRuntimeLocale.InvalidProviderAPIKey.replaceAll('{{provider}}', 'ElevenLabs');++ expect(invalidProviderAPIKeyMessage('elevenlabs')).toBe(+ `${copy}. Set it in Settings → AI Providers → ElevenLabs, or in the server environment.`,+ );+ expect(invalidProviderAPIKeyMessage('elevenlabs')).not.toContain('{{provider}}');+ });++ it('keeps the upstream message when the provider rejected the key', () => {+ expect(invalidProviderAPIKeyMessage('elevenlabs', 'Invalid API key')).toBe(+ 'ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again (Invalid API key). Set it in Settings → AI Providers → ElevenLabs, or in the server environment.',+ );+ });++ it('names other providers the same way, falling back to the raw id', () => {+ expect(invalidProviderAPIKeyMessage('openai')).toMatch(/^OpenAI API Key is incorrect or empty/);+ expect(invalidProviderAPIKeyMessage('minimax')).toMatch(/^Minimax API Key is incorrect/);+ expect(invalidProviderAPIKeyMessage('my-gateway')).toMatch(/^my-gateway API Key is incorrect/);+ });});diff --git a/apps/server/src/services/tts/index.ts b/apps/server/src/services/tts/index.tsindex 8829e396e81..fefb6432e42 100644--- a/apps/server/src/services/tts/index.ts+++ b/apps/server/src/services/tts/index.ts@@ -1,8 +1,11 @@+import type { ModelRuntime } from '@lobechat/model-runtime';+import { countTextToSpeechCharacters } from '@lobechat/model-runtime';import type { ModelUsage } from '@lobechat/types';-import { RequestTrigger } from '@lobechat/types';+import { AgentRuntimeErrorType, RequestTrigger } from '@lobechat/types';import type { AITTSModelCard, TTSAudioFormat } from 'model-bank';import { LOBE_DEFAULT_MODEL_LIST, TTS_AUDIO_MIME_TYPES, validateTTSParams } from 'model-bank';import { ModelProvider } from 'model-bank/modelProvider';+import { DEFAULT_MODEL_PROVIDER_LIST } from 'model-bank/modelProviders';import type { LobeChatDatabase } from '@/database/type';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';@@ -15,6 +18,16 @@ import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';*/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.+ */+export const INLINE_TTS_MAX_INPUT_CHARACTERS = 4096;++const INLINE_INPUT_CAPPED_PROVIDERS = new Set<string>([ModelProvider.ElevenLabs]);+export interface TTSSynthesizeParams {emotion?: string;format?: (typeof INLINE_TTS_AUDIO_FORMATS)[number];@@ -75,15 +88,45 @@ export class TTSProviderError extends Error {const isRecord = (value: unknown): value is Record<string, any> =>typeof value === 'object' && value !== null;+const providerDisplayName = (provider: string): string =>+ DEFAULT_MODEL_PROVIDER_LIST.find((card) => card.id === provider)?.name ?? provider;++/**+ * The app's own `InvalidProviderAPIKey` copy, plus where to set the key. Server code renders+ * source English, so this is the `modelRuntime.InvalidProviderAPIKey` source string (shown in+ * chat and the provider checker); a test keeps the two in sync.+ */+export const invalidProviderAPIKeyMessage = (provider: string, upstreamMessage?: string) => {+ const name = providerDisplayName(provider);+ const copy = `${name} API Key is incorrect or empty, please check your ${name} API Key and try again`;+ const hint = `Set it in Settings → AI Providers → ${name}, or in the server environment.`;++ return upstreamMessage ? `${copy} (${upstreamMessage}). ${hint}` : `${copy}. ${hint}`;+};+const toProviderError = (error: unknown, provider: string): TTSProviderError => {if (!isRecord(error)) return new TTSProviderError(String(error), undefined, error);const errorType = typeof error.errorType === 'string' ? error.errorType : undefined;const detail = isRecord(error.error) ? error.error : undefined;- const message =+ const upstreamMessage =(typeof error.message === 'string' && error.message) ||(typeof detail?.message === 'string' && detail.message) ||(typeof detail?.base_resp?.status_msg === 'string' && detail.base_resp.status_msg) ||+ undefined;++ // A missing or rejected key reads the same as everywhere else in the app, so the+ // caller knows to configure the key rather than retry.+ if (errorType === AgentRuntimeErrorType.InvalidProviderAPIKey) {+ return new TTSProviderError(+ invalidProviderAPIKeyMessage(provider, upstreamMessage),+ errorType,+ error,+ );+ }++ const message =+ upstreamMessage ||(errorType ? `${provider} text-to-speech failed: ${errorType}` : '') ||`${provider} text-to-speech failed`;@@ -94,11 +137,14 @@ const toProviderError = (error: unknown, provider: string): TTSProviderError =>* Built-in card of a TTS model: the provider's own card first, then any provider* serving the same model id (aggregators reuse upstream cards).*/-export const findTTSModelCard = (provider: string, model: string): AITTSModelCard | undefined => {+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);return (cards.find((card) => card.providerId === provider) ?? cards[0]) as- AITTSModelCard | undefined;+ (AITTSModelCard & { providerId?: string }) | undefined;};const KNOWN_PROVIDERS = new Set<string>(Object.values(ModelProvider));@@ -138,7 +184,21 @@ export class TTSService {async synthesize(request: TTSSynthesizeRequest): Promise<TTSSynthesizeResult> {const { input, model, provider } = request;+const card = findTTSModelCard(provider, model);++ // Capped by the model's vendor, so the LobeHub provider routing an ElevenLabs model is+ // capped too. Counted in Unicode characters, as billing does: an emoji is one, not two.+ const capped =+ INLINE_INPUT_CAPPED_PROVIDERS.has(provider) ||+ (!!card?.providerId && INLINE_INPUT_CAPPED_PROVIDERS.has(card.providerId));+ const inputCharacters = capped ? countTextToSpeechCharacters(input) : 0;+ if (inputCharacters > INLINE_TTS_MAX_INPUT_CHARACTERS) {+ throw new TTSRequestError(+ `input is ${inputCharacters} characters; ${model} speech is limited to ${INLINE_TTS_MAX_INPUT_CHARACTERS} characters per request. Split the text into shorter requests.`,+ 'invalid_params',+ );+ }const params: TTSSynthesizeParams = { ...request.params };// Older CLIs always send the deprecated top-level `speed`; drop it for models that// declare no speed instead of failing validation they never opted into.@@ -159,12 +219,23 @@ export class TTSService {const voice = request.voice ?? card?.parameters?.voice?.default ?? 'alloy';- const runtime = await initModelRuntimeFromDB(this.db, this.userId, provider, this.workspaceId);+ let runtime: ModelRuntime;+ try {+ runtime = await initModelRuntimeFromDB(this.db, this.userId, provider, this.workspaceId);+ } catch (error) {+ // Runtimes reject a missing key at construction with a plain+ // `{ errorType: 'InvalidProviderAPIKey' }` payload; surface it as a readable provider+ // error instead of a bare 500. Anything else (e.g. a DB failure) propagates as is.+ if (isRecord(error) && typeof error.errorType === 'string' && !(error instanceof Error)) {+ throw toProviderError(error, provider);+ }+ throw error;+ }let result: Awaited<ReturnType<typeof runtime.textToSpeech>>;try {result = await runtime.textToSpeech(- { input, model, params, voice },+ { input, model, params, voice, voiceIsDefault: request.voice === undefined },{ metadata: { trigger: RequestTrigger.Tts }, user: this.userId },);} catch (error) {diff --git a/docs/self-hosting/environment-variables/model-provider.mdx b/docs/self-hosting/environment-variables/model-provider.mdxindex 23ccc2ee80f..d9b386fbe5e 100644--- a/docs/self-hosting/environment-variables/model-provider.mdx+++ b/docs/self-hosting/environment-variables/model-provider.mdx@@ -715,6 +715,33 @@ If you need to use Azure OpenAI to provide model services, you can refer to theThe above example disables all models first, then enables `fal-ai/flux/schnell` and `fal-ai/flux-pro/kontext` (displayed as `FLUX.1 Kontext [pro]`).+## ElevenLabs++Text-to-speech only. See [Using ElevenLabs in LobeHub](/docs/usage/providers/elevenlabs) for setup instructions.++### `ELEVENLABS_API_KEY`++- Type: Optional for the deployment; required when providing a shared server key. Users can instead enter their own key in ElevenLabs provider settings, which takes precedence.+- Description: A key created on the [ElevenLabs API Keys](https://elevenlabs.io/app/settings/api-keys) page. Setting a non-empty key automatically enables ElevenLabs in the server configuration. `ENABLED_ELEVENLABS` is derived from this key, not a separate environment switch. Without a key from either source, speech requests to ElevenLabs fail with an `InvalidProviderAPIKey` error.+- Default: Unset; no shared server key.+- Example: `sk_xxxxxx...xxxxxx`++### `ELEVENLABS_PROXY_URL`++- Type: Optional+- Description: Overrides the ElevenLabs API base URL, for example a data-residency endpoint. Only used together with the server key. A trailing `/v1` is accepted.+- Default: `https://api.elevenlabs.io`+- Example: `https://api.eu.residency.elevenlabs.io`++### `ELEVENLABS_MODEL_LIST`++- Type: Optional+- Description: Customizes the ElevenLabs model list using the shared [model-list syntax][model-list]: `+` adds a model, `-` hides a model, and `model_id=display_name` renames a model. Separate entries with commas.+- Default: Unset; uses the built-in model list.+- Example: `-all,+eleven_v4,+eleven_flash_v2_5`++The example hides all default models and enables only `eleven_v4` and `eleven_flash_v2_5`.+## 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.mdxindex 3d3c627bc96..06c032f48ad 100644--- a/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx+++ b/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx@@ -773,6 +773,33 @@ LobeHub 在部署时提供了丰富的模型服务商相关的环境变量,你上述示例表示先禁用所有模型,再启用 `fal-ai/flux/schnell` 和 `fal-ai/flux-pro/kontext`(显示名为 `FLUX.1 Kontext [pro]`)。+## ElevenLabs++仅提供语音合成(TTS)。设置步骤见[在 LobeHub 中使用 ElevenLabs](/zh/docs/usage/providers/elevenlabs)。++### `ELEVENLABS_API_KEY`++- 类型:部署时可选;提供共享服务端密钥时必填。用户也可以在 ElevenLabs 服务商设置中填写自己的密钥,用户密钥优先。+- 描述:在 [ElevenLabs API Keys](https://elevenlabs.io/app/settings/api-keys) 页面创建的密钥。设置非空密钥后,服务端配置会自动启用 ElevenLabs。`ENABLED_ELEVENLABS` 由此密钥派生,不是独立的环境变量开关。两处都没有密钥时,调用 ElevenLabs 语音合成会返回 `InvalidProviderAPIKey` 错误。+- 默认值:未设置,不提供共享服务端密钥。+- 示例:`sk_xxxxxx...xxxxxx`++### `ELEVENLABS_PROXY_URL`++- 类型:可选+- 描述:覆盖 ElevenLabs API 的 Base URL,例如数据驻留地址。仅与服务端密钥一起使用。末尾带 `/v1` 也可以。+- 默认值:`https://api.elevenlabs.io`+- 示例:`https://api.eu.residency.elevenlabs.io`++### `ELEVENLABS_MODEL_LIST`++- 类型:可选+- 描述:使用通用的 [模型列表语法][model-list] 自定义 ElevenLabs 模型列表:`+` 增加模型,`-` 隐藏模型,`模型 ID=展示名` 自定义展示名,用英文逗号隔开。+- 默认值:未设置,使用内置模型列表。+- 示例:`-all,+eleven_v4,+eleven_flash_v2_5`++上述示例表示隐藏所有默认模型,只启用 `eleven_v4` 和 `eleven_flash_v2_5`。+## BFL### `BFL_API_KEY`diff --git a/docs/usage/providers.mdx b/docs/usage/providers.mdxindex aed53f46982..802687e70b7 100644--- a/docs/usage/providers.mdx+++ b/docs/usage/providers.mdx@@ -40,13 +40,14 @@ These groups are shortcuts, not exclusive capability categories or a complete prModels, regional access, prices, and API support depend on the provider and your account.-| Category | Setup guides |-| --- | --- |-| **Major Commercial Providers** | [OpenAI](/docs/usage/providers/openai) (GPT-6 Astra) · [Anthropic](/docs/usage/providers/anthropic) (Claude Fable 5.1, Claude Opus 5, Claude Sonnet 5) · [Google](/docs/usage/providers/google) (Gemini 3.8 Flash) · [Azure OpenAI](/docs/usage/providers/azure) · [AWS Bedrock](/docs/usage/providers/bedrock) |-| **Aggregators and Inference Platforms** | [OpenRouter](/docs/usage/providers/openrouter) · [Together AI](/docs/usage/providers/togetherai) · [Groq](/docs/usage/providers/groq) · [Fireworks AI](/docs/usage/providers/fireworksai) · [SambaNova](/docs/usage/providers/sambanova) |-| **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) |+| Category | Setup guides |+| --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **Major Commercial Providers** | [OpenAI](/docs/usage/providers/openai) (GPT-6 Astra) · [Anthropic](/docs/usage/providers/anthropic) (Claude Fable 5.1, Claude Opus 5, Claude Sonnet 5) · [Google](/docs/usage/providers/google) (Gemini 3.8 Flash) · [Azure OpenAI](/docs/usage/providers/azure) · [AWS Bedrock](/docs/usage/providers/bedrock) |+| **Aggregators and Inference Platforms** | [OpenRouter](/docs/usage/providers/openrouter) · [Together AI](/docs/usage/providers/togetherai) · [Groq](/docs/usage/providers/groq) · [Fireworks AI](/docs/usage/providers/fireworksai) · [SambaNova](/docs/usage/providers/sambanova) |+| **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) |An image model name is not a provider name. Select the guide for the provider or local runtime that serves the model.diff --git a/docs/usage/providers.zh-CN.mdx b/docs/usage/providers.zh-CN.mdxindex 846401f9152..9cd11673a66 100644--- a/docs/usage/providers.zh-CN.mdx+++ b/docs/usage/providers.zh-CN.mdx@@ -36,13 +36,14 @@ tags:分类用于快速查找,不是互斥的能力划分,也不是全部服务商列表。同一服务商可以同时提供文本和图像能力;实际模型、地区、价格和接口以服务商及账号为准。-| 类别 | 配置教程 |-| --- | --- |-| **主流商业服务商** | [OpenAI](/zh/docs/usage/providers/openai)(GPT-6 Astra) · [Anthropic](/zh/docs/usage/providers/anthropic)(Claude Fable 5.1、Claude Opus 5、Claude Sonnet 5) · [Google](/zh/docs/usage/providers/google)(Gemini 3.8 Flash) · [Azure OpenAI](/zh/docs/usage/providers/azure) · [AWS Bedrock](/zh/docs/usage/providers/bedrock) |-| **聚合与推理平台** | [OpenRouter](/zh/docs/usage/providers/openrouter) · [Together AI](/zh/docs/usage/providers/togetherai) · [Groq](/zh/docs/usage/providers/groq) · [Fireworks AI](/zh/docs/usage/providers/fireworksai) · [SambaNova](/zh/docs/usage/providers/sambanova) |-| **国内服务商** | [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) |+| 类别 | 配置教程 |+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| **主流商业服务商** | [OpenAI](/zh/docs/usage/providers/openai)(GPT-6 Astra) · [Anthropic](/zh/docs/usage/providers/anthropic)(Claude Fable 5.1、Claude Opus 5、Claude Sonnet 5) · [Google](/zh/docs/usage/providers/google)(Gemini 3.8 Flash) · [Azure OpenAI](/zh/docs/usage/providers/azure) · [AWS Bedrock](/zh/docs/usage/providers/bedrock) |+| **聚合与推理平台** | [OpenRouter](/zh/docs/usage/providers/openrouter) · [Together AI](/zh/docs/usage/providers/togetherai) · [Groq](/zh/docs/usage/providers/groq) · [Fireworks AI](/zh/docs/usage/providers/fireworksai) · [SambaNova](/zh/docs/usage/providers/sambanova) |+| **国内服务商** | [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) |图像模型名称不是服务商名称。请按提供该模型的服务商或本地运行时选择配置教程。diff --git a/docs/usage/providers/elevenlabs.mdx b/docs/usage/providers/elevenlabs.mdxnew file mode 100644index 00000000000..e7dc7d11212--- /dev/null+++ b/docs/usage/providers/elevenlabs.mdx@@ -0,0 +1,67 @@+---+title: Using ElevenLabs API Key in LobeHub+description: >-+ Configure an ElevenLabs API key in LobeHub and generate lifelike speech with Eleven v4, Eleven Multilingual v2, and Eleven Flash v2.5.+tags:+ - ElevenLabs+ - Text to Speech+ - TTS+ - API Key+---++# Using ElevenLabs in LobeHub++[ElevenLabs](https://elevenlabs.io) is an AI audio company. Its text-to-speech models generate expressive speech in 90+ languages from a large voice library. In LobeHub, ElevenLabs is a text-to-speech provider only: it has no chat models.++<Steps>+ ### Step 1: Obtain your ElevenLabs API key++ - Sign up or sign in at [ElevenLabs](https://elevenlabs.io).+ - Open [API Keys](https://elevenlabs.io/app/settings/api-keys) and create a key.+ - Copy the key and store it securely.++ ### Step 2: Configure ElevenLabs in LobeHub++ - Open **App Settings → AI Providers** and select **ElevenLabs** (type `Eleven` 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: if your ElevenLabs workspace uses a data-residency endpoint, enter it in **API Proxy URL** (for example `https://api.eu.residency.elevenlabs.io`). Leave it empty to use `https://api.elevenlabs.io`.++ ### Step 3: Choose models++ The **Model List** shows the ElevenLabs speech models under the **TTS** tab. Eleven v4, Eleven Multilingual v2, and Eleven Flash v2.5 are enabled by default; Eleven v3, Eleven Flash v2, and Eleven Turbo v2.5 can be turned on in the same list.++ ElevenLabs has no chat model, so the provider page shows no **Check** button. Verify the key by generating speech as described below.++ <Callout type={'warning'}>+ ElevenLabs bills each synthesized character. Review the [ElevenLabs API pricing](https://elevenlabs.io/pricing/api) 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 elevenlabs/eleven_v4 -o hello.mp3+```++- **Voice** — when no voice is given, the default voice Roger is used, which also works with free-tier keys. Pass `--voice <voice id>` to use another voice from the built-in list or from your own ElevenLabs voice library.++<Callout type={'warning'}>+ Apart from the default Roger, the built-in voices come from the ElevenLabs Voice Library, which **free-tier API keys cannot use through the API**. On the free plan, keep the default or pass a voice you own (for example one created with Voice Design or Instant Voice Cloning) with `--voice <voice id>`, or upgrade to a paid plan. Roger is one of the ElevenLabs Default voices, which only accounts created before March 2026 can use, until ElevenLabs retires them on 2026-12-31. When Roger is not available to your account, LobeHub picks a voice from your account instead (your own voices first, then premade ones); this needs the `voices_read` permission on the key. If no usable voice is found, pass one with `--voice`.+</Callout>++- **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** — Eleven Multilingual v2 and the Flash and Turbo models accept a speed from `0.7` to `1.2`. Eleven v3 and v4 do not accept a speed setting.++## Troubleshooting++**"ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again."** — No key was found, or ElevenLabs rejected the key. Enter a valid key in **App Settings → AI Providers → ElevenLabs**, or ask the administrator to set `ELEVENLABS_API_KEY` on the server. When ElevenLabs rejected the key, its own message follows in parentheses, for example `ElevenLabs API error (401): Invalid API key`.++**"Free-tier ElevenLabs keys cannot use Voice Library voices…"** — Your key is on the free plan and the voice comes from the Voice Library. See the voice note above.++**Quota or rate-limit errors** — Your ElevenLabs plan has run out of characters or reached its concurrency limit. Check usage in the ElevenLabs dashboard.++For self-hosted deployments, see `ELEVENLABS_API_KEY` in the [model provider environment variables](/docs/self-hosting/environment-variables/model-provider#elevenlabs).diff --git a/docs/usage/providers/elevenlabs.zh-CN.mdx b/docs/usage/providers/elevenlabs.zh-CN.mdxnew file mode 100644index 00000000000..72e9553d177--- /dev/null+++ b/docs/usage/providers/elevenlabs.zh-CN.mdx@@ -0,0 +1,65 @@+---+title: 在 LobeHub 中使用 ElevenLabs API Key+description: 在 LobeHub 中配置 ElevenLabs API Key,使用 Eleven v4、Eleven Multilingual v2、Eleven Flash v2.5 生成自然逼真的语音。+tags:+ - ElevenLabs+ - 语音合成+ - TTS+ - API Key+---++# 在 LobeHub 中使用 ElevenLabs++[ElevenLabs](https://elevenlabs.io) 是一家 AI 音频公司,其语音合成模型支持 90 多种语言,并提供丰富的音色库。在 LobeHub 中,ElevenLabs 只提供语音合成(TTS),没有对话模型。++<Steps>+ ### 步骤一:获取 ElevenLabs API Key++ - 注册或登录 [ElevenLabs](https://elevenlabs.io);+ - 打开 [API Keys](https://elevenlabs.io/app/settings/api-keys) 页面,创建一个密钥;+ - 复制密钥并妥善保存。++ ### 步骤二:在 LobeHub 中配置 ElevenLabs++ - 打开 **应用设置 → AI 服务商**,选择 **ElevenLabs**(可在服务商搜索框中输入 `Eleven` 快速定位);+ - 将密钥粘贴到 **API Key** 输入框。修改会自动保存,密钥在存储前会使用 AES-GCM 加密;+ - 打开服务商名称右侧的开关;+ - 可选:如果你的 ElevenLabs 工作区使用数据驻留(data residency)地址,可在 **API 代理地址** 中填写,例如 `https://api.eu.residency.elevenlabs.io`。留空则使用 `https://api.elevenlabs.io`。++ ### 步骤三:选择模型++ **模型列表** 的 **TTS** 标签下列出了 ElevenLabs 语音模型。Eleven v4、Eleven Multilingual v2、Eleven Flash v2.5 默认启用;Eleven v3、Eleven Flash v2、Eleven Turbo v2.5 可在同一列表中手动开启。++ ElevenLabs 没有对话模型,因此服务商页面不显示 **检查** 按钮。可按下文方式生成一段语音来验证密钥。++ <Callout type={'warning'}>+ ElevenLabs 按合成的字符数计费。大量生成音频前,请先查看 [ElevenLabs API 定价](https://elevenlabs.io/pricing/api)。+ </Callout>+</Steps>++## 生成语音++语音合成通过 LobeHub 的语音合成接口完成,LobeHub CLI(`lh`)与兼容 OpenAI 的 `POST /api/v1/audio/speech` 接口都使用该接口:++```bash+lh generate tts "你好,LobeHub" -m elevenlabs/eleven_v4 -o hello.mp3+```++- **音色**:未指定时使用默认音色 Roger,免费档 API Key 也能使用。可用 `--voice <音色 ID>` 选择内置列表或你自己 ElevenLabs 音色库中的音色;+- **长度**:语音以单个响应返回,每次请求最多 4096 个字符,更长的文本请拆成多次请求;+- **格式**:`mp3`(默认)或 `opus`;+- **语速**:Eleven Multilingual v2 以及 Flash、Turbo 系列支持 `0.7` 至 `1.2` 的语速;Eleven v3 和 v4 不支持语速设置。++<Callout type={'warning'}>+ 除默认的 Roger 外,内置音色都来自 ElevenLabs 音色库(Voice Library),**免费档 API Key 无法通过 API 使用这些音色**。免费档请保留默认音色,或用 `--voice <音色 ID>` 指定你自己拥有的音色(例如通过 Voice Design 或即时声音克隆创建的音色),或升级到付费套餐。Roger 属于 ElevenLabs 的旧版默认音色,仅 2026 年 3 月前注册的账号可用,并将于 2026-12-31 停用。账号无法使用 Roger 时,LobeHub 会改用你账号中的音色(优先你自己创建的音色,其次是预置音色),这需要密钥具备 `voices_read` 权限;找不到可用音色时,请用 `--voice` 指定。+</Callout>++## 常见问题++**“ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again.”**:没有找到密钥,或密钥被 ElevenLabs 拒绝。请在 **应用设置 → AI 服务商 → ElevenLabs** 中填写有效密钥,或请管理员在服务端设置 `ELEVENLABS_API_KEY`。密钥被拒绝时,括号中会附上 ElevenLabs 返回的原始信息,例如 `ElevenLabs API error (401): Invalid API key`。++**“Free-tier ElevenLabs keys cannot use Voice Library voices…”**:你的密钥属于免费档,而所选音色来自音色库,见上文音色说明。++**额度或限流错误**:ElevenLabs 套餐的字符额度已用完或达到并发上限,请在 ElevenLabs 控制台查看用量。++自托管部署请参阅 [模型服务商环境变量](/zh/docs/self-hosting/environment-variables/model-provider#elevenlabs) 中的 `ELEVENLABS_API_KEY`。diff --git a/locales/en-US/models.json b/locales/en-US/models.jsonindex 0a4bbced535..98003758539 100644--- a/locales/en-US/models.json+++ b/locales/en-US/models.json@@ -452,6 +452,12 @@"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.","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.",+ "eleven_flash_v2_5.description": "Ultra-low-latency (~100 ms) speech model for real-time use across 32 languages, at half the price of the quality models. Up to 40,000 characters per request.",+ "eleven_multilingual_v2.description": "Lifelike speech with rich emotional expression across 29 languages. Up to 10,000 characters per request.",+ "eleven_turbo_v2_5.description": "Low-latency speech model across 32 languages. ElevenLabs has deprecated it in favor of Eleven Flash v2.5, which matches it at lower latency.",+ "eleven_v3.description": "Previous-generation expressive speech model with audio tags and 70+ languages. Up to 5,000 characters per request.",+ "eleven_v4.description": "ElevenLabs’ most expressive, highest-quality speech model, with audio tags, high-fidelity voice cloning and 90+ languages. Up to 10,000 characters per request.","emohaa.description": "Emohaa is a mental health model with professional counseling abilities to help users understand emotional issues.","ernie-4.5-8k-preview.description": "ERNIE 4.5 8K Preview is an 8K context preview model for evaluating ERNIE 4.5.","ernie-4.5-turbo-128k.description": "ERNIE 4.5 Turbo 128K is a high-performance general model with search augmentation and tool calling for QA, coding, and agent scenarios.",diff --git a/locales/en-US/providers.json b/locales/en-US/providers.jsonindex 59ad5d0f6f9..4682d144521 100644--- a/locales/en-US/providers.json+++ b/locales/en-US/providers.json@@ -19,6 +19,7 @@"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.",+ "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.","giteeai.description": "Gitee AI Serverless APIs provide plug-and-play LLM inference services for developers.",diff --git a/locales/zh-CN/models.json b/locales/zh-CN/models.jsonindex 12193b6eacd..b9ceece506a 100644--- a/locales/zh-CN/models.json+++ b/locales/zh-CN/models.json@@ -452,6 +452,12 @@"doubao-seedream-5-0-260128.description": "Doubao-Seedream-5.0-lite是字节跳动最新的图像生成模型。首次集成在线检索功能,能够结合实时网络信息,提升生成图像的时效性。模型智能性也得到升级,能够精确解析复杂指令和视觉内容。此外,它在专业场景中的全球知识覆盖、参考一致性和生成质量方面均有提升,更好地满足企业级视觉创作需求。","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 个字符。",+ "eleven_flash_v2_5.description": "超低延迟(约 100 ms)语音模型,适用于实时场景,支持 32 种语言,价格为高质量模型的一半。单次请求最多 40,000 个字符。",+ "eleven_multilingual_v2.description": "逼真自然、情感表达丰富的语音模型,支持 29 种语言。单次请求最多 10,000 个字符。",+ "eleven_turbo_v2_5.description": "支持 32 种语言的低延迟语音模型。ElevenLabs 已将其弃用,建议改用效果相同、延迟更低的 Eleven Flash v2.5。",+ "eleven_v3.description": "上一代高表现力语音模型,支持音频标签与 70 多种语言。单次请求最多 5,000 个字符。",+ "eleven_v4.description": "ElevenLabs 表现力最强、音质最高的语音模型,支持音频标签、高保真声音克隆与 90 多种语言。单次请求最多 10,000 个字符。","emohaa.description": "Emohaa 是一款心理健康模型,具备专业咨询能力,帮助用户理解情绪问题。","ernie-4.5-8k-preview.description": "ERNIE 4.5 8K Preview 是一款用于评估 ERNIE 4.5 的 8K 上下文预览模型。","ernie-4.5-turbo-128k.description": "ERNIE 4.5 Turbo 128K 是一款高性能通用模型,支持搜索增强与工具调用,适用于问答、编程与代理场景。",diff --git a/locales/zh-CN/providers.json b/locales/zh-CN/providers.jsonindex e1f4a14f6fd..52c1de8b328 100644--- a/locales/zh-CN/providers.json+++ b/locales/zh-CN/providers.json@@ -19,6 +19,7 @@"cometapi.description": "CometAPI 提供对 OpenAI、Anthropic、Google 等前沿模型的访问,用户可根据不同需求选择最优模型与价格。","comfyui.description": "一个强大的开源工作流引擎,支持图像、视频和音频生成,兼容 SD、FLUX、Qwen、混元、WAN 等模型,支持节点式编辑与私有部署。","deepseek.description": "DeepSeek 专注于人工智能研究与应用。其最新的 DeepSeek V4 系列包含 Flash 和 Pro 两个版本,具备 100 万上下文窗口和混合式思维能力,在推理与智能体基准测试中可与领先的闭源前沿模型竞争。",+ "elevenlabs.description": "ElevenLabs 是一家 AI 音频公司,其文本转语音模型可生成 90 多种语言的逼真、富有表现力的语音,并提供丰富的音色库与声音克隆能力。","fal.description": "一个为开发者打造的生成式媒体平台。","fireworksai.description": "Fireworks AI 提供先进的语言模型服务,支持函数调用与多模态处理。Firefunction V2(基于 Llama-3)优化了函数调用、对话与指令执行,FireLLaVA-13B 支持图文混合输入,另有 Llama 与 Mixtral 系列模型。","giteeai.description": "Gitee AI Serverless API 为开发者提供即插即用的大模型推理服务。",diff --git a/packages/env/src/llm.ts b/packages/env/src/llm.tsindex 17204bd6249..0696e562ab2 100644--- a/packages/env/src/llm.ts+++ b/packages/env/src/llm.ts@@ -56,6 +56,9 @@ export const getLLMConfig = () => {ENABLED_MINIMAX: z.boolean(),MINIMAX_API_KEY: z.string().optional(),+ ENABLED_ELEVENLABS: z.boolean(),+ ELEVENLABS_API_KEY: z.string().optional(),+ENABLED_MISTRAL: z.boolean(),MISTRAL_API_KEY: z.string().optional(),@@ -303,6 +306,9 @@ export const getLLMConfig = () => {ENABLED_MINIMAX: !!process.env.MINIMAX_API_KEY,MINIMAX_API_KEY: process.env.MINIMAX_API_KEY,+ ENABLED_ELEVENLABS: !!process.env.ELEVENLABS_API_KEY,+ ELEVENLABS_API_KEY: process.env.ELEVENLABS_API_KEY,+ENABLED_MISTRAL: !!process.env.MISTRAL_API_KEY,MISTRAL_API_KEY: process.env.MISTRAL_API_KEY,diff --git a/packages/model-bank/package.json b/packages/model-bank/package.jsonindex d77ed5f9c87..8ba551e4021 100644--- a/packages/model-bank/package.json+++ b/packages/model-bank/package.json@@ -32,6 +32,7 @@"./cometapi": "./src/aiModels/cometapi.ts","./comfyui": "./src/aiModels/comfyui.ts","./deepseek": "./src/aiModels/deepseek.ts",+ "./elevenlabs": "./src/aiModels/elevenlabs.ts","./fal": "./src/aiModels/fal.ts","./fireworksai": "./src/aiModels/fireworksai.ts","./giteeai": "./src/aiModels/giteeai.ts",diff --git a/packages/model-bank/src/aiModels/elevenlabs.ts b/packages/model-bank/src/aiModels/elevenlabs.tsnew file mode 100644index 00000000000..4bec55d89a5--- /dev/null+++ b/packages/model-bank/src/aiModels/elevenlabs.ts@@ -0,0 +1,100 @@+import {+ elevenlabsExpressiveTTSSchema,+ elevenlabsTTSSchema,+ elevenlabsTTSVoices,+} from '../const/ttsParameters';+import type { AITTSModelCard } from '../types/aiModel';++// API list prices: $0.08 (v4 / v3 / Multilingual v2) and $0.04 (Flash / Turbo) per 1k characters.+// `eleven_v4_turbo` is left out: ElevenLabs only serves it over the Text to Dialogue websocket,+// not the Create speech endpoint.+// @see https://elevenlabs.io/pricing/api+// @see https://elevenlabs.io/docs/overview/models+const elevenlabsTTSModels: AITTSModelCard[] = [+ {+ description:+ 'ElevenLabs’ most expressive, highest-quality speech model, with audio tags, high-fidelity voice cloning and 90+ languages. Up to 10,000 characters per request.',+ displayName: 'Eleven v4',+ enabled: true,+ id: 'eleven_v4',+ isOfficial: true,+ parameters: elevenlabsExpressiveTTSSchema,+ pricing: {+ units: [{ name: 'textInput', rate: 80, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: elevenlabsTTSVoices,+ },+ {+ description:+ 'Lifelike speech with rich emotional expression across 29 languages. Up to 10,000 characters per request.',+ displayName: 'Eleven Multilingual v2',+ enabled: true,+ id: 'eleven_multilingual_v2',+ isOfficial: true,+ parameters: elevenlabsTTSSchema,+ pricing: {+ units: [{ name: 'textInput', rate: 80, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: elevenlabsTTSVoices,+ },+ {+ description:+ 'Ultra-low-latency (~100 ms) speech model for real-time use across 32 languages, at half the price of the quality models. Up to 40,000 characters per request.',+ displayName: 'Eleven Flash v2.5',+ enabled: true,+ id: 'eleven_flash_v2_5',+ isOfficial: true,+ parameters: elevenlabsTTSSchema,+ pricing: {+ units: [{ name: 'textInput', rate: 40, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: elevenlabsTTSVoices,+ },+ {+ description:+ 'Previous-generation expressive speech model with audio tags and 70+ languages. Up to 5,000 characters per request.',+ displayName: 'Eleven v3',+ id: 'eleven_v3',+ isOfficial: true,+ parameters: elevenlabsExpressiveTTSSchema,+ pricing: {+ units: [{ name: 'textInput', rate: 80, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: elevenlabsTTSVoices,+ },+ {+ description:+ 'English-only ultra-low-latency (~135 ms) speech model for real-time use. Up to 30,000 characters per request.',+ displayName: 'Eleven Flash v2',+ id: 'eleven_flash_v2',+ isOfficial: true,+ parameters: elevenlabsTTSSchema,+ pricing: {+ units: [{ name: 'textInput', rate: 40, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: elevenlabsTTSVoices,+ },+ {+ description:+ 'Low-latency speech model across 32 languages. ElevenLabs has deprecated it in favor of Eleven Flash v2.5, which matches it at lower latency.',+ displayName: 'Eleven Turbo v2.5',+ id: 'eleven_turbo_v2_5',+ isOfficial: true,+ legacy: true,+ parameters: elevenlabsTTSSchema,+ pricing: {+ units: [{ name: 'textInput', rate: 40, strategy: 'fixed', unit: 'millionCharacters' }],+ },+ type: 'tts',+ voices: elevenlabsTTSVoices,+ },+];++export const allModels = [...elevenlabsTTSModels];++export default allModels;diff --git a/packages/model-bank/src/aiModels/index.ts b/packages/model-bank/src/aiModels/index.tsindex 85ce1300090..6cf3f037d66 100644--- a/packages/model-bank/src/aiModels/index.ts+++ b/packages/model-bank/src/aiModels/index.ts@@ -21,6 +21,7 @@ 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 elevenlabs } from './elevenlabs';import { default as fal } from './fal';import { default as fireworksai } from './fireworksai';import { default as giteeai } from './giteeai';@@ -135,6 +136,7 @@ const staticModelMap: ModelsMap = {cometapi,comfyui,deepseek,+ elevenlabs,fal,fireworksai,giteeai,@@ -255,6 +257,7 @@ 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 elevenlabs } from './elevenlabs';export { default as fal, fluxSchnellParamsSchema } from './fal';export { default as fireworksai } from './fireworksai';export { default as giteeai } from './giteeai';diff --git a/packages/model-bank/src/const/__tests__/ttsParameters.test.ts b/packages/model-bank/src/const/__tests__/ttsParameters.test.tsindex 87589ba5069..f9e604f3a06 100644--- a/packages/model-bank/src/const/__tests__/ttsParameters.test.ts+++ b/packages/model-bank/src/const/__tests__/ttsParameters.test.ts@@ -1,8 +1,14 @@import { describe, expect, it } from 'vitest';+import elevenlabsModels from '../../aiModels/elevenlabs';import minimaxModels from '../../aiModels/minimax';import { openaiTTSModels } from '../../aiModels/openai/nonChat';-import { TTSVoiceSchema, validateTTSModelParamsSchema } from '../../standard-parameters';+import {+ extractTTSDefaultValues,+ TTSVoiceSchema,+ validateTTSModelParamsSchema,+ validateTTSParams,+} from '../../standard-parameters';import type { AITTSModelCard } from '../../types/aiModel';describe('OpenAI TTS model cards', () => {@@ -111,3 +117,99 @@ describe('MiniMax TTS model cards', () => {expect(emotionsOf('speech-02-hd')).not.toContain('fluent');});});++describe('ElevenLabs TTS model cards', () => {+ const ttsCards = elevenlabsModels.filter((card): card is AITTSModelCard => card.type === 'tts');+ const cardOf = (id: string) => ttsCards.find((card) => card.id === id)!;++ it('lists the current speech models, enabling v4, Multilingual v2 and Flash v2.5', () => {+ expect(ttsCards).toHaveLength(elevenlabsModels.length);+ expect(ttsCards.map((card) => card.id)).toEqual([+ 'eleven_v4',+ 'eleven_multilingual_v2',+ 'eleven_flash_v2_5',+ 'eleven_v3',+ 'eleven_flash_v2',+ 'eleven_turbo_v2_5',+ ]);+ expect(ttsCards.filter((card) => card.enabled).map((card) => card.id)).toEqual([+ 'eleven_v4',+ 'eleven_multilingual_v2',+ 'eleven_flash_v2_5',+ ]);+ // Deprecated by ElevenLabs in favor of Flash v2.5.+ expect(cardOf('eleven_turbo_v2_5').legacy).toBe(true);+ });++ it.each(ttsCards.map((card) => [card.id, card]))(+ '%s declares valid params, voices and USD per-character pricing',+ (id, card) => {+ const params = validateTTSModelParamsSchema(card.parameters);+ expect(params.format?.enum).toEqual(['mp3', 'opus', 'wav', 'pcm']);+ expect(params.format?.default).toBe('mp3');+ for (const key of ['emotion', 'instructions', 'pitch', 'sampleRate', 'volume'])+ expect(params).not.toHaveProperty(key);++ const voiceIds = card.voices!.map((voice) => voice.id);+ expect(voiceIds).toContain(params.voice!.default);+ expect(new Set(voiceIds).size).toBe(voiceIds.length);+ for (const voice of card.voices!) expect(() => TTSVoiceSchema.parse(voice)).not.toThrow();++ // $0.08 (v4 / v3 / Multilingual v2) or $0.04 (Flash / Turbo) per 1k characters+ const rate = /flash|turbo/.test(id) ? 40 : 80;+ expect(card.isOfficial).toBe(true);+ expect(card.pricing).toEqual({+ units: [{ name: 'textInput', rate, strategy: 'fixed', unit: 'millionCharacters' }],+ });+ },+ );++ it('only offers speed (0.7–1.2) on the models that accept it', () => {+ for (const id of ['eleven_multilingual_v2', 'eleven_flash_v2_5', 'eleven_flash_v2']) {+ expect(validateTTSModelParamsSchema(cardOf(id).parameters).speed).toMatchObject({+ default: 1,+ max: 1.2,+ min: 0.7,+ });+ }++ // Eleven v3 and v4 have no speed setting.+ for (const id of ['eleven_v4', 'eleven_v3']) {+ const schema = cardOf(id).parameters!;+ expect(schema).not.toHaveProperty('speed');+ expect(validateTTSParams(schema, { speed: 1.1 })).toEqual([+ { key: 'speed', reason: 'not supported by this model' },+ ]);+ }++ const flash = cardOf('eleven_flash_v2_5').parameters!;+ expect(validateTTSParams(flash, { format: 'wav', speed: 1.2 })).toEqual([]);+ expect(validateTTSParams(flash, { speed: 1.5 })).toEqual([+ { key: 'speed', reason: 'must be between 0.7 and 1.2' },+ ]);+ expect(validateTTSParams(flash, { format: 'aac' })).toHaveLength(1);+ expect(extractTTSDefaultValues(flash)).toEqual({ format: 'mp3', speed: 1 });+ });++ it('ships the long-lived replacements for the Default voices that expire on 2026-12-31', () => {+ const voices = cardOf('eleven_v4').voices!;+ const ids = voices.map((voice) => voice.id);++ expect(voices).toHaveLength(20);+ expect(voices.every((voice) => voice.language === 'multilingual')).toBe(true);+ // Replacements for Sarah, George and Daniel.+ expect(ids).toEqual(+ expect.arrayContaining([+ 'OZ0L6eISlOejga3XjDFt',+ '6WwXjDDEMyNmFG95zycZ',+ 'fnYMz3F5gMEDGMWcH1ex',+ ]),+ );+ // Roger is the free-tier-callable default and the only legacy Default voice offered.+ expect(voices[0].id).toBe('CwhRBWXzGAHq8TQ4Fs17');+ expect(cardOf('eleven_v4').parameters?.voice?.default).toBe('CwhRBWXzGAHq8TQ4Fs17');+ // Other legacy Default voice ids (Sarah, George, Rachel) must not be offered.+ for (const legacyId of ['EXAVITQu4vr4xnSDxMaL', 'JBFqnCBsd6RMkjVDRZzb', '21m00Tcm4TlvDq8ikWAM'])+ expect(ids).not.toContain(legacyId);+ });+});diff --git a/packages/model-bank/src/const/modelProvider.ts b/packages/model-bank/src/const/modelProvider.tsindex e8922d9d6ab..f211be0ee4a 100644--- a/packages/model-bank/src/const/modelProvider.ts+++ b/packages/model-bank/src/const/modelProvider.ts@@ -19,6 +19,7 @@ export enum ModelProvider {CometAPI = 'cometapi',ComfyUI = 'comfyui',DeepSeek = 'deepseek',+ ElevenLabs = 'elevenlabs',Fal = 'fal',FireworksAI = 'fireworksai',GiteeAI = 'giteeai',diff --git a/packages/model-bank/src/const/ttsParameters.ts b/packages/model-bank/src/const/ttsParameters.tsindex 8f3d3cd3c26..efef7dbe89f 100644--- a/packages/model-bank/src/const/ttsParameters.ts+++ b/packages/model-bank/src/const/ttsParameters.ts@@ -172,3 +172,194 @@ export const minimaxSpeech26Schema = createMiniMaxTTSSchema([]);export const minimaxSpeech02Schema = createMiniMaxTTSSchema(MINIMAX_BASE_EMOTIONS);++/**+ * ElevenLabs voices that every account keeps using after the legacy Default voices+ * (Rachel, George, Sarah, ...) expire on 2026-12-31. Each entry is the official+ * replacement for one Default voice; `gender` follows the voice it replaces. They are+ * Voice Library voices, so free-tier keys cannot call them through the API.+ * ElevenLabs voices speak every language the selected model supports.+ * @see https://elevenlabs.io/docs/help-center/product/voices/my-voices/what-are-default-voices+ */+export const elevenlabsTTSVoices: TTSVoice[] = [+ /**+ * Default voice: a legacy Default (premade) voice, so free-tier keys can call it+ * through the API, unlike the Voice Library replacements below. ElevenLabs expires the+ * Default voices on 2026-12-31; switch the default to a replacement by then.+ */+ {+ description: 'Laid-back, casual, resonant',+ displayName: 'Roger',+ gender: 'male',+ id: 'CwhRBWXzGAHq8TQ4Fs17',+ language: 'multilingual',+ },+ {+ description: 'Warm, grounded storyteller',+ displayName: 'Darian',+ gender: 'male',+ id: 'gOupLcAkjEnguROwi4oS',+ language: 'multilingual',+ },+ {+ description: 'Warm, soft guide',+ displayName: 'Talia',+ gender: 'female',+ id: 'OZ0L6eISlOejga3XjDFt',+ language: 'multilingual',+ },+ {+ description: 'Crisp professional narrator',+ displayName: 'Elara',+ gender: 'female',+ id: 'WQP7cQUF5aAS6Axh5yaa',+ language: 'multilingual',+ },+ {+ description: 'Dry, calm Australian',+ displayName: 'Baxter',+ gender: 'male',+ id: 'jSuBIjxMKhqIfb0wCK1F',+ language: 'multilingual',+ },+ {+ description: 'Crisp British baritone',+ displayName: 'Eldrin',+ gender: 'male',+ id: '6WwXjDDEMyNmFG95zycZ',+ language: 'multilingual',+ },+ {+ description: 'Husky trickster',+ displayName: 'Callum',+ gender: 'male',+ id: 'fs2OqxduwXgp9foh2xjK',+ language: 'multilingual',+ },+ {+ description: 'Upbeat modern narrator',+ displayName: 'Elowen',+ gender: 'neutral',+ id: 'dvbL7qkNGZY1IqPGZAjM',+ language: 'multilingual',+ },+ {+ description: 'Amateur warrior',+ displayName: 'Kaelen',+ gender: 'male',+ id: '10NkTYmU7tSz3Kkl3Lex',+ language: 'multilingual',+ },+ {+ description: 'Bright and informative',+ displayName: 'Lawrence',+ gender: 'male',+ id: 'ktkP7Nsj67dw2zcplQYt',+ language: 'multilingual',+ },+ {+ description: 'Polished global anchor',+ displayName: 'Alicia',+ gender: 'female',+ id: 'BFd5oBc2DDna33pSi4Gf',+ language: 'multilingual',+ },+ {+ description: 'Friendly, casual neighbor',+ displayName: 'Maisie',+ gender: 'female',+ id: 'QtY3JBOUKEB5xzrRfOKc',+ language: 'multilingual',+ },+ {+ description: 'Effortless and cool',+ displayName: 'Warren',+ gender: 'male',+ id: '7QN34D2r3hCNwbOYIeK0',+ language: 'multilingual',+ },+ {+ description: 'Upbeat and natural',+ displayName: 'Jade',+ gender: 'female',+ id: 'g7LVvkPWALzPxOQbF6OE',+ language: 'multilingual',+ },+ {+ description: 'Natural and helpful',+ displayName: 'Eddie',+ gender: 'male',+ id: 'l7kNoIfnJKPg7779LI2t',+ language: 'multilingual',+ },+ {+ description: 'Trusted guide',+ displayName: 'Caleb',+ gender: 'male',+ id: 'AaOhDHYJ1XLZk74lXhdE',+ language: 'multilingual',+ },+ {+ description: 'Midnight storyteller',+ displayName: 'Sawyer',+ gender: 'male',+ id: '8dEUmyPMdDdK91vboYih',+ language: 'multilingual',+ },+ {+ description: 'Articulate anchor',+ displayName: 'Finley',+ gender: 'male',+ id: 'fnYMz3F5gMEDGMWcH1ex',+ language: 'multilingual',+ },+ {+ description: 'Atmospheric storyteller',+ displayName: 'Florence',+ gender: 'female',+ id: '22N9cF8z0o7y23njdyaY',+ language: 'multilingual',+ },+ {+ description: 'Seasoned mentor',+ displayName: 'Wyatt',+ gender: 'male',+ id: 'FrS6cKLB1wg4WYgPa9GW',+ language: 'multilingual',+ },+];++/**+ * `output_format` covers mp3, opus, pcm and wav (plus telephony ulaw/alaw); there is no+ * aac or flac output.+ * @see https://elevenlabs.io/docs/api-reference/text-to-speech/convert+ */+const ELEVENLABS_TTS_FORMATS = TTS_AUDIO_FORMATS.filter(+ (format) => format !== 'aac' && format !== 'flac',+);++/**+ * Roger, a Default (premade) voice: callable on every plan for accounts created before+ * March 2026, until ElevenLabs retires the Default voices on 2026-12-31. The runtime falls+ * back to a voice from the account when this one is unavailable.+ */+export const ELEVENLABS_DEFAULT_VOICE_ID = 'CwhRBWXzGAHq8TQ4Fs17';++/** Voice ids in the built-in ElevenLabs catalog. */+export const ELEVENLABS_VOICE_IDS: ReadonlySet<string> = new Set(+ elevenlabsTTSVoices.map((voice) => voice.id),+);+const ELEVENLABS_DEFAULT_VOICE = ELEVENLABS_DEFAULT_VOICE_ID;++/** Multilingual v2 and the Flash / Turbo family take `voice_settings.speed` from 0.7 to 1.2. */+export const elevenlabsTTSSchema: TTSModelParamsSchema = {+ format: { default: 'mp3', enum: ELEVENLABS_TTS_FORMATS },+ speed: { default: 1, max: 1.2, min: 0.7, step: 0.05 },+ voice: { default: ELEVENLABS_DEFAULT_VOICE },+};++/** Eleven v3 and v4 have no speed setting. */+export const elevenlabsExpressiveTTSSchema: TTSModelParamsSchema = {+ format: { default: 'mp3', enum: ELEVENLABS_TTS_FORMATS },+ voice: { default: ELEVENLABS_DEFAULT_VOICE },+};diff --git a/packages/model-bank/src/index.ts b/packages/model-bank/src/index.tsindex 698bb4d8bc4..3252499080c 100644--- a/packages/model-bank/src/index.ts+++ b/packages/model-bank/src/index.ts@@ -1,6 +1,7 @@export * from './aiModels';export * from './const/knowledgeCutoff';export * from './const/modelProvider';+export { ELEVENLABS_DEFAULT_VOICE_ID, ELEVENLABS_VOICE_IDS } from './const/ttsParameters';export * from './standard-parameters';export * from './types';export * from './utils';diff --git a/packages/model-bank/src/modelProviders/elevenlabs.test.ts b/packages/model-bank/src/modelProviders/elevenlabs.test.tsnew file mode 100644index 00000000000..3974692f41c--- /dev/null+++ b/packages/model-bank/src/modelProviders/elevenlabs.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { LOBE_DEFAULT_MODEL_LIST } from '../aiModels';+import { ModelProvider } from '../const/modelProvider';+import ElevenLabsProviderCard from './elevenlabs';+import {+ DEFAULT_MODEL_PROVIDER_LIST,+ ElevenLabsProviderCard as ExportedCard,+ getProviderDisplayName,+ isProviderDisableBrowserRequest,+} from './index';++describe('ElevenLabs provider', () => {+ it('is registered under the elevenlabs id', () => {+ expect(ModelProvider.ElevenLabs).toBe('elevenlabs');+ expect(ExportedCard).toBe(ElevenLabsProviderCard);+ expect(DEFAULT_MODEL_PROVIDER_LIST.filter((card) => card.id === 'elevenlabs')).toEqual([+ ElevenLabsProviderCard,+ ]);+ expect(getProviderDisplayName('elevenlabs')).toBe('ElevenLabs');+ });++ it('asks only for an API key and keeps requests on the server', () => {+ expect(ElevenLabsProviderCard).toMatchObject({+ apiKeyUrl: 'https://elevenlabs.io/app/settings/api-keys',+ chatModels: [],+ name: 'ElevenLabs',+ url: 'https://elevenlabs.io',+ });+ expect(ElevenLabsProviderCard.description).toBeTruthy();+ expect(ElevenLabsProviderCard.settings).toMatchObject({+ proxyUrl: { placeholder: 'https://api.elevenlabs.io' },+ showChecker: false,+ showModelFetcher: false,+ });+ // No chat model to check against and no OpenAI-compatible SDK.+ expect(ElevenLabsProviderCard.settings.sdkType).toBeUndefined();+ expect(ElevenLabsProviderCard.checkModel).toBeUndefined();+ expect(isProviderDisableBrowserRequest('elevenlabs')).toBe(true);+ });++ it('contributes only TTS cards to the default model list', () => {+ const cards = LOBE_DEFAULT_MODEL_LIST.filter((card) => card.providerId === 'elevenlabs');++ expect(cards.length).toBeGreaterThanOrEqual(3);+ expect(cards.every((card) => card.type === 'tts' && card.source === 'builtin')).toBe(true);+ expect(cards.map((card) => card.id)).toEqual(+ expect.arrayContaining(['eleven_multilingual_v2', 'eleven_flash_v2_5', 'eleven_turbo_v2_5']),+ );+ });+});diff --git a/packages/model-bank/src/modelProviders/elevenlabs.ts b/packages/model-bank/src/modelProviders/elevenlabs.tsnew file mode 100644index 00000000000..dc582565134--- /dev/null+++ b/packages/model-bank/src/modelProviders/elevenlabs.ts@@ -0,0 +1,28 @@+import type { ModelProviderCard } from '../types';++/**+ * Text-to-speech only. Requests carry the key in the `xi-api-key` header; the base URL+ * can point at a data-residency host instead of the global API.+ * @see https://elevenlabs.io/docs/api-reference/text-to-speech/convert+ */+const ElevenLabs: ModelProviderCard = {+ apiKeyUrl: 'https://elevenlabs.io/app/settings/api-keys',+ chatModels: [],+ 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.',+ id: 'elevenlabs',+ modelsUrl: 'https://elevenlabs.io/docs/overview/models',+ name: 'ElevenLabs',+ settings: {+ disableBrowserRequest: true,+ proxyUrl: {+ placeholder: 'https://api.elevenlabs.io',+ },+ showAddNewModel: false,+ showChecker: false,+ showModelFetcher: false,+ },+ url: 'https://elevenlabs.io',+};++export default ElevenLabs;diff --git a/packages/model-bank/src/modelProviders/index.ts b/packages/model-bank/src/modelProviders/index.tsindex 3c237e168ac..d033d6d62dd 100644--- a/packages/model-bank/src/modelProviders/index.ts+++ b/packages/model-bank/src/modelProviders/index.ts@@ -21,6 +21,7 @@ import CohereProvider from './cohere';import CometAPIProvider from './cometapi';import ComfyUIProvider from './comfyui';import DeepSeekProvider from './deepseek';+import ElevenLabsProvider from './elevenlabs';import FalProvider from './fal';import FireworksAIProvider from './fireworksai';import GiteeAIProvider from './giteeai';@@ -172,6 +173,7 @@ export const DEFAULT_MODEL_PROVIDER_LIST = [AiHubMixProvider,OpenRouterProvider,FalProvider,+ ElevenLabsProvider,OllamaProvider,OllamaCloudProvider,VLLMProvider,@@ -325,6 +327,7 @@ 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 ElevenLabsProviderCard } from './elevenlabs';export { default as FalProviderCard } from './fal';export { default as FireworksAIProviderCard } from './fireworksai';export { default as GiteeAIProviderCard } from './giteeai';diff --git a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts b/packages/model-runtime/src/core/RouterRuntime/apiTypes.tsindex 0188091c21a..49fca31a1cd 100644--- a/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts+++ b/packages/model-runtime/src/core/RouterRuntime/apiTypes.ts@@ -7,6 +7,7 @@ export type ApiType =| 'bedrock'| 'cloudflare'| 'deepseek'+ | 'elevenlabs'| 'fal'| 'google'| 'meta'diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.tsindex 5da550a9679..333d4876b0e 100644--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';+import { LobeElevenLabsAI } from '../../providers/elevenlabs';import { LobeTypeSafeAI } from '../../providers/typesafe';import { baseRuntimeMap } from './baseRuntimeMap';@@ -7,4 +8,8 @@ describe('baseRuntimeMap', () => {it('routes the typesafe api type through the TypeSafe runtime', () => {expect(baseRuntimeMap.typesafe).toBe(LobeTypeSafeAI);});++ it('routes the elevenlabs api type through the ElevenLabs speech runtime', () => {+ expect(baseRuntimeMap.elevenlabs).toBe(LobeElevenLabsAI);+ });});diff --git a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.tsindex ee2ffb23bdf..c7e449848df 100644--- a/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts+++ b/packages/model-runtime/src/core/RouterRuntime/baseRuntimeMap.ts@@ -4,6 +4,7 @@ import { LobeAzureOpenAI } from '../../providers/azureOpenai';import { LobeBedrockAI } from '../../providers/bedrock';import { LobeCloudflareAI } from '../../providers/cloudflare';import { LobeDeepSeekAI } from '../../providers/deepseek';+import { LobeElevenLabsAI } from '../../providers/elevenlabs';import { LobeFalAI } from '../../providers/fal';import { LobeGoogleAI } from '../../providers/google';import { LobeMetaAI } from '../../providers/meta';@@ -26,6 +27,7 @@ export const baseRuntimeMap = {bedrock: LobeBedrockAI,cloudflare: LobeCloudflareAI,deepseek: LobeDeepSeekAI,+ elevenlabs: LobeElevenLabsAI,fal: LobeFalAI,google: LobeGoogleAI,meta: LobeMetaAI,diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.tsindex 3f64373f475..f47c2c027d2 100644--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.textToSpeech.test.ts@@ -49,4 +49,35 @@ describe('createRouterRuntime textToSpeech', () => {routeAttempt: expect.objectContaining({ attemptId: expect.any(String) }),});});++ it('routes apiType elevenlabs through the ElevenLabs 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: 'elevenlabs',+ models: ['eleven_flash_v2_5'],+ options: { apiKey: 'channel-xi-key' },+ },+ ],+ });++ const result = await new Runtime().textToSpeech(+ { input: 'Hi', model: 'eleven_flash_v2_5', voice: 'voice-1' },+ { 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.elevenlabs.io/v1/text-to-speech/voice-1?output_format=mp3_44100_128',+ );+ expect((init.headers as Record<string, string>)['xi-api-key']).toBe('channel-xi-key');+ vi.unstubAllGlobals();+ });});diff --git a/packages/model-runtime/src/index.ts b/packages/model-runtime/src/index.tsindex 4fe7a53b127..c8e25a04698 100644--- a/packages/model-runtime/src/index.ts+++ b/packages/model-runtime/src/index.ts@@ -57,6 +57,7 @@ export { LobeChatGPTAI } from './providers/chatGPT';export { LobeCometAPIAI } from './providers/cometapi';export { LobeComfyUI } from './providers/comfyui';export { LobeDeepSeekAI } from './providers/deepseek';+export { LobeElevenLabsAI } from './providers/elevenlabs';export { LobeGLMCodingPlanAI } from './providers/glmCodingPlan';export { LobeGoogleAI } from './providers/google';export * from './providers/google/modelId';diff --git a/packages/model-runtime/src/providers/elevenlabs/createSpeech.test.ts b/packages/model-runtime/src/providers/elevenlabs/createSpeech.test.tsnew file mode 100644index 00000000000..e9338667a5a--- /dev/null+++ b/packages/model-runtime/src/providers/elevenlabs/createSpeech.test.ts@@ -0,0 +1,689 @@+// @vitest-environment node+import { AgentRuntimeErrorType } from '@lobechat/types';+import type { Pricing } from 'model-bank';+import { ELEVENLABS_DEFAULT_VOICE_ID } from 'model-bank';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getModelPricing } from '../../utils/getModelPricing';+import {+ buildElevenLabsSpeechRequest,+ clearElevenLabsFallbackVoices,+ createElevenLabsSpeech,+ ELEVENLABS_MAX_INPUT_CHARACTERS,+ ELEVENLABS_NO_ACCOUNT_VOICE_HINT,+ ELEVENLABS_PAID_VOICE_HINT,+ type ElevenLabsSpeechOptions,+ FALLBACK_VOICE_TTL_MS,+ normalizeElevenLabsBaseURL,+ resolveElevenLabsOutputFormat,+} from './createSpeech';++vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));++// $0.08 per 1k characters, as on the eleven_multilingual_v2 card+const multilingualPricing: Pricing = {+ units: [{ name: 'textInput', rate: 80, strategy: 'fixed', unit: 'millionCharacters' }],+};++const options: ElevenLabsSpeechOptions = {+ apiKey: 'xi-test-key',+ baseURL: 'https://api.elevenlabs.io',+ provider: 'elevenlabs',+};++const VOICE = 'OZ0L6eISlOejga3XjDFt';+const AUDIO_BYTES = new Uint8Array([0x49, 0x44, 0x33, 0x04, 0x00]);++const audioResponse = (headers: Record<string, string> = {}) =>+ new Response(AUDIO_BYTES, {+ headers: { 'content-type': 'audio/mpeg', 'request-id': 'req-1', ...headers },+ status: 200,+ });++const errorResponse = (status: number, body: unknown, statusText = '') =>+ new Response(typeof body === 'string' ? body : JSON.stringify(body), {+ headers: { 'content-type': 'application/json' },+ status,+ statusText,+ });++describe('createElevenLabsSpeech', () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);+ vi.mocked(getModelPricing).mockResolvedValue(multilingualPricing);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ vi.restoreAllMocks();+ clearElevenLabsFallbackVoices();+ });++ describe('request mapping', () => {+ it('sends text and model_id, and omits voice_settings when nothing is set', () => {+ const { body, format, outputFormat } = buildElevenLabsSpeechRequest(+ { input: 'Hello', model: 'eleven_multilingual_v2', voice: VOICE },+ 'eleven_multilingual_v2',+ );++ expect(body).toEqual({ model_id: 'eleven_multilingual_v2', text: 'Hello' });+ expect(format).toBe('mp3');+ expect(outputFormat).toBe('mp3_44100_128');+ });++ it('maps speed (and the legacy top-level speed) onto voice_settings.speed', () => {+ expect(+ buildElevenLabsSpeechRequest(+ { input: 'Hi', model: 'm', params: { speed: 1.1 }, voice: VOICE },+ 'm',+ ).body,+ ).toEqual({ model_id: 'm', text: 'Hi', voice_settings: { speed: 1.1 } });++ expect(+ buildElevenLabsSpeechRequest({ input: 'Hi', model: 'm', speed: 0.8, voice: VOICE }, 'm')+ .body,+ ).toMatchObject({ voice_settings: { speed: 0.8 } });+ });++ it.each([+ ['mp3', undefined, 'mp3_44100_128'],+ ['mp3', 22_050, 'mp3_22050_32'],+ ['opus', undefined, 'opus_48000_128'],+ ['pcm', undefined, 'pcm_24000'],+ ['pcm', 16_000, 'pcm_16000'],+ ['wav', undefined, 'wav_44100'],+ ['wav', 48_000, 'wav_48000'],+ ['wav', 12_345, 'wav_44100'],+ ] as const)('maps format %s / sampleRate %s to output_format %s', (format, rate, expected) => {+ expect(resolveElevenLabsOutputFormat(format, rate)).toBe(expected);+ });++ it.each(['aac', 'flac'] as const)('rejects the unsupported %s format', (format) => {+ expect(() => resolveElevenLabsOutputFormat(format)).toThrow(+ `ElevenLabs speech does not support the "${format}" format`,+ );+ });++ it('normalizes a base URL with many slashes in linear time', () => {+ const input = `https://proxy.example.com${'/'.repeat(100_000)}x`;+ const start = performance.now();+ expect(normalizeElevenLabsBaseURL(input)).toBe(input);+ expect(normalizeElevenLabsBaseURL(`https://h${'/'.repeat(100_000)}`)).toBe('https://h');+ expect(performance.now() - start).toBeLessThan(500);+ });++ it('normalizes the base URL, with or without /v1 and trailing slashes', () => {+ expect(normalizeElevenLabsBaseURL(undefined)).toBe('https://api.elevenlabs.io');+ expect(normalizeElevenLabsBaseURL('')).toBe('https://api.elevenlabs.io');+ expect(normalizeElevenLabsBaseURL('https://api.eu.residency.elevenlabs.io/')).toBe(+ 'https://api.eu.residency.elevenlabs.io',+ );+ expect(normalizeElevenLabsBaseURL('https://proxy.example.com/v1/')).toBe(+ 'https://proxy.example.com',+ );+ });+ });++ describe('success', () => {+ it('POSTs to /v1/text-to-speech/{voice_id} with xi-api-key and returns the audio bytes', async () => {+ fetchMock.mockResolvedValue(audioResponse({ 'character-cost': '4' }));+ const onUsage = vi.fn();++ const result = await createElevenLabsSpeech(+ {+ input: 'Hello world',+ model: 'eleven_multilingual_v2',+ params: { format: 'opus', speed: 1.05 },+ voice: VOICE,+ },+ { ...options, headers: { 'x-trace': 't1' }, onUsage },+ );++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(+ `https://api.elevenlabs.io/v1/text-to-speech/${VOICE}?output_format=opus_48000_128`,+ );+ expect(init.method).toBe('POST');+ expect(init.headers).toMatchObject({+ 'Content-Type': 'application/json',+ 'x-trace': 't1',+ 'xi-api-key': 'xi-test-key',+ });+ expect(init.headers.Authorization).toBeUndefined();+ expect(JSON.parse(init.body)).toEqual({+ model_id: 'eleven_multilingual_v2',+ text: 'Hello world',+ voice_settings: { speed: 1.05 },+ });++ expect(result.format).toBe('opus');+ expect(new Uint8Array(result.audio)).toEqual(AUDIO_BYTES);+ // 11 chars × $80 / 1M chars+ expect(result.usage).toEqual({ cost: 0.000_88, inputCharacters: 11 });+ expect(onUsage).toHaveBeenCalledWith(result.usage);+ expect(getModelPricing).toHaveBeenCalledWith(+ 'eleven_multilingual_v2',+ 'elevenlabs',+ undefined,+ );+ });++ it('bills input characters, not the character-cost credits header', async () => {+ // Real Flash responses report e.g. character-cost=7 for 34 characters.+ fetchMock.mockResolvedValue(audioResponse({ 'character-cost': '3' }));++ const result = await createElevenLabsSpeech(+ { input: 'Hello world', model: 'eleven_multilingual_v2', voice: VOICE },+ options,+ );++ expect(result.usage?.inputCharacters).toBe(11);+ });++ it('falls back to counting code points when the header is missing', async () => {+ fetchMock.mockResolvedValue(audioResponse());++ const result = await createElevenLabsSpeech(+ { input: '你好,世界', model: 'eleven_flash_v2_5', voice: VOICE },+ options,+ );++ expect(result.usage?.inputCharacters).toBe(5);+ });++ it('passes the voice id and model id through, applying model id mapping', async () => {+ fetchMock.mockResolvedValue(audioResponse());++ await createElevenLabsSpeech(+ { input: 'Hi', model: 'my-alias', voice: 'custom/voice id' },+ {+ ...options,+ baseURL: 'https://proxy.example.com/v1/',+ modelIdMapping: { 'my-alias': 'eleven_v4' },+ },+ );++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(+ 'https://proxy.example.com/v1/text-to-speech/custom%2Fvoice%20id?output_format=mp3_44100_128',+ );+ expect(JSON.parse(init.body).model_id).toBe('eleven_v4');+ // pricing keys off the public model id+ expect(getModelPricing).toHaveBeenCalledWith('my-alias', 'elevenlabs', undefined);+ });++ it('forwards the abort signal', async () => {+ fetchMock.mockResolvedValue(audioResponse());+ const controller = new AbortController();++ await createElevenLabsSpeech(+ { input: 'Hi', model: 'eleven_v4', voice: VOICE },+ { ...options, signal: controller.signal },+ );++ expect(fetchMock.mock.calls[0][1].signal).toBe(controller.signal);+ });+ });++ describe('routed aliases', () => {+ it('replaces a non-ElevenLabs default voice filled in by the service', async () => {+ fetchMock.mockResolvedValueOnce(audioResponse());++ await createElevenLabsSpeech(+ { input: 'Hi', model: 'my-speech', voice: 'alloy', voiceIsDefault: true },+ {+ ...options,+ modelIdMapping: { 'my-speech': 'eleven_flash_v2_5' },+ } as ElevenLabsSpeechOptions,+ );++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toContain(`/v1/text-to-speech/${ELEVENLABS_DEFAULT_VOICE_ID}?`);+ expect(JSON.parse(init.body).model_id).toBe('eleven_flash_v2_5');+ });++ it('keeps an explicit voice even when it is not in the catalog', async () => {+ fetchMock.mockResolvedValueOnce(audioResponse());+ await createElevenLabsSpeech({ input: 'Hi', model: 'm', voice: 'my-clone' }, options);+ expect(fetchMock.mock.calls[0][0]).toContain('/v1/text-to-speech/my-clone?');+ });++ it('rejects input over the per-request cap before calling ElevenLabs', async () => {+ await expect(+ createElevenLabsSpeech(+ {+ input: '字'.repeat(ELEVENLABS_MAX_INPUT_CHARACTERS + 1),+ model: 'my-speech',+ voice: VOICE,+ },+ options,+ ),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.ProviderBizError });+ expect(fetchMock).not.toHaveBeenCalled();+ });+ });++ describe('default voice fallback', () => {+ const callDefault = () =>+ createElevenLabsSpeech(+ {+ input: 'Hello',+ model: 'eleven_flash_v2_5',+ voice: ELEVENLABS_DEFAULT_VOICE_ID,+ voiceIsDefault: true,+ },+ options,+ );+ const paymentRequired = () =>+ errorResponse(402, {+ detail: {+ message: 'Free users cannot use library voices via the API.',+ status: 'payment_required',+ },+ });+ const voicesResponse = (voices: unknown[]) =>+ new Response(JSON.stringify({ voices }), { headers: { 'content-type': 'application/json' } });++ it('retries once with an account voice, preferring created voices over premade ones', async () => {+ fetchMock+ .mockResolvedValueOnce(+ errorResponse(404, { detail: { message: 'Voice not found', status: 'voice_not_found' } }),+ )+ // personal: the rejected default is skipped, an owned clone is taken+ .mockResolvedValueOnce(+ voicesResponse([+ { category: 'generated', is_owner: true, voice_id: ELEVENLABS_DEFAULT_VOICE_ID },+ { category: 'professional', is_owner: true, voice_id: 'pvc-1' },+ ]),+ )+ .mockResolvedValueOnce(audioResponse());++ const result = await callDefault();++ expect(result.audio.byteLength).toBe(AUDIO_BYTES.byteLength);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(fetchMock.mock.calls[1][0]).toBe(+ 'https://api.elevenlabs.io/v2/voices?voice_type=personal&page_size=2',+ );+ expect(fetchMock.mock.calls[1][1].headers['xi-api-key']).toBe('xi-test-key');+ expect(fetchMock.mock.calls[2][0]).toContain('/v1/text-to-speech/pvc-1?');+ });++ it('skips Voice Library voices the account does not own, then uses premade ones', async () => {+ fetchMock+ .mockResolvedValueOnce(paymentRequired())+ .mockResolvedValueOnce(+ voicesResponse([{ category: 'professional', is_owner: false, voice_id: 'library-1' }]),+ )+ .mockResolvedValueOnce(voicesResponse([{ category: 'premade', voice_id: 'premade-1' }]))+ .mockResolvedValueOnce(audioResponse());++ await callDefault();++ expect(fetchMock.mock.calls[2][0]).toBe(+ 'https://api.elevenlabs.io/v2/voices?category=premade&page_size=2',+ );+ expect(fetchMock.mock.calls[3][0]).toContain('/v1/text-to-speech/premade-1?');+ });++ it('explains how to pick a voice when the account voices cannot be listed', async () => {+ fetchMock.mockResolvedValueOnce(paymentRequired()).mockResolvedValueOnce(+ errorResponse(401, {+ detail: { message: 'missing voices_read', status: 'missing_permissions' },+ }),+ );++ await expect(callDefault()).rejects.toMatchObject({+ error: { message: expect.stringContaining(ELEVENLABS_NO_ACCOUNT_VOICE_HINT) },+ errorType: AgentRuntimeErrorType.InsufficientQuota,+ });+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('surfaces the retry error when the account voice also fails', async () => {+ fetchMock+ .mockResolvedValueOnce(paymentRequired())+ .mockResolvedValueOnce(+ voicesResponse([{ category: 'cloned', is_owner: true, voice_id: 'clone-1' }]),+ )+ .mockResolvedValueOnce(+ errorResponse(429, { detail: { message: 'busy', status: 'system_busy' } }),+ );++ await expect(callDefault()).rejects.toMatchObject({+ error: { message: 'ElevenLabs API error (429): busy' },+ errorType: AgentRuntimeErrorType.RateLimitExceeded,+ });+ });++ const warmCache = async () => {+ fetchMock+ .mockResolvedValueOnce(paymentRequired())+ .mockResolvedValueOnce(+ voicesResponse([{ category: 'cloned', is_owner: true, voice_id: 'clone-1' }]),+ )+ .mockResolvedValueOnce(audioResponse());+ await callDefault();+ fetchMock.mockClear();+ };++ it('reuses the resolved voice for the same key without retrying the default', async () => {+ await warmCache();++ fetchMock.mockResolvedValueOnce(audioResponse());+ await callDefault();++ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0][0]).toContain('/v1/text-to-speech/clone-1?');++ // A different key does not share the entry.+ fetchMock.mockClear();+ fetchMock.mockResolvedValueOnce(audioResponse());+ await createElevenLabsSpeech(+ {+ input: 'Hello',+ model: 'eleven_flash_v2_5',+ voice: ELEVENLABS_DEFAULT_VOICE_ID,+ voiceIsDefault: true,+ },+ { ...options, apiKey: 'other-key' },+ );+ expect(fetchMock.mock.calls[0][0]).toContain(+ `/v1/text-to-speech/${ELEVENLABS_DEFAULT_VOICE_ID}?`,+ );+ });++ it('drops a cached voice that stops working and starts over from the default', async () => {+ await warmCache();++ fetchMock+ .mockResolvedValueOnce(+ errorResponse(404, { detail: { message: 'Voice not found', status: 'voice_not_found' } }),+ )+ .mockResolvedValueOnce(audioResponse());+ await callDefault();++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls[1][0]).toContain(+ `/v1/text-to-speech/${ELEVENLABS_DEFAULT_VOICE_ID}?`,+ );++ // The default worked, so nothing is cached any more.+ fetchMock.mockClear();+ fetchMock.mockResolvedValueOnce(audioResponse());+ await callDefault();+ expect(fetchMock.mock.calls[0][0]).toContain(+ `/v1/text-to-speech/${ELEVENLABS_DEFAULT_VOICE_ID}?`,+ );+ });++ it('keeps the cache entry on unrelated errors, and expires it after the TTL', async () => {+ await warmCache();++ fetchMock.mockResolvedValueOnce(+ errorResponse(429, { detail: { message: 'busy', status: 'system_busy' } }),+ );+ await expect(callDefault()).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.RateLimitExceeded,+ });+ expect(fetchMock).toHaveBeenCalledTimes(1);++ // Still cached within the TTL: the next request goes straight to the cached voice.+ fetchMock.mockClear();+ fetchMock.mockResolvedValueOnce(audioResponse());+ await callDefault();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(fetchMock.mock.calls[0][0]).toContain('/v1/text-to-speech/clone-1?');++ const now = Date.now();+ vi.spyOn(Date, 'now').mockReturnValue(now + FALLBACK_VOICE_TTL_MS + 1);+ fetchMock.mockClear();+ fetchMock.mockResolvedValueOnce(audioResponse());+ await callDefault();+ expect(fetchMock.mock.calls[0][0]).toContain(+ `/v1/text-to-speech/${ELEVENLABS_DEFAULT_VOICE_ID}?`,+ );+ });++ it('keeps an explicitly requested default voice instead of substituting one', async () => {+ fetchMock.mockResolvedValueOnce(paymentRequired());++ await expect(+ createElevenLabsSpeech(+ { input: 'Hello', model: 'eleven_flash_v2_5', voice: ELEVENLABS_DEFAULT_VOICE_ID },+ options,+ ),+ ).rejects.toMatchObject({ errorType: AgentRuntimeErrorType.InsufficientQuota });+ expect(fetchMock).toHaveBeenCalledTimes(1);++ // Nothing was cached either: an omitted voice still starts from the default.+ fetchMock.mockClear();+ fetchMock.mockResolvedValueOnce(audioResponse());+ await callDefault();+ expect(fetchMock.mock.calls[0][0]).toContain(+ `/v1/text-to-speech/${ELEVENLABS_DEFAULT_VOICE_ID}?`,+ );+ });++ it('treats exhausted credits as a quota error, not an unavailable voice', async () => {+ fetchMock.mockResolvedValueOnce(+ errorResponse(402, {+ detail: {+ code: 'insufficient_credits',+ message: 'You have run out of credits.',+ status: 'payment_required',+ },+ }),+ );++ await expect(callDefault()).rejects.toMatchObject({+ error: { message: 'ElevenLabs API error (402): You have run out of credits.' },+ errorType: AgentRuntimeErrorType.InsufficientQuota,+ });+ // No voice lookup, no retry.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('falls back on a 402 that names the voice even without a known code', async () => {+ fetchMock+ .mockResolvedValueOnce(+ errorResponse(402, {+ detail: { message: 'Free users cannot use library voices via the API.' },+ }),+ )+ .mockResolvedValueOnce(voicesResponse([{ category: 'premade', voice_id: 'premade-1' }]))+ .mockResolvedValueOnce(audioResponse());++ await callDefault();+ expect(fetchMock.mock.calls[2][0]).toContain('/v1/text-to-speech/premade-1?');+ });++ it('does not fall back for an explicitly chosen voice or for other errors', async () => {+ fetchMock.mockResolvedValueOnce(paymentRequired());+ await expect(+ createElevenLabsSpeech(+ { input: 'Hello', model: 'eleven_flash_v2_5', voice: VOICE },+ options,+ ),+ ).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.InsufficientQuota,+ });++ fetchMock.mockResolvedValueOnce(+ errorResponse(401, { detail: { message: 'Invalid API key' } }),+ );+ await expect(callDefault()).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,+ });++ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+ });++ describe('errors', () => {+ const call = () =>+ createElevenLabsSpeech({ input: 'Hi', model: 'eleven_v4', voice: VOICE }, options);++ it('maps 401 invalid_api_key to InvalidProviderAPIKey with a readable message', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(401, {+ detail: { message: 'Invalid API key', status: 'invalid_api_key' },+ }),+ );++ await expect(call()).rejects.toMatchObject({+ error: {+ detail: { message: 'Invalid API key', status: 'invalid_api_key' },+ message: 'ElevenLabs API error (401): Invalid API key',+ status: 401,+ },+ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey,+ provider: 'elevenlabs',+ });+ });++ it('maps a 401 quota_exceeded to InsufficientQuota rather than a bad key', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(401, {+ detail: {+ message: 'This request exceeds your quota of 10000.',+ status: 'quota_exceeded',+ },+ }),+ );++ await expect(call()).rejects.toMatchObject({+ error: { message: 'ElevenLabs API error (401): This request exceeds your quota of 10000.' },+ errorType: AgentRuntimeErrorType.InsufficientQuota,+ });+ });++ it('maps 422 validation errors to ProviderBizError and keeps the field messages', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(422, {+ detail: [{ loc: ['body', 'text'], msg: 'Field required', type: 'missing' }],+ }),+ );++ await expect(call()).rejects.toMatchObject({+ error: { message: 'ElevenLabs API error (422): body.text: Field required', status: 422 },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ });+ });++ it('maps 429 to RateLimitExceeded', async () => {+ fetchMock.mockResolvedValue(+ errorResponse(429, {+ detail: {+ message: 'Too many concurrent requests',+ status: 'too_many_concurrent_requests',+ },+ }),+ );++ await expect(call()).rejects.toMatchObject({+ error: { message: 'ElevenLabs API error (429): Too many concurrent requests' },+ errorType: AgentRuntimeErrorType.RateLimitExceeded,+ });+ });++ it('maps 403 to PermissionDenied and 402 to InsufficientQuota', async () => {+ fetchMock.mockResolvedValueOnce(errorResponse(403, { detail: { message: 'Forbidden' } }));+ await expect(call()).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.PermissionDenied,+ });++ fetchMock.mockResolvedValueOnce(errorResponse(402, { detail: { message: 'Pay up' } }));+ await expect(call()).rejects.toMatchObject({+ errorType: AgentRuntimeErrorType.InsufficientQuota,+ });+ });++ it('adds the paid voice hint when ElevenLabs requires a paid plan', async () => {+ fetchMock.mockResolvedValueOnce(+ errorResponse(402, {+ detail: {+ message: 'Free users cannot use library voices via the API.',+ status: 'payment_required',+ },+ }),+ );++ await expect(call()).rejects.toMatchObject({+ error: {+ message: `ElevenLabs API error (402): Free users cannot use library voices via the API. ${ELEVENLABS_PAID_VOICE_HINT}`,+ },+ errorType: AgentRuntimeErrorType.InsufficientQuota,+ });+ });++ it('keeps a non-JSON error body and falls back to statusText', async () => {+ fetchMock.mockResolvedValueOnce(errorResponse(500, 'upstream exploded'));+ await expect(call()).rejects.toMatchObject({+ error: { message: 'ElevenLabs API error (500): upstream exploded' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ });++ fetchMock.mockResolvedValueOnce(errorResponse(503, '', 'Service Unavailable'));+ await expect(call()).rejects.toMatchObject({+ error: { message: 'ElevenLabs API error (503): Service Unavailable' },+ });+ });++ it('rejects an empty audio body instead of returning silence', async () => {+ fetchMock.mockResolvedValue(new Response(new Uint8Array(), { status: 200 }));+ const onUsage = vi.fn();++ await expect(+ createElevenLabsSpeech(+ { input: 'Hi', model: 'eleven_v4', voice: VOICE },+ { ...options, onUsage },+ ),+ ).rejects.toMatchObject({+ error: { message: 'ElevenLabs returned empty audio' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ });+ expect(onUsage).not.toHaveBeenCalled();+ });++ it('rejects unsupported formats and a missing voice before calling the API', async () => {+ await expect(+ createElevenLabsSpeech(+ { input: 'Hi', model: 'eleven_v4', params: { format: 'aac' }, voice: VOICE },+ options,+ ),+ ).rejects.toMatchObject({+ error: { message: 'ElevenLabs speech does not support the "aac" format' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ });++ await expect(+ createElevenLabsSpeech({ input: 'Hi', model: 'eleven_v4', voice: ' ' }, options),+ ).rejects.toMatchObject({ error: { message: 'ElevenLabs speech requires a voice id' } });++ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('wraps network failures as ProviderBizError', async () => {+ fetchMock.mockRejectedValue(new TypeError('fetch failed'));++ await expect(call()).rejects.toMatchObject({+ error: { message: 'fetch failed' },+ errorType: AgentRuntimeErrorType.ProviderBizError,+ provider: 'elevenlabs',+ });+ });++ it('rethrows AbortError untouched', async () => {+ const abort = Object.assign(new Error('aborted'), { name: 'AbortError' });+ fetchMock.mockRejectedValue(abort);++ await expect(call()).rejects.toBe(abort);+ });+ });+});diff --git a/packages/model-runtime/src/providers/elevenlabs/createSpeech.ts b/packages/model-runtime/src/providers/elevenlabs/createSpeech.tsnew file mode 100644index 00000000000..b69579ac601--- /dev/null+++ b/packages/model-runtime/src/providers/elevenlabs/createSpeech.ts@@ -0,0 +1,536 @@+import { AgentRuntimeErrorType } from '@lobechat/types';+import createDebug from 'debug';+import type { TTSAudioFormat } from 'model-bank';+import {+ DEFAULT_TTS_AUDIO_FORMAT,+ ELEVENLABS_DEFAULT_VOICE_ID,+ ELEVENLABS_VOICE_IDS,+} from 'model-bank';++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:elevenlabs');++export const DEFAULT_ELEVENLABS_BASE_URL = 'https://api.elevenlabs.io';++/**+ * Characters per request. The audio comes back in one inline response, and 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 ELEVENLABS_MAX_INPUT_CHARACTERS = 4096;++export interface ElevenLabsSpeechOptions extends ModelIdMappingOptions, TextToSpeechOptions {+ apiKey: string;+ /** API host, e.g. `https://api.elevenlabs.io` or a data-residency host. */+ baseURL: string;+ /** Provider id used for pricing lookup and error payloads. */+ provider: string;+}++/**+ * `output_format` sent for each standard format. Formats with several sample rates take+ * `params.sampleRate` when it is one ElevenLabs offers; there is no `aac` or `flac` output.+ * @see https://elevenlabs.io/docs/api-reference/text-to-speech/convert+ */+const ELEVENLABS_OUTPUT_FORMATS: Partial<+ Record<TTSAudioFormat, { default: string; sampleRates?: Record<number, string> }>+> = {+ mp3: {+ default: 'mp3_44100_128',+ sampleRates: { 22_050: 'mp3_22050_32', 24_000: 'mp3_24000_48' },+ },+ opus: { default: 'opus_48000_128' },+ pcm: {+ default: 'pcm_24000',+ sampleRates: {+ 8000: 'pcm_8000',+ 16_000: 'pcm_16000',+ 22_050: 'pcm_22050',+ 24_000: 'pcm_24000',+ 44_100: 'pcm_44100',+ 48_000: 'pcm_48000',+ },+ },+ wav: {+ default: 'wav_44100',+ sampleRates: {+ 8000: 'wav_8000',+ 16_000: 'wav_16000',+ 22_050: 'wav_22050',+ 24_000: 'wav_24000',+ 44_100: 'wav_44100',+ 48_000: 'wav_48000',+ },+ },+};++const HTTP_ERROR_TYPES: Record<number, ILobeAgentRuntimeErrorType> = {+ 401: AgentRuntimeErrorType.InvalidProviderAPIKey,+ 402: AgentRuntimeErrorType.InsufficientQuota,+ 403: AgentRuntimeErrorType.PermissionDenied,+ 429: AgentRuntimeErrorType.RateLimitExceeded,+};++/**+ * `detail.status` values that override the HTTP status mapping, e.g. an exhausted quota+ * comes back as a 401 but is not a bad key.+ * @see https://elevenlabs.io/docs/developers/resources/errors+ */+const DETAIL_STATUS_ERROR_TYPES: Record<string, ILobeAgentRuntimeErrorType> = {+ concurrent_limit_exceeded: AgentRuntimeErrorType.RateLimitExceeded,+ insufficient_credits: AgentRuntimeErrorType.InsufficientQuota,+ invalid_api_key: AgentRuntimeErrorType.InvalidProviderAPIKey,+ missing_permissions: AgentRuntimeErrorType.PermissionDenied,+ payment_required: AgentRuntimeErrorType.InsufficientQuota,+ quota_exceeded: AgentRuntimeErrorType.InsufficientQuota,+ rate_limit_exceeded: AgentRuntimeErrorType.RateLimitExceeded,+ system_busy: AgentRuntimeErrorType.RateLimitExceeded,+ too_many_concurrent_requests: AgentRuntimeErrorType.RateLimitExceeded,+};++/**+ * Free-tier keys cannot use Voice Library voices through the API, and every built-in+ * voice except the default (Roger) comes from the Voice Library.+ * @see https://elevenlabs.io/docs/eleven-creative/voices/voice-library+ */+export const ELEVENLABS_NO_ACCOUNT_VOICE_HINT =+ 'The default voice is not available to this ElevenLabs account and no usable voice was found in it (the key needs the voices_read permission to look one up): pass a voice you own with --voice.';++export const ELEVENLABS_PAID_VOICE_HINT =+ 'Free-tier ElevenLabs keys cannot use Voice Library voices (such as Talia) through the API: upgrade the plan, or pass the default voice or a voice you own with --voice.';++/** Thrown inside the request flow and unwrapped into a runtime error payload. */+class ElevenLabsSpeechError extends Error {+ constructor(+ message: string,+ readonly errorType: ILobeAgentRuntimeErrorType,+ readonly detail?: Record<string, unknown>,+ /** The request failed because of the voice, so another voice might succeed. */+ readonly voiceUnavailable = false,+ ) {+ 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 normalizeElevenLabsBaseURL = (baseURL?: string | null) => {+ const url = trimTrailing(baseURL?.trim() || DEFAULT_ELEVENLABS_BASE_URL, '/');+ return url.endsWith('/v1') ? url.slice(0, -3) : url;+};++export const resolveElevenLabsOutputFormat = (+ format: TTSAudioFormat,+ sampleRate?: number,+): string => {+ const entry = ELEVENLABS_OUTPUT_FORMATS[format];++ if (!entry) {+ throw new ElevenLabsSpeechError(+ `ElevenLabs speech does not support the "${format}" format`,+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ return (sampleRate !== undefined && entry.sampleRates?.[sampleRate]) || entry.default;+};++/**+ * Map the standard TTS payload onto a Create speech request. `voice_settings` is only sent+ * when the caller set something, so the voice keeps its own saved settings otherwise.+ */+export const buildElevenLabsSpeechRequest = (+ payload: TextToSpeechPayload,+ requestModel: string,+): { body: Record<string, unknown>; format: TTSAudioFormat; outputFormat: string } => {+ if (!payload.voice?.trim()) {+ throw new ElevenLabsSpeechError(+ 'ElevenLabs speech requires a voice id',+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ const params = resolveTextToSpeechParams(payload);+ const format = params.format ?? DEFAULT_TTS_AUDIO_FORMAT;+ const outputFormat = resolveElevenLabsOutputFormat(format, params.sampleRate);++ return {+ body: {+ model_id: requestModel,+ text: payload.input,+ ...(params.speed !== undefined && { voice_settings: { speed: params.speed } }),+ },+ format,+ outputFormat,+ };+};++interface ElevenLabsErrorDetail {+ code?: string;+ message?: string;+ status?: string;+}++interface ElevenLabsErrorBody {+ detail?: ElevenLabsErrorDetail | { loc?: unknown[]; msg?: string; type?: string }[] | string;+}++const readErrorBody = async (response: Response): Promise<ElevenLabsErrorBody | undefined> => {+ const text = await response.text().catch(() => '');+ if (!text) return;++ try {+ return JSON.parse(text) as ElevenLabsErrorBody;+ } catch {+ return { detail: text };+ }+};++/** Readable message and `detail.status` from the error shapes ElevenLabs returns. */+const parseErrorDetail = (+ body?: ElevenLabsErrorBody,+): { codes: string[]; message?: string; status?: string } => {+ const detail = body?.detail;+ if (!detail) return { codes: [] };+ if (typeof detail === 'string') return { codes: [], message: detail };++ // 422 validation errors are FastAPI-style `[{ loc, msg, type }]`+ if (Array.isArray(detail)) {+ const message = detail+ .map((item) => {+ const loc = Array.isArray(item.loc) ? item.loc.join('.') : undefined;+ return loc ? `${loc}: ${item.msg}` : item.msg;+ })+ .filter(Boolean)+ .join('; ');++ return { codes: [], message: message || undefined };+ }++ return {+ codes: [detail.status, detail.code].filter((value): value is string => !!value),+ message: detail.message,+ status: detail.status ?? detail.code,+ };+};++/** Turn a failed Create speech response into a typed error with a readable message. */+/** Codes ElevenLabs uses when the account may not use the requested voice. */+const VOICE_UNAVAILABLE_CODES = new Set([+ 'paid_plan_required',+ 'payment_required',+ 'voice_does_not_exist',+ 'voice_not_found',+]);++/** Account-level billing failures: no other voice would help. */+const QUOTA_CODES = new Set(['insufficient_credits', 'quota_exceeded']);++/**+ * Whether a failed request was about the voice rather than the account: 404 or a+ * voice/plan code, or a 402 whose message names the voice (free keys calling Voice Library+ * voices). Credit and quota exhaustion are never voice failures.+ * @see https://elevenlabs.io/docs/eleven-api/resources/errors+ */+const classifyVoiceError = (httpStatus: number, codes: string[], message?: string) => {+ if (codes.some((code) => QUOTA_CODES.has(code))) return { paidVoice: false, unavailable: false };++ const paidVoice =+ codes.some((code) => code === 'payment_required' || code === 'paid_plan_required') ||+ (httpStatus === 402 && /voice/i.test(message ?? ''));++ return {+ paidVoice,+ unavailable:+ paidVoice || httpStatus === 404 || codes.some((code) => VOICE_UNAVAILABLE_CODES.has(code)),+ };+};++/** Turn a failed Create speech response into a typed error with a readable message. */+const toSpeechError = async (response: Response): Promise<ElevenLabsSpeechError> => {+ const errorBody = await readErrorBody(response);+ const { codes, message } = parseErrorDetail(errorBody);+ const { paidVoice, unavailable } = classifyVoiceError(response.status, codes, message);+ const reason = message || response.statusText || 'request failed';++ return new ElevenLabsSpeechError(+ paidVoice+ ? `ElevenLabs API error (${response.status}): ${trimTrailing(reason, '.')}. ${ELEVENLABS_PAID_VOICE_HINT}`+ : `ElevenLabs API error (${response.status}): ${reason}`,+ codes.map((code) => DETAIL_STATUS_ERROR_TYPES[code]).find(Boolean) ??+ HTTP_ERROR_TYPES[response.status] ??+ AgentRuntimeErrorType.ProviderBizError,+ { detail: errorBody?.detail, status: response.status },+ unavailable,+ );+};++const isVoiceUnavailable = (error: ElevenLabsSpeechError) => error.voiceUnavailable;++/**+ * Queries for a voice the account can always call, best first: voices it created+ * (`voice_type=personal`: instant and professional clones and designed voices), then the+ * premade ones it still has. Voice Library voices saved to the account are also+ * `professional` but not owned, and need a paid plan on the API, so they are skipped.+ * @see https://elevenlabs.io/docs/api-reference/voices/search+ */+const ACCOUNT_VOICE_QUERIES: Record<string, string>[] = [+ { voice_type: 'personal' },+ { category: 'premade' },+];++/**+ * First voice in the account that it can call, from the paginated `GET /v2/voices` (the+ * legacy `GET /v1/voices` stops working past 500 voices). Two results per query are enough+ * to skip the rejected default. Returns undefined when the key lacks `voices_read` or the+ * account has no such voice.+ */+export const resolveAccountVoice = async (+ baseURL: string,+ apiKey: string,+ options: Pick<ElevenLabsSpeechOptions, 'headers' | 'signal'>,+): Promise<string | undefined> => {+ for (const query of ACCOUNT_VOICE_QUERIES) {+ try {+ const url = new URL(`${baseURL}/v2/voices`);+ for (const [key, value] of Object.entries(query)) url.searchParams.set(key, value);+ url.searchParams.set('page_size', '2');++ const response = await fetch(url.toString(), {+ headers: { ...options.headers, 'xi-api-key': apiKey },+ signal: options.signal,+ });+ if (!response.ok) {+ log('list voices %o failed: %d', query, response.status);+ // A missing permission or bad key fails every query the same way.+ return;+ }++ const { voices = [] } = (await response.json()) as {+ voices?: { is_owner?: boolean; voice_id?: string }[];+ };+ const voice = voices.find(+ (item) =>+ item.voice_id &&+ item.voice_id !== ELEVENLABS_DEFAULT_VOICE_ID &&+ // Owned voices only from the personal query; premade voices report no owner.+ (query.voice_type !== 'personal' || item.is_owner !== false),+ );+ if (voice?.voice_id) return voice.voice_id;+ } catch (error) {+ if ((error as Error)?.name === 'AbortError') throw error;+ log('list voices %o error: %O', query, error);+ return;+ }+ }+};++/** How long an account fallback voice is reused before it is looked up again. */+export const FALLBACK_VOICE_TTL_MS = 60 * 60 * 1000;+const FALLBACK_VOICE_CACHE_LIMIT = 500;++/**+ * Account fallback voice per host + key (stored by SHA-256, never the key itself), so an+ * account that cannot use the default skips the rejected request and the voice lookup.+ * Per process: each serverless instance warms its own entry.+ */+const fallbackVoices = new Map<string, { expiresAt: number; voice: string }>();++const fallbackCacheKey = async (baseURL: string, apiKey: string) => {+ const digest = await crypto.subtle.digest(+ 'SHA-256',+ new TextEncoder().encode(`${baseURL}\n${apiKey}`),+ );+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');+};++const readFallbackVoice = (key: string) => {+ const entry = fallbackVoices.get(key);+ if (!entry) return;+ if (entry.expiresAt <= Date.now()) {+ fallbackVoices.delete(key);+ return;+ }+ return entry.voice;+};++const writeFallbackVoice = (key: string, voice: string) => {+ fallbackVoices.delete(key);+ if (fallbackVoices.size >= FALLBACK_VOICE_CACHE_LIMIT) {+ // Maps iterate in insertion order: drop the oldest entry.+ fallbackVoices.delete(fallbackVoices.keys().next().value!);+ }+ fallbackVoices.set(key, { expiresAt: Date.now() + FALLBACK_VOICE_TTL_MS, voice });+};++/** Test helper: forget every cached fallback voice. */+export const clearElevenLabsFallbackVoices = () => fallbackVoices.clear();++/**+ * Synthesize speech with ElevenLabs' `POST /v1/text-to-speech/{voice_id}`, which returns+ * the audio bytes directly. Usage is the input character count, which is what the+ * per-character API price applies to. The `character-cost` response header is logged but+ * not used: it reports plan credits (e.g. 7 for a 34-character Flash request, 14 on+ * Multilingual v2), not characters.+ * @see https://elevenlabs.io/docs/api-reference/text-to-speech/convert+ */+export async function createElevenLabsSpeech(+ request: TextToSpeechPayload,+ options: ElevenLabsSpeechOptions,+): Promise<TextToSpeechResponse> {+ const { apiKey, provider } = options;+ const baseURL = normalizeElevenLabsBaseURL(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 ElevenLabs default instead.+ const payload: TextToSpeechPayload =+ request.voiceIsDefault && !ELEVENLABS_VOICE_IDS.has(request.voice)+ ? { ...request, voice: ELEVENLABS_DEFAULT_VOICE_ID }+ : request;+ const requestModel = resolveMappedModelId(payload.model, options);++ let result: TextToSpeechResponse;+ try {+ const inputCharacters = countTextToSpeechCharacters(payload.input);+ if (inputCharacters > ELEVENLABS_MAX_INPUT_CHARACTERS) {+ throw new ElevenLabsSpeechError(+ `ElevenLabs speech input is ${inputCharacters} characters; the limit is ${ELEVENLABS_MAX_INPUT_CHARACTERS} per request. Split the text into shorter requests.`,+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ const { body, format, outputFormat } = buildElevenLabsSpeechRequest(payload, requestModel);+ const pricing = await getModelPricing(payload.model, provider, options.pricingContext);++ const send = (voice: string) => {+ const url = new URL(`${baseURL}/v1/text-to-speech/${encodeURIComponent(voice)}`);+ url.searchParams.set('output_format', outputFormat);++ log(+ 'text-to-speech request: model=%s voice=%s output_format=%s',+ requestModel,+ voice,+ outputFormat,+ );++ return fetch(url.toString(), {+ body: JSON.stringify(body),+ headers: {+ ...options.headers,+ 'Accept': 'audio/*',+ 'Content-Type': 'application/json',+ 'xi-api-key': apiKey,+ },+ method: 'POST',+ signal: options.signal,+ });+ };++ // Only a voice the service filled in from the card may be swapped; a caller that asked+ // for the default voice by id gets that voice or its error.+ const fallbackKey =+ payload.voiceIsDefault && payload.voice === ELEVENLABS_DEFAULT_VOICE_ID+ ? await fallbackCacheKey(baseURL, apiKey)+ : undefined;+ const cachedVoice = fallbackKey ? readFallbackVoice(fallbackKey) : undefined;++ let response = await send(cachedVoice ?? payload.voice);++ // A cached fallback voice that stops working (deleted, plan change) is dropped, and+ // the request starts over from the default voice.+ if (!response.ok && cachedVoice) {+ const error = await toSpeechError(response);+ // Transient failures (429, 5xx) keep the entry: the cached voice is still valid.+ if (!isVoiceUnavailable(error)) throw error;+ fallbackVoices.delete(fallbackKey!);+ response = await send(payload.voice);+ }++ if (!response.ok) {+ const error = await toSpeechError(response);++ // The built-in default voice is not callable on every account (free tier, or+ // accounts created after the Default voices were withdrawn): retry once with a+ // voice the account can use, and remember it. A rejected request is not billed.+ if (!fallbackKey || !isVoiceUnavailable(error)) throw error;++ const fallback = await resolveAccountVoice(baseURL, apiKey, options);+ if (!fallback) {+ throw new ElevenLabsSpeechError(+ `${trimTrailing(error.message, '.')}. ${ELEVENLABS_NO_ACCOUNT_VOICE_HINT}`,+ error.errorType,+ error.detail,+ );+ }++ log('default voice unavailable, retrying with account voice %s', fallback);+ response = await send(fallback);+ if (!response.ok) throw await toSpeechError(response);+ writeFallbackVoice(fallbackKey, fallback);+ }++ const audio = await response.arrayBuffer();++ if (audio.byteLength === 0) {+ throw new ElevenLabsSpeechError(+ 'ElevenLabs returned empty audio',+ AgentRuntimeErrorType.ProviderBizError,+ );+ }++ log(+ 'text-to-speech done: %d bytes, character-cost=%s, request-id=%s',+ audio.byteLength,+ response.headers.get('character-cost'),+ response.headers.get('request-id'),+ );++ const usage = convertTextToSpeechUsage(payload.input, pricing);++ result = { audio, format, usage };+ } catch (error) {+ log('createElevenLabsSpeech error: %O', error);++ if ((error as Error)?.name === 'AbortError') throw error;++ const errorType =+ error instanceof ElevenLabsSpeechError+ ? error.errorType+ : AgentRuntimeErrorType.ProviderBizError;++ throw AgentRuntimeError.chat({+ error: {+ message: (error as Error)?.message ?? String(error),+ ...(error instanceof ElevenLabsSpeechError ? error.detail : undefined),+ },+ errorType,+ provider,+ } satisfies ChatCompletionErrorPayload);+ }++ await options.onUsage?.(result.usage!);++ return result;+}diff --git a/packages/model-runtime/src/providers/elevenlabs/index.test.ts b/packages/model-runtime/src/providers/elevenlabs/index.test.tsnew file mode 100644index 00000000000..570c4815c05--- /dev/null+++ b/packages/model-runtime/src/providers/elevenlabs/index.test.ts@@ -0,0 +1,155 @@+// @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 { LobeElevenLabsAI } from './index';++vi.mock('../../utils/getModelPricing', () => ({ getModelPricing: vi.fn() }));++const VOICE = 'OZ0L6eISlOejga3XjDFt';++describe('LobeElevenLabsAI', () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ fetchMock = vi.fn(+ async () =>+ new Response(new Uint8Array([1, 2, 3]), {+ headers: { 'content-type': 'audio/mpeg', 'character-cost': '2' },+ }),+ );+ vi.stubGlobal('fetch', fetchMock);+ vi.mocked(getModelPricing).mockResolvedValue({+ units: [{ name: 'textInput', rate: 40, strategy: 'fixed', unit: 'millionCharacters' }],+ });+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.clearAllMocks();+ });++ describe('constructor', () => {+ it.each([undefined, '', ' '])(+ 'throws InvalidProviderAPIKey when the API key is %j',+ (apiKey) => {+ expect(() => new LobeElevenLabsAI({ apiKey })).toThrow(+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),+ );+ },+ );++ it('throws InvalidProviderAPIKey when constructed with no options', () => {+ expect(() => new LobeElevenLabsAI()).toThrow(+ expect.objectContaining({ errorType: AgentRuntimeErrorType.InvalidProviderAPIKey }),+ );+ });++ it('defaults to the global API host and accepts an override', () => {+ expect(new LobeElevenLabsAI({ apiKey: 'k' }).baseURL).toBe('https://api.elevenlabs.io');+ expect(+ new LobeElevenLabsAI({ apiKey: 'k', baseURL: 'https://api.eu.residency.elevenlabs.io/' })+ .baseURL,+ ).toBe('https://api.eu.residency.elevenlabs.io');+ });+ });++ it('synthesizes through the configured host with the trimmed key', async () => {+ const runtime = new LobeElevenLabsAI({+ apiKey: ' xi-key ',+ baseURL: 'https://proxy.example.com',+ });++ const result = await runtime.textToSpeech({+ input: 'Hello',+ model: 'eleven_flash_v2_5',+ voice: VOICE,+ });++ const [url, init] = fetchMock.mock.calls[0] as any;+ expect(url).toBe(+ `https://proxy.example.com/v1/text-to-speech/${VOICE}?output_format=mp3_44100_128`,+ );+ expect(init.headers['xi-api-key']).toBe('xi-key');+ expect(result.format).toBe('mp3');+ expect(result.usage).toEqual({ cost: 0.0002, inputCharacters: 5 });+ });++ it('uses its provider id for pricing and errors, overridable for custom providers', async () => {+ await new LobeElevenLabsAI({ apiKey: 'k', id: 'my-elevenlabs' }).textToSpeech({+ input: 'Hi',+ model: 'eleven_v4',+ voice: VOICE,+ });++ expect(getModelPricing).toHaveBeenCalledWith('eleven_v4', 'my-elevenlabs', undefined);+ });++ describe('via ModelRuntime', () => {+ it("is registered in the runtime map under 'elevenlabs'", () => {+ expect(providerRuntimeMap.elevenlabs).toBe(LobeElevenLabsAI);+ });++ it("initializes from the provider id 'elevenlabs' instead of falling back to OpenAI", () => {+ const runtime = ModelRuntime.initializeWithProvider('elevenlabs', { apiKey: 'xi-key' });++ expect(runtime['_runtime']).toBeInstanceOf(LobeElevenLabsAI);+ });++ it('rejects initialization without an API key', () => {+ expect(() => ModelRuntime.initializeWithProvider('elevenlabs', {})).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(+ 'elevenlabs',+ { apiKey: 'xi-key' },+ { onTextToSpeechFinal },+ );++ const result = await runtime.textToSpeech(+ { input: 'Hello', model: 'eleven_flash_v2_5', params: { format: 'opus' }, voice: VOICE },+ { metadata: { trigger: 'tts' } },+ );++ expect(new Uint8Array(result!.audio)).toEqual(new Uint8Array([1, 2, 3]));+ expect(result!.format).toBe('opus');+ expect(fetchMock.mock.calls[0][0]).toContain('output_format=opus_48000_128');+ expect(onTextToSpeechFinal).toHaveBeenCalledWith(+ expect.objectContaining({ usage: { cost: 0.0002, inputCharacters: 5 } }),+ expect.anything(),+ );+ });++ it('surfaces upstream errors through the error hook instead of failing silently', async () => {+ fetchMock.mockResolvedValueOnce(+ new Response(+ JSON.stringify({ detail: { message: 'Invalid API key', status: 'invalid_api_key' } }),+ {+ status: 401,+ },+ ),+ );+ const onTextToSpeechError = vi.fn();+ const runtime = ModelRuntime.initializeWithProvider(+ 'elevenlabs',+ { apiKey: 'bad' },+ { onTextToSpeechError },+ );++ await expect(+ runtime.textToSpeech({ input: 'Hi', model: 'eleven_v4', 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/elevenlabs/index.ts b/packages/model-runtime/src/providers/elevenlabs/index.tsnew file mode 100644index 00000000000..62a130d8150--- /dev/null+++ b/packages/model-runtime/src/providers/elevenlabs/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 { createElevenLabsSpeech, normalizeElevenLabsBaseURL } from './createSpeech';++export interface LobeElevenLabsAIParams extends ModelIdMappingOptions {+ apiKey?: string;+ baseURL?: string | null;+ /** Provider id for pricing and error payloads; custom providers pass their own id. */+ id?: string;+}++/**+ * ElevenLabs is text-to-speech only, so the runtime implements `textToSpeech` alone; chat,+ * image and other calls resolve to `undefined` through `ModelRuntime`.+ */+export class LobeElevenLabsAI implements LobeRuntimeAI {+ baseURL: string;+ private apiKey: string;+ private id: string;+ private modelIdMapping?: ModelIdMappingOptions['modelIdMapping'];++ constructor({ apiKey, baseURL, id, modelIdMapping }: LobeElevenLabsAIParams = {}) {+ if (!apiKey?.trim())+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.InvalidProviderAPIKey);++ this.apiKey = apiKey.trim();+ this.baseURL = normalizeElevenLabsBaseURL(baseURL);+ this.id = id || ModelProvider.ElevenLabs;+ this.modelIdMapping = modelIdMapping;+ }++ textToSpeech(payload: TextToSpeechPayload, options?: TextToSpeechOptions) {+ return createElevenLabsSpeech(payload, {+ ...options,+ apiKey: this.apiKey,+ baseURL: this.baseURL,+ modelIdMapping: this.modelIdMapping,+ provider: this.id,+ });+ }+}++export default LobeElevenLabsAI;diff --git a/packages/model-runtime/src/runtimeMap.ts b/packages/model-runtime/src/runtimeMap.tsindex c4b9d0a1a6c..b8ed245f40b 100644--- a/packages/model-runtime/src/runtimeMap.ts+++ b/packages/model-runtime/src/runtimeMap.ts@@ -18,6 +18,7 @@ import { LobeCohereAI } from './providers/cohere';import { LobeCometAPIAI } from './providers/cometapi';import { LobeComfyUI } from './providers/comfyui';import { LobeDeepSeekAI } from './providers/deepseek';+import { LobeElevenLabsAI } from './providers/elevenlabs';import { LobeFalAI } from './providers/fal';import { LobeFireworksAI } from './providers/fireworksai';import { LobeGiteeAI } from './providers/giteeai';@@ -107,6 +108,7 @@ export const providerRuntimeMap = {cometapi: LobeCometAPIAI,comfyui: LobeComfyUI,deepseek: LobeDeepSeekAI,+ elevenlabs: LobeElevenLabsAI,fal: LobeFalAI,fireworksai: LobeFireworksAI,giteeai: LobeGiteeAI,diff --git a/packages/model-runtime/src/types/tts.ts b/packages/model-runtime/src/types/tts.tsindex 12f69edbcd9..a6913044879 100644--- a/packages/model-runtime/src/types/tts.ts+++ b/packages/model-runtime/src/types/tts.ts@@ -17,6 +17,11 @@ export interface TextToSpeechPayload {*/speed?: number;voice: string;+ /**+ * True when the caller gave no voice and `voice` is the model card default. Providers+ * may then substitute a voice the account can use; an explicit voice is never replaced.+ */+ voiceIsDefault?: boolean;}export interface TextToSpeechOptions {diff --git a/packages/openapi/src/controllers/audio.controller.test.ts b/packages/openapi/src/controllers/audio.controller.test.tsindex cc3354f1e26..cfe7454f092 100644--- a/packages/openapi/src/controllers/audio.controller.test.ts+++ b/packages/openapi/src/controllers/audio.controller.test.ts@@ -162,6 +162,44 @@ describe('AudioController.handleSpeech', () => {});});+ it('passes an ElevenLabs request through with its voice, model and format', async () => {+ const res = await speech({+ input: 'Hello',+ model: 'eleven_multilingual_v2',+ provider: 'elevenlabs',+ response_format: 'opus',+ speed: 1.1,+ voice: 'gOupLcAkjEnguROwi4oS',+ });++ expect(res.status).toBe(200);+ expect(res.headers.get('X-LobeHub-Provider')).toBe('elevenlabs');+ expect(synthesizeMock).toHaveBeenCalledWith({+ input: 'Hello',+ model: 'eleven_multilingual_v2',+ params: { format: 'opus', speed: 1.1 },+ provider: 'elevenlabs',+ voice: 'gOupLcAkjEnguROwi4oS',+ });+ });++ it('reports a missing ElevenLabs key as a readable 502, not a silent 500', async () => {+ synthesizeMock.mockRejectedValue(+ new TTSProviderError(+ 'ElevenLabs API Key is incorrect or empty, please check your ElevenLabs API Key and try again. Set it in Settings → AI Providers → ElevenLabs, or in the server environment.',+ 'InvalidProviderAPIKey',+ ),+ );++ const res = await speech({ input: 'hi', model: 'eleven_v4', provider: 'elevenlabs' });++ expect(res.status).toBe(502);+ expect((await res.json()).error).toMatchObject({+ code: 'InvalidProviderAPIKey',+ message: expect.stringContaining('ElevenLabs API Key is incorrect or empty'),+ });+ });+it('surfaces upstream failures as 502 with a readable message', async () => {synthesizeMock.mockRejectedValue(new TTSProviderError('voice id not exist', 'ProviderBizError'),diff --git a/src/components/LobeIcons/index.tsx b/src/components/LobeIcons/index.tsxindex af0a37e59d5..b578dd7a4ea 100644--- a/src/components/LobeIcons/index.tsx+++ b/src/components/LobeIcons/index.tsx@@ -11,8 +11,12 @@ import { lazy, Suspense } from 'react';// The catalog-backed features of @lobehub/icons statically import every brand// icon (~3 MB). Mounting them through lazy() keeps that catalog in one shared// chunk that loads after paint instead of inside each route's closure.-const LazyModelIcon = lazy(() => import('@lobehub/icons/es/features/ModelIcon'));-const LazyModelTag = lazy(() => import('@lobehub/icons/es/features/ModelTag'));+const LazyModelIcon = lazy(() =>+ import('@/libs/modelIcon').then(({ ModelIcon }) => ({ default: ModelIcon })),+);+const LazyModelTag = lazy(() =>+ import('@/libs/modelIcon').then(({ ModelTag }) => ({ default: ModelTag })),+);const LazyProviderIcon = lazy(() =>import('@/libs/providerIcon').then(({ ProviderIcon }) => ({ default: ProviderIcon })),);diff --git a/src/libs/lobeIconMappings.ts b/src/libs/lobeIconMappings.tsnew file mode 100644index 00000000000..c2f153816f3--- /dev/null+++ b/src/libs/lobeIconMappings.ts@@ -0,0 +1,37 @@+import { ElevenLabs, 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+ * 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' },+];++/** `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' },+];++let registered = false;++export const registerLocalIconMappings = () => {+ if (registered) return;+ registered = true;++ for (const { probe, ...mapping } of LOCAL_PROVIDER_MAPPINGS) {+ const mapped = providerMappings.some((item) =>+ item.keywords.some((keyword) => keyword.toLowerCase() === probe),+ );+ if (!mapped) providerMappings.push(mapping);+ }++ for (const { probe, ...mapping } of LOCAL_MODEL_MAPPINGS) {+ const mapped = modelMappings.some((item) =>+ item.keywords.some((keyword) => new RegExp(keyword, 'i').test(probe)),+ );+ if (!mapped) modelMappings.push(mapping);+ }+};diff --git a/src/libs/modelIcon.test.ts b/src/libs/modelIcon.test.tsnew file mode 100644index 00000000000..454d90002fd--- /dev/null+++ b/src/libs/modelIcon.test.ts@@ -0,0 +1,41 @@+import { createElement } from 'react';+import { renderToStaticMarkup } from 'react-dom/server';+import { describe, expect, it } from 'vitest';++import { registerLocalIconMappings } from './lobeIconMappings';+import { ModelIcon } from './modelIcon';+import { ProviderIcon } from './providerIcon';++describe('local icon mappings', () => {+ it.each(['eleven_v4', 'eleven_multilingual_v2', 'eleven_flash_v2_5', 'eleven_turbo_v2_5'])(+ 'renders the ElevenLabs avatar for the %s model',+ (model) => {+ const avatar = renderToStaticMarkup(createElement(ModelIcon, { model, type: 'avatar' }));++ expect(avatar).toContain('<title>ElevenLabs</title>');+ },+ );++ it('leaves models of other vendors alone', () => {+ const avatar = renderToStaticMarkup(+ createElement(ModelIcon, { model: 'speech-2.8-hd', type: 'avatar' }),+ );++ expect(avatar).not.toContain('ElevenLabs');+ });++ it('registers each mapping once however often it runs', async () => {+ const { modelMappings, providerMappings } = await import('@lobehub/icons');+ const count = () =>+ providerMappings.filter((item) => item.keywords.includes('elevenlabs')).length ++ modelMappings.filter((item) => item.keywords.includes('^eleven_')).length;++ registerLocalIconMappings();+ registerLocalIconMappings();++ expect(count()).toBe(2);+ expect(+ renderToStaticMarkup(createElement(ProviderIcon, { provider: 'elevenlabs', type: 'mono' })),+ ).toContain('<title>ElevenLabs</title>');+ });+});diff --git a/src/libs/modelIcon.ts b/src/libs/modelIcon.tsnew file mode 100644index 00000000000..92cb1e5b5d3--- /dev/null+++ b/src/libs/modelIcon.ts@@ -0,0 +1,10 @@+import LobeModelIcon from '@lobehub/icons/es/features/ModelIcon';+import LobeModelTag from '@lobehub/icons/es/features/ModelTag';++import { registerLocalIconMappings } from './lobeIconMappings';++registerLocalIconMappings();++// Plain `export const` on purpose, for the same rolldown reason as ./providerIcon.+export const ModelIcon = LobeModelIcon;+export const ModelTag = LobeModelTag;diff --git a/src/libs/providerIcon.test.ts b/src/libs/providerIcon.test.tsindex 51d259a1fe5..5a24b05fec3 100644--- a/src/libs/providerIcon.test.ts+++ b/src/libs/providerIcon.test.ts@@ -20,4 +20,21 @@ describe('provider artwork', () => {expect(wordmark).not.toContain('lucide-provider');expect((wordmark.match(/<svg /g) || []).length).toBe(2);});++ // Mapped locally until @lobehub/icons maps the id (see ./lobeIconMappings).+ it.each(['elevenlabs', 'ElevenLabs'])(+ 'renders the official %s avatar and wordmark',+ (provider) => {+ const avatar = renderToStaticMarkup(+ createElement(ProviderIcon, { provider, type: 'avatar' }),+ );+ const wordmark = renderToStaticMarkup(createElement(ProviderCombine, { provider }));++ expect(avatar).toContain('<title>ElevenLabs</title>');+ expect(avatar).not.toContain('lucide-provider');+ // The brand's combined artwork is the wordmark alone.+ expect(wordmark).toContain('<title>ElevenLabs</title>');+ expect(wordmark).not.toContain('lucide-provider');+ },+ );});diff --git a/src/libs/providerIcon.ts b/src/libs/providerIcon.tsindex be0880353bb..d358538f164 100644--- a/src/libs/providerIcon.ts+++ b/src/libs/providerIcon.ts@@ -3,7 +3,11 @@ import {ProviderCombine as LobeProviderCombine,ProviderIcon as LobeProviderIcon,} from '@lobehub/icons';+/* eslint-enable no-restricted-imports */+import { registerLocalIconMappings } from './lobeIconMappings';++registerLocalIconMappings();// Do not turn these back into `export { ... }` re-exports: with rolldown's// strictExecutionOrder (rolldown 1.2.12) the icon modules' init wrappers are