Spaces:
Running
Running
Qifan Zhang
commited on
Commit
•
e60f0c0
1
Parent(s):
f89a7d8
add random api_key to avoid openai restrict
Browse files- utils/chatgpt.py +13 -6
utils/chatgpt.py
CHANGED
@@ -1,16 +1,25 @@
|
|
|
|
|
|
1 |
import openai
|
2 |
|
3 |
|
4 |
class ChatGPTAPI:
|
5 |
def __init__(self, api_key: str = '', max_input_length: int = 1024):
|
|
|
|
|
|
|
|
|
|
|
6 |
if not api_key:
|
7 |
try:
|
8 |
api_key = open('data/api_key.txt', 'r').read()
|
9 |
except Exception as e:
|
10 |
raise Exception(f'ChatGPT Error: No API key provided {e}')
|
11 |
|
12 |
-
|
13 |
-
|
|
|
|
|
14 |
|
15 |
def __call__(self, content: str):
|
16 |
assert isinstance(content, str), 'ChatGPT Error: content must be a string'
|
@@ -30,7 +39,5 @@ class ChatGPTAPI:
|
|
30 |
|
31 |
if __name__ == '__main__':
|
32 |
chatgpt = ChatGPTAPI()
|
33 |
-
|
34 |
-
|
35 |
-
# response = chatgpt('Hello, how are you?')
|
36 |
-
# print(response)
|
|
|
1 |
+
import random
|
2 |
+
|
3 |
import openai
|
4 |
|
5 |
|
6 |
class ChatGPTAPI:
|
7 |
def __init__(self, api_key: str = '', max_input_length: int = 1024):
|
8 |
+
openai.api_key = self.load_api_key(api_key)
|
9 |
+
self.max_input_length = max_input_length
|
10 |
+
|
11 |
+
@staticmethod
|
12 |
+
def load_api_key(api_key: str):
|
13 |
if not api_key:
|
14 |
try:
|
15 |
api_key = open('data/api_key.txt', 'r').read()
|
16 |
except Exception as e:
|
17 |
raise Exception(f'ChatGPT Error: No API key provided {e}')
|
18 |
|
19 |
+
if '\n' in api_key:
|
20 |
+
api_key_list = api_key.strip().split('\n')
|
21 |
+
api_key = random.choice(api_key_list)
|
22 |
+
return api_key
|
23 |
|
24 |
def __call__(self, content: str):
|
25 |
assert isinstance(content, str), 'ChatGPT Error: content must be a string'
|
|
|
39 |
|
40 |
if __name__ == '__main__':
|
41 |
chatgpt = ChatGPTAPI()
|
42 |
+
response = chatgpt('Hello, how are you?')
|
43 |
+
print(response)
|
|
|
|