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

```shell
pip install livekit-plugins-tts-cache-router
```

**agent.py**

```python
from 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](https://app.ttscacherouter.dev/app/provider-keys). `TTS`’s own arguments are on [the plugin’s page](https://docs.ttscacherouter.dev/livekit.md#tts).

### 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](https://docs.ttscacherouter.dev/reference/models.md#elevenlabs).

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | 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. |
| `voice` | string | Required |  | A voice of the chosen model, passed to ElevenLabs as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#elevenlabs-models). |
| `language` | string \| null | Optional |  | A ElevenLabs language code from [languages](https://docs.ttscacherouter.dev/reference/models.md#elevenlabs-languages), passed through as given. Leave it out and ElevenLabs detects the language. |
| `sample_rate` | int | Default `24000` | 8000, 16000, 22050, 24000, 32000, 44100, 48000 | Of the audio you receive, in Hz. |
| `options.voice_settings` | object \| null | Default `null` |  | 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_normalization` | string | Default `"auto"` | auto, on, off | Spell out numbers, dates and the like before speaking. |
| `options.apply_language_text_normalization` | boolean \| null | Default `null` |  | Language-specific normalization (Japanese); adds latency. |
| `options.enable_ssml_parsing` | boolean | Default `false` |  | Parse SSML tags in the text. |
| `options.enable_logging` | boolean | Default `true` |  | false: ElevenLabs' zero-retention mode (enterprise accounts). |
| `options.pronunciation_dictionary_locators` | array \| null | Default `null` |  | Up to 3 {pronunciation_dictionary_id, version_id}. |
| `options.sync_alignment` | boolean | Default `true` |  | /v1/stream: send each sentence's word timings (`words` messages). |
| `options.preferred_alignment` | string \| null | Default `null` | normalized, original | /v1/stream: words of the text as sent (`original`) or as ElevenLabs normalized it. Null: `original` for Japanese, Korean and Chinese, else `normalized`. |

### Changing settings

Replies that start afterwards use the new settings:

```python
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.

```shell
pip install livekit-plugins-elevenlabs
```

**agent.py**

```python
import os

from livekit.plugins import elevenlabs

tts = 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](https://docs.ttscacherouter.dev/providers/elevenlabs.md#sdk).

## 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 with `update_options`.
- **ElevenLabs’s plugin** is the smallest change to an agent that already uses it. Its metrics count every character, cached or not; [Usage](https://docs.ttscacherouter.dev/dashboard.md#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`.

**speak.py**

```python
import os

from elevenlabs.client import ElevenLabs

client = 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](https://app.ttscacherouter.dev/app/provider-keys), and the router splits your text into sentences and caches each one (see [What is cached](https://docs.ttscacherouter.dev/providers/elevenlabs.md#caching)). For a LiveKit agent, see [LiveKit’s ElevenLabs plugin](https://docs.ttscacherouter.dev/providers/elevenlabs.md#provider-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’s `convert_realtime` uses it.
- `/elevenlabs/v1/text-to-dialogue/multi-stream-input`: `eleven_v3` and `eleven_v4` models.

```text
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=true
```

Audio 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 requested `output_format`, once every sentence is ready, as ElevenLabs answers it. `…/stream` streams 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-timestamps` streams 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-id` or `character-cost` header: no one ElevenLabs request made it.
- `GET /elevenlabs/v1/voices` and `GET /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](https://docs.ttscacherouter.dev/reference/voices.md) lists your ElevenLabs voices in the router’s own shape, beside every other provider’s. Any other path under `/elevenlabs` answers 404.

**Stream**

```shell
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.mp3
```

**With timestamps**

```shell
curl "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"}'
```

**Voices**

```shell
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_text` goes with the first sentence and your `next_text` (`future_text` on 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_format` `mp3_44100_128`, `enable_logging` true, `model_id` `eleven_multilingual_v2` (`eleven_v3` on dialogue), `apply_text_normalization` `auto`, `apply_language_text_normalization` false. `voice_settings` is cached as you send it. REST entries are their own: [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md), [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) and the WebSockets use ElevenLabs’ WebSocket APIs, a different request.
- **Prefer `mp3`, `pcm`, `ulaw` or `alaw` over `opus`.** Opus takes don’t join into one stream, so a request in `opus` goes 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 for `audio_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, an `output_format` of a codec ElevenLabs doesn’t make), and one with `previous_request_ids` or `next_request_ids`, whose stitching needs the `request-id` of 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. `flush` ends the sentence in progress.
- A voice’s stored settings (used when `voice_settings` is left out or partial) and a pronunciation dictionary named without a `version_id` aren’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](https://docs.ttscacherouter.dev/index.md#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.

**REST**

```http
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"}}
```

**WebSocket**

```text
{"message": "API key is invalid.", "error": "invalid_api_key", "code": 1008}
(close 1008)
```
