AI Agents by HandAll problemsAbout

All problems › Agent problem · medium · ~15 min

Retry and backoff on API errors

retries backoff error handling

Solve it in your browser →

A loop that survives the API (~15 min)

retry_backoff.py is an on-call helper with two read-only tools (get_service_status, get_recent_deploys) and their schemas, but run_agent is a stub.

In production the Messages API sometimes answers with 429 rate_limit_error, 529 overloaded_error, a 5xx, or a dropped connection. The SDK retries those itself by default (max_retries=2), but this agent owns its retry policy: the starter's get_client() builds the client with max_retries=0.

Implement run_agent(prompt, client=None, max_turns=10, max_retries=3, sleep=time.sleep) -> str so that:

  1. It calls client.messages.create with the model, max_tokens, tools=TOOLS and the running messages. While the model wants tools, it runs every tool_use block through HANDLERS and calls the model again with the results (strings, all in one user message). When the model is done, it returns the text blocks joined.
  2. If a tool raises, or the model asks for an unknown tool, send that tool_result back with is_error: True and a useful message. One bad call must not drop the others.
  3. max_turns counts model calls that returned a response. Still calling tools after that many: raise RuntimeError.
  4. Transient failures are retried. When create raises anthropic.RateLimitError, anthropic.APIConnectionError (including APITimeoutError), or any anthropic.APIStatusError whose status_code >= 500 (InternalServerError, OverloadedError), wait and send the same request again: at most max_retries retries per model call, waiting 1s before the first retry, 2s before the second, 4s before the third (doubling), via sleep(seconds). If the error's response carries a retry-after header (seconds), wait that many seconds instead for that retry. When the retries are used up, re-raise the last error.
  5. Nothing else is retried. BadRequestError (400), AuthenticationError (401), PermissionDeniedError, NotFoundError, and any non-SDK exception propagate immediately, with no sleep.
  6. Retries don't count toward max_turns, and a retried request carries exactly the same messages as the failed one (no duplicated or missing tool results).

Be ready to say when you'd rely on the SDK's built-in retries instead, and why a 400 must never be retried.

Try it: python -m retry_backoff Check it: pytest tests/test_retry_backoff.py

Starter code and hidden tests open in the editor. Nothing to install.