-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathchatgpt.py
39 lines (35 loc) · 1.31 KB
/
chatgpt.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
import time
import openai
from colorama import Fore
from config import cfg
def create_chat_completion(messages, model=cfg.fast_llm_model, temperature=cfg.temperature, max_tokens=None) -> str:
"""Create a chat completion using the OpenAI API"""
response = None
num_retries = 5
for attempt in range(num_retries):
try:
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=temperature,
max_tokens=max_tokens
)
break
except openai.error.RateLimitError:
if cfg.debug_mode:
print(Fore.RED + "Error: ", "API Rate Limit Reached. Waiting 20 seconds..." + Fore.RESET)
time.sleep(20)
except openai.error.APIError as e:
if e.http_status == 502:
if cfg.debug_mode:
print(Fore.RED + "Error: ", "API Bad gateway. Waiting 20 seconds..." + Fore.RESET)
time.sleep(20)
else:
raise
if attempt == num_retries - 1:
raise
except openai.error.InvalidRequestError:
raise
if response is None:
raise RuntimeError("Failed to get response after 5 retries")
return response.choices[0].message["content"]