-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.py
47 lines (39 loc) · 1.36 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import time
import openai
import anthropic
import google.api_core.exceptions as google_exceptions
# define a retry decorator
def retry_with_linear_backoff(
delay: float = 90,
max_retries: int = 10,
errors: tuple = (
openai.RateLimitError,
anthropic.RateLimitError,
google_exceptions.ResourceExhausted,
),
):
"""Retry a function with linear backoff."""
def decorator(func):
def wrapper(*args, **kwargs):
# Initialize variables
num_retries = 0
# Loop until a successful response or max_retries is hit or an exception is raised
while True:
try:
return func(*args, **kwargs)
# Retry on specified errors
except errors as e:
# Increment retries
num_retries += 1
# Check if max retries has been reached
if num_retries > max_retries:
raise Exception(
f"Maximum number of retries ({max_retries}) exceeded."
)
# Sleep for the delay
time.sleep(delay)
# Raise exceptions for any errors not specified
except Exception as e:
raise e
return wrapper
return decorator