Python: Add auto_retry.py sample for rate limit handling#4223
Draft
Python: Add auto_retry.py sample for rate limit handling#4223
Conversation
Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com>
Copilot
AI
changed the title
[WIP] Add rate limiting handling for model clients
Python: Add auto_retry.py sample for rate limit handling
Feb 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation and Context
Every model inference API is rate-limited. Without built-in retry support in the framework, every consumer must write the same boilerplate. This sample shows two clean, copy-paste-ready patterns using
tenacityso developers can focus on agent logic instead.Description
Adds
python/samples/02-agents/auto_retry.pydemonstrating two approaches to automatic retry onRateLimitError(HTTP 429):Approach 1 – Client subclass
Override
get_response()in a subclass of any chat client. Non-streaming calls are wrapped in atenacity.AsyncRetryingloop so each retry re-issues the full HTTP request (not a re-await of a stale coroutine). Streaming falls back to the parent with a note that streaming retry requires more delicate handling.Approach 2 – Chat middleware (two styles)
Class-based –
RateLimitRetryMiddleware(ChatMiddleware)wrapsawait call_next()inAsyncRetrying.Function-based –
@chat_middlewaredecorated function, with an inner async function decorated by@retry, that callscall_next():Contribution Checklist
Original prompt
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.