# Gemini

> Gemini through the cache: in a LiveKit agent with our plugin or LiveKit's Gemini plugin, or with Google's Gemini API for speech, streamed and not, and Google's GenAI SDK, changing only the base URL and key.

## With our LiveKit plugin

Gemini’s speech models with every setting of LiveKit’s Gemini plugin, from version 0.5.0 of our plugin. Gemini speaks the language of the text, at 24000 Hz, and takes no `language` or `speed`: ask for a pace or a tone in `instructions`. The 3.8 and 3.1 models stream a sentence’s audio as they make it; the 2.5 models send it once it is complete, so their first audio takes a few seconds longer.

```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="gemini/gemini-3.8-flash-tts",
    voice="Kore",
)
```

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

| Field | Type | Required or default | Values | Description |
| --- | --- | --- | --- | --- |
| `model` | string | Required | gemini/gemini-3.8-flash-tts, gemini/gemini-3.8-flash-lite-tts, gemini/gemini-3.1-flash-tts-preview, gemini/gemini-2.5-flash-preview-tts, gemini/gemini-2.5-pro-preview-tts | Which model synthesizes the replies, with its provider. |
| `voice` | str \| None | Required, unless `options.speakers` |  | A voice of the chosen model, passed to Gemini as given. See [models and voices](https://docs.ttscacherouter.dev/reference/models.md#gemini-models). With `options.speakers`, `None`. |
| `sample_rate` | int | Default `24000` | 24000 | Of the audio you receive, in Hz. |
| `options.instructions` | string \| null | Default `null` |  | How to speak: style, tone, accent, pace. Null: for gemini-2.5 and gemini-3.1, LiveKit's plugin's default ("Say the text with a proper tone, don't omit or add any words"), which keeps them reading the text; for gemini-3.8, none. |
| `options.speakers` | object \| null | `gemini-3.8-flash-tts` , `gemini-3.8-flash-lite-tts` only. Default `null` |  | Two speakers' names, each with a voice (a multi-speaker voice config); replaces voice. Requires speaker. |
| `options.speaker` | string \| null | `gemini-3.8-flash-tts` , `gemini-3.8-flash-lite-tts` only. Default `null` |  | Which of speakers voices this request. |

### Changing settings

Replies that start afterwards use the new settings:

```python
tts.update_options(options={"instructions": "Speak calmly and slowly."})

# Two speakers (the 3.8 models): no voice, and the speaker of each reply in options.
tts = tcr.TTS(
    model="gemini/gemini-3.8-flash-tts",
    voice=None,
    options={"speakers": {"Joe": "Kore", "Jane": "Puck"}, "speaker": "Jane"},
)
tts.update_options(options={"speakers": {"Joe": "Kore", "Jane": "Puck"}, "speaker": "Joe"})
```

## With LiveKit's Gemini plugin

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

```shell
pip install livekit-plugins-google
```

**agent.py**

```python
import os

from livekit.plugins import google

os.environ["GOOGLE_GEMINI_BASE_URL"] = "https://api.media.ttscacherouter.dev/gemini"

tts = google.beta.GeminiTTS(
    model="gemini-3.8-flash-tts",
    voice_name="Kore",
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
)
```

The plugin has no `base_url`: Google’s GenAI SDK reads `GOOGLE_GEMINI_BASE_URL` when the plugin creates its client, so set it before creating the TTS, in code as above or in the agent’s environment. It applies to every Gemini API client the process creates, so in an agent that also uses Gemini as its LLM, use our plugin instead. Vertex AI (`vertexai=True`) doesn’t go through the router.

The plugin doesn’t stream text, so an `AgentSession` sends it one sentence at a time, and each sentence is cached on its own; text you pass to `synthesize()` is split into sentences too. Its requests are the ones our plugin makes, so the two share cached sentences. The other differences from calling Google are under [What is cached](https://docs.ttscacherouter.dev/providers/gemini.md#caching).

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

## Google's GenAI SDK

The Gemini API’s speech generation, mirrored under `https://api.media.ttscacherouter.dev/gemini`. Keep Google’s GenAI SDK (`google-genai`): pass the router as its `base_url` and your router API key as its `api_key`.

**Streaming**

```python
import os
import wave

from google import genai
from google.genai import types

client = genai.Client(
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    http_options=types.HttpOptions(base_url="https://api.media.ttscacherouter.dev/gemini"),
)

config = types.GenerateContentConfig(
    response_modalities=["AUDIO"],
    speech_config=types.SpeechConfig(
        voice_config=types.VoiceConfig(prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")),
    ),
)

pcm = bytearray()
for chunk in client.models.generate_content_stream(
    model="gemini-3.8-flash-tts",
    contents="Your order has shipped. It arrives on Friday.",
    config=config,
):
    content = chunk.candidates[0].content  # None when Gemini stops a take without audio
    for part in content.parts if content else []:
        if part.inline_data:  # the last event has an empty text part
            pcm += part.inline_data.data  # 16-bit PCM, 24000 Hz, mono

with wave.open("speech.wav", "wb") as f:
    f.setnchannels(1)
    f.setsampwidth(2)
    f.setframerate(24000)
    f.writeframes(pcm)
```

**generateContent**

```python
import os
import wave

from google import genai
from google.genai import types

client = genai.Client(
    api_key=os.environ["TTS_CACHE_ROUTER_API_KEY"],
    http_options=types.HttpOptions(base_url="https://api.media.ttscacherouter.dev/gemini"),
)

response = client.models.generate_content(
    model="gemini-3.8-flash-tts",
    contents="Your order has shipped. It arrives on Friday.",
    config=types.GenerateContentConfig(
        response_modalities=["AUDIO"],
        speech_config=types.SpeechConfig(
            voice_config=types.VoiceConfig(prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")),
        ),
        # PCM rather than the 3.8 models' default WAV file, as LiveKit's plugin asks
        http_options=types.HttpOptions(
            extra_body={"generationConfig": {"response_format": {"audio": {"mime_type": "AUDIO_L16"}}}},
        ),
    ),
)
pcm = response.candidates[0].content.parts[0].inline_data.data  # 16-bit PCM, 24000 Hz, mono
with wave.open("speech.wav", "wb") as f:
    f.setnchannels(1)
    f.setsampwidth(2)
    f.setframerate(24000)
    f.writeframes(pcm)
```

`generate_content_stream` and `generate_content` work through the router with every speech model, voice and setting, sync or async (`client.aio`). Instead of `http_options`, you can set `GOOGLE_GEMINI_BASE_URL=https://api.media.ttscacherouter.dev/gemini` in the environment, which every GenAI client in the process then uses. Requests, responses and errors are Google’s own, sent to the Gemini API with the Gemini key stored under [Provider keys](https://app.ttscacherouter.dev/app/provider-keys). The Gemini API only: Vertex AI doesn’t go through the router.

LiveKit’s Gemini plugin (`google.beta.GeminiTTS`) uses the same SDK, so `GOOGLE_GEMINI_BASE_URL` points it at the router too: see [above](https://docs.ttscacherouter.dev/providers/gemini.md#provider-plugin).

This is Google’s API, with Google’s request shape. The router’s own [/v1/audio/speech](https://docs.ttscacherouter.dev/clients/speech.md) takes `gemini/gemini-3.8-flash-tts` as the model, with `voice` and `instructions` as fields, and serves every provider.

## REST

Send your router API key where Google takes its key: the `x-goog-api-key` header, or the `key` query parameter.

- `POST /gemini/v1beta/models/{model}:streamGenerateContent?alt=sse`: Gemini’s server-sent events, each with a part of the audio, streamed sentence by sentence.
- `POST /gemini/v1beta/models/{model}:generateContent`: one JSON response with the whole audio, once every sentence is ready.
- `GET /gemini/v1beta/voices`: Gemini’s voices, never cached. [GET /v1/voices](https://docs.ttscacherouter.dev/reference/voices.md) lists them in the router’s own shape.
- `GET /gemini/v1beta/models` and `GET /gemini/v1beta/models/{model}`: Google’s model list, never cached.

Any other path under `/gemini` answers Google’s empty 404.

**Streaming**

```shell
curl -N "https://api.media.ttscacherouter.dev/gemini/v1beta/models/gemini-3.8-flash-tts:streamGenerateContent?alt=sse" \
  -H "x-goog-api-key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"parts": [{"text": "Your order has shipped."}]}],
       "generationConfig": {"responseModalities": ["AUDIO"],
         "speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Kore"}}}}}'
```

**generateContent**

```shell
curl "https://api.media.ttscacherouter.dev/gemini/v1beta/models/gemini-3.8-flash-tts:generateContent" \
  -H "x-goog-api-key: $TTS_CACHE_ROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"parts": [{"text": "Your order has shipped."}]}],
       "generationConfig": {"responseModalities": ["AUDIO"],
         "speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Kore"}}},
         "responseFormat": {"audio": {"mimeType": "AUDIO_L16"}}}}'
```

**Voices**

```shell
curl "https://api.media.ttscacherouter.dev/gemini/v1beta/voices?pageSize=100" \
  -H "x-goog-api-key: $TTS_CACHE_ROUTER_API_KEY"
```

## What is cached

- Each sentence: the router splits the text at sentence ends and at the opening sentence’s first comma, and sends each piece to the method you called as a request of its own with your 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 nothing to speak is skipped.
- With the 3.8 models, the text is what is spoken; a part with a `speech_metadata` style or speaker in quotes, as LiveKit’s plugin sends it, has each sentence quoted and carry the same metadata. With the 2.5 and 3.1 models, the text is a prompt: in LiveKit’s plugin’s form, `<instructions>:\n"<text>"`, each sentence goes with the same instructions.
- The sentences reach you as one response, in Google’s shape: with `alt=sse`, each sentence’s audio in events as it comes, then a last event with `finishReason: "STOP"`; with `generateContent`, one object with all the audio in one part. The last event or the object carries `usageMetadata` adding up what Gemini spent on this request: a sentence from the cache spent nothing. Only that last event carries usage, and there is no `responseId`, since no one Gemini request produced the response.
- Google’s defaults count as set: audio out, and a 3.8 stream’s PCM (`AUDIO_L16`). Each field is the same setting under either of its names (`speechConfig` or `speech_config`, `voiceName` or `voice_name`), and a lone content is the user’s with or without `role`. A `streamGenerateContent` sentence shares 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. `generateContent` sentences keep entries of their own.
- **Prefer LiveKit’s prompt form, `<instructions>:\n"<text>"`, over a prompt of your own with the 2.5 and 3.1 models.** Any other text may direct the speech or name speakers, and so may a multi-speaker request to these models, so a split would cut the directions off from the text they govern: such a request goes to Gemini 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. Whitespace in it is collapsed to single spaces, as in every sentence.
- **Prefer `AUDIO_L16`, `AUDIO_MULAW` or `AUDIO_ALAW` over the 3.8 models’ default WAV on `generateContent`.** Google signs each WAV file as a whole (a C2PA manifest in the file), so sentences can’t join into one: the whole text goes to Gemini as one request and is cached as one entry, with the cost above. Name the format in `generationConfig.response_format`, as in the samples.
- Only a complete take is cached: one Gemini ended with `finishReason: "STOP"`. A take Gemini stopped for another reason, and errors, are never cached.
- If your client disconnects mid-request, the sentence Gemini is synthesizing finishes and is cached; the sentences after it aren’t sent.
- A request the router doesn’t read as a speech request Gemini accepts (several contents or parts, a part that isn’t text, a field LiveKit’s plugin doesn’t send such as `systemInstruction`, `temperature` or `languageCode`, a model that isn’t a speech model, text with nothing to speak) goes to Gemini as you sent it, isn’t cached, and gets Gemini’s own answer. So does `streamGenerateContent` without `alt=sse`.
- The preview models can change under the same name, so a sentence cached from one keeps the voice it was made with until it expires.
- 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 Gemini.

## Limits and timeouts

- A request body is at most 80,000 bytes.
- Each sentence’s first audio within 120 seconds (the 2.5 models send a sentence only once it is complete), then 10 seconds at most between chunks. A request sent to Gemini as is gets the same.
- Each request uses one connection to Gemini from your org’s pool and synthesizes one sentence at a time, so Gemini’s own limits on your key apply as when you call it directly. A sentence from the cache makes no request to Gemini. Sentences go one after another, so a whole `generateContent` response that misses the cache takes longer than one request for the whole text.

## Errors

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

- A wrong router key gets Google’s own refusal, HTTP 400 `API_KEY_INVALID`, and no key at all HTTP 403 `PERMISSION_DENIED`. An org with no Gemini key stored gets the same 400, with a message that links to the dashboard.
- Errors from Gemini, such as a voice the model doesn’t have, a wrong stored Gemini key or a rate limit (429), reach you with Gemini’s status and body.
- The router’s own come in Google’s shape: 402 `FAILED_PRECONDITION` when your org is out of credit, 400 `INVALID_ARGUMENT` for a body over 80,000 bytes, 502 `UNAVAILABLE` when Gemini can’t be reached and 504 `DEADLINE_EXCEEDED` when it sends nothing in time.
- A stream begins with the first sentence’s audio, so a later sentence that fails ends it with an `error` event, Gemini’s own or the router’s, which Google’s SDK raises as it does Gemini’s.

```http
HTTP/1.1 400 Bad Request

{"error": {"code": 400, "message": "API key not valid. Please pass a valid API key.",
           "status": "INVALID_ARGUMENT",
           "details": [{"@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "API_KEY_INVALID", …}, …]}}
```
