# Smallest AI

> Smallest AI through the cache: in a LiveKit agent with our plugin or LiveKit's Smallest AI plugin, or with Smallest AI's own REST, SSE and WebSocket APIs and Smallest AI's SDK, changing only the base URLs and key.

## With our LiveKit plugin

Smallest AI’s Lightning voices with every setting of LiveKit’s Smallest AI plugin. `TTS`’s `sample_rate` is 8000, 16000, 24000 or 44100.

```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="smallestai/lightning_v3.1_pro",
    voice="meher",
    language="en",
)
```

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

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | smallestai/lightning_v3.1, smallestai/lightning_v3.1_pro | Which model synthesizes the replies, with its provider. |
| `voice` | string | Required |  | A voice of the chosen model, passed to Smallest AI as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#smallestai-models). |
| `language` | string | Default `"en"` |  | A Smallest AI language code from [languages](https://docs.ttscacherouter.dev/reference/models.md#smallestai-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, 24000, 44100 | Of the audio you receive, in Hz. |

### Changing settings

Replies that start afterwards use the new settings:

```python
tts.update_options(language="hi", speed=1.1)
```

## With LiveKit's Smallest AI plugin

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

```shell
pip install livekit-plugins-smallestai
```

**agent.py**

```python
import os

from livekit.plugins import smallestai

tts = smallestai.TTS(
    model="lightning_v3.1_pro",
    voice_id="meher",
    language="en",
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    base_url="https://api.media.ttscacherouter.dev/smallestai/waves/v1",
    ws_url="wss://api.media.ttscacherouter.dev/smallestai/waves/v1/tts/live",
)
```

Set both URLs: `ws_url` for streaming, as an agent speaks, and `base_url` for `synthesize()`.

The router splits the reply into sentences and synthesizes each on its own: a sentence’s audio starts once the sentence is complete, and each sentence is a take of its own rather than a continuation of the one before. `use_continuations`, `max_buffer_delay_ms` and `max_buffer_flush_ms` change nothing, and `word_timestamps=True` gets no word timings. The other differences from Smallest AI’s own messages are under [WebSocket](https://docs.ttscacherouter.dev/providers/smallestai.md#websocket), below.

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

## Smallest AI's Python SDK

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

**WebSocket**

```python
import os

from smallestai.waves import TTSConfig, WavesStreamingTTS

tts = WavesStreamingTTS(
    TTSConfig(
        voice_id="meher",
        api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
        model="lightning_v3.1_pro",
        language="en",
        sample_rate=24000,
    )
)
tts.ws_url = "wss://api.media.ttscacherouter.dev/smallestai/waves/v1/tts/live"

audio = b"".join(tts.synthesize("Your order has shipped. It arrives on Friday."))
with open("speech.pcm", "wb") as f:
    f.write(audio)
```

**REST**

```python
import os

from smallestai import SmallestAI, SmallestAIEnvironment

client = SmallestAI(
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    environment=SmallestAIEnvironment(
        atoms=SmallestAIEnvironment.PRODUCTION.atoms,
        waves="https://api.media.ttscacherouter.dev/smallestai",
        waves_ws="wss://api.media.ttscacherouter.dev/smallestai",
        payment=SmallestAIEnvironment.PRODUCTION.payment,
    ),
)

audio = b"".join(
    client.waves.synthesize_tts(
        text="Your order has shipped.",
        voice_id="meher",
        model="lightning_v3.1_pro",
        language="en",
        sample_rate=24000,
        output_format="wav",
    )
)
with open("speech.wav", "wb") as f:
    f.write(audio)
```

The SDK’s `environment` sets the text-to-speech base URLs (`waves` and `waves_ws`); `WavesStreamingTTS` takes its URL in `ws_url`. Requests go to Smallest AI with the Smallest AI key stored under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys). For a LiveKit agent, see [LiveKit’s Smallest AI plugin](https://docs.ttscacherouter.dev/providers/smallestai.md#provider-plugin) above.

## WebSocket

`wss://api.media.ttscacherouter.dev/smallestai/waves/v1/tts/live` speaks Smallest AI’s WebSocket protocol: messages with text and the synthesis settings, answered with `chunk` messages of base64 PCM and `complete`.

Send your router API key in `Authorization: Bearer`. Both of Smallest AI’s ways of streaming text work: `continue` and `flush` (one `complete` after a request’s audio), and continuations with a `context_id`, ended by `continue: false` or `context_close: true` and stopped by `cancel_request: true`. `{"type": "ping"}` gets `{"type": "pong"}`, and a connection with no message for 60 seconds is closed (the `timeout` query parameter sets up to 180), as at Smallest AI.

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

- Audio for a sentence starts once the sentence is complete.
- Each sentence is a take of its own: it doesn’t continue from the audio of the sentence before, as text in one Smallest AI continuation does.
- With continuations, a `complete` follows each sentence.
- `session_id` and `request_id` are the router’s own; yours come back as `external_session_id` and `external_request_id`.
- A sentence that fails gets an `error` message for its request, and the rest of that request is dropped.
- `word_timestamps` is accepted, and no word timings are sent. `max_buffer_flush_ms` and `max_buffer_delay_ms` change nothing.

As at Smallest AI, the audio is always 16-bit PCM at `sample_rate`, and text with no letter or digit (`...` alone) gets no audio.

## REST and SSE

- `POST /smallestai/waves/v1/tts`: the audio in the body’s `output_format`, with Smallest AI’s own `Content-Type`, in one response once the whole text is synthesized, as from Smallest AI. The router splits the text into sentences and caches each one (see [What is cached](https://docs.ttscacherouter.dev/providers/smallestai.md#caching)).
- `POST /smallestai/waves/v1/tts/live`: Smallest AI’s server-sent events, base64 audio then `done`, streamed sentence by sentence as each is ready.
- Your `session_id` and `request_id` come back in `X-External-Session-Id` and `X-External-Request-Id`, as from Smallest AI. A split request has no `X-Request-ID` or `X-Session-Id`: no one Smallest AI request made it.
- `GET /smallestai/waves/v1/lightning-v3.1/get_voices` (and `lightning-v3.1-pro`) and `GET /smallestai/waves/v1/voice-cloning` (your cloned voices): Smallest AI’s voice lists, never cached. With the SDK, `client.waves.get_voices(...)` and `client.waves.list_voice_clones()`. [GET /v1/voices](https://docs.ttscacherouter.dev/reference/voices.md) lists both in the router’s own shape.

Any other path under `/smallestai` answers 404.

**REST**

```shell
curl "https://api.media.ttscacherouter.dev/smallestai/waves/v1/tts" \
  -H "Authorization: Bearer $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Your order has shipped.", "voice_id": "meher", "model": "lightning_v3.1_pro", "language": "en", "sample_rate": 24000, "output_format": "wav"}' \
  --output speech.wav
```

**SSE**

```shell
curl -N "https://api.media.ttscacherouter.dev/smallestai/waves/v1/tts/live" \
  -H "Authorization: Bearer $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Your order has shipped.", "voice_id": "meher", "model": "lightning_v3.1_pro", "language": "en", "sample_rate": 24000, "output_format": "pcm"}'
```

## What is cached

- REST and SSE: each sentence. The router splits `text` at sentence ends and at the opening sentence’s first comma, and sends each piece to the Smallest AI API you called as a request of its own with your body’s settings, 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 (`pcm`, `ulaw`, `alaw`) and MP3 frames one after another, and one WAV file for `wav`. On the SSE every format but `ulaw` and `alaw` is 16-bit PCM, as from Smallest AI.
- A field you leave out counts as Smallest AI’s default for it: a `sample_rate` of 44100, `speed` 1, `output_format` `pcm` and `math_notation` off. A `model` or `language` you leave out is its own setting (Smallest AI picks the model by the voice, and `lightning_v3.1_pro` speaks English and Hindi), so name both to share sentences with the router’s own surfaces. `session_id`, `request_id` and `word_timestamps` aren’t sent and aren’t part of the cache key.
- An SSE sentence in `pcm`, `ulaw` or `alaw`, and a REST sentence in `mp3`, share the cache with [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md), [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md) and the LiveKit plugins at the same settings (`pcm`, `mulaw`, `alaw` and `mp3` there). REST in the other formats, and the SSE in `wav` or `mp3`, keep entries of their own.
- With a `content_filter` that rejects, Smallest AI refuses the whole text before any audio, so the whole text goes to Smallest AI as one request and is cached as one entry: only the same text with the same settings replays it.
- Only a complete take is cached: a 200 in the format you asked for whose body Smallest AI ended cleanly, or an SSE stream that reached `done`. Errors are never cached.
- If your client disconnects mid-request, the sentence Smallest AI is synthesizing finishes and is cached; the sentences after it aren’t sent.
- A request the router doesn’t read as one Smallest AI accepts (a missing `text` or `voice_id`, a field Smallest AI’s reference doesn’t list, which Smallest AI ignores, a `null` or a value of the wrong type, an `output_format` Smallest AI doesn’t make, text with nothing to speak or over 8,000 characters) goes to Smallest AI as you sent it, isn’t cached, and gets Smallest AI’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_dicts` is cached by the dictionaries’ ids: if you edit a dictionary in place, 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 Smallest AI.
- Smallest’s zero-retention header, `x-expire-content`, is passed on with every request the router makes to Smallest for yours, on REST, SSE and the WebSocket (send it on the handshake). It applies to Smallest’s storage only: the router’s cache keeps the audio for your org’s retention, so set retention to `0` as well if nothing may be stored.

## Limits and timeouts

- A REST or SSE request body is at most 80,000 bytes; Smallest AI takes at most 8,000 characters of text.
- Over SSE, each sentence’s first audio within 10 seconds, then 10 seconds at most between events. Over REST, each sentence’s answer within 60 seconds. A request sent to Smallest AI as is gets the same.
- Each request uses one connection to Smallest AI from your org’s pool and synthesizes one sentence at a time, so it uses as much of your Smallest AI concurrency as calling it directly. A REST response comes once every sentence is synthesized, so on a miss it takes longer than one request to Smallest AI would; a sentence from the cache makes no request to Smallest AI.

## Errors

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

- A missing or wrong router key gets Smallest AI’s own refusal: HTTP 401 `unauthorized`, at the WebSocket handshake too. An org with no Smallest AI key stored gets the same, with a message that links to the dashboard.
- Errors from Smallest AI, such as a voice of another model, a `speed` out of range or your Smallest AI concurrency limit, reach you with Smallest AI’s status and body; on the WebSocket, as an `error` message carrying Smallest AI’s message, and the connection stays open.
- The router’s own come in Smallest AI’s shape: 402 `insufficient_credits` when your org is out of credit, 413 `payload_too_large` for a body over 80,000 bytes, 502 `bad_gateway` when Smallest AI can’t be reached and 504 `gateway_timeout` when it sends nothing in time.
- An SSE response begins with the first sentence’s audio, so a later sentence that fails breaks the stream off before its `done`, as a dropped connection to Smallest AI would. A REST response waits for every sentence, so a failure gets Smallest AI’s status and body.

```http
HTTP/1.1 401 Unauthorized

{"error": "unauthorized"}
```
