Tool Error Handling

When a tool raises, the agent sees the error and can recover — only timeouts and connection errors are retried

When a tool raises an exception, the error goes back to the model as the tool result. The agent can then fix its arguments, try another tool, or explain the problem.

python
from praisonaiagents import Agent

def fetch_price(ticker: str) -> float:
    """Get the latest price for a stock ticker."""
    if not ticker:
        raise ValueError("ticker must be non-empty")  # the model sees this
    return 189.5

agent = Agent(
    name="Trader",
    instructions="Look up prices and summarise.",
    tools=[fetch_price],
)

agent.start("What's AAPL at?")
Diagram

No

Timeout / Connection

Bad input

Other error

🤖 Agent

🔧 Tool call

Raised?

✅ Result to model

🔁 Retry

📨 Error to model

📨 Error to model
counts toward breaker

Quick Start

  1. Just raise

    Raise a normal Python exception from your tool. No wrapper needed.

    python
    from praisonaiagents import Agent
    
    def send_email(to: str) -> str:
        """Send an email to a recipient."""
        if "@" not in to:
            raise ValueError(f"'{to}' is not an email address")
        return f"sent to {to}"
    
    agent = Agent(name="Mailer", tools=[send_email])
    agent.start("Email the report to bob")

    The model gets the ValueError text and can ask for a real address instead of the turn ending.

  2. Tune transient retries

    Timeouts and connection errors retry with backoff. Change the policy with ToolConfig:

    python
    from praisonaiagents import Agent
    from praisonaiagents.config import ToolConfig
    from praisonaiagents.tools import RetryPolicy
    
    agent = Agent(
        name="Fetcher",
        tools=[fetch_price],
        tool_config=ToolConfig(retry_policy=RetryPolicy(max_attempts=5)),
    )

How It Works

Every raised exception is sorted into one of three buckets:

BucketExceptionsRetried?Counts toward circuit breaker?
TransientTimeoutError, ConnectionError, or any class with Timeout / Connection in its name (covers requests, httpx, aiohttp)Yes, then reported to the modelYes
Bad inputValueError, TypeError, AttributeError, LookupError, FileNotFoundError, FileExistsError, IsADirectoryError, NotADirectoryError, PermissionErrorNo — runs onceNo
OtherAnything elseNo — runs onceYes

In every bucket the error ends up as the tool result the model sees. A raising tool does not end the turn.

Diagram
ToolAgentUserToolAgentUser“Email the report to bob”send_email(to=”bob”)ValueError: ‘bob’ is not an email address“What’s Bob’s email address?”

Wrong arguments

If the model calls a tool with bad arguments, it sees the error and can call again with fixed arguments. This works the same on every provider route.

Text-based retry

RetryPolicy.retry_on still matches error text. An error like "429 too many requests" is classed as rate_limit and retried by default. A tool whose raised message only looks like a rate limit is not mistaken for a model error.

Sync and async

chat(), achat(), start() and astart() behave the same way.

Durable runs

The error is recorded as the tool’s result and the run carries on — it is not finalized failed because a tool raised. See Durable Tool Runs.


Configuration Options

Retries are controlled by RetryPolicy (from praisonaiagents.tools), passed via ToolConfig(retry_policy=...).

OptionTypeDefaultDescription
max_attemptsint3Total tries for a transient error
backoff_factorfloat2.0Delay multiplier per attempt
initial_delay_msint1000First retry delay
max_delay_msint30000Delay ceiling
retry_onSet[str]{"timeout", "rate_limit", "connection_error"}Error types that retry
jitterboolFalseRandomise delays
jitter_factorfloat0.25Jitter range (±25%)

Migrating

Before, a raising tool often ended the turn with ToolExecutionError, and the model never saw what went wrong. Now the model sees it.

  • If you caught ToolExecutionError around agent.start() to detect tool failures, check the agent’s answer or the tool’s own result instead.
  • If a tool must stop the whole run, return a clear answer from the tool or use a guardrail rather than relying on an exception to abort.

Best Practices

Write helpful error messages

The model reads your exception text. Say what was wrong and what a valid value looks like: "ticker must be a symbol like AAPL".

Raise ValueError for bad input

Bad-input errors run once and don’t trip the circuit breaker, so one wrong call never blocks the tool for others.

Let network errors raise

Don’t swallow TimeoutError or requests / httpx connection errors. Letting them raise gives you free retries with backoff.

Mark side-effect tools restart_safe=False

A tool that charges money or sends messages should be declared non-idempotent so even a transient error never runs it twice. See Durable Tool Runs.


Related