Add realtime speech-to-speech support with `Agent.realtime()`

Merged
DO
4mo ago
+62458-741

Updated since the last review rounds (2026-07-22):

  • API: the entry point is now agent.realtime(model, ...).session() — an AgentRealtime accessor that binds the agent's realtime config once (mirroring iter) so a session, and (in the stacked WebRTC PR) browser signaling, reuse the same instructions and tools without re-passing them. Agent.realtime_session() is removed.
  • Typed frame parsing: the OpenAI-protocol codec now parses every inbound WebSocket frame through the OpenAI SDK's typed openai.types.realtime.* models (via the SDK's lenient recursive construct()), instead of raw dict reads — dispatching on the wire type so clone/beta events aren't mis-classified. Transport and every cassette are unchanged.
  • Azure: this PR now ships Azure OpenAI GA realtime as a single AzureRealtimeModel (provider='azure' / AzureProvider, api-key auth, /openai/v1/realtime), live-verified. Azure AI Voice Live moved to a stacked follow-up, #6642 (additive azure_voice_live setting), so nothing here is breaking.
  • New events / usage: InputTranscriptionFailedEvent (recoverable), input-transcription (ASR) usage reported in RunUsage.details separate from response tokens, and ReconnectedEvent.state_restored distinguishing providers that restore vs lose conversation state on reconnect.
  • Gateway: realtime detects gateway providers via a registry (works for both provider='gateway/openai' and a gateway_provider('openai') instance) so it adds the required /v1 WebSocket path either way.
  • Docs: docs/realtime.md restructured into a Realtime sidebar section — an overview (positioning, one-agent-many-modalities, choose-your-path, connecting a frontend, troubleshooting, provider matrix) plus per-provider pages (OpenAI, Azure, xAI, Gemini).
  • Plus review-blocker fixes from a deep review pass (see commits).

Adds realtime (speech-to-speech) support: Agent.realtime() opens a bidirectional session against OpenAI Realtime, Gemini Live, xAI Grok Voice, or Azure OpenAI realtime, with the agent's tools, instructions, and capabilities wired through the existing framework infrastructure.

This builds directly on #6042 by @DEENUU1 (thank you Kacper! your commits are preserved in this branch) and reshapes it per our internal design work on realtime integration:

Kept from #6042: the RealtimeModel/RealtimeConnection provider seam, the session tool loop with background_tools, the run-setup reuse (toolsets → ToolManager.handle_call, instructions, capability tool hooks, durable-exec guards), both providers on the GA APIs, usage limits, reconnection, and the docs structure.

Changed:

  • Message history: sessions now build ordinary ModelMessage history via a new SpeechPart (member of both part unions, speaker discriminator; optional transcript and audio, plus a content property mirroring TextPart for generic consumers). session.all_messages() feeds straight into agent.run(message_history=...) for realtime↔text handoff, and message_history= seeds a session from prior conversation (text/transcript projection). Native-tool results (Gemini WebSearch/WebFetch grounding and code execution) are written into history as NativeToolCallPart/NativeToolReturnPart matching the classic path, so they survive the handoff too. New Model.prepare_messages normalization means every existing model accepts realtime history. audio_retention controls whether raw audio is kept.
  • Events: the session emits the shared vocabulary — PartStartEvent/PartDeltaEvent/PartEndEvent (with SpeechPartDelta carrying transcript and audio chunks) and FunctionToolCallEvent/FunctionToolResultEvent — plus a small set of realtime control events (ResponseCompleteEvent per model response and TurnCompleteEvent when the exchange is over, InputSpeechStartEvent/InputSpeechEndEvent, ResponseInterruptedEvent, SessionReconnectEvent, SessionErrorEvent, …, Event-suffixed to match the framework's event naming), instead of a parallel event system.
  • Providers: realtime models route through pydantic_ai.providers (provider='openai' / 'google' / 'xai' / 'azure'; Vertex AI works; OpenAI-compatible base URLs work; the Pydantic AI Gateway works via provider='gateway/openai'). xAI Grok Voice and Azure OpenAI both implement the OpenAI realtime wire protocol, so XaiRealtimeModel and the GA AzureRealtimeModel reuse a shared _openai_protocol codec module — two more providers validating the abstraction. (Azure AI Voice Live — Microsoft's managed speech-to-speech superset — is a stacked follow-up, #6642.)
  • Model profile: RealtimeModel.profile returns a RealtimeModelProfile — a ModelProfile-style TypedDict of supports_* flags (supports_image_input, supports_manual_turn_control, supports_interruption, supports_output_truncation (split out because xAI can cancel but not truncate), supports_session_seeding, and supported_native_tools) — making provider gaps queryable; gated session methods raise UserError before sending instead of NotImplementedError mid-session, and requested native tools (session- or capability-contributed) are validated up front against supported_native_tools with one uniform error, mirroring the classic path's Model.supported_native_tools(). It's a standalone parallel to ModelProfile (realtime models have their own flags and don't compose with the LLM profile).
  • Instrumentation: capability-native — realtime() injects the Instrumentation capability exactly like run()/iter() do, so tool spans flow through the capability's wrap_tool_execute (an explicit Instrumentation capability's settings win over instrument=, no double spans). Per-response chat {model} spans share attribute-building code with the classic path (response_attributes() helper) under a realtime {model} session span with aggregated usage; session/turn spans move fully onto capability hooks when exchange-level hooks land. Each provider's connect() also injects W3C trace context into the WebSocket handshake headers (the raw socket bypasses the provider's httpx client, so this is the realtime analogue of the gateway provider's HTTP request hook), so a proxy like the Pydantic AI Gateway can nest its own realtime spans under the client's trace when a span is active as the session connects.
  • Capabilities: a session resolves capabilities through the same Agent._resolve_run_capabilities helper as run/iter (extracted from iter and shared), so a capability's setup contributions — instructions, native tools (including under override(native_tools=...)), model settings, and toolsets — reach a session exactly as they reach a run, and the two can't silently drift. Only the tool hooks run (prepare_tools, tool_validate, tool_execute); model-request/graph/output/event-stream hooks have no corresponding stage in a session and are skipped. Documented in the realtime guide; session/turn-level capability hooks (to wrap a whole exchange) are a planned addition.
  • Tests: a WebSocket cassette engine (VCR can't record WS) with real recorded protocol sessions for all three providers — which immediately caught three live bugs mocks couldn't: a User-Agent duplication breaking the Gemini Live handshake entirely on websockets>=14, Gemini native-audio thinking text leaking into transcripts, and OpenAI seeding rejecting assistant items encoded as text instead of output_text. All fixed here.
  • Examples: the two large demo apps are replaced by a single minimal realtime_voice.py; the full apps can return separately.

Limitations and planned follow-ups

Documented in the docs' "Not yet supported" section, and called out here explicitly:

  • Browser/client story (ephemeral tokens + end-to-end frontend demo) — planned follow-up. Sessions are currently server-side WebSocket only; browsers can't connect through Pydantic AI. The follow-up, in implementation order:
    1. Ephemeral client-token minting on the realtime models — the equivalent of Vercel AI Gateway's getToken. OpenAI: POST /v1/realtime/client_secrets (client secret + expiry; tools/instructions/session config can be bound into the secret at mint time). xAI: same endpoint shape, token delivered to the WebSocket as a subprotocol string (xai-client-secret.{token}). Gemini: v1alpha ephemeral auth tokens. The method belongs on the RealtimeModel (it needs the provider's credentials), returning a small typed result (secret, expiry, connect URL).
    2. End-to-end demo with a real frontend: a Python backend endpoint that mints the token and declares the agent's tools, consumed by a Vercel AI SDK experimental_useRealtime React frontend connecting directly to the provider. The repo already ships Vercel AI chat-UI protocol support (pydantic_ai.ui.vercel_ai) to build on/align with.
    3. WebRTC SDP relay + server-side "sideband" control session (Python answers the browser's WebRTC offer, then attaches a server-side control WebSocket to the live call so the agent runs tools/history while the browser owns media) — the bigger step, full design exists internally; not needed for Vercel-SDK-frontend parity.
  • Session resumption:
    • Native provider resumption — shipped in this PR: Gemini Live session-resumption handles (enable in setup, store handle updates from the server, pass the handle on reconnect) and xAI resumption.enabled + reconnect with ?conversation_id= (server caches for a reportedly ~30-minute window). These are two different shapes, so each is a per-provider mechanism keyed to its own token rather than one unified abstraction, and both restore prior turns automatically on reconnect (xAI suppresses the provider's replay burst from the local event stream). OpenAI Realtime and Azure OpenAI offer no native resumption.
    • Provider-agnostic re-seed on reconnect — planned follow-up (cheap now that history is first-class): when a ReconnectPolicy re-dial succeeds, re-seed the fresh connection from the session's accumulated ModelMessage history via the existing connect(messages=...) text-projection path, so a dropped OpenAI/Azure connection (no native resumption) no longer loses the conversation. The ReconnectedEvent should say whether context was restored.
  • Per-model-name profile resolution / provider-level merging — each RealtimeModel class currently returns one fixed RealtimeModelProfile. That's already a mild over-claim (OpenAI's gpt-4o-realtime-preview lacks the image input GA gpt-realtime has), and gateways (LiteLLM, Vercel AI Gateway) front OpenAI+Gemini+xAI — with differing profiles — behind one endpoint. When a second flag starts differing by model name, add a Provider.realtime_model_profile(model_name) resolver folded into RealtimeModel.profile (needs a total=False partial-override variant; mirrors the classic Provider.model_profile() + merge_profile() split, intrinsic-vs-provider-API division included). Purely additive — model.profile is a computed property over a plain TypedDict, so no freeze risk and nothing to reserve now.
  • More providers — Amazon Nova Sonic (Bedrock): a genuinely new RealtimeConnection impl over HTTP/2 bidirectional streams + SigV4 with its own event vocabulary (sessionStart/promptStart/contentStart/audioInput…) — the sans-IO seam accommodates it, but it's the one integration that would stress the event verb set. (Azure OpenAI GA realtime is now supported via provider='azure' / AzureRealtimeModel, live-verified against a real resource; it reuses the shared OpenAI-protocol codec over Azure's /openai/v1/realtime WebSocket URL with an api-key header. Azure AI Voice Live — Microsoft's managed speech-to-speech superset on the same resource/key — is a stacked follow-up in #6642 (an additive azure_voice_live setting). OpenRouter has no realtime API.)
  • Realtime-specific capability hooks (wrap_realtime_exchange-style, on AbstractCapability) — planned follow-up; will also let session/turn spans move fully onto the Instrumentation capability. Tool-execution hooks already fire via ToolManager.
  • Audio replay when seeding — message_history= seeds via text/transcript projection only; replaying retained audio into a new session is a possible follow-up.
  • SIP / telephony transport — out of scope for now; the provider seam doesn't preclude it.
  • Mid-session instruction changes — deliberately unsupported (context-cache cost trap; provider support is inconsistent).
  • Bounded structured-output runs (session.run(output_type=...)) — not planned unless demand materializes: live voice sessions are long-running human conversations; structured extraction is served by handing session.all_messages() to a text agent afterwards (the documented delegation pattern).
  • Concurrent tool results vs. epistemically faithful history — design question to grapple with post-release. Tools run concurrently, so a result can arrive after later turns. The session currently canonicalizes all_messages(): the ToolReturnPart is inserted directly after the response carrying its call (request-response APIs demand that adjacency), while the FunctionToolResultEvent streams in true completion order and the part's timestamp records when it really arrived. The cost: a text LLM continuing that history sees a result already present that intervening assistant speech visibly didn't use — an incoherent world model that could degrade continuation quality (and diverges from the provider-side conversation, which stores the item at its true position — including what we'd re-seed on reconnect). Alternatives considered: store true order and normalize adjacency at the LLM seam — Model.prepare_messages (precedent: SpeechPart normalization happens there) or the graph's clean_message_history (precedent: dangling-tool-call cleanup, though it doesn't currently work across request/response boundaries) — so renderers/logs keep the truth and only LLM-bound requests get reordered; and/or render a placeholder + "result arrived: …" note (possibly reusing the <system>-tagged-user-part mechanism) so the continuation LLM sees exactly what happened. Wrinkle: the harness's request-response BackgroundTools capability must own its placeholder/late-result injection (only it knows a dangling call still has a result coming — a generic clean step can't distinguish that from a genuinely abandoned call), so a generic seam solution risks duplicating that logic with a different look; unifying the two representations is a worthy goal but undesigned. Current insertion behavior is the conservative choice and ordering isn't contractual, so this can change in a minor release.
  • Move realtime WebSockets onto httpx2 — OpenAI/xAI realtime currently hand-roll the wire protocol over the websockets library, bypassing the provider's HTTP client (which is why gateway trace-context injection needed a hand-rolled hook). httpx2 — the Pydantic-maintained fork of httpx — supports WebSockets, and the project is moving to it anyway; realtime should use it and route through the provider's client so request hooks come back for free. Wrinkle: users can pass their own client, which may not support WebSockets — capability-detect and fall back to constructing our own. (xAI passes its token as a WS subprotocol; reconnect logic moves too.)
  • Example apps — the camera demo is back in this PR (examples/pydantic_ai_examples/realtime_camera/, ported to the final API and verified live); the finance-dashboard demo can return separately once debugged.

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.

🤖 Generated with Claude Code