Add realtime speech-to-speech support
Adds native support for realtime, bidirectional speech-to-speech (and live video) models behind a
small provider-agnostic abstraction that lives alongside the request-response Model interface, with
two providers out of the box — OpenAI Realtime and Gemini Live.
Builds on the approach explored in #4375 (closed), incorporating its review feedback and migrating to
the GA OpenAI Realtime API (the beta surface is no longer supported).
What's added
pydantic_ai.realtime— provider-facing ABCs and the session:RealtimeModel(connect()opens a connection) andRealtimeConnection(send()content in,
iterate events out) — a sans-IO-style boundary so adding a provider is one file.RealtimeSession— wraps a connection and runs the tool loop automatically: intercepts each
ToolCall, executes it, sends theToolResultback, and emitsToolCallStarted/
ToolCallCompleted. Tools listed inbackground_toolsrun concurrently (the model keeps
talking while they work) and are multiplexed through one queue so a completion never stalls the
stream; others run synchronously. AToolResultis always returned, so the model never stalls.
Tracks cumulativeusage(aRunUsage) across the session.- Typed inputs —
AudioInput,TextInput,ImageInput(a video frame),ToolResult, plus the
manual turn-taking verbsCommitAudio,ClearAudio,CreateResponse,CancelResponse,
TruncateOutput. - Typed events —
AudioDelta,Transcript,InputTranscript(streamed),ToolCall,
TurnComplete,SpeechStarted/SpeechStopped,Usage,RateLimits,Reconnected,
SessionError(withtype/code/recoverable), plus the session-levelToolCallStarted/
ToolCallCompleted.
Agent.realtime_session(model, *, deps, model_settings, instructions, background_tools)— the
high-level entry point; resolves the agent's per-run toolsets and instructions into a session and
forwards instrumentation.- OpenAI provider (
pydantic_ai.realtime.openai) overwebsockets: GA/v1/realtime, PCM16 @
24 kHz, function calling, input transcription, and barge-in. Configurable turn-taking
(ServerVAD/SemanticVAD/Nonefor push-to-talk), input noise reduction, output modalities,
and output speed; token usage and rate-limit snapshots; and an optionalReconnectPolicythat
re-dials with backoff. It defersresponse.createwhile a response is active (so a background-tool
result landing mid-answer is still announced, not dropped) and does not replay it after a barge-in. - Gemini provider (
pydantic_ai.realtime.google) over thegoogle-genaiSDK: PCM16 @ 16 kHz
input (24 kHz output), one response modality per session, and native live video frames (each
ImageInputis sent as avideoblob) — enabling "show me this" camera interactions. A broad,
optional configuration surface:voice/language_code/multi_speaker,affective_dialog
andproactive_audio(native-audio),AutomaticVAD(disabled + start/end sensitivity + padding/
silence),activity_handling,turn_coverage, transcription language hints,ContextCompression
for long sessions, transparent reconnect via session resumption (enable_session_resumption+
ReconnectPolicy, which restores server state), and aconfig_overridesescape hatch. Generation
parameters (temperature,top_p,top_k,max_tokens,seed,google_thinking_config,
google_video_resolution) are read frommodel_settings, consistent with the non-realtime Google
model. Authenticates with an API key or Vertex AI via Application Default Credentials
(vertexai=True), useful where org policy disallows API keys. - Observability — when the agent is instrumented (
logfire.instrument_pydantic_ai()), a session
emits an OpenTelemetry span tree: therealtime <model>session (cumulative usage + transcript as
gen_ai.input.messageswheninclude_content) with anexecute_toolspan per tool call
(including any delegated text-agent run) nested underneath. - Optional dependency groups —
realtime(websockets>=14.0) for OpenAI; the Gemini provider
usesgoogle-genai, already a pydantic-ai dependency (googlegroup).
Design notes
- Separate from
Modelon purpose. Realtime is a long-lived, full-duplex session, not
request-response — so it gets its own ABCs, while reusingToolDefinitionandModelSettings. - Structured output is delegated, not faked. Realtime models don't support structured output, so
the recommended pattern is to expose a single tool that hands off to a normalAgentwith an
output_type. The finance example demonstrates this end-to-end. - Provider-agnostic. Everything above the provider (
RealtimeSession,Agent.realtime_session,
instrumentation) depends only on the ABCs and shared types; a new provider (Nova Sonic, ...) is a
connect()+ event-mapping module. Provider-specific knobs (VAD types, reconnect, voice config)
live in the provider module, with names mirrored across providers where the concept is shared.
Docs & examples
- Guide:
docs/realtime.md(quickstart, configuration incl. a Gemini config matrix, turn-taking &
barge-in, push-to-talk, images/live vision, usage & cost, Logfire, reconnect, delegation); API
reference:docs/api/realtime.md. Both added to nav. - Two runnable examples (each with its own docs page):
realtime_finance/— a voice finance assistant where the realtime model delegates to a
supervisor agent whose typed Pydantic tool outputs render as cards, showing both sync and
background ("subagent") dispatch. A UI settings panel switches provider/model/voice and
provider-specific tuning.realtime_camera/— a "talk and show your camera" assistant on Gemini Live, streaming mic audio- ~1 fps frames, with a Watch toggle for proactive narration. Runs on localhost; documents
exposing it to a phone over HTTPS via a Cloudflare quick tunnel, and Vertex AI auth.
- ~1 fps frames, with a Watch toggle for proactive narration. Runs on localhost; documents
Tests
-
Network-free tests under
tests/realtime/(fake connection/model, fake websocket, fakegoogle-genai
session); 100% coverage of thepydantic_ai.realtimemodule. Optional-dependency and
instrumentation imports are guarded so the slim/evals CI jobs collect cleanly. Pyright/mypy/ruff clean. -
Closes #1447
Checklist
- Any AI generated code has been reviewed line-by-line by the human PR author, who stands by it.
- No breaking changes in accordance with the version policy.
- PR title is fit for the release changelog.
Context: Found while building project at Vstorm · github.com/vstorm-co.