Перейти к навигации

Gemini Live API

Просмотр в формате Markdown

Gemini Live streams audio in and audio out over a single WebSocket. BeatAPI serves Google’s Gemini Live protocol (BidiGenerateContent) unchanged, so a client written for the Gemini Live API works once it points at BeatAPI and sends a BeatAPI key.

ModelWhat it doesInputOutput
gemini-4-liveVoice conversation. Ask by speaking, or send an image or video frames and ask about them. Optional thinking.Audio, text, image, videoAudio and text
gemini-4-live-translateLive speech-to-speech translation across more than 70 languages, with subtitles of both sides.Audio (speech)Translated audio and text

Endpoint

wss://api.beatapi.io/v1beta/live?model=<model>

wss://api.beatapi.io/v1/live is the same endpoint; Google’s SDKs use their own path, see Google Gen AI SDK. model is gemini-4-live or gemini-4-live-translate, with or without the models/ prefix. The session runs the model named in the URL: BeatAPI rewrites setup.model to it.

Authorization

Send your BeatAPI API key in one of three ways:

  • Authorization: Bearer <BEATAPI_API_KEY>
  • x-goog-api-key: <BEATAPI_API_KEY>
  • the key query parameter: wss://api.beatapi.io/v1beta/live?model=gemini-4-live&key=<BEATAPI_API_KEY>

Browsers cannot set headers on a WebSocket, which is what the query parameter is for. A URL can end up in proxy and browser logs, so keep permanent keys on your server and open sessions from there. An invalid key is refused with HTTP 401 before the WebSocket opens.

Google Gen AI SDK

Google’s own SDKs connect natively: set their base URL to https://api.beatapi.io and pass a BeatAPI key as the API key. Session code written for the Gemini API needs no other change. The SDKs open wss://api.beatapi.io/ws/google.ai.generativelanguage.v1.GenerativeService.BidiGenerateContent (the v1alpha and v1beta forms work too) and name the model in setup; BeatAPI routes on that model. Tested with google-genai 3.7.0 for Python and @google/genai 3.7.0 for Node.js.

import os
from google import genai
from google.genai import types
client = genai.Client(
api_key=os.environ["BEATAPI_API_KEY"],
http_options=types.HttpOptions(base_url="https://api.beatapi.io"),
)
async with client.aio.live.connect(
model="gemini-4-live",
config={"response_modalities": ["AUDIO"], "output_audio_transcription": {}},
) as session:
for chunk in pcm_chunks: # 16 kHz mono PCM, about 100 ms each
await session.send_realtime_input(audio=types.Blob(data=chunk, mime_type="audio/pcm;rate=16000"))
await session.send_realtime_input(audio_stream_end=True)
async for message in session.receive():
...
import { GoogleGenAI, Modality } from "@google/genai";
const ai = new GoogleGenAI({
apiKey: process.env.BEATAPI_API_KEY,
httpOptions: { baseUrl: "https://api.beatapi.io" },
});
const session = await ai.live.connect({
model: "gemini-4-live-translate",
config: {
responseModalities: [Modality.AUDIO],
translationConfig: { targetLanguageCode: "zh" },
inputAudioTranscription: {},
outputAudioTranscription: {},
},
callbacks: { onmessage: (message) => console.log(message.serverContent) },
});

Send audio as a stream of small chunks, about 100 ms each, as it is recorded. A whole recording sent as one message can stall the session.

Session flow

Every message is one JSON object in a text frame.

  1. Connect, then send setup as the first message. Nothing else is accepted before it.
  2. Wait for setupComplete.
  3. Stream input with realtimeInput (audio chunks, video frames, text), or send whole turns with clientContent. Answer function calls with toolResponse.
  4. Read serverContent: modelTurn carries audio (inlineData) and text parts, inputTranscription and outputTranscription carry the subtitles, and turnComplete ends an answer. Messages may also carry usageMetadata.
  5. Close the WebSocket when you are done. The session is billed when it closes.

Audio in is 16-bit little-endian PCM, 16 kHz, mono (audio/pcm;rate=16000), base64-encoded. Audio out is 16-bit PCM at 24 kHz.

Voice conversation

{
"setup": {
"model": "models/gemini-4-live",
"generationConfig": {
"responseModalities": ["AUDIO"],
"thinkingConfig": { "thinkingLevel": "LOW" }
},
"inputAudioTranscription": {},
"outputAudioTranscription": {}
}
}

Leave out thinkingConfig for the fastest answers. Then send audio as it is recorded, and mark the end of a spoken question:

{ "realtimeInput": { "audio": { "mimeType": "audio/pcm;rate=16000", "data": "<base64 PCM>" } } }
{ "realtimeInput": { "audioStreamEnd": true } }

To ask about a picture, send it first: {"realtimeInput": {"video": {"mimeType": "image/jpeg", "data": "<base64 JPEG>"}}}.

Live translation

{
"setup": {
"model": "models/gemini-4-live-translate",
"generationConfig": {
"responseModalities": ["AUDIO"],
"translationConfig": { "targetLanguageCode": "zh", "echoTargetLanguage": false }
},
"inputAudioTranscription": {},
"outputAudioTranscription": {}
}
}

targetLanguageCode is the language to speak back, for example zh or en. Then stream speech with realtimeInput.audio. Translation is continuous: it may never send turnComplete, so close the session when the speaker is done.

Python example

The script streams a 16 kHz mono WAV file into the session in 100 ms chunks and prints both subtitles. Install websockets first (pip install websockets).

import base64, json, os, sys, time, wave
from websockets.sync.client import connect
mode, wav_path = sys.argv[1], sys.argv[2] # mode: live or translate
model = "gemini-4-live-translate" if mode == "translate" else "gemini-4-live"
generation = {"responseModalities": ["AUDIO"]}
if mode == "translate":
generation["translationConfig"] = {"targetLanguageCode": "zh", "echoTargetLanguage": False}
url = "wss://api.beatapi.io/v1beta/live?model=" + model
headers = {"Authorization": "Bearer " + os.environ["BEATAPI_API_KEY"]}
with wave.open(wav_path, "rb") as wav:
pcm = wav.readframes(wav.getnframes()) + bytes(32000) # 1 s of trailing silence
with connect(url, additional_headers=headers, max_size=None) as ws:
ws.send(json.dumps({"setup": {"model": "models/" + model, "generationConfig": generation,
"inputAudioTranscription": {}, "outputAudioTranscription": {}}}))
while "setupComplete" not in json.loads(ws.recv(timeout=30)):
pass
for i in range(0, len(pcm), 3200): # 100 ms chunks
chunk = base64.b64encode(pcm[i:i + 3200]).decode()
ws.send(json.dumps({"realtimeInput": {"audio": {"mimeType": "audio/pcm;rate=16000", "data": chunk}}}))
time.sleep(0.1)
if mode == "live":
ws.send(json.dumps({"realtimeInput": {"audioStreamEnd": True}}))
heard, said = "", ""
while True:
try:
event = json.loads(ws.recv(timeout=8))
except TimeoutError:
break
content = event.get("serverContent", {})
heard += content.get("inputTranscription", {}).get("text", "")
said += content.get("outputTranscription", {}).get("text", "")
if content.get("turnComplete") and mode == "live":
break
print("heard:", heard)
print("said: ", said)

Pricing

Billed per token on the usage each session reports, at 75% of Google’s list price. Audio is 25 tokens per second.

ModelInput, per 1M tokensOutput, per 1M tokens
gemini-4-live0.5625text,0.5625 text, 0.75 image or video, $2.25 audio3.375text(thinkingincluded),3.375 text (thinking included), 9.00 audio
gemini-4-live-translate$2.625 audio$15.75 audio

A session is charged once, when it closes. It cannot outspend your account: when its running cost passes the balance the session started with, BeatAPI closes it with code 1008 and reason insufficient balance; the usage up to that point is billed.

Close codes

CodeReasonWhat to do
1000—Normal end of the session.
1003the first message must be a JSON setup messageSend setup first, as JSON.
1008insufficient balanceTop up, then open a new session.
1011the model ended the sessionThe model closed the session on its side. Open a new one.
1013an error sentenceThe session could not start, for example no line for the model is available. Retry later.

Limits

  • One WebSocket is one session. Reconnecting starts a new session: sessionResumption handles are passed through but are not guaranteed to resume on another connection.
  • There is no plain HTTP or SSE form of these models; use the WebSocket.