Skip to content

pydantic_ai.retries

Retries utilities based on tenacity, especially for HTTP requests.

This module provides HTTP transport wrappers and wait strategies that integrate with the tenacity library to add retry capabilities to HTTP requests. The transports can be used with HTTP clients that support custom transports (such as httpx), while the wait strategies can be used with any tenacity retry decorator.

The module includes:

  • TenacityTransport: Synchronous HTTP transport with retry capabilities
  • AsyncTenacityTransport: Asynchronous HTTP transport with retry capabilities
  • wait_retry_after: Wait strategy that respects HTTP Retry-After headers

RetryConfig

Bases: TypedDict

The configuration for tenacity-based retrying.

These are precisely the arguments to the tenacity retry decorator, and they are generally used internally by passing them to that decorator via @retry(**config) or similar.

All fields are optional, and if not provided, the default values from the tenacity.retry decorator will be used.

Attributes

sleep

A sleep strategy to use for sleeping between retries.

Tenacity’s default for this argument is tenacity.nap.sleep.

Type: Callable[[int | float], None | Awaitable[None]]

stop

A stop strategy to determine when to stop retrying.

Tenacity’s default for this argument is tenacity.stop.stop_never.

Type: StopBaseT

wait

A wait strategy to determine how long to wait between retries.

Tenacity’s default for this argument is tenacity.wait.wait_none.

Type: WaitBaseT

retry

A retry strategy to determine which exceptions should trigger a retry.

Tenacity’s default for this argument is tenacity.retry.retry_if_exception_type().

Type: SyncRetryBaseT | RetryBaseT

before

A callable that is called before each retry attempt.

Tenacity’s default for this argument is tenacity.before.before_nothing.

Type: Callable[[RetryCallState], None | Awaitable[None]]

after

A callable that is called after each retry attempt.

Tenacity’s default for this argument is tenacity.after.after_nothing.

Type: Callable[[RetryCallState], None | Awaitable[None]]

before_sleep

An optional callable that is called before sleeping between retries.

Tenacity’s default for this argument is None.

Type: Callable[[RetryCallState], None | Awaitable[None]] | None

reraise

Whether to reraise the last exception if the retry attempts are exhausted, or raise a RetryError instead.

Tenacity’s default for this argument is False.

Type: bool

retry_error_cls

The exception class to raise when the retry attempts are exhausted and reraise is False.

Tenacity’s default for this argument is tenacity.RetryError.

Type: type[RetryError]

retry_error_callback

An optional callable that is called when the retry attempts are exhausted and reraise is False.

Tenacity’s default for this argument is None.

Type: Callable[[RetryCallState], Any | Awaitable[Any]] | None

TenacityTransport

Bases: BaseTransport

Synchronous HTTP transport with tenacity-based retry functionality.

This transport wraps another BaseTransport and adds retry capabilities using the tenacity library. It can be configured to retry requests based on various conditions such as specific exception types, response status codes, or custom validation logic.

The transport works by intercepting HTTP requests and responses, allowing the tenacity controller to determine when and how to retry failed requests. The validate_response function can be used to convert HTTP responses into exceptions that trigger retries.

Constructor Parameters

wrapped : BaseTransport | None Default: None

The underlying transport to wrap and add retry functionality to.

config : RetryConfig

The arguments to use for the tenacity retry decorator, including retry conditions, wait strategy, stop conditions, etc. See the tenacity docs for more info.

validate_response : Callable[[Response], Any] | None Default: None

Optional callable that takes a Response and can raise an exception to be handled by the controller if the response should trigger a retry. Common use case is to raise exceptions for certain HTTP status codes. If None, no response validation is performed.

Methods

handle_request
def handle_request(request: Request) -> Response

Handle an HTTP request with retry logic.

Returns

Response — The HTTP response.

Parameters

request : Request

The HTTP request to handle.

Raises
  • RuntimeError — If the retry controller did not make any attempts.
  • Exception — Any exception raised by the wrapped transport or validation function.

AsyncTenacityTransport

Bases: AsyncBaseTransport

Asynchronous HTTP transport with tenacity-based retry functionality.

This transport wraps another AsyncBaseTransport and adds retry capabilities using the tenacity library. It can be configured to retry requests based on various conditions such as specific exception types, response status codes, or custom validation logic.

The transport works by intercepting HTTP requests and responses, allowing the tenacity controller to determine when and how to retry failed requests. The validate_response function can be used to convert HTTP responses into exceptions that trigger retries.

Constructor Parameters

wrapped : AsyncBaseTransport | None Default: None

The underlying async transport to wrap and add retry functionality to.

config : RetryConfig

The arguments to use for the tenacity retry decorator, including retry conditions, wait strategy, stop conditions, etc. See the tenacity docs for more info.

validate_response : Callable[[Response], Any] | None Default: None

Optional callable that takes a Response and can raise an exception to be handled by the controller if the response should trigger a retry. Common use case is to raise exceptions for certain HTTP status codes. If None, no response validation is performed.

Methods

handle_async_request

@async

def handle_async_request(request: Request) -> Response

Handle an async HTTP request with retry logic.

Returns

Response — The HTTP response.

Parameters

request : Request

The HTTP request to handle.

Raises
  • RuntimeError — If the retry controller did not make any attempts.
  • Exception — Any exception raised by the wrapped transport or validation function.

wait_retry_after

def wait_retry_after(
    fallback_strategy: Callable[[RetryCallState], float] | None = None,
    max_wait: float = 300,
) -> Callable[[RetryCallState], float]

Create a tenacity-compatible wait strategy that respects HTTP Retry-After headers.

This wait strategy checks if the exception contains an HTTPStatusError with a Retry-After header, and if so, waits for the time specified in the header. If no header is present or parsing fails, it falls back to the provided strategy.

The Retry-After header can be in two formats:

  • An integer representing seconds to wait
  • An HTTP date string representing when to retry

Returns

Callable[[RetryCallState], float] — A wait function that can be used with tenacity retry decorators.

Parameters

fallback_strategy : Callable[[RetryCallState], float] | None Default: None

Wait strategy to use when no Retry-After header is present or parsing fails. Defaults to exponential backoff with max 60s.

max_wait : float Default: 300

Maximum time to wait in seconds, regardless of header value. Defaults to 300 (5 minutes).