Delete chatgpt/ChatService.py
Browse files- chatgpt/ChatService.py +0 -521
chatgpt/ChatService.py
DELETED
@@ -1,521 +0,0 @@
|
|
1 |
-
import asyncio
|
2 |
-
import json
|
3 |
-
import random
|
4 |
-
import uuid
|
5 |
-
|
6 |
-
from fastapi import HTTPException
|
7 |
-
from starlette.concurrency import run_in_threadpool
|
8 |
-
|
9 |
-
from api.files import get_image_size, get_file_extension, determine_file_use_case
|
10 |
-
from api.models import model_proxy
|
11 |
-
from chatgpt.authorization import get_req_token, verify_token, get_ua
|
12 |
-
from chatgpt.chatFormat import api_messages_to_chat, stream_response, format_not_stream_response, head_process_response
|
13 |
-
from chatgpt.chatLimit import check_is_limit, handle_request_limit
|
14 |
-
from chatgpt.proofofWork import get_config, get_dpl, get_answer_token, get_requirements_token
|
15 |
-
|
16 |
-
from utils.Client import Client
|
17 |
-
from utils.Logger import logger
|
18 |
-
from utils.config import (
|
19 |
-
proxy_url_list,
|
20 |
-
chatgpt_base_url_list,
|
21 |
-
ark0se_token_url_list,
|
22 |
-
history_disabled,
|
23 |
-
pow_difficulty,
|
24 |
-
conversation_only,
|
25 |
-
enable_limit,
|
26 |
-
upload_by_url,
|
27 |
-
check_model,
|
28 |
-
auth_key,
|
29 |
-
user_agents_list,
|
30 |
-
turnstile_solver_url,
|
31 |
-
)
|
32 |
-
|
33 |
-
|
34 |
-
class ChatService:
|
35 |
-
def __init__(self, origin_token=None):
|
36 |
-
# self.user_agent = random.choice(user_agents_list) if user_agents_list else "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
|
37 |
-
self.req_token = get_req_token(origin_token)
|
38 |
-
self.ua = get_ua(self.req_token)
|
39 |
-
self.user_agent = self.ua.get(
|
40 |
-
"user-agent",
|
41 |
-
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
|
42 |
-
)
|
43 |
-
self.chat_token = "gAAAAAB"
|
44 |
-
self.s = None
|
45 |
-
self.ws = None
|
46 |
-
|
47 |
-
async def set_dynamic_data(self, data):
|
48 |
-
if self.req_token:
|
49 |
-
logger.info(f"Request impersonate: {self.ua.get('impersonate')}")
|
50 |
-
logger.info(f"Request ua:{self.user_agent}")
|
51 |
-
logger.info(f"Request token: {self.req_token}")
|
52 |
-
req_len = len(self.req_token.split(","))
|
53 |
-
if req_len == 1:
|
54 |
-
self.access_token = await verify_token(self.req_token)
|
55 |
-
self.account_id = None
|
56 |
-
else:
|
57 |
-
self.access_token = await verify_token(self.req_token.split(",")[0])
|
58 |
-
self.account_id = self.req_token.split(",")[1]
|
59 |
-
else:
|
60 |
-
logger.info("Request token is empty, use no-auth 3.5")
|
61 |
-
self.access_token = None
|
62 |
-
self.account_id = None
|
63 |
-
|
64 |
-
self.data = data
|
65 |
-
await self.set_model()
|
66 |
-
if enable_limit and self.req_token:
|
67 |
-
limit_response = await handle_request_limit(self.req_token, self.req_model)
|
68 |
-
if limit_response:
|
69 |
-
raise HTTPException(status_code=429, detail=limit_response)
|
70 |
-
|
71 |
-
self.account_id = self.data.get('Chatgpt-Account-Id', self.account_id)
|
72 |
-
self.parent_message_id = self.data.get('parent_message_id')
|
73 |
-
self.conversation_id = self.data.get('conversation_id')
|
74 |
-
self.history_disabled = self.data.get('history_disabled', history_disabled)
|
75 |
-
|
76 |
-
self.api_messages = self.data.get("messages", [])
|
77 |
-
self.prompt_tokens = 0
|
78 |
-
self.max_tokens = self.data.get("max_tokens", 2147483647)
|
79 |
-
if not isinstance(self.max_tokens, int):
|
80 |
-
self.max_tokens = 2147483647
|
81 |
-
|
82 |
-
self.proxy_url = random.choice(proxy_url_list) if proxy_url_list else None
|
83 |
-
self.host_url = random.choice(chatgpt_base_url_list) if chatgpt_base_url_list else "https://chatgpt.com"
|
84 |
-
self.ark0se_token_url = random.choice(ark0se_token_url_list) if ark0se_token_url_list else None
|
85 |
-
|
86 |
-
self.s = Client(proxy=self.proxy_url, impersonate=self.ua.get("impersonate", "safari15_3"))
|
87 |
-
|
88 |
-
self.oai_device_id = str(uuid.uuid4())
|
89 |
-
self.persona = None
|
90 |
-
self.ark0se_token = None
|
91 |
-
self.proof_token = None
|
92 |
-
self.turnstile_token = None
|
93 |
-
|
94 |
-
self.chat_headers = None
|
95 |
-
self.chat_request = None
|
96 |
-
|
97 |
-
self.base_headers = {
|
98 |
-
'accept': '*/*',
|
99 |
-
'accept-encoding': 'gzip, deflate, br, zstd',
|
100 |
-
'accept-language': 'en-US,en;q=0.9',
|
101 |
-
'content-type': 'application/json',
|
102 |
-
'oai-device-id': self.oai_device_id,
|
103 |
-
'oai-language': 'en-US',
|
104 |
-
'origin': self.host_url,
|
105 |
-
'priority': 'u=1, i',
|
106 |
-
'referer': f'{self.host_url}/',
|
107 |
-
'sec-ch-ua': self.ua.get("sec-ch-ua", '"Chromium";v="124", "Microsoft Edge";v="124", "Not-A.Brand";v="99"'),
|
108 |
-
'sec-ch-ua-mobile': self.ua.get("sec-ch-ua-mobile", "?0"),
|
109 |
-
'sec-ch-ua-platform': self.ua.get("sec-ch-ua-platform", '"Windows"'),
|
110 |
-
'sec-fetch-dest': 'empty',
|
111 |
-
'sec-fetch-mode': 'cors',
|
112 |
-
'sec-fetch-site': 'same-origin',
|
113 |
-
'user-agent': self.user_agent
|
114 |
-
}
|
115 |
-
if self.access_token:
|
116 |
-
self.base_url = self.host_url + "/backend-api"
|
117 |
-
self.base_headers['Authorization'] = f'Bearer {self.access_token}'
|
118 |
-
if self.account_id:
|
119 |
-
self.base_headers['Chatgpt-Account-Id'] = self.account_id
|
120 |
-
else:
|
121 |
-
self.base_url = self.host_url + "/backend-anon"
|
122 |
-
|
123 |
-
if auth_key:
|
124 |
-
self.base_headers['authkey'] = auth_key
|
125 |
-
|
126 |
-
await get_dpl(self)
|
127 |
-
|
128 |
-
async def set_model(self):
|
129 |
-
self.origin_model = self.data.get("model", "gpt-3.5-turbo-0125")
|
130 |
-
self.resp_model = model_proxy.get(self.origin_model, self.origin_model)
|
131 |
-
if "o1-preview" in self.origin_model:
|
132 |
-
self.req_model = "o1-preview"
|
133 |
-
elif "o1-mini" in self.origin_model:
|
134 |
-
self.req_model = "o1-mini"
|
135 |
-
elif "o1" in self.origin_model:
|
136 |
-
self.req_model = "o1"
|
137 |
-
elif "gpt-4.5o" in self.origin_model:
|
138 |
-
self.req_model = "gpt-4.5o"
|
139 |
-
elif "gpt-4o-canmore" in self.origin_model:
|
140 |
-
self.req_model = "gpt-4o-canmore"
|
141 |
-
elif "gpt-4o-mini" in self.origin_model:
|
142 |
-
self.req_model = "gpt-4o-mini"
|
143 |
-
elif "gpt-4o" in self.origin_model:
|
144 |
-
self.req_model = "gpt-4o"
|
145 |
-
elif "gpt-4-mobile" in self.origin_model:
|
146 |
-
self.req_model = "gpt-4-mobile"
|
147 |
-
elif "gpt-4-gizmo" in self.origin_model:
|
148 |
-
self.req_model = "gpt-4o"
|
149 |
-
elif "gpt-4" in self.origin_model:
|
150 |
-
self.req_model = "gpt-4"
|
151 |
-
elif "gpt-3.5" in self.origin_model:
|
152 |
-
self.req_model = "text-davinci-002-render-sha"
|
153 |
-
elif "auto" in self.origin_model:
|
154 |
-
self.req_model = "auto"
|
155 |
-
else:
|
156 |
-
self.req_model = "auto"
|
157 |
-
|
158 |
-
async def get_chat_requirements(self):
|
159 |
-
if conversation_only:
|
160 |
-
return None
|
161 |
-
url = f'{self.base_url}/sentinel/chat-requirements'
|
162 |
-
headers = self.base_headers.copy()
|
163 |
-
try:
|
164 |
-
config = get_config(self.user_agent)
|
165 |
-
p = get_requirements_token(config)
|
166 |
-
data = {'p': p}
|
167 |
-
r = await self.s.post(url, headers=headers, json=data, timeout=5)
|
168 |
-
if r.status_code == 200:
|
169 |
-
resp = r.json()
|
170 |
-
|
171 |
-
if check_model:
|
172 |
-
r = await self.s.get(f'{self.base_url}/models', headers=headers, timeout=5)
|
173 |
-
if r.status_code == 200:
|
174 |
-
models = r.json().get('models')
|
175 |
-
if not any(self.req_model in model.get("slug", "") for model in models):
|
176 |
-
logger.error(f"Model {self.req_model} not support.")
|
177 |
-
raise HTTPException(
|
178 |
-
status_code=404,
|
179 |
-
detail={
|
180 |
-
"message": f"The model `{self.origin_model}` does not exist or you do not have access to it.",
|
181 |
-
"type": "invalid_request_error",
|
182 |
-
"param": None,
|
183 |
-
"code": "model_not_found",
|
184 |
-
},
|
185 |
-
)
|
186 |
-
else:
|
187 |
-
raise HTTPException(status_code=404, detail="Failed to get models")
|
188 |
-
else:
|
189 |
-
self.persona = resp.get("persona")
|
190 |
-
if self.persona != "chatgpt-paid":
|
191 |
-
if self.req_model == "gpt-4":
|
192 |
-
logger.error(f"Model {self.resp_model} not support for {self.persona}")
|
193 |
-
raise HTTPException(
|
194 |
-
status_code=404,
|
195 |
-
detail={
|
196 |
-
"message": f"The model `{self.origin_model}` does not exist or you do not have access to it.",
|
197 |
-
"type": "invalid_request_error",
|
198 |
-
"param": None,
|
199 |
-
"code": "model_not_found",
|
200 |
-
},
|
201 |
-
)
|
202 |
-
|
203 |
-
turnstile = resp.get('turnstile', {})
|
204 |
-
turnstile_required = turnstile.get('required')
|
205 |
-
if turnstile_required:
|
206 |
-
turnstile_dx = turnstile.get("dx")
|
207 |
-
try:
|
208 |
-
if turnstile_solver_url:
|
209 |
-
res = await self.s.post(
|
210 |
-
turnstile_solver_url, json={"url": "https://chatgpt.com", "p": p, "dx": turnstile_dx}
|
211 |
-
)
|
212 |
-
self.turnstile_token = res.json().get("t")
|
213 |
-
except Exception as e:
|
214 |
-
logger.info(f"Turnstile ignored: {e}")
|
215 |
-
# raise HTTPException(status_code=403, detail="Turnstile required")
|
216 |
-
|
217 |
-
ark0se = resp.get('ark' + 'ose', {})
|
218 |
-
ark0se_required = ark0se.get('required')
|
219 |
-
if ark0se_required:
|
220 |
-
if self.persona == "chatgpt-freeaccount":
|
221 |
-
ark0se_method = "chat35"
|
222 |
-
else:
|
223 |
-
ark0se_method = "chat4"
|
224 |
-
if not self.ark0se_token_url:
|
225 |
-
raise HTTPException(status_code=403, detail="Ark0se service required")
|
226 |
-
ark0se_dx = ark0se.get("dx")
|
227 |
-
ark0se_client = Client(impersonate=self.ua.get("impersonate", "safari15_3"))
|
228 |
-
try:
|
229 |
-
r2 = await ark0se_client.post(
|
230 |
-
url=self.ark0se_token_url, json={"blob": ark0se_dx, "method": ark0se_method}, timeout=15
|
231 |
-
)
|
232 |
-
r2esp = r2.json()
|
233 |
-
logger.info(f"ark0se_token: {r2esp}")
|
234 |
-
if r2esp.get('solved', True):
|
235 |
-
self.ark0se_token = r2esp.get('token')
|
236 |
-
else:
|
237 |
-
raise HTTPException(status_code=403, detail="Failed to get Ark0se token")
|
238 |
-
except Exception:
|
239 |
-
raise HTTPException(status_code=403, detail="Failed to get Ark0se token")
|
240 |
-
finally:
|
241 |
-
await ark0se_client.close()
|
242 |
-
|
243 |
-
proofofwork = resp.get('proofofwork', {})
|
244 |
-
proofofwork_required = proofofwork.get('required')
|
245 |
-
if proofofwork_required:
|
246 |
-
proofofwork_diff = proofofwork.get("difficulty")
|
247 |
-
if proofofwork_diff <= pow_difficulty:
|
248 |
-
raise HTTPException(status_code=403, detail=f"Proof of work difficulty too high: {proofofwork_diff}")
|
249 |
-
proofofwork_seed = proofofwork.get("seed")
|
250 |
-
self.proof_token, solved = await run_in_threadpool(
|
251 |
-
get_answer_token, proofofwork_seed, proofofwork_diff, config
|
252 |
-
)
|
253 |
-
if not solved:
|
254 |
-
raise HTTPException(status_code=403, detail="Failed to solve proof of work")
|
255 |
-
|
256 |
-
self.chat_token = resp.get('token')
|
257 |
-
if not self.chat_token:
|
258 |
-
raise HTTPException(status_code=403, detail=f"Failed to get chat token: {r.text}")
|
259 |
-
return self.chat_token
|
260 |
-
else:
|
261 |
-
if "application/json" == r.headers.get("Content-Type", ""):
|
262 |
-
detail = r.json().get("detail", r.json())
|
263 |
-
else:
|
264 |
-
detail = r.text
|
265 |
-
if "cf-spinner-please-wait" in detail:
|
266 |
-
raise HTTPException(status_code=r.status_code, detail="cf-spinner-please-wait")
|
267 |
-
if r.status_code == 429:
|
268 |
-
raise HTTPException(status_code=r.status_code, detail="rate-limit")
|
269 |
-
raise HTTPException(status_code=r.status_code, detail=detail)
|
270 |
-
except HTTPException as e:
|
271 |
-
raise HTTPException(status_code=e.status_code, detail=e.detail)
|
272 |
-
except Exception as e:
|
273 |
-
raise HTTPException(status_code=500, detail=str(e))
|
274 |
-
|
275 |
-
async def prepare_send_conversation(self):
|
276 |
-
try:
|
277 |
-
chat_messages, self.prompt_tokens = await api_messages_to_chat(self, self.api_messages, upload_by_url)
|
278 |
-
except Exception as e:
|
279 |
-
logger.error(f"Failed to format messages: {str(e)}")
|
280 |
-
raise HTTPException(status_code=400, detail="Failed to format messages.")
|
281 |
-
self.chat_headers = self.base_headers.copy()
|
282 |
-
self.chat_headers.update(
|
283 |
-
{
|
284 |
-
'accept': 'text/event-stream',
|
285 |
-
'openai-sentinel-chat-requirements-token': self.chat_token,
|
286 |
-
'openai-sentinel-proof-token': self.proof_token,
|
287 |
-
}
|
288 |
-
)
|
289 |
-
if self.ark0se_token:
|
290 |
-
self.chat_headers['openai-sentinel-ark' + 'ose-token'] = self.ark0se_token
|
291 |
-
|
292 |
-
if self.turnstile_token:
|
293 |
-
self.chat_headers['openai-sentinel-turnstile-token'] = self.turnstile_token
|
294 |
-
|
295 |
-
if conversation_only:
|
296 |
-
self.chat_headers.pop('openai-sentinel-chat-requirements-token', None)
|
297 |
-
self.chat_headers.pop('openai-sentinel-proof-token', None)
|
298 |
-
self.chat_headers.pop('openai-sentinel-ark' + 'ose-token', None)
|
299 |
-
self.chat_headers.pop('openai-sentinel-turnstile-token', None)
|
300 |
-
|
301 |
-
if "gpt-4-gizmo" in self.origin_model:
|
302 |
-
gizmo_id = self.origin_model.split("gpt-4-gizmo-")[-1]
|
303 |
-
conversation_mode = {"kind": "gizmo_interaction", "gizmo_id": gizmo_id}
|
304 |
-
else:
|
305 |
-
conversation_mode = {"kind": "primary_assistant"}
|
306 |
-
|
307 |
-
logger.info(f"Model mapping: {self.origin_model} -> {self.req_model}")
|
308 |
-
self.chat_request = {
|
309 |
-
"action": "next",
|
310 |
-
"conversation_mode": conversation_mode,
|
311 |
-
"force_nulligen": False,
|
312 |
-
"force_paragen": False,
|
313 |
-
"force_paragen_model_slug": "",
|
314 |
-
"force_rate_limit": False,
|
315 |
-
"force_use_sse": True,
|
316 |
-
"history_and_training_disabled": self.history_disabled,
|
317 |
-
"messages": chat_messages,
|
318 |
-
"model": self.req_model,
|
319 |
-
"parent_message_id": self.parent_message_id if self.parent_message_id else f"{uuid.uuid4()}",
|
320 |
-
"reset_rate_limits": False,
|
321 |
-
"suggestions": [],
|
322 |
-
"timezone_offset_min": -480,
|
323 |
-
"variant_purpose": "comparison_implicit",
|
324 |
-
"websocket_request_id": f"{uuid.uuid4()}",
|
325 |
-
}
|
326 |
-
if self.conversation_id:
|
327 |
-
self.chat_request['conversation_id'] = self.conversation_id
|
328 |
-
return self.chat_request
|
329 |
-
|
330 |
-
async def send_conversation(self):
|
331 |
-
try:
|
332 |
-
url = f'{self.base_url}/conversation'
|
333 |
-
stream = self.data.get("stream", False)
|
334 |
-
r = await self.s.post_stream(url, headers=self.chat_headers, json=self.chat_request, timeout=10, stream=True)
|
335 |
-
if r.status_code != 200:
|
336 |
-
rtext = await r.atext()
|
337 |
-
if "application/json" == r.headers.get("Content-Type", ""):
|
338 |
-
detail = json.loads(rtext).get("detail", json.loads(rtext))
|
339 |
-
if r.status_code == 429:
|
340 |
-
check_is_limit(detail, token=self.req_token, model=self.req_model)
|
341 |
-
else:
|
342 |
-
if "cf-spinner-please-wait" in rtext:
|
343 |
-
# logger.error(f"Failed to send conversation: cf-spinner-please-wait")
|
344 |
-
raise HTTPException(status_code=r.status_code, detail="cf-spinner-please-wait")
|
345 |
-
if r.status_code == 429:
|
346 |
-
# logger.error(f"Failed to send conversation: rate-limit")
|
347 |
-
raise HTTPException(status_code=r.status_code, detail="rate-limit")
|
348 |
-
detail = r.text[:100]
|
349 |
-
# logger.error(f"Failed to send conversation: {detail}")
|
350 |
-
raise HTTPException(status_code=r.status_code, detail=detail)
|
351 |
-
|
352 |
-
content_type = r.headers.get("Content-Type", "")
|
353 |
-
if "text/event-stream" in content_type:
|
354 |
-
res, start = await head_process_response(r.aiter_lines())
|
355 |
-
if not start:
|
356 |
-
raise HTTPException(
|
357 |
-
status_code=403,
|
358 |
-
detail="Our systems have detected unusual activity coming from your system. Please try again later.",
|
359 |
-
)
|
360 |
-
if stream:
|
361 |
-
return stream_response(self, res, self.resp_model, self.max_tokens)
|
362 |
-
else:
|
363 |
-
return await format_not_stream_response(
|
364 |
-
stream_response(self, res, self.resp_model, self.max_tokens),
|
365 |
-
self.prompt_tokens,
|
366 |
-
self.max_tokens,
|
367 |
-
self.resp_model,
|
368 |
-
)
|
369 |
-
elif "application/json" in content_type:
|
370 |
-
rtext = await r.atext()
|
371 |
-
resp = json.loads(rtext)
|
372 |
-
raise HTTPException(status_code=r.status_code, detail=resp)
|
373 |
-
else:
|
374 |
-
rtext = await r.atext()
|
375 |
-
raise HTTPException(status_code=r.status_code, detail=rtext)
|
376 |
-
except HTTPException as e:
|
377 |
-
raise HTTPException(status_code=e.status_code, detail=e.detail)
|
378 |
-
except Exception as e:
|
379 |
-
raise HTTPException(status_code=500, detail=str(e))
|
380 |
-
|
381 |
-
async def get_download_url(self, file_id):
|
382 |
-
url = f"{self.base_url}/files/{file_id}/download"
|
383 |
-
headers = self.base_headers.copy()
|
384 |
-
try:
|
385 |
-
r = await self.s.get(url, headers=headers, timeout=5)
|
386 |
-
if r.status_code == 200:
|
387 |
-
download_url = r.json().get('download_url')
|
388 |
-
return download_url
|
389 |
-
else:
|
390 |
-
return ""
|
391 |
-
except HTTPException:
|
392 |
-
return ""
|
393 |
-
|
394 |
-
async def get_download_url_from_upload(self, file_id):
|
395 |
-
url = f"{self.base_url}/files/{file_id}/uploaded"
|
396 |
-
headers = self.base_headers.copy()
|
397 |
-
try:
|
398 |
-
r = await self.s.post(url, headers=headers, json={}, timeout=5)
|
399 |
-
if r.status_code == 200:
|
400 |
-
download_url = r.json().get('download_url')
|
401 |
-
return download_url
|
402 |
-
else:
|
403 |
-
return ""
|
404 |
-
except HTTPException:
|
405 |
-
return ""
|
406 |
-
|
407 |
-
async def get_upload_url(self, file_name, file_size, use_case="multimodal"):
|
408 |
-
url = f'{self.base_url}/files'
|
409 |
-
headers = self.base_headers.copy()
|
410 |
-
try:
|
411 |
-
r = await self.s.post(
|
412 |
-
url,
|
413 |
-
headers=headers,
|
414 |
-
json={"file_name": file_name, "file_size": file_size, "timezone_offset_min": -480, "use_case": use_case},
|
415 |
-
timeout=5,
|
416 |
-
)
|
417 |
-
if r.status_code == 200:
|
418 |
-
res = r.json()
|
419 |
-
file_id = res.get('file_id')
|
420 |
-
upload_url = res.get('upload_url')
|
421 |
-
logger.info(f"file_id: {file_id}, upload_url: {upload_url}")
|
422 |
-
return file_id, upload_url
|
423 |
-
else:
|
424 |
-
return "", ""
|
425 |
-
except HTTPException:
|
426 |
-
return "", ""
|
427 |
-
|
428 |
-
async def upload(self, upload_url, file_content, mime_type):
|
429 |
-
headers = self.base_headers.copy()
|
430 |
-
headers.update(
|
431 |
-
{
|
432 |
-
'accept': 'application/json, text/plain, */*',
|
433 |
-
'content-type': mime_type,
|
434 |
-
'x-ms-blob-type': 'BlockBlob',
|
435 |
-
'x-ms-version': '2020-04-08',
|
436 |
-
}
|
437 |
-
)
|
438 |
-
headers.pop('Authorization', None)
|
439 |
-
try:
|
440 |
-
r = await self.s.put(upload_url, headers=headers, data=file_content)
|
441 |
-
if r.status_code == 201:
|
442 |
-
return True
|
443 |
-
return False
|
444 |
-
except Exception:
|
445 |
-
return False
|
446 |
-
|
447 |
-
async def upload_file(self, file_content, mime_type):
|
448 |
-
if not file_content or not mime_type:
|
449 |
-
return None
|
450 |
-
|
451 |
-
width, height = None, None
|
452 |
-
if mime_type.startswith("image/"):
|
453 |
-
try:
|
454 |
-
width, height = await get_image_size(file_content)
|
455 |
-
except Exception as e:
|
456 |
-
logger.error(f"Error image mime_type, change to text/plain: {e}")
|
457 |
-
mime_type = 'text/plain'
|
458 |
-
file_size = len(file_content)
|
459 |
-
file_extension = await get_file_extension(mime_type)
|
460 |
-
file_name = f"{uuid.uuid4()}{file_extension}"
|
461 |
-
use_case = await determine_file_use_case(mime_type)
|
462 |
-
|
463 |
-
file_id, upload_url = await self.get_upload_url(file_name, file_size, use_case)
|
464 |
-
if file_id and upload_url:
|
465 |
-
if await self.upload(upload_url, file_content, mime_type):
|
466 |
-
download_url = await self.get_download_url_from_upload(file_id)
|
467 |
-
if download_url:
|
468 |
-
file_meta = {
|
469 |
-
"file_id": file_id,
|
470 |
-
"file_name": file_name,
|
471 |
-
"size_bytes": file_size,
|
472 |
-
"mime_type": mime_type,
|
473 |
-
"width": width,
|
474 |
-
"height": height,
|
475 |
-
"use_case": use_case,
|
476 |
-
}
|
477 |
-
logger.info(f"File_meta: {file_meta}")
|
478 |
-
return file_meta
|
479 |
-
else:
|
480 |
-
logger.error("Failed to get download url")
|
481 |
-
else:
|
482 |
-
logger.error("Failed to upload file")
|
483 |
-
else:
|
484 |
-
logger.error("Failed to get upload url")
|
485 |
-
|
486 |
-
async def check_upload(self, file_id):
|
487 |
-
url = f'{self.base_url}/files/{file_id}'
|
488 |
-
headers = self.base_headers.copy()
|
489 |
-
try:
|
490 |
-
for i in range(30):
|
491 |
-
r = await self.s.get(url, headers=headers, timeout=5)
|
492 |
-
if r.status_code == 200:
|
493 |
-
res = r.json()
|
494 |
-
retrieval_index_status = res.get('retrieval_index_status', '')
|
495 |
-
if retrieval_index_status == "success":
|
496 |
-
break
|
497 |
-
await asyncio.sleep(1)
|
498 |
-
return True
|
499 |
-
except HTTPException:
|
500 |
-
return False
|
501 |
-
|
502 |
-
async def get_response_file_url(self, conversation_id, message_id, sandbox_path):
|
503 |
-
try:
|
504 |
-
url = f"{self.base_url}/conversation/{conversation_id}/interpreter/download"
|
505 |
-
params = {"message_id": message_id, "sandbox_path": sandbox_path}
|
506 |
-
headers = self.base_headers.copy()
|
507 |
-
r = await self.s.get(url, headers=headers, params=params, timeout=10)
|
508 |
-
if r.status_code == 200:
|
509 |
-
return r.json().get("download_url")
|
510 |
-
else:
|
511 |
-
return None
|
512 |
-
except Exception:
|
513 |
-
logger.info("Failed to get response file url")
|
514 |
-
return None
|
515 |
-
|
516 |
-
async def close_client(self):
|
517 |
-
if self.s:
|
518 |
-
await self.s.close()
|
519 |
-
if self.ws:
|
520 |
-
await self.ws.close()
|
521 |
-
del self.ws
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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