ARCHITECTURE · VOICE · GOOGLE · 5 MIN READ

A voice agent with Google Gemini Live

Use a live audio session with a clear boundary between media, agent context, and tools.

Download example files Code + setup + checks in a ZIP
Jump to a section 13 sections

EXAMPLE USE CASE

Hold a spoken policy conversation using Gemini Live

A developer needs microphone capture, streamed model audio, interruption handling and correct input/output clocks.

Input
16 kHz mono microphone PCM plus a fixed 30-day returns policy in the session instruction.
Expected output
24 kHz mono model audio played through the speaker while the conversation remains live.
  • Success check: You can ask a policy question, hear the answer, interrupt, and end the session without orphaned audio devices.
  • Try a failure: Use an unavailable microphone or model. Surface the error; never treat an empty audio stream as a successful conversation.

Example scope: A real client-to-server audio integration requiring your key, microphone and speakers. Hardware/provider behavior is documented for you to verify; site QA does not capture audio or make paid calls.

Google Gemini Live exampleLiveKit Agents exampleSilero VAD example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
framesPCM inmodel eventsaudio queueclear stalereleaseMicrophone16 kHz mono PCMTransmit taskSend microphone framesGemini LivePolicy conversationReceive taskInspect all content partsSpeaker task24 kHz PCM playbackInterrupt + stopDiscard stale playback
  1. PyAudio captures bounded chunks from the selected input device.

  2. The async task sends each PCM chunk using send_realtime_input with its declared sample rate.

  3. The Live session detects turns and produces streamed replies using the fixed demonstration policy.

  4. The receiver processes every audio/text part and puts audio into a bounded playback queue.

  5. A separate task writes returned audio without blocking capture or WebSocket reception.

    Result or stopping point
  6. Interruption clears queued audio; cancellation or the time limit releases both devices.

Gemini Live

The Live session detects turns and produces streamed replies using the fixed demonstration policy.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Components for this use case

  • The Python client captures 16 kHz PCM and plays 24 kHz PCM. Gemini Live owns turn detection and streamed replies; bounded queues decouple network and speaker rates.
  • For browser/mobile production delivery, choose an authenticated backend or supported short-lived client credential flow, and implement reconnect/session limits.

Choose the connection path

  • A client can connect to the Live API using an ephemeral token issued by a trusted backend.
  • A server-mediated approach relays audio through your own service.
  • Choose based on network constraints, control requirements, and latency.

Keep media handling explicit

  • Capture and convert audio to the format required by the chosen session.
  • Buffer and play model output without blocking tool execution.
  • Handle turn boundaries and interrupted output deliberately.
  • Google ADK streaming is another application layer to consider when building an ADK-based system.

Attach context and actions

  • Retrieve only the memories needed for the session.
  • Authorize every tool invocation outside the model.
  • Persist task results separately from transient audio buffers so reconnecting does not lose a confirmed transaction.

Test real conversations

  • Include background noise, overlapping speech, silence, tool delays, and network drops.
  • Evaluate whether the agent completes the user’s task, not just whether audio streams successfully.

Set up the lab

  • Python 3.11+, a microphone, speakers and a Gemini API key/model with Live API access. Use headphones to reduce speaker-to-microphone feedback.
  • Install PortAudio through your platform package manager if PyAudio requires it; on macOS: brew install portaudio. The program asks your OS for microphone permission when you run it.
  • This 120-second local lab makes provider audio calls when you run it. The website itself does not access your microphone or credentials.
Shell
python3 -m venv .venv
source .venv/bin/activate
python -m pip install google-genai pyaudio
export GEMINI_API_KEY="YOUR_KEY"
export GEMINI_LIVE_MODEL="YOUR_ENABLED_LIVE_AUDIO_MODEL"

Implement the example

Save as live_audio.py

Python · live_audio.py
import asyncio
import os
import pyaudio
from google import genai
from google.genai import types

async def main():
    audio = pyaudio.PyAudio()
    mic = speaker = None
    queue = asyncio.Queue(maxsize=50)
    try:
        mic = audio.open(format=pyaudio.paInt16, channels=1, rate=16000,
                         input=True, frames_per_buffer=1024)
        speaker = audio.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
        client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
        config = {"response_modalities":["AUDIO"], "system_instruction":
            "Be concise. Demo policy: returns accepted within 30 days. "
            "Answer only from this policy; never invent order statuses."}
        async with client.aio.live.connect(
            model=os.environ["GEMINI_LIVE_MODEL"], config=config) as session:
            async def send_microphone():
                while True:
                    data = await asyncio.to_thread(mic.read, 1024, exception_on_overflow=False)
                    await session.send_realtime_input(audio=types.Blob(
                        data=data, mime_type="audio/pcm;rate=16000"))

            async def receive_audio():
                while True:
                    # receive() yields one turn; repeat for the next turn.
                    async for message in session.receive():
                        content = message.server_content
                        if not content:
                            continue
                        if content.interrupted:
                            while not queue.empty():
                                queue.get_nowait()  # Discard stale playback.
                        for part in (content.model_turn.parts if content.model_turn else []):
                            if part.inline_data and part.inline_data.data:
                                await queue.put(part.inline_data.data)
                            if part.text:
                                print(part.text)

            async def play_audio():
                while True:
                    await asyncio.to_thread(speaker.write, await queue.get())

            print("Connected. Ask a returns question; Ctrl+C stops. Lab limit: 120 seconds.")
            async with asyncio.timeout(120):
                async with asyncio.TaskGroup() as tasks:
                    tasks.create_task(send_microphone())
                    tasks.create_task(receive_audio())
                    tasks.create_task(play_audio())
    except TimeoutError:
        print("Demo session time limit reached")
    finally:
        for stream in (mic, speaker):
            if stream:
                stream.stop_stream()
                stream.close()
        audio.terminate()

try:
    asyncio.run(main())
except KeyboardInterrupt:
    print("Stopped")

Run and verify

Shell
python live_audio.py
# Say: Can I return an item after twenty days?
# Interrupt with a follow-up, then press Ctrl+C to stop.
  • Microphone frames are sent as 16 kHz mono 16-bit PCM; replies are played as 24 kHz mono 16-bit PCM.
  • The reply should use the supplied 30-day policy. A new spoken turn should produce a new reply without restarting the program.
  • Interrupt the model and verify stale queued playback is cleared. Ctrl+C and the time limit must close both audio devices.

Troubleshooting and failure tests

  • Permission/device errors need a working microphone and OS permission; a valid API key does not establish the audio path.
  • An unavailable Live model, disconnected WebSocket or unsupported session configuration must surface as an error.
  • Headphones and a bounded output queue reduce feedback/backlog; production echo cancellation and reconnect/session-resume are separate work.

Before production

  • Use an authenticated session backend or supported ephemeral client tokens for browser/mobile clients, with permanent keys on the server.
  • Add consent, session limits, redacted observability, real interruption/reconnect tests and tool authorization before customer use.
  • Measure real end-of-turn latency and audio quality on target devices. This example has documentation/syntax review; paid provider calls and audio hardware are not executed by site QA.

Protocol details checked against the maintainer

Keep exploring

Build with Google’s Agent Development KitA realtime voice agent with OpenAIA layered architecture for agent memory