Providers
ElevenLabs
ElevenLabs through the cache: in a LiveKit agent with our plugin or LiveKit's ElevenLabs plugin, or with ElevenLabs' own WebSockets, REST and voices APIs and the ElevenLabs SDK, changing only the URL and key.
With our LiveKit plugin#
ElevenLabs, with every setting of ElevenLabs' own LiveKit plugin. eleven_v3 and eleven_v4 models go through ElevenLabs' text-to-dialogue API, as that plugin sends them.
pip install livekit-plugins-tts-cache-routerfrom livekit.plugins import tts_cache_router as tcr# The API key comes from TTS_CACHE_ROUTER_API_KEY.tts = tcr.TTS( model="elevenlabs/eleven_flash_v2_5", voice="JBFqnCBsd6RMkjVDRZzb",)Pass tts to AgentSession(tts=tts). Set TTS_CACHE_ROUTER_API_KEY in the agent’s environment, and store your ElevenLabs key under Provider keys. TTS’s own arguments are on the plugin’s page.
Options#
tcr.TTS(...)’s settings for ElevenLabs, in the router’s names: model, voice, language and speed as arguments, and the rest in the options dict (options={"name": value}). The router checks them; the languages per model are in Models and options.
modelstringRequiredOne of elevenlabs/eleven_flash_v2_5, elevenlabs/eleven_turbo_v2_5, elevenlabs/eleven_multilingual_v2, elevenlabs/eleven_flash_v2, elevenlabs/eleven_turbo_v2, elevenlabs/eleven_v3, elevenlabs/eleven_v3_conversational, elevenlabs/eleven_v4, elevenlabs/eleven_v4_turbo
Which model synthesizes the replies, with its provider.voicestringRequired- A voice of the chosen model, passed to ElevenLabs as given. See models and voices.
languagestring | nullOptional- A ElevenLabs language code from languages, passed through as given. Leave it out and ElevenLabs detects the language.
sample_rateintDefault24000One of 8000, 16000, 22050, 24000, 32000, 44100, 48000
Of the audio you receive, in Hz.options.voice_settingsobject | nullDefaultnull- Any of stability, similarity_boost and style (0–1), speed (0.7–1.2) and use_speaker_boost; one left out keeps the voice's stored setting. Null: the voice's stored settings. Dialogue models (eleven_v3, eleven_v4) use stability only.
options.apply_text_normalizationstringDefault"auto"One of auto, on, off
Spell out numbers, dates and the like before speaking.options.apply_language_text_normalizationboolean | nullDefaultnull- Language-specific normalization (Japanese); adds latency.
options.enable_ssml_parsingbooleanDefaultfalse- Parse SSML tags in the text.
options.enable_loggingbooleanDefaulttrue- false: ElevenLabs' zero-retention mode (enterprise accounts).
options.pronunciation_dictionary_locatorsarray | nullDefaultnull- Up to 3 {pronunciation_dictionary_id, version_id}.
options.sync_alignmentbooleanDefaulttrue- /v1/stream: send each sentence's word timings (
wordsmessages). options.preferred_alignmentstring | nullDefaultnullOne of normalized, original
/v1/stream: words of the text as sent (original) or as ElevenLabs normalized it. Null:originalfor Japanese, Korean and Chinese, elsenormalized.
Changing settings#
Replies that start afterwards use the new settings:
tts.update_options( options={"voice_settings": {"stability": 0.4, "similarity_boost": 0.8, "speed": 1.1}},)With LiveKit's ElevenLabs plugin#
Keep livekit-plugins-elevenlabs and point it at the router: your router API key in place of your ElevenLabs key, and the router’s address.
pip install livekit-plugins-elevenlabsimport osfrom livekit.plugins import elevenlabstts = elevenlabs.TTS( voice_id="JBFqnCBsd6RMkjVDRZzb", model="eleven_flash_v2_5", api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"], base_url="https://api.media.ttscacherouter.dev/elevenlabs/v1",)base_url ends in /v1, as ElevenLabs’ own does. Streaming (the multi-context WebSocket), synthesize(), word-aligned transcripts, eleven_v3 and eleven_v4 through text-to-dialogue, and list_voices() all work as before.
Requests, responses and errors keep ElevenLabs’s own shape; the endpoints are below.
Which plugin to choose#
Both use your org's cache and your stored provider key, and sound the same.
- Our plugin reports only the characters ElevenLabs billed in
TTSMetrics(cache hits count zero), and switches provider withupdate_options. - ElevenLabs’s plugin is the smallest change to an agent that already uses it. Its metrics count every character, cached or not; Usage has the real split.
ElevenLabs' Python SDK#
ElevenLabs’ API, mirrored under https://api.media.ttscacherouter.dev/elevenlabs. Keep the ElevenLabs SDK: pass the router as its base_url and your router API key as its api_key.
import osfrom elevenlabs.client import ElevenLabsclient = ElevenLabs( base_url="https://api.media.ttscacherouter.dev/elevenlabs", api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],)audio = client.text_to_speech.convert( "JBFqnCBsd6RMkjVDRZzb", text="Your order has shipped. It arrives on Friday.", model_id="eleven_flash_v2_5", output_format="mp3_22050_32",)with open("speech.mp3", "wb") as f: f.writelines(audio)convert, stream, convert_with_timestamps, stream_with_timestamps and convert_realtime work through the router. Requests, responses, messages, status codes and error bodies are ElevenLabs’ own; your settings go to ElevenLabs as you sent them, with the ElevenLabs key stored under Provider keys, and the router splits your text into sentences and caches each one (see What is cached). For a LiveKit agent, see LiveKit’s ElevenLabs plugin above.
WebSockets#
/elevenlabs/v1/text-to-speech/{voice_id}/multi-stream-input: contexts by id, as LiveKit’s plugin uses it./elevenlabs/v1/text-to-speech/{voice_id}/stream-input: one stream per connection, as the SDK’sconvert_realtimeuses it./elevenlabs/v1/text-to-dialogue/multi-stream-input:eleven_v3andeleven_v4models.
wss://api.media.ttscacherouter.dev/elevenlabs/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/multi-stream-input?model_id=eleven_flash_v2_5&output_format=pcm_24000&auto_mode=true&sync_alignment=trueAudio messages carry the same timings (alignment, normalizedAlignment) a direct call gets, from the cache too, and each context ends with its isFinal (is_final on dialogue) once you close it. Every output format works, opus included. In MP3, a context’s later sentences carry no ID3 tag, as one direct stream carries only one.
REST and voices#
POST /elevenlabs/v1/text-to-speech/{voice_id}: one file in the requestedoutput_format, once every sentence is ready, as ElevenLabs answers it.…/streamstreams the audio sentence by sentence, as it is ready.POST /elevenlabs/v1/text-to-speech/{voice_id}/with-timestamps: one JSON object, the audio and its character timings (alignment,normalized_alignment), once every sentence is ready.…/stream/with-timestampsstreams ElevenLabs’ objects sentence by sentence. Either way the timings run on across the response as one request’s do: a later sentence’s start where the audio before it ended, with a space between sentences where your text has one.POST /elevenlabs/v1/text-to-dialogue/stream: dialogue models, streamed sentence by sentence.- A split response has no
request-id,history-item-idorcharacter-costheader: no one ElevenLabs request made it. GET /elevenlabs/v1/voicesandGET /elevenlabs/v2/voices: your voices.GET /elevenlabs/v1/voices/{voice_id}/settings: a voice’s stored settings.GET /elevenlabs/v1/shared-voices: the voice library.POST /elevenlabs/v1/voices/add/{public_user_id}/{voice_id}: adds a library voice to your ElevenLabs account.
The voice endpoints are never cached. GET /v1/voices lists your ElevenLabs voices in the router’s own shape, beside every other provider’s. Any other path under /elevenlabs answers 404.
curl -N "https://api.media.ttscacherouter.dev/elevenlabs/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/stream?output_format=mp3_22050_32" \ -H "xi-api-key: $TTS_CACHE_ROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"text": "Your order has shipped. It arrives on Friday.", "model_id": "eleven_flash_v2_5"}' \ --output speech.mp3curl "https://api.media.ttscacherouter.dev/elevenlabs/v1/text-to-speech/JBFqnCBsd6RMkjVDRZzb/with-timestamps?output_format=pcm_16000" \ -H "xi-api-key: $TTS_CACHE_ROUTER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"text": "Your order has shipped.", "model_id": "eleven_flash_v2_5"}'curl "https://api.media.ttscacherouter.dev/elevenlabs/v2/voices?page_size=100" -H "xi-api-key: $TTS_CACHE_ROUTER_API_KEY"What is cached#
- REST: each sentence. The router splits
text(a dialogue’s one input) at sentence ends and at the opening sentence’s first comma, and sends each piece to the ElevenLabs endpoint you called as a request of its own with your query and body’s settings, one at a time. A sentence your org has synthesized before with the same settings comes from the cache, whatever text surrounds it. - The sentences reach you as one response in your format: raw samples one after another, MP3 under one ID3 tag, WAV under one header.
- Your
previous_textgoes with the first sentence and yournext_text(future_texton dialogue) with the last, and is part of their cache keys; the sentences between are sent and cached without them. - A field you leave out, or send as
null, counts as ElevenLabs’ default for it:output_formatmp3_44100_128,enable_loggingtrue,model_ideleven_multilingual_v2(eleven_v3on dialogue),apply_text_normalizationauto,apply_language_text_normalizationfalse.voice_settingsis cached as you send it. REST entries are their own: /v1/stream, /v1/audio/speech and the WebSockets use ElevenLabs’ WebSocket APIs, a different request. - Prefer
mp3,pcm,ulaworalawoveropus. Opus takes don’t join into one stream, so a request inopusgoes to ElevenLabs as one request and is cached as one entry. Only the same text with the same settings replays it, so a sentence your agent repeats inside other replies is synthesized and paid for every time. The same goes foraudio_effects(a reverb tail or a noise bed runs across the take), text with an audio tag such as[whispers](it sets the delivery from where it stands) and a dialogue of several inputs (its turns are made together). - Only a complete take is cached: a 200 in the format you asked for whose body ElevenLabs ended cleanly. Errors are never cached.
- If your client disconnects mid-request, the sentence ElevenLabs is synthesizing finishes and is cached; the sentences after it aren’t sent.
- A request the router doesn’t read as one ElevenLabs accepts (a missing
text, a field or query parameter ElevenLabs’ reference doesn’t list, a value of the wrong type, anoutput_formatof a codec ElevenLabs doesn’t make), and one withprevious_request_idsornext_request_ids, whose stitching needs therequest-idof ElevenLabs’ own answer, goes to ElevenLabs as you sent it, isn’t cached, and gets ElevenLabs’ own answer. - WebSockets: each sentence. With
auto_mode=true(LiveKit’s default) each text message you send is synthesized on its own, as at ElevenLabs. Without it, the router splits buffered text into sentences (LiveKit’s BlingFire tokenizer) and synthesizes each once complete, where ElevenLabs would choose its own chunks.flushends the sentence in progress. - A voice’s stored settings (used when
voice_settingsis left out or partial) and a pronunciation dictionary named without aversion_idaren’t part of the cache key: after you change one, sentences cached before keep their audio until they go unused for your cache retention period. - Audio is kept for your org’s retention, counted from its last use. At retention
0, nothing is cached and every sentence goes to ElevenLabs.
Limits and timeouts#
- A REST request body is at most 80,000 bytes.
- Each sentence’s first audio within 10 seconds on a stream, 60 seconds without one, then 10 seconds at most between chunks. A request sent to ElevenLabs as is gets the same.
- Each REST request uses one connection to ElevenLabs from your org’s pool and synthesizes one sentence at a time, so it uses as much of your ElevenLabs concurrency as calling it directly. A sentence from the cache makes no request to ElevenLabs.
Errors#
A wrong router key gets ElevenLabs’ own refusal: HTTP 400 invalid_api_key (401 when no key is sent), and on a WebSocket the same error message followed by a close with code 1008. So does an org with no ElevenLabs key stored, with a message that links to the dashboard. Errors from ElevenLabs, such as an unknown voice, reach you as ElevenLabs sent them. The router’s own come in ElevenLabs’ shape: 402 when your org is out of credit, 413 for a body over 80,000 bytes, 502 when ElevenLabs can’t be reached and 504 when it sends nothing in time. A REST response begins with the first sentence’s audio, so a later sentence that fails breaks a streamed response off, as a dropped connection to ElevenLabs would.
HTTP/1.1 400 Bad Request{"detail": {"type": "authentication_error", "code": "invalid_api_key", "message": "API key is invalid.", "status": "invalid_api_key", "request_id": null, "param": "api_key"}}{"message": "API key is invalid.", "error": "invalid_api_key", "code": 1008}(close 1008)