# How to retry a failed API call inside a tool, not in the model

> Absorb resets, 429 and 503 inside the tool with bounded backoff under a time cap, and hand 400 and 404 back to the model with the field or the id named.

Source: https://voxgig.com/howto/retry-inside-a-tool-not-in-the-model

- Audience: agent-builder
- Level: intermediate
- Languages: typescript, python
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Retry transport errors, 429 with Retry-After, and 503 inside the tool, with capped backoff and a total time cap below the agent's tool timeout. Hand back 400 with the offending field and 404 with the missing id at once. A model that retries spends a turn per attempt and can change the arguments, while the tool repeats the identical request.

---
## You will need

Node 22 or later, which runs the TypeScript tool with no dependencies, and Python 3.12 or later for
the two library comparisons. The usage API is a stand-in on 127.0.0.1 that answers from a script.
Waits run on a controlled clock, so the cap is tested without sleeping. The model is a scripted
policy in every run, and turn counts are what that policy did.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [Framework retry such as Pydantic AI ModelRetry](https://pydantic.dev/docs/ai/tools-toolsets/tools-advanced/#tool-retries) | The model can fix the call, such as a malformed argument | A model request per attempt, and a run that ends when the tool's budget runs out | The failure is transient and the arguments were right |
| [No retry with the model as the loop](https://code.claude.com/docs/en/agent-sdk/agent-loop) | Prototypes, and APIs that rarely fail | A turn per failure, room for argument drift, and turn or spend caps as the only bounds | Any API that answers 429 or 503 under load |
| [Retry inside the wrapped SDK](https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html) | The client library already retries and you can configure it | Its limits count attempts and single waits, with no total-time budget among its parameters | The agent has a tool timeout that the SDK's worst case exceeds |

The SDK's retry costs one setting and runs before the tool sees a failure. Its waits are bounded
one at a time, so the total needs a cap of its own. A framework retry puts the model back in the
loop, which suits a fixable argument and wastes a turn on a 503. The model as the loop needs no code.
It spends the most turns, and every one of them is a chance to change the call.

## Sort failures into absorb and hand back

The tool decides per outcome. A transport error, a 429, or a 503 gets a wait. Anything else stops
the loop at once. It decides on the status alone, so a 503 whose body is an HTML error page is
retried like any other.

```ts title="tool.mjs"
// Seconds to wait before the next attempt, or null to stop retrying.
export function retryDelay(outcome, attempt, random) {
  if (outcome.error) return TRANSPORT.has(outcome.error.code) ? backoff(attempt, random) : null
  if (outcome.status === 429 || outcome.status === 503) {
    // Delay-seconds only. An HTTP-date or a missing header falls back to backoff.
    const raw = String(outcome.headers['retry-after'] ?? '')
    return /^\d+$/.test(raw) ? Number(raw) : backoff(attempt, random)
  }
  return null
}
```

[`Retry-After`](https://www.rfc-editor.org/rfc/rfc9110.html#field.retry-after) may be a number of
seconds or an HTTP-date. This tool reads the seconds form and backs off with full jitter for the
rest. A 400 and a 404 come back as `invalid_argument` with the field, or `not_found` with the id,
because those are the facts the model needs to change its call.

## Cap the time the tool may spend

Every wait is checked against the cap before it starts. A wait that would cross it ends the loop
with `retryable: true` and the wait the API asked for. The model can then tell the user, rather than
sit in a tool until the framework kills it.

```ts title="tool.mjs"
      const spent = clock.now() - started
      if (attempt >= maxAttempts || spent + wait > capS) {
        return {
          error: outcome.status === 429 ? 'rate_limited' : 'unavailable',
          retryable: true,
          attempts: attempt,
          waited_s: spent,
          next_wait_s: wait,
          message: `gave up inside the ${capS} s cap; try again later or tell the user`,
        }
      }
      await clock.sleep(wait)
```

Each request also runs under a timer set to whatever is left of the cap. The timer ends a request
that stalls, and one that sends its body a byte at a time, which a socket timeout would let run on.
The demo sets the cap to 20 seconds against an agent tool timeout of 30.

```bash
node demo.mjs
```

```text output
retry inside the tool: cap 20 s, agent tool timeout 30 s, one model turn 3 s

scenario           requests  in tool  turns  the model saw
transient                 4   3.25 s      2  {"ok":true,"meter_id":"m-1","from":"2026-11-01","kwh":412.5}
bad argument              1      0 s      2  {"error":"invalid_argument","field":"from","message":"must be a date such as 2026-11-01","retry":"fix the argument"}
missing id                1      0 s      2  {"error":"not_found","meter_id":"m-9","retry":"check the id"}
slow dependency           3     16 s      2  {"error":"unavailable","retryable":true,"next_wait_s":8,"message":"gave up inside the 20 s cap; try again later or tell the user"}
Retry-After 3600          1      0 s      2  {"error":"rate_limited","retryable":true,"next_wait_s":3600,"message":"gave up inside the 20 s cap; try again later or tell the user"}

no retry in the tool, transient scenario: 6 turns, answer: used 412.5 kWh
  stand-in received /v1/meters/m-1/usage?from=2026-11-01
  stand-in received /v1/meters/m-1/usage?from=November+2026
  stand-in received /v1/meters/m-1/usage?from=2026-11-01
  stand-in received /v1/meters/m-1/usage?from=2026-11-01
  stand-in received /v1/meters/m-1/usage?from=2026-11-01
```

A reset, a 429, and a 503 cost four requests and two turns inside the tool. With the model as the
loop the same failures cost six turns. The scripted policy also sent `November 2026` on its second
try, which the API refused with a 400 and which nothing in the tool's own retries can do.

## Compare the SDK's retry and the framework's

`urllib3`'s [`Retry`](https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html) is
the retry policy of the connection pool that `requests` is built on. It absorbs the same three
failures in one call, and it honors `Retry-After` up to `retry_after_max`.

```bash
python3 sdk_retry.py
```

```text output
urllib3 2.8.0
one call, Retry(total=4, status_forcelist=[503]): status 200, 4 requests reached the stand-in, body {'meter_id': 'm-1', 'kwh': 412.5}
Retry-After 3600, default policy sleeps: 3600 s
Retry-After 3600, retry_after_max=20 sleeps: 20 s
default retry_after_max: 21600 s
Retry parameters: allowed_methods, backoff_factor, backoff_jitter, backoff_max, connect, history, other, raise_on_redirect, raise_on_status, read, redirect, remove_headers_on_redirect, respect_retry_after_header, retry_after_max, status, status_forcelist, total
```

The default would sleep an hour on one header.[^1] Every limit in that parameter list counts
attempts or caps a single wait, so the tool around the SDK still owns the total.

Pydantic AI takes the other route. A tool raises
[`ModelRetry`](https://pydantic.dev/docs/ai/tools-toolsets/tools-advanced/#tool-retries) to send the
model a retry prompt, or `ToolFailed` to report a failure the model should not retry. The model here is
a `FunctionModel`, and the API answers 503 twice before a 200.

```bash
python3 framework_retry.py
```

```text output
pydantic-ai-slim 2.77.0, the API answers 503, 503, then 200
ModelRetry, tool retries not set: 2 model requests, 2 API requests
  UnexpectedModelBehavior: Tool 'get_usage' exceeded max retries count of 1. Consider raising the retry limit, or see the docs on tool retries: https://pydantic.dev/docs/ai/tools-toolsets/tools-advanced/#tool-retries
ModelRetry, tool retries=3: 4 model requests, 3 API requests
  success: {"meter_id": "m-1", "kwh": 412.5}
retry inside the tool: 2 model requests, 3 API requests
  success: {"meter_id": "m-1", "kwh": 412.5}
```

With the default budget of one retry, the second 503 ended the whole run with an exception. Raising
it to three worked, at four model requests where the in-tool retry needed two.

## Check it worked

The Node suite pins the table and tries three jitter values against the cap. It also runs the slow
dependency with the cap removed, where five attempts take 32 seconds and pass the 30-second agent
timeout. Four of its tests answer with bodies the tool cannot use. A 503 and a 429 with an HTML
page are retried on the status, and a 400 and a 500 come back in the tool's own shape. A 200 that
is not a JSON object comes back as `upstream_error`, and a body past one megabyte ends the request.
Two more tests run on a real clock against a server that stalls and one that sends a byte at a
time, and the cap ends both. The Python suite pins both comparisons, a 404 reported through
`ToolFailed`, and the attempts two retry layers multiply into.

```bash
node --test retry.test.mjs
```

```text output
1..16
# tests 16
# suites 0
# pass 16
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

```bash
python3 -m unittest test_python 2>&1 | tail -n 1
```

```text output
OK
```

## When it goes wrong

The agent run times out inside a tool that was retrying. The in-tool waits had no total, so a
slow dependency used the agent's whole budget. Check `spent + wait` against a cap below the agent's
tool timeout before each wait, as `makeGetUsage` does.

The agent's process exits on a 503. The error page was HTML, and the tool parsed it as JSON inside
the response's `end` listener, where a throw is outside every `try` around the call. Decide on the
status first, and treat a body that does not parse as missing, as `parseJson` does.

The model loops on a 400. The tool returned the API's raw error, which named no field, so the model
guessed. Return `invalid_argument` with the field and the API's message, and never retry a 400
inside the tool.

The Pydantic AI run ends with `UnexpectedModelBehavior`. A tool raised `ModelRetry` more times than
its `retries` setting allows, which is one by default. Absorb transient failures in the tool, and
keep `ModelRetry` for an argument the model can fix.

## When not to do this

Do not retry a write inside the tool unless the API takes an idempotency key. A reset after the
request was sent may hide a write that landed, and a second attempt makes it two.

Do not absorb failures the user needs to hear about. A cap that ends with `retryable: true` gives
the model something to say, and a tool that waits out a one-hour `Retry-After` gives it nothing.

Do not add a tool-level retry when the SDK under it already retries. Two layers multiply attempts,
because each attempt the tool makes runs the client's whole retry sequence: in the Python suite,
three tool attempts over `Retry(total=2)` send nine requests. The Claude Agent SDK's guides leave
retries to the model. A tool returns `isError: true`, after which
[Claude can retry](https://code.claude.com/docs/en/agent-sdk/custom-tools#handle-errors), and the
loop's own guards,
[`maxTurns` and `maxBudgetUsd`](https://code.claude.com/docs/en/agent-sdk/agent-loop), have no
limit by default.

## Related how-tos

- [Convert OpenAPI operations into tool function schemas](/howto/openapi-operations-to-tool-function-schemas)

- [Run an agent loop against a mock API in tests](/howto/run-an-agent-loop-against-a-mock-api)

- [Decide which layer retries a failed vendor call](/howto/which-layer-retries-a-vendor-call)

- [Decide which status codes an SDK should retry](/howto/decide-which-status-codes-an-sdk-retries)

- [Design error responses an autonomous agent can act on](/howto/error-responses-an-agent-can-act-on)

## Last verified

Verified 2026-11-30 against Node 22.23.5, `pydantic-ai-slim` 2.77.0, and `urllib3` 2.8.0, on
Python 3.12, 3.13, and 3.14. Every output block is what the command preceding it printed, with the model
scripted. The Claude Agent SDK was not run, because it needs an agent product: its row and its
sentences are read from its agent loop and custom tools guides.

[^1]: The six hours come with a comment in
[urllib3's source](https://raw.githubusercontent.com/urllib3/urllib3/2.8.0/src/urllib3/util/retry.py):
the value is undocumented in the RFC, and setting it to six hours matches other popular libraries.
[RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#field.retry-after) sets no ceiling on the
header, so every client picks its own.