# Raya

> Raya Bakbak through the cache: in a LiveKit agent with our plugin or Raya's LiveKit plugin, or with Raya's own REST, SSE and voices APIs from your Raya client, changing only the URL and key.

> **Write each word in its own script**
>
> Raya pronounces a word most reliably when it is written in the script of its language: a Hindi word in Devanagari, a Tamil word in Tamil script, an English word in Latin letters. The same Hindi word spelled in Latin letters (`dhanyavaad` for `धन्यवाद`) is more likely to be mispronounced.
>
> If an LLM writes your agent’s replies, say so in its system prompt, for example: “Write every word in the script of its own language: Hindi words in Devanagari, English words in English letters. Never write a Hindi word in English letters.”

## Which way in

This page covers Raya in a LiveKit agent and Raya's own API through the router. Every way in uses your org's cache and the Raya key stored under Provider keys.

- **A LiveKit agent:** [our plugin](https://docs.ttscacherouter.dev/providers/raya.md#our-plugin), or [Raya’s own plugin](https://docs.ttscacherouter.dev/providers/raya.md#provider-plugin) pointed at the router.
- **A Pipecat pipeline:** [our Pipecat service](https://docs.ttscacherouter.dev/pipecat.md).
- **Your own code, streaming an LLM’s reply:** [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md). Send text as it arrives; the router splits it into sentences, caches each one and streams the audio back in order. Raya has no text-to-speech WebSocket of its own.
- **Your own code, with the whole text:** [POST /v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) with `model: "raya/standard"` or `"raya/m1"`. It splits the text into sentences and caches each one, so a sentence your agent says in many replies is synthesized once.
- **Code that already calls Raya’s API:** the endpoints below. Change the base URL and the key, nothing else. The router splits each request’s text into sentences and caches each one, as it does on every other way in.

## With our LiveKit plugin

Raya Bakbak voices for Indian languages.

```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="raya/standard",
    voice="d6a002d0-230c-49b1-a137-b8a7d564b1ae",
    language="hi",
)
```

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

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | raya/m1, raya/standard | Which model synthesizes the replies, with its provider. |
| `voice` | string | Required |  | A voice of the chosen model, passed to Raya as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#raya-models). |
| `language` | string | Required |  | A Raya language code from [languages](https://docs.ttscacherouter.dev/reference/models.md#raya-languages), passed through as given. |
| `speed` | number | Default `1.0` | 0.5 – 1.5 | Speech speed. 1.0 is normal speed. |
| `sample_rate` | int | Default `24000` | 8000, 16000, 22050, 24000 | Of the audio you receive, in Hz. |

### Changing settings

Replies that start afterwards use the new settings:

```python
tts.update_options(speed=1.1)
```

## With Raya's LiveKit plugin

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

```shell
pip install "livekit-plugins-raya @ git+https://github.com/raya-voice-ai/livekit-plugins-raya"
```

**agent.py**

```python
import os

from livekit.plugins import raya

tts = raya.TTS(
    model="standard",
    voice_id="d6a002d0-230c-49b1-a137-b8a7d564b1ae",
    language="hi",
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    base_url="https://api.media.ttscacherouter.dev/raya",
)
```

Raya publishes its plugin on GitHub rather than PyPI. Instead of `base_url` you can set `RAYA_BASE_URL` in the environment. Streaming uses Raya’s SSE endpoint, and `list_voices()` works through the router too.

Requests, responses and errors keep Raya’s own shape; the endpoints are [below](https://docs.ttscacherouter.dev/providers/raya.md#endpoints).

## 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 Raya billed in `TTSMetrics` (cache hits count zero), and switches provider with `update_options`.
- **Raya’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.

## Endpoints

Raya’s API, mirrored under `https://api.media.ttscacherouter.dev/raya`: Raya’s requests, responses and errors. Send your router API key in `X-API-Key` where Raya takes its key; the router splits your text into sentences, plays each one your org has synthesized before from the cache, and sends the rest to Raya with the Raya key stored under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys).

- `POST /raya/v1/text-to-speech/stream`: Raya’s server-sent events, `chunk` events then `done`. Audio starts as soon as the first sentence is ready.
- `POST /raya/v1/text-to-speech`: one file in the requested `codec` once every sentence is ready, with Raya’s `Content-Type` and `Content-Disposition`.
- `GET /raya/v1/voices`: Raya’s voice list, with your query string passed on, never cached. Each voice belongs to one model and works only with it. [GET /v1/voices](https://docs.ttscacherouter.dev/reference/voices.md) lists the same voices in the router’s own shape.

Any other path under `/raya` answers 404.

**Python (SSE)**

```python
import array
import base64
import json
import os
import wave

import requests

resp = requests.post(
    "https://api.media.ttscacherouter.dev/raya/v1/text-to-speech/stream",
    headers={
        "X-API-Key": os.environ["TTS_CACHE_ROUTER_API_KEY"],
        "Accept": "text/event-stream",
    },
    json={
        "text": "नमस्ते, मैं प्रिया बोल रही हूँ।",
        "voice_id": "d6a002d0-230c-49b1-a137-b8a7d564b1ae",
        "language": "hi",
        "model": "standard",
        "sample_rate": 24000,
    },
    stream=True,
)
resp.raise_for_status()

# Each chunk is base64 of 32-bit float samples; a chunk can end mid-sample.
samples, pending = array.array("f"), b""
for line in resp.iter_lines():
    if not line.startswith(b"data:"):
        continue
    event = json.loads(line[5:])
    if event["type"] == "chunk":
        pending += base64.b64decode(event["data"])
        whole = len(pending) - len(pending) % 4
        samples.frombytes(pending[:whole])
        pending = pending[whole:]
    elif event["type"] == "done":
        break
    else:
        raise RuntimeError(f"Raya: {event}")

pcm = array.array("h", (int(max(-1.0, min(1.0, s)) * 32767) for s in samples))
with wave.open("speech.wav", "wb") as w:
    w.setnchannels(1)
    w.setsampwidth(2)
    w.setframerate(24000)
    w.writeframes(pcm.tobytes())
```

**SSE**

```shell
curl -N https://api.media.ttscacherouter.dev/raya/v1/text-to-speech/stream \
  -H "X-API-Key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "नमस्ते, मैं प्रिया बोल रही हूँ।", "voice_id": "d6a002d0-230c-49b1-a137-b8a7d564b1ae",
       "language": "hi", "model": "standard", "sample_rate": 24000}'
```

**REST**

```shell
curl https://api.media.ttscacherouter.dev/raya/v1/text-to-speech \
  -H "X-API-Key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "नमस्ते, मैं प्रिया बोल रही हूँ।", "voice_id": "d6a002d0-230c-49b1-a137-b8a7d564b1ae",
       "language": "hi", "model": "standard", "codec": "mulaw", "sample_rate": 8000}' \
  --output speech.mulaw
```

**Voices**

```shell
curl https://api.media.ttscacherouter.dev/raya/v1/voices -H "X-API-Key: $TTS_CACHE_ROUTER_API_KEY"
```

## Request fields

Raya's own JSON body, the same on both endpoints. Raya refuses any other field with HTTP 422.

- `text` (`string`, Required): The text to speak. Hindi must be in Devanagari.
- `voice_id` (`string`, Required): A voice of `model`, from `GET /raya/v1/voices`.
- `language` (`string`, Required): Raya’s language code, such as `hi`, `en-in` or `ta`. Every code is in [Models and options](https://docs.ttscacherouter.dev/reference/models.md).
- `model` (`"standard" | "m1"`, Default `"standard"`): Each model has its own voices.
- `codec` (`"wav" | "pcm" | "mulaw" | "mp3"`, Default `"wav"`): The REST endpoint’s format (see [Responses](https://docs.ttscacherouter.dev/providers/raya.md#responses)). The SSE endpoint ignores it and always streams 32-bit float samples.
- `sample_rate` (`8000 | 16000 | 22050 | 24000`, Default `24000`): Of the audio, in Hz.
- `speed` (`number`, Default `1.0`): 0.5 to 1.5.

## Responses

Raya's audio as Raya sends it, mono at the requested sample rate.

SSE: each `chunk` event’s `data` is base64 of 32-bit float little-endian samples, whatever `codec` says, at most half a second of them and without Raya’s `step_time`. Raya’s own chunks can end mid-sample, so join the bytes before decoding them, as the sample above does. REST, by codec and model:

| codec | standard | m1 |
| --- | --- | --- |
| `wav` | 16-bit WAV, `audio/wav` | 16-bit WAV, `audio/wav` |
| `pcm` | 16-bit little-endian, `audio/pcm` | 16-bit little-endian, `application/octet-stream` |
| `mulaw` | 8-bit μ-law, `audio/basic` | 8-bit μ-law, `audio/basic` |
| `mp3` | WAV bytes, labelled `audio/mpeg` | MP3, `audio/mpeg` |

## What is cached

- Each sentence: the router splits `text` at sentence ends (including `।`) and at the opening sentence’s first comma, and sends each piece to Raya as a request of its own with your settings. A sentence your org has synthesized before with the same settings comes from the cache, whatever text surrounds it. A piece with nothing to speak, such as `...`, is skipped.
- A field you leave out counts as Raya’s default for it, and the SSE endpoint’s entries don’t depend on `codec`. SSE sentences share the cache with [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md) and [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) PCM and WAV for the same voice and settings; REST `mulaw` and `mp3` sentences share it with their `mulaw` and `mp3`.
- Only a complete take is cached: a sentence that ended with Raya’s `done`, or a whole REST body. Errors are never cached.
- If your client disconnects mid-request, the sentence Raya is synthesizing finishes and is cached; the sentences after it aren’t sent.
- A body the router doesn’t read as a request Raya accepts (a field Raya doesn’t take, a value outside its range, text with nothing to speak) goes to Raya as you sent it, isn’t cached, and gets Raya’s own answer.
- 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 Raya.

## Limits and timeouts

- A request body is at most 80,000 bytes.
- Each sentence: Raya’s first byte within 10 seconds, then 10 seconds at most between chunks. A body sent to Raya as is: on REST, the first byte within 60 seconds.
- Each request uses one connection to Raya from your org’s pool and synthesizes one sentence at a time, so Raya’s own limits on your key apply as when you call it directly. A sentence from the cache makes no request to Raya.

## Errors

Errors from Raya, such as a wrong stored Raya key, an unknown voice or field (422) or a rate limit (429), reach you with Raya’s status and body. The router’s own come in Raya’s shape:

| Status | When |
| --- | --- |
| 401 | A wrong or missing router key, as Raya refuses a key (below); also an org with no Raya key stored, with a message that links to the dashboard. |
| 402 | Your org is out of credit: `{"detail": "…"}`. |
| 413 | The body is over 80,000 bytes: `{"detail": "…"}`. |
| 502 | Raya couldn’t be reached: `{"detail": "…"}`. |
| 504 | Raya sent nothing in time: `{"detail": "…"}`. |

On REST, a sentence that fails fails the whole request with its error. On SSE, the response begins with the first sentence’s audio, so a later sentence that fails ends the stream with an `error` event instead of `done`:

```
event: error
data: {"type": "error", "status_code": 504, "done": true, "message": "Raya sent no audio in time"}
```

```http
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Key realm="bakbak-tts"

{"message": "Unauthorized", "request_id": null}
```
