Spaces:
Running
Running
Husnain
commited on
Commit
•
fd1c2b0
1
Parent(s):
14ab9c7
♻️ [Refactor] Configure api info with config.json
Browse files- tests/openai.py +180 -0
tests/openai.py
ADDED
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import json
|
3 |
+
import re
|
4 |
+
import uuid
|
5 |
+
|
6 |
+
from pathlib import Path
|
7 |
+
|
8 |
+
from curl_cffi import requests
|
9 |
+
from tclogger import logger, OSEnver
|
10 |
+
from constants.envs import PROXIES
|
11 |
+
|
12 |
+
|
13 |
+
class OpenaiAPI:
|
14 |
+
def __init__(self):
|
15 |
+
self.init_requests_params()
|
16 |
+
|
17 |
+
def init_requests_params(self):
|
18 |
+
self.api_base = "https://chat.openai.com/backend-anon"
|
19 |
+
self.api_me = f"{self.api_base}/me"
|
20 |
+
self.api_models = f"{self.api_base}/models"
|
21 |
+
self.api_chat_requirements = f"{self.api_base}/sentinel/chat-requirements"
|
22 |
+
self.api_conversation = f"{self.api_base}/conversation"
|
23 |
+
self.uuid = str(uuid.uuid4())
|
24 |
+
self.requests_headers = {
|
25 |
+
# "Accept": "*/*",
|
26 |
+
"Accept-Encoding": "gzip, deflate, br, zstd",
|
27 |
+
"Accept-Language": "en-US,en;q=0.9",
|
28 |
+
"Cache-Control": "no-cache",
|
29 |
+
"Content-Type": "application/json",
|
30 |
+
"Oai-Device-Id": self.uuid,
|
31 |
+
"Oai-Language": "en-US",
|
32 |
+
"Pragma": "no-cache",
|
33 |
+
"Referer": "https://chat.openai.com/",
|
34 |
+
"Sec-Ch-Ua": 'Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
|
35 |
+
"Sec-Ch-Ua-Mobile": "?0",
|
36 |
+
"Sec-Ch-Ua-Platform": '"Windows"',
|
37 |
+
"Sec-Fetch-Dest": "empty",
|
38 |
+
"Sec-Fetch-Mode": "cors",
|
39 |
+
"Sec-Fetch-Site": "same-origin",
|
40 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36",
|
41 |
+
}
|
42 |
+
|
43 |
+
def log_request(self, url, method="GET"):
|
44 |
+
logger.note(f"> {method}:", end=" ")
|
45 |
+
logger.mesg(f"{url}", end=" ")
|
46 |
+
|
47 |
+
def log_response(self, res: requests.Response, stream=False, verbose=False):
|
48 |
+
status_code = res.status_code
|
49 |
+
status_code_str = f"[{status_code}]"
|
50 |
+
|
51 |
+
if status_code == 200:
|
52 |
+
logger_func = logger.success
|
53 |
+
else:
|
54 |
+
logger_func = logger.warn
|
55 |
+
|
56 |
+
logger_func(status_code_str)
|
57 |
+
|
58 |
+
if verbose:
|
59 |
+
if stream:
|
60 |
+
if not hasattr(self, "content_offset"):
|
61 |
+
self.content_offset = 0
|
62 |
+
|
63 |
+
for line in res.iter_lines():
|
64 |
+
line = line.decode("utf-8")
|
65 |
+
line = re.sub(r"^data:\s*", "", line)
|
66 |
+
if re.match(r"^\[DONE\]", line):
|
67 |
+
logger.success("\n[Finished]")
|
68 |
+
break
|
69 |
+
line = line.strip()
|
70 |
+
if line:
|
71 |
+
try:
|
72 |
+
data = json.loads(line, strict=False)
|
73 |
+
message_role = data["message"]["author"]["role"]
|
74 |
+
message_status = data["message"]["status"]
|
75 |
+
if (
|
76 |
+
message_role == "assistant"
|
77 |
+
and message_status == "in_progress"
|
78 |
+
):
|
79 |
+
content = data["message"]["content"]["parts"][0]
|
80 |
+
delta_content = content[self.content_offset :]
|
81 |
+
self.content_offset = len(content)
|
82 |
+
logger_func(delta_content, end="")
|
83 |
+
except Exception as e:
|
84 |
+
logger.warn(e)
|
85 |
+
else:
|
86 |
+
logger_func(res.json())
|
87 |
+
|
88 |
+
def get_models(self):
|
89 |
+
self.log_request(self.api_models)
|
90 |
+
res = requests.get(
|
91 |
+
self.api_models,
|
92 |
+
headers=self.requests_headers,
|
93 |
+
proxies=PROXIES,
|
94 |
+
timeout=10,
|
95 |
+
impersonate="chrome120",
|
96 |
+
)
|
97 |
+
self.log_response(res)
|
98 |
+
|
99 |
+
def auth(self):
|
100 |
+
self.log_request(self.api_chat_requirements, method="POST")
|
101 |
+
res = requests.post(
|
102 |
+
self.api_chat_requirements,
|
103 |
+
headers=self.requests_headers,
|
104 |
+
proxies=PROXIES,
|
105 |
+
timeout=10,
|
106 |
+
impersonate="chrome120",
|
107 |
+
)
|
108 |
+
self.chat_requirements_token = res.json()["token"]
|
109 |
+
self.log_response(res)
|
110 |
+
|
111 |
+
def transform_messages(self, messages: list[dict]):
|
112 |
+
def get_role(role):
|
113 |
+
if role in ["system", "user", "assistant"]:
|
114 |
+
return role
|
115 |
+
else:
|
116 |
+
return "system"
|
117 |
+
|
118 |
+
new_messages = [
|
119 |
+
{
|
120 |
+
"author": {"role": get_role(message["role"])},
|
121 |
+
"content": {"content_type": "text", "parts": [message["content"]]},
|
122 |
+
"metadata": {},
|
123 |
+
}
|
124 |
+
for message in messages
|
125 |
+
]
|
126 |
+
return new_messages
|
127 |
+
|
128 |
+
def chat_completions(self, messages: list[dict]):
|
129 |
+
new_headers = {
|
130 |
+
"Accept": "text/event-stream",
|
131 |
+
"Openai-Sentinel-Chat-Requirements-Token": self.chat_requirements_token,
|
132 |
+
}
|
133 |
+
requests_headers = copy.deepcopy(self.requests_headers)
|
134 |
+
requests_headers.update(new_headers)
|
135 |
+
post_data = {
|
136 |
+
"action": "next",
|
137 |
+
"messages": self.transform_messages(messages),
|
138 |
+
"parent_message_id": "",
|
139 |
+
"model": "text-davinci-002-render-sha",
|
140 |
+
"timezone_offset_min": -480,
|
141 |
+
"suggestions": [],
|
142 |
+
"history_and_training_disabled": False,
|
143 |
+
"conversation_mode": {"kind": "primary_assistant"},
|
144 |
+
"force_paragen": False,
|
145 |
+
"force_paragen_model_slug": "",
|
146 |
+
"force_nulligen": False,
|
147 |
+
"force_rate_limit": False,
|
148 |
+
"websocket_request_id": str(uuid.uuid4()),
|
149 |
+
}
|
150 |
+
self.log_request(self.api_conversation, method="POST")
|
151 |
+
s = requests.Session()
|
152 |
+
res = s.post(
|
153 |
+
self.api_conversation,
|
154 |
+
headers=requests_headers,
|
155 |
+
json=post_data,
|
156 |
+
proxies=PROXIES,
|
157 |
+
timeout=10,
|
158 |
+
impersonate="chrome120",
|
159 |
+
stream=True,
|
160 |
+
)
|
161 |
+
self.log_response(res, stream=True, verbose=True)
|
162 |
+
|
163 |
+
|
164 |
+
if __name__ == "__main__":
|
165 |
+
api = OpenaiAPI()
|
166 |
+
# api.get_models()
|
167 |
+
api.auth()
|
168 |
+
messages = [
|
169 |
+
{"role": "system", "content": "i am Hansimov"},
|
170 |
+
{"role": "system", "content": "i have a cat named lucky"},
|
171 |
+
{"role": "user", "content": "Repeat my name and my cat's name"},
|
172 |
+
{
|
173 |
+
"role": "assistant",
|
174 |
+
"content": "Your name is Hansimov and your cat's name is Lucky.",
|
175 |
+
},
|
176 |
+
{"role": "user", "content": "summarize our conversation"},
|
177 |
+
]
|
178 |
+
api.chat_completions(messages)
|
179 |
+
|
180 |
+
# python -m tests.openai
|