Add realtime speech-to-speech support with `Agent.realtime()`
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
ModelMessagehistory via a newSpeechPart(member of both part unions,speakerdiscriminator; optionaltranscriptandaudio, plus acontentproperty mirroringTextPartfor generic consumers).session.all_messages()feeds straight intoagent.run(message_history=...)for realtime↔text handoff, andmessage_history=seeds a session from prior conversation (text/transcript projection). Native-tool results (GeminiWebSearch/WebFetchgrounding and code execution) are written into history asNativeToolCallPart/NativeToolReturnPartmatching the classic path, so they survive the handoff too. NewModel.prepare_messagesnormalization means every existing model accepts realtime history.audio_retentioncontrols whether raw audio is kept. - Events: the session emits the shared vocabulary —
PartStartEvent/PartDeltaEvent/PartEndEvent(withSpeechPartDeltacarrying transcript and audio chunks) andFunctionToolCallEvent/FunctionToolResultEvent— plus a small set of realtime control events (ResponseCompleteEventper model response andTurnCompleteEventwhen 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 viaprovider='gateway/openai'). xAI Grok Voice and Azure OpenAI both implement the OpenAI realtime wire protocol, soXaiRealtimeModeland the GAAzureRealtimeModelreuse a shared_openai_protocolcodec 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.profilereturns aRealtimeModelProfile— aModelProfile-styleTypedDictofsupports_*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, andsupported_native_tools) — making provider gaps queryable; gated session methods raiseUserErrorbefore sending instead ofNotImplementedErrormid-session, and requested native tools (session- or capability-contributed) are validated up front againstsupported_native_toolswith one uniform error, mirroring the classic path'sModel.supported_native_tools(). It's a standalone parallel toModelProfile(realtime models have their own flags and don't compose with the LLM profile). - Instrumentation: capability-native —
realtime()injects theInstrumentationcapability exactly likerun()/iter()do, so tool spans flow through the capability'swrap_tool_execute(an explicitInstrumentationcapability's settings win overinstrument=, no double spans). Per-responsechat {model}spans share attribute-building code with the classic path (response_attributes()helper) under arealtime {model}session span with aggregated usage; session/turn spans move fully onto capability hooks when exchange-level hooks land. Each provider'sconnect()also injects W3C trace context into the WebSocket handshake headers (the raw socket bypasses the provider'shttpxclient, 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_capabilitieshelper asrun/iter(extracted fromiterand shared), so a capability's setup contributions — instructions, native tools (including underoverride(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-Agentduplication breaking the Gemini Live handshake entirely onwebsockets>=14, Gemini native-audio thinking text leaking into transcripts, and OpenAI seeding rejecting assistant items encoded astextinstead ofoutput_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:
- 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 theRealtimeModel(it needs the provider's credentials), returning a small typed result (secret, expiry, connect URL). - 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_useRealtimeReact 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. - 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.
- Ephemeral client-token minting on the realtime models — the equivalent of Vercel AI Gateway's
- 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
ReconnectPolicyre-dial succeeds, re-seed the fresh connection from the session's accumulatedModelMessagehistory via the existingconnect(messages=...)text-projection path, so a dropped OpenAI/Azure connection (no native resumption) no longer loses the conversation. TheReconnectedEventshould say whether context was restored.
- 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
- Per-model-name profile resolution / provider-level merging — each
RealtimeModelclass currently returns one fixedRealtimeModelProfile. That's already a mild over-claim (OpenAI'sgpt-4o-realtime-previewlacks the image input GAgpt-realtimehas), 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 aProvider.realtime_model_profile(model_name)resolver folded intoRealtimeModel.profile(needs atotal=Falsepartial-override variant; mirrors the classicProvider.model_profile()+merge_profile()split, intrinsic-vs-provider-API division included). Purely additive —model.profileis a computed property over a plainTypedDict, so no freeze risk and nothing to reserve now. - More providers — Amazon Nova Sonic (Bedrock): a genuinely new
RealtimeConnectionimpl 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 viaprovider='azure'/AzureRealtimeModel, live-verified against a real resource; it reuses the shared OpenAI-protocol codec over Azure's/openai/v1/realtimeWebSocket URL with anapi-keyheader. Azure AI Voice Live — Microsoft's managed speech-to-speech superset on the same resource/key — is a stacked follow-up in #6642 (an additiveazure_voice_livesetting). OpenRouter has no realtime API.) - Realtime-specific capability hooks (
wrap_realtime_exchange-style, onAbstractCapability) — planned follow-up; will also let session/turn spans move fully onto theInstrumentationcapability. Tool-execution hooks already fire viaToolManager. - 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 handingsession.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(): theToolReturnPartis inserted directly after the response carrying its call (request-response APIs demand that adjacency), while theFunctionToolResultEventstreams in true completion order and the part'stimestamprecords 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:SpeechPartnormalization happens there) or the graph'sclean_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-responseBackgroundToolscapability 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
websocketslibrary, 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