APIMaster.ai

Gemini Live, transcription and translation

Use the APIMaster API key for Google-native voice conversations, audio transcription and speech translation.

Choose a model

Model ID HTTP / WSS Use case and implementation
gemini-3.8-live WSS Voice help desk
gemini-3.8-live-extended-thinking WSS Voice troubleshooting with multiple steps
gemini-3.5-transcribe-live WSS Live meeting captions
gemini-3.5-live-translate-preview WSS English-to-Spanish interpretation
gemini-3.5-transcribe POST Recorded interview to searchable transcript

Connection and audio format

WSS wss://apimaster.ai/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent
POST https://apimaster.ai/v1beta/models/gemini-3.5-transcribe:generateContent
WSS  x-goog-api-key: $APIMASTER_API_KEY
POST Authorization: Bearer $APIMASTER_API_KEY

PCM input   16000 Hz · mono · s16le · audio/pcm;rate=16000
PCM output  24000 Hz · mono · s16le

Live sessions are limited to 10 minutes by APIMaster. File transcription accepts a JSON request up to 20 MiB with one inline audio part. The prices below are base rates; check the marketplace for the charged route.

For a production stream, send and receive concurrently so the client can display live text or play audio while recording. On a disconnect, open a fresh session and send setup again. Use one server-side connection per audio stream.

WebSocket helper

Save the helper as gemini_live.py. Run each model’s example from the same directory. Set APIMASTER_API_KEY on the server; use a short recording to verify the flow before replacing the file reader with a microphone stream.

python3 -m pip install websocket-client
import base64
import json
import os
import time
from contextlib import ExitStack, closing
from pathlib import Path
from urllib.parse import urlsplit

from websocket import WebSocketTimeoutException, create_connection

HOST = urlsplit("https://apimaster.ai").netloc
PATH = "/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent"


def run(setup, recording, *, output=None, manual=False, stop=None):
    pcm = Path(recording).read_bytes()
    if not pcm or len(pcm) % 2:
        raise ValueError("Expected nonempty raw 16-bit PCM")

    got_result = False
    with ExitStack() as stack:
        ws = stack.enter_context(closing(create_connection(
            f"wss://{HOST}{PATH}",
            header={"x-goog-api-key": os.environ["APIMASTER_API_KEY"]},
            timeout=30,
        )))
        audio_file = stack.enter_context(open(output, "wb")) if output else None

        def send(payload):
            ws.send(json.dumps(payload))

        send({"setup": setup})
        ack = ws.recv()
        if not ack or "setupComplete" not in json.loads(ack):
            raise RuntimeError("WebSocket closed or rejected setup before setupComplete")

        if manual:
            send({"realtimeInput": {"activityStart": {}}})
        for offset in range(0, len(pcm), 3200):
            chunk = pcm[offset:offset + 3200]
            send({"realtimeInput": {"audio": {
                "mimeType": "audio/pcm;rate=16000",
                "data": base64.b64encode(chunk).decode("ascii"),
            }}})
            time.sleep(len(chunk) / 32000)
        send({"realtimeInput": {"activityEnd": {}} if manual
              else {"audioStreamEnd": True}})

        deadline = time.monotonic() + 60
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                if not stop and got_result:
                    break
                raise TimeoutError("No completion event within 60 seconds")
            ws.settimeout(min(remaining, 30 if stop else 8))
            try:
                raw = ws.recv()
            except WebSocketTimeoutException:
                if not stop and got_result:
                    break
                if time.monotonic() >= deadline:
                    raise
                continue
            if not raw:
                raise RuntimeError("WebSocket closed before the sample ended")
            message = json.loads(raw)
            content = message.get("serverContent", {})
            for name in ("interimInputTranscription", "inputTranscription",
                         "outputTranscription"):
                item = content.get(name)
                if item:
                    print(name, item.get("text", ""), flush=True)
                    if output is None and name == "inputTranscription" and item.get("text"):
                        got_result = True
            for part in content.get("modelTurn", {}).get("parts", []):
                blob = part.get("inlineData", {})
                if audio_file and blob.get("mimeType", "").startswith("audio/"):
                    audio_file.write(base64.b64decode(blob["data"]))
                    got_result = True
            if "interactionStatus" in content:
                print("interactionStatus", content["interactionStatus"], flush=True)
            if stop and content.get(stop[0]) == stop[1] and got_result:
                break

gemini-3.8-live

Use case and implementation

Voice help desk

A user asks how to reset a password. Stream microphone audio, play the returned voice, show subtitles if enabled, and release the turn when turnComplete arrives. Clear queued playback on interrupted.

Request parameters

Field Type Required or default What it does
setup.model string Required · models/gemini-3.8-live Session model ID
setup.generationConfig.responseModalities string[] Required · ["AUDIO"] Response modality
setup.systemInstruction.parts[].text string Optional System instructions at setup
setup.generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName string Optional · Kore Select an available voice
setup.inputAudioTranscription object Optional · {} Enable input subtitles
setup.outputAudioTranscription object Optional · {} Enable output subtitles
setup.realtimeInputConfig.automaticActivityDetection.disabled boolean false Automatic voice activity detection; when disabled, send start and end signals
setup.realtimeInputConfig.automaticActivityDetection.silenceDurationMs integer Optional Milliseconds of silence before ending detected speech
realtimeInput.activityStart / realtimeInput.activityEnd object {} Automatic voice activity detection; when disabled, send start and end signals
realtimeInput.audio.mimeType string Required · audio/pcm;rate=16000 Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audio.data string Required Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audioStreamEnd boolean true End of audio with automatic activity detection
realtimeInput.text string Optional Simple text input
realtimeInput.video object Optional Inline image or video frame

Response fields and events

Event Type What it does
setupComplete object Setup accepted; start sending audio
serverContent.modelTurn.parts[].inlineData object · PCM 24 kHz Audio to decode and play
serverContent.inputTranscription.text string Input transcript
serverContent.outputTranscription.text string Output transcript
serverContent.turnComplete boolean The speaking turn has ended
serverContent.interrupted boolean Stop playback of the interrupted response
usageMetadata object Token counts when reported

Runnable example

ffmpeg -hide_banner -loglevel error -y -i support.wav -ar 16000 -ac 1 -f s16le support.pcm

python3 - <<'PYTHON'
from gemini_live import run

run({
    "model": "models/gemini-3.8-live",
    "generationConfig": {"responseModalities": ["AUDIO"]},
    "systemInstruction": {"parts": [{"text": "You are a concise support agent."}]},
    "inputAudioTranscription": {},
    "outputAudioTranscription": {},
    "realtimeInputConfig": {"automaticActivityDetection": {"disabled": True}},
}, "support.pcm", output="support-reply.pcm", manual=True,
    stop=("turnComplete", True))
PYTHON

For playback, use the following command with the PCM output produced by the voice or translation examples.

ffplay -f s16le -ar 24000 -ac 1 support-reply.pcm

Base price

USD per million tokens · text input $0.75 · audio input $3 · image/video input $1 · text output $4.50 · audio output $12.

Official reference

gemini-3.8-live-extended-thinking

Use case and implementation

Voice troubleshooting with multiple steps

Ask for a step-by-step diagnosis of intermittent Wi-Fi. Play intermediate speech as it arrives and keep the interface in a processing state until interactionStatus is IDLE.

Request parameters

Field Type Required or default What it does
setup.model string Required · models/gemini-3.8-live-extended-thinking Session model ID
setup.generationConfig.responseModalities string[] Required · ["AUDIO"] Response modality
setup.generationConfig.thinkingConfig.thinkingLevel enum Required · LOW / MEDIUM / HIGH Depth of background reasoning
setup.systemInstruction.parts[].text string Optional System instructions at setup
setup.generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName string Optional · Kore Select an available voice
setup.inputAudioTranscription object Optional · {} Enable input subtitles
setup.outputAudioTranscription object Optional · {} Enable output subtitles
setup.realtimeInputConfig.automaticActivityDetection.disabled boolean false Automatic voice activity detection; when disabled, send start and end signals
setup.realtimeInputConfig.automaticActivityDetection.silenceDurationMs integer Optional Milliseconds of silence before ending detected speech
realtimeInput.activityStart / realtimeInput.activityEnd object {} Automatic voice activity detection; when disabled, send start and end signals
realtimeInput.audio.mimeType string Required · audio/pcm;rate=16000 Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audio.data string Required Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audioStreamEnd boolean true End of audio with automatic activity detection
setup.tools[].functionDeclarations[].behavior enum NON_BLOCKING Declare asynchronous tools; reply with matching call IDs
toolResponse.functionResponses[].id string Optional Declare asynchronous tools; reply with matching call IDs

Response fields and events

Event Type What it does
setupComplete object Setup accepted; start sending audio
serverContent.modelTurn.parts[].inlineData object · PCM 24 kHz Audio to decode and play
serverContent.inputTranscription.text string Input transcript
serverContent.outputTranscription.text string Output transcript
serverContent.turnComplete boolean The speaking turn has ended
serverContent.interactionStatus IN_PROGRESS / IDLE Background processing or finished
toolCall.functionCalls[] object[] Declare asynchronous tools; reply with matching call IDs
serverContent.interrupted boolean Stop playback of the interrupted response
usageMetadata object Token counts when reported

Runnable example

ffmpeg -hide_banner -loglevel error -y -i wifi.wav -ar 16000 -ac 1 -f s16le wifi.pcm

python3 - <<'PYTHON'
from gemini_live import run

run({
    "model": "models/gemini-3.8-live-extended-thinking",
    "generationConfig": {"responseModalities": ["AUDIO"],
                         "thinkingConfig": {"thinkingLevel": "LOW"}},
    "inputAudioTranscription": {},
    "realtimeInputConfig": {"automaticActivityDetection": {"disabled": True}},
    "outputAudioTranscription": {},
}, "wifi.pcm", output="wifi-reply.pcm", manual=True,
    stop=("interactionStatus", "IDLE"))
PYTHON

For playback, use the following command with the PCM output produced by the voice or translation examples.

ffplay -f s16le -ar 24000 -ac 1 wifi-reply.pcm

Base price

USD per million tokens · text input $0.75 · audio input $3 · image/video input $1 · text output $4.50 · audio output $12.

Official reference

gemini-3.5-transcribe-live

Use case and implementation

Live meeting captions

Show interim text on screen as it changes, then append VERBATIM final segments. For SMART mode, replace the current transcript buffer with the latest final text. Use the end-of-generation event after you stop sending audio.

Request parameters

Field Type Required or default What it does
setup.model string Required · models/gemini-3.5-transcribe-live Session model ID
setup.generationConfig.responseModalities string[] Required · ["TEXT"] Response modality
setup.inputAudioTranscription.languageCodes string[] [] Language hints; empty enables automatic detection
setup.inputAudioTranscription.customVocabulary string[] Optional Names and technical terms to favor
setup.inputAudioTranscription.mode enum VERBATIM / SMART Verbatim or cleaned and formatted transcript
setup.inputAudioTranscription.sourceText string Optional · SMART Existing text to revise by voice in SMART
setup.realtimeInputConfig.automaticActivityDetection.disabled boolean false Automatic voice activity detection; when disabled, send start and end signals
setup.realtimeInputConfig.interimTranscriptTimestampEnabled boolean Optional Enable offsets on interim utterances
realtimeInput.audio.mimeType string Required · audio/pcm;rate=16000 Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audio.data string Required Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audioStreamEnd boolean true End of audio with automatic activity detection
realtimeInput.activityStart / realtimeInput.activityEnd object {} Automatic voice activity detection; when disabled, send start and end signals

Response fields and events

Event Type What it does
setupComplete object Setup accepted; start sending audio
serverContent.interimInputTranscription.text string Temporary hypothesis; replace the preview
serverContent.inputTranscription.text string Committed transcription text
serverContent.inputTranscription.startOffset / endOffset Duration Enable offsets on interim utterances
serverContent.interimInputTranscription.startOffset / endOffset Duration Enable offsets on interim utterances
serverContent.generationComplete boolean Generation complete for the submitted speech

Runnable example

ffmpeg -hide_banner -loglevel error -y -i meeting.wav -ar 16000 -ac 1 -f s16le meeting.pcm

python3 - <<'PYTHON'
from gemini_live import run

run({
    "model": "models/gemini-3.5-transcribe-live",
    "generationConfig": {"responseModalities": ["TEXT"]},
    "inputAudioTranscription": {"languageCodes": ["en-US"], "mode": "VERBATIM"},
}, "meeting.pcm", stop=("generationComplete", True))
PYTHON

For word timestamps or speaker labels, use the file-transcription model.

Base price

Live transcription uses forwarded audio duration, including sent silence. Connection idle time and control frames cost zero. $0.008925 USD per audio minute.

Official reference

gemini-3.5-live-translate-preview

Use case and implementation

English-to-Spanish interpretation

Send English speech and play the translated 24 kHz PCM for listeners. Show the translated subtitles separately. For a two-way conversation, use two independent streams with opposite target languages.

Request parameters

Field Type Required or default What it does
setup.model string Required · models/gemini-3.5-live-translate-preview Session model ID
setup.generationConfig.responseModalities string[] Required · ["AUDIO"] Response modality
setup.generationConfig.translationConfig.targetLanguageCode string Required · es Target language code (BCP 47)
setup.generationConfig.translationConfig.echoTargetLanguage boolean false Play back speech already in the target language when true
setup.systemInstruction.parts[].text string Optional System instructions at setup
setup.inputAudioTranscription object Optional · {} Enable input subtitles
setup.outputAudioTranscription object Optional · {} Enable output subtitles
realtimeInput.audio.mimeType string Required · audio/pcm;rate=16000 Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audio.data string Required Base64 bytes; PCM mono, signed 16-bit little-endian
realtimeInput.audioStreamEnd boolean true End of audio with automatic activity detection

Response fields and events

Event Type What it does
setupComplete object Setup accepted; start sending audio
serverContent.modelTurn.parts[].inlineData object · PCM 24 kHz Audio to decode and play
serverContent.inputTranscription.text string Input transcript
serverContent.outputTranscription.text string Output transcript
serverContent.inputTranscription.languageCode / outputTranscription.languageCode string Target language code (BCP 47)
usageMetadata object Token counts when reported

Runnable example

ffmpeg -hide_banner -loglevel error -y -i english.wav -ar 16000 -ac 1 -f s16le english.pcm

python3 - <<'PYTHON'
from gemini_live import run

run({
    "model": "models/gemini-3.5-live-translate-preview",
    "generationConfig": {
        "responseModalities": ["AUDIO"],
        "translationConfig": {"targetLanguageCode": "es", "echoTargetLanguage": False},
    },
    "inputAudioTranscription": {},
    "outputAudioTranscription": {},
}, "english.pcm", output="spanish.pcm")
PYTHON

Source and target language transcripts arrive as separate events. For this finite recording, the sample drains buffered translation until eight seconds pass without a message. A continuous interpreter keeps receiving until the application closes the stream.

For playback, use the following command with the PCM output produced by the voice or translation examples.

ffplay -f s16le -ar 24000 -ac 1 spanish.pcm

Base price

USD per million tokens · audio input $3.50 · audio output $21.

Official reference

gemini-3.5-transcribe

Use case and implementation

Recorded interview to searchable transcript

Send one recording with word timings and read the returned text and available audio metadata. Use VERBATIM for subtitling with timings, or SMART for a clean reading transcript.

Request parameters

Field Type Required or default What it does
contents[].parts[] object[] Required · 1 One inline audio part
contents[].parts[].inlineData.mimeType string Required · audio/wav / audio/mpeg File MIME type
contents[].parts[].inlineData.data string Required Base64 bytes of the original recording
generationConfig.audioTranscriptionConfig.languageCodes string[] [] Language hints; empty enables automatic detection
generationConfig.audioTranscriptionConfig.customVocabulary string[] Optional Names and technical terms to favor
generationConfig.audioTranscriptionConfig.mode enum VERBATIM / SMART Verbatim or cleaned and formatted transcript
generationConfig.audioTranscriptionConfig.wordTimestamp boolean false Word timestamps in VERBATIM
generationConfig.audioTranscriptionConfig.diarization boolean false Speaker labels in VERBATIM
generationConfig.audioTranscriptionConfig.sourceText string Optional · SMART Existing text to revise by voice in SMART

Response fields and events

Event Type What it does
candidates[].content.parts[].text string Transcribed text
candidates[].content.parts[].audioTranscription.words[].startOffset / endOffset string Timing or speaker metadata when present
candidates[].content.parts[].audioTranscription.speakerLabel string Timing or speaker metadata when present
usageMetadata object Token counts when reported

Runnable example

python3 - <<'PYTHON' > request.json
import base64
import json
from pathlib import Path

encoded = base64.b64encode(Path("interview.wav").read_bytes()).decode("ascii")
print(json.dumps({
    "contents": [{"parts": [{"inlineData": {"mimeType": "audio/wav", "data": encoded}}]}],
    "generationConfig": {"audioTranscriptionConfig": {
        "languageCodes": ["en-US"],
        "mode": "VERBATIM",
        "wordTimestamp": True,
        "diarization": True,
        "customVocabulary": ["APIMaster"],
    }},
}))
PYTHON
curl --fail-with-body -sS "https://apimaster.ai/v1beta/models/gemini-3.5-transcribe:generateContent" \
  -H "Authorization: Bearer $APIMASTER_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @request.json > response.json

python3 - <<'PYTHON'
import json
from pathlib import Path

response = json.loads(Path("response.json").read_text())
for candidate in response.get("candidates", []):
    for part in candidate.get("content", {}).get("parts", []):
        if "text" in part:
            print(part["text"])
        if "audioTranscription" in part:
            print(json.dumps(part["audioTranscription"], ensure_ascii=False))
print("usageMetadata", response.get("usageMetadata"))
PYTHON

Base price

USD per million tokens · audio input $2 · text output $12.

Official reference

Official reference · Base price