# Sarvam

> Sarvam Bulbul through the cache: in a LiveKit agent with our plugin or LiveKit's Sarvam plugin, or with Sarvam's own REST, HTTP stream and WebSocket APIs and the Sarvam SDK, changing only the URL and key.

> **Write each word in its own script**
>
> Sarvam 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.”

## With our LiveKit plugin

Sarvam Bulbul in eleven 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="sarvam/bulbul:v3",
    voice="shubh",
    language="hi-IN",
)
```

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

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | sarvam/bulbul:v3, sarvam/bulbul:v4-flash | Which model synthesizes the replies, with its provider. |
| `voice` | string | Required |  | A voice of the chosen model, passed to Sarvam as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#sarvam-models). |
| `language` | string | Required |  | A Sarvam language code from [languages](https://docs.ttscacherouter.dev/reference/models.md#sarvam-languages), passed through as given. |
| `speed` | number | Default `1.0` | 0.5 – 2.0 | Speech speed. 1.0 is normal speed. |
| `sample_rate` | int | Default `24000` | 8000, 16000, 22050, 24000 | Of the audio you receive, in Hz. |
| `options.temperature` | number | Default `0.6` | 0.01 – 1.0 | Sampling temperature: lower is steadier, higher is more expressive. |
| `options.dict_id` | string \| null | Default `null` |  | A Sarvam pronunciation dictionary to apply. |
| `options.pitch` | number | `bulbul:v4-flash` only. Default `0.0` | -0.5 – 0.5 | Pitch: lower is deeper, higher is sharper. |
| `options.loudness` | number | `bulbul:v4-flash` only. Default `1.0` | 0.1 – 2.5 | Loudness: lower is quieter, higher is louder. |
| `options.enable_preprocessing` | boolean | `bulbul:v4-flash` only. Default `false` |  | Normalize numbers and English words in the text before synthesis. |
| `options.min_buffer_size` | integer \| null | Default `null` | 30 – 200 | Characters Sarvam buffers before it starts synthesizing. Null: the router's choice, the least Sarvam allows. |
| `options.max_chunk_length` | integer \| null | Default `null` | 50 – 500 | The longest text Sarvam synthesizes in one piece; it splits longer sentences. Null: the router's choice, the most Sarvam allows, so each sentence is synthesized whole. |

### Changing settings

Replies that start afterwards use the new settings:

```python
tts.update_options(voice="priya", speed=1.1, options={"temperature": 0.4})
```

## With LiveKit's Sarvam plugin

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

```shell
pip install livekit-plugins-sarvam
```

**agent.py**

```python
import os

from livekit.plugins import sarvam

tts = sarvam.TTS(
    model="bulbul:v3",
    speaker="shubh",
    target_language_code="hi-IN",
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    base_url="https://api.media.ttscacherouter.dev/sarvam/text-to-speech",
    ws_url="wss://api.media.ttscacherouter.dev/sarvam/text-to-speech/ws",
)
```

`ws_url` carries streaming (Sarvam’s WebSocket; for `bulbul:v4-flash` the plugin adds `/v2` itself, which the router serves too) and `base_url` carries `synthesize()` (Sarvam’s REST API). Set both. Every other argument, `pitch`, `loudness` and `speech_sample_rate` included, goes to Sarvam as the plugin sends it.

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

## Sarvam's Python SDK

Sarvam’s API, mirrored under `https://api.media.ttscacherouter.dev/sarvam`. Keep your Sarvam client: give it the router as its environment and your router API key as its `api_subscription_key`.

**REST**

```python
import base64
import os

from sarvamai import SarvamAI
from sarvamai.environment import SarvamAIEnvironment

client = SarvamAI(
    api_subscription_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    environment=SarvamAIEnvironment(
        base="https://api.media.ttscacherouter.dev/sarvam",
        production="wss://api.media.ttscacherouter.dev/sarvam",
        creative="https://api.media.ttscacherouter.dev/sarvam/dubbing",  # unused: the router serves text-to-speech only
    ),
)

response = client.text_to_speech.convert(
    text="नमस्ते, मैं प्रिया बोल रही हूँ।",
    language_code="hi-IN",
    speaker="shubh",
    model="bulbul:v3",
)
with open("speech.wav", "wb") as f:
    f.write(base64.b64decode(response.audios[0]))
```

**WebSocket**

```python
import asyncio
import base64
import os

from sarvamai import AsyncSarvamAI
from sarvamai.environment import SarvamAIEnvironment

HTTP = "https://api.media.ttscacherouter.dev/sarvam"


async def main() -> None:
    client = AsyncSarvamAI(
        api_subscription_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
        environment=SarvamAIEnvironment(base=HTTP, production="wss://api.media.ttscacherouter.dev/sarvam", creative=f"{HTTP}/dubbing"),
    )
    pcm = b""
    async with client.text_to_speech_streaming.connect(model="bulbul:v3", send_completion_event=True) as ws:
        await ws.configure(target_language_code="hi-IN", speaker="shubh", output_audio_codec="linear16")
        await ws.convert("नमस्ते, मैं प्रिया बोल रही हूँ।")
        await ws.flush()
        async for message in ws:
            if message.type == "audio":
                pcm += base64.b64decode(message.data.audio)
            elif message.type == "event" and message.data.event_type == "final":
                break
    print(f"{len(pcm)} bytes of 16-bit PCM")


asyncio.run(main())
```

`convert`, `convert_stream` and `text_to_speech_streaming.connect` work through the router. Requests, responses, status codes, error bodies and WebSocket messages are Sarvam’s own; your settings go to Sarvam as you sent them, sentence by sentence, with the Sarvam key stored under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys). For a LiveKit agent, see [LiveKit’s Sarvam plugin](https://docs.ttscacherouter.dev/providers/sarvam.md#provider-plugin) above.

## WebSocket

`wss://api.media.ttscacherouter.dev/sarvam/text-to-speech/ws`, and `/ws/v2`, which LiveKit’s Sarvam plugin uses for `bulbul:v4-flash`.

Sarvam’s `model` and `send_completion_event` query parameters and its `config`, `text`, `flush` and `ping` messages. The router splits your text into sentences and synthesizes each one on its own, so each sentence your org has synthesized before with the same config plays from the cache.

- As with Sarvam, text that ends a sentence is spoken without waiting for `flush`, and one `final` event follows each `flush`, after all its audio (when you set `send_completion_event=true`).
- A sentence with no letter or digit (an emoji on its own) is skipped, since Sarvam refuses it, and so is such a run at the end of a sentence (`…shipped it. 🚀`), which Sarvam would refuse along with the sentence.
- Every codec works, `wav`, `flac` and `opus` included, message for message as Sarvam sends them.
- A connection with no messages for 60 seconds is closed with Sarvam’s own idle error.

## REST and HTTP stream

`POST https://api.media.ttscacherouter.dev/sarvam/text-to-speech` and `POST https://api.media.ttscacherouter.dev/sarvam/text-to-speech/stream`, with your router API key in `api-subscription-key`.

**HTTP stream**

```shell
curl https://api.media.ttscacherouter.dev/sarvam/text-to-speech/stream \
  -H "api-subscription-key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "नमस्ते, मैं प्रिया बोल रही हूँ।", "language_code": "hi-IN",
       "speaker": "shubh", "model": "bulbul:v3", "output_audio_codec": "mp3"}' \
  --output speech.mp3
```

**REST**

```shell
curl https://api.media.ttscacherouter.dev/sarvam/text-to-speech \
  -H "api-subscription-key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "नमस्ते, मैं प्रिया बोल रही हूँ।", "language_code": "hi-IN",
       "speaker": "shubh", "model": "bulbul:v3"}'
```

Bodies, responses and status codes are Sarvam’s own. REST answers once every sentence is ready, with one take in `audios[0]` and `"request_id": null` (no single Sarvam request made it). The HTTP stream sends each sentence’s audio as it comes, as one stream: one WAV header for `wav`. Only text-to-speech is served: any other path under `/sarvam` answers 404.

## 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 the same Sarvam API 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 Sarvam’s default for it (`bulbul:v3`, the model’s default speaker, `pace` 1.0, 22050 Hz, `temperature` 0.6, bitrate `128k`; codec `wav` on REST, `mp3` on the stream). `language_code` and `target_language_code` are cached apart. REST sentences at 32000, 44100 and 48000 Hz share the cache with [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) at those rates for the same voice and settings (`linear16` with `pcm`; `mp3`, `aac`, `mulaw` and `alaw` with themselves). At the other rates, `/v1/stream` and `/v1/audio/speech` use Sarvam’s WebSocket, a different request, and the HTTP stream is a third: each keeps its own entries.
- **Prefer `mp3`, `aac`, `linear16`, `wav`, `mulaw` or `alaw` over `flac` and `opus`.** `flac` and `opus` make a file of their own per request, so their sentences don’t join into one: the whole text goes to Sarvam 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.
- Only a complete take is cached: a whole REST reply, or a stream that ended cleanly. Errors are never cached.
- If your client disconnects mid-request, the sentence Sarvam is synthesizing finishes and is cached; the sentences after it aren’t sent.
- A body the router doesn’t read as a request Sarvam accepts (a field Sarvam’s reference doesn’t list, a value outside its range, `bulbul:v2`, text with nothing to speak) goes to Sarvam as you sent it, isn’t cached, and gets Sarvam’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 Sarvam.

## Limits and timeouts

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

## Errors

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

- A wrong or missing router API key gets Sarvam’s own refusal, HTTP 403 (at the WebSocket handshake too). So does an org with no Sarvam key stored, with a message that links to the dashboard.
- Errors from Sarvam, such as a wrong stored Sarvam key, an unknown speaker or a rate limit (429), reach you with Sarvam’s status and body.
- The router’s own come in Sarvam’s shape: 402 `insufficient_credits` when your org is out of credit, 422 `unprocessable_entity_error` for a body over 80,000 bytes, 502 `internal_server_error` when Sarvam can’t be reached and 504 `gateway_timeout_error` when it sends nothing in time.
- On REST, a sentence that fails fails the whole request with its error. The HTTP stream begins with the first sentence’s audio, so a later sentence that fails breaks the response off before its end, as a dropped connection to Sarvam would.
- When Sarvam reports an error and still speaks (a `dict_id` it can’t find, for example), you get the error, the audio and the `final` as Sarvam sends them, and that audio isn’t cached.

```http
HTTP/1.1 403 Forbidden

{"error": {"message": "Invalid or missing authentication credentials",
           "code": "invalid_api_key_error", "request_id": null}}
```
