OpenaiChat.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. from copy import copy
  10. try:
  11. import nodriver
  12. from nodriver.cdp.network import get_response_body
  13. has_nodriver = True
  14. except ImportError:
  15. has_nodriver = False
  16. try:
  17. from platformdirs import user_config_dir
  18. has_platformdirs = True
  19. except ImportError:
  20. has_platformdirs = False
  21. from ..base_provider import AsyncGeneratorProvider, ProviderModelMixin
  22. from ...typing import AsyncResult, Messages, Cookies, ImageType, AsyncIterator
  23. from ...requests.raise_for_status import raise_for_status
  24. from ...requests.aiohttp import StreamSession
  25. from ...image import ImageResponse, ImageRequest, to_image, to_bytes, is_accepted_format
  26. from ...errors import MissingAuthError, ResponseError
  27. from ...providers.response import BaseConversation, FinishReason, SynthesizeData
  28. from ..helper import format_cookies
  29. from ..openai.har_file import get_request_config, NoValidHarFileError
  30. from ..openai.har_file import RequestConfig, arkReq, arkose_url, start_url, conversation_url, backend_url, backend_anon_url
  31. from ..openai.proofofwork import generate_proof_token
  32. from ..openai.new import get_requirements_token
  33. from ... import debug
  34. DEFAULT_HEADERS = {
  35. "accept": "*/*",
  36. "accept-encoding": "gzip, deflate, br, zstd",
  37. "accept-language": "en-US,en;q=0.5",
  38. "referer": "https://chatgpt.com/",
  39. "sec-ch-ua": "\"Brave\";v=\"123\", \"Not:A-Brand\";v=\"8\", \"Chromium\";v=\"123\"",
  40. "sec-ch-ua-mobile": "?0",
  41. "sec-ch-ua-platform": "\"Windows\"",
  42. "sec-fetch-dest": "empty",
  43. "sec-fetch-mode": "cors",
  44. "sec-fetch-site": "same-origin",
  45. "sec-gpc": "1",
  46. "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"
  47. }
  48. class OpenaiChat(AsyncGeneratorProvider, ProviderModelMixin):
  49. """A class for creating and managing conversations with OpenAI chat service"""
  50. label = "OpenAI ChatGPT"
  51. url = "https://chatgpt.com"
  52. working = True
  53. needs_auth = True
  54. supports_gpt_4 = True
  55. supports_message_history = True
  56. supports_system_message = True
  57. default_model = "auto"
  58. default_vision_model = "gpt-4o"
  59. fallback_models = ["auto", "gpt-4", "gpt-4o", "gpt-4o-mini", "gpt-4o-canmore", "o1-preview", "o1-mini"]
  60. vision_models = fallback_models
  61. image_models = fallback_models
  62. _api_key: str = None
  63. _headers: dict = None
  64. _cookies: Cookies = None
  65. _expires: int = None
  66. @classmethod
  67. def get_models(cls):
  68. if not cls.models:
  69. try:
  70. response = requests.get(f"{cls.url}/backend-anon/models")
  71. response.raise_for_status()
  72. data = response.json()
  73. cls.models = [model.get("slug") for model in data.get("models")]
  74. except Exception:
  75. cls.models = cls.fallback_models
  76. return cls.models
  77. @classmethod
  78. async def create(
  79. cls,
  80. prompt: str = None,
  81. model: str = "",
  82. messages: Messages = [],
  83. action: str = "next",
  84. **kwargs
  85. ) -> Response:
  86. """
  87. Create a new conversation or continue an existing one
  88. Args:
  89. prompt: The user input to start or continue the conversation
  90. model: The name of the model to use for generating responses
  91. messages: The list of previous messages in the conversation
  92. history_disabled: A flag indicating if the history and training should be disabled
  93. action: The type of action to perform, either "next", "continue", or "variant"
  94. conversation_id: The ID of the existing conversation, if any
  95. parent_id: The ID of the parent message, if any
  96. image: The image to include in the user input, if any
  97. **kwargs: Additional keyword arguments to pass to the generator
  98. Returns:
  99. A Response object that contains the generator, action, messages, and options
  100. """
  101. # Add the user input to the messages list
  102. if prompt is not None:
  103. messages.append({
  104. "role": "user",
  105. "content": prompt
  106. })
  107. generator = cls.create_async_generator(
  108. model,
  109. messages,
  110. return_conversation=True,
  111. **kwargs
  112. )
  113. return Response(
  114. generator,
  115. action,
  116. messages,
  117. kwargs
  118. )
  119. @classmethod
  120. async def upload_image(
  121. cls,
  122. session: StreamSession,
  123. headers: dict,
  124. image: ImageType,
  125. image_name: str = None
  126. ) -> ImageRequest:
  127. """
  128. Upload an image to the service and get the download URL
  129. Args:
  130. session: The StreamSession object to use for requests
  131. headers: The headers to include in the requests
  132. image: The image to upload, either a PIL Image object or a bytes object
  133. Returns:
  134. An ImageRequest object that contains the download URL, file name, and other data
  135. """
  136. # Convert the image to a PIL Image object and get the extension
  137. data_bytes = to_bytes(image)
  138. image = to_image(data_bytes)
  139. extension = image.format.lower()
  140. data = {
  141. "file_name": "" if image_name is None else image_name,
  142. "file_size": len(data_bytes),
  143. "use_case": "multimodal"
  144. }
  145. # Post the image data to the service and get the image data
  146. async with session.post(f"{cls.url}/backend-api/files", json=data, headers=headers) as response:
  147. cls._update_request_args(session)
  148. await raise_for_status(response)
  149. image_data = {
  150. **data,
  151. **await response.json(),
  152. "mime_type": is_accepted_format(data_bytes),
  153. "extension": extension,
  154. "height": image.height,
  155. "width": image.width
  156. }
  157. # Put the image bytes to the upload URL and check the status
  158. async with session.put(
  159. image_data["upload_url"],
  160. data=data_bytes,
  161. headers={
  162. "Content-Type": image_data["mime_type"],
  163. "x-ms-blob-type": "BlockBlob"
  164. }
  165. ) as response:
  166. await raise_for_status(response)
  167. # Post the file ID to the service and get the download URL
  168. async with session.post(
  169. f"{cls.url}/backend-api/files/{image_data['file_id']}/uploaded",
  170. json={},
  171. headers=headers
  172. ) as response:
  173. cls._update_request_args(session)
  174. await raise_for_status(response)
  175. image_data["download_url"] = (await response.json())["download_url"]
  176. return ImageRequest(image_data)
  177. @classmethod
  178. async def get_default_model(cls, session: StreamSession, headers: dict):
  179. """
  180. Get the default model name from the service
  181. Args:
  182. session: The StreamSession object to use for requests
  183. headers: The headers to include in the requests
  184. Returns:
  185. The default model name as a string
  186. """
  187. if not cls.default_model:
  188. url = f"{cls.url}/backend-anon/models" if cls._api_key is None else f"{cls.url}/backend-api/models"
  189. async with session.get(url, headers=headers) as response:
  190. cls._update_request_args(session)
  191. if response.status == 401:
  192. raise MissingAuthError('Add a .har file for OpenaiChat' if cls._api_key is None else "Invalid api key")
  193. await raise_for_status(response)
  194. data = await response.json()
  195. if "categories" in data:
  196. cls.default_model = data["categories"][-1]["default_model"]
  197. return cls.default_model
  198. raise ResponseError(data)
  199. return cls.default_model
  200. @classmethod
  201. def create_messages(cls, messages: Messages, image_request: ImageRequest = None):
  202. """
  203. Create a list of messages for the user input
  204. Args:
  205. prompt: The user input as a string
  206. image_response: The image response object, if any
  207. Returns:
  208. A list of messages with the user input and the image, if any
  209. """
  210. # Create a message object with the user role and the content
  211. messages = [{
  212. "author": {"role": message["role"]},
  213. "content": {"content_type": "text", "parts": [message["content"]]},
  214. "id": str(uuid.uuid4()),
  215. "create_time": int(time.time()),
  216. "id": str(uuid.uuid4()),
  217. "metadata": {"serialization_metadata": {"custom_symbol_offsets": []}}
  218. } for message in messages]
  219. # Check if there is an image response
  220. if image_request is not None:
  221. # Change content in last user message
  222. messages[-1]["content"] = {
  223. "content_type": "multimodal_text",
  224. "parts": [{
  225. "asset_pointer": f"file-service://{image_request.get('file_id')}",
  226. "height": image_request.get("height"),
  227. "size_bytes": image_request.get("file_size"),
  228. "width": image_request.get("width"),
  229. }, messages[-1]["content"]["parts"][0]]
  230. }
  231. # Add the metadata object with the attachments
  232. messages[-1]["metadata"] = {
  233. "attachments": [{
  234. "height": image_request.get("height"),
  235. "id": image_request.get("file_id"),
  236. "mimeType": image_request.get("mime_type"),
  237. "name": image_request.get("file_name"),
  238. "size": image_request.get("file_size"),
  239. "width": image_request.get("width"),
  240. }]
  241. }
  242. return messages
  243. @classmethod
  244. async def get_generated_image(cls, session: StreamSession, headers: dict, element: dict) -> ImageResponse:
  245. """
  246. Retrieves the image response based on the message content.
  247. This method processes the message content to extract image information and retrieves the
  248. corresponding image from the backend API. It then returns an ImageResponse object containing
  249. the image URL and the prompt used to generate the image.
  250. Args:
  251. session (StreamSession): The StreamSession object used for making HTTP requests.
  252. headers (dict): HTTP headers to be used for the request.
  253. line (dict): A dictionary representing the line of response that contains image information.
  254. Returns:
  255. ImageResponse: An object containing the image URL and the prompt, or None if no image is found.
  256. Raises:
  257. RuntimeError: If there'san error in downloading the image, including issues with the HTTP request or response.
  258. """
  259. try:
  260. prompt = element["metadata"]["dalle"]["prompt"]
  261. file_id = element["asset_pointer"].split("file-service://", 1)[1]
  262. except Exception as e:
  263. raise RuntimeError(f"No Image: {e.__class__.__name__}: {e}")
  264. try:
  265. async with session.get(f"{cls.url}/backend-api/files/{file_id}/download", headers=headers) as response:
  266. cls._update_request_args(session)
  267. await raise_for_status(response)
  268. download_url = (await response.json())["download_url"]
  269. return ImageResponse(download_url, prompt)
  270. except Exception as e:
  271. raise RuntimeError(f"Error in downloading image: {e}")
  272. @classmethod
  273. async def delete_conversation(cls, session: StreamSession, headers: dict, conversation_id: str):
  274. """
  275. Deletes a conversation by setting its visibility to False.
  276. This method sends an HTTP PATCH request to update the visibility of a conversation.
  277. It's used to effectively delete a conversation from being accessed or displayed in the future.
  278. Args:
  279. session (StreamSession): The StreamSession object used for making HTTP requests.
  280. headers (dict): HTTP headers to be used for the request.
  281. conversation_id (str): The unique identifier of the conversation to be deleted.
  282. Raises:
  283. HTTPError: If the HTTP request fails or returns an unsuccessful status code.
  284. """
  285. async with session.patch(
  286. f"{cls.url}/backend-api/conversation/{conversation_id}",
  287. json={"is_visible": False},
  288. headers=headers
  289. ) as response:
  290. cls._update_request_args(session)
  291. ...
  292. @classmethod
  293. async def create_async_generator(
  294. cls,
  295. model: str,
  296. messages: Messages,
  297. proxy: str = None,
  298. timeout: int = 180,
  299. api_key: str = None,
  300. cookies: Cookies = None,
  301. auto_continue: bool = False,
  302. history_disabled: bool = False,
  303. action: str = "next",
  304. conversation_id: str = None,
  305. conversation: Conversation = None,
  306. parent_id: str = None,
  307. image: ImageType = None,
  308. image_name: str = None,
  309. return_conversation: bool = False,
  310. max_retries: int = 3,
  311. **kwargs
  312. ) -> AsyncResult:
  313. """
  314. Create an asynchronous generator for the conversation.
  315. Args:
  316. model (str): The model name.
  317. messages (Messages): The list of previous messages.
  318. proxy (str): Proxy to use for requests.
  319. timeout (int): Timeout for requests.
  320. api_key (str): Access token for authentication.
  321. cookies (dict): Cookies to use for authentication.
  322. auto_continue (bool): Flag to automatically continue the conversation.
  323. history_disabled (bool): Flag to disable history and training.
  324. action (str): Type of action ('next', 'continue', 'variant').
  325. conversation_id (str): ID of the conversation.
  326. parent_id (str): ID of the parent message.
  327. image (ImageType): Image to include in the conversation.
  328. return_conversation (bool): Flag to include response fields in the output.
  329. **kwargs: Additional keyword arguments.
  330. Yields:
  331. AsyncResult: Asynchronous results from the generator.
  332. Raises:
  333. RuntimeError: If an error occurs during processing.
  334. """
  335. await cls.login(proxy)
  336. async with StreamSession(
  337. proxy=proxy,
  338. impersonate="chrome",
  339. timeout=timeout
  340. ) as session:
  341. try:
  342. image_request = await cls.upload_image(session, cls._headers, image, image_name) if image else None
  343. except Exception as e:
  344. image_request = None
  345. debug.log("OpenaiChat: Upload image failed")
  346. debug.log(f"{e.__class__.__name__}: {e}")
  347. model = cls.get_model(model)
  348. if conversation is None:
  349. conversation = Conversation(conversation_id, str(uuid.uuid4()) if parent_id is None else parent_id)
  350. else:
  351. conversation = copy(conversation)
  352. if cls._api_key is None:
  353. auto_continue = False
  354. conversation.finish_reason = None
  355. while conversation.finish_reason is None:
  356. async with session.post(
  357. f"{cls.url}/backend-anon/sentinel/chat-requirements"
  358. if cls._api_key is None else
  359. f"{cls.url}/backend-api/sentinel/chat-requirements",
  360. json={"p": get_requirements_token(RequestConfig.proof_token) if RequestConfig.proof_token else None},
  361. headers=cls._headers
  362. ) as response:
  363. cls._update_request_args(session)
  364. await raise_for_status(response)
  365. chat_requirements = await response.json()
  366. need_turnstile = chat_requirements.get("turnstile", {}).get("required", False)
  367. need_arkose = chat_requirements.get("arkose", {}).get("required", False)
  368. chat_token = chat_requirements.get("token")
  369. if need_arkose and RequestConfig.arkose_token is None:
  370. await get_request_config(proxy)
  371. cls._create_request_args(RequestConfig,cookies, RequestConfig.headers)
  372. cls._set_api_key(RequestConfig.access_token)
  373. if RequestConfig.arkose_token is None:
  374. raise MissingAuthError("No arkose token found in .har file")
  375. if "proofofwork" in chat_requirements:
  376. proofofwork = generate_proof_token(
  377. **chat_requirements["proofofwork"],
  378. user_agent=cls._headers.get("user-agent"),
  379. proof_token=RequestConfig.proof_token
  380. )
  381. [debug.log(text) for text in (
  382. f"Arkose: {'False' if not need_arkose else RequestConfig.arkose_token[:12]+'...'}",
  383. f"Proofofwork: {'False' if proofofwork is None else proofofwork[:12]+'...'}",
  384. f"AccessToken: {'False' if cls._api_key is None else cls._api_key[:12]+'...'}",
  385. )]
  386. data = {
  387. "action": action,
  388. "messages": None,
  389. "parent_message_id": conversation.message_id,
  390. "model": model,
  391. "paragen_cot_summary_display_override": "allow",
  392. "history_and_training_disabled": history_disabled and not auto_continue and not return_conversation,
  393. "conversation_mode": {"kind":"primary_assistant"},
  394. "websocket_request_id": str(uuid.uuid4()),
  395. "supported_encodings": ["v1"],
  396. "supports_buffering": True
  397. }
  398. if conversation.conversation_id is not None:
  399. data["conversation_id"] = conversation.conversation_id
  400. debug.log(f"OpenaiChat: Use conversation: {conversation.conversation_id}")
  401. if action != "continue":
  402. messages = messages if conversation_id is None else [messages[-1]]
  403. data["messages"] = cls.create_messages(messages, image_request)
  404. headers = {
  405. **cls._headers,
  406. "accept": "text/event-stream",
  407. "content-type": "application/json",
  408. "openai-sentinel-chat-requirements-token": chat_token,
  409. }
  410. if RequestConfig.arkose_token:
  411. headers["openai-sentinel-arkose-token"] = RequestConfig.arkose_token
  412. if proofofwork is not None:
  413. headers["openai-sentinel-proof-token"] = proofofwork
  414. if need_turnstile and RequestConfig.turnstile_token is not None:
  415. headers['openai-sentinel-turnstile-token'] = RequestConfig.turnstile_token
  416. async with session.post(
  417. f"{cls.url}/backend-anon/conversation"
  418. if cls._api_key is None else
  419. f"{cls.url}/backend-api/conversation",
  420. json=data,
  421. headers=headers
  422. ) as response:
  423. cls._update_request_args(session)
  424. if response.status == 403 and max_retries > 0:
  425. max_retries -= 1
  426. debug.log(f"Retry: Error {response.status}: {await response.text()}")
  427. await asyncio.sleep(5)
  428. continue
  429. await raise_for_status(response)
  430. if return_conversation:
  431. history_disabled = False
  432. yield conversation
  433. async for line in response.iter_lines():
  434. async for chunk in cls.iter_messages_line(session, line, conversation):
  435. yield chunk
  436. if not history_disabled:
  437. yield SynthesizeData(cls.__name__, {
  438. "conversation_id": conversation.conversation_id,
  439. "message_id": conversation.message_id,
  440. "voice": "maple",
  441. })
  442. if auto_continue and conversation.finish_reason == "max_tokens":
  443. conversation.finish_reason = None
  444. action = "continue"
  445. await asyncio.sleep(5)
  446. else:
  447. break
  448. yield FinishReason(conversation.finish_reason)
  449. if history_disabled and auto_continue:
  450. await cls.delete_conversation(session, cls._headers, conversation.conversation_id)
  451. @classmethod
  452. async def iter_messages_chunk(
  453. cls,
  454. messages: AsyncIterator,
  455. session: StreamSession,
  456. fields: Conversation,
  457. ) -> AsyncIterator:
  458. async for message in messages:
  459. async for chunk in cls.iter_messages_line(session, message, fields):
  460. yield chunk
  461. @classmethod
  462. async def iter_messages_line(cls, session: StreamSession, line: bytes, fields: Conversation) -> AsyncIterator:
  463. if not line.startswith(b"data: "):
  464. return
  465. elif line.startswith(b"data: [DONE]"):
  466. if fields.finish_reason is None:
  467. fields.finish_reason = "error"
  468. return
  469. try:
  470. line = json.loads(line[6:])
  471. except:
  472. return
  473. if isinstance(line, dict) and "v" in line:
  474. v = line.get("v")
  475. if isinstance(v, str) and fields.is_recipient:
  476. yield v
  477. elif isinstance(v, list) and fields.is_recipient:
  478. for m in v:
  479. if m.get("p") == "/message/content/parts/0":
  480. yield m.get("v")
  481. elif m.get("p") == "/message/metadata":
  482. fields.finish_reason = m.get("v", {}).get("finish_details", {}).get("type")
  483. break
  484. elif isinstance(v, dict):
  485. if fields.conversation_id is None:
  486. fields.conversation_id = v.get("conversation_id")
  487. debug.log(f"OpenaiChat: New conversation: {fields.conversation_id}")
  488. m = v.get("message", {})
  489. fields.is_recipient = m.get("recipient") == "all"
  490. if fields.is_recipient:
  491. c = m.get("content", {})
  492. if c.get("content_type") == "multimodal_text":
  493. generated_images = []
  494. for element in c.get("parts"):
  495. if isinstance(element, dict) and element.get("content_type") == "image_asset_pointer":
  496. generated_images.append(
  497. cls.get_generated_image(session, cls._headers, element)
  498. )
  499. for image_response in await asyncio.gather(*generated_images):
  500. yield image_response
  501. if m.get("author", {}).get("role") == "assistant":
  502. fields.message_id = v.get("message", {}).get("id")
  503. return
  504. if "error" in line and line.get("error"):
  505. raise RuntimeError(line.get("error"))
  506. @classmethod
  507. async def synthesize(cls, params: dict) -> AsyncIterator[bytes]:
  508. await cls.login()
  509. async with StreamSession(
  510. impersonate="chrome",
  511. timeout=900
  512. ) as session:
  513. async with session.get(
  514. f"{cls.url}/backend-api/synthesize",
  515. params=params,
  516. headers=cls._headers
  517. ) as response:
  518. await raise_for_status(response)
  519. async for chunk in response.iter_content():
  520. yield chunk
  521. @classmethod
  522. async def login(cls, proxy: str = None):
  523. if cls._expires is not None and cls._expires < time.time():
  524. cls._headers = cls._api_key = None
  525. try:
  526. await get_request_config(proxy)
  527. cls._create_request_args(RequestConfig.cookies, RequestConfig.headers)
  528. cls._set_api_key(RequestConfig.access_token)
  529. except NoValidHarFileError:
  530. if has_nodriver:
  531. await cls.nodriver_auth(proxy)
  532. else:
  533. raise
  534. @classmethod
  535. async def nodriver_auth(cls, proxy: str = None):
  536. if has_platformdirs:
  537. user_data_dir = user_config_dir("g4f-nodriver")
  538. else:
  539. user_data_dir = None
  540. debug.log(f"Open nodriver with user_dir: {user_data_dir}")
  541. browser = await nodriver.start(
  542. user_data_dir=user_data_dir,
  543. browser_args=None if proxy is None else [f"--proxy-server={proxy}"],
  544. )
  545. page = browser.main_tab
  546. def on_request(event: nodriver.cdp.network.RequestWillBeSent):
  547. if event.request.url == start_url or event.request.url.startswith(conversation_url):
  548. RequestConfig.access_request_id = event.request_id
  549. RequestConfig.headers = event.request.headers
  550. elif event.request.url in (backend_url, backend_anon_url):
  551. if "OpenAI-Sentinel-Proof-Token" in event.request.headers:
  552. RequestConfig.proof_token = json.loads(base64.b64decode(
  553. event.request.headers["OpenAI-Sentinel-Proof-Token"].split("gAAAAAB", 1)[-1].encode()
  554. ).decode())
  555. if "OpenAI-Sentinel-Turnstile-Token" in event.request.headers:
  556. RequestConfig.turnstile_token = event.request.headers["OpenAI-Sentinel-Turnstile-Token"]
  557. if "Authorization" in event.request.headers:
  558. RequestConfig.access_token = event.request.headers["Authorization"].split()[-1]
  559. elif event.request.url == arkose_url:
  560. RequestConfig.arkose_request = arkReq(
  561. arkURL=event.request.url,
  562. arkBx=None,
  563. arkHeader=event.request.headers,
  564. arkBody=event.request.post_data,
  565. userAgent=event.request.headers.get("user-agent")
  566. )
  567. await page.send(nodriver.cdp.network.enable())
  568. page.add_handler(nodriver.cdp.network.RequestWillBeSent, on_request)
  569. page = await browser.get(cls.url)
  570. try:
  571. if RequestConfig.access_request_id is not None:
  572. body = await page.send(get_response_body(RequestConfig.access_request_id))
  573. if isinstance(body, tuple) and body:
  574. body = body[0]
  575. if body:
  576. match = re.search(r'"accessToken":"(.*?)"', body)
  577. if match:
  578. RequestConfig.access_token = match.group(1)
  579. except KeyError:
  580. pass
  581. for c in await page.send(nodriver.cdp.network.get_cookies([cls.url])):
  582. RequestConfig.cookies[c.name] = c.value
  583. RequestConfig.user_agent = await page.evaluate("window.navigator.userAgent")
  584. await page.select("#prompt-textarea", 240)
  585. while True:
  586. if RequestConfig.proof_token:
  587. break
  588. await asyncio.sleep(1)
  589. await page.close()
  590. cls._create_request_args(RequestConfig.cookies, RequestConfig.headers, user_agent=RequestConfig.user_agent)
  591. cls._set_api_key(RequestConfig.access_token)
  592. @staticmethod
  593. def get_default_headers() -> dict:
  594. return {
  595. **DEFAULT_HEADERS,
  596. "content-type": "application/json",
  597. }
  598. @classmethod
  599. def _create_request_args(cls, cookies: Cookies = None, headers: dict = None, user_agent: str = None):
  600. cls._headers = cls.get_default_headers() if headers is None else headers
  601. if user_agent is not None:
  602. cls._headers["user-agent"] = user_agent
  603. cls._cookies = {} if cookies is None else cookies
  604. cls._update_cookie_header()
  605. @classmethod
  606. def _update_request_args(cls, session: StreamSession):
  607. for c in session.cookie_jar if hasattr(session, "cookie_jar") else session.cookies.jar:
  608. cls._cookies[c.key if hasattr(c, "key") else c.name] = c.value
  609. cls._update_cookie_header()
  610. @classmethod
  611. def _set_api_key(cls, api_key: str):
  612. cls._api_key = api_key
  613. cls._expires = int(time.time()) + 60 * 60 * 4
  614. if api_key:
  615. cls._headers["authorization"] = f"Bearer {api_key}"
  616. @classmethod
  617. def _update_cookie_header(cls):
  618. cls._headers["cookie"] = format_cookies(cls._cookies)
  619. class Conversation(BaseConversation):
  620. """
  621. Class to encapsulate response fields.
  622. """
  623. def __init__(self, conversation_id: str = None, message_id: str = None, finish_reason: str = None):
  624. self.conversation_id = conversation_id
  625. self.message_id = message_id
  626. self.finish_reason = finish_reason
  627. self.is_recipient = False
  628. class Response():
  629. """
  630. Class to encapsulate a response from the chat service.
  631. """
  632. def __init__(
  633. self,
  634. generator: AsyncResult,
  635. action: str,
  636. messages: Messages,
  637. options: dict
  638. ):
  639. self._generator = generator
  640. self.action = action
  641. self.is_end = False
  642. self._message = None
  643. self._messages = messages
  644. self._options = options
  645. self._fields = None
  646. async def generator(self) -> AsyncIterator:
  647. if self._generator is not None:
  648. self._generator = None
  649. chunks = []
  650. async for chunk in self._generator:
  651. if isinstance(chunk, Conversation):
  652. self._fields = chunk
  653. else:
  654. yield chunk
  655. chunks.append(str(chunk))
  656. self._message = "".join(chunks)
  657. if self._fields is None:
  658. raise RuntimeError("Missing response fields")
  659. self.is_end = self._fields.finish_reason == "stop"
  660. def __aiter__(self):
  661. return self.generator()
  662. async def get_message(self) -> str:
  663. await self.generator()
  664. return self._message
  665. async def get_fields(self) -> dict:
  666. await self.generator()
  667. return {
  668. "conversation_id": self._fields.conversation_id,
  669. "parent_id": self._fields.message_id
  670. }
  671. async def create_next(self, prompt: str, **kwargs) -> Response:
  672. return await OpenaiChat.create(
  673. **self._options,
  674. prompt=prompt,
  675. messages=await self.get_messages(),
  676. action="next",
  677. **await self.get_fields(),
  678. **kwargs
  679. )
  680. async def do_continue(self, **kwargs) -> Response:
  681. fields = await self.get_fields()
  682. if self.is_end:
  683. raise RuntimeError("Can't continue message. Message already finished.")
  684. return await OpenaiChat.create(
  685. **self._options,
  686. messages=await self.get_messages(),
  687. action="continue",
  688. **fields,
  689. **kwargs
  690. )
  691. async def create_variant(self, **kwargs) -> Response:
  692. if self.action != "next":
  693. raise RuntimeError("Can't create variant from continue or variant request.")
  694. return await OpenaiChat.create(
  695. **self._options,
  696. messages=self._messages,
  697. action="variant",
  698. **await self.get_fields(),
  699. **kwargs
  700. )
  701. async def get_messages(self) -> list:
  702. messages = self._messages
  703. messages.append({"role": "assistant", "content": await self.message()})
  704. return messages