> ## Documentation Index
> Fetch the complete documentation index at: https://docs.modellix.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Gemini 3.1 Flash Live Preview

> Stream text, audio, and image frames to Gemini 3.1 Flash Live Preview over WebSocket. Set a thinking level and receive spoken replies with optional text transcripts.

> [card] WSS
>
> `wss://api.modellix.ai/api/v1/live/google/gemini-3.1-flash-live-preview`

| Item | Value |
| - | - |
| Model ID | `google/gemini-3.1-flash-live-preview` |
| Release stage | Preview |
| Input | Text, PCM audio, JPEG or PNG image frames |
| Output | 24 kHz PCM audio and optional text transcription |
| Token limits | 131,072 input tokens and 65,536 output tokens |
| Authentication | `Authorization: Bearer <Modellix API Key>` on the WebSocket handshake |

## Quick Start

Install `websockets>=14` and set the `MODELLIX_API_KEY` environment variable. This Python example sends a text question, prints the transcript, and saves the spoken reply to `reply.wav`.

```python theme={null}
import asyncio
import base64
import json
import os
import wave

from websockets.asyncio.client import connect

URL = "wss://api.modellix.ai/api/v1/live/google/gemini-3.1-flash-live-preview"


async def main():
    headers = {"Authorization": f"Bearer {os.environ['MODELLIX_API_KEY']}"}
    async with connect(URL, additional_headers=headers, max_size=16 * 1024 * 1024) as ws:
        await ws.send(json.dumps({
            "setup": {
                "generationConfig": {
                    "responseModalities": ["AUDIO"],
                    "thinkingConfig": {"thinkingLevel": "MINIMAL"},
                },
                "outputAudioTranscription": {},
            }
        }))
        reply = json.loads(await ws.recv())
        if "setupComplete" not in reply:
            raise RuntimeError(f"Could not start session: {reply}")

        await ws.send(json.dumps({"realtimeInput": {"text": "Name one moon of Jupiter."}}))
        with wave.open("reply.wav", "wb") as audio:
            audio.setnchannels(1)
            audio.setsampwidth(2)
            audio.setframerate(24000)
            while True:
                message = json.loads(await ws.recv())
                content = message.get("serverContent", {})
                for part in content.get("modelTurn", {}).get("parts", []):
                    chunk = part.get("inlineData", {})
                    if chunk.get("mimeType", "").startswith("audio/pcm"):
                        audio.writeframesraw(base64.b64decode(chunk["data"]))
                transcript = content.get("outputTranscription", {}).get("text")
                if transcript:
                    print(transcript, end="", flush=True)
                if content.get("turnComplete"):
                    print()
                    break


asyncio.run(main())
```

## Session Setup

Send `setup` as the first JSON message. The URL selects the model, so you can omit `setup.model`.

**setup.generationConfig.responseModalities** `string[]`

Set to `["AUDIO"]` for a spoken reply.

**setup.generationConfig.thinkingConfig.thinkingLevel** `string` (default: MINIMAL)

Choose `MINIMAL`, `LOW`, `MEDIUM`, or `HIGH`. The default favors low latency. Higher levels let the model spend more time reasoning before it answers.

**setup.inputAudioTranscription** `object` (default: off)

Set to `{}` to receive a transcript of your audio input.

**setup.outputAudioTranscription** `object` (default: off)

Set to `{}` to receive the spoken reply as text alongside the audio.

**setup.sessionResumption** `object`

Set to `{}` to request resumption handles. To resume a session, connect to the same model from the same Modellix team and set `handle` to the latest saved value. An unrecognized handle closes the connection with code `1008`. Reconnect without a handle to start a new session.

**setup.tools** `object[]`

Declare tools your application runs with `functionDeclarations`. Omit Google Search. Requesting Google Search closes the connection with code `1008`.

## Send Input

Wait for `setupComplete` before sending any of these messages.

**realtimeInput.text** `string`

Send a text prompt in a `realtimeInput` message.

**realtimeInput.audio** `object`

Send base64-encoded, 16-bit little-endian mono PCM in `data`. For 16 kHz input, set `mimeType` to `audio/pcm;rate=16000`.

**realtimeInput.video** `object`

Send base64-encoded JPEG or PNG frames in `data` with the matching `mimeType`. Send at most one frame per second.

**toolResponse.functionResponses** `object[]`

Set `name` to the function name and `response` to an object containing its result. Copy the matching call's `id` when provided.

## Read the Reply

A server message can contain audio, transcription, and a turn marker together. Read the content before handling the turn marker.

**setupComplete** `object`

The session is ready for input.

**serverContent.modelTurn.parts\[].inlineData** `object`

Decode each audio part's base64 `data` and play the chunks in arrival order as mono 24 kHz, 16-bit little-endian PCM.

**serverContent.inputTranscription.text** `string`

Transcribed microphone input when input transcription is enabled.

**serverContent.outputTranscription.text** `string`

Transcribed model speech when output transcription is enabled.

**serverContent.turnComplete** `boolean`

Marks the end of this turn. Keep the socket open for another turn.

**toolCall.functionCalls** `object[]`

The tools for your application to run. Each call identifies the function by `name` and may include an `id` and `args`.

**sessionResumptionUpdate.newHandle** `string`

When `sessionResumptionUpdate.resumable` is `true`, save the latest non-empty handle for reconnection.

**usageMetadata** `object`

Token usage for the response, including modality breakdowns when provided.

## Billing

Modellix calculates each turn's charges from the input and output tokens the model reports. It bills thinking tokens at the output text rate. For shared billing rules, connection limits, and close codes, see the [Live Overview](https://docs.modellix.ai/live/overview.md).

For more details on the upstream model and message format, see the [Google AI Studio model reference](https://aistudio.google.com/docs/models/gemini-3.1-flash-live-preview) and [Gemini Live WebSocket reference](https://aistudio.google.com/api-reference/live).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.