adk-realtime
Real-time bidirectional audio streaming for Rust Agent Development Kit (ADK-Rust) agents.
Stability: Stable — follows semantic versioning, so breaking changes wait for the next major release. See STABILITY.md.
Overview
adk-realtime connects voice agents to real-time streaming APIs. It offers a low-level session
API (RealtimeModel, RealtimeSession), an event loop with tool dispatch (RealtimeRunner), and
RealtimeAgent, which implements adk_core::Agent so a voice agent runs under the standard ADK
runner.
Features
- RealtimeAgent — implements
adk_core::Agentwith instructions, tools, sub-agent handoff, and agent and tool callbacks - Providers — OpenAI Realtime API, Gemini Live API, Vertex AI Live API
- Transports — WebSocket, WebRTC (OpenAI), and a LiveKit bridge
- Audio — PCM16 and G.711 (µ-law, A-law) encodings; Opus on the WebRTC transport
- Voice activity detection — server-side VAD, and
ManualorAutomaticinterruption handling - Governed tool calls — every tool call goes through
adk_core::authorize_tool_call: the kill switch, theToolPolicy, and confirmation - Context mutation — swap instructions and tools mid-session (OpenAI: in-place update; Gemini: session resumption)
- Telephony — phone calls for voice agents (
telephony,openai-sip,livekit-sip): verified webhooks, accept, reject, transfer and hang up over OpenAI Realtime SIP, inbound and outbound calls over LiveKit SIP for any realtime provider, and governedtransfer_call,end_call,send_dtmfandplace_calltools; a kill-switch freeze hangs up the call - Video avatars — HeyGen and D-ID providers (
heygen-avatar,did-avatar) - Opt-in dependencies — no provider or transport is compiled by default
Architecture
┌─────────────────────────────────────────┐
│ Agent trait │
│ (name, description, run, sub_agents) │
└────────────────┬────────────────────────┘
│
┌───────────────────────┼───────────────────────┐
│ │ │
┌──────▼──────┐ ┌─────────▼─────────┐ ┌─────────▼─────────┐
│ LlmAgent │ │ RealtimeAgent │ │ SequentialAgent │
│ (text-based)│ │ (voice-based) │ │ (workflow) │
└─────────────┘ └───────────────────┘ └───────────────────┘
┌──────────────────────────────────────────────────────────────┐
│ RealtimeSession trait │
├──────────────┬──────────────┬──────────────┬─────────────────┤
│ OpenAI WS │ OpenAI WebRTC│ Gemini Live │ Vertex AI Live │
│ (openai) │ (openai- │ (gemini) │ (vertex-live) │
│ │ webrtc) │ │ │
└──────────────┴──────────────┴──────────────┴─────────────────┘
Providers and transports
| Provider | Model | Transport | Feature |
|---|---|---|---|
| OpenAI | gpt-realtime-2.1 |
WebSocket | openai |
| OpenAI | gpt-realtime-2.1 |
WebRTC with Opus | openai-webrtc |
| Google Gemini Live | gemini-3.1-flash-live-preview (default), gemini-3.8-live, gemini-3.8-live-extended-thinking |
WebSocket | gemini |
| Vertex AI Live | gemini-3.8-live |
WebSocket with OAuth2 (ADC) | vertex-live |
| LiveKit | any of the above | WebRTC bridge | livekit |
| Gemini Live model | Choose it for | Setup |
|---|---|---|
gemini-3.1-flash-live-preview |
The default (gemini::DEFAULT_MODEL) |
Optional RealtimeConfig::with_thinking_level |
gemini-3.8-live |
The newer model, with built-in reasoning | No thinking level (not sent); tools declared BLOCKING |
gemini-3.8-live-extended-thinking |
Configurable background reasoning (low, medium, high) | RealtimeConfig::with_thinking_level(Effort::…); the model requires a level, and ADK sends medium unless you set one. Tools run non-blocking; tool calls are unverified, none reached the client in live tests |
Quick Start
[]
= { = "3.0.0", = ["openai"] }
Low-level session
The program sends one text turn and prints the text reply. It needs the openai feature.
use OpenAIRealtimeModel;
use ;
async
RealtimeAgent
RealtimeAgent implements adk_core::Agent, so adk_runner::Runner runs it like any other agent.
The example needs the openai feature.
use RealtimeAgent;
use OpenAIRealtimeModel;
use Arc;
RealtimeAgentBuilder::build fails with agent.duplicate_tool_name when two registered tools
share a name.
Transport guides
Gemini Live
= { = "3.0.0", = ["gemini"] }
use ;
use ;
async
The Gemini Live, OpenAI Realtime, and LiveKit connects install aws-lc-rs as the process-level
rustls provider through adk_core::ensure_crypto_provider(), so an application that also
compiles ring (the livekit feature does) needs no setup; a provider the application
installed first is kept.
Gemini Live takes 16 kHz mono PCM16 input and returns 24 kHz mono PCM16 output.
Vertex AI Live
= { = "3.0.0", = ["vertex-live"] }
use ;
use ;
async
GeminiLiveBackend::Vertex { credentials, region, project_id } takes credentials you built
yourself, and gemini::build_vertex_live_url(region, project_id) returns the endpoint.
OpenAI WebRTC
= { = "3.0.0", = ["openai-webrtc"] }
use ;
use ;
async
openai-webrtc builds the Opus C library from source through audiopus, so cmake must be
installed. With cmake 4.0 or later, set CMAKE_POLICY_VERSION_MINIMUM=3.5.
LiveKit bridge
= { = "3.0.0", = ["livekit", "openai"] }
LiveKitRoomBuilder is a typestate builder: connect() is available once identity is set.
LiveKitConfig keeps the API key and secret as secrecy::SecretString and redacts them in
Debug output.
use ;
async
LiveKitEventHandler::new(inner, audio_source, sample_rate, channels) wraps an EventHandler
and publishes model audio to the room. bridge_input(track, &runner) feeds a participant's audio
track into a RealtimeRunner; bridge_gemini_input does the same at Gemini's 16 kHz.
Mid-session context mutation
RealtimeRunner::update_session swaps instructions and tools without dropping the call:
use RealtimeRunner;
use ;
async
| Provider | Outcome |
|---|---|
| OpenAI | Updates the session in place with session.update (ContextMutationOutcome::Applied) |
| Gemini | Queues a transport resumption that runs when the session is idle (ContextMutationOutcome::RequiresResumption); a newer update replaces a pending one |
See SESSION_MANAGEMENT.md and the openai_session_update and
gemini_context_mutation examples.
Interruption detection
use ;
Manual(default): the application cancels responses explicitly.Automatic: VAD detects the start of user speech and cancels the agent's audio output.
Tool governance
RealtimeAgent, RealtimeRunner, and IntegratedRealtimeRunner (integration feature) dispatch
every tool call through adk_core::authorize_tool_call. RealtimeAgent reads the kill switch,
ToolPolicy, and confirmation from the run's RunConfig and runs the runner's plugin callbacks;
the runners take them from tool_governance on their builders, and without it govern under
RunConfig::default(). No runner runs a tool call outside the governed path.
| Behaviour | Rule |
|---|---|
| Kill switch | Each runner has one: governance() returns it, governance(control) on the builder shares one across runners. A freeze stops the next call of an open session, and RealtimeRunner::run ends with governance.frozen |
| Confirmation | require_tool_confirmation(name), require_tool_confirmation_for_all() and tool_confirmation_policy(policy) on RealtimeAgentBuilder and both runner builders. A call that needs confirmation is decided by the governance config's handler, approvals or approval store; with none of them (and, for IntegratedRealtimeRunner, no session service to hold it in) the runner refuses it with a reason the model can speak |
| Tool timeout | tool_timeout(duration) answers a call that runs too long with an error; the default is five minutes |
| Malformed arguments | Arguments that are not valid JSON are answered with an error and the tool does not run |
| Tool and callback errors | The model receives the error's component, category, and code; expose_tool_error_messages(true) sends the full message |
| After-tool failure | An after-tool callback or plugin error withholds the result (result_withheld) |
| Result screening | tool_result_screen(screen) rewrites or withholds each result before the model sees it; a screen that cannot decide withholds the result |
| Authenticated identity | IntegratedRealtimeRunnerBuilder::request_context(ctx) runs every tool call as the identity the server authenticated: tool contexts answer is_authenticated() with true and user_scopes() with its scopes. Without it they report an unauthenticated user; a context for a user other than identity's fails build |
| Run config in tool contexts | Every tool context answers run_config() with the governance config (run_config() on the runner) and acting_context() with the acting context the gate authorized the call under |
Secrets in Debug |
OpenAIRealtimeModel and GeminiLiveBackend redact their API key and credentials from Debug output |
| Governing agent | agent_name(name) on either runner builder names the agent calls are governed, metered and held under (default realtime); a surface running an existing agent's tools sets that agent's name, so its tool policy recognises them |
| Held calls | A call the governed path holds, or that a tool's delegate holds (an AgentTool whose agent held a call), is answered to the model as confirmation_pending, recorded in the session under the runner's agent name (agent_name, default realtime) and in the run's ApprovalStore, and surfaced as ServerEvent::ToolConfirmationRequested; held_calls() lists them and resume_held_calls() runs each one that has a decision under its original call ID. RealtimeAgent holds its own call when its delegate holds one and resumes decided calls at the start of a run |
| Approval binding | A held call's request names the runner's acting agent and the tool's origin: an ADK tool's Tool::origin(), or for a native handler REALTIME_HANDLER_ORIGIN (realtime) with a digest of its ToolDefinition (ToolDefinition::handler_origin), so an approval never covers another agent's call, a Tool of the same name, or a handler redefined since |
| Concurrent dispatch | IntegratedRealtimeRunnerBuilder::concurrent_tool_dispatch(true) runs each dispatch on its own task, so next_event keeps reading provider events while a tool runs; off by default |
| Waiting for results | On gemini-3.8-live a tool is declared BLOCKING, so the model answers with the result in the turn that called it; ToolDefinition::with_behavior(ToolBehavior::NonBlocking) lets the conversation continue while a tool runs. gemini-3.8-live-extended-thinking accepts only non-blocking tools; other models keep their own default |
| Metering | With a spend_ledger in the governance config, every response reserves a hold (the run's LlmSpendEstimate) when it starts and commits its cost when it ends: RealtimeUsage::from_response reads OpenAI's response.usage or Gemini's usageMetadata, realtime_pricing(RealtimePricing) prices it, and without pricing the estimate is committed. A refused hold ends the session with RealtimeError::SpendRefused. RealtimeAgent yields the usage on an event at each response's end |
| Output guardrails | output_guardrails(GuardrailSet) (feature guardrails) screens each completed turn as LlmAgent screens final text: a transform replaces the persisted text; a block interrupts the response, persists nothing of the turn and reports RealtimeError::OutputBlocked (the agent ends the run with the guardrail's error) |
RealtimeAgent builder
| Method | Description |
|---|---|
instruction(str), instruction_provider(fn) |
Static or dynamic system instruction |
global_instruction(str), global_instruction_provider(fn) |
Global instruction, prepended |
tool(Arc<dyn Tool>), toolset(Arc<dyn Toolset>) |
Register tools |
sub_agent(Arc<dyn Agent>) |
Register a sub-agent for handoff |
before_agent_callback, after_agent_callback |
Agent callbacks |
before_tool_callback, after_tool_callback |
Tool callbacks |
tool_timeout, tool_result_screen, expose_tool_error_messages |
See Tool governance |
voice(str) |
Voice, such as "alloy" |
server_vad(), vad(VadConfig) |
Server-side VAD with defaults, or custom VAD |
modalities(vec) |
Output modalities, such as ["audio"] or ["text"]. Unset, the provider's default applies: audio with a transcript on OpenAI and Gemini Live |
transcription() |
Transcribe the user's speech (and, on Gemini Live, the model's), so spoken turns are saved |
on_audio, on_transcript, on_speech_started, on_speech_stopped |
Event callbacks |
avatar(AvatarConfig), avatar_provider(provider) |
Video avatar (video-avatar) |
Under Runner, the agent saves each of the user's spoken turns (with transcription()) as a
user event ahead of the model's reply: on OpenAI when its transcript completes, on Gemini Live,
which never completes a transcript, when the model's reply starts or ends. Each reply is saved
under its own event id, also on Gemini Live, which streams replies without an item id. A
session the provider closes with a failure code — Gemini Live closes with 1007 on a setup it
refuses — ends the run with model.realtime.session_closed, carrying the code and the
provider's reason.
Events
| Server event | Description |
|---|---|
SessionCreated, SessionUpdated |
Session established or updated |
AudioCommitted, AudioCleared |
Input audio buffer committed or cleared |
ItemCreated |
Conversation item created |
OutputItemAdded, OutputItemDone |
Response output item added or completed |
AudioDelta, AudioDone |
Output audio chunk, end of output audio |
TextDelta, TextDone |
Text response chunk, end of text |
TranscriptDelta, TranscriptDone |
Transcript of the output audio |
InputTranscriptDelta, InputTranscriptCompleted |
Transcript of the user's input audio |
FunctionCallDelta, FunctionCallDone |
Tool call arguments, completed tool call |
ResponseCreated, ResponseDone |
Response started, response completed |
ToolConfirmationRequested |
A tool call held for a confirmation decision (emitted by the integrated runner, not a provider) |
SpeechStarted, SpeechStopped |
VAD detected speech or silence (OpenAI speech_started / speech_stopped, Gemini Live voiceActivity) |
RateLimitsUpdated |
Rate limit information |
Error |
Provider error |
Unknown |
An event type this version does not model |
| Client event | Description |
|---|---|
AudioDelta |
Append audio to the input buffer |
InputAudioBufferCommit, InputAudioBufferClear |
Commit or clear the input buffer |
ConversationItemCreate |
Send a text message or tool response |
ResponseCreate, ResponseCancel |
Request or cancel a response |
SessionUpdate |
Update the session configuration |
Message |
A message with adk_core roles and parts |
UpdateSession |
Mid-session instruction and tool update for the runner to intercept; never serialized to the provider |
Audio formats
| Encoding | Sample rate | Provider |
|---|---|---|
| PCM16 mono | 24 kHz | OpenAI input and output, Gemini output |
| PCM16 mono | 16 kHz | Gemini input |
| G.711 µ-law, A-law | 8 kHz | OpenAI |
| Opus | 24 kHz mono | OpenAI WebRTC |
Feature flags
| Feature | Enables | Requires |
|---|---|---|
openai |
OpenAI Realtime API over WebSocket | |
gemini |
Gemini Live API over WebSocket | |
vertex-live |
Vertex AI Live API with ADC (implies gemini) |
GCP credentials |
openai-webrtc |
OpenAI WebRTC transport with Opus (implies openai) |
cmake |
livekit |
LiveKit WebRTC bridge | a LiveKit server |
telephony |
Provider-neutral call control (CallControl, CallAnswerer, OutboundDialer), hang_up_on_freeze, and the call-control tools |
|
openai-sip |
OpenAI Realtime SIP: webhook verification, accept, reject, refer, hang up, and a session attached to a call (implies openai, telephony) |
an OpenAI SIP trunk |
livekit-sip |
LiveKit SIP over the server API: trunks, dispatch rules, participant_joined webhooks, outbound calls, transfer, hang up (implies telephony; no WebRTC stack) |
a LiveKit server with SIP |
video-avatar |
Avatar configuration and the AvatarProvider trait |
|
heygen-avatar |
HeyGen LiveAvatar provider (implies video-avatar, livekit) |
|
did-avatar |
D-ID Realtime Agents provider (implies video-avatar) |
|
integration |
IntegratedRealtimeRunner: sessions, memory, and plugins around RealtimeRunner |
|
guardrails |
Output guardrails on the model's text and transcripts (adk-guardrail) |
|
scripted |
ScriptedRealtimeModel: a provider-free model that answers each client action from a script, for tests |
|
record-payloads |
Quotes provider frames in OpenAI schema-drift warnings; without it they are redacted | |
full |
openai, gemini, vertex-live, livekit |
|
full-webrtc |
full and openai-webrtc |
cmake |
No feature is enabled by default.
Examples
# OpenAI mid-session context mutation
# Gemini mid-session context mutation (session resumption)
# Vertex AI Live voice assistant and tools (ADC and a GCP project)
# LiveKit bridge with OpenAI or Gemini (a LiveKit server)
# OpenAI WebRTC (cmake)
CMAKE_POLICY_VERSION_MINIMUM=3.5
# Video avatars
Testing
CMAKE_POLICY_VERSION_MINIMUM=3.5
# Integration tests that need credentials are #[ignore]
License
Apache-2.0
Part of ADK-Rust
This crate is part of the ADK-Rust framework for building AI agents in Rust.