Add `ModelSettings['request_timeout']` covering all attempts and stream consumption of one model request
- Closes #9333
ModelSettings['timeout'] is applied by the provider client to one attempt: an SDK retry re-arms it, and on a streamed response it only limits the wait for each chunk. This adds ModelSettings['request_timeout'], one deadline over one request to one model that Pydantic AI enforces itself, so it works the same on every model class (it is never sent to the provider).
New public surface
ModelSettings['request_timeout'](seconds).ModelRequestTimeout(ModelAPIError), exported frompydantic_ai, withmodel_nameandtimeout. It pickles, so it crosses a Temporal activity boundary as itself.
What the deadline covers
- Every attempt the provider SDK and HTTP transport make, the backoff between them, and every continuation segment of a paused response (Anthropic
pause_turn, OpenAI background mode), including the waits between segments. - Streaming: opening the stream and reading it through its last chunk. The deadline is fixed when the request is made, so time the consumer spends between events counts (the first open question in the issue). Once the last chunk is read, it no longer applies. A partial stream is kept in history as
'interrupted', as for any mid-stream error. This also covers the streamingrun()does behind the scenes, e.g. with an event stream handler. FallbackModelgives each model it tries a fresh deadline, and its defaultfallback_onfalls back onModelRequestTimeout. Failed attempts show up infailed_attemptswithoutcome='error'. The agent graph skips its own deadline when the model is aFallbackModel, also behind aWrapperModelsuch as a durable wrapper, so there is no outer deadline over the whole chain. If the picked model pauses its response, the graph's continuation loop calls theFallbackModelagain for each segment. TheFallbackModelcarries the picked model's deadline on the suspended response, as a wall-clock UTC timestamp in the__pydantic_ai__metadata next to the continuation pin. Each later segment gets what's left of it, so the continuation stays one request to that model, also when each segment runs in its own durable activity or step. The timestamp is dropped when the turn completes, and when a later run resumes the suspended response from history (a new request). A model's ownsettingscan set its ownrequest_timeout.- The direct API (
model_request,model_request_stream) applies it too, using the same helpers (the second open question). - An
on_model_request_errorhook can recover a non-streamed timeout like any other model error.
How it's enforced
RequestDeadline (models/_request_timeout.py) is an absolute point on anyio's clock. Each wait that belongs to the request runs under an anyio cancel scope with that deadline: the whole non-streamed model_request loop, opening a stream, and each pull of the stream's next event. Scopes never span a yield, so a stream can be consumed from any task. When the scope's own deadline fires it raises ModelRequestTimeout. A cancellation from outside, such as a cancelled run, still propagates as a cancellation. Whether a model gets a deadline at all is decided by a private Model._start_request_deadline() hook. WrapperModel delegates it, and FallbackModel returns None because it starts one for each model it tries.
Durable execution
The anyio clock in a Temporal workflow is the workflow's clock, so the deadline runs as a durable workflow timer. When it fires, the in-flight model activity is cancelled through the existing execute_activity path, which also ends its activity retries. The workflow then sees ModelRequestTimeout, and replay is deterministic (tested with Replayer). With a FallbackModel, the per-model deadlines run inside the activity instead. The picked model's deadline crosses from one continuation activity to the next on the suspended response, as above.
Cancellation cleanup
PeekableAsyncStream.aclose() now shields its teardown. It runs inside the cancelled scope, where waiting for its lock raised again and left the source stream (e.g. the SDK's HTTP stream) to garbage collection. This was reproduced with a FunctionModel stream under coverage timing.
Design choices to review
- Streaming enforcement. The issue sketched the scope wrapping the
wrap_model_requesttask. The stream is opened and read lazily in the consumer's task, though, and a scope can't follow aFallbackModelcandidate's stream there. So the deadline is enforced on each pull. Expiry while the consumer is idle surfaces on its next pull, not by actively tearing the stream down. - Temporal. The issue said the deadline maps onto the model activity's
schedule_to_close_timeout. A workflow timer gives the same bound, covering activity retries and backoff, with no race between two deadlines. It also covers continuation segments and inter-segment waits, which a per-activity timeout would not. So this PR doesn't setschedule_to_close_timeout. - Run deadline (#9332). Clipping to the run's remaining time is not here, since #9332 hasn't landed.
RequestDeadline.start()is the one place it would bemin'd in.
Relationship to ModelTimeoutError (#9354)
ModelRequestTimeout is a sibling of #9354's ModelTimeoutError(ModelConnectionError), not a subclass:
ModelTimeoutErroris a transport failure of one attempt (with aphase), controlled bytimeout.ModelRequestTimeoutis the framework's deadline across attempts, and no transport failed.
except (ModelTimeoutError, ModelRequestTimeout) catches both. The two PRs don't conflict, as this one only uses ModelAPIError(model_name, message).
Verification
-
tests/test_request_timeout.pycovers non-streamed and streamed requests:- a mid-stream timeout, with stream teardown asserted;
run()with an event stream handler;- a slow consumer;
- the deadline ending at the last chunk, and starting before the first pull;
- outer cancellation, hook recovery, and model-level settings.
FallbackModelcases:- a fresh deadline per model, also behind a wrapper;
- every model timing out;
- per-model settings;
- a stream that never opens falling back;
- a mid-stream timeout on the chosen model's own deadline;
- nested fallbacks;
- the picked model's deadline carried across continuation polls, streamed and not, and not kept in history once the turn completes;
- a resumed suspended response getting a fresh deadline despite an expired carried one.
Also covered: no leaked tasks, the direct API, and an OpenAI client over a mock transport showing that SDK retries don't re-arm the deadline (streamed and not).
-
tests/durable_exec/temporal/test_durability.py: aFallbackModelwhose picked model keeps pausing times out on its second segment's activity, because the deadline carried over, and falls back. Also request and stream: The workflow seesModelRequestTimeout, history has the timer and the activity cancel request, and replay passes. -
tests/models/test_model_settings_support.pyprobesrequest_timeout, proving no model sends it. -
Mutation checks: dropping the
FallbackModelskip fails 5 tests. Dropping the per-candidate stream deadline makes the fallback mid-stream and direct-stream tests hang. Ignoring the carried deadline fails the Temporal test and both continuation tests. Not stripping it on resume or on completion fails the matching test.
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.
š¤ Generated with Claude Code