AGTCloud API Docs
GuidesAPI ReferenceIntegrations and resourcesUpdate and help
RealtimeGemini Live multimodal

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
wss://api.agtcloud.cn/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent

Google Gemini API · v1alpha

WSS
wss://api.agtcloud.cn/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContent

Vertex AI · v1

WSS
wss://api.agtcloud.cn/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent

Vertex AI · v1beta1

WSS
wss://api.agtcloud.cn/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContent

Connection parameters

All four endpoints use the same platform API Key authentication.

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.

The setup object in the first JSON message; wait for setupComplete before further input.

Session flow

  1. Connect with a platform API Key and send a first frame containing only setup.
  2. After setupComplete, send text through clientContent or media through realtimeInput.
  3. Continuously process all fields of serverContent, tool messages and usageMetadata.
  4. 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

ItemUsing gemini-3.8-live
OutputUse responseModalities: ["AUDIO"]; set outputAudioTranscription: {} for text transcripts, not the TEXT output modality
Voice and languageSet the voice through speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName. Response language follows input and system instructions; omit speechConfig.languageCode
ReasoningInterleaved reasoning is built in; omit thinkingConfig and thinkingLevel
Proactive audioAlways enabled; do not set proactivity.proactiveAudio to false. Also omit the removed enableAffectiveDialog
ToolsSupports function calling and Google Search. Functions are asynchronous by default; use behavior: "BLOCKING" for synchronous execution
Configuration limitsDo not copy ordinary Generate Content settings for responseMimeType, responseSchema, responseJsonSchema or Logprobs
Configuration changesDo not resend setup on the current connection. Reconnect to change startup configuration; keep the same model when resuming

Media input and playback

Input or outputHandling
Audio inputMono, little-endian PCM16. Examples use 16 kHz, sending mimeType: "audio/pcm;rate=16000" and Base64 through realtimeInput.audio; omit WAV headers
Images and video framesSend Base64 JPEG/PNG through realtimeInput.video. Stream video frames over time and audio separately through audio; do not put a complete MP4 in data
PacingSend audio chunks at realtime speed. Start video at one frame per second, preserving audio/video order; do not send all frames at once
Message sizeEach client message is limited to 1 MiB, including JSON and Base64. Resize or compress large images. Server messages are limited to 4 MiB
Speech outputRead Base64 audio from serverContent.modelTurn.parts[].inlineData and play according to the returned mimeType. Examples save only mono PCM16/24 kHz audio
Receive handlingA 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.pcm

Message 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.

Event direction
Category
Event

setup

Initialize the connection; send only once.

Turns, tools and resumption

ScenarioHandling
Text turnsclientContent.turnComplete: true triggers a response and interrupts current generation; time history updates appropriately
Automatic speech segmentationVAD is enabled by default; stream audio continuously. Send audioStreamEnd: true when the audio stream pauses or ends
Manual speech segmentationSet automaticActivityDetection.disabled: true during setup, then send activityStart: {}, audio chunks and activityEnd: {} in order. Do not replace manual completion with audioStreamEnd
Turn completiongenerationComplete ends the current generation; turnComplete ends the turn. Also check interactionStatus when returned: IN_PROGRESS means more output may follow
InterruptionsOn serverContent.interrupted, immediately stop and clear the local playback queue to avoid playing old responses
Function callingExecute calls from toolCall.functionCalls, then return matching id, name and results through toolResponse.functionResponses. Stop pending calls when cancelled
Asynchronous toolsbehavior: "NON_BLOCKING" allows conversation during tool execution; use scheduling to select SILENT, WHEN_IDLE or INTERRUPTED for results
Initial historyTo load history before realtime input, set historyConfig.initialHistoryInClientContent: true, finish history input through clientContent, then send realtime media
Long sessionsSet contextWindowCompression.slidingWindow: {} to enable sliding-window compression; configure the trigger threshold as needed
Session resumptionSet sessionResumption: {}; retain a nonempty newHandle when resumable: true. On reconnect, place it in setup.sessionResumption.handle, using the original Key and same model
Imminent disconnectionOn 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 situationInterpretation
promptTokenCountTotal input for this turn may include retained history; do not subtract the previous turn usage from the next
responseTokenCount、totalTokenCountKeep returned output and total counts; do not force modality breakdowns to reproduce totals
promptTokensDetails、responseTokensDetailsText, audio, image or video breakdowns; record frames under their returned modality
thoughtsTokenCountReasoning usage breakdown; do not add it to output or totals again
Multiple usage messages in one turnUpdate 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

SymptomWhat to check
HTTP 401/403Check the platform Key, group and permissions. Changing the path does not grant access to other groups
No available channel / 429The group has no available resources or is rate-limited. Retry later with a limit; do not keep creating connections
Initialization timeoutSend setup within 10 seconds of connecting; do not send other input before setupComplete
Initialized, but generation reports a modality errorUse 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 audioCheck Base64, raw PCM, bit depth, channels, sample rate and returned mimeType
No responseCheck text turnComplete, or VAD mode and activityStart/activityEnd. Proactive audio may ignore irrelevant input
Tools do not progressThe client executes tools and returns results; check call IDs, function names and cancellation messages
Resumption failedUse the latest nonempty resumable handle, original Key and same model. Do not reuse handles across users, Keys or models

Official references