# 60db

> 60db through the cache: in a LiveKit agent with our plugin or 60db's LiveKit plugin, or with 60db's own TTS WebSocket from your 60db client, changing only the URL and key.

> **Write each word in its own script**
>
> 60db 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

60db’s Fast and Quality voices, with every setting of 60db’s TTS WebSocket. The model is the voice’s tier: each voice belongs to `60db-fast-v01` or `60db-quality-v01`, and [GET /v1/voices](https://docs.ttscacherouter.dev/reference/voices.md) lists each tier’s, your workspace’s own included. 60db speaks the language of the text and takes no `language`; set the pace with `wpm`.

```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="60db/60db-fast-v01",
    voice="fbb75ed2-975a-40c7-9e06-38e30524a9a1",
)
```

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

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | 60db/60db-fast-v01, 60db/60db-quality-v01 | Which model synthesizes the replies, with its provider. |
| `voice` | string | Required |  | A voice of the chosen model, passed to 60db as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#60db-models). |
| `speed` | number | Optional | 0.5 – 2.0 | Speech speed. 1.0 is normal speed; left out, the provider's default. |
| `sample_rate` | int | Default `24000` | 8000, 16000, 24000, 48000 | Of the audio you receive, in Hz. |
| `options.wpm` | integer \| null | Default `null` | 60 – 300 | Target pace in words per minute, 60–300. Null: the voice's own pace. |
| `options.stability` | integer \| null | Default `null` | 0 – 100 | 0 (expressive) to 100 (consistent). Null: 60db's default (50). |
| `options.similarity` | integer \| null | Default `null` | 0 – 100 | How closely the voice matches its source, 0 (loose) to 100 (exact). Null: 60db's default (75). |

### Changing settings

Replies that start afterwards use the new settings:

```python
tts.update_options(options={"wpm": 150})

# A Quality voice: the model is the tier the voice belongs to.
tts.update_options(model="60db/60db-quality-v01", voice="voice_ba5baec75601")
```

## With 60db's LiveKit plugin

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

```shell
pip install "livekit-plugins-60db @ git+https://github.com/60db-ai/livekit-agents#subdirectory=livekit-plugins/livekit-plugin-60db"
```

**agent.py**

```python
import os

from livekit.plugins import _60db

tts = _60db.TTS(
    voice_id="fbb75ed2-975a-40c7-9e06-38e30524a9a1",
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    ws_url="wss://api.media.ttscacherouter.dev/60db/ws/tts",
)
```

60db publishes its plugin in its fork of LiveKit Agents rather than on PyPI, so install it from GitHub. Instead of `ws_url` you can set `SIXTY_DB_TTS_URL` in the environment. The plugin streams 16-bit PCM at 16000 Hz unless you pass `sample_rate`.

The plugin sends a reply’s text and a flush; the router splits each flush into sentences and caches each one. Its requests are the ones our plugin makes with `sample_rate=16000`, so the two share cached sentences.

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

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

## WebSocket

60db’s TTS WebSocket, mirrored at `wss://api.media.ttscacherouter.dev/60db/ws/tts`: 60db’s messages, in and out. Send your router API key in `apiKey`, where 60db takes its key; the router sends your text to 60db with the 60db key stored under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys).

**speak.py**

```python
import asyncio
import base64
import json
import os
import wave

import websockets

URL = f"wss://api.media.ttscacherouter.dev/60db/ws/tts?apiKey={os.environ['TTS_CACHE_ROUTER_API_KEY']}"


async def main() -> None:
    async with websockets.connect(URL) as ws:
        # {"connecting": true} comes first, then connection_established.
        while "connection_established" not in json.loads(await ws.recv()):
            pass

        await ws.send(json.dumps({"create_context": {
            "context_id": "reply-1",
            "voice_id": "fbb75ed2-975a-40c7-9e06-38e30524a9a1",
            "audio_config": {"audio_encoding": "LINEAR16", "sample_rate_hertz": 24000},
        }}))
        reply = json.loads(await ws.recv())
        if "context_created" not in reply:
            raise RuntimeError(reply)

        await ws.send(json.dumps({"send_text": {
            "context_id": "reply-1",
            "text": "नमस्ते, आपका ऑर्डर भेज दिया गया है। यह शुक्रवार को पहुँचेगा।",
        }}))
        await ws.send(json.dumps({"flush_context": {"context_id": "reply-1"}}))

        pcm = bytearray()
        while True:
            message = json.loads(await ws.recv())
            if "audio_chunk" in message:
                pcm += base64.b64decode(message["audio_chunk"]["audioContent"])
            elif "flush_completed" in message:
                break
            elif "error" in message:
                raise RuntimeError(message["error"])

        await ws.send(json.dumps({"close_context": {"context_id": "reply-1"}}))
        while "context_closed" not in json.loads(await ws.recv()):
            pass

    with wave.open("speech.wav", "wb") as f:  # 16-bit PCM, 24000 Hz, mono
        f.setnchannels(1)
        f.setsampwidth(2)
        f.setframerate(24000)
        f.writeframes(pcm)


asyncio.run(main())
```

60db’s own clients work by changing the URL and the key: its LiveKit plugin (`ws_url`, [above](https://docs.ttscacherouter.dev/providers/60db.md#provider-plugin)) and its Pipecat service, `SixtyDBTTSService`, with the router as `url` and your router API key as `api_key`.

- In: `create_context` (`voice_id`, `audio_config` with `audio_encoding` and `sample_rate_hertz`, `speed`, `wpm`, `stability`, `similarity`), `send_text`, `flush_context` and `close_context`. Out: `connecting`, `connection_established` and `context_created` (60db’s own, passed on), `audio_chunk` (base64 audio in `audioContent`), `flush_completed`, `context_closed`, `warning` and `error`.
- One context per connection, as at 60db: open a new connection for another voice or format.
- Text is spoken at `flush_context`, sentence by sentence, and `flush_completed` follows all of that flush’s audio. A flush with nothing to speak gets 60db’s `empty_audio` error.
- Text sent while a flush is still being spoken interrupts it, as at 60db: its audio stops, a `synthesis_interrupted` warning follows, and the text not yet spoken is kept and spoken at your next flush, with the new text.
- `close_context` speaks any text not yet flushed, then sends `context_closed` and closes the connection.

The router’s own [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) takes `60db/60db-fast-v01` as the model, with `voice` and the settings as fields, and serves every provider.

## What is cached

- Each sentence: the router splits each flush’s text at sentence ends (including `।`) and at the opening sentence’s first comma, and sends each piece to 60db on its own with your context’s settings. A sentence your org has synthesized before with the same settings comes from the cache, whatever text surrounds it.
- Sentences share the cache with [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md), [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) and our plugins when the context is the same: `LINEAR16` at 24000 Hz is `format: "pcm"` at `sample_rate: 24000`, with the same voice and settings. A setting sent at 60db’s default (`"speed": 1`, `"stability": 50`, `"similarity": 75`) counts as left out, so it shares entries too.
- Only a complete take is cached: a sentence 60db ended with `flush_completed`. Errors and interrupted sentences are never cached.
- If your client disconnects mid-flush, the sentence 60db is synthesizing finishes and is cached; the sentences after it aren’t sent.
- 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 60db.

## Limits and concurrency

- Every open WebSocket to 60db holds one of your 60db workspace’s concurrent text-to-speech sessions, which 60db limits by plan: 1 on Free, 5 on Starter, 10 on Creator, unlimited on Pro.
- Our plugins, `/v1/stream` and `/v1/audio/speech` share your org’s open 60db connections: a reply takes an open one with its voice and settings or opens one, and gives it back when it ends; one unused for 15 seconds is closed. So you hold about as many sessions as you have replies being spoken at once. A drop-in connection holds one from when it opens, as your own connection to 60db would.
- When your plan has no session free, the router first closes your org’s unused connections and tries once more. If 60db still refuses, the reply fails with `provider_rate_limited`, and on the drop-in with 60db’s own `TTS_CONCURRENCY_LIMIT` error, as when you call 60db directly.
- At most 20,000 characters of text between flushes; more gets a `text_buffer_exceeded` error and the unflushed text is dropped.
- 60db’s first audio for a sentence within 10 seconds, then 10 seconds at most between chunks. A drop-in connection with no message for 120 seconds is closed, as at 60db.

## Errors

On the drop-in, errors arrive as 60db sends them, so your client's error handling keeps working.

- A wrong or missing router key gets 60db’s own refusal: the connection closes with code 1008, `Invalid API key`. An org with no 60db key stored, or out of credit, gets an `error` with a message that links to the dashboard, then a close with code 1008.
- Errors from 60db, such as an unknown voice, a wrong stored 60db key or your plan’s concurrency limit, reach you as 60db sent them, with 60db’s close code.
- The router’s own come in 60db’s shape: an `error` with the router’s code, such as `provider_unavailable` when 60db can’t be reached or `provider_timeout` when it sends nothing in time, then a close with code 1011.
- A sentence that fails ends the connection; open a new one to go on.
- 60db refuses some short sentences on their own, such as `OK.`, though it speaks them within longer text. The router then sends such a sentence again together with the next one, everywhere; a last one with nothing after it is left out once the reply’s earlier sentences have been spoken. A text that is only such a sentence gets 60db’s `empty_audio` refusal (`provider_rejected` elsewhere).
- Elsewhere, 60db’s refusals become the router’s [error codes](https://docs.ttscacherouter.dev/reference/errors.md): an unknown voice or a wrong 60db key is `provider_rejected`, a full plan `provider_rate_limited`.

```json
{"error": {"context_id": "reply-1", "code": "empty_audio", "message": "Synthesis produced no audio.",
           "retry_after_ms": 1000, "backoff_base": 1.5}}
```
