Retry on an LLM Provider's rate limit error with exponential backoff For example, to use for OpenAI, do the following: ``` from openai import RateLimitError # Recommend specifying max_retries to avoid infinite loops! @retry_on_specific_exceptions([RateLimitError], max_retries=3)
(
on_exceptions: List[Type[Exception]],
max_retries: Optional[int] = None,
backoff_time: float = 3.0,
backoff_multiplier: float = 1.5,
on_exception_callback: Optional[Callable[[Exception, float], Any]] = None,
)
| 313 | |
| 314 | |
| 315 | def retry_on_specific_exceptions( |
| 316 | on_exceptions: List[Type[Exception]], |
| 317 | max_retries: Optional[int] = None, |
| 318 | backoff_time: float = 3.0, |
| 319 | backoff_multiplier: float = 1.5, |
| 320 | on_exception_callback: Optional[Callable[[Exception, float], Any]] = None, |
| 321 | ): |
| 322 | """Retry on an LLM Provider's rate limit error with exponential backoff |
| 323 | For example, to use for OpenAI, do the following: |
| 324 | ``` |
| 325 | from openai import RateLimitError |
| 326 | |
| 327 | # Recommend specifying max_retries to avoid infinite loops! |
| 328 | @retry_on_specific_exceptions([RateLimitError], max_retries=3) |
| 329 | def completion(...): |
| 330 | # Wrap OpenAI completion function here |
| 331 | ... |
| 332 | ``` |
| 333 | """ |
| 334 | |
| 335 | def decorator(func: Callable): |
| 336 | @wraps(func) |
| 337 | def wrapper(*args, **kwargs): |
| 338 | sleep_time = backoff_time |
| 339 | attempt = 0 |
| 340 | while max_retries is None or attempt < max_retries: |
| 341 | try: |
| 342 | return func(*args, **kwargs) |
| 343 | except tuple(on_exceptions) as e: |
| 344 | if on_exception_callback is not None: |
| 345 | on_exception_callback(e, sleep_time) |
| 346 | time.sleep(sleep_time) |
| 347 | sleep_time *= backoff_multiplier |
| 348 | attempt += 1 |
| 349 | |
| 350 | return wrapper |
| 351 | |
| 352 | return decorator |
| 353 | |
| 354 | |
| 355 | class Collator: |
nothing calls this directly
no outgoing calls
no test coverage detected