# Cartesia

> Cartesia through the cache: in a LiveKit agent with our plugin or LiveKit's Cartesia plugin, or with Cartesia's own bytes, SSE and WebSocket APIs and Cartesia's SDK, changing only the base URL and key.

## With our LiveKit plugin

Cartesia’s Sonic voices with every setting of LiveKit’s Cartesia plugin. `TTS`’s `sample_rate` is 8000, 16000, 22050, 24000, 44100 or 48000.

```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="cartesia/sonic-3",
    voice="f786b574-daa5-4673-aa0c-cbe3e8534c02",
    language="en",
)
```

Pass `tts` to `AgentSession(tts=tts)`. Set `TTS_CACHE_ROUTER_API_KEY` in the agent’s environment, and store your Cartesia 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 Cartesia, 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#cartesia).

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | cartesia/sonic-3.6, cartesia/sonic-3.5, cartesia/sonic-3 | Which model synthesizes the replies, with its provider. |
| `voice` | string | Required |  | A voice of the chosen model, passed to Cartesia as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#cartesia-models). |
| `language` | string | Default `"en"` |  | A Cartesia language code from [languages](https://docs.ttscacherouter.dev/reference/models.md#cartesia-languages), passed through as given. |
| `speed` | number | Optional | 0.6 – 1.5 | Speech speed. 1.0 is normal speed; left out, the provider's default. |
| `sample_rate` | int | Default `24000` | 8000, 16000, 22050, 24000, 44100, 48000 | Of the audio you receive, in Hz. |
| `options.volume` | number \| null | Default `null` | 0.5 – 2.0 | Loudness relative to the voice's own. Null: Cartesia's default (1.0). |
| `options.emotion` | string \| null | Default `null` |  | Guide the delivery (English): neutral, calm, angry, content, sad, scared, and the others Cartesia lists. Null: Cartesia reads the emotion from the text. |
| `options.pronunciation_dict_id` | string \| null | Default `null` |  | A Cartesia pronunciation dictionary's id. Cached takes keep the dictionary as it was when they were synthesized, until they expire. |
| `options.word_timestamps` | boolean | Default `true` |  | /v1/stream: send each sentence's word timings (`words` messages). Not with mp3. |

### Changing settings

Replies that start afterwards use the new settings:

```python
tts.update_options(speed=1.1, options={"emotion": "calm"})
```

## With LiveKit's Cartesia plugin

Keep `livekit-plugins-cartesia` and point it at the router: your router API key in place of your Cartesia key, and the router’s address.

```shell
pip install livekit-plugins-cartesia
```

**agent.py**

```python
import os

from livekit.plugins import cartesia

tts = cartesia.TTS(
    model="sonic-3",
    voice="f786b574-daa5-4673-aa0c-cbe3e8534c02",
    language="en",
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    base_url="https://api.media.ttscacherouter.dev/cartesia",
)
```

`base_url` is the only URL to change: the plugin derives its WebSocket URL from it. Streaming, `synthesize()` and word timestamps work as before.

The router splits the reply into sentences and synthesizes each on its own, through either plugin: each sentence is a take of its own rather than a continuation of the one before, and the pauses between sentences are shorter than in one Cartesia context. When the user interrupts, the sentence being synthesized finishes at Cartesia and is cached; the rest of the reply isn’t sent. The other differences from Cartesia’s own messages are under [WebSocket](https://docs.ttscacherouter.dev/providers/cartesia.md#websocket), below.

Requests, responses and errors keep Cartesia’s own shape; the endpoints are [below](https://docs.ttscacherouter.dev/providers/cartesia.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 Cartesia billed in `TTSMetrics` (cache hits count zero), and switches provider with `update_options`.
- **Cartesia’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.

## Cartesia's Python SDK

Cartesia’s text-to-speech API, mirrored under `https://api.media.ttscacherouter.dev/cartesia`. Point Cartesia’s SDK at the router and use your router API key as the API key.

**Bytes**

```python
import os

from cartesia import Cartesia

client = Cartesia(
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    base_url="https://api.media.ttscacherouter.dev/cartesia",
)

response = client.tts.generate(
    model_id="sonic-3",
    transcript="Your order has shipped. It arrives on Friday.",
    voice={"mode": "id", "id": "f786b574-daa5-4673-aa0c-cbe3e8534c02"},
    language="en",
    output_format={"container": "wav", "encoding": "pcm_s16le", "sample_rate": 24000},
)
response.write_to_file("speech.wav")
```

**WebSocket**

```python
import asyncio
import os

from cartesia import AsyncCartesia


async def main() -> None:
    client = AsyncCartesia(
        api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
        websocket_base_url="wss://api.media.ttscacherouter.dev/cartesia",
    )
    pcm = bytearray()
    async with client.tts.websocket_connect() as connection:
        ctx = connection.context(
            model_id="sonic-3",
            voice={"mode": "id", "id": "f786b574-daa5-4673-aa0c-cbe3e8534c02"},
            language="en",
            output_format={"container": "raw", "encoding": "pcm_s16le", "sample_rate": 24000},
        )
        await ctx.push("Your order has shipped. ")
        await ctx.push("It arrives on Friday.")
        await ctx.no_more_inputs()
        async for response in ctx.receive():
            if response.type == "chunk" and response.audio:
                pcm += response.audio
            elif response.type == "done":
                break
    with open("speech.pcm", "wb") as f:
        f.write(pcm)


asyncio.run(main())
```

The SDK takes the router in `base_url` (bytes, SSE and voices) and `websocket_base_url`. `generate`, `generate_sse` and `websocket_connect` work through the router. Requests, responses, messages and errors are Cartesia’s own, sent to Cartesia with the Cartesia key stored under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys). For a LiveKit agent, see [LiveKit’s Cartesia plugin](https://docs.ttscacherouter.dev/providers/cartesia.md#provider-plugin) above.

## WebSocket

`wss://api.media.ttscacherouter.dev/cartesia/tts/websocket` speaks Cartesia’s WebSocket protocol: contexts by `context_id`, answered with `chunk`, `timestamps`, `flush_done` and `done` messages.

Send your router API key as Cartesia’s clients send theirs, and the API version in `Cartesia-Version` or the `cartesia_version` query parameter, as at Cartesia. Contexts run side by side on one connection, each with its own settings, and a connection with no message for 300 seconds is closed, as at Cartesia.

The router splits each context’s text into sentences and serves each sentence from the cache or synthesizes it at Cartesia, so the messages are Cartesia’s with these differences:

- Each sentence is a take of its own: it doesn’t continue from the audio of the sentence before, as text in one Cartesia context does, and the pauses between sentences are shorter.
- With `max_buffer_delay_ms: 0` (as LiveKit’s plugin sends it), each message’s text is synthesized as it comes. With buffering, a sentence is synthesized once it ends, and a trailing fragment after `max_buffer_delay_ms` without more text.
- Word timestamps run on across a context, as Cartesia’s do.
- `add_phoneme_timestamps` is refused with an error for that context.
- `cancel` drops the context’s sentences not yet sent to Cartesia; one being synthesized finishes and is cached. You get `done` at once.
- Cartesia checks a context’s settings when its first sentence is synthesized, so an error for a bad setting comes then. A context served entirely from the cache isn’t checked.

## Bytes, SSE and voices

- `POST /cartesia/tts/bytes`: the audio in the body’s `output_format`, with Cartesia’s own `Content-Type`, streamed as it is synthesized, as from Cartesia. The router splits the transcript into sentences and caches each one (see [What is cached](https://docs.ttscacherouter.dev/providers/cartesia.md#caching)).
- `POST /cartesia/tts/sse`: Cartesia’s server-sent events, `chunk`, `timestamps` and `phoneme_timestamps` with your `context_id`, then `done`, streamed sentence by sentence as each is ready.
- A split response has no `X-Request-Id` or `Cartesia-Model-Latency`: no one Cartesia request made it.
- `GET /cartesia/voices` and `GET /cartesia/voices/{id}`: Cartesia’s voice library and your own voices, never cached. [GET /v1/voices](https://docs.ttscacherouter.dev/reference/voices.md) lists them in the router’s own shape.

Any other path under `/cartesia` answers Cartesia’s `404 page not found`.

**Bytes**

```shell
curl "https://api.media.ttscacherouter.dev/cartesia/tts/bytes" \
  -H "X-API-Key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Cartesia-Version: 2026-08-14" \
  -H "Content-Type: application/json" \
  -d '{"model_id": "sonic-3", "transcript": "Your order has shipped.",
       "voice": {"mode": "id", "id": "f786b574-daa5-4673-aa0c-cbe3e8534c02"}, "language": "en",
       "output_format": {"container": "mp3", "sample_rate": 44100, "bit_rate": 128000}}' \
  --output speech.mp3
```

**SSE**

```shell
curl -N "https://api.media.ttscacherouter.dev/cartesia/tts/sse" \
  -H "X-API-Key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Cartesia-Version: 2026-08-14" \
  -H "Content-Type: application/json" \
  -d '{"model_id": "sonic-3", "transcript": "Your order has shipped.",
       "voice": {"mode": "id", "id": "f786b574-daa5-4673-aa0c-cbe3e8534c02"}, "language": "en",
       "output_format": {"container": "raw", "encoding": "pcm_s16le", "sample_rate": 24000},
       "add_timestamps": true}'
```

**Voices**

```shell
curl "https://api.media.ttscacherouter.dev/cartesia/voices?limit=20" \
  -H "X-API-Key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Cartesia-Version: 2026-08-14"
```

## What is cached

- Bytes and SSE: each sentence. The router splits `transcript` at sentence ends and at the opening sentence’s first comma, and sends each piece to the Cartesia endpoint you called as a request of its own with your body’s settings and API version, one at a time. A sentence your org has synthesized before with the same settings comes from the cache, whatever text surrounds it. A piece with no letter or digit is skipped.
- The sentences reach you as one response in your format: raw samples and MP3 frames one after another, under one WAV header or one MP3 tag. On the SSE, word and phoneme timestamps run on across the response as one request’s do: a later sentence’s start where the audio before it ended. You get one `done`, at the end.
- A field you leave out, or send as `null`, counts as Cartesia’s default for it: `normalization` `auto`, a `generation_config` `speed` or `volume` of 1, and `add_timestamps`, `add_phoneme_timestamps` and `save` off. A voice is the same setting however you name it: a string, `{"id": …}` or `{"mode": "id", "id": …}`. A `language` you leave out is its own setting, and the API version is part of every key. `context_id` isn’t sent and isn’t part of the cache key.
- Under API version `2025-04-16` (LiveKit’s Cartesia plugin’s), a bytes sentence in `mp3` or raw PCM, μ-law or A-law shares the cache with [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) at the same settings, and in `mp3` also with [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md) and the LiveKit plugins. WAV bytes and every SSE sentence keep entries of their own, and `/v1/stream` sends its other formats over Cartesia’s WebSocket, with its own entries.
- **Prefer `generation_config` over `speed`, `volume` and `emotion` tags.** A tag in the transcript sets the speech after it, and `<spell>` wraps the text it spells, so a split would cut them off from that text: a transcript with one goes to Cartesia 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. `<break>` tags and phonemes split as usual.
- Only a complete take is cached: a 200 in the format you asked for whose body Cartesia ended cleanly, or an SSE stream that reached `done`. Errors are never cached.
- If your client disconnects mid-request, the sentence Cartesia is synthesizing finishes and is cached; the sentences after it aren’t sent.
- A request the router doesn’t read as one Cartesia accepts (no `Cartesia-Version`, a missing `transcript`, `model_id`, `voice` or `output_format`, a field Cartesia’s reference doesn’t list, which Cartesia ignores, a value of the wrong type, an `output_format` missing a field Cartesia requires, `save: true`, text with nothing to speak) goes to Cartesia as you sent it, isn’t cached, and gets Cartesia’s own answer.
- WebSocket: each sentence, so a sentence you have sent before with the same settings comes from the cache whatever came around it. Sentences share the cache with the router’s own [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md) when the settings are the same.
- A request with `pronunciation_dict_id` is cached by the dictionary’s id: if you edit the dictionary, entries cached before keep the old pronunciation 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 Cartesia.

## Limits and timeouts

- A bytes or SSE request body is at most 80,000 bytes.
- Each sentence’s first audio within 10 seconds, then 10 seconds at most between chunks or events. A request sent to Cartesia as is gets the same.
- Each request uses one connection to Cartesia from your org’s pool and synthesizes one sentence at a time, so it uses as much of your Cartesia concurrency as calling it directly. A sentence from the cache makes no request to Cartesia.

## Errors

Errors arrive as Cartesia sends them, so your client's error handling keeps working.

- Errors come in the shape of your API version: `Title: Message` text before `2026-03-01`, JSON with `error_code`, `title`, `message` and `request_id` from it on.
- A missing or wrong router key gets Cartesia’s own refusal, HTTP 401, at the WebSocket handshake too. An org with no Cartesia key stored gets the same, with a message that links to the dashboard.
- Errors from Cartesia, such as an unknown voice, a sample rate it doesn’t make or your Cartesia concurrency limit, reach you with Cartesia’s status and body; on the WebSocket, as an error message for that context, and the connection stays open.
- The router’s own come in Cartesia’s shape: 402 when your org is out of credit, 413 for a body over 80,000 bytes, 502 when Cartesia can’t be reached and 504 when it sends nothing in time.
- A response begins with the first sentence’s audio, so a later sentence that fails breaks a bytes response off, as a dropped connection to Cartesia would, and ends an SSE stream with an `error` event in place of `done`, as Cartesia ends one.

```http
HTTP/1.1 401 Unauthorized

{"error_code": null, "message": "Invalid API key.", "request_id": null, "title": "Unauthorized"}
```
