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:
- It calls
client.messages.createwith the model,max_tokens,tools=TOOLSand the runningmessages. While the model wants tools, it runs everytool_useblock throughHANDLERSand calls the model again with the results (strings, all in one user message). When the model is done, it returns the text blocks joined. - If a tool raises, or the model asks for an unknown tool, send that
tool_resultback withis_error: Trueand a useful message. One bad call must not drop the others. max_turnscounts model calls that returned a response. Still calling tools after that many: raiseRuntimeError.- Transient failures are retried. When
createraisesanthropic.RateLimitError,anthropic.APIConnectionError(includingAPITimeoutError), or anyanthropic.APIStatusErrorwhosestatus_code >= 500(InternalServerError,OverloadedError), wait and send the same request again: at mostmax_retriesretries per model call, waiting 1s before the first retry, 2s before the second, 4s before the third (doubling), viasleep(seconds). If the error'sresponsecarries aretry-afterheader (seconds), wait that many seconds instead for that retry. When the retries are used up, re-raise the last error. - Nothing else is retried.
BadRequestError(400),AuthenticationError(401),PermissionDeniedError,NotFoundError, and any non-SDK exception propagate immediately, with nosleep. - Retries don't count toward
max_turns, and a retried request carries exactly the samemessagesas 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