Add persistent Responses WebSocket connections with `Agent.connect()`
This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.
Repeated Responses requests pay HTTP transport overhead during tool-heavy runs. This adds opt-in persistent WebSocket connections for ordinary Responses runs and keeps the existing HTTP path unchanged. See issue #4414.
New public surface
AbstractAgent.connect(): inside the context, runs that select no model of their own use a connection to the agent's configured model. A run'smodel=, a runspecmodel, and a run capability model are honored as usual. Anoverride(model=...)entered inside the context still wins; under an active override,connect()connects the overriding model. When the configured model is a model ID, the context owns the temporary model's provider client. It raisesUserErrorinside a durable workflow or flow, onTemporalAgent,DBOSAgentandPrefectAgent, and on agents without connection support.Model.connect()takes no arguments; models without connection support raiseUserError.OpenAIResponsesModel.connect()yields an independent connected model and accepts typed SDK WebSocket options and handshake headers. Those options stay on the concrete model's typed signature rather than passing throughModel.connect()oragent.connect()as untyped**kwargs: connect the model directly, then pass or wrap the connected model.openai_previous_response_idacceptsNone, which clears an inherited'auto'value for full-history recovery.
User-visible behavior
async with agent.connect():
await agent.run('What is the capital of France?') # over the socket
await agent.run('Hi', model='openai-responses:gpt-5.2') # honored, over HTTP
Each connection serves one response at a time; parallel runs open separate contexts. Cancelling or abandoning a stream closes the socket. There is no automatic retry or HTTP fallback. Each socket keeps the credentials it opened with, and request headers are compared only with the connection's configured headers, never the client's credentials, so a shared client refreshing its token doesn't affect open connections. Codex connections are rejected before a handshake. Install with pydantic-ai-slim[openai-realtime]. Ultrafast support is tracked in #9469.
Verification
- Recorded runs:
test_tool_continuation(re-recorded live) andtest_streaming_sequential_turns. - Model precedence:
test_agent_connection_replaces_only_configured_modelandtest_agent_connection_nested_override. - Shared-client token refresh:
test_refreshed_shared_client_credentials_keep_open_connection_usable. - Benchmark, three trials: median total time 5,737.61 ms over HTTP vs 4,434.35 ms over WebSocket, and median time to first token 991.02 ms vs 628.59 ms. This small sample is not a performance guarantee. See the script at its commit.
Other regression coverage
- Provider-client lifetimes:
test_agent_connection_reuses_entered_model_clientandtest_agent_connection_closes_inferred_provider_after_count_tokens. - Fallback composition:
test_connected_fallback_models_use_and_close_both_sockets. - Warmup continuation:
test_connected_model_warmup_response_id_continues_agent_runandtest_agent_run_retries_empty_connected_warmup_response. - Full-history recovery reset:
test_agent_run_can_reset_default_auto_response_id_for_full_history. - Task-local contexts and HTTP restoration:
test_agent_connections_are_task_localandtest_agent_connection_restores_http. - Overlap, cancellation, errors and timeouts:
test_overlap,test_stream_cancel_during_receive,test_errorsandtest_handshake_timeout. - Headers:
test_request_header_overridesandtest_client_default_headers. - Azure filtering, Codex rejection, and Bedrock Mantle authentication:
test_content_filter,test_codex_connection_unsupportedandtest_bedrock_mantle_websocket_auth_requires_compatible_sdk_client. - Durable execution:
test_durability_connect_in_workflow_fails_the_workflow,test_dbos_durability_rejects_connect_in_workflow,test_prefect_durability_rejects_connect_in_flowandtest_temporal_agent_rejects_connect. - MCP sampling unchanged for agents that never connect:
test_agent_sampling_model_outlives_entered_agent. pydantic_graph'sinfer_nameno-frame branch is now tested instead of excluded from coverage. On Python 3.11, CI's tracer recorded an asyncio line on thatpragma: no coverline in this PR's shard.
Out of scope
- Native steering, several responses multiplexed on one socket, and connection pooling. A connection serves one response at a time, so cancellation and incomplete-stream cleanup have one socket owner. Parallel runs open separate contexts.
- Automatic reconnect, retry, or HTTP fallback.
- Codex subscription connections, whose session headers are only known per request.
- Handshake response headers and
response.metadataevents: #10237. - Structured
code,typeandparamon in-stream errors, for both transports: #10279.
What changes for existing users
Nothing, unless they enter a connection.
- Closes #4414
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
- PR title is fit for the release changelog.