# How to build a realtime audio agent

> Build a live audio-to-audio agent with AudioAgent and Gemini Live: arealtime sessions, LiveInputQueue, image input, reconnection, and the WebSocket bridge.

Source: https://10xgraph.com/docs/guides/use-realtime-audio
Last updated: 2026-11-26

This guide builds a live audio-to-audio agent with `AudioAgent` and Gemini Live. A realtime graph does not run through `invoke` or `stream`: the provider owns the turn loop and 10xGraph wraps it.

## Install

```bash
pip install "10xgraph[realtime]"
```

The `realtime` extra pulls in `google-genai`. Provider SDK imports are lazy: importing `tenxgraph.core.realtime` never loads the SDK unless you open a session.

Set your credentials:

```bash
export GEMINI_API_KEY=your-api-key

```

`GOOGLE_API_KEY` also works. The model is the string you pass to `AudioAgent` and `RealtimeConfig`; the examples use `gemini-3.8-live`. Google renames Live models often, so check which one your key can use.

For Vertex AI, pass `use_vertex_ai=True` to `AudioAgent(...)` and set `GOOGLE_CLOUD_PROJECT` (and optionally `GOOGLE_CLOUD_LOCATION`, default `us-central1`). Credentials come from Application Default Credentials. The `GOOGLE_GENAI_USE_VERTEXAI` variable is not used for realtime sessions.

---

## Audio format

| Direction | Format |
|---|---|
| Input (you -> model) | PCM16, mono, 16 kHz |
| Output (model -> you) | PCM16, mono, 24 kHz |

Raw audio is never stored. Finished transcripts are persisted as `Message` objects with `metadata={"modality": "audio"}`.

---

## Quick start: WAV file in, WAV file out

```python
import asyncio
import wave

from tenxgraph.core.realtime.base import OUTPUT_SAMPLE_RATE, RealtimeConfig
from tenxgraph.core.realtime.queue import LiveInputQueue
from tenxgraph.prebuilt.agent import AudioAgent

MODEL = "gemini-3.8-live"

# 1. Compile the agent once.
app = AudioAgent(
    MODEL,
    realtime_config=RealtimeConfig(
        model=MODEL,
        voice="Puck",
        system_instruction="You are a concise voice assistant.",
    ),
).compile()

async def main():
    # 2. Open a WAV file for output (24 kHz, mono, PCM16).
    out = wave.open("out.wav", "wb")
    out.setnchannels(1)
    out.setsampwidth(2)
    out.setframerate(OUTPUT_SAMPLE_RATE)

    # 3. Create the input queue and load your audio.
    with wave.open("input.wav", "rb") as wf:
        sample_rate = wf.getframerate()
        pcm = wf.readframes(wf.getnframes())

    queue = LiveInputQueue()

    # 4. Stream input audio in ~100 ms chunks.
    chunk = (sample_rate // 10) * 2  # 100 ms at 2 bytes/sample
    for offset in range(0, len(pcm), chunk):
        queue.send_audio(pcm[offset : offset + chunk], sample_rate=sample_rate)
        await asyncio.sleep(0.0)  # yield so the pump can flush to the socket

    # 5. Iterate events until the session ends.
    try:
        async for event in app.arealtime(queue, {"thread_id": "demo"}):
            if event.type == "audio_delta":
                out.writeframes(event.data)
            elif event.type == "input_transcript" and event.finished:
                print(f"you:   {event.text}")
            elif event.type == "output_transcript" and event.finished:
                print(f"agent: {event.text}")
            elif event.type == "turn_complete":
                queue.close()  # end after the first model turn
    finally:
        out.close()
        await app.aclose()

asyncio.run(main())
```

`input.wav` must be mono 16-bit PCM at 16 kHz. The example in `examples/realtime_audio/audio_agent_file.py` is the reference for this pattern.

---

## Building an AudioAgent

`AudioAgent` is a React-style builder that wraps a `LiveAgent` as the graph root. It mirrors `ReactAgent`'s construction surface.

```python
from tenxgraph.core.realtime.base import RealtimeConfig, VADConfig
from tenxgraph.prebuilt.agent import AudioAgent

def get_weather(location: str) -> str:
    """Get the current weather for a city."""
    return f"It is 22 degrees and sunny in {location}."

app = AudioAgent(
    "gemini-3.8-live",
    realtime_config=RealtimeConfig(
        model="gemini-3.8-live",
        voice="Puck",
        system_instruction="You are a helpful voice assistant. Keep answers brief.",
        input_audio_transcription=True,
        output_audio_transcription=True,
    ),
    tools=[get_weather],
).compile()
```

### compile() parameters

`compile()` takes the same arguments as the other prebuilt agents, such as `checkpointer`, `store`, `callback_manager` and `shutdown_timeout`. A `media_store` raises `ValueError`: images and video go frame by frame through `LiveInputQueue.send_image()` and are never stored.

---

## Driving a session with arealtime

```python
queue = LiveInputQueue()

async for event in app.arealtime(
    queue,
    config={"thread_id": "my-thread"},
    state=None,       # optional AgentState; use to pre-seed custom state fields
):
    match event.type:
        case "audio_delta":
            # PCM16 chunk at 24 kHz; write to speaker or file
            speaker.write(event.data)
        case "input_transcript":
            if event.finished:
                print(f"you: {event.text}")
        case "output_transcript":
            if event.finished:
                print(f"agent: {event.text}")
        case "tool_call":
            print(f"calling {event.name}({event.args})")
        case "turn_complete":
            ...   # model finished speaking; re-enable mic if in echo-safe mode
        case "interrupted":
            ...   # barge-in; flush audio playback buffer
        case "error":
            print(f"error ({event.code}): {event.message}")
            if event.fatal:
                break

queue.close()  # signal end of input
await app.aclose()
```

`arealtime` is an async generator. It yields `RealtimeEvent` objects (see the [reference](/docs/reference/python/realtime) for the full event union).

`realtime(queue, config, state)` is the synchronous equivalent: it drives a private event loop. Do not call it from inside an async context or a running event loop.

---

## LiveInputQueue

`LiveInputQueue` decouples audio capture from the network pump. All `send_*` methods are synchronous and non-blocking (`put_nowait`), so they are safe to call from audio callbacks on any thread.

```python
from tenxgraph.core.realtime.queue import LiveInputQueue

queue = LiveInputQueue()

# Audio input (PCM16, default 16 kHz)
queue.send_audio(pcm16_bytes)
queue.send_audio(pcm16_bytes, sample_rate=16000)

# Text input (injected as a user turn)
queue.send_text("What is the weather in Tokyo?")

# Image input (still image or video frame)
with open("frame.jpg", "rb") as f:
    queue.send_image(f.read())                    # default mime_type="image/jpeg"
    queue.send_image(f.read(), mime_type="image/jpeg")

# Manual VAD / push-to-talk (only when vad.enabled=False)
queue.send_activity_start()
queue.send_activity_end()

# End the session
queue.close()
```

Once closed, further sends are dropped silently. Image frames are not persisted to history; on reconnect only text transcripts are reseeded.

---

## Tools

Tools are advertised to the model at connect time through the same `ToolNode` mechanism as `ReactAgent`. The model calls them during a turn; 10xGraph dispatches the call and returns the result before the model continues speaking.

```python
from tenxgraph.utils import tool

@tool
def lookup_order(order_id: str) -> str:
    """Look up a customer order by ID."""
    return f"Order {order_id} ships tomorrow."

app = AudioAgent(
    "gemini-3.8-live",
    realtime_config=RealtimeConfig(model="gemini-3.8-live"),
    tools=[lookup_order],
).compile()
```

Tool events appear in the stream as `ToolCallEvent` (before execution) and `ToolResultEvent` (after). Handoff to other agents is not wired into realtime sessions.

**A tool call runs once per thread.** If the provider re-sends a call after a reconnect, or a new session on the same thread repeats it, 10xGraph returns the recorded result instead of running the tool again. The key is the thread id, a hash of the tool name and arguments, and the provider's call id, and it needs a checkpointer on the session. This matters for tools with side effects such as payments or emails. See [Tool call deduplication](/docs/reference/python/realtime#tool-call-deduplication).

---

## System prompt, skills, and memory

`system_prompt`, `skills`, and `memory` work the same as `ReactAgent`. They are flattened into Gemini Live's single `system_instruction` string at connect time. `{field}` placeholders in the prompt are interpolated from state at connect time.

```python
AudioAgent(
    MODEL,
    realtime_config=RealtimeConfig(model=MODEL),
    system_prompt=[
        {"role": "system", "content": "You are a helpful assistant for {user_name}."}
    ],
    skills=skill_config,
    memory=memory_config,
)
```

`system_instruction` is fixed for the session (Gemini Live does not allow mid-session instruction updates). State-dependent content is a connect-time snapshot. For mid-session dynamic behavior, use `activate_skill` or memory tools.

---

## Image and video input

Send still images or video frames directly through the queue. Gemini Live accepts individual frames; send video as a stream of frames (~1 fps is the model's effective ceiling).

```python
import time

import cv2  # pip install opencv-python

cap = cv2.VideoCapture(0)  # laptop camera
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break
    _, jpeg = cv2.imencode(".jpg", frame)
    queue.send_image(jpeg.tobytes())
    time.sleep(1.0)  # ~1 fps
```

---

## Checkpointing and cross-session resume

Pass a checkpointer to `compile()` to persist transcripts and resumption handles across connections.

```python
import os

from tenxgraph.storage.checkpointer import InMemoryCheckpointer, PgCheckpointer

# Development
app = AudioAgent(MODEL, ...).compile(
    checkpointer=InMemoryCheckpointer()
)

# Production (needs the pg_checkpoint extra; Postgres plus Redis)
app = AudioAgent(MODEL, ...).compile(
    checkpointer=PgCheckpointer(
        postgres_dsn=os.environ["DATABASE_URL"],
        redis_url=os.environ["REDIS_URL"],
    )
)
```

Within a session, the runtime automatically reconnects on transient drops and uses the Gemini session resumption handle (stored in the checkpointer thread metadata) to restore provider-side context. When no handle is available, persisted transcripts are reseeded into the fresh session.

To resume across separate `arealtime` calls (different processes or restarts), the same `thread_id` and a persistent checkpointer are all that is required.

---

## Reconnection behavior

Reconnection is automatic and transparent. Two cases:

| Trigger | Behavior |
|---|---|
| `go_away` (planned provider rotation) | Reconnect immediately, no backoff. |
| Transient drop / receive error | Exponential backoff: `min(base * 2^(n-1), max_delay)`, up to `max_attempts`. After that, fatal `ErrorEvent(code="reconnect_failed")` ends the session. |

Configure via `RealtimeConfig.reconnect`:

```python
from tenxgraph.core.realtime.base import RealtimeConfig, ReconnectConfig

config = RealtimeConfig(
    model=MODEL,
    reconnect=ReconnectConfig(
        base_delay=0.5,    # seconds
        max_delay=10.0,    # seconds
        max_attempts=5,    # set 0 to disable error-driven reconnect
    ),
)
```

---

## API server WebSocket bridge

When the configured graph is rooted at a `LiveAgent` (i.e. built with `AudioAgent`), `10xgraph dev` automatically exposes a WebSocket endpoint at `/v1/graph/live`.

### Setup

`10xgraph.json`:

```json
{
  "agent": "graph:app",
  "env": ".env"
}
```

```python
# graph.py
import os
from tenxgraph.core.realtime.base import RealtimeConfig
from tenxgraph.prebuilt.agent import AudioAgent
from tenxgraph.storage.checkpointer import InMemoryCheckpointer

MODEL = os.getenv("GEMINI_LIVE_MODEL", "gemini-3.8-live")
checkpointer = InMemoryCheckpointer()
app = AudioAgent(
    MODEL,
    realtime_config=RealtimeConfig(model=MODEL, voice="Puck"),
).compile(checkpointer=checkpointer)
```

```bash
export GEMINI_API_KEY=...
10xgraph dev --no-open
# WebSocket available at ws://localhost:8000/v1/graph/live
```

The init frame, the binary and JSON frames in each direction and the server limits on `model` and `tools_tags` are in [WebSockets: realtime audio](/docs/server/websockets#realtime-audio-v1graphlive). Image and video input is SDK-only: the bridge does not forward image frames.

---

## Live microphone example

The `examples/realtime_audio/audio_agent_mic.py` example shows full-duplex microphone input with speaker output and barge-in. Run it with:

```bash
pip install sounddevice
export GEMINI_API_KEY=...
python examples/realtime_audio/audio_agent_mic.py
# say: "What's the weather in Tokyo?"   (Ctrl+C to stop)
```

---

## Forcing rules

- A graph containing a `LiveAgent` must use `arealtime()` or `realtime()`. Calling `invoke`, `ainvoke`, `stream`, or `astream` raises `RuntimeError`.
- `arealtime()` requires a graph rooted at exactly one `LiveAgent`. Passing an ordinary graph raises. Passing a graph with more than one `LiveAgent` raises.
- `realtime()` (sync) raises if called from inside a running event loop. Use `arealtime()` from async contexts.

## Run it in production

Realtime audio runs over a long-lived connection, so authenticate the socket and apply the WebSocket limits from `10xgraph.json`. See [WebSockets](/docs/server/websockets), [Server auth](/docs/server/auth) and [Rate limiting](/docs/server/rate-limiting).
