1A two-second hiccup
Why an agent needs a plan for failed calls.
A typical AI support agent makes several calls to outside services for every question: one model call to classify the message, a search call to find the answer, and a second model call to write the reply. Any of them can fail for reasons that have nothing to do with your code: a dropped connection, a brief overload, a rate limit.
Most of these failures clear up within seconds. Without a plan, though, one failed call ends the whole conversation. A retry is that plan: try again, but in a controlled way.
2Which failures to retry
Retry what waiting can fix. Fail fast on the rest.
Only some failures are worth a second try. The rule of thumb: retry what waiting can fix, and fail fast on everything else. The codes below are from Anthropic's API errors page; other providers use similar ones.
| What happened | What it means | Retry? |
|---|---|---|
| Connection dropped or timed out | A network or server hiccup | Yes |
| 429 rate_limit_error | Too many requests for your current limit | Yes, after waiting. One exception: a 429 from hitting a monthly spend cap keeps failing until access resumes |
| 500 api_error | An unexpected error on the provider's side | Yes, with backoff (the docs say so) |
| 529 overloaded_error | The API is temporarily overloaded | Yes, after waiting |
| 400, 401, 403 | A malformed request, a bad key, or no permission | No. It will fail the same way every time |
3How many attempts
A ceiling of three, and what happens when all three fail.
Tenacity adds retries to a function with one decorator. The version below uses the settings from my agent: at most 3 attempts, with a growing wait between them. The fake model call fails twice, then succeeds.
from tenacity import retry, stop_after_attempt, wait_exponential
calls = {"n": 0}
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def call_model(prompt): # stand-in for a real model call
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("connection dropped")
return "Billing"
waits = []
call_model.retry.sleep = waits.append # record each wait instead of sleeping, so the demo runs instantly
print("result:", call_model("Can I get a refund?"))
print("attempts:", calls["n"], "| waits (seconds):", waits)result: Billing attempts: 3 | waits (seconds): [2.0, 2.0]
Three attempts is a sensible ceiling for a live conversation. Most brief failures clear on the second or third try, and a customer will not wait much longer than that. When all three fail, something is really wrong, and the error should come through rather than loop forever.
One detail surprised me: by default, Tenacity does not raise your original error after the last attempt. It raises its own RetryError with the original tucked inside:
from tenacity import retry, stop_after_attempt, wait_exponential, RetryError
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
def call_model(prompt):
raise ConnectionError("service down") # fails every time
call_model.retry.sleep = lambda s: None
try:
call_model("hello")
except RetryError as e:
print("caught:", type(e).__name__)
print("the real error inside:", repr(e.last_attempt.exception()))caught: RetryError
the real error inside: ConnectionError('service down')
Any code above it that catches ConnectionError will miss this. Card 6 shows the one-word fix.
4How long to wait
Exponential backoff, and the mistake in the settings.
Waiting longer after each failure is called exponential backoff. An overloaded service needs room to recover, and hitting it again instantly makes the overload worse. Tenacity's wait_exponential doubles the wait each time, then clamps it between min and max.
Here is the mistake I made. I believed my settings meant "wait 2, then 4, then 8 seconds". Running it shows otherwise:
from tenacity import wait_exponential
class Attempt: # the one field wait_exponential reads
def __init__(self, n): self.attempt_number = n
for label, w in [("multiplier=1, min=2, max=10", wait_exponential(multiplier=1, min=2, max=10)),
("multiplier=2, min=2, max=10", wait_exponential(multiplier=2, min=2, max=10))]:
print(label, "->", [float(w(Attempt(n))) for n in range(1, 5)])multiplier=1, min=2, max=10 -> [2.0, 2.0, 4.0, 8.0] multiplier=2, min=2, max=10 -> [2.0, 4.0, 8.0, 10.0]
| Setting | What it does | Waits actually used with 3 attempts |
|---|---|---|
multiplier=1, min=2 | The first two waits are 1 and 2 seconds, and min=2 raises the first to 2 | 2s, 2s |
multiplier=2, min=2 | Starts at 2 and doubles | 2s, 4s |
min can flatten the start of the curve. To actually get 2, 4 and 8 seconds, you need multiplier=2 and 4 attempts.Many systems also add a small random amount to each wait, called jitter, so that many clients that failed together do not all retry at the same moment. Tenacity offers wait_random_exponential for this.
5What to wrap
Only the risky call, never the logic around it.
The third decision is where the decorator goes. Put it only on the function that makes the network call, not on the whole step around it.
from tenacity import retry, stop_after_attempt
ALLOWED = {"Billing", "Technical", "Sales", "General"}
calls = {"model": 0, "validate": 0}
@retry(stop=stop_after_attempt(3))
def _call_classifier(text): # only the risky network call is retried
calls["model"] += 1
if calls["model"] < 3:
raise TimeoutError("timed out")
return " billing\n"
def classify(text): # the step: one call, then local logic
raw = _call_classifier(text)
calls["validate"] += 1
label = raw.strip().title()
return label if label in ALLOWED else "General"
_call_classifier.retry.sleep = lambda s: None
print("label:", classify("Why was I charged twice?"))
print("model calls:", calls["model"], "| validation runs:", calls["validate"])label: Billing model calls: 3 | validation runs: 1
The model call ran three times. The validation ran once, on the answer that finally came back. If the decorator wrapped the whole step instead, every retry would also repeat the logic around the call, including anything that writes, logs or sends.
The same rule applies to tools. A tool that only reads local data has no network to fail on, so it gets no retry at all.
6Retry only what a wait can fix
Filter errors, and raise the real one.
My first version retried any error, so a bad API key got three slow, doomed attempts. Two more arguments fix that: retry= limits retries to errors a wait can fix, and reraise=True raises the real error at the end instead of RetryError.
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
calls = {"n": 0}
@retry(stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=10),
retry=retry_if_exception_type((ConnectionError, TimeoutError)), # only what a wait can fix
reraise=True) # raise the real error, not RetryError
def call_model(prompt, error):
calls["n"] += 1
raise error
call_model.retry.sleep = lambda s: None
for err in [TimeoutError("timed out"), PermissionError("invalid API key")]:
calls["n"] = 0
try:
call_model("hi", err)
except Exception as e:
print(f"{type(e).__name__:<16} attempts: {calls['n']}")TimeoutError attempts: 3 PermissionError attempts: 1
The timeout was retried three times. The permission error failed on its first attempt, which is what you want. With a provider SDK, you would list that SDK's own exception classes for timeouts, connection errors, rate limits and overload, instead of Python's built-in ones used here.
7Check the layer below
Your retry and the SDK's retry can multiply.
Before adding your own retries, check what the layer below already does. Anthropic's errors page says its official SDK already retries connection errors, rate limits and 5xx errors twice by default, with exponential backoff, and it respects the retry-after header the API sends.
max_retries and let your code decide, or rely on the SDK and keep your own retries for the services that do not have them. Agent frameworks often add a third layer, such as a retry setting on a graph node, so check there too.8Make retries safe
Repeatable side effects, and a log line per retry.
Two habits make retries safe:
- Make side effects safe to repeat first. If a call sends an email or charges a card, a retry after a lost response can do it twice. Give the action a unique key that the receiving side can recognise, a pattern called idempotency, before you put a retry on it.
- Log every retry. A call that succeeds on its third attempt looks exactly like one that worked first time unless you record it. Tenacity's
before_sleephook runs before each wait and is a natural place for a log line. (See Logging for AI apps.)
9Check yourself
Short questions, a try-it and one line to remember.
What are the three decisions behind a retry?
How many attempts to allow, how long to wait between them, and which code to wrap.
With stop_after_attempt(3), how many waits happen?
Two. There is no wait after the last failure.
Why do wait_exponential(multiplier=1, min=2) waits start 2s, 2s?
The raw waits are 1s then 2s, and min=2 raises the first one to 2s.
Why wrap only the network call, not the whole step?
So the logic around the call, such as validation or writing data, runs once on the final answer, not once per attempt.
Which errors should you not retry?
Ones a wait cannot fix: a malformed request, a bad key, missing permission, or a spend cap that has been reached.
multiplier=2 and stop_after_attempt(4), make the fake call fail three times, and confirm the waits come out as 2, 4 and 8. Then add reraise=True to the "gives up" snippet and see which error it raises now.