# WebSocket protocol

> /v1/stream, the protocol the LiveKit plugin speaks: stream text in, sentences and audio out, from any language.

## Connecting

One WebSocket: JSON messages in, JSON messages and binary audio frames out. The LiveKit plugin and the Pipecat service speak this protocol; use it from any language.

Open a WebSocket to `/v1/stream` on the [speech host](https://docs.ttscacherouter.dev/index.md#regions), `wss://api.media.ttscacherouter.dev`, for every provider, with the header `Authorization: Bearer <API key>`. A missing, wrong or deleted key is refused at the handshake with HTTP 403. A key deleted while a connection is open is refused at its next `start` with `unauthorized`.

A complete client in Python (`pip install websockets`). It speaks one sentence into `out.wav`; run it twice and the second run plays from the cache.

**speak.py**

```python
import asyncio
import json
import os
import uuid
import wave

from websockets.asyncio.client import connect

ROUTER_URL = "wss://api.media.ttscacherouter.dev/v1/stream"
SAMPLE_RATE = 24000


async def main() -> None:
    headers = {"Authorization": f"Bearer {os.environ['TTS_CACHE_ROUTER_API_KEY']}"}
    segment_id = uuid.uuid4().hex
    async with connect(ROUTER_URL, additional_headers=headers) as ws:
        await ws.send(json.dumps({
            "type": "start",
            "segment_id": segment_id,
            "provider": "sarvam",
            "model": "bulbul:v3",
            "voice": "shubh",
            "language": "hi-IN",
            "speed": 1.0,
            "sample_rate": SAMPLE_RATE,
        }))
        await ws.send(json.dumps({
            "type": "text", "segment_id": segment_id, "text": "नमस्ते, मैं प्रिया बोल रही हूँ।",
        }))
        await ws.send(json.dumps({"type": "flush", "segment_id": segment_id}))

        pcm = bytearray()
        async for message in ws:
            if isinstance(message, bytes):
                pcm += message  # 16-bit little-endian mono PCM
                continue
            event = json.loads(message)
            if event["type"] == "sentence":
                print(f"sentence {event['index']} from {event['source']}")
            elif event["type"] == "done":
                print(f"done: {event['billed_characters']} characters billed")
                break
            elif event["type"] == "error":
                raise RuntimeError(f"{event['code']}: {event['message']}")

    with wave.open("out.wav", "wb") as wav:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(SAMPLE_RATE)
        wav.writeframes(pcm)


asyncio.run(main())
```

## Segments

A connection carries **segments**, one after another. A segment is one `start`, any number of `text` messages and one `flush`, each carrying the segment’s `segment_id`. The router answers each sentence with a `sentence` message followed by its audio as binary frames, and ends the segment with `done`. Send the next `start` on the same connection after `done` (or `cancelled`).

Sentences are spoken as soon as they’re complete, so audio usually starts before you send `flush`:

One segment on the wire (→ you send, ← the router sends):

```text
→ {"type": "start", "segment_id": "c0ffee", "provider": "sarvam", …}
→ {"type": "text", "segment_id": "c0ffee", "text": "नमस्ते, मैं सिटी हॉस्पिटल से "}
→ {"type": "text", "segment_id": "c0ffee", "text": "प्रिया बोल रही हूँ। मैं आपकी "}
← {"type": "sentence", "index": 0, "source": "cache", "text": "नमस्ते, मैं सिटी हॉस्पिटल से प्रिया बोल रही हूँ।"}
← binary frames: audio for sentence 0, replayed from the cache
→ {"type": "text", "segment_id": "c0ffee", "text": "क्या मदद कर सकती हूँ?"}
→ {"type": "flush", "segment_id": "c0ffee"}
← {"type": "sentence", "index": 1, "source": "provider", "text": "मैं आपकी क्या मदद कर सकती हूँ?"}
← binary frames: audio for sentence 1, streamed as the provider synthesizes it
← {"type": "done", "segment_id": "c0ffee", "sentences": 2, "cached_sentences": 1, "billed_characters": 30}
```

Messages out of order (`text` before `start`, a second `start`, anything after `flush` before `done`, a `segment_id` that isn’t the open segment’s, a `warm` while a segment is open) end the segment with a `bad_request` error.

## start

Opens a segment and sets the provider, voice and settings for all of its sentences. The router calls the provider with the key stored for your org.

```json
{
  "type": "start",
  "segment_id": "c0ffee",
  "provider": "sarvam",
  "model": "bulbul:v3",
  "voice": "shubh",
  "language": "hi-IN",
  "speed": 1.0,
  "sample_rate": 24000,
  "format": "pcm",
  "options": {"temperature": 0.6, "dict_id": null}
}
```

- `type` (`"start"`, Required): Identifies the message.
- `segment_id` (`string`, Required): Your id for the segment, 1–128 characters. Sent with every `text`, `flush` and `cancel`, and echoed in `done`, `cancelled` and `error`.
- `provider` (`"maya" | "vaakini" | "sarvam" | "raya" | "elevenlabs" | "openai" | "deepgram" | "xai" | "soniox" | "smallestai" | "cartesia" | "gemini" | "60db"`, Required): Which provider synthesizes, and which values below apply.
- `model` (`string`, Required): The provider’s model, without the provider: `maya-2-native`, `vaakini-tts-1`, `bulbul:v3`, `standard`, `eleven_flash_v2_5`, `tts-1`, `aura-2`, `xai-tts`, `tts-rt-v2`, `lightning_v3.1`, `sonic-3`, `gemini-3.8-flash-tts`, `60db-fast-v01`, … Every model is in [Models and options](https://docs.ttscacherouter.dev/reference/models.md).
- `voice` (`string`, Required): A voice of the model, as [GET /v1/voices](https://docs.ttscacherouter.dev/reference/voices.md) lists it, passed to the provider as given; the provider checks it. Gemini with `options.speakers`: left out or null.
- `language` (`string`, Sarvam, Raya and Soniox: required. Maya Open-Source, Vaakini, ElevenLabs and xAI: optional. Smallest AI and Cartesia: default `en`. OpenAI, Deepgram, Gemini and 60db: not taken): The provider’s language code, passed through as given: `hi-IN` for Sarvam, `hi` for Raya, Maya Open-Source and Vaakini (left out, Maya and Vaakini pick it from the script), `en` for Soniox (which reads the text in that language). Left out, ElevenLabs detects the language, and xAI too (or send `auto`); Smallest AI gets `en` (send `auto` for Smallest AI to detect it), and Cartesia too. OpenAI, Gemini and 60db speak the language of the text; a Deepgram voice names its language.
- `speed` (`number`, Sarvam, Raya and OpenAI: required. Soniox and Smallest AI: default 1.0. Deepgram, xAI, Cartesia and 60db: optional. Maya Open-Source, Vaakini, ElevenLabs and Gemini: not taken): 1.0 is normal speed; ranges are in [Models and options](https://docs.ttscacherouter.dev/reference/models.md). Deepgram takes it with `aura-2` only, and with Deepgram, xAI, Cartesia and 60db, leaving it out leaves it to the provider. ElevenLabs takes speed in `options.voice_settings.speed`; with Gemini, ask for a pace in `options.instructions`.
- `sample_rate` (`integer`, Required): Of the audio you receive, one the provider streams in `format`: see [Models and options](https://docs.ttscacherouter.dev/reference/models.md).
- `format` (`string`, Default `"pcm"`): The audio format, produced by the provider itself: `pcm` (16-bit little-endian mono) for every provider; `mp3`, `aac`, `mulaw` or `alaw` where the provider makes it ([Models and options](https://docs.ttscacherouter.dev/reference/models.md)).
- `options` (`object`, Default `{}`): The provider’s other settings, such as `temperature` for Sarvam, `voice_settings` for ElevenLabs, `instructions` for OpenAI and Gemini, `wpm` for 60db, `temperature` and `seed` for Maya Open-Source, or `normalize` and `temperature` for Vaakini. Each provider’s options, ranges and defaults are in [Models and options](https://docs.ttscacherouter.dev/reference/models.md); Raya and Smallest AI take none. A left-out option and its default share cache entries.

Any other field is a `bad_request`. [Models and options](https://docs.ttscacherouter.dev/reference/models.md) has a `start` message for every provider.

## text and flush

Send text as it arrives, chunked any way you like, such as an LLM’s tokens; the router finds the sentence boundaries. `flush` ends the segment’s input and speaks whatever text remains. A `flush` with no text gets a `done` with zeros.

```json
{"type": "text", "segment_id": "c0ffee", "text": "नमस्ते, मैं सिटी हॉस्पिटल से "}
{"type": "flush", "segment_id": "c0ffee"}
```

## warm

Send `warm` right after connecting, or when you change settings, and the router connects to the provider now instead of at the next `start` (a few hundred milliseconds to a second), so that segment’s audio doesn’t wait. The LiveKit plugin sends it on every new connection.

```json
{
  "type": "warm",
  "provider": "sarvam",
  "model": "bulbul:v3",
  "voice": "shubh",
  "language": "hi-IN",
  "speed": 1.0,
  "sample_rate": 24000,
  "format": "pcm"
}
```

It takes the fields of `start` without `segment_id`, validated the same way; an invalid one, or a `warm` while a segment is open, is a `bad_request` error. Otherwise the router doesn’t answer it. The next `start` with the same settings uses the warm connection; other settings open a new one. Nothing is billed until a sentence isn’t in the cache. If the provider can’t be reached, the next `start` tries again and reports its error.

## Router messages

`sentence` comes before each sentence’s audio. `index` counts from 0 within the segment, `text` is the sentence as it was spoken (use it to align transcripts), and `source` is `cache` or `provider`.

```json
{"type": "sentence", "index": 0, "text": "नमस्ते, मैं सिटी हॉस्पिटल से प्रिया बोल रही हूँ।", "source": "cache"}
```

The audio follows as one or more **binary frames** in the segment’s `format`, with no header. Concatenate the frames in order.

`words` (ElevenLabs and Cartesia) gives the timings of a sentence’s words. It follows the sentence’s `sentence` message, interleaved with its audio, each batch before the audio it covers. `index` is the sentence’s; `start` and `end` are seconds from the start of that sentence’s audio. Each word’s `text` runs up to the next word, trailing whitespace included, so a sentence’s words concatenate to its spoken text. Turn them off with `options.sync_alignment: false` (ElevenLabs) or `options.word_timestamps: false` (Cartesia, which sends none with `mp3`).

```json
{"type": "words", "index": 0, "words": [{"text": "Hello, ", "start": 0.02, "end": 0.35}, {"text": "this ", "start": 0.35, "end": 0.52}]}
```

`done` ends the segment. `sentences` counts every sentence, `cached_sentences` the ones from the cache, and `billed_characters` the characters of the provider sentences: what the provider charges you for.

```json
{"type": "done", "segment_id": "c0ffee", "sentences": 2, "cached_sentences": 1, "billed_characters": 30}
```

## Interrupting

To stop speaking, for example when the user barges in, send `cancel` with the segment’s id. The router stops sending its audio and answers `cancelled` after the last frame it sends for the segment. Binary frames carry no segment id, so discard frames until `cancelled` arrives. The connection is then ready for the next `start`, already warm.

`cancelled` carries `done`’s counts for the sentences whose audio the router sent in full before the cancel: `sentences`, `cached_sentences`, and `billed_characters`, what the provider billed for them. A sentence cut off mid-synthesis is not counted.

```json
{"type": "cancel", "segment_id": "c0ffee"}
{"type": "cancelled", "segment_id": "c0ffee", "sentences": 1, "cached_sentences": 0, "billed_characters": 30}
```

A `cancel` for a segment that already finished is answered with `cancelled` too, with zeros: its `done` had its counts. The provider stops the sentence it was synthesizing, which isn’t cached (ElevenLabs and Cartesia finish it, and it is cached and billed, but `cancelled` doesn’t wait for it or count it; [Usage](https://app.ttscacherouter.dev/app/usage) does). Closing the connection also stops the segment, but a sentence already being synthesized then finishes and is cached.

Segment length, message size and idle timeouts are listed in [Limits](https://docs.ttscacherouter.dev/reference/limits.md).

## Errors

An `error` message ends the segment. Close the connection and open a new one before sending anything else.

```json
{
  "type": "error",
  "segment_id": "c0ffee",
  "code": "provider_rejected",
  "message": "…",
  "retryable": false,
  "provider_status": 403
}
```

`segment_id` is `null` if the error came before a valid `start`. `provider_status` is the provider’s HTTP status when there is one, and `null` otherwise. `retryable` says whether the same request can succeed if you try again.

- `bad_request` (not retryable): The request failed validation or a message arrived out of order. The message says which field or rule.
- `unauthorized` (not retryable): The API key is missing, wrong or deleted, or its org is disabled.
- `insufficient_credits` (not retryable): Your org is out of credit, so the router refuses new connections and requests until you [buy more](https://app.ttscacherouter.dev/app/billing). Connections already open carry on.
- `provider_key_missing` (not retryable): Your org has no key stored for the provider. Add one under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys). Maya Open-Source needs none.
- `provider_rejected` (not retryable): The provider refused the request, e.g. a wrong stored provider key or an unknown voice. The provider’s message is passed through.
- `provider_rate_limited` (retryable): Your own quota at the provider is exhausted, or Maya Open-Source is at capacity (the message says so); try again in a moment.
- `provider_unavailable` (retryable): The provider returned a server error, or the connection to it failed or closed unexpectedly.
- `provider_timeout` (retryable): The provider took too long to send audio.
- `internal` (retryable): The router failed.
