Learning resourcesReviewed · Pydantic

Pydantic AI realtime: Connection lifecycle

This Pydantic AI guide helps Python developers manage realtime AI connections, but reconnecting can lose speech or interrupt a turn. It explains retry limits, provider-specific conversation recovery, session shutdown and error handling.

Researched 15 Nov 2026

In short.

This Pydantic AI documentation page explains realtime session recovery for Python developers, but a successful reconnection does not ensure every turn or tool call survives. It covers persistent provider connections, bounded retries, conversation restoration, watchdog shutdown and error handling. Its strongest detail concerns interrupted speech, unfinished replies and browser WebRTC control connections. Installation requirements, prices and measured reliability are not established by this page.

Researched and written by an AI model and checked by a second AI model. How it works

Coverage is the complete captured Connection lifecycle page at [https://pydantic.dev/docs/ai/realtime/lifecycle/index.md], including its lifecycle diagram, Python examples, handshake settings, reconnect and restoration behavior, provider limits, shutdown guidance and errors. The introductory documentation-index and query-parameter notices are included as source content; they do not establish application requirements. Linked pages, API reference contents, implementation code, provider terms and pricing are excluded. No examples or provider behavior were executed or tested.

The overview

Identity

Connection lifecycle is a feature guide within Pydantic AI's realtime documentation. Its original address is [https://pydantic.dev/docs/ai/realtime/lifecycle/index.md]. It explains how a backend opens, maintains, recovers and closes a persistent connection to a realtime model provider.

The resource is documentation for using Pydantic AI's realtime interface. The surrounding framework, deployment guides and linked API references are outside this page's scope.

Assessment

The guide is useful when implementing recovery and shutdown in a Pydantic AI voice application. It explains consequences that a simple retry example would leave unresolved: which conversation state survives, what happens to running tools, and when the application must ask someone to repeat speech.

It is best approached with an existing understanding of Python asynchronous code. Beginners will need additional material to build the surrounding application and audio connection. The documented behavior is detailed, but no reliability measurements or performance comparisons are provided.

Users

The main audience is Python developers building realtime voice assistants or maintaining an application's connection to an AI provider. It also helps developers diagnosing dropped calls, replies that stop unexpectedly, tool failures and sessions that fail to close.

Backend developers using browser WebRTC need particular care with the sideband, the separate server control connection to the browser's provider call. The guide notes that close() only detaches from the browser's call, while hang_up() ends it.

Capabilities

The guide covers handshake timeouts, exponential-backoff reconnection, limits on retries and repeated recoveries, provider-specific state restoration, application timeouts and shutdown. Its lifecycle diagram connects listening, user input, model responses, tool execution, reconnection and closure.

It distinguishes UserError for invalid application use or missing credentials, ModelHTTPError for an HTTP rejection of the WebSocket upgrade, RealtimeError for connection or protocol failures, and UsageLimitExceeded for a configured usage limit. RealtimeError and ModelHTTPError can both be covered through ModelAPIError.

Recoverable provider-operation and input-transcription failures arrive as events while the session remains usable. The page also explains how rejected inputs affect message history and wait_for_reply(), including automatic retries when OpenAI Realtime or Azure OpenAI temporarily refuses a response request because another response is underway.

Using it

Requirements

Applying the examples requires a Python application using Pydantic AI's Agent and realtime APIs, asynchronous session handling, and credentials for the chosen provider. The backend owns the provider session and the media bridge connecting it to the user.

The page assumes familiarity with async with, async for, asyncio tasks and exception handling. It does not give installation commands, supported Python or package versions, credential configuration, or a complete microphone, browser or audio-playback implementation.

Mechanism

Entering session() opens the connection and performs the provider handshake. The session then listens for input. Turn detection or an explicit response request starts a model response, which can include tool calls. RealtimeTurnCompleteEvent marks the turn boundary. An enabled reconnect policy replaces a dropped connection, reapplies configuration and emits RealtimeSessionReconnectEvent after recovery.

OpenAI, Azure OpenAI and xAI restore conversation context by replaying local message history as text. Prior audio is not replayed; speech without a transcript is represented by a placeholder. An unfinished response is settled as interrupted and running tools receive cancelled returns. A requested response that had not begun streaming can be requested again after recovery.

Gemini uses native session resumption when a reconnect policy is present. Its resumption handles exist only in the current process. GPT-Live normally replays history or forks a stored session; its WebRTC sideband can instead reattach to the browser call's continuing session. These mechanisms have different meanings for state_restored, so application logic must account for provider-specific caveats.

Failures generally surface through the responsible send call or the session iterator. A receive-loop failure ends the session. A tool failure can be caught and iteration resumed because the model receives a failed-tool result. Failures occurring without an active iterator can surface when the session context exits.

Setup

Configure reconnect through model_settings, either as a model default or for an individual session. The example sets max_attempts to 5. That bounds retries for one dropped connection; max_reconnects separately bounds recoveries across the session. Without a policy, an unexpected provider closure raises RealtimeError through iteration.

The shared handshake_timeout defaults to 30 seconds. Its boundary differs by provider: each handshake event on OpenAI, Azure OpenAI and xAI; the complete setup on Gemini; and conversation-initiation metadata on ElevenLabs Agents.

Use the asynchronous session context and consume its events. Leaving the context closes the session, and close() can also be awaited from another task. Concurrent closure requests share the same teardown, which completes even if a task waiting for it is cancelled. On a browser WebRTC sideband, use hang_up() when the intention is to end the browser call; close() detaches the backend connection.

Example

The first Python example creates Agent(), selects the documented model identifier openai:gpt-realtime-2.1, and passes model_settings={'reconnect': {'max_attempts': 5}}. It demonstrates the retry configuration without providing a complete audio application.

The shutdown example opens an asynchronous session and starts close_after(session, 300) as an asyncio task. That task sleeps for 300 seconds and then awaits session.close(), ending the async for loop over session events. A finally block cancels the watchdog task whenever that loop exits, which matters when the session ends before the timeout.

The 300-second value illustrates an application-defined maximum call duration. An idle timeout needs activity tracking: speech events where supported, or the application's own non-silent audio input alongside assistant activity and turn-completion events. Tracking assistant output alone can disconnect someone who is still speaking.

Assessment & evidence

Limitations

During reconnection, send_audio() drops audio chunks instead of raising, so microphone capture can continue; other sends still raise RealtimeError. Speech interrupted by the drop cannot be reconstructed from that lost audio. For push-to-talk, the page recommends asking the user to repeat themselves after the reconnect event.

Provider recovery has additional gaps. On Gemini 2.5, which withholds resumption handles while working on a turn, a typed turn with no handle issued after its reply is missing from the resumed session; it stays in history, state_restored is False, and it can be sent again. Interrupted tool calls are cancelled. Some cases involving typed input during a spoken response are ambiguous for wait_for_reply() and state_restored. A GPT-Live sideband can report state_restored=True while events from a longer disconnection are missing; an unanswered tool call from that gap can prevent further delegation for the rest of the call.

A clean WebRTC sideband close ends iteration without reconnection, even with a policy configured. A proxy that closes that connection cleanly during a call can therefore detach the backend while the browser keeps talking. The page recommends handling such connection draining in infrastructure.

Provider duration limits remain relevant. Gemini sends GoAway shortly before its cap, but Pydantic AI currently reconnects only after the connection drops, so a long call can briefly drop mid-turn. ElevenLabs Agents cannot resume a conversation after its configured maximum duration, so reconnect is ignored with an UnsupportedSettingWarning. Exact provider caps are not stated here.

Reasoning

A practical inference from the documented behavior is that transport recovery and conversation continuity need separate application handling. Reopening a socket can leave missing speech, an interrupted reply or cancelled tools, depending on the recovery mechanism.

Reconnect events should therefore inform the conversation experience as well as connection status. The explicit push-to-talk repetition guidance supports prompting for missing input. The GPT-Live sideband caveat also means state_restored alone cannot prove that every event reached the backend.

Alternatives

The page describes several choices within Pydantic AI: automatic turn detection or manual push-to-talk, model-wide or per-session reconnect settings, and application shutdown through context exit or an explicit close(). Browser WebRTC adds hang_up() for ending the call.

It also documents different provider recovery approaches, including local history replay, Gemini's in-process resumption and GPT-Live sideband reattachment. Their limitations can inform provider choice, but the page provides no comparison of competing frameworks, prices, latency or measured reliability.

Evidence

The evidence is the complete captured page at [https://pydantic.dev/docs/ai/realtime/lifecycle/index.md], captured on 2026-11-15.

The page supplies explanatory text, a lifecycle diagram and Python examples. These establish what the documentation describes. No code was executed, and runtime behavior, provider compatibility and recovery reliability were not tested. Linked documentation and implementation code are not included.

Access & freshness

Costs

Costs are unknown. The page supplies no Pydantic AI pricing, provider rates, billing units, hosting estimates or example call costs.

Retry settings bound reconnection behavior. The page does not establish their effect on charges. It documents UsageLimitExceeded for configured usage limits but does not explain how those limits correspond to monetary spending.

Rights

The page does not include a licence or explicit redistribution permission for its documentation or code examples. Reuse and redistribution rights are unknown from this evidence.

Provider terms, rights concerning recorded speech, and data-retention rules are also not established by this page.

Freshness

The page was captured on 2026-11-15 at 14:33:12.550 UTC. The text does not establish its publication date, last update or compatible Pydantic AI release.

The guide explicitly says provider session limits and behavior can change and directs readers to provider-specific pages. Those linked pages are outside this evidence. Current model availability, exact duration limits and compatibility with a particular installed release remain unverified.

Actions

Before implementation, confirm the documented APIs against the installed Pydantic AI release and check the chosen provider's current credentials, session limits and pricing. Set deliberate bounds for both retries per drop and recoveries per session.

Plan how the application will respond to missing speech, interrupted replies and cancelled tools. For browser WebRTC, decide when to detach the backend and when to end the call, and account for clean sideband closures during infrastructure changes.

Validate the intended application with drops during speech, replies and tool calls; rejected sends; exhausted retries; watchdog timeouts; and concurrent shutdown. These are recommended future checks, with no execution results established here.

Evidence for this report

selected-page.txtselected · checked 2026-11-15