# xAI

> xAI through the cache: in a LiveKit agent with our plugin or LiveKit's xAI plugin, or with xAI's own text-to-speech API, REST and WebSocket, changing only the base URL and key.

## With our LiveKit plugin

xAI's text to speech, with every setting of LiveKit's xAI plugin.

```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="xai/xai-tts",
    voice="ara",
    language="auto",
)
```

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

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | xai/xai-tts | Which model synthesizes the replies, with its provider. |
| `voice` | string | Required |  | A voice of the chosen model, passed to xAI as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#xai-models). |
| `language` | string \| null | Optional |  | A xAI language code from [languages](https://docs.ttscacherouter.dev/reference/models.md#xai-languages), passed through as given. Leave it out and xAI detects the language. |
| `speed` | number | Optional | 0.7 – 1.5 | Speech speed. 1.0 is normal speed; left out, the provider's default. |
| `sample_rate` | int | Default `24000` | 8000, 16000, 22050, 24000, 44100, 48000 | Of the audio you receive, in Hz. |
| `options.optimize_streaming_latency` | integer \| null | Default `null` | 0 – 2 | 0: best quality (xAI's default); 1 and 2: a smaller first chunk for lower time to first audio, with a quality tradeoff at chunk boundaries. Null: xAI's default. |
| `options.text_normalization` | boolean \| null | Default `null` |  | Normalize written forms (numbers, abbreviations, symbols) into spoken forms before synthesis. Null: xAI's default (false). |

### Changing settings

Replies that start afterwards use the new settings:

```python
tts.update_options(voice="eve", speed=1.1)
```

## With LiveKit's xAI plugin

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

```shell
pip install livekit-plugins-xai
```

**agent.py**

```python
import os

from livekit.agents import tokenize
from livekit.plugins import xai

from livekit.plugins.xai import tts as xai_tts

xai_tts.XAI_WEBSOCKET_URL = "wss://api.media.ttscacherouter.dev/xai/v1/tts"

tts = xai.TTS(
    voice="ara",
    language="auto",
    tokenizer=tokenize.basic.WordTokenizer(ignore_punctuation=False, retain_format=True),
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
)
```

LiveKit’s xAI plugin has no `base_url`: set its module’s `XAI_WEBSOCKET_URL` to the router before creating the TTS, as above.

Pass the `tokenizer` shown, with or without the router: the plugin’s default drops the spaces between words, and xAI speaks `Hi` then `there.` as `Hithere.`. With the default, the router also can’t tell where sentences end, so each reply is synthesized and cached whole.

The router splits the reply into sentences and caches each one, with [a few differences from xAI’s own messages](https://docs.ttscacherouter.dev/providers/xai.md#websocket).

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

xAI’s text-to-speech API, mirrored under `https://api.media.ttscacherouter.dev/xai`. Use xAI’s URLs with `https://api.x.ai` replaced by `https://api.media.ttscacherouter.dev/xai`, and your router API key in `Authorization: Bearer`.

**speak.py**

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

import websockets


async def main():
    uri = "wss://api.media.ttscacherouter.dev/xai/v1/tts?voice=ara&language=en&codec=pcm&sample_rate=24000"
    headers = {"Authorization": f"Bearer {os.environ['TTS_CACHE_ROUTER_API_KEY']}"}
    async with websockets.connect(uri, additional_headers=headers) as ws:
        await ws.send(json.dumps({"type": "text.delta", "delta": "Your order has shipped. "}))
        await ws.send(json.dumps({"type": "text.delta", "delta": "It arrives on Friday."}))
        await ws.send(json.dumps({"type": "text.done"}))
        audio = bytearray()
        async for message in ws:
            event = json.loads(message)
            if event["type"] == "audio.delta":
                audio.extend(base64.b64decode(event["delta"]))
            elif event["type"] == "audio.done":
                break
            elif event["type"] == "error":
                raise RuntimeError(event["message"])
    with open("speech.pcm", "wb") as f:
        f.write(audio)


asyncio.run(main())
```

`wss://api.media.ttscacherouter.dev/xai/v1/tts` takes xAI’s query (`voice`, `language`, `codec`, `sample_rate`, `bit_rate`, `speed`, `optimize_streaming_latency`, `text_normalization`) and refuses a bad one at the handshake, as xAI does. Send `text.delta` messages and end each utterance with `text.done`; you get `audio.delta` messages, then `audio.done`. `text.clear` stops the utterance and is answered with `audio.clear`. Requests go to xAI with the xAI key stored under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys). For a LiveKit agent, see [LiveKit’s xAI plugin](https://docs.ttscacherouter.dev/providers/xai.md#provider-plugin) above.

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

- Audio for a sentence starts once the sentence is complete.
- `text.delta` messages are joined exactly as sent, as xAI joins them: put the spaces between words in your text.
- `audio.done`’s `trace_id` is the router’s own.
- `with_timestamps=true` is refused at the handshake, and `session.update` (pronunciation replacements) is answered with an `error` message: use the REST endpoint for either. `codec=opus` is refused.
- With `codec=wav`, each utterance starts with one WAV header, as from xAI.
- A failure at xAI (an unknown voice, your xAI quota) arrives as an `error` message once a sentence needs xAI, then the router closes the connection (code 1011). A connection idle for 30 minutes is closed.

## REST

- `POST /xai/v1/tts`: the audio in the codec the body asks for (MP3 when it doesn’t), with xAI’s own `Content-Type`; JSON with `with_timestamps`. `replace` and speech tags work as at xAI. The router splits the text into sentences and caches each one (see [What is cached](https://docs.ttscacherouter.dev/providers/xai.md#caching)).
- `GET /xai/v1/tts/voices` and `GET /xai/v1/tts/voices/{voice_id}`: xAI’s voices, not cached.

Any other path under `/xai` answers 404.

**Speech**

```shell
curl "https://api.media.ttscacherouter.dev/xai/v1/tts" \
  -H "Authorization: Bearer $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"text": "Your order has shipped.", "voice_id": "eve", "language": "en"}' \
  --output speech.mp3
```

**Voices**

```shell
curl "https://api.media.ttscacherouter.dev/xai/v1/tts/voices" \
  -H "Authorization: Bearer $TTS_CACHE_ROUTER_API_KEY"
```

## What is cached

- REST: each sentence. The router splits `text` at sentence ends and at the opening sentence’s first comma, and sends each piece to xAI as a request of its own with your body’s 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 is skipped.
- The sentences reach you as one response in your codec: MP3, PCM, μ-law and A-law streamed as xAI streams them, raw samples or MP3 frames one after another; WAV, which xAI sends whole, once every sentence is ready, as one file with one header.
- A field you leave out counts as xAI’s default for it: `voice_id` `eve`, MP3 at a `sample_rate` of 24000 and a `bit_rate` of 128000, `speed` 1.0, `optimize_streaming_latency` 0, and `text_normalization` and `with_timestamps` off. [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) sends xAI the same REST request, so a sentence here shares its cache for the same voice, language, codec and settings. [/v1/stream](https://docs.ttscacherouter.dev/clients/stream.md) and the LiveKit plugins use xAI’s WebSocket and keep a cache of their own.
- **Prefer `mp3`, `pcm`, `wav`, `mulaw` or `alaw` over `opus`.** Opus takes an Ogg stream of its own per request, so its sentences don’t join into one: the whole text goes to xAI 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. A request with `with_timestamps`, whose timings cover the whole text, and text with a wrapping speech tag (`<whisper>…</whisper>`), which a split could cut in two, are cached whole in the same way. Inline tags such as `[pause]` are split as usual.
- Only a complete take is cached: a 200 in the codec you asked for whose body xAI ended cleanly. Errors are never cached.
- If your client disconnects mid-request, the sentence xAI is synthesizing finishes and is cached; the sentences after it aren’t sent.
- A request the router doesn’t read as one xAI accepts (a field xAI’s reference doesn’t list, which xAI ignores; a value of the wrong type; a codec, sample rate or MP3 bit rate xAI doesn’t make; text with nothing to speak or over 60,000 characters) goes to xAI as you sent it, isn’t cached, and gets xAI’s own answer with its `x-trace-id`.
- A response the router assembled carries only `Content-Type`: no one xAI request produced it, so there is no `x-trace-id`.
- WebSocket: each sentence, so a sentence you have sent before with the same query 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.
- 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 xAI.

## Limits and timeouts

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

## Errors

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

- A wrong router key gets xAI’s own refusal, HTTP 400, and a missing one HTTP 401, on REST and at the WebSocket handshake. An org with no xAI key stored gets the same 400, with a message that links to the dashboard.
- Errors from xAI, such as an unknown voice (404), a `speed` out of range (400) or a rate limit (429), reach you with xAI’s status and body.
- The router’s own come in xAI’s shape (`error`): 402 `insufficient_credits` when your org is out of credit, 400 for a body over 80,000 bytes, 502 when xAI can’t be reached and 504 when it sends nothing in time.
- A streamed REST response 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 xAI would. A WAV response is sent only once every sentence is ready, so any failure gets xAI’s status and body.

```http
HTTP/1.1 400 Bad Request

{"code": "Client specified an invalid argument", "error": "Incorrect API key provided."}
```
