WebSocket connection
Send text, audio and frames through Gemini Live WebSocket and receive speech, transcripts and tool calls.
Stream text, audio and frames over one WebSocket to receive speech and optional transcripts. All four endpoints share the parameter and message reference below. Examples use Google v1beta; replace the connection URL to switch endpoints. Paths start at the platform root; do not prepend /v1.
Google Gemini API · v1beta
wss://api.agtcloud.cn/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentGoogle Gemini API · v1alpha
wss://api.agtcloud.cn/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentVertex AI · v1
wss://api.agtcloud.cn/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContentVertex AI · v1beta1
wss://api.agtcloud.cn/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContentConnection parameters
Startup configuration
Within 10 seconds of connecting, send a first frame containing only setup. Wait for setupComplete before input. Put the following configuration inside setup.
Session flow
- Connect with a platform API Key and send a first frame containing only
setup. - After
setupComplete, send text throughclientContentor media throughrealtimeInput. - Continuously process all fields of
serverContent, tool messages andusageMetadata. - Keep the connection open for the next turn. To end the session, stop input, collect the current turn results and usage, then close the WebSocket.
The Node.js/Python examples on the right send two text turns and save speech to reply-1.pcm and reply-2.pcm, with a 60-second limit. Set API_KEY; optionally change the model with MODEL_ID. Install ws for Node.js or websocket-client for Python. Keep long-lived Keys on your server; this integration does not use Google ephemeral-token issuance.
Model and configuration
| Item | Using gemini-3.8-live |
|---|---|
| Output | Use responseModalities: ["AUDIO"]; set outputAudioTranscription: {} for text transcripts, not the TEXT output modality |
| Voice and language | Set the voice through speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName. Response language follows input and system instructions; omit speechConfig.languageCode |
| Reasoning | Interleaved reasoning is built in; omit thinkingConfig and thinkingLevel |
| Proactive audio | Always enabled; do not set proactivity.proactiveAudio to false. Also omit the removed enableAffectiveDialog |
| Tools | Supports function calling and Google Search. Functions are asynchronous by default; use behavior: "BLOCKING" for synchronous execution |
| Configuration limits | Do not copy ordinary Generate Content settings for responseMimeType, responseSchema, responseJsonSchema or Logprobs |
| Configuration changes | Do not resend setup on the current connection. Reconnect to change startup configuration; keep the same model when resuming |
Media input and playback
| Input or output | Handling |
|---|---|
| Audio input | Mono, little-endian PCM16. Examples use 16 kHz, sending mimeType: "audio/pcm;rate=16000" and Base64 through realtimeInput.audio; omit WAV headers |
| Images and video frames | Send Base64 JPEG/PNG through realtimeInput.video. Stream video frames over time and audio separately through audio; do not put a complete MP4 in data |
| Pacing | Send audio chunks at realtime speed. Start video at one frame per second, preserving audio/video order; do not send all frames at once |
| Message size | Each client message is limited to 1 MiB, including JSON and Base64. Resize or compress large images. Server messages are limited to 4 MiB |
| Speech output | Read Base64 audio from serverContent.modelTurn.parts[].inlineData and play according to the returned mimeType. Examples save only mono PCM16/24 kHz audio |
| Receive handling | A message may contain audio, transcription, turn state and usage together. Process fields independently; do not skip others with mutually exclusive branches |
# Convert input audio to raw mono PCM16 at 16 kHz
ffmpeg -i input.wav -f s16le -acodec pcm_s16le -ac 1 -ar 16000 audio.pcm
# Extract video frames and a separate audio track; stream in temporal order
ffmpeg -i input.mp4 -vf 'fps=1,scale=768:-2' frame-%04d.jpg
ffmpeg -i input.mp4 -vn -f s16le -acodec pcm_s16le -ac 1 -ar 16000 video-audio.pcm
# Play the saved 24 kHz response
ffplay -f s16le -ar 24000 -ac 1 reply-1.pcmMessage Reference
Each client JSON has exactly one top-level field: setup, clientContent, realtimeInput or toolResponse; do not use GPT-Live session.start. JSON below illustrates structure; replace media data and tool results with actual values.
setup
Initialize the connection; send only once.
Turns, tools and resumption
| Scenario | Handling |
|---|---|
| Text turns | clientContent.turnComplete: true triggers a response and interrupts current generation; time history updates appropriately |
| Automatic speech segmentation | VAD is enabled by default; stream audio continuously. Send audioStreamEnd: true when the audio stream pauses or ends |
| Manual speech segmentation | Set automaticActivityDetection.disabled: true during setup, then send activityStart: {}, audio chunks and activityEnd: {} in order. Do not replace manual completion with audioStreamEnd |
| Turn completion | generationComplete ends the current generation; turnComplete ends the turn. Also check interactionStatus when returned: IN_PROGRESS means more output may follow |
| Interruptions | On serverContent.interrupted, immediately stop and clear the local playback queue to avoid playing old responses |
| Function calling | Execute calls from toolCall.functionCalls, then return matching id, name and results through toolResponse.functionResponses. Stop pending calls when cancelled |
| Asynchronous tools | behavior: "NON_BLOCKING" allows conversation during tool execution; use scheduling to select SILENT, WHEN_IDLE or INTERRUPTED for results |
| Initial history | To load history before realtime input, set historyConfig.initialHistoryInClientContent: true, finish history input through clientContent, then send realtime media |
| Long sessions | Set contextWindowCompression.slidingWindow: {} to enable sliding-window compression; configure the trigger threshold as needed |
| Session resumption | Set sessionResumption: {}; retain a nonempty newHandle when resumable: true. On reconnect, place it in setup.sessionResumption.handle, using the original Key and same model |
| Imminent disconnection | On goAway.timeLeft, prepare to reconnect. The application controls reconnection and replay; do not repeat completed tools or blindly resend media |
Usage and charges
| Field or situation | Interpretation |
|---|---|
promptTokenCount | Total input for this turn may include retained history; do not subtract the previous turn usage from the next |
responseTokenCount、totalTokenCount | Keep returned output and total counts; do not force modality breakdowns to reproduce totals |
promptTokensDetails、responseTokensDetails | Text, audio, image or video breakdowns; record frames under their returned modality |
thoughtsTokenCount | Reasoning usage breakdown; do not add it to output or totals again |
| Multiple usage messages in one turn | Update the turn snapshot rather than summing messages. Usage may arrive after turnComplete; keep receiving before closing |
See Model Gallery for model and tool prices. After abnormal disconnection, retain the request ID and received usage. Reserved quota is not final consumption; incomplete records do not establish a refund.
Troubleshooting
| Symptom | What to check |
|---|---|
| HTTP 401/403 | Check the platform Key, group and permissions. Changing the path does not grant access to other groups |
| No available channel / 429 | The group has no available resources or is rate-limited. Retry later with a limit; do not keep creating connections |
| Initialization timeout | Send setup within 10 seconds of connecting; do not send other input before setupComplete |
| Initialized, but generation reports a modality error | Use AUDIO for gemini-3.8-live and get text through output transcription. Initialization alone does not mean the configuration can generate |
| No audio or distorted audio | Check Base64, raw PCM, bit depth, channels, sample rate and returned mimeType |
| No response | Check text turnComplete, or VAD mode and activityStart/activityEnd. Proactive audio may ignore irrelevant input |
| Tools do not progress | The client executes tools and returns results; check call IDs, function names and cancellation messages |
| Resumption failed | Use the latest nonempty resumable handle, original Key and same model. Do not reuse handles across users, Keys or models |