-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgpt_auto_retry.py
44 lines (41 loc) · 1.17 KB
/
gpt_auto_retry.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
'''
Automatic retry of OpenAI GPT calls.
'''
from typing import Callable
import time
import openai
def callWithAutoRetry(callable: Callable, *a, **kw):
retry_i = 0
max_retry = 4
while retry_i < max_retry:
try:
return callable(*a, **kw)
except (
openai.BadRequestError,
openai.AuthenticationError,
openai.PermissionDeniedError,
openai.NotFoundError,
openai.ConflictError,
openai.UnprocessableEntityError,
) as e:
raise e
except openai.RateLimitError as e:
print(e)
to_sleep = ((retry_i + 1) / 2) ** 2
print(f'Retrying in {to_sleep} seconds.')
time.sleep(to_sleep)
print('Retrying...')
continue
except openai.InternalServerError as e:
print(e)
to_sleep = 1
print(f'Retrying in {to_sleep} seconds.')
time.sleep(to_sleep)
print('Retrying...')
continue
except Exception as e:
raise e
finally:
retry_i += 1
else:
raise RuntimeError('Too many retries.')