Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install gemini-live-api@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin gemini-live-api v1.0.0 follows the Agent Plugins spec.
gh skills-hub install gemini-live-api Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/gemini-live-api/ Extract the ZIP to .github/skills/ in your repo. The folder name must match gemini-live-api for Copilot to auto-discover it.
Skill Files (8)
SKILL.md 26.9 KB
---
name: gemini-live-api
metadata:
version: "1.1.0"
category: AiAndMachineLearning
description: >-
Builds, integrates, and troubleshoots Gemini Enterprise Agent Platform Live
API (BidiGenerateContent) WebSocket clients and sessions. Use when scaffolding
a LiveAPI client or demo UI/backend (GA v1 WebSockets, isolated Python venv,
ADC bearer token refresh, transparent session resumption, ClientMessage and
ServerMessage JSON protos, tool responses, context_update, interrupt and
transcription handling) or debugging Live API issues such as silent or empty
turns, audio amplitude collapse, tonal humming, voice gender or accent drift,
premature turn completion, barge-in failures, output_transcription leaks,
malformed or looping tool calls, WebSocket 1008/1011/goAway drops, or latency
spikes. Don't use for non-live, non-bidirectional Gemini API calls such as
unary generateContent, embeddings, image/video generation, or fine-tuning —
use the gemini-api skill for those.
---
> [!IMPORTANT]
> Gemini Enterprise Agent Platform was previously named "Vertex AI"; the API
> service endpoint remains `aiplatform.googleapis.com`.
# LiveAPI Service Skill
This skill provides instructions for generating a **LiveAPI client service
class** that connects to the Gemini Enterprise Agent Platform Live API over
WebSockets (`LlmBidiService/BidiGenerateContent`), as well as diagnosing and
resolving Live API runtime issues. The generated client handles bidirectional
JSON frame streaming, bearer-token authentication via Application Default
Credentials (ADC), transparent session resumption, tool call responses,
mid-session context updates, and `ClientMessage` / `ServerMessage` proto
exchange.
The skill also produces a demo frontend + backend service so the user can
interactively validate the generated client (text, audio, video, transcription,
and interrupt handling).
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Prerequisites
Before running the generation flow, verify or guide the user through the
following prerequisites (always ask for user approval before modifying host
configurations or installing system tools):
- **Google Cloud Project & Billing**: An active Google Cloud project with a
linked billing account (review [Gemini Enterprise Agent Platform pricing](https://cloud.google.com/products/gemini-enterprise-agent-platform/pricing)):
```bash
gcloud config set project {project_id}
```
- **API Enablement & IAM**: The `aiplatform.googleapis.com` API enabled on the
project, and the caller principal granted at least Vertex AI User
(`roles/aiplatform.user`):
```bash
gcloud services enable aiplatform.googleapis.com
```
- **Application Default Credentials (ADC)**: Configured on the host running
the generated client (see [Google Cloud authentication](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/start/gcp-auth.md.txt)):
```bash
gcloud auth application-default login
```
- **Regional Location**: Default to `us-central1` unless the user specifies
another supported US or EU region (e.g., `europe-west4`; see [supported locations](https://docs.cloud.google.com/gemini-enterprise-agent-platform/resources/locations.md.txt)).
Live API models do **not** support the `global` endpoint.
- **Isolated Output Directory**: A destination folder supplied by the user
(e.g., `/tmp/liveapi_out`) where generated code, virtual environments, and
the demo service will be written. **Never** mutate the host's system Python
environment.
- **Implementation Language**: Python is the default and reference language
when the user does not specify another language.
## Supported Live API Models
- **`gemini-3.8-live` (GA — Recommended default)**: Native audio I/O, VAD,
affective dialog and proactive audio **always enabled by default**,
`NON_BLOCKING` and `BLOCKING` function calling, mid-session
`context_update`, and custom transcription vocabulary.
- **`gemini-live-2.5-flash-native-audio` (GA)**: Native audio I/O,
transcriptions, VAD, optional `generation_config.enable_affective_dialog`
and `proactivity.proactive_audio`, and function calling.
- **`gemini-3.5-transcribe-live-preview` (Preview)**: Dedicated low-latency
speech-to-text streaming (`input_transcription` and
`interim_input_transcription`) with `VERBATIM` and `SMART` modes and custom
vocabulary.
## Reference Files
Load these files from `references/` on demand (do **not** treat them as
standalone skills):
- [client_server_messages.md](references/client_server_messages.md): Wire
protocol reference for `ClientMessage` / `ServerMessage`, model-specific
`gemini-3.8-live` rules, and JSON examples.
- [client_server_messages.proto](references/client_server_messages.proto):
Proto3 schema derived from the public Live API documentation for generating
typed `ClientMessage` and `ServerMessage` classes.
- [session_manager.md](references/session_manager.md): Specification for
connection lifecycle, 1-based message buffering, `go_away` handling, and
transparent session resumption.
- [Audio, Voice, Accent, and Quality Troubleshooting](references/troubleshooting_audio_voice.md):
Prebuilt voice gender table, accent/locale fixes, amplitude collapse, tonal
humming, and jitter buffering.
- [Turns, VAD, Barge-In, and Transcriptions Troubleshooting](references/troubleshooting_turns_vad.md):
`generationComplete` vs. `turnComplete`, `contextWindowCompression` readback
settings, client stall nudges, backchannel gating, telephony VAD padding,
and transcription/instruction leakage guards.
- [Tool Calling, Safety Filters, Lifecycle, Latency, and Cost Troubleshooting](references/troubleshooting_tools_lifecycle.md):
Typed schemas, `NON_BLOCKING` scheduling, state-machine polarity, pre-tool
filler handling, safety filters, WebSocket `1008`/`1011` and `goAway`
recovery, `TTFT` triage, and cost optimization.
## Steps
### Step 1: Copy the reference files
Copy `client_server_messages.md`, `client_server_messages.proto`, and
`session_manager.md` from this skill's `references/` folder into the user's
destination output folder. These files become the local source of truth for the
generated client.
### Step 2: Reconcile and compile the proto definitions
Check the public documentation linked in
[client_server_messages.md](references/client_server_messages.md). If any new
server fields are needed for the user's task, update the copied
`client_server_messages.md` and `client_server_messages.proto` in the
destination folder, and compile `client_server_messages.proto` (e.g., via
`grpc_tools.protoc` or `protoc`) into the destination folder.
### Step 3: Implement the client class and `SessionManager`
Implement a client service class in the user's chosen language that:
- Imports the local compiled `client_server_messages.proto` types
(`ClientMessage`, `ServerMessage`).
- Connects over WebSockets to:
`wss://{location}-aiplatform.googleapis.com/ws/google.cloud.aiplatform.{api_version}.LlmBidiService/BidiGenerateContent`
where `api_version` defaults to `"v1"` (allow overriding to `"v1beta1"` for
preview-only features such as Vertex RAG Engine).
- Formats `setup.model` as
`projects/{project_id}/locations/{location}/publishers/google/models/{model_id}`.
- Serializes outgoing `ClientMessage` instances as **UTF-8 JSON text frames**
(e.g., `google.protobuf.json_format.MessageToJson`) and parses incoming JSON
text frames into `ServerMessage` with unknown fields ignored
(`ignore_unknown_fields=True`). **Never** send binary protobuf bytes.
- Implements transparent session resumption per
[session_manager.md](references/session_manager.md) (including
`context_window_compression.sliding_window` when sessions may exceed 15
minutes).
For languages that require an isolated runtime (e.g., Python), create an
isolated environment (e.g., `venv`) **inside the destination folder** along with
a `requirements.txt` pinning exact compatible versions within tested bounds
(`websockets>=13.0,<16.0`, `protobuf>=5.29.0,<7.0.0`,
`google-auth>=2.35.0,<3.0.0`, `requests>=2.32.0,<3.0.0`,
`grpcio-tools>=1.68.0,<2.0.0`) and a runnable `setup.sh` script that creates the
`venv`, runs `pip install -r requirements.txt` (explicitly referencing
`requirements.txt`), and compiles `client_server_messages.proto`. **Never**
install into the system interpreter or user-global site-packages, and never
instruct the user to run `sudo pip install`.
#### Initialization parameters
Accept at construction time:
- `project_id`: Google Cloud project ID.
- `location`: Regional location (e.g., `"us-central1"`; reject `"global"`).
- `model_id`: Live API model ID (e.g., `"gemini-3.8-live"`).
- `config`: A `ClientMessage` with the `setup` field populated.
- `api_version` (optional): Defaults to `"v1"` (supports `"v1beta1"`).
#### Authentication
Obtain an access token via Application Default Credentials with scope
`https://www.googleapis.com/auth/cloud-platform`, attach it to the WebSocket
handshake header as `Authorization: Bearer <token>`, refresh it before or upon
expiry, and attach the valid/refreshed token on every reconnection (including
`go_away` and close codes `1000`, `1006`, or `1011`). **Do not** hard-code a
long-lived API key as the only auth mechanism.
#### Public async API
Expose the following async methods, all gated on receipt of a `setup_complete`
`ServerMessage` before sending:
- `send_realtime_data(data: ClientMessage)`: Send continuous low-latency
media/text. `data` MUST be typed as `ClientMessage` carrying
`realtime_input`.
- `send_client_content(data: ClientMessage)`: Send discrete, history-bearing
turns. `data` MUST be typed as `ClientMessage` carrying `client_content`.
(On `gemini-3.8-live`, set
`setup.history_config.initial_history_in_client_content = true` when seeding
prior history, and never use `role="system"` in `client_content`.)
- `send_tool_response(data: ClientMessage)`: Reply to a server `tool_call`.
`data` MUST be typed as `ClientMessage` carrying `tool_response`. (On
`gemini-3.8-live`, return informative status objects such as
`{"status": "ok"|"not_found", "retryable": false, ...}` instead of empty
`{}` to prevent retry sweeps.)
- `send_context_update(data: ClientMessage)`: Update `system_instruction`
and/or `tools` mid-session (`gemini-3.8-live`). `data` MUST be typed as
`ClientMessage` carrying `context_update`.
- `receive() -> AsyncIterator[ServerMessage]`: Async generator yielding
`ServerMessage` instances parsed from the WebSocket stream.
Do not expose synchronous blocking variants as the primary API surface.
### Step 4: Write a test file
Generate a test file in the destination folder that initializes the client and
exercises `text`, `audio` (16 kHz PCM), `video` (sampled JPEG/PNG frames),
`send_tool_response`, and `send_context_update`, verifying `ServerMessage`
responses. Ask the user for any runtime inputs needed (`project_id`, model, or
sample media).
### Step 5: Generate `how_to_run.md`
Write `how_to_run.md` in the destination folder documenting the generated client
class, setup scripts, and complete examples building `ClientMessage` payloads
for realtime audio/video/text, `client_content` turns (including seeded
history), `tool_response` (async `scheduling` and structured responses), and
`context_update`.
### Step 6: Generate a demo frontend + backend service
Create a frontend UI and backend service in the destination folder that reuse
the local `ClientMessage` / `ServerMessage` protos from Step 1. Through the UI
the user must be able to:
- Open and close a Live API session.
- Select the model (defaulting to `gemini-3.8-live`).
- Stream microphone audio (16 kHz mono PCM) and camera or screen frames (~1
fps JPEG) to the model.
- Send typed text messages.
- Play back 24 kHz model audio and view interleaved user and model
transcriptions.
Follow [Live API best practices](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/best-practices.md.txt)
for audio capture, echo cancellation, and playback buffering.
#### Handling the `interrupt` signal
When `server_content` arrives with `interrupted: true`, the UI MUST:
- Keep played audio and rendered transcription time-aligned.
- Immediately stop currently playing model audio and stop appending to the
in-progress model transcription bubble.
- Clear unplayed audio buffers and queued unrendered transcription text so
stale content never bleeds into the next turn.
- Start fresh chat bubbles for subsequent user and model turns.
#### Handling the transcription `finished` signal
For streamed `input_transcription` and `output_transcription` chunks (and
optional `interim_input_transcription` previews), append text to the active
bubble while `finished` is unset/`false`, and close that bubble to start a fresh
one when `finished: true` arrives. Route `input_transcription` to user-role
bubbles and `output_transcription` to model-role bubbles.
### Step 7: Generate `how_to_test_with_ui.md`
Write `how_to_test_with_ui.md` in the destination folder with:
- Exact shell command(s) to start the backend service.
- Exact shell command(s) to start the frontend UI.
- Browser URL (`http://localhost:PORT`).
- Walkthrough for starting a session, selecting a model, streaming mic/camera/
screen inputs, sending text, and verifying audio + transcription + barge-in.
## Validation Checklist
Verify every item before completing generation:
- [ ] `client_server_messages.md`, `client_server_messages.proto`, and
`session_manager.md` were copied into the destination folder.
- [ ] The generated client compiles and imports the local `ClientMessage` and
`ServerMessage` proto types, and exchanges UTF-8 JSON text frames
(`MessageToJson` / `Parse` with unknown fields ignored).
- [ ] The client connects to
`wss://{location}-aiplatform.googleapis.com/ws/google.cloud.aiplatform.{api_version}.LlmBidiService/BidiGenerateContent`
defaulting `api_version` to `"v1"` on a regional endpoint (never `global`),
and formats `setup.model` as
`projects/{project_id}/locations/{location}/publishers/google/models/{model_id}`.
- [ ] Authentication uses ADC bearer tokens (`Authorization: Bearer <token>`),
refreshes before expiry, and reattaches the valid token on every reconnect.
- [ ] Public async methods `send_realtime_data`, `send_client_content`,
`send_tool_response`, `send_context_update`, and `receive` are present,
typed with `ClientMessage` / `ServerMessage`, and gated on `setup_complete`.
- [ ] Transparent session resumption sets `session_resumption.transparent =
true`, tracks `new_handle`, indexes buffered messages starting at `1`,
prunes via `last_consumed_client_message_index`, and replays from index `1`
on reconnect (`go_away` and WebSocket codes `1000` / `1006` / `1011`).
- [ ] For Python, an isolated `venv`, `setup.sh`, and `requirements.txt` live
inside the destination folder with zero changes to system/global Python.
- [ ] `how_to_run.md` and `how_to_test_with_ui.md` exist, and the demo UI
implements `interrupted: true` and `Transcription.finished` handling.
- [ ] The client does **not** target `generativelanguage.googleapis.com` and
does **not** pass API keys in URL query strings.
--------------------------------------------------------------------------------
## Troubleshooting Live API Issues
When debugging an existing Live API integration or runtime failure (rather than
scaffolding a new client from scratch), follow this diagnostic workflow before
making prompt tweaks.
### Diagnostic Workflow
1. **Verify environment and model currency:** Confirm a regional endpoint
(for example, `us-central1`; `global` is not supported for Live API
WebSockets) and active billing ([Google Cloud Pricing](https://cloud.google.com/pricing)).
Legacy `gemini-2.0-*` models and `gemini-live-2.5-flash` (half-cascade) are
deprecated or shut down; test whether the symptom resolves on
`gemini-3.8-live` or `gemini-live-2.5-flash-native-audio`.
2. **Capture the full serialized wire payload:** Log the exact
`BidiGenerateContentSetup` JSON, `clientContent`, `realtimeInput`,
`toolResponse`, and `contextUpdate` frames actually sent over the WebSocket.
Frameworks often inject extra session state or tool declarations absent from
source prompt files.
3. **Audit against Pre-Flight Configuration Rules:** Fix primary structural
defects (gender mismatch, missing regional `languageCode`, low `temperature`
+ `generationConfig.enableAffectiveDialog`, bloated `tools` or
`systemInstruction`) first.
4. **Isolate optional flags and tools:** On
`gemini-live-2.5-flash-native-audio`, temporarily disable
`setup.proactivity.proactiveAudio` and
`setup.generationConfig.enableAffectiveDialog` (both are built-in by default
on `gemini-3.8-live` and should be omitted there), and stub out `tools` when
testing minimal prompt behavior.
5. **Reproduce and verify A/B:** Replay the failing turn sequence before and
after 1-2 targeted changes, checking audio duration, PCM amplitude,
`output_transcription`, and `turnComplete` signals.
### Quick Symptom Triage Matrix
| Symptom | Primary Suspect | Immediate Fix | Reference |
| --- | --- | --- | --- |
| Voice flips gender (Turn 1 or mid-call) | Prebuilt voice gender mismatches SI persona name/pronouns | Match `voiceName` gender to SI persona | [Audio & Voice](references/troubleshooting_audio_voice.md#voice-gender-swaps) |
| Accent reverts to `en-US`, pitch jumps, or code-mix fails | Omitted `speechConfig.languageCode` or long single-script SI | Set supported BCP-47 `languageCode` (e.g., `en-IN`) and concise SI | [Audio & Voice](references/troubleshooting_audio_voice.md#accent-reversion-pitch-jumps-and-code-mixed-switching) |
| Output mimics user's voice timbre | Native audio role leakage from user audio in context | Upgrade to `gemini-3.8-live`; clarify role boundaries; reconnect | [Audio & Voice](references/troubleshooting_audio_voice.md#output-voice-mimics-user-timbre) |
| Gradual voice/tone drift over long calls | Audio-token conditioning drift as history grows | Enable `contextWindowCompression` and rotate long sessions | [Audio & Voice](references/troubleshooting_audio_voice.md#multi-turn-voice-and-tone-drift) |
| Fast speech (240+ WPM) or raw `/IPA/` leaks | Long single-breath clauses, `2.5` affective dialog, or TTS markup in SI | Shorten clauses, strip TTS headers/IPA, or use `gemini-3.8-live` | [Audio & Voice](references/troubleshooting_audio_voice.md#fast-speech-rate-and-tts-markup-or-ipa-leaks) |
| Near-zero audio volume (`-34 dBFS`), intact text | Tool schemas `>40k` tokens or rolling text logs in SI | Prune `tools` to active turn/step, drop rolling text logs, keep SI `<2,000` tokens | [Audio & Voice](references/troubleshooting_audio_voice.md#near-zero-audio-amplitude-collapse) |
| `150-700 Hz` tonal hum or endless greeting | `temperature <= 0.3` with `2.5` `generationConfig.enableAffectiveDialog` | Set `temperature >= 0.7`, disable `2.5` affective dialog, open fresh session | [Audio & Voice](references/troubleshooting_audio_voice.md#tonal-humming-buzz-150-700-hz-and-non-terminating-greetings) |
| Choppy playback with `0.1-0.5s` gaps | Small variable WebSocket audio chunks played raw | Add a `~200 ms` client-side jitter buffer | [Audio & Voice](references/troubleshooting_audio_voice.md#choppy-playback-and-audio-jitter) |
| Premature `generationComplete` (`~0.75s`) or missing `turnComplete` | Advancing on `generationComplete`, `<verbatim>` tags, or history bloat | Wait for `turnComplete`, strip `<verbatim>` tags, add `contextWindowCompression` | [Turns & Transcripts](references/troubleshooting_turns_vad.md#premature-generationcomplete-and-missing-turncomplete) |
| `0` audio chunks after `toolResponse` (`>14k` tokens) | XML/JSON bloat diluting voice conditioning | Use prose SI, clean JSON tools, and `contextWindowCompression` | [Turns & Transcripts](references/troubleshooting_turns_vad.md#post-toolresponse-zero-audio-turns-in-deep-contexts) |
| Empty turns (`output_audio=0`) and `12-30s` wedges | `2.5` `proactivity.proactiveAudio` or client `3s` stall nudges | Disable `proactivity.proactiveAudio` on `2.5`; remove `3s` `clientContent` nudges | [Turns & Transcripts](references/troubleshooting_turns_vad.md#empty-turns-from-proactiveaudio-and-client-stall-nudges) |
| Turn-1 `output_transcription` dropped or silence placeholder leak | `realtimeInput.text` kickoff under `TURN_INCLUDES_ALL_INPUT` | Use `TURN_INCLUDES_ONLY_ACTIVITY` and `clientContent(turnComplete=True)` | [Turns & Transcripts](references/troubleshooting_turns_vad.md#turn-1-transcript-drops-and-prompt-template-newlines) |
| Unspoken Markdown or code in `output_transcription` | Post-speech text flush into UI / persisted transcripts | Set `languageCode`, ban Markdown in SI, strip trailing code blocks in UI | [Turns & Transcripts](references/troubleshooting_turns_vad.md#unspoken-markdown-or-code-tail-bursts-in-output_transcription) |
| Audible instruction leak pre-tool without transcript | Spoken pre-tool filler in `>70k`-token context | Call tools silently, strip `"speak..."` wrappers, compress context | [Turns & Transcripts](references/troubleshooting_turns_vad.md#pre-tool-filler-audible-leakage-without-transcripts) |
| Model speaks `<no speech>`, `{pause}`, or raw JSON | `NON_BLOCKING` missing `scheduling="SILENT"`, echo, or routing trap | Set `scheduling="SILENT"`, enable AEC, cap unclear turns | [Turns & Transcripts](references/troubleshooting_turns_vad.md#spoken-placeholder-tokens-and-raw-json-leaks) |
| Short `"Mm-hmm"` cuts off speech; double interrupt stalls | Acoustic barge-in firing on brief backchannels | Filter `<500 ms` backchannels client-side before streaming | [Turns & Transcripts](references/troubleshooting_turns_vad.md#short-backchannel-cutoffs-and-double-interruption-silence) |
| Final digits clipped (`"98058"` -> `"98050"`) | Manual VAD closing too fast on 8 kHz PSTN audio | Add `400-500 ms` hangover padding; confirm critical digits | [Turns & Transcripts](references/troubleshooting_turns_vad.md#manual-vad-tail-clipping-and-8-khz-telephony-distortion) |
| New turn plays over old turn after barge-in | Server finished fast without emitting `interrupted: true` | Flush client playback buffer on new turn start and on `interrupted` | [Turns & Transcripts](references/troubleshooting_turns_vad.md#barge-in-playback-overlap-and-background-noise-triggers) |
| `MALFORMED_FUNCTION_CALL` on complex args | Single `STRING` parameter used as mini-DSL | Use typed `OBJECT`, `ARRAY`, `ENUM`, `BOOLEAN` properties | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#malformed_function_call-on-complex-tool-arguments) |
| Tool loops or duplicate reply on `NON_BLOCKING` tool | State machine in SI or missing `scheduling="SILENT"` | Move state machine to app layer; set `scheduling="SILENT"` | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#redundant-tool-loops-and-duplicate-non_blocking-speech) |
| Unreliable pre-tool filler on fast vs. slow tools | Per-latency-tier natural-language filler rules in SI | Call tools silently and play a client-side UI/audio cue while waiting | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#pre-tool-early-acknowledgement-filler-misfires) |
| Minimal test prompt ignored or agent invents data | Production `tools` left attached or framework context leak | Stub `tools` in tests; audit full serialized wire JSON | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#test-prompt-ignored-or-model-invents-unseen-data) |
| Stall on search grounding or ignored SI update | Undeclared `googleSearch` (incompatible with custom functions) or `clientContent` SI update | Use `googleSearch` alone or custom search tool; use `contextUpdate` on `3.8-live` | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#undeclared-google-search-deadlock-and-mid-session-si-updates) |
| Safety refusal on `custom_vocabulary` | Synthetic concatenated single-token compounds distorting ASR | Keep multi-word phrases space-delimited in `custom_vocabulary` | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#safety-refusals-on-custom_vocabulary) |
| WebSocket `1008` / `1011` / `goAway` or `429` | Unsupported `generationConfig`, timeout, or burst traffic | Audit setup fields, enable `sessionResumption`, backoff on `429` | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#websocket-1008-1011-goaway-drops-and-429-throttling) |
| `6-12s` `TTFT` spike or high multi-turn audio cost | Client 3P tool delay, regional queue, or 1:1 audio token retention | Log per-stage timestamps; compress/rotate sessions; check pricing | [Tools & Lifecycle](references/troubleshooting_tools_lifecycle.md#latency-ttft-triage) |
### Pre-Flight Configuration Rules
1. **Align voice gender with persona gender:** Match prebuilt `voiceName`
gender with `systemInstruction` persona gender so acoustic and text
conditioning do not compete.
2. **Set `speechConfig.languageCode` when pinning a regional accent or default
language:** While optional for dynamic multilingual auto-detection, omitting
it defaults the initial voice reference to `en-US` and overrides text accent
instructions. Use a supported BCP-47 code (such as `en-IN` or `es-US`).
3. **Keep `temperature >= 0.7` (default `1.0`):** Values `<= 0.3` (especially
when paired with `generationConfig.enableAffectiveDialog` on `2.5` models)
trap native-audio sampling in tonal humming loops.
4. **Keep `systemInstruction` `< 2,000` tokens and prune `tools` per turn:**
Rolling text transcripts in SI and `>40,000`-token tool declarations dilute
voice conditioning, causing `-34 dBFS` amplitude collapse and `0`-audio
turns.
5. **Write plain-spoken prose without markup:** Strip `#` Markdown headers,
`<verbatim>` / `<taskflow>` XML, Gemini-TTS `# Director's Notes`, raw IPA
`/slashes/`, and `"""` code delimiters so unspoken code or markup does not
leak into `output_transcription`.
6. **Separate prompt template blocks with `\n`:** Avoid concatenating adjacent
template sections onto a single run-on line without newline separators.
7. **Declare typed tool schemas:** Use `OBJECT`, `ARRAY`, `ENUM`, and `BOOLEAN`
instead of packing mini-DSLs into a single `STRING` argument.
8. **Set `scheduling="SILENT"` on transactional `NON_BLOCKING` responses:**
Prevents duplicate speech or `<no speech>` leaks after async tool results
(note: `gemini-3.8-live-extended-thinking-preview` does not support explicit
`FunctionResponse.scheduling`).
9. **Wait for `turnComplete`, not `generationComplete`:** Prevents sequential
`clientContent` turns from self-interrupting active playback pacing.
10. **Enable `contextWindowCompression` and `sessionResumption`:** Prevents
long-session audio drop/drift, bounds multi-turn audio token retention cost,
and recovers cleanly across `goAway`, `1000`, `1006`, and `1011`
disconnects.
attribution.md 1.8 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:gemini-live-api)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:gemini-live-api)`
in the `User-Agent` header. If a `User-Agent` header is already specified,
append this string to the end of it rather than overwriting existing
`User-Agent` data — the collection pipeline parses the
`agent-skills/<version>` and `skill:<name>` tokens, so any rewording breaks
attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:gemini-live-api)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
client_server_messages.md 25.7 KB
# Live API `ClientMessage` and `ServerMessage` Reference
This document describes the **wire-level WebSocket JSON protocol** for the
Gemini Enterprise Agent Platform Live API
(`LlmBidiService/BidiGenerateContent`).
Canonical reference docs:
- [Live API reference](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/live-api.md.txt)
- [RPC reference (`google.cloud.aiplatform.v1`)](https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rpc/google.cloud.aiplatform.v1)
- [Start and manage live sessions](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/start-manage-session.md.txt)
- [Migrate from Gemini 2.5 to Gemini 3.8 Live](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/migrate-from-gemini-2-5-to-gemini-3-8-live.md.txt)
- [Asynchronous function calling](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/asynchronous-function-calling.md.txt)
- [Configure language and voice](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/configure-language-voice.md.txt)
- [Live API best practices](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/best-practices.md.txt)
## Table of Contents
1. [Connection, Endpoints, and Models](#1-connection-endpoints-and-models): Lines 35-69
2. [Top-Level Envelopes (`ClientMessage` and `ServerMessage`)](#2-top-level-envelopes-clientmessage-and-servermessage): Lines 71-101
3. [Session Lifecycle](#3-session-lifecycle): Lines 103-134
4. [`BidiGenerateContentSetup` (`setup`)](#4-bidigeneratecontentsetup-setup): Lines 136-206
5. [`BidiGenerateContentClientContent` (`clientContent`)](#5-bidigeneratecontentclientcontent-clientcontent): Lines 208-224
6. [`BidiGenerateContentRealtimeInput` (`realtimeInput`)](#6-bidigeneratecontentrealtimeinput-realtimeinput): Lines 226-243
7. [`BidiGenerateContentToolResponse` (`toolResponse`) and Function Calling](#7-bidigeneratecontenttoolresponse-toolresponse-and-function-calling): Lines 245-264
8. [`BidiGenerateContentContextUpdate` (`contextUpdate`)](#8-bidigeneratecontentcontextupdate-contextupdate): Lines 266-279
9. [Server Messages (`setupComplete`, `serverContent`, `toolCall`, `voiceActivity`)](#9-server-messages-setupcomplete-servercontent-toolcall-voiceactivity): Lines 281-315
10. [Lifecycle and Accounting (`GoAway`, `SessionResumptionUpdate`, `UsageMetadata`)](#10-lifecycle-and-accounting-goaway-sessionresumptionupdate-usagemetadata): Lines 317-334
11. [End-to-End JSON Wire Examples](#11-end-to-end-json-wire-examples): Lines 336-420
12. [Realtime vs. Add-Context Input Cookbook](#12-realtime-vs-add-context-input-cookbook): Lines 422-484
13. [Common Pitfalls](#13-common-pitfalls): Lines 486-504
---
## 1. Connection, Endpoints, and Models
### Endpoints
| Channel | WebSocket URI | When to use |
| --- | --- | --- |
| **GA (`v1`, default)** | `wss://{LOCATION}-aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent` | Default for all standard Live API sessions (`gemini-3.8-live`, `gemini-live-2.5-flash-native-audio`, etc.). |
| **Preview (`v1beta1`)** | `wss://{LOCATION}-aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContent` | Use when configuring `v1beta1`-only tools such as Vertex RAG Engine (`retrieval.vertexRagStore`). |
> **Regional endpoints required:** Live API models only support regional
> endpoints in US and EU multi-regions (recommended default: `us-central1`; for
> example, `europe-west4` in EU). Live API models do **not** support the
> `global` endpoint (`wss://aiplatform.googleapis.com/...`).
### Authentication & Wire Framing
- **Header**: `Authorization: Bearer <ADC access token>` on the WebSocket HTTP
upgrade request (refresh before expiry and re-attach on every reconnect).
- **Wire format**: Every frame is a **JSON-serialized protobuf text message**
(UTF-8 WebSocket text frame) matching `ClientMessage` (client -> server) or
`ServerMessage` (server -> client) from `client_server_messages.proto`. Never
send binary-encoded protobuf bytes (`SerializeToString()`). When parsing
server JSON frames into `ServerMessage`, ignore unknown fields
(`ignore_unknown_fields=True` in Python `google.protobuf.json_format.Parse`)
for forward compatibility.
### Supported Models
| Model ID | Status | Key Capabilities & Behavioral Notes |
| --- | --- | --- |
| `gemini-3.8-live` | **GA (Recommended)** | Native audio I/O, VAD, affective dialog & proactive audio **always enabled by default**, `contextUpdate` (mid-session instructions/tools), `NON_BLOCKING` & `BLOCKING` function calling, custom vocabulary. |
| `gemini-live-2.5-flash-native-audio` | **GA** | Native audio I/O, transcriptions, VAD, opt-in `enableAffectiveDialog` & `proactivity.proactiveAudio`, function calling. |
| `gemini-3.5-transcribe-live-preview` | **Preview** | Dedicated low-latency speech-to-text streaming (`inputTranscription` / `interimInputTranscription`), `VERBATIM` & `SMART` modes, custom vocabulary. |
---
## 2. Top-Level Envelopes (`ClientMessage` and `ServerMessage`)
### `ClientMessage` (client -> server)
Each client frame sets **exactly one** `message_type` oneof field:
| JSON Field | Proto Type | When to use |
| --- | --- | --- |
| `setup` | `BidiGenerateContentSetup` | First frame only. Configures model, voice, tools, VAD, resumption, and transcriptions. |
| `clientContent` | `BidiGenerateContentClientContent` | Turn-based, history-bearing input (typed turns, uploaded clips/images, seeded history). Interrupts active model output. |
| `realtimeInput` | `BidiGenerateContentRealtimeInput` | Continuous, low-latency audio/video/text stream + manual VAD markers. |
| `toolResponse` | `BidiGenerateContentToolResponse` | Replies to server-issued `toolCall` requests. |
| `contextUpdate` | `BidiGenerateContentContextUpdate` | Updates `systemInstruction` and/or `tools` mid-session (`gemini-3.8-live`). |
### `ServerMessage` (server -> client)
Each server frame carries one `message_type` event (and may carry top-level
`usageMetadata`):
| JSON Field | Proto Type | Meaning |
| --- | --- | --- |
| `setupComplete` | `BidiGenerateContentSetupComplete` | Sent once after `setup` succeeds. Gate all subsequent sends on this. |
| `serverContent` | `BidiGenerateContentServerContent` | Streamed model output (`modelTurn`), `inputTranscription` / `outputTranscription` / `interimInputTranscription`, `interrupted`, `generationComplete`, `turnComplete`. |
| `toolCall` | `BidiGenerateContentToolCall` | Requests client execution of one or more `FunctionCall`s. |
| `toolCallCancellation` | `BidiGenerateContentToolCallCancellation` | Cancels previously issued `FunctionCall.id`s (typically on user barge-in). |
| `goAway` | `GoAway` | Connection will close soon (`timeLeft`, typically ~60s before the 10-minute WebSocket limit). |
| `sessionResumptionUpdate` | `SessionResumptionUpdate` | Checkpoint `newHandle` and `lastConsumedClientMessageIndex` for transparent reconnects. |
| `voiceActivity` | `VoiceActivity` | Server VAD `ACTIVITY_START` / `ACTIVITY_END` signal (when `setup.explicitVadSignal = true`). |
| `usageMetadata` | `UsageMetadata` | Token counts across prompt, candidate, thought, cached, and tool-use modalities. |
---
## 3. Session Lifecycle
```text
Client Server
|-- ClientMessage { setup } -----------------------> |
| <------------------ ServerMessage { setupComplete }|
|-- contextUpdate / clientContent / realtimeInput -> |
| <-------- serverContent (modelTurn, transcripts) --|
| <-------- serverContent { generationComplete } ----|
| <-------- serverContent { turnComplete } ----------|
| <-------- toolCall { functionCalls[] } ------------|
|-- toolResponse { functionResponses[] } ----------> |
| <-------- sessionResumptionUpdate { newHandle } ---|
| <-------- goAway { timeLeft: "60s" } --------------|
| (reconnect with setup.sessionResumption.handle) |
```
**Core protocol rules:**
1. **First frame**: Must be `setup`. Wait for `setupComplete` before sending any
`realtimeInput`, `clientContent`, `toolResponse`, or `contextUpdate`.
2. **Connection vs. session limits**: A single WebSocket connection lasts up to
**10 minutes** (`goAway` arrives ~60 seconds before termination). Without
context compression, session context is capped at **15 minutes**; enable
`contextWindowCompression.slidingWindow` + `sessionResumption` to extend
sessions indefinitely across reconnects.
3. **Mid-session instruction updates**: In `gemini-3.8-live`, `role: "system"`
in `clientContent` is **not supported**; always use `contextUpdate`.
4. **Initial history seeding**: In `gemini-3.8-live`, set
`setup.historyConfig.initialHistoryInClientContent = true` if you will send
prior conversation turns via `clientContent` after `setupComplete`.
---
## 4. `BidiGenerateContentSetup` (`setup`)
| JSON Field | Type | Notes |
| --- | --- | --- |
| `model` | `string` (required) | `projects/{project}/locations/{location}/publishers/google/models/{model_id}`. |
| `generationConfig` | `GenerationConfig` | Response modality, sampling, `speechConfig`, `mediaResolution`, `enableAffectiveDialog`. |
| `systemInstruction` | `Content` | Developer instructions (`parts[].text` only). |
| `tools[]` | repeated `Tool` | `functionDeclarations`, `googleSearch`, `codeExecution`, `urlContext`, `retrieval`, etc. Cannot mix `googleSearch` with `functionDeclarations`. |
| `sessionResumption` | `SessionResumptionConfig` | `{ handle?: string, transparent?: bool }`. Set `transparent: true` for lossless buffer replay. |
| `contextWindowCompression` | `ContextWindowCompressionConfig` | `{ triggerTokens?: int64, slidingWindow?: { targetTokens?: int64 } }`. Required for sessions >15 min. |
| `realtimeInputConfig` | `RealtimeInputConfig` | VAD sensitivity, barge-in (`activityHandling`), and `turnCoverage`. |
| `inputAudioTranscription` | `AudioTranscriptionConfig` | Enables `serverContent.inputTranscription` (and `interimInputTranscription`). Supports `languageCodes`, `customVocabulary`, `mode`. |
| `outputAudioTranscription` | `AudioTranscriptionConfig` | Enables `serverContent.outputTranscription`. |
| `explicitVadSignal` | `bool` | If `true`, server emits top-level `voiceActivity` messages on speech start/end. |
| `proactivity` | `ProactivityConfig` | `{ proactiveAudio?: bool }`. Always on in `gemini-3.8-live`; configurable on `gemini-live-2.5-flash-native-audio`. |
| `historyConfig` | `HistoryConfig` | `{ initialHistoryInClientContent?: bool }`. Set `true` when seeding history in `gemini-3.8-live`. |
| `safetySettings[]` | repeated `SafetySetting` | `{ category, threshold, method? }`. |
| `labels` | `map<string, string>` | Billing/reporting resource labels. |
### `GenerationConfig` (Live API subset)
| JSON Field | Type | Notes |
| --- | --- | --- |
| `responseModalities[]` | repeated enum | `AUDIO` (default) or `TEXT`. Pick one primary output mode per session. |
| `temperature`, `topP`, `topK`, `maxOutputTokens`, `seed` | numeric | Standard sampling controls (`temperature` 0.0–2.0). |
| `speechConfig` | `SpeechConfig` | Voice and language settings when outputting audio. |
| `mediaResolution` | enum | `MEDIA_RESOLUTION_LOW` (64 tokens), `MEDIA_RESOLUTION_MEDIUM` (256 tokens), `MEDIA_RESOLUTION_HIGH` (256 tokens + zoomed reframing). |
| `enableAffectiveDialog` | `bool` | Emotion-aware responses. Always enabled by default on `gemini-3.8-live`; opt-in on `2.5` native-audio. |
> **Unsupported in Live `setup.generationConfig`:** `responseLogprobs`,
> `responseMimeType`, `logprobs`, `responseSchema`, `stopSequences`,
> `routingConfig`, `audioTimestamp`.
### `SpeechConfig` & `VoiceConfig`
| JSON Field | Type | Notes |
| --- | --- | --- |
| `voiceConfig.prebuiltVoiceConfig.voiceName` | `string` | Case-sensitive name from the 30 prebuilt voices below (e.g., `"Aoede"`, `"Puck"`, `"Charon"`). |
| `languageCode` | `string` | Optional BCP-47 output language/accent code (e.g., `"en-US"`, `"en-IN"`, `"ja-JP"`). Native-audio models auto-detect and switch languages dynamically when omitted; set explicitly to pin a specific regional accent or default session language so setup does not fall back to `"en-US"`. |
**30 Prebuilt Voices** (case-sensitive; see [Configure language and voice](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/configure-language-voice.md.txt)):
`Zephyr`, `Puck`, `Charon`, `Kore`, `Fenrir`, `Leda`, `Orus`, `Aoede`,
`Callirrhoe`, `Autonoe`, `Enceladus`, `Iapetus`, `Umbriel`, `Algieba`,
`Despina`, `Erinome`, `Algenib`, `Rasalgethi`, `Laomedeia`, `Achernar`,
`Alnilam`, `Schedar`, `Gacrux`, `Pulcherrima`, `Achird`, `Zubenelgenubi`,
`Vindemiatrix`, `Sadachbia`, `Sadaltager`, `Sulafat`.
### `AudioTranscriptionConfig`
Pass `{}` to enable default verbatim transcription, or customize:
- `languageCodes[]`: BCP-47 hints (e.g., `["en-US", "es-US"]`); omit for
auto-detection.
- `customVocabulary[]`: Up to 1,000 domain-specific terms, product names, or
acronyms to bias speech recognition (`gemini-3.8-live` and
`gemini-3.5-transcribe-live-preview`).
- `mode`: `VERBATIM` (default) or `SMART` (disfluency removal and formatting).
### `RealtimeInputConfig` and `AutomaticActivityDetection`
- `automaticActivityDetection`: Configures `disabled`,
`startOfSpeechSensitivity` (`START_SENSITIVITY_HIGH` or `LOW`),
`endOfSpeechSensitivity` (`END_SENSITIVITY_HIGH` or `LOW`),
`prefixPaddingMs`, and `silenceDurationMs`. Server-side VAD is enabled when
`disabled` is unset or `false`.
- `activityHandling`: `START_OF_ACTIVITY_INTERRUPTS` (default barge-in) or
`NO_INTERRUPTION`.
- `turnCoverage`: `TURN_INCLUDES_ALL_INPUT` (default) or
`TURN_INCLUDES_ONLY_ACTIVITY`.
---
## 5. `BidiGenerateContentClientContent` (`clientContent`)
Appends discrete `Content` turns (`role: "user"` or `"model"`) to session
history.
| JSON Field | Type | Notes |
| --- | --- | --- |
| `turns[]` | repeated `Content` | Ordered oldest -> newest. In `gemini-3.8-live`, `role: "system"` is rejected (use `contextUpdate`). |
| `turnComplete` | `bool` | `true` starts generation immediately; `false` buffers context without generating yet. |
> **Seeding initial history (`gemini-3.8-live`):** Set
> `setup.historyConfig.initialHistoryInClientContent = true` in `setup`, wait
> for `setupComplete`, and send prior turns in `clientContent` (`turnComplete:
> false` if seeding silently before starting live audio, or `true` to prompt an
> immediate reply).
---
## 6. `BidiGenerateContentRealtimeInput` (`realtimeInput`)
Continuous, low-latency streaming input. Set **one** payload field per frame:
| JSON Field | Type | Notes |
| --- | --- | --- |
| `audio` | `Blob` | `mimeType: "audio/pcm;rate=16000"` (16-bit signed, 16 kHz, mono, little-endian PCM, ~20–100 ms chunks). |
| `video` | `Blob` | Sampled image frames (`image/jpeg`, `image/png`, `image/webp`) at ~1 fps. Do not send MP4/WebM containers. |
| `text` | `string` | Low-latency text input streamed into the active session. |
| `audioStreamEnd` | `bool` | Flushes cached audio when the mic is muted/stopped (auto-VAD enabled only). |
| `activityStart` / `activityEnd` | `{}` | Manual utterance boundaries (only valid when `automaticActivityDetection.disabled: true`). |
| `mediaChunks[]` | repeated `Blob` | **Deprecated.** Use `audio` or `video` instead. |
**Audio I/O formats:** Input is **16 kHz** 16-bit signed mono PCM
(`audio/pcm;rate=16000`); model audio output in `serverContent.modelTurn` is
**24 kHz** 16-bit signed mono PCM (`audio/pcm;rate=24000`).
---
## 7. `BidiGenerateContentToolResponse` (`toolResponse`) and Function Calling
Declare functions in `setup.tools[].functionDeclarations[]` (or update via
`contextUpdate`). When the server sends `toolCall`, reply via `toolResponse`
(never `clientContent`):
| Message / Field | Values & Behavior |
| --- | --- |
| `FunctionDeclaration.behavior` | `NON_BLOCKING` (Live API default: model keeps speaking/listening while tool executes asynchronously) \| `BLOCKING` (`gemini-3.8-live`: pauses conversation until `toolResponse` arrives; canceled via `toolCallCancellation` if user barges in). |
| `FunctionResponse.id` | Must match the originating `FunctionCall.id`. |
| `FunctionResponse.scheduling` | Controls `NON_BLOCKING` delivery: `WHEN_IDLE` (default — waits until model finishes speaking), `INTERRUPT` (interrupts model output; if user is currently speaking in `gemini-3.8-live`, waits for user to finish), or `SILENT` (adds to context without generating). Note: `gemini-3.8-live-extended-thinking-preview` does not support explicit `FunctionResponse.scheduling`. |
| `FunctionResponse.parts[]` | Optional multimodal blobs/URIs (`inlineData` / `fileData`) alongside `response` JSON. |
> **Critical `gemini-3.8-live` anti-retry rule:** `gemini-3.8-live` actively
> retries or sweeps parameters 2–5x when a tool returns an empty or ambiguous
> payload like `{}` or `{"results": []}`. Always return structured status fields
> (`status`, `retryable: false`, and an explanatory `message` on empty/error
> results, or `status: "ok"` on success) and cap retries in `systemInstruction`.
---
## 8. `BidiGenerateContentContextUpdate` (`contextUpdate`)
Updates session preamble mid-stream in order with other inputs
(`gemini-3.8-live`):
| JSON Field | Type | Behavior |
| --- | --- | --- |
| `systemInstruction` | `Content` | Replaces `setup.systemInstruction`. Omit to keep existing instructions. |
| `tools` | `{ tools?: Tool[] }` | Wrapper message: omit `tools` to keep existing tools; set `"tools": {"tools": [...]}` to replace tools; set `"tools": {}` (or `{"tools": []}`) to clear all tools. |
> Updating `systemInstruction` or `tools` invalidates the server prefix cache;
> send `contextUpdate` only when instructions or tools actually change.
---
## 9. Server Messages (`setupComplete`, `serverContent`, `toolCall`, `voiceActivity`)
### `BidiGenerateContentSetupComplete` (`setupComplete`)
- `{ "sessionId": "..." }` — confirms session initialization; gate all client
sends on receiving this message.
### `BidiGenerateContentServerContent` (`serverContent`)
| JSON Field | Type | Notes |
| --- | --- | --- |
| `modelTurn` | `Content` | Streamed model parts (`inlineData` 24 kHz PCM audio, `text`, or `thought: true` reasoning parts). |
| `generationComplete` | `bool` | Model finished generating tokens/audio for this turn (client playback buffer may still be draining). |
| `turnComplete` | `bool` | Logical end of the turn. |
| `turnCompleteReason` | enum | Reason turn ended (e.g., `NEED_MORE_INPUT`, `MALFORMED_FUNCTION_CALL`, `RESPONSE_REJECTED`, or safety enums). |
| `interrupted` | `bool` | User barged in — immediately stop audio playback, clear queued audio/unrendered transcript buffers, and close the active bubble. |
| `inputTranscription` | `Transcription` | `{ text, finished }`. Finalized/chunked user speech transcript. |
| `interimInputTranscription` | `Transcription` | `{ text, finished }`. Low-latency interim hypothesis updated while the user is still speaking. |
| `outputTranscription` | `Transcription` | `{ text, finished }`. Streamed transcript of model speech. |
| `speechState` | enum | `SPEECH` \| `NON_SPEECH` transitions on `realtimeInput.audio`. |
| `interactionStatus` | enum | Sent alongside `turnComplete`: `IN_PROGRESS` (background tool/reasoning still active) \| `IDLE` (all processing done). |
| `groundingMetadata` | object | Search / grounding citations when grounding tools are active. |
### `BidiGenerateContentToolCall` (`toolCall`) and `BidiGenerateContentToolCallCancellation` (`toolCallCancellation`)
- `toolCall.functionCalls[]`: `{ id, name, args }`.
- `toolCallCancellation.ids[]`: Stop in-flight work for these `id`s and do
**not** send `toolResponse` for them.
### `VoiceActivity` (`voiceActivity`)
- `{ "type": "ACTIVITY_START" | "ACTIVITY_END", "audioOffset": "3.240s" }` —
emitted when `setup.explicitVadSignal = true`.
---
## 10. Lifecycle and Accounting (`GoAway`, `SessionResumptionUpdate`, `UsageMetadata`)
- **`GoAway`**: `{ "timeLeft": "60s" }`. Proactively open a new WebSocket and
resume using the latest `SessionResumptionUpdate.newHandle`.
- **`SessionResumptionUpdate`**: Carries `newHandle`, `resumable`, and
`lastConsumedClientMessageIndex`. When `setup.sessionResumption.transparent =
true`, prune buffered client messages up to `lastConsumedClientMessageIndex`.
- **`UsageMetadata`**:
- Token counters: `promptTokenCount`, `candidatesTokenCount`,
`totalTokenCount`, `toolUsePromptTokenCount`, `thoughtsTokenCount`,
`cachedContentTokenCount`.
- Per-modality breakdowns (`ModalityTokenCount[]` with `modality` and
`tokenCount`): `promptTokensDetails`, `cacheTokensDetails`,
`candidatesTokensDetails`, `toolUsePromptTokensDetails`.
- `trafficType`: `ON_DEMAND`, `PROVISIONED_THROUGHPUT`,
`ON_DEMAND_PRIORITY`, etc.
---
## 11. End-to-End JSON Wire Examples
### Session `setup` (`gemini-3.8-live` with transparent resumption, custom vocabulary & async tool)
```json
{
"setup": {
"model": "projects/my-proj/locations/us-central1/publishers/google/models/gemini-3.8-live",
"generationConfig": {
"responseModalities": ["AUDIO"],
"speechConfig": {
"voiceConfig": { "prebuiltVoiceConfig": { "voiceName": "Aoede" } }
}
},
"systemInstruction": {
"parts": [{ "text": "You are a concise voice assistant. Retry failed tools at most once." }]
},
"tools": [{
"functionDeclarations": [{
"name": "lookup_order",
"description": "Looks up order status by ID.",
"behavior": "NON_BLOCKING",
"parametersJsonSchema": {
"type": "object",
"properties": { "order_id": { "type": "string" } },
"required": ["order_id"]
}
}]
}],
"sessionResumption": { "transparent": true },
"contextWindowCompression": {
"triggerTokens": "100000",
"slidingWindow": { "targetTokens": "50000" }
},
"inputAudioTranscription": {
"customVocabulary": ["Cloud Run", "GKE", "AlloyDB"]
},
"outputAudioTranscription": {},
"historyConfig": { "initialHistoryInClientContent": true }
}
}
```
### Mid-session `contextUpdate`
```json
{
"contextUpdate": {
"systemInstruction": {
"parts": [{ "text": "Switch to Spanish and keep answers under two sentences." }]
}
}
}
```
### Async `toolCall` & structured `toolResponse`
```json
// Server -> client
{
"toolCall": {
"functionCalls": [
{ "id": "call_1", "name": "lookup_order", "args": { "order_id": "ORD-99" } }
]
}
}
// Client -> server
{
"toolResponse": {
"functionResponses": [{
"id": "call_1",
"name": "lookup_order",
"scheduling": "WHEN_IDLE",
"response": {
"status": "ok",
"retryable": false,
"order": { "id": "ORD-99", "eta": "2026-11-08" }
}
}]
}
}
```
---
## 12. Realtime vs. Add-Context Input Cookbook
Choose the input envelope based on whether you are streaming live media or
appending discrete turns:
| Aspect | `realtimeInput` | `clientContent` |
| --- | --- | --- |
| **Use case** | Live mic, camera/screen frames (~1 fps), push-to-talk | Typed chat turns, seeding history, discrete audio/image uploads |
| **Turn boundary** | Server VAD (default) or `activityStart` / `activityEnd` | Explicit `turnComplete: true` |
| **Barge-in effect** | Controlled by `realtimeInputConfig.activityHandling` | Immediately interrupts active model output |
### A. `realtimeInput` payloads
```json
// 1. Continuous mic chunk (16 kHz, 16-bit mono PCM)
{ "realtimeInput": { "audio": { "mimeType": "audio/pcm;rate=16000", "data": "<base64-pcm>" } } }
// 2. Mic muted / stream paused (auto-VAD enabled)
{ "realtimeInput": { "audioStreamEnd": true } }
// 3. Manual VAD utterance (requires automaticActivityDetection.disabled = true in setup)
{ "realtimeInput": { "activityStart": {} } }
{ "realtimeInput": { "audio": { "mimeType": "audio/pcm;rate=16000", "data": "<base64-pcm>" } } }
{ "realtimeInput": { "activityEnd": {} } }
// 4. Camera / screen frame (~1 fps JPEG/PNG/WebP)
{ "realtimeInput": { "video": { "mimeType": "image/jpeg", "data": "<base64-jpeg>" } } }
// 5. Realtime text
{ "realtimeInput": { "text": "Focus on the top-right chart." } }
```
### B. `clientContent` payloads
```json
// 1. Seeded multi-turn history (requires historyConfig.initialHistoryInClientContent = true on 3.8-live)
{
"clientContent": {
"turns": [
{ "role": "user", "parts": [{ "text": "Hi, my name is Sam." }] },
{ "role": "model", "parts": [{ "text": "Hello Sam! How can I help?" }] }
],
"turnComplete": false
}
}
// 2. Discrete user text + inline image + Cloud Storage URI
{
"clientContent": {
"turns": [{
"role": "user",
"parts": [
{ "text": "Compare this screenshot with the reference diagram:" },
{ "inlineData": { "mimeType": "image/jpeg", "data": "<base64-jpeg>" } },
{ "fileData": { "mimeType": "application/pdf", "fileUri": "gs://my-bucket/spec.pdf" } }
]
}],
"turnComplete": true
}
}
```
---
## 13. Common Pitfalls
- **Sending binary protobuf frames** — the WebSocket accepts UTF-8 JSON text
frames only (`MessageToJson` / `Parse`).
- **Using the `global` endpoint** — Live API models require a regional endpoint
such as `us-central1`.
- **Sending frames before `setupComplete`** — causes immediate connection close.
- **Using `role: "system"` in `clientContent` on `gemini-3.8-live`** — rejected;
use `contextUpdate` instead.
- **Seeding history without `historyConfig.initialHistoryInClientContent: true`**
— required on `gemini-3.8-live`.
- **Returning `{}` in `FunctionResponse.response`** — causes `gemini-3.8-live`
to retry/sweep tool arguments; always return `status`, `retryable`, and
`message`.
- **Combining `googleSearch` and `functionDeclarations`** — unsupported in the
same `setup.tools` list.
- **Ignoring `interrupted: true` or `Transcription.finished`** — flush queued
24 kHz playback audio immediately on `interrupted: true`, and close/rotate UI
transcript bubbles when `finished: true` arrives.
client_server_messages.proto 18.6 KB
// Proto definitions for the Gemini Enterprise Agent Platform Live API wire
// protocol (`LlmBidiService/BidiGenerateContent`), derived from the public
// documentation:
// - https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/models/live-api
// - https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rpc/google.cloud.aiplatform.v1
//
// Always serialize and parse WebSocket frames as UTF-8 JSON text (e.g.,
// `google.protobuf.json_format.MessageToJson` and
// `Parse(..., ignore_unknown_fields=True)` in Python), never as binary protobuf
// bytes. Field numbers below are sequential local identifiers; only JSON field
// names and enum names appear on the WebSocket wire.
syntax = "proto3";
package google.ai.live.v1;
import "google/protobuf/duration.proto";
import "google/protobuf/struct.proto";
option java_multiple_files = true;
// =============================================================================
// Top-level envelopes
// =============================================================================
// Client -> server WebSocket frame (`BidiGenerateContentClientMessage`).
// Exactly one field in `message_type` must be set per frame.
message ClientMessage {
oneof message_type {
// First frame only. Configures the session.
BidiGenerateContentSetup setup = 1;
// Turn-based, history-bearing input. Interrupts ongoing model generation.
BidiGenerateContentClientContent client_content = 2;
// Continuous, low-latency audio/video/text input.
BidiGenerateContentRealtimeInput realtime_input = 3;
// Reply to a server-issued `tool_call`.
BidiGenerateContentToolResponse tool_response = 4;
// Mid-session update to `system_instruction` or `tools`
// (`gemini-3.8-live`).
BidiGenerateContentContextUpdate context_update = 5;
}
}
// Server -> client WebSocket frame (`BidiGenerateContentServerMessage`).
message ServerMessage {
oneof message_type {
// Sent once after `setup` is accepted. Gate all subsequent sends on this.
BidiGenerateContentSetupComplete setup_complete = 1;
// Streamed model output (audio/text), transcriptions, turn lifecycle.
BidiGenerateContentServerContent server_content = 2;
// Model is requesting tool execution.
BidiGenerateContentToolCall tool_call = 3;
// Cancels previously issued tool calls (e.g., on user barge-in).
BidiGenerateContentToolCallCancellation tool_call_cancellation = 4;
// Connection will be terminated soon (typically ~60s warning).
GoAway go_away = 5;
// Checkpoint handle for transparent session resumption.
SessionResumptionUpdate session_resumption_update = 6;
// Server-side VAD signal emitted when `setup.explicit_vad_signal = true`.
VoiceActivity voice_activity = 7;
}
// Token usage accounting for the session / turn.
UsageMetadata usage_metadata = 8;
}
// =============================================================================
// Common content & tool primitives
// =============================================================================
// Inline binary media payload (audio chunk, image frame, etc.).
message Blob {
// IANA MIME type, e.g., "audio/pcm;rate=16000" or "image/jpeg".
string mime_type = 1;
// Raw bytes (base64-encoded on the JSON wire).
bytes data = 2;
// Optional display name for the blob.
string display_name = 3;
}
// Reference to a remote file (e.g., Cloud Storage `gs://` URI).
message FileData {
string mime_type = 1;
string file_uri = 2;
string display_name = 3;
}
// Code generated by the model when the `code_execution` tool is enabled.
message ExecutableCode {
enum Language {
LANGUAGE_UNSPECIFIED = 0;
PYTHON = 1;
}
Language language = 1;
string code = 2;
optional string id = 3;
}
// Output of server-side execution of `ExecutableCode`.
message CodeExecutionResult {
enum Outcome {
OUTCOME_UNSPECIFIED = 0;
OUTCOME_OK = 1;
OUTCOME_FAILED = 2;
OUTCOME_DEADLINE_EXCEEDED = 3;
}
Outcome outcome = 1;
string output = 2;
optional string id = 3;
}
// A function call requested by the model.
message FunctionCall {
// Unique call ID; echo in the matching `FunctionResponse.id`.
string id = 1;
string name = 2;
google.protobuf.Struct args = 3;
}
// Media payload carried inside a multimodal `FunctionResponse`.
message FunctionResponseBlob {
string mime_type = 1;
bytes data = 2;
string display_name = 3;
}
// URI reference carried inside a multimodal `FunctionResponse`.
message FunctionResponseFileData {
string mime_type = 1;
string file_uri = 2;
string display_name = 3;
}
// Multimodal part inside `FunctionResponse.parts`.
message FunctionResponsePart {
oneof data {
FunctionResponseBlob inline_data = 1;
FunctionResponseFileData file_data = 2;
}
}
// Result of executing a `FunctionCall`.
message FunctionResponse {
// Controls how a `NON_BLOCKING` function response is scheduled into the turn.
enum Scheduling {
SCHEDULING_UNSPECIFIED = 0;
// Add result to context only; do not interrupt or trigger generation.
SILENT = 1;
// Wait until current generation/speech finishes, then generate a response.
WHEN_IDLE = 2;
// Interrupt ongoing model output and immediately generate a response.
INTERRUPT = 3;
}
// Must match the originating `FunctionCall.id`.
string id = 1;
string name = 2;
google.protobuf.Struct response = 3;
repeated FunctionResponsePart parts = 4;
// Only applicable to `NON_BLOCKING` function calls. Defaults to `WHEN_IDLE`.
optional Scheduling scheduling = 5;
}
// Single content part within a `Content` turn.
message Part {
oneof data {
string text = 1;
Blob inline_data = 2;
FileData file_data = 3;
FunctionCall function_call = 4;
FunctionResponse function_response = 5;
ExecutableCode executable_code = 6;
CodeExecutionResult code_execution_result = 7;
}
// True if this part represents model thought/reasoning text.
bool thought = 8;
bytes thought_signature = 9;
}
// Conversation turn with role ("user" or "model") and ordered parts.
message Content {
string role = 1;
repeated Part parts = 2;
}
// Declaration of a client-executed function tool.
message FunctionDeclaration {
enum Behavior {
UNSPECIFIED = 0;
// Pause conversation until `FunctionResponse` arrives (`gemini-3.8-live`).
BLOCKING = 1;
// Continue conversation asynchronously while tool runs (Live API default).
NON_BLOCKING = 2;
}
string name = 1;
string description = 2;
// OpenAPI 3.0 Schema object (mutually exclusive with
// `parameters_json_schema`).
google.protobuf.Struct parameters = 3;
// Standard JSON Schema object for parameters.
google.protobuf.Value parameters_json_schema = 4;
// OpenAPI 3.0 response Schema object (mutually exclusive with
// `response_json_schema`).
google.protobuf.Struct response = 5;
// Standard JSON Schema object for response.
google.protobuf.Value response_json_schema = 6;
// Execution mode in `BidiGenerateContent` (`NON_BLOCKING` or `BLOCKING`).
optional Behavior behavior = 7;
}
// Tool configuration entry. Set at most one tool type per `Tool` message.
// Note: Search tools (`google_search`) cannot be combined with
// `function_declarations` in Live API setup.
message Tool {
message GoogleSearch {
repeated string exclude_domains = 1;
}
message CodeExecution {}
message UrlContext {}
repeated FunctionDeclaration function_declarations = 1;
// Retrieval config (e.g., Vertex RAG Store on `v1beta1`).
google.protobuf.Struct retrieval = 2;
GoogleSearch google_search = 3;
google.protobuf.Struct google_maps = 4;
google.protobuf.Struct enterprise_web_search = 5;
CodeExecution code_execution = 6;
UrlContext url_context = 7;
}
// =============================================================================
// Safety settings
// =============================================================================
enum HarmCategory {
HARM_CATEGORY_UNSPECIFIED = 0;
HARM_CATEGORY_HATE_SPEECH = 1;
HARM_CATEGORY_DANGEROUS_CONTENT = 2;
HARM_CATEGORY_HARASSMENT = 3;
HARM_CATEGORY_SEXUALLY_EXPLICIT = 4;
HARM_CATEGORY_CIVIC_INTEGRITY = 5 [deprecated = true];
HARM_CATEGORY_IMAGE_HATE = 6;
HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 7;
HARM_CATEGORY_IMAGE_HARASSMENT = 8;
HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 9;
HARM_CATEGORY_JAILBREAK = 10;
}
message SafetySetting {
enum HarmBlockThreshold {
HARM_BLOCK_THRESHOLD_UNSPECIFIED = 0;
BLOCK_LOW_AND_ABOVE = 1;
BLOCK_MEDIUM_AND_ABOVE = 2;
BLOCK_ONLY_HIGH = 3;
BLOCK_NONE = 4;
OFF = 5;
}
enum HarmBlockMethod {
HARM_BLOCK_METHOD_UNSPECIFIED = 0;
SEVERITY = 1;
PROBABILITY = 2;
}
HarmCategory category = 1;
HarmBlockThreshold threshold = 2;
HarmBlockMethod method = 3;
}
// =============================================================================
// Session setup (`BidiGenerateContentSetup`)
// =============================================================================
message BidiGenerateContentSetup {
// Required. Format:
// "projects/{project}/locations/{location}/publishers/google/models/{model}"
string model = 1;
GenerationConfig generation_config = 2;
// Developer / system instructions (text parts only).
Content system_instruction = 3;
repeated Tool tools = 4;
SessionResumptionConfig session_resumption = 5;
ContextWindowCompressionConfig context_window_compression = 6;
RealtimeInputConfig realtime_input_config = 7;
AudioTranscriptionConfig input_audio_transcription = 8;
AudioTranscriptionConfig output_audio_transcription = 9;
// If true, server emits top-level `voice_activity` frames on VAD transitions.
bool explicit_vad_signal = 10;
// Proactive audio configuration (always on in `gemini-3.8-live`; opt-in on
// `gemini-live-2.5-flash-native-audio`).
ProactivityConfig proactivity = 11;
// Conversation history configuration (set
// `initial_history_in_client_content = true` when seeding prior turns).
HistoryConfig history_config = 12;
repeated SafetySetting safety_settings = 13;
// User-defined billing/reporting labels.
map<string, string> labels = 14;
}
message GenerationConfig {
enum Modality {
MODALITY_UNSPECIFIED = 0;
TEXT = 1;
IMAGE = 2;
AUDIO = 3;
VIDEO = 4;
}
enum MediaResolution {
MEDIA_RESOLUTION_UNSPECIFIED = 0;
MEDIA_RESOLUTION_LOW = 1;
MEDIA_RESOLUTION_MEDIUM = 2;
MEDIA_RESOLUTION_HIGH = 3;
}
optional float temperature = 1;
optional float top_p = 2;
optional float top_k = 3;
optional int32 candidate_count = 4;
optional int32 max_output_tokens = 5;
optional float presence_penalty = 6;
optional float frequency_penalty = 7;
optional int32 seed = 8;
// Response modality for the session: typically `[AUDIO]` (default) or
// `[TEXT]`.
repeated Modality response_modalities = 9;
optional MediaResolution media_resolution = 10;
optional SpeechConfig speech_config = 11;
reserved 12;
// Enables emotion-aware responses (always on in `gemini-3.8-live`; opt-in on
// `gemini-live-2.5-flash-native-audio`).
optional bool enable_affective_dialog = 13;
}
message SpeechConfig {
// Single-speaker voice configuration (Live API is single-speaker only).
VoiceConfig voice_config = 1;
// BCP-47 language code (e.g., "en-US", "en-IN").
string language_code = 2;
}
message VoiceConfig {
oneof voice_config {
PrebuiltVoiceConfig prebuilt_voice_config = 1;
}
}
message PrebuiltVoiceConfig {
// Case-sensitive prebuilt voice name (e.g., "Aoede", "Puck", "Charon").
string voice_name = 1;
}
message ProactivityConfig {
optional bool proactive_audio = 1;
}
message HistoryConfig {
// Must be set to `true` in `gemini-3.8-live` when seeding prior conversation
// history via `client_content`.
bool initial_history_in_client_content = 1;
}
message AudioTranscriptionConfig {
enum Mode {
MODE_UNSPECIFIED = 0;
VERBATIM = 1;
SMART = 2;
}
// Optional BCP-47 language hints; omit for automatic language detection.
repeated string language_codes = 1;
// Domain-specific terms/phrases (up to 1,000) to bias speech recognition.
repeated string custom_vocabulary = 2;
// Transcription mode (`VERBATIM` default or `SMART` cleanup).
Mode mode = 3;
}
message SessionResumptionConfig {
// Previous session handle from `SessionResumptionUpdate.new_handle`.
optional string handle = 1;
// Enables `last_consumed_client_message_index` in resumption updates.
bool transparent = 2;
}
message ContextWindowCompressionConfig {
message SlidingWindow {
optional int64 target_tokens = 1;
}
optional int64 trigger_tokens = 1;
oneof compression_mechanism {
SlidingWindow sliding_window = 2;
}
}
message RealtimeInputConfig {
enum ActivityHandling {
ACTIVITY_HANDLING_UNSPECIFIED = 0;
START_OF_ACTIVITY_INTERRUPTS = 1;
NO_INTERRUPTION = 2;
}
enum TurnCoverage {
TURN_COVERAGE_UNSPECIFIED = 0;
TURN_INCLUDES_ONLY_ACTIVITY = 1;
TURN_INCLUDES_ALL_INPUT = 2;
}
message AutomaticActivityDetection {
enum StartSensitivity {
START_SENSITIVITY_UNSPECIFIED = 0;
START_SENSITIVITY_HIGH = 1;
START_SENSITIVITY_LOW = 2;
}
enum EndSensitivity {
END_SENSITIVITY_UNSPECIFIED = 0;
END_SENSITIVITY_HIGH = 1;
END_SENSITIVITY_LOW = 2;
}
optional bool disabled = 1;
StartSensitivity start_of_speech_sensitivity = 2;
EndSensitivity end_of_speech_sensitivity = 3;
int32 prefix_padding_ms = 4;
int32 silence_duration_ms = 5;
}
AutomaticActivityDetection automatic_activity_detection = 1;
optional ActivityHandling activity_handling = 2;
optional TurnCoverage turn_coverage = 3;
}
// =============================================================================
// Post-setup client messages
// =============================================================================
message BidiGenerateContentClientContent {
repeated Content turns = 1;
bool turn_complete = 2;
}
message BidiGenerateContentRealtimeInput {
message ActivityStart {}
message ActivityEnd {}
// Deprecated: prefer typed `audio`, `video`, or `text` fields below.
repeated Blob media_chunks = 1 [deprecated = true];
// Realtime audio stream (`audio/pcm;rate=16000`, 16-bit signed mono PCM).
Blob audio = 2;
// Realtime video/screen frame (`image/jpeg`, `image/png`, or `image/webp`).
Blob video = 3;
// Manual VAD markers (only valid when `automatic_activity_detection.disabled`
// is `true`).
ActivityStart activity_start = 4;
ActivityEnd activity_end = 5;
// Signals microphone turned off (only valid when auto-VAD is enabled).
optional bool audio_stream_end = 6;
// Realtime text input.
optional string text = 7;
}
message BidiGenerateContentToolResponse {
repeated FunctionResponse function_responses = 1;
}
// Mid-session update to `system_instruction` and/or `tools`.
message BidiGenerateContentContextUpdate {
// Wrapper distinguishing "leave tools unchanged" (unset) from "clear all
// tools" (`tools: {}` / empty list).
message Tools {
repeated Tool tools = 1;
}
Tools tools = 1;
Content system_instruction = 2;
}
// =============================================================================
// Server messages
// =============================================================================
message BidiGenerateContentSetupComplete {
optional string session_id = 1;
}
message BidiGenerateContentServerContent {
message Transcription {
string text = 1;
bool finished = 2;
}
enum TurnCompleteReason {
TURN_COMPLETE_REASON_UNSPECIFIED = 0;
MALFORMED_FUNCTION_CALL = 1;
RESPONSE_REJECTED = 2;
NEED_MORE_INPUT = 3;
PROHIBITED_INPUT_CONTENT = 4;
IMAGE_PROHIBITED_INPUT_CONTENT = 5;
INPUT_TEXT_CONTAIN_PROMINENT_PERSON_PROHIBITED = 6;
INPUT_IMAGE_CELEBRITY = 7;
INPUT_IMAGE_PHOTO_REALISTIC_CHILD_PROHIBITED = 8;
INPUT_TEXT_NCII_PROHIBITED = 9;
INPUT_OTHER = 10;
INPUT_IP_PROHIBITED = 11;
BLOCKLIST = 12;
UNSAFE_PROMPT_FOR_IMAGE_GENERATION = 13;
GENERATED_IMAGE_SAFETY = 14;
GENERATED_CONTENT_SAFETY = 15;
GENERATED_AUDIO_SAFETY = 16;
GENERATED_VIDEO_SAFETY = 17;
GENERATED_CONTENT_PROHIBITED = 18;
GENERATED_CONTENT_BLOCKLIST = 19;
GENERATED_IMAGE_PROHIBITED = 20;
GENERATED_IMAGE_CELEBRITY = 21;
GENERATED_IMAGE_PROMINENT_PEOPLE_DETECTED_BY_REWRITER = 22;
GENERATED_IMAGE_IDENTIFIABLE_PEOPLE = 23;
GENERATED_IMAGE_MINORS = 24;
OUTPUT_IMAGE_IP_PROHIBITED = 25;
GENERATED_OTHER = 26;
MAX_REGENERATION_REACHED = 27;
}
enum SpeechState {
SPEECH_STATE_UNSPECIFIED = 0;
NON_SPEECH = 1;
SPEECH = 2;
}
enum InteractionStatus {
INTERACTION_STATUS_UNSPECIFIED = 0;
IN_PROGRESS = 1;
REQUIRES_ACTION = 2 [deprecated = true];
IDLE = 3;
}
optional Content model_turn = 1;
bool turn_complete = 2;
bool interrupted = 3;
bool generation_complete = 4;
google.protobuf.Struct grounding_metadata = 5;
Transcription input_transcription = 6;
Transcription output_transcription = 7;
TurnCompleteReason turn_complete_reason = 8;
SpeechState speech_state = 9;
Transcription interim_input_transcription = 10;
InteractionStatus interaction_status = 11;
}
message BidiGenerateContentToolCall {
repeated FunctionCall function_calls = 1;
}
message BidiGenerateContentToolCallCancellation {
repeated string ids = 1;
}
// =============================================================================
// Lifecycle, VAD & token accounting
// =============================================================================
message GoAway {
google.protobuf.Duration time_left = 1;
}
message SessionResumptionUpdate {
string new_handle = 1;
bool resumable = 2;
int64 last_consumed_client_message_index = 3;
}
message VoiceActivity {
enum Type {
TYPE_UNSPECIFIED = 0;
ACTIVITY_START = 1;
ACTIVITY_END = 2;
}
Type type = 1;
google.protobuf.Duration audio_offset = 2;
}
enum Modality {
MODALITY_UNSPECIFIED = 0;
TEXT = 1;
IMAGE = 2;
VIDEO = 3;
AUDIO = 4;
DOCUMENT = 5;
}
message ModalityTokenCount {
Modality modality = 1;
int32 token_count = 2;
}
message UsageMetadata {
enum TrafficType {
TRAFFIC_TYPE_UNSPECIFIED = 0;
ON_DEMAND = 1;
ON_DEMAND_PRIORITY = 2;
ON_DEMAND_FLEX = 3;
PROVISIONED_THROUGHPUT = 4;
}
int32 prompt_token_count = 1;
int32 candidates_token_count = 2;
int32 total_token_count = 3;
int32 tool_use_prompt_token_count = 4;
int32 thoughts_token_count = 5;
int32 cached_content_token_count = 6;
repeated ModalityTokenCount prompt_tokens_details = 7;
repeated ModalityTokenCount cache_tokens_details = 8;
repeated ModalityTokenCount candidates_tokens_details = 9;
repeated ModalityTokenCount tool_use_prompt_tokens_details = 10;
TrafficType traffic_type = 11;
}
session_manager.md 6.1 KB
# Live API Session Manager
This document guides the implementation of a `SessionManager` class for the
Gemini Enterprise Agent Platform Live API over WebSockets. It ensures robust
handling of connection rotation, unexpected disconnections, and lossless
transparent session resumption.
## Table of Contents
- [Core Responsibilities](#core-responsibilities): Lines 15-24
- [Protocol and Limits](#protocol-and-limits): Lines 26-40
- [Session Resumption Logic](#session-resumption-logic): Lines 42-115
- [Gotchas](#gotchas): Lines 117-126
## Core Responsibilities
1. **Connection Management**: Maintain a continuous WebSocket connection to the
regional Live API endpoint until explicitly stopped.
2. **Bidirectional Communication**: Handle sending and receiving JSON text
frames concurrently (using separate async tasks, coroutines, or threads)
gated on `setup_complete`.
3. **Transparent Session Resumption**: Automatically reconnect, refresh ADC
bearer tokens if needed, and replay unconsumed messages without losing
in-flight audio, video, tool responses, or context updates.
## Protocol and Limits
- **Proto File**: `client_server_messages.proto`
- **Client Envelope**: `ClientMessage` (`BidiGenerateContentClientMessage`)
- **Server Envelope**: `ServerMessage` (`BidiGenerateContentServerMessage`)
- **Wire Serialization**: UTF-8 JSON text frames via Protobuf JSON mapping
(e.g., `MessageToJson` and `Parse(..., ignore_unknown_fields=True)`).
- **Duration Limits**:
- **WebSocket connection lifetime (~10 minutes)**: The server sends a
`go_away` frame (`time_left` typically ~60s) before closing the socket.
- **Session context limit (~15 minutes uncompressed)**: For long-running
sessions (>15 minutes), also configure
`setup.context_window_compression.sliding_window` alongside
`setup.session_resumption` so session context does not hit the token/time
ceiling across reconnects.
## Session Resumption Logic
### 1. Enable Transparent Session Resumption
In the initial `ClientMessage.setup` (`BidiGenerateContentSetup`), always set
`session_resumption.transparent = true` (`SessionResumptionConfig`). This
instructs the server to emit `last_consumed_client_message_index` inside
`SessionResumptionUpdate` frames so the client knows which buffered frames have
been committed to session state.
### 2. Track Session Handle Updates
Listen for `session_resumption_update` frames from the server:
- Whenever `resumable` is `true` and `new_handle` is non-empty, store
`new_handle` as the latest resumption token.
- Note that during active generation or tool execution, the server may emit
`resumable: false` with an empty `new_handle`; retain the most recent valid
`new_handle` rather than overwriting it with an empty string.
### 3. Message Buffering and 1-Based Indexing
Maintain an ordered client-side buffer of post-setup `ClientMessage` frames
(`realtime_input`, `client_content`, `tool_response`, `context_update`) so
unacknowledged frames can be replayed on reconnect:
- **Indexing**: User-managed message indices MUST start at **1**. Index **0** is
reserved by the server for the initial `setup` frame.
- Increment the index by 1 for each post-setup `ClientMessage` sent on the
current connection.
- **Pruning**: When a `session_resumption_update` arrives with
`last_consumed_client_message_index > 0`, remove all buffered messages with
`index <= last_consumed_client_message_index`.
- **Reset on Resumption**: Upon reconnecting, re-index the remaining buffered
messages starting from **1** for the first replayed message on the new
WebSocket connection.
### 4. Handling Disconnections and `go_away`
- **Proactive Reconnection**: When `go_away` arrives, proactively initiate
reconnection using the stored `new_handle` before `time_left` expires.
- **Transient Socket Closes**: Catch WebSocket close codes **1000** (normal
closure), **1006** (abnormal closure), and **1011** (transient internal server
error) in **both** the receive loop **and** every `send_*` / internal `_send`
path, triggering reconnection from whichever path observes the close first.
- **Unexpected Errors**: For non-recoverable protocol/auth errors (e.g., `1007`
invalid frame, `1008` invalid setup/policy violation, or permission denied),
stop the session manager and surface the error immediately; subsequent
`send_*` / `receive` calls should raise an exception describing the stop
reason.
- **Reconnect Backoff**: Retry transient reconnection failures with bounded
exponential backoff and fresh/valid ADC bearer tokens.
### 5. Reconnection with Message Replay
When reconnecting:
1. Clear the "ready for user sends" gate before opening the new socket so new
`send_*` calls wait until **both** `setup_complete` and full buffer replay
have completed.
2. Open a new WebSocket connection with a valid (refreshed if needed) ADC
`Authorization: Bearer <token>` header, send `setup` with
`session_resumption.handle = <latest_new_handle>` and
`session_resumption.transparent = true`, and wait for `setup_complete`.
3. Replay all messages remaining in the buffer **before** unblocking new user
sends. Do **not** clear, pop, or mutate the buffered message list in-place
during replay — keep all unacknowledged messages intact until a fresh
`session_resumption_update` arrives on the new connection, in case the
reconnection attempt itself drops mid-replay.
4. Map the replayed messages to sequential per-connection indices starting at
**1** (`1`, `2`, ..., `len(buffer)`) on the new connection without mutating
the underlying list prior to server acknowledgment, then set the
ready-to-send gate so new user messages continue at index `len(buffer) + 1`,
`len(buffer) + 2`, and so on.
## Gotchas
- **Never use index 0** for post-setup messages; index `0` is always the `setup`
frame.
- **Idle-loop detection**: Ensure the receive loop triggers reconnection when
the send loop is idle, and the send loop triggers reconnection when the
receive loop is idle.
- **Expired handles**: Resumption handles expire after a period of inactivity;
if resuming with an expired handle is rejected during `setup`, fall back
cleanly to starting a fresh session if configured to do so.
troubleshooting_audio_voice.md 12.6 KB
# Audio, Voice, Accent, and Quality Troubleshooting
Comprehensive root causes, config fixes, and synthetic examples for voice
gender swaps, accent/language drift, timbre mimicry, speech-rate anomalies,
amplitude collapse, tonal humming, and playback jitter.
## Table of Contents
- [Voice Gender Swaps](#voice-gender-swaps): Lines 20-66
- [Accent Reversion, Pitch Jumps, and Code-Mixed Switching](#accent-reversion-pitch-jumps-and-code-mixed-switching): Lines 68-117
- [Output Voice Mimics User Timbre](#output-voice-mimics-user-timbre): Lines 119-141
- [Multi-Turn Voice and Tone Drift](#multi-turn-voice-and-tone-drift): Lines 143-164
- [Fast Speech Rate and TTS Markup or IPA Leaks](#fast-speech-rate-and-tts-markup-or-ipa-leaks): Lines 166-200
- [Near-Zero Audio Amplitude Collapse](#near-zero-audio-amplitude-collapse): Lines 202-224
- [Tonal Humming Buzz (150-700 Hz) and Non-Terminating Greetings](#tonal-humming-buzz-150-700-hz-and-non-terminating-greetings): Lines 226-262
- [Choppy Playback and Audio Jitter](#choppy-playback-and-audio-jitter): Lines 264-278
--------------------------------------------------------------------------------
## Voice Gender Swaps
**Symptom:** The model speaks in the opposite gender from the configured voice
on Turn 1 or switches between male and female voices mid-conversation.
**Root Cause:** Pairing a male prebuilt voice with a female persona in
`system_instruction` (name, role/title, or pronouns), or pairing a female
prebuilt voice with a male persona, creates conflicting acoustic and text
conditioning.
### Prebuilt Voice Gender Reference
Match `prebuilt_voice_config.voice_name` to the `system_instruction` persona:
- **Male prebuilt voices (16):** `Achird`, `Algenib`, `Algieba`, `Alnilam`,
`Charon`, `Enceladus`, `Fenrir`, `Iapetus`, `Orus`, `Puck`, `Rasalgethi`,
`Sadachbia`, `Sadaltager`, `Schedar`, `Umbriel`, `Zubenelgenubi`.
- **Female prebuilt voices (14):** `Achernar`, `Aoede`, `Autonoe`,
`Callirrhoe`, `Despina`, `Erinome`, `Gacrux`, `Kore`, `Laomedeia`, `Leda`,
`Pulcherrima`, `Sulafat`, `Vindemiatrix`, `Zephyr`.
### Fix
Align either the configured voice or the persona name, title, and pronouns so
both share the same gender.
```python
# Bad: female preset voice paired with male persona
bad_config = {
"voice_name": "Kore", # Female
"system_instruction": "You are Arjun, a travel booking specialist.",
}
# Good: male preset voice aligned with male persona
good_config = types.LiveConnectConfig(
response_modalities=[types.Modality.AUDIO],
speech_config=types.SpeechConfig(
language_code="en-IN",
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Puck")
),
),
system_instruction="You are Arjun, a travel booking specialist.",
)
```
--------------------------------------------------------------------------------
## Accent Reversion, Pitch Jumps, and Code-Mixed Switching
**Symptom:**
- The assistant opens with an `en-US` accent or reverts to `en-US` after a
non-English turn or barge-in, even though `system_instruction` specifies a
regional accent such as Indian English (`en-IN`).
- Pitch jumps sharply after switching languages mid-call.
- Short code-mixed utterances (for example, English mixed with Tamil or Hindi)
fail to trigger a language switch.
**Root Cause:**
1. **Omitted `speech_config.language_code`:** While `language_code` is optional
for dynamic multilingual auto-detection, omitting it defaults the initial
voice reference to `en-US`. That acoustic reference competes with text
accent rules in `system_instruction`, causing pitch overcompensation and
snap-back to `en-US` on later turns.
2. **Single-script verbatim prompt inertia:** Long `system_instruction` flows
written verbatim in one non-Latin script (for example, multi-paragraph
Devanagari templates) bias the model against switching when a user speaks a
short, fast code-mixed phrase in another regional language.
### Fix
1. Set `speech_config.language_code` explicitly to a supported BCP-47 locale
from the Live API language table (such as `"en-IN"` for Indian English; see
[Configure Language and Voice](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api/configure-language-voice.md.txt)).
2. Keep `system_instruction` concise, written in neutral goal-oriented English
rather than multi-paragraph single-script scripts, and add explicit
code-switching triggers.
```python
config = types.LiveConnectConfig(
response_modalities=[types.Modality.AUDIO],
speech_config=types.SpeechConfig(
language_code="en-IN", # Supported locale prevents en-US fallback
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Aoede")
),
),
system_instruction=(
"You are Priya, a Bengaluru hotel concierge. Speak in natural Indian "
"English. If the guest switches to Hindi or Tamil, reply in that "
"language seamlessly."
),
)
```
--------------------------------------------------------------------------------
## Output Voice Mimics User Timbre
**Symptom:** The model momentarily adopts the user's voice timbre and speaks in
first person as if continuing the user's sentence, then recovers on the next
turn.
**Root Cause:** In native audio-to-audio models, user input audio remains in the
active context window alongside the system voice reference. When role boundaries
blur (for example, after a trailing user pause or ambiguous context), decoder
attention can lock onto the user's recent audio tokens instead of the system
voice reference. Text prompts attempting to describe vocal timbre do not prevent
this and can worsen role confusion.
### Fix
1. Upgrade to `gemini-3.8-live` if running an older preview model.
2. State assistant-vs-user role boundaries crisply in `system_instruction`, and
remove text instructions that attempt to dictate acoustic timbre or pitch.
3. Monitor `serverContent.outputTranscription` for first-person role confusion
and open a fresh session if role leakage occurs so the polluted turn does
not remain in context.
--------------------------------------------------------------------------------
## Multi-Turn Voice and Tone Drift
**Symptom:** Over long sessions (many turns), a prebuilt voice drifts in pitch,
cadence, or perceived gender even though audio playback and client settings are
unchanged.
**Root Cause:** Model-side discrete audio-token conditioning degrades
gradually as turn history grows far past the initial voice reference tokens at
the start of the session. Client-side playback speed or synthesizer settings are
not the cause.
### Fix
1. Ensure `speech_config.language_code` is set explicitly and remove any
text-based timbre/voice-acting instructions from `system_instruction`.
2. Configure `contextWindowCompression` with a sliding window (for example,
`trigger_tokens=24000`, `target_tokens=12000`) to prevent unbounded history
growth.
3. Rotate or reconnect long sessions periodically at natural conversation
boundaries (with a concise text summary if continuity is required).
--------------------------------------------------------------------------------
## Fast Speech Rate and TTS Markup or IPA Leaks
**Symptom:**
- Spoken turns on `gemini-live-2.5-flash-native-audio` race past 240-300 WPM
on long single-breath disclosures regardless of prompt instructions like
*"speak slowly"*.
- On `gemini-3.8-live`, `output_transcription` leaks raw IPA slashes
(`/ˌmɛdɪˈkeɪʃən/`) or the model opens with off-script broadcast-style prose.
**Root Cause:**
1. `gemini-live-2.5-flash-native-audio` does not expose a `speaking_rate`
parameter; combining fast-cadence voices (such as `Callirrhoe`) with
`setup.generationConfig.enableAffectiveDialog = true` and dense 50-word
clauses accelerates speech.
2. Copying Gemini-TTS headers (`# Audio Profile`, `# Director's Notes`) or raw
IPA `/.../` pronunciation notation into a Live API `system_instruction`
causes literal IPA leakage into transcripts and destabilizes conversational
prosody.
### Fix
1. Upgrade to `gemini-3.8-live`, which speaks naturally at a steadier
conversational pace (~180-205 WPM; affective dialog is built-in by default,
so omit `enableAffectiveDialog` on `gemini-3.8-live`).
2. If remaining on `gemini-live-2.5-flash-native-audio`, break long disclosures
into 1-2 short sentences per turn, disable
`setup.generationConfig.enableAffectiveDialog`, and test steadier voices
such as `Aoede` or `Puck`.
3. Remove `# Audio Profile` / `# Director's Notes` headers and replace IPA
slashes with plain phonetic respellings (for example, write
`"ah-SET-uh-MIN-oh-fen"` instead of IPA notation).
--------------------------------------------------------------------------------
## Near-Zero Audio Amplitude Collapse
**Symptom:** Full-length responses arrive with intact `output_transcription` and
normal turn duration, but the 24 kHz PCM waveform is nearly silent (`~ -34` to
`-44 dBFS`, with peak amplitudes under `3%` of normal full-scale speech).
**Root Cause:** Attaching massive `tools` declarations (`>40,000` tokens or
`100+` functions) or embedding pure-text rolling dialogue history blocks inside
`system_instruction` pushes the voice reference tokens tens of thousands of
tokens away from generation. Attention to the voice reference collapses,
producing near-zero-energy audio tokens while text generation remains intact.
### Fix
1. Prune `tools` in `BidiGenerateContentSetup` to only the active domain or
workflow step (keep total tool schema size well under `40,000` tokens,
ideally `<20` functions per session).
2. Keep `system_instruction` concise (`<2,000` tokens) and never inject
pure-text multi-turn conversation logs inside `system_instruction`.
3. If multi-domain routing is needed, route in application code or expose a
compact retrieval tool instead of attaching an entire catalog of schemas.
--------------------------------------------------------------------------------
## Tonal Humming Buzz (150-700 Hz) and Non-Terminating Greetings
**Symptom:**
- On numeric readbacks (phone numbers, verification codes) or opening
greetings, the model emits a sustained `150-700 Hz` harmonic hum or endless
silence without sending `turnComplete: true`.
- Audio output token counts spike `50x-600x` relative to text tokens.
- Cancelling the stuck turn and sending a follow-up text nudge on the **same**
WebSocket connection reproduces the hum >90% of the time.
- If the client locks the user microphone until the first bot `turnComplete`,
the call deadlocks permanently.
**Root Cause:** On `gemini-live-2.5-flash-native-audio`, setting low
`temperature` (`<= 0.3`) alongside
`setup.generationConfig.enableAffectiveDialog = true` traps the discrete audio
sampler in a low-entropy token-repetition attractor that never emits an
end-of-turn token. Because `temperature <= 0.3` is near-deterministic and the
partial humming turn stays in session history, nudging on the same connection
replays the attractor.
### Fix
1. Keep `temperature >= 0.7` (default `1.0` is recommended; never set
`temperature <= 0.3` on native-audio sessions).
2. On `gemini-live-2.5-flash-native-audio`, disable
`setup.generationConfig.enableAffectiveDialog` (`enable_affective_dialog` in
the SDK) during triage and when reading structured digits/codes. (On
`gemini-3.8-live`, affective dialog is built-in by default — omit the flag.)
3. On any stalled or humming turn, **close and open a new WebSocket session**
(or reconnect with a clean history) rather than nudging on the stalled
connection.
4. Never lock the user microphone indefinitely waiting for the first
`turnComplete`; add a short client timeout (`3-5s`) and avoid overly low
VAD barge-in sensitivity (`START_SENSITIVITY_LOW`) on greeting gates.
--------------------------------------------------------------------------------
## Choppy Playback and Audio Jitter
**Symptom:** `output_transcription` is clean and complete, but spoken playback
sounds choppy with `0.1-0.5s` dropouts between short bursts.
**Root Cause:** The server streams raw 24 kHz 16-bit PCM frames as they are
decoded, which can arrive in small or unevenly timed chunks (`2-20+` bytes at
turn boundaries or under network jitter). Playing each WebSocket frame
immediately starves the client audio device buffer.
### Fix
Add a `~200 ms` client-side jitter buffer before starting playback for each
turn, concatenating incoming `inlineData` PCM chunks (`audio/pcm;rate=24000`)
into the audio ring buffer before draining to the speaker.
troubleshooting_tools_lifecycle.md 14.7 KB
# Tool Calling, Safety Filters, Lifecycle, Latency, and Cost
Root causes and fixes for malformed or looping tool calls, duplicate
`NON_BLOCKING` speech, early-acknowledgement ("filler") misfires, prompt/context
contamination, input safety false positives, WebSocket `1008`/`1011`/`goAway`
drops, `429` throttling, latency (`TTFT`) triage, and multi-turn audio token
cost optimization.
## Table of Contents
- [MALFORMED_FUNCTION_CALL on Complex Tool Arguments](#malformed_function_call-on-complex-tool-arguments): Lines 24-58
- [Redundant Tool Loops and Duplicate NON_BLOCKING Speech](#redundant-tool-loops-and-duplicate-non_blocking-speech): Lines 60-121
- [State-Machine Polarity Traps and Unbounded Routing Loops](#state-machine-polarity-traps-and-unbounded-routing-loops): Lines 123-149
- [Pre-Tool Early Acknowledgement (Filler) Misfires](#pre-tool-early-acknowledgement-filler-misfires): Lines 151-172
- [Test Prompt Ignored or Model Invents Unseen Data](#test-prompt-ignored-or-model-invents-unseen-data): Lines 174-201
- [Undeclared Google Search Deadlock and Mid-Session SI Updates](#undeclared-google-search-deadlock-and-mid-session-si-updates): Lines 203-239
- [Safety Refusals on custom_vocabulary](#safety-refusals-on-custom_vocabulary): Lines 241-258
- [WebSocket 1008, 1011, goAway Drops, and 429 Throttling](#websocket-1008-1011-goaway-drops-and-429-throttling): Lines 260-290
- [Latency (TTFT) Triage](#latency-ttft-triage): Lines 292-315
- [Multi-Turn Audio Token Cost Optimization](#multi-turn-audio-token-cost-optimization): Lines 317-336
--------------------------------------------------------------------------------
## MALFORMED_FUNCTION_CALL on Complex Tool Arguments
**Symptom:** Tool calls fail with `MALFORMED_FUNCTION_CALL` or dropped quotes /
closing brackets, sometimes accompanied by stray reasoning text.
**Root Cause:** Declaring a tool with a single `STRING` parameter (for example,
`query_dsl: STRING` or `payload: STRING`) and instructing the model inside
`system_instruction` to format a quote-heavy JSON or key-value mini-DSL string
causes the model to drop closing quotes or delimiters during real-time speech
generation.
### Fix
Always declare explicit typed schema properties (`OBJECT`, `ARRAY`, `ENUM`,
`BOOLEAN`, `INTEGER`) in `functionDeclarations[].parameters` (or
`parametersJsonSchema`) instead of encoding a mini-DSL inside a `STRING`.
```json
{
"name": "search_flights",
"description": "Search available flights for a route and cabin.",
"parameters": {
"type": "OBJECT",
"properties": {
"origin": { "type": "STRING" },
"destination": { "type": "STRING" },
"cabin": { "type": "STRING", "enum": ["ECONOMY", "BUSINESS", "FIRST"] },
"nonstop_only": { "type": "BOOLEAN" }
},
"required": ["origin", "destination"]
}
}
```
--------------------------------------------------------------------------------
## Redundant Tool Loops and Duplicate NON_BLOCKING Speech
**Symptom:**
- The model invokes the same tool repeatedly with identical arguments in a
loop.
- With `NON_BLOCKING` tools, the assistant speaks a response while the tool
runs and then speaks a second, duplicate answer when `toolResponse` arrives.
**Root Cause:**
1. **State-machine bloat & contradictory directives:** Multi-hop deterministic
state machines inside large `system_instruction` prompts combined with
conflicting rules (*"ALWAYS call tools"* vs. *"Only one tool call per
turn"*) push real-time native-audio models into repetitive tool loops.
2. **Default `FunctionResponse` scheduling:** Returning a `NON_BLOCKING`
`FunctionResponse` without `scheduling="SILENT"` instructs the server to
trigger a new model generation turn when the response arrives, causing a
duplicate spoken reply.
### Fix
1. Move deterministic state transitions and retry counters into application
code, and expose only the tools valid for the current conversation step.
2. Set `scheduling="SILENT"` on transactional or background `FunctionResponse`
payloads when the model has already acknowledged the action and only needs
the result stored in context. (Note:
`gemini-3.8-live-extended-thinking-preview` does not support explicit
`FunctionResponse.scheduling`.)
```json
{
"toolResponse": {
"functionResponses": [{
"id": "call_1",
"name": "save_preference",
"scheduling": "SILENT",
"response": { "status": "saved", "retryable": false }
}]
}
}
```
```python
# Equivalent Python google-genai SDK call
await session.send_tool_response(
function_responses=[
types.FunctionResponse(
id=call.id,
name=call.name,
response={"status": "saved", "retryable": false},
scheduling=types.FunctionResponseScheduling.SILENT,
)
]
)
```
3. For small reference lists (`<= 50` items), include a compact lookup table in
`system_instruction` or resolve entities via client-side retrieval before
injecting results.
--------------------------------------------------------------------------------
## State-Machine Polarity Traps and Unbounded Routing Loops
**Symptom:** In branching voice workflows (such as triage or confirmation
flows), the assistant misroutes when the user says `"No"`, loops indefinitely
on ambiguous questions or unintelligible fragments, or leaks raw JSON routing
blocks.
**Root Cause:**
1. **Question polarity inversion:** Asking `"Do you want to cancel your
order?"` (`"No"` = keep order) followed immediately by `"To confirm, you
want to keep your order, correct?"` (`"No"` = cancel order) without
explicitly mapping `"No"` on the confirmation step causes the model to
carry over the initial `"No"` intent.
2. **Unbounded Q&A / forbidden same-state routing:** Prohibiting a routing tool
from targeting the current state without a turn cap causes infinite loops or
raw JSON fallback dumps when callers stay off-topic.
### Fix
1. Keep confirmation question polarity consistent across turns, or explicitly
specify both affirmative and negative branch targets in the tool response
instructions.
2. Enforce a bounded retry limit (for example, re-prompt once on unclear input,
then escalate or transfer on the second consecutive unclear turn).
--------------------------------------------------------------------------------
## Pre-Tool Early Acknowledgement (Filler) Misfires
**Symptom:** Attempting to use natural-language `system_instruction` rules to
make the model speak a filler phrase (*"Let me look that up"*) before slow
tools (`3-5s`) while remaining silent before fast utility tools (`< 1s`) causes
frequent false-positive fillers on fast tools, silent execution on slow tools,
or double spoken sentences (empathy + filler) before a single tool call.
**Root Cause:** Natural-language filler rules inside large `system_instruction`
prompts cannot reliably discriminate tool latency tiers at decode time.
### Fix
1. **Silent tools + client UI cue (recommended):** Instruct the model to
invoke tools immediately without spoken filler, and play a lightweight
client-side chime or visual indicator while awaiting `toolResponse`.
2. **Uniform single-sentence acknowledgement:** If spoken acknowledgement is
required before slow operations, keep it uniform rather than writing
per-tool latency rules in `system_instruction`, and combine any empathy and
waiting phrase into a single short sentence.
--------------------------------------------------------------------------------
## Test Prompt Ignored or Model Invents Unseen Data
**Symptom:**
- Replacing `system_instruction` with a 1-line echo test prompt still causes
the assistant to run the production workflow.
- The assistant states user details (account tiers, dates, names) that are not
in the prompt template and were never spoken by the user.
**Root Cause:**
1. **Latent tool schemas:** Leaving production `tools` attached in
`BidiGenerateContentSetup` acts as latent workflow instructions that
outweigh a minimal 1-line `system_instruction`.
2. **Client framework context contamination:** Agent frameworks or middleware
often serialize extra session-state attributes (templates, script buffers,
user profile objects) into the assembled setup or `clientContent` payload
without appearing in the raw prompt file.
### Fix
1. Remove or stub out `tools` when testing minimal or echo prompts in
isolation.
2. Log and inspect the **complete serialized wire JSON** (`setup`,
`clientContent`, `toolResponse`) actually sent over the WebSocket rather
than auditing only source prompt templates.
--------------------------------------------------------------------------------
## Undeclared Google Search Deadlock and Mid-Session SI Updates
**Symptom:**
- Sessions stall for `8-10s` until idle timeout when the prompt demands
search grounding.
- Mid-session `clientContent` attempts to update instructions fail, trigger an
unsolicited model reply, or erase earlier rules.
**Root Cause:**
1. Instructing *"Ground answers to Google Search ONLY"* in `system_instruction`
without declaring `{"googleSearch": {}}` in `setup.tools` causes the model
to attempt an undeclared search call and stall waiting for a response. Note
that on Live API, `googleSearch` **cannot** be combined with
`functionDeclarations` in the same `setup.tools` configuration.
2. `gemini-3.8-live` rejects `role="system"` in `clientContent` (mid-session
instruction and tool updates must use `contextUpdate`, which replaces
`setup.systemInstruction` in full). On `2.5` models, sending
`turnComplete: true` on a context update immediately triggers an unsolicited
spoken turn rather than quietly updating instructions for the next user
utterance.
### Fix
1. Either declare `{"googleSearch": {}}` alone in `setup.tools` (when no
`functionDeclarations` are used), remove the Google Search mandate from
`system_instruction`, or expose search behind a custom server-executed
function declaration when combining search with other custom tools.
2. On `gemini-3.8-live`, send a `contextUpdate`
(`BidiGenerateContentContextUpdate`) frame carrying the **complete**
replacement `systemInstruction` (and/or updated `tools`). On `2.5` models,
reconnect or resume a session with the updated `setup.systemInstruction` at
a turn boundary rather than sending `role="system"` or `turnComplete: true`
in `clientContent`.
--------------------------------------------------------------------------------
## Safety Refusals on custom_vocabulary
**Symptom:** Spoken queries containing domain terms registered in
`inputAudioTranscription.customVocabulary` trigger an unexpected canned safety
refusal (*"I'm just a language model and can't help with that."*), while the
exact same audio passes when `customVocabulary` is omitted.
**Root Cause:** Concatenating multi-word domain phrases into synthetic
single-token compounds in `customVocabulary` can distort speech-recognition
subword tokenization and trigger false-positive input safety blocks.
### Fix
Keep multi-word phrases in `inputAudioTranscription.customVocabulary`
space-delimited as natural words rather than concatenating synthetic
single-token compounds.
--------------------------------------------------------------------------------
## WebSocket 1008, 1011, goAway Drops, and 429 Throttling
**Symptom:** Sessions terminate mid-call with WebSocket close codes `1008`
(Policy Violation), `1011` (Internal Error), `goAway`, or fail to connect during
traffic spikes with HTTP `429 RESOURCE_EXHAUSTED`.
**Root Cause:**
1. **`1008` on setup:** Caused by unsupported `generationConfig` fields in Live
API (`responseSchema`, `responseMimeType`, `responseLogprobs`, `logprobs`,
`stopSequence`, `routingConfig`, `audioTimestamp`), an unknown or
case-mismatched `voiceName`, or invalid `toolResponse` payloads.
2. **`1008` / `goAway` mid-call:** Hitting the per-connection Live session
duration limit (~10-15 minutes) without session resumption enabled.
3. **`1011` / `429`:** Transient upstream disconnects without resumption, or
unsmoothed outbound dialing / connection bursts exceeding regional QPM/RPM.
### Fix
1. Audit `setup.generationConfig` against supported Live API fields, and verify
case-sensitive `voiceName` spelling.
2. Enable transparent session resumption (`sessionResumption: { transparent:
true }`), track `sessionResumptionUpdate.newHandle` and
`lastConsumedClientMessageIndex`, and reconnect automatically on `goAway`
and close codes `1000`, `1006`, or `1011`. Follow the Session Manager
reference (`references/session_manager.md`) linked from `SKILL.md` for the
full buffering and replay state machine.
3. Smooth connection bursts with jittered exponential backoff on `429`, and
evaluate Provisioned Throughput for predictable high-concurrency workloads.
--------------------------------------------------------------------------------
## Latency (TTFT) Triage
**Symptom:** Time-to-first-audio-byte (`TTFT`) spikes from `< 1.5s` to `6-12s`,
causing idle timeouts.
**Root Cause:** Multi-second delays fall into three distinct buckets:
1. **Client 3P tool latency:** Gap between receiving `toolCall` and sending
`toolResponse`.
2. **User barge-in overlap:** Caller resumes speaking before the server turn
finishes.
3. **Regional backend / prefix-cache latency:** Delay between `activityEnd` /
`turnComplete` (or `toolResponse`) and the first `serverContent` chunk with
no pending client tool calls.
### Fix
Log monotonic timestamps at `activityEnd` (or `clientContent`), `toolCall`,
`toolResponse`, and first `serverContent` audio chunk. Optimize slow client 3P
APIs (or mark non-critical calls `NON_BLOCKING` with `scheduling="SILENT"`). If
server latency spikes at flat QPS with no client tool delay, test an alternate
supported region and share session IDs + UTC timestamps with Google Cloud
Support.
--------------------------------------------------------------------------------
## Multi-Turn Audio Token Cost Optimization
**Symptom:** Multi-turn Live API call costs grow superlinearly as session
duration increases.
**Root Cause:** Live API retains prior model audio output tokens 1-for-1 as
audio input context across subsequent turns in the same session, and streams
continuous background audio when `TURN_INCLUDES_ALL_INPUT` is active.
### Fix
1. Configure `contextWindowCompression` sliding windows to cap retained audio
history.
2. Rotate/reset long sessions at natural conversation boundaries.
3. Set `realtimeInputConfig.turnCoverage = "TURN_INCLUDES_ONLY_ACTIVITY"` so
long silent intervals are not retained in turn context.
4. Offload pure text/data post-processing (summarization, classification) to
non-audio `generateContent` calls.
5. Review current rates and calculators on the
[Google Cloud Pricing](https://cloud.google.com/pricing) page.
troubleshooting_turns_vad.md 17.5 KB
# Turns, VAD, Barge-In, and Transcription Leaks
Root causes and concrete fixes for empty turns, premature completion, missing
`turnComplete`, VAD clipping on telephony audio, backchannel cutoffs, and
unspoken code or instruction leaks in `output_transcription`.
## Table of Contents
- [Premature generationComplete and Missing turnComplete](#premature-generationcomplete-and-missing-turncomplete): Lines 23-86
- [Post-toolResponse Zero-Audio Turns in Deep Contexts](#post-toolresponse-zero-audio-turns-in-deep-contexts): Lines 88-112
- [Empty Turns from proactiveAudio and Client Stall Nudges](#empty-turns-from-proactiveaudio-and-client-stall-nudges): Lines 114-149
- [Turn-1 Transcript Drops and Prompt Template Newlines](#turn-1-transcript-drops-and-prompt-template-newlines): Lines 151-170
- [Unspoken Markdown or Code Tail-Bursts in output_transcription](#unspoken-markdown-or-code-tail-bursts-in-output_transcription): Lines 172-201
- [Pre-Tool Filler Audible Leakage Without Transcripts](#pre-tool-filler-audible-leakage-without-transcripts): Lines 203-230
- [Massive Unscoped System Instruction Dumps](#massive-unscoped-system-instruction-dumps): Lines 232-252
- [Spoken Placeholder Tokens and Raw JSON Leaks](#spoken-placeholder-tokens-and-raw-json-leaks): Lines 254-282
- [Short Backchannel Cutoffs and Double-Interruption Silence](#short-backchannel-cutoffs-and-double-interruption-silence): Lines 284-309
- [Manual VAD Tail Clipping and 8 kHz Telephony Distortion](#manual-vad-tail-clipping-and-8-khz-telephony-distortion): Lines 311-336
- [Barge-In Playback Overlap and Background Noise Triggers](#barge-in-playback-overlap-and-background-noise-triggers): Lines 338-361
--------------------------------------------------------------------------------
## Premature generationComplete and Missing turnComplete
**Symptom:**
- In multi-turn sequential readback or voice sessions, sending the next
`clientContent` turn right after `generationComplete: true` triggers
`interrupted: true` and cuts off playback.
- After 3 or more turns (`ordinal >= 3`), turns occasionally stop after
`~0.75s` of audio (or emit zero-audio / near-empty PCM turns) while
`output_transcription` emits the full passage or a short fragment.
- Occasionally `turnComplete: true` never arrives after a zero-audio turn,
causing client timeouts.
**Root Cause:**
1. **`generationComplete` vs. `turnComplete`:** `generationComplete` fires as
soon as the server finishes synthesizing audio (faster than real time),
while `turnComplete` waits for simulated real-time playback pacing. Sending
the next `clientContent` turn before `turnComplete` is interpreted as a
user barge-in.
2. **Multi-turn history desynchronization (`ordinal >= 3`) + `<verbatim>`
tags:** Accumulating past audio/text turns combined with `<verbatim>` XML
tags causes the model to emit the entire text at once and predict
end-of-turn after one audio block, or stall playback completion on a silent
turn.
### Fix
1. Wait for `serverContent.turnComplete == true` before sending the next
sequential `clientContent` turn.
2. Remove `<verbatim>` XML tags from `system_instruction` and user turns.
3. For **stateless** turn-by-turn TTS/readback workloads reusing a warm
WebSocket connection, configure `contextWindowCompression` with a sliding
window (`triggerTokens >= 5000`) so completed turns do not accumulate
unboundedly:
```json
{
"setup": {
"model": "projects/my-project-id/locations/us-central1/publishers/google/models/gemini-3.8-live",
"generationConfig": {
"responseModalities": ["AUDIO"],
"speechConfig": {
"languageCode": "en-US",
"voiceConfig": {
"prebuiltVoiceConfig": { "voiceName": "Aoede" }
}
}
},
"contextWindowCompression": {
"triggerTokens": 10000,
"slidingWindow": { "targetTokens": 1000 }
},
"outputAudioTranscription": {}
}
}
```
4. **Client defense-in-depth:** If `generationComplete` arrives and useful
non-zero PCM audio bytes remain `0` for `>= 500 ms` (or `< 1.5s` of audio
when expecting a multi-sentence readback), close/rotate the session and
retry once rather than waiting indefinitely for `turnComplete`.
--------------------------------------------------------------------------------
## Post-toolResponse Zero-Audio Turns in Deep Contexts
**Symptom:** After a `toolResponse` in turn 5+ (`>14,000` context tokens), the
server emits `output_transcription` and `turnComplete: true` in `< 0.5s` with
`0` audio chunks (`AUDIO` tokens `0`, `TEXT` tokens `> 0`).
**Root Cause:** In long, text-heavy contexts containing XML state machines
(`<taskflow>`), large JSON payloads, or inline pronunciation guides inside
`system_instruction` or `toolResponse`, the voice reference tokens at the start
of the session are too far from the generation cursor. After `toolResponse`,
interleaved text-before-audio generation can enter a pure-text trajectory and
terminate without generating audio tokens.
### Fix
1. Replace XML/JSON state machines in `system_instruction` with concise,
natural-language prose (`< 2,000` tokens).
2. Return only the minimal structured JSON needed from `toolResponse` — strip
multi-paragraph formatting instructions or pronunciation dictionaries from
tool outputs.
3. Enable `contextWindowCompression` so prompt growth stays bounded across
multi-turn tool loops (for example, `trigger_tokens=12000`,
`target_tokens=6000`).
--------------------------------------------------------------------------------
## Empty Turns from proactiveAudio and Client Stall Nudges
**Symptom:** Frequent empty model turns (`output_audio=0`,
`output_transcription` empty or minimal), consecutive empty turns ("wedges"),
and `12-30s` of dead air.
**Root Cause:**
1. **Proactive audio suppression:** On `gemini-live-2.5-flash-native-audio`
when `setup.proactivity.proactiveAudio = true` (and by default on
`gemini-3.8-live`), the model intentionally withholds audio output (`0`
audio chunks) when it judges an utterance incomplete or background speech
not directed at the assistant.
2. **Client stall-watchdog self-interruption:** Client timers that fire
`clientContent(turnComplete=True)` after `~3s` of silence immediately abort
in-flight server generation or tool-call decoding and return `interrupted:
true` with `0` audio.
3. **Missed `interrupted` frames:** Clients often inspect `interrupted` only on
the `turnComplete` message, missing the preceding `ServerMessage` where
`serverContent.interrupted == true` actually arrived.
### Fix
1. On `gemini-live-2.5-flash-native-audio`, set
`setup.proactivity.proactiveAudio = false` (`proactivity={"proactive_audio":
False}` in the SDK, or omit `proactivity`) during triage to verify whether
intentional response suppression is causing silent turns. (On
`gemini-3.8-live`, proactive audio is built-in by default — omit
`setup.proactivity`.)
2. Remove aggressive `3s` client `clientContent(turnComplete=True)` stall
nudges (if needed as a last-resort timeout, wait `>= 10-15s` and ensure no
tool call is in flight).
3. Track `serverContent.interrupted` across **every** `ServerMessage` in the
turn stream, not only on the frame carrying `turnComplete: true`.
--------------------------------------------------------------------------------
## Turn-1 Transcript Drops and Prompt Template Newlines
**Symptom:** Kicking off Turn 1 with `realtimeInput.text` while user microphone
PCM is muted intermittently drops Turn-1 `output_transcription` (`""`) and leaks
silence placeholders on call teardown.
**Root Cause:** Sending `realtimeInput.text` with zero voice activity under
`TURN_INCLUDES_ALL_INPUT` can desynchronize Turn-1 transcript emission. In
addition, concatenating interpolated prompt template sections onto a single
run-on line without `\n` separators makes multi-section instructions ambiguous.
### Fix
1. Set `realtimeInputConfig.turnCoverage = "TURN_INCLUDES_ONLY_ACTIVITY"`,
trigger scripted Turn-1 greetings with `clientContent(turnComplete=True)`,
and close the WebSocket cleanly immediately after hangup tools complete.
2. As general template hygiene, ensure interpolated sections and blocks in
`system_instruction` are separated with explicit `\n` newlines.
--------------------------------------------------------------------------------
## Unspoken Markdown or Code Tail-Bursts in output_transcription
**Symptom:** The model speaks a normal voice answer, and right before
`generationComplete` an unrequested burst of Markdown (`##`, bullet lists) or
fenced Python/C++ code appears in `output_transcription` after spoken audio has
ceased.
**Root Cause:** Post-speech text tokens emitted after the final audio chunk can
flush as a trailing `output_transcription` update at `generationComplete`. While
within-session Live API history is managed server-side, rendering or persisting
those trailing code blocks in client UI bubbles or cross-session text replay
stores pollutes user transcripts and subsequent resumed sessions. This is
amplified by omitting `speech_config.language_code` and including Markdown
headings or code snippets in `system_instruction`.
### Fix
1. Set `speech_config.language_code` explicitly to a supported session locale.
2. Strip Markdown headers (`#`, `##`) and code fences from
`system_instruction`, and add a plain-spoken instruction: *"Respond only in
plain spoken prose. Never output Markdown formatting, bullet lists, or code
blocks."*
3. For UI rendering and client-persisted cross-session transcript stores, strip
trailing fenced code blocks (` ```...``` `) or Markdown headers flushed at
`generationComplete` after audio chunks have stopped (do not filter per
WebSocket frame with `turn_audio_bytes > 0`, as `outputTranscription` and
audio `inlineData` arrive on separate frames and prior speech in the same
turn already sets cumulative `turn_audio_bytes > 0`).
--------------------------------------------------------------------------------
## Pre-Tool Filler Audible Leakage Without Transcripts
**Symptom:** Right before calling a tool, the voice assistant audibly recites
internal instructions, FAQ text, or tool-wrapper rules for `10-35s`, yet
**none** of the leaked words appear in `output_transcription` (only the opening
phrase like *"One moment while I check that"* is transcribed).
**Root Cause:** In native audio-to-audio sessions under heavy text context
(`>50,000-70,000` tokens from multi-domain fallbacks and imperative `"speak..."`
instructions inside `toolResponse`), speaking a pre-tool filler opens an audio
stream before emitting a `toolCall` message. Under heavy text dilution, the
audio decoder can drift and read nearby prompt/tool text aloud without emitting
interleaved text tokens—leaving `output_transcription` blind to the leak.
### Fix
1. **Call tools silently:** Remove pre-tool spoken filler directives from
`system_instruction` in deep-context agents and play any subtle waiting
tone on the client UI instead.
2. **Return pure data from `toolResponse`:** Strip `"say exactly..."` or
imperative `"speak..."` wrapper prose from function responses.
3. **Bound context size:** Fix domain-router fallbacks so only the active
domain loads, and lower `contextWindowCompression` (for example,
`trigger_tokens=32000`, `target_tokens=20000`).
4. **Client circuit breaker:** Immediately mute/stop pre-tool audio playback
the moment a `toolCall` message arrives.
--------------------------------------------------------------------------------
## Massive Unscoped System Instruction Dumps
**Symptom:** `output_transcription` suddenly streams thousands of characters of
the `system_instruction` verbatim (sometimes ending with `"""` code delimiters)
between two normal spoken sentences.
**Root Cause:** When a domain classifier falls back to loading all domains
(`>50,000` tokens), combining repeated `"Output ONLY ... VERBATIM"` rules,
triple-quote delimiters, and rules blocking tool calls on unsupported inputs
causes the model to scan the prompt and copy trailing SI text verbatim.
### Fix
1. Never load all domain prompts on classifier fallback; route to a
lightweight clarification prompt (`< 2,000` tokens).
2. Remove `"Output VERBATIM"` rules and `"""` triple-quote delimiters from
`system_instruction`.
3. Validate unsupported inputs inside a typed tool response instead of
forbidding tool calls in the prompt.
--------------------------------------------------------------------------------
## Spoken Placeholder Tokens and Raw JSON Leaks
**Symptom:** The model speaks `"No speech. Pause."` aloud, emits `<no speech>`,
`{pause}`, or `…` in `output_transcription`, or leaks raw JSON routing
objects (`{"state": "..."}`).
**Root Cause:**
1. **Duplicate post-tool turn:** Returning a `FunctionResponse` on a
`NON_BLOCKING` or side-effect tool (such as `hangup_call` or `log_metric`)
without `scheduling="SILENT"` triggers a follow-up turn after the assistant
already said goodbye; having nothing to say, it emits `<no speech>` or
`{pause}`.
2. **Bot self-echo:** Without acoustic echo cancellation (AEC), the model hears
its own TTS output and tries to stay silent.
3. **Forbidden state-transition loop:** State-machine prompts that forbid
calling a routing tool for the current state cause the model to emit raw
JSON or `…` when a caller repeats unintelligible fragments.
### Fix
1. Set `scheduling="SILENT"` on transactional/side-effect `FunctionResponse`s,
and set `behavior="BLOCKING"` on tools whose result the model must wait for
before speaking.
2. Enable client AEC and mute/gate echoed bot output.
3. Bound unclear-input loops (for example, escalate after 2 unclear turns) and
explicitly forbid emitting control placeholders or JSON in spoken turns.
--------------------------------------------------------------------------------
## Short Backchannel Cutoffs and Double-Interruption Silence
**Symptom:** Short user affirmations (`"Mm-hmm"`, `"Uh-huh"`, `"Got it"`) while
the assistant is speaking immediately trigger `serverContent.interrupted: true`,
cutting off the assistant and dropping the rest of its explanation. Brief pauses
mid-utterance (`"Wait, [pause]..."`) cause two rapid interrupts and a silent
(`0.0s`) stalled turn.
**Root Cause:** Server-side barge-in interrupts the active turn immediately on
acoustic start-of-speech before semantic intent or sentence completion can be
evaluated. Tuning `startOfSpeechSensitivity` to `START_SENSITIVITY_LOW` reduces
sensitivity slightly, but cannot reliably distinguish brief backchannels from
real questions.
### Fix
Implement a client-side voice activity gate for backchannels:
1. Buffer short (`< 500 ms`) non-lexical affirmations locally without
forwarding them as interrupting turns (or suppress client playback cutoff
until sustained speech / lexical intent is detected).
2. When strict uninterrupted storytelling or multi-step readouts are required,
set `realtimeInputConfig.activityHandling = "NO_INTERRUPTION"` or manage
barge-in boundaries manually on the client.
--------------------------------------------------------------------------------
## Manual VAD Tail Clipping and 8 kHz Telephony Distortion
**Symptom:** Critical numbers (postal codes, confirmation codes, account IDs)
are truncated in `input_transcription` (for example, `"98058"` transcribed as
`"98050"`), causing wrong tool arguments even though the full call recording
sounds clear.
**Root Cause:** Two factors compound on telephony streams:
1. **Client manual VAD tail clipping:** When `automaticActivityDetection` is
`disabled: true`, sending `activityEnd` immediately when local RMS drops
(or bouncing on `< 400 ms` pauses) cuts off the last `200-300 ms` of
final plosives (`/t/`, `/d/`).
2. **8 kHz narrowband PSTN attenuation:** Telephone audio rolls off above
`3.4-4 kHz`, making final consonants fragile if clipped even slightly.
### Fix
1. Add `400-500 ms` of post-speech hangover padding before sending
`activityEnd`, and debounce `< 400 ms` `activityStart`/`activityEnd`
spikes (or use server-side VAD with `prefix_padding_ms=300`,
`silence_duration_ms=600`, `end_of_speech_sensitivity="END_SENSITIVITY_LOW"`).
2. For critical telephony fields (dates, confirmation codes, amounts), require
an explicit spoken read-back confirmation before committing the transaction.
--------------------------------------------------------------------------------
## Barge-In Playback Overlap and Background Noise Triggers
**Symptom:**
- After barge-in, the new assistant turn plays on top of the previous turn's
buffered audio.
- Background music or ambient noise causes the assistant to cut off
mid-sentence or respond to noise.
**Root Cause:** Faster-than-realtime server generation can finish a turn before
the user interrupts; because the server turn already ended, no
`interrupted: true` event is emitted, so a client that only flushes on
`interrupted: true` plays old buffered audio underneath the new turn. Meanwhile,
missing AEC or discontinuous audio chunks trigger false server VAD events.
### Fix
1. **Flush on new turn:** Clear the client audio playback queue both when
`serverContent.interrupted == true` **and** whenever the first audio chunk
of a new model turn arrives while prior audio is still playing.
2. Enable hardware/software **AEC**, gate pure background music client-side,
stream continuous 16 kHz 16-bit mono PCM frames (`audio/pcm;rate=16000`),
and tune `automaticActivityDetection` (`start_of_speech_sensitivity`,
`silence_duration_ms`).
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE