Skip to main content

Error Recovery for AI Agents

This package ships error handling and recovery patterns for improved reliability of AI Agents, as a native Pydantic AI 2.0 capability.

[!NOTE] This package is in early development, the API might still change before v1.0.

Motivation

Agentic tool calling can fail for many reasons, and adding error handling and retries to every tool is cumbersome. For third-party tools and MCPs, it's often impossible. ToolErrorRecovery is a standardized capability for AI agents to recover from errors during tool calls. Similar in spirit to FastAPI's exception handlers, but for agents.

Related Work

This package combines the ideas and vocabulary of pydantic-ai-harness PR #171 with its own mechanics: it uses a classify callable rather than a per-tool strategy map for more flexibility; a single wrap_tool_execute hook rather than two; and does not expose str(error) to the agent by default for added security. It is intended as a stand-alone capability, but also as a proposal of how to make progress on PR #171.

Quick start

pip install pydantic-ai-error-recovery
from pydantic_ai import Agent
from pydantic_ai_error_recovery import ToolErrorRecovery

agent = Agent('openai:gpt-5', capabilities=[ToolErrorRecovery()])

Out of the box, connection errors are retried, bugs are propagated, and everything else is reported to the model, preventing a crash of the agent run. Continue reading to learn how to customize the capability.

Features

The ToolErrorRecovery capability supports four different recovery outcomes:

Outcome Effect
retry Re-attempt the tool call a number of times (invisible to the model)
inform Report a terminal failure to the model via ToolFailed (outcome='failed')
fallback Return a substitute value as the tool result
propagate Re-raise the exception, will crash the run unless caught by another wrapper

Error Classification

ToolErrorRecovery intercepts tool execution errors and applies a per-error reaction. A classify callable you supply inspects each failure and returns the intended recovery outcome:

def classify(ctx: RunContext[Any], call: ToolCallPart, error: BaseException) -> RecoveryOutcome:
    if isinstance(error, SomeException):
        return RecoveryOutcome.inform(...)
    # and so on

Notes:

  • You can classify on a tool's name and other properties of the tool call, on the exception type, or both.
  • The ctx: RunContext parameter is included for cases in which your classification logic additionally depends on the run context.
  • To not interfere with existing error handling, the following exceptions from the Pydantic AI control flow are never classified: SkipToolExecution, CallDeferred, ApprovalRequired, ModelRetry, ToolRetryError, ToolFailed, and ToolFailedError. Note that this list is hardcoded for now and would require updating if Pydantic AI changes their control flow exceptions.
  • Special care must be taken when classifying an exception which is a subclass, be careful about the order of isinstance(...) calls, or use type(...) is instead.

Default Behaviour

As mentioned above, control flow exceptions are never classified. Our default classifier is:

def classify(ctx: RunContext[Any], call: ToolCallPart, error: BaseException) -> RecoveryOutcome:
    if isinstance(error, DEFAULT_BUG_TYPES):
        return RecoveryOutcome.propagate()
    if isinstance(error, HookTimeoutError):
        return RecoveryOutcome.inform()
    if isinstance(error, DEFAULT_TRANSIENT_TYPES):
        return RecoveryOutcome.retry(3)
    return RecoveryOutcome.inform()

The classification function is the key piece required to construct your own RecoveryPolicy via RecoveryPolicy(classify=classify). A fully custom example could look like this:

from pydantic_ai import Agent
from pydantic_ai_error_recovery import ToolErrorRecovery

def classify(...):
    # your classification logic

agent = Agent('openai:gpt-5', capabilities=[
    ToolErrorRecovery(
        policy=RecoveryPolicy(
            classify=classify,
            format_error=my_formatter,
            max_message_len=450,
            include_traceback=False,
            logger=my_logger,
        ),
        max_recoveries=10,
        per_tool_recoveries={"my_tool_name": 5},
    )
])

Contributing

We welcome community contributions, please create an issue to discuss or submit a PR.

make install   # uv sync --extra dev
make all       # lint + typecheck + tests with 100% branch coverage

make all must pass before every commit. Conventions -- coding standards, file layout, testing patterns -- are in AGENTS.md.

License

Apache-2.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_ai_error_recovery-0.1.0.tar.gz (59.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_ai_error_recovery-0.1.0-py3-none-any.whl (20.7 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_ai_error_recovery-0.1.0.tar.gz.

File metadata

File hashes

Hashes for pydantic_ai_error_recovery-0.1.0.tar.gz
Algorithm Hash digest
SHA256 6f0d9b31c8ecdcc5849b8da7f75713b2683dcdf6735725e592e0474c903eef9b
MD5 67ba4147d019d06eb0758c0065e60e90
BLAKE2b-256 815639aec20d862cf7ef9f3d511062622aa177e5d46b652234eb8afbce7ee8fb

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_ai_error_recovery-0.1.0.tar.gz:

Publisher: publish.yml on aixbrain/pydantic-ai-error-recovery

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file pydantic_ai_error_recovery-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_ai_error_recovery-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1a5d7719404d56f8944803a32565a3ab3b5aa759e04a07770469f1cf9f014213
MD5 47044cba7ec5772664b9bd00402436a5
BLAKE2b-256 7aec577c4b26fa8c03971819654c01c06f8f76d171b0a793e405d6b5ec6c98e6

See more details on using hashes here.

Provenance

The following attestation bundles were made for pydantic_ai_error_recovery-0.1.0-py3-none-any.whl:

Publisher: publish.yml on aixbrain/pydantic-ai-error-recovery

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page