Retry a flaky tool with exponential backoff

MediumAgentsPro

Tools fail: APIs time out, rate limits hit. Agents retry with exponential backoff, but must not retry errors that will never succeed.

Write call_with_retry(fn, max_attempts, base, cap, sleep). Call fn() up to max_attempts times. If it returns, return ("ok", value, delays). If it raises an exception whose class name is "RateLimit" or "Timeout", wait and retry: the wait before retry number k (k = 1 for the first retry) is min(cap, base * 2 ** (k - 1)); call sleep(wait) and record it in delays. Any other exception: stop at once and return ("fatal", class name, delays). If all attempts fail with retryable errors, return ("gave_up", class name of the last error, delays). No sleep after the final attempt.

Signaturedef call_with_retry(fn, max_attempts, base, cap, sleep)

Understand the idea

Tools fail for temporary reasons, like rate limits or timeouts, and for permanent ones, like a bad request. Retrying a temporary failure after a growing wait often works; retrying a permanent one never does and just wastes time and tokens. Exponential backoff doubles the wait each retry, up to a cap. Like calling a busy shop: wait a minute, then two, then four, but stop if they say the item does not exist. Worked example: base 1, cap 5, max_attempts 5, and every call times out. Waits before retries 1 to 4 are min(5, 1 x 2^0) = 1, then 2, then 4, then min(5, 8) = 5. Delays [1, 2, 4, 5], and there is no sleep after the fifth attempt, so the result is gave_up with the last error name. If attempt 3 instead raised a ValueError, you stop at once with fatal and delays [1, 2]. Rule: wait_k = min(cap, base x 2^(k - 1)); retry only RateLimit and Timeout; never sleep after the final attempt. Every production agent wraps API calls this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: succeeds on third trycall_with_retry(_flaky([RateLimit, Timeout], 42), 5, 1.0, 30.0, _noop)
  • Sample 2: fatal error stopscall_with_retry(_flaky([Timeout, BadRequest], 1), 5, 1.0, 30.0, _noop)