OpenaiChat.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. from __future__ import annotations
  2. import re
  3. import asyncio
  4. import uuid
  5. import json
  6. import base64
  7. import time
  8. import requests
  9. import random
  10. from copy import copy
  11. try:
  12. import nodriver
  13. from nodriver.cdp.network import get_response_body
  14. has_nodriver = True
  15. except ImportError:
  16. has_nodriver = False
  17. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  18. from ...typing import AsyncResult, Messages, Cookies, ImagesType, AsyncIterator
  19. from ...requests.raise_for_status import raise_for_status
  20. from ...requests import StreamSession
  21. from ...requests import get_nodriver
  22. from ...image import ImageResponse, ImageRequest, to_image, to_bytes, is_accepted_format
  23. from ...errors import MissingAuthError, NoValidHarFileError
  24. from ...providers.response import BaseConversation, FinishReason, SynthesizeData
  25. from ..helper import format_cookies
  26. from ..openai.har_file import get_request_config
  27. from ..openai.har_file import RequestConfig, arkReq, arkose_url, start_url, conversation_url, backend_url, backend_anon_url
  28. from ..openai.proofofwork import generate_proof_token
  29. from ..openai.new import get_requirements_token, get_config
  30. from ... import debug
  31. DEFAULT_HEADERS = {
  32. "accept": "*/*",
  33. "accept-encoding": "gzip, deflate, br, zstd",
  34. 'accept-language': 'en-US,en;q=0.8',
  35. "referer": "https://chatgpt.com/",
  36. "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
  37. "sec-ch-ua-mobile": "?0",
  38. "sec-ch-ua-platform": "\"Windows\"",
  39. "sec-fetch-dest": "empty",
  40. "sec-fetch-mode": "cors",
  41. "sec-fetch-site": "same-origin",
  42. "sec-gpc": "1",
  43. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
  44. }
  45. INIT_HEADERS = {
  46. 'accept': '*/*',
  47. 'accept-language': 'en-US,en;q=0.8',
  48. 'cache-control': 'no-cache',
  49. 'pragma': 'no-cache',
  50. 'priority': 'u=0, i',
  51. "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
  52. 'sec-ch-ua-arch': '"arm"',
  53. 'sec-ch-ua-bitness': '"64"',
  54. 'sec-ch-ua-mobile': '?0',
  55. 'sec-ch-ua-model': '""',
  56. "sec-ch-ua-platform": "\"Windows\"",
  57. 'sec-ch-ua-platform-version': '"14.4.0"',
  58. 'sec-fetch-dest': 'document',
  59. 'sec-fetch-mode': 'navigate',
  60. 'sec-fetch-site': 'none',
  61. 'sec-fetch-user': '?1',
  62. 'upgrade-insecure-requests': '1',
  63. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
  64. }
  65. UPLOAD_HEADERS = {
  66. "accept": "application/json, text/plain, */*",
  67. 'accept-language': 'en-US,en;q=0.8',
  68. "referer": "https://chatgpt.com/",
  69. "priority": "u=1, i",
  70. "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
  71. "sec-ch-ua-mobile": "?0",
  72. 'sec-ch-ua-platform': '"macOS"',
  73. "sec-fetch-dest": "empty",
  74. "sec-fetch-mode": "cors",
  75. "sec-fetch-site": "cross-site",
  76. "x-ms-blob-type": "BlockBlob",
  77. "x-ms-version": "2020-04-08",
  78. "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
  79. }
  80. class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
  81. """A class for creating and managing conversations with OpenAI chat service"""
  82. label = "OpenAI ChatGPT"
  83. url = "https://chatgpt.com"
  84. working = True
  85. supports_gpt_4 = True
  86. supports_message_history = True
  87. supports_system_message = True
  88. default_model = "auto"
  89. fallback_models = [default_model, "gpt-4", "gpt-4o", "gpt-4o-mini", "gpt-4o-canmore", "o1", "o1-preview", "o1-mini"]
  90. vision_models = fallback_models
  91. synthesize_content_type = "audio/mpeg"
  92. _api_key: str = None
  93. _headers: dict = None
  94. _cookies: Cookies = None
  95. _expires: int = None
  96. @classmethod
  97. def get_models(cls):
  98. if not cls.models:
  99. try:
  100. response = requests.get(f"{cls.url}/backend-anon/models")
  101. response.raise_for_status()
  102. data = response.json()
  103. cls.models = [model.get("slug") for model in data.get("models")]
  104. except Exception:
  105. cls.models = cls.fallback_models
  106. return cls.models
  107. @classmethod
  108. async def upload_images(
  109. cls,
  110. session: StreamSession,
  111. headers: dict,
  112. images: ImagesType,
  113. ) -> ImageRequest:
  114. """
  115. Upload an image to the service and get the download URL
  116. Args:
  117. session: The StreamSession object to use for requests
  118. headers: The headers to include in the requests
  119. images: The images to upload, either a PIL Image object or a bytes object
  120. Returns:
  121. An ImageRequest object that contains the download URL, file name, and other data
  122. """
  123. async def upload_image(image, image_name):
  124. # Convert the image to a PIL Image object and get the extension
  125. data_bytes = to_bytes(image)
  126. image = to_image(data_bytes)
  127. extension = image.format.lower()
  128. data = {
  129. "file_name": "" if image_name is None else image_name,
  130. "file_size": len(data_bytes),
  131. "use_case": "multimodal"
  132. }
  133. # Post the image data to the service and get the image data
  134. async with session.post(f"{cls.url}/backend-api/files", json=data, headers=headers) as response:
  135. cls._update_request_args(session)
  136. await raise_for_status(response, "Create file failed")
  137. image_data = {
  138. **data,
  139. **await response.json(),
  140. "mime_type": is_accepted_format(data_bytes),
  141. "extension": extension,
  142. "height": image.height,
  143. "width": image.width
  144. }
  145. # Put the image bytes to the upload URL and check the status
  146. await asyncio.sleep(1)
  147. async with session.put(
  148. image_data["upload_url"],
  149. data=data_bytes,
  150. headers={
  151. **UPLOAD_HEADERS,
  152. "Content-Type": image_data["mime_type"],
  153. "x-ms-blob-type": "BlockBlob",
  154. "x-ms-version": "2020-04-08",
  155. "Origin": "https://chatgpt.com",
  156. }
  157. ) as response:
  158. await raise_for_status(response)
  159. # Post the file ID to the service and get the download URL
  160. async with session.post(
  161. f"{cls.url}/backend-api/files/{image_data['file_id']}/uploaded",
  162. json={},
  163. headers=headers
  164. ) as response:
  165. cls._update_request_args(session)
  166. await raise_for_status(response, "Get download url failed")
  167. image_data["download_url"] = (await response.json())["download_url"]
  168. return ImageRequest(image_data)
  169. if not images:
  170. return
  171. return [await upload_image(image, image_name) for image, image_name in images]
  172. @classmethod
  173. def create_messages(cls, messages: Messages, image_requests: ImageRequest = None, system_hints: list = None):
  174. """
  175. Create a list of messages for the user input
  176. Args:
  177. prompt: The user input as a string
  178. image_response: The image response object, if any
  179. Returns:
  180. A list of messages with the user input and the image, if any
  181. """
  182. # Create a message object with the user role and the content
  183. messages = [{
  184. "author": {"role": message["role"]},
  185. "content": {"content_type": "text", "parts": [message["content"]]},
  186. "id": str(uuid.uuid4()),
  187. "create_time": int(time.time()),
  188. "metadata": {"serialization_metadata": {"custom_symbol_offsets": []}, "system_hints": system_hints},
  189. } for message in messages]
  190. # Check if there is an image response
  191. if image_requests:
  192. # Change content in last user message
  193. messages[-1]["content"] = {
  194. "content_type": "multimodal_text",
  195. "parts": [*[{
  196. "asset_pointer": f"file-service://{image_request.get('file_id')}",
  197. "height": image_request.get("height"),
  198. "size_bytes": image_request.get("file_size"),
  199. "width": image_request.get("width"),
  200. }
  201. for image_request in image_requests],
  202. messages[-1]["content"]["parts"][0]]
  203. }
  204. # Add the metadata object with the attachments
  205. messages[-1]["metadata"] = {
  206. "attachments": [{
  207. "height": image_request.get("height"),
  208. "id": image_request.get("file_id"),
  209. "mimeType": image_request.get("mime_type"),
  210. "name": image_request.get("file_name"),
  211. "size": image_request.get("file_size"),
  212. "width": image_request.get("width"),
  213. }
  214. for image_request in image_requests]
  215. }
  216. return messages
  217. @classmethod
  218. async def get_generated_image(cls, session: StreamSession, headers: dict, element: dict, prompt: str = None) -> ImageResponse:
  219. """
  220. Retrieves the image response based on the message content.
  221. This method processes the message content to extract image information and retrieves the
  222. corresponding image from the backend API. It then returns an ImageResponse object containing
  223. the image URL and the prompt used to generate the image.
  224. Args:
  225. session (StreamSession): The StreamSession object used for making HTTP requests.
  226. headers (dict): HTTP headers to be used for the request.
  227. line (dict): A dictionary representing the line of response that contains image information.
  228. Returns:
  229. ImageResponse: An object containing the image URL and the prompt, or None if no image is found.
  230. Raises:
  231. RuntimeError: If there'san error in downloading the image, including issues with the HTTP request or response.
  232. """
  233. try:
  234. prompt = element["metadata"]["dalle"]["prompt"]
  235. file_id = element["asset_pointer"].split("file-service://", 1)[1]
  236. except TypeError:
  237. return
  238. except Exception as e:
  239. raise RuntimeError(f"No Image: {e.__class__.__name__}: {e}")
  240. try:
  241. async with session.get(f"{cls.url}/backend-api/files/{file_id}/download", headers=headers) as response:
  242. cls._update_request_args(session)
  243. await raise_for_status(response)
  244. download_url = (await response.json())["download_url"]
  245. return ImageResponse(download_url, prompt)
  246. except Exception as e:
  247. raise RuntimeError(f"Error in downloading image: {e}")
  248. @classmethod
  249. async def create_async_generator(
  250. cls,
  251. model: str,
  252. messages: Messages,
  253. proxy: str = None,
  254. timeout: int = 180,
  255. cookies: Cookies = None,
  256. auto_continue: bool = False,
  257. history_disabled: bool = False,
  258. action: str = "next",
  259. conversation_id: str = None,
  260. conversation: Conversation = None,
  261. parent_id: str = None,
  262. images: ImagesType = None,
  263. return_conversation: bool = False,
  264. max_retries: int = 3,
  265. web_search: bool = False,
  266. **kwargs
  267. ) -> AsyncResult:
  268. """
  269. Create an asynchronous generator for the conversation.
  270. Args:
  271. model (str): The model name.
  272. messages (Messages): The list of previous messages.
  273. proxy (str): Proxy to use for requests.
  274. timeout (int): Timeout for requests.
  275. api_key (str): Access token for authentication.
  276. cookies (dict): Cookies to use for authentication.
  277. auto_continue (bool): Flag to automatically continue the conversation.
  278. history_disabled (bool): Flag to disable history and training.
  279. action (str): Type of action ('next', 'continue', 'variant').
  280. conversation_id (str): ID of the conversation.
  281. parent_id (str): ID of the parent message.
  282. images (ImagesType): Images to include in the conversation.
  283. return_conversation (bool): Flag to include response fields in the output.
  284. **kwargs: Additional keyword arguments.
  285. Yields:
  286. AsyncResult: Asynchronous results from the generator.
  287. Raises:
  288. RuntimeError: If an error occurs during processing.
  289. """
  290. if cls.needs_auth:
  291. await cls.login(proxy)
  292. async with StreamSession(
  293. proxy=proxy,
  294. impersonate="chrome",
  295. timeout=timeout
  296. ) as session:
  297. image_requests = None
  298. if not cls.needs_auth:
  299. if cls._headers is None:
  300. cls._create_request_args(cookies)
  301. async with session.get(cls.url, headers=INIT_HEADERS) as response:
  302. cls._update_request_args(session)
  303. await raise_for_status(response)
  304. else:
  305. async with session.get(cls.url, headers=cls._headers) as response:
  306. cls._update_request_args(session)
  307. await raise_for_status(response)
  308. try:
  309. image_requests = await cls.upload_images(session, cls._headers, images) if images else None
  310. except Exception as e:
  311. debug.log("OpenaiChat: Upload image failed")
  312. debug.log(f"{e.__class__.__name__}: {e}")
  313. model = cls.get_model(model)
  314. if conversation is None:
  315. conversation = Conversation(conversation_id, str(uuid.uuid4()) if parent_id is None else parent_id)
  316. else:
  317. conversation = copy(conversation)
  318. if cls._api_key is None:
  319. auto_continue = False
  320. conversation.finish_reason = None
  321. while conversation.finish_reason is None:
  322. async with session.post(
  323. f"{cls.url}/backend-anon/sentinel/chat-requirements"
  324. if cls._api_key is None else
  325. f"{cls.url}/backend-api/sentinel/chat-requirements",
  326. json={"p": get_requirements_token(RequestConfig.proof_token) if RequestConfig.proof_token else None},
  327. headers=cls._headers
  328. ) as response:
  329. cls._update_request_args(session)
  330. await raise_for_status(response)
  331. chat_requirements = await response.json()
  332. need_turnstile = chat_requirements.get("turnstile", {}).get("required", False)
  333. need_arkose = chat_requirements.get("arkose", {}).get("required", False)
  334. chat_token = chat_requirements.get("token")
  335. if need_arkose and RequestConfig.arkose_token is None:
  336. await get_request_config(proxy)
  337. cls._create_request_args(RequestConfig,cookies, RequestConfig.headers)
  338. cls._set_api_key(RequestConfig.access_token)
  339. if RequestConfig.arkose_token is None:
  340. raise MissingAuthError("No arkose token found in .har file")
  341. if "proofofwork" in chat_requirements:
  342. if RequestConfig.proof_token is None:
  343. RequestConfig.proof_token = get_config(cls._headers.get("user-agent"))
  344. proofofwork = generate_proof_token(
  345. **chat_requirements["proofofwork"],
  346. user_agent=cls._headers.get("user-agent"),
  347. proof_token=RequestConfig.proof_token
  348. )
  349. [debug.log(text) for text in (
  350. f"Arkose: {'False' if not need_arkose else RequestConfig.arkose_token[:12]+'...'}",
  351. f"Proofofwork: {'False' if proofofwork is None else proofofwork[:12]+'...'}",
  352. f"AccessToken: {'False' if cls._api_key is None else cls._api_key[:12]+'...'}",
  353. )]
  354. data = {
  355. "action": action,
  356. "messages": None,
  357. "parent_message_id": conversation.message_id,
  358. "model": model,
  359. "timezone_offset_min":-60,
  360. "timezone":"Europe/Berlin",
  361. "history_and_training_disabled": history_disabled and not auto_continue and not return_conversation or not cls.needs_auth,
  362. "conversation_mode":{"kind":"primary_assistant","plugin_ids":None},
  363. "force_paragen":False,
  364. "force_paragen_model_slug":"",
  365. "force_rate_limit":False,
  366. "reset_rate_limits":False,
  367. "websocket_request_id": str(uuid.uuid4()),
  368. "system_hints": ["search"] if web_search else None,
  369. "supported_encodings":["v1"],
  370. "conversation_origin":None,
  371. "client_contextual_info":{"is_dark_mode":False,"time_since_loaded":random.randint(20, 500),"page_height":578,"page_width":1850,"pixel_ratio":1,"screen_height":1080,"screen_width":1920},
  372. "paragen_stream_type_override":None,
  373. "paragen_cot_summary_display_override":"allow",
  374. "supports_buffering":True
  375. }
  376. if conversation.conversation_id is not None:
  377. data["conversation_id"] = conversation.conversation_id
  378. debug.log(f"OpenaiChat: Use conversation: {conversation.conversation_id}")
  379. if action != "continue":
  380. messages = messages if conversation_id is None else [messages[-1]]
  381. data["messages"] = cls.create_messages(messages, image_requests, ["search"] if web_search else None)
  382. headers = {
  383. **cls._headers,
  384. "accept": "text/event-stream",
  385. "content-type": "application/json",
  386. "openai-sentinel-chat-requirements-token": chat_token,
  387. }
  388. if RequestConfig.arkose_token:
  389. headers["openai-sentinel-arkose-token"] = RequestConfig.arkose_token
  390. if proofofwork is not None:
  391. headers["openai-sentinel-proof-token"] = proofofwork
  392. if need_turnstile and RequestConfig.turnstile_token is not None:
  393. headers['openai-sentinel-turnstile-token'] = RequestConfig.turnstile_token
  394. async with session.post(
  395. f"{cls.url}/backend-anon/conversation"
  396. if cls._api_key is None else
  397. f"{cls.url}/backend-api/conversation",
  398. json=data,
  399. headers=headers
  400. ) as response:
  401. cls._update_request_args(session)
  402. if response.status == 403 and max_retries > 0:
  403. max_retries -= 1
  404. debug.log(f"Retry: Error {response.status}: {await response.text()}")
  405. await asyncio.sleep(5)
  406. continue
  407. await raise_for_status(response)
  408. if return_conversation:
  409. yield conversation
  410. async for line in response.iter_lines():
  411. async for chunk in cls.iter_messages_line(session, line, conversation):
  412. yield chunk
  413. if not history_disabled and RequestConfig.access_token is not None:
  414. yield SynthesizeData(cls.__name__, {
  415. "conversation_id": conversation.conversation_id,
  416. "message_id": conversation.message_id,
  417. "voice": "maple",
  418. })
  419. if auto_continue and conversation.finish_reason == "max_tokens":
  420. conversation.finish_reason = None
  421. action = "continue"
  422. await asyncio.sleep(5)
  423. else:
  424. break
  425. yield FinishReason(conversation.finish_reason)
  426. @classmethod
  427. async def iter_messages_line(cls, session: StreamSession, line: bytes, fields: Conversation) -> AsyncIterator:
  428. if not line.startswith(b"data: "):
  429. return
  430. elif line.startswith(b"data: [DONE]"):
  431. if fields.finish_reason is None:
  432. fields.finish_reason = "error"
  433. return
  434. try:
  435. line = json.loads(line[6:])
  436. except:
  437. return
  438. if isinstance(line, dict) and "v" in line:
  439. v = line.get("v")
  440. if isinstance(v, str) and fields.is_recipient:
  441. if "p" not in line or line.get("p") == "/message/content/parts/0":
  442. yield v
  443. elif isinstance(v, list) and fields.is_recipient:
  444. for m in v:
  445. if m.get("p") == "/message/content/parts/0":
  446. yield m.get("v")
  447. elif m.get("p") == "/message/metadata":
  448. fields.finish_reason = m.get("v", {}).get("finish_details", {}).get("type")
  449. break
  450. elif isinstance(v, dict):
  451. if fields.conversation_id is None:
  452. fields.conversation_id = v.get("conversation_id")
  453. debug.log(f"OpenaiChat: New conversation: {fields.conversation_id}")
  454. m = v.get("message", {})
  455. fields.is_recipient = m.get("recipient", "all") == "all"
  456. if fields.is_recipient:
  457. c = m.get("content", {})
  458. if c.get("content_type") == "multimodal_text":
  459. generated_images = []
  460. for element in c.get("parts"):
  461. if isinstance(element, dict) and element.get("content_type") == "image_asset_pointer":
  462. image = cls.get_generated_image(session, cls._headers, element)
  463. generated_images.append(image)
  464. for image_response in await asyncio.gather(*generated_images):
  465. if image_response is not None:
  466. yield image_response
  467. if m.get("author", {}).get("role") == "assistant":
  468. fields.message_id = v.get("message", {}).get("id")
  469. return
  470. if "error" in line and line.get("error"):
  471. raise RuntimeError(line.get("error"))
  472. @classmethod
  473. async def synthesize(cls, params: dict) -> AsyncIterator[bytes]:
  474. await cls.login()
  475. async with StreamSession(
  476. impersonate="chrome",
  477. timeout=900
  478. ) as session:
  479. async with session.get(
  480. f"{cls.url}/backend-api/synthesize",
  481. params=params,
  482. headers=cls._headers
  483. ) as response:
  484. await raise_for_status(response)
  485. async for chunk in response.iter_content():
  486. yield chunk
  487. @classmethod
  488. async def login(cls, proxy: str = None):
  489. if cls._expires is not None and cls._expires < time.time():
  490. cls._headers = cls._api_key = None
  491. try:
  492. await get_request_config(proxy)
  493. cls._create_request_args(RequestConfig.cookies, RequestConfig.headers)
  494. cls._set_api_key(RequestConfig.access_token)
  495. except NoValidHarFileError:
  496. if has_nodriver:
  497. if RequestConfig.access_token is None:
  498. await cls.nodriver_auth(proxy)
  499. else:
  500. raise
  501. @classmethod
  502. async def nodriver_auth(cls, proxy: str = None):
  503. browser = await get_nodriver(proxy=proxy, user_data_dir="chatgpt")
  504. page = browser.main_tab
  505. def on_request(event: nodriver.cdp.network.RequestWillBeSent):
  506. if event.request.url == start_url or event.request.url.startswith(conversation_url):
  507. RequestConfig.headers = event.request.headers
  508. elif event.request.url in (backend_url, backend_anon_url):
  509. if "OpenAI-Sentinel-Proof-Token" in event.request.headers:
  510. RequestConfig.proof_token = json.loads(base64.b64decode(
  511. event.request.headers["OpenAI-Sentinel-Proof-Token"].split("gAAAAAB", 1)[-1].encode()
  512. ).decode())
  513. if "OpenAI-Sentinel-Turnstile-Token" in event.request.headers:
  514. RequestConfig.turnstile_token = event.request.headers["OpenAI-Sentinel-Turnstile-Token"]
  515. if "Authorization" in event.request.headers:
  516. RequestConfig.access_token = event.request.headers["Authorization"].split()[-1]
  517. elif event.request.url == arkose_url:
  518. RequestConfig.arkose_request = arkReq(
  519. arkURL=event.request.url,
  520. arkBx=None,
  521. arkHeader=event.request.headers,
  522. arkBody=event.request.post_data,
  523. userAgent=event.request.headers.get("user-agent")
  524. )
  525. await page.send(nodriver.cdp.network.enable())
  526. page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
  527. page = await browser.get(cls.url)
  528. user_agent = await page.evaluate("window.navigator.userAgent")
  529. await page.select("#prompt-textarea", 240)
  530. while True:
  531. if RequestConfig.access_token:
  532. break
  533. body = await page.evaluate("JSON.stringify(window.__remixContext)")
  534. if body:
  535. match = re.search(r'"accessToken":"(.*?)"', body)
  536. if match:
  537. RequestConfig.access_token = match.group(1)
  538. break
  539. await asyncio.sleep(1)
  540. while True:
  541. if RequestConfig.proof_token:
  542. break
  543. await asyncio.sleep(1)
  544. RequestConfig.data_build = await page.evaluate("document.documentElement.getAttribute('data-build')")
  545. for c in await page.send(nodriver.cdp.network.get_cookies([cls.url])):
  546. RequestConfig.cookies[c.name] = c.value
  547. await page.close()
  548. cls._create_request_args(RequestConfig.cookies, RequestConfig.headers, user_agent=user_agent)
  549. cls._set_api_key(RequestConfig.access_token)
  550. @staticmethod
  551. def get_default_headers() -> dict:
  552. return {
  553. **DEFAULT_HEADERS,
  554. "content-type": "application/json",
  555. }
  556. @classmethod
  557. def _create_request_args(cls, cookies: Cookies = None, headers: dict = None, user_agent: str = None):
  558. cls._headers = cls.get_default_headers() if headers is None else headers
  559. if user_agent is not None:
  560. cls._headers["user-agent"] = user_agent
  561. cls._cookies = {} if cookies is None else cookies
  562. cls._update_cookie_header()
  563. @classmethod
  564. def _update_request_args(cls, session: StreamSession):
  565. for c in session.cookie_jar if hasattr(session, "cookie_jar") else session.cookies.jar:
  566. cls._cookies[c.key if hasattr(c, "key") else c.name] = c.value
  567. cls._update_cookie_header()
  568. @classmethod
  569. def _set_api_key(cls, api_key: str):
  570. cls._api_key = api_key
  571. cls._expires = int(time.time()) + 60 * 60 * 4
  572. if api_key:
  573. cls._headers["authorization"] = f"Bearer {api_key}"
  574. @classmethod
  575. def _update_cookie_header(cls):
  576. if cls._cookies:
  577. cls._headers["cookie"] = format_cookies(cls._cookies)
  578. class Conversation(BaseConversation):
  579. """
  580. Class to encapsulate response fields.
  581. """
  582. def __init__(self, conversation_id: str = None, message_id: str = None, finish_reason: str = None):
  583. self.conversation_id = conversation_id
  584. self.message_id = message_id
  585. self.finish_reason = finish_reason
  586. self.is_recipient = False