Retries
Tools can automatically retry failed operations.
Retries are one of the simplest and most effective ways to handle errors in tools. Instead of failing immediately, a tool can automatically try again when something goes wrong.
This makes your workflows more resilient, reduces unnecessary crashes, and improves overall reliability with minimal setup.
Error Handling with Retries
Below is how simple it is to enable retry logic in a tool.
from peargent import create_tool
api_tool = create_tool(
name="external_api",
description="Call external API",
input_parameters={"query": str},
call_function=call_external_api,
max_retries=3, # Retry up to 3 times on failure
retry_delay=1.0, # Initial delay: 1 second
retry_backoff=True, # Exponential backoff: 1s → 2s → 4s
on_error="return_error"
)Retry Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
max_retries | int | 0 | Number of retry attempts (0 = no retries) |
retry_delay | float | 1.0 | Initial delay between retries in seconds |
retry_backoff | bool | True | Doubles delay after each retry attempt (Exponential) |
How Retry Works
First Attempt:
Tool executes normally.
On Failure:
If execution or validation fails:
- If
max_retries > 0, the tool waits for retry_delay seconds - If
retry_backoff=True, the wait time doubles each retry (1s → 2s → 4s → …)
Repeat:
Retries continue until:
- A retry succeeds, or
- All retry attempts are exhausted
Final Failure:
Handled according to the on_error strategy (raise, return_error, return_none).
Retry Example with Backoff
unreliable_tool = create_tool(
name="flaky_api",
description="API that sometimes fails",
input_parameters={"query": str},
call_function=call_flaky_api,
max_retries=3,
retry_delay=1.0,
retry_backoff=True,
on_error="return_error"
)
# If all attempts fail, timing will be:
# Attempt 1: Immediate
# Attempt 2: +1 second (1.0 * 2^0)
# Attempt 3: +2 seconds (1.0 * 2^1)
# Attempt 4: +4 seconds (1.0 * 2^2)
# Final: Return error message