pydantic_ai.exceptions
Bases: UserWarning
Warning emitted when a deprecated Pydantic AI API is used.
Inherits from UserWarning instead of DeprecationWarning so that
deprecations are visible by default at runtime, following the approach
described in https://sethmlarson.dev/deprecations-via-warnings-dont-work-for-python-libraries.
Bases: Exception
Exception to raise to request a model retry.
Can be raised from tool functions, output validators, and capability hooks
(such as after_model_request, after_tool_execute, etc.) to send
a retry prompt back to the model asking it to try again.
For a terminal failure the model should see but not retry, raise
ToolFailed instead.
The message to return to the model.
Type: str Default: message
@classmethod
def __get_pydantic_core_schema__(cls, _: Any, __: Any) -> core_schema.CoreSchema
Pydantic core schema to allow ModelRetry to be (de)serialized.
core_schema.CoreSchema
Bases: Exception
Exception to raise to report a terminal tool failure to the model.
Raise this when a tool call is done and has failed — a missing resource, an unsupported operation, a definitive upstream error — and you want the model to see the failure and adapt rather than try the same call again. Can be raised from tool functions, args validators, and tool validation/execution hooks.
Like ModelRetry, this produces a failed tool result the
model sees; unlike ModelRetry it does not prepend retry/correction instructions and does not
consume the tool’s retry budget. Bound repeated failures with
UsageLimits at the run level instead.
The failure message to return to the model.
Type: str Default: message
@classmethod
def __get_pydantic_core_schema__(cls, _: Any, __: Any) -> core_schema.CoreSchema
Pydantic core schema to allow ToolFailed to be (de)serialized.
core_schema.CoreSchema
Bases: Exception
Exception to raise when a tool call should be deferred.
See tools docs for more information.
Optional dictionary of metadata to attach to the deferred tool call.
This metadata will be available in DeferredToolRequests.metadata keyed by tool_call_id.
Bases: Exception
Exception to raise when a tool call requires human-in-the-loop approval.
See tools docs for more information.
Optional dictionary of metadata to attach to the deferred tool call.
This metadata will be available in DeferredToolRequests.metadata keyed by tool_call_id.
Bases: Exception
Exception to raise in before/wrap model request hooks to skip the model call.
The provided response will be used instead of calling the model.
Note: when raised in before_model_request, any message history modifications
made by earlier capabilities in that hook will not be persisted to the agent’s
message history, since the request preparation is aborted.
Bases: Exception
Exception to raise in before/wrap tool validate hooks to skip validation.
The provided args will be used as the validated arguments.
Bases: Exception
Exception to raise in before/wrap tool execute hooks to skip execution.
The provided result will be used as the tool result.
Bases: RuntimeError
Error caused by a usage mistake by the application developer — You!
Description of the mistake.
Type: str Default: message
Bases: UserError
Error raised when an agent run ends with messages still queued via enqueue.
A bare async for node in agent_run loop only drains 'asap' messages (in
before_model_request); 'when_idle' messages and end-of-run redirects drain in
after_node_run, which bare iteration skips. Reaching the run’s End with a non-empty
queue means those messages were stranded — drive the run with agent.run() or
AgentRun.next() instead.
Bases: RuntimeError
Base class for errors occurring during an agent run.
The error message.
Type: str Default: message
Bases: AgentRunError
Raised when resuming a suspended response whose server-side job is no longer available.
Suspended/background jobs are only resumable within the provider’s retention window (e.g. ~10 minutes for OpenAI background mode). Resuming a persisted suspended response after that window raises this instead of an opaque provider HTTP error; start a new run from the preceding messages to retry from scratch.
Bases: AgentRunError
Error raised when a Model’s usage exceeds the specified limits.
Bases: AgentRunError
Error raised when the concurrency queue depth exceeds max_queued.
Bases: AgentRunError
Error caused by unexpected Model behavior, e.g. an unexpected response code.
Description of the unexpected behavior.
Type: str Default: message
The body of the response, if available.
Type: str | None Default: json.dumps(json.loads(body), indent=2)
Bases: UnexpectedModelBehavior
Raised when content filtering is triggered by the model provider.
Bases: AgentRunError
Raised when a model provider API request fails.
The name of the model associated with the error.
Type: str Default: model_name
Bases: ModelAPIError
Raised when a model provider response has a status code of 4xx or 5xx.
The HTTP status code returned by the API.
Type: int Default: status_code
The body of the response, if available.
Type: object | None Default: body
Response headers from the provider, with keys lowercased for consistent access.
For example, use exc.headers.get('retry-after') to read the Retry-After header
regardless of provider casing. None when the provider does not supply headers
(e.g. gRPC-based providers or synthesised errors).
Type: dict[str, str] | None Default: {(k.lower()): v for k, v in (headers.items())} if headers is not None else None
Seconds to wait before retrying, parsed from the Retry-After response header.
Returns None when the header is absent or cannot be parsed. The header value
is interpreted first as an integer number of seconds, then as an
HTTP-date string.
Bases: ExceptionGroup[Any]
A group of exceptions that can be raised when all fallback models fail.
Bases: Exception
Exception used to signal a ToolRetry message should be returned to the LLM.
Bases: Exception
Exception used to signal a failed ToolReturnPart should be returned to the LLM.
Bases: UnexpectedModelBehavior
Error raised when a model stops due to token limit while emitting a tool call.
Bases: Warning
Warning raised when in-place mutation of the message history is detected at the end of a run.
Mutating messages that are already part of the run’s history in place (e.g.
ctx.messages[0].parts[0].content = '...' from a tool) is not supported: the per-request
gen_ai.input.messages span attribute caches each message’s serialized form, so spans recorded
after the mutation may not match the messages actually sent to the model. The run-level
pydantic_ai.all_messages attribute is always serialized fresh and does reflect the mutation.
To transform history mid-run, build new message or part objects instead — e.g. with
dataclasses.replace, passing the message a new parts list (replacing a message in the
history and reassigning its parts list are both safe) — for instance in a history processor
(ProcessHistory).
The warning is best-effort: it’s raised when a mutation is detected at the end of a successful run, which covers messages still present in the final history. Errored runs aren’t checked — with warnings configured as errors, the warning would displace the run’s own exception. Its absence does not guarantee that no stale span was recorded.