OpenaiChat.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. from __future__ import annotations
  2. import asyncio
  3. import uuid
  4. import json
  5. import os
  6. from py_arkose_generator.arkose import get_values_for_request
  7. from async_property import async_cached_property
  8. from selenium.webdriver.common.by import By
  9. from selenium.webdriver.support.ui import WebDriverWait
  10. from selenium.webdriver.support import expected_conditions as EC
  11. from ..base_provider import AsyncGeneratorProvider
  12. from ..helper import format_prompt, get_cookies
  13. from ...webdriver import get_browser, get_driver_cookies
  14. from ...typing import AsyncResult, Messages
  15. from ...requests import StreamSession
  16. from ...image import to_image, to_bytes, ImageType, ImageResponse
  17. # Aliases for model names
  18. MODELS = {
  19. "gpt-3.5": "text-davinci-002-render-sha",
  20. "gpt-3.5-turbo": "text-davinci-002-render-sha",
  21. "gpt-4": "gpt-4",
  22. "gpt-4-gizmo": "gpt-4-gizmo"
  23. }
  24. class OpenaiChat(AsyncGeneratorProvider):
  25. """A class for creating and managing conversations with OpenAI chat service"""
  26. url = "https://chat.openai.com"
  27. working = True
  28. needs_auth = True
  29. supports_gpt_35_turbo = True
  30. supports_gpt_4 = True
  31. _cookies: dict = {}
  32. _default_model: str = None
  33. @classmethod
  34. async def create(
  35. cls,
  36. prompt: str = None,
  37. model: str = "",
  38. messages: Messages = [],
  39. history_disabled: bool = False,
  40. action: str = "next",
  41. conversation_id: str = None,
  42. parent_id: str = None,
  43. image: ImageType = None,
  44. **kwargs
  45. ) -> Response:
  46. """
  47. Create a new conversation or continue an existing one
  48. Args:
  49. prompt: The user input to start or continue the conversation
  50. model: The name of the model to use for generating responses
  51. messages: The list of previous messages in the conversation
  52. history_disabled: A flag indicating if the history and training should be disabled
  53. action: The type of action to perform, either "next", "continue", or "variant"
  54. conversation_id: The ID of the existing conversation, if any
  55. parent_id: The ID of the parent message, if any
  56. image: The image to include in the user input, if any
  57. **kwargs: Additional keyword arguments to pass to the generator
  58. Returns:
  59. A Response object that contains the generator, action, messages, and options
  60. """
  61. # Add the user input to the messages list
  62. if prompt:
  63. messages.append({
  64. "role": "user",
  65. "content": prompt
  66. })
  67. generator = cls.create_async_generator(
  68. model,
  69. messages,
  70. history_disabled=history_disabled,
  71. action=action,
  72. conversation_id=conversation_id,
  73. parent_id=parent_id,
  74. image=image,
  75. response_fields=True,
  76. **kwargs
  77. )
  78. return Response(
  79. generator,
  80. action,
  81. messages,
  82. kwargs
  83. )
  84. @classmethod
  85. async def _upload_image(
  86. cls,
  87. session: StreamSession,
  88. headers: dict,
  89. image: ImageType
  90. ) -> ImageResponse:
  91. """
  92. Upload an image to the service and get the download URL
  93. Args:
  94. session: The StreamSession object to use for requests
  95. headers: The headers to include in the requests
  96. image: The image to upload, either a PIL Image object or a bytes object
  97. Returns:
  98. An ImageResponse object that contains the download URL, file name, and other data
  99. """
  100. # Convert the image to a PIL Image object and get the extension
  101. image = to_image(image)
  102. extension = image.format.lower()
  103. # Convert the image to a bytes object and get the size
  104. data_bytes = to_bytes(image)
  105. data = {
  106. "file_name": f"{image.width}x{image.height}.{extension}",
  107. "file_size": len(data_bytes),
  108. "use_case": "multimodal"
  109. }
  110. # Post the image data to the service and get the image data
  111. async with session.post(f"{cls.url}/backend-api/files", json=data, headers=headers) as response:
  112. response.raise_for_status()
  113. image_data = {
  114. **data,
  115. **await response.json(),
  116. "mime_type": f"image/{extension}",
  117. "extension": extension,
  118. "height": image.height,
  119. "width": image.width
  120. }
  121. # Put the image bytes to the upload URL and check the status
  122. async with session.put(
  123. image_data["upload_url"],
  124. data=data_bytes,
  125. headers={
  126. "Content-Type": image_data["mime_type"],
  127. "x-ms-blob-type": "BlockBlob"
  128. }
  129. ) as response:
  130. response.raise_for_status()
  131. # Post the file ID to the service and get the download URL
  132. async with session.post(
  133. f"{cls.url}/backend-api/files/{image_data['file_id']}/uploaded",
  134. json={},
  135. headers=headers
  136. ) as response:
  137. response.raise_for_status()
  138. download_url = (await response.json())["download_url"]
  139. return ImageResponse(download_url, image_data["file_name"], image_data)
  140. @classmethod
  141. async def _get_default_model(cls, session: StreamSession, headers: dict):
  142. """
  143. Get the default model name from the service
  144. Args:
  145. session: The StreamSession object to use for requests
  146. headers: The headers to include in the requests
  147. Returns:
  148. The default model name as a string
  149. """
  150. # Check the cache for the default model
  151. if cls._default_model:
  152. return cls._default_model
  153. # Get the models data from the service
  154. async with session.get(f"{cls.url}/backend-api/models", headers=headers) as response:
  155. data = await response.json()
  156. if "categories" in data:
  157. cls._default_model = data["categories"][-1]["default_model"]
  158. else:
  159. raise RuntimeError(f"Response: {data}")
  160. return cls._default_model
  161. @classmethod
  162. def _create_messages(cls, prompt: str, image_response: ImageResponse = None):
  163. """
  164. Create a list of messages for the user input
  165. Args:
  166. prompt: The user input as a string
  167. image_response: The image response object, if any
  168. Returns:
  169. A list of messages with the user input and the image, if any
  170. """
  171. # Check if there is an image response
  172. if not image_response:
  173. # Create a content object with the text type and the prompt
  174. content = {"content_type": "text", "parts": [prompt]}
  175. else:
  176. # Create a content object with the multimodal text type and the image and the prompt
  177. content = {
  178. "content_type": "multimodal_text",
  179. "parts": [{
  180. "asset_pointer": f"file-service://{image_response.get('file_id')}",
  181. "height": image_response.get("height"),
  182. "size_bytes": image_response.get("file_size"),
  183. "width": image_response.get("width"),
  184. }, prompt]
  185. }
  186. # Create a message object with the user role and the content
  187. messages = [{
  188. "id": str(uuid.uuid4()),
  189. "author": {"role": "user"},
  190. "content": content,
  191. }]
  192. # Check if there is an image response
  193. if image_response:
  194. # Add the metadata object with the attachments
  195. messages[0]["metadata"] = {
  196. "attachments": [{
  197. "height": image_response.get("height"),
  198. "id": image_response.get("file_id"),
  199. "mimeType": image_response.get("mime_type"),
  200. "name": image_response.get("file_name"),
  201. "size": image_response.get("file_size"),
  202. "width": image_response.get("width"),
  203. }]
  204. }
  205. return messages
  206. @classmethod
  207. async def _get_generated_image(cls, session: StreamSession, headers: dict, line: dict) -> ImageResponse:
  208. """
  209. Retrieves the image response based on the message content.
  210. This method processes the message content to extract image information and retrieves the
  211. corresponding image from the backend API. It then returns an ImageResponse object containing
  212. the image URL and the prompt used to generate the image.
  213. Args:
  214. session (StreamSession): The StreamSession object used for making HTTP requests.
  215. headers (dict): HTTP headers to be used for the request.
  216. line (dict): A dictionary representing the line of response that contains image information.
  217. Returns:
  218. ImageResponse: An object containing the image URL and the prompt, or None if no image is found.
  219. Raises:
  220. RuntimeError: If there'san error in downloading the image, including issues with the HTTP request or response.
  221. """
  222. if "parts" not in line["message"]["content"]:
  223. return
  224. first_part = line["message"]["content"]["parts"][0]
  225. if "asset_pointer" not in first_part or "metadata" not in first_part:
  226. return
  227. file_id = first_part["asset_pointer"].split("file-service://", 1)[1]
  228. prompt = first_part["metadata"]["dalle"]["prompt"]
  229. try:
  230. async with session.get(f"{cls.url}/backend-api/files/{file_id}/download", headers=headers) as response:
  231. response.raise_for_status()
  232. download_url = (await response.json())["download_url"]
  233. return ImageResponse(download_url, prompt)
  234. except Exception as e:
  235. raise RuntimeError(f"Error in downloading image: {e}")
  236. @classmethod
  237. async def _delete_conversation(cls, session: StreamSession, headers: dict, conversation_id: str):
  238. """
  239. Deletes a conversation by setting its visibility to False.
  240. This method sends an HTTP PATCH request to update the visibility of a conversation.
  241. It's used to effectively delete a conversation from being accessed or displayed in the future.
  242. Args:
  243. session (StreamSession): The StreamSession object used for making HTTP requests.
  244. headers (dict): HTTP headers to be used for the request.
  245. conversation_id (str): The unique identifier of the conversation to be deleted.
  246. Raises:
  247. HTTPError: If the HTTP request fails or returns an unsuccessful status code.
  248. """
  249. async with session.patch(
  250. f"{cls.url}/backend-api/conversation/{conversation_id}",
  251. json={"is_visible": False},
  252. headers=headers
  253. ) as response:
  254. response.raise_for_status()
  255. @classmethod
  256. async def create_async_generator(
  257. cls,
  258. model: str,
  259. messages: Messages,
  260. proxy: str = None,
  261. timeout: int = 120,
  262. access_token: str = None,
  263. cookies: dict = None,
  264. auto_continue: bool = False,
  265. history_disabled: bool = True,
  266. action: str = "next",
  267. conversation_id: str = None,
  268. parent_id: str = None,
  269. image: ImageType = None,
  270. response_fields: bool = False,
  271. **kwargs
  272. ) -> AsyncResult:
  273. """
  274. Create an asynchronous generator for the conversation.
  275. Args:
  276. model (str): The model name.
  277. messages (Messages): The list of previous messages.
  278. proxy (str): Proxy to use for requests.
  279. timeout (int): Timeout for requests.
  280. access_token (str): Access token for authentication.
  281. cookies (dict): Cookies to use for authentication.
  282. auto_continue (bool): Flag to automatically continue the conversation.
  283. history_disabled (bool): Flag to disable history and training.
  284. action (str): Type of action ('next', 'continue', 'variant').
  285. conversation_id (str): ID of the conversation.
  286. parent_id (str): ID of the parent message.
  287. image (ImageType): Image to include in the conversation.
  288. response_fields (bool): Flag to include response fields in the output.
  289. **kwargs: Additional keyword arguments.
  290. Yields:
  291. AsyncResult: Asynchronous results from the generator.
  292. Raises:
  293. RuntimeError: If an error occurs during processing.
  294. """
  295. model = MODELS.get(model, model)
  296. if not parent_id:
  297. parent_id = str(uuid.uuid4())
  298. if not cookies:
  299. cookies = cls._cookies or get_cookies("chat.openai.com")
  300. if not access_token and "access_token" in cookies:
  301. access_token = cookies["access_token"]
  302. if not access_token:
  303. login_url = os.environ.get("G4F_LOGIN_URL")
  304. if login_url:
  305. yield f"Please login: [ChatGPT]({login_url})\n\n"
  306. access_token, cookies = cls._browse_access_token(proxy)
  307. cls._cookies = cookies
  308. headers = {"Authorization": f"Bearer {access_token}"}
  309. async with StreamSession(
  310. proxies={"https": proxy},
  311. impersonate="chrome110",
  312. timeout=timeout,
  313. cookies=dict([(name, value) for name, value in cookies.items() if name == "_puid"])
  314. ) as session:
  315. if not model:
  316. model = await cls._get_default_model(session, headers)
  317. try:
  318. image_response = None
  319. if image:
  320. image_response = await cls._upload_image(session, headers, image)
  321. yield image_response
  322. except Exception as e:
  323. yield e
  324. end_turn = EndTurn()
  325. while not end_turn.is_end:
  326. data = {
  327. "action": action,
  328. "arkose_token": await cls._get_arkose_token(session),
  329. "conversation_id": conversation_id,
  330. "parent_message_id": parent_id,
  331. "model": model,
  332. "history_and_training_disabled": history_disabled and not auto_continue,
  333. }
  334. if action != "continue":
  335. prompt = format_prompt(messages) if not conversation_id else messages[-1]["content"]
  336. data["messages"] = cls._create_messages(prompt, image_response)
  337. async with session.post(
  338. f"{cls.url}/backend-api/conversation",
  339. json=data,
  340. headers={"Accept": "text/event-stream", **headers}
  341. ) as response:
  342. if not response.ok:
  343. raise RuntimeError(f"Response {response.status_code}: {await response.text()}")
  344. try:
  345. last_message: int = 0
  346. async for line in response.iter_lines():
  347. if not line.startswith(b"data: "):
  348. continue
  349. elif line.startswith(b"data: [DONE]"):
  350. break
  351. try:
  352. line = json.loads(line[6:])
  353. except:
  354. continue
  355. if "message" not in line:
  356. continue
  357. if "error" in line and line["error"]:
  358. raise RuntimeError(line["error"])
  359. if "message_type" not in line["message"]["metadata"]:
  360. continue
  361. try:
  362. image_response = await cls._get_generated_image(session, headers, line)
  363. if image_response:
  364. yield image_response
  365. except Exception as e:
  366. yield e
  367. if line["message"]["author"]["role"] != "assistant":
  368. continue
  369. if line["message"]["content"]["content_type"] != "text":
  370. continue
  371. if line["message"]["metadata"]["message_type"] not in ("next", "continue", "variant"):
  372. continue
  373. conversation_id = line["conversation_id"]
  374. parent_id = line["message"]["id"]
  375. if response_fields:
  376. response_fields = False
  377. yield ResponseFields(conversation_id, parent_id, end_turn)
  378. if "parts" in line["message"]["content"]:
  379. new_message = line["message"]["content"]["parts"][0]
  380. if len(new_message) > last_message:
  381. yield new_message[last_message:]
  382. last_message = len(new_message)
  383. if "finish_details" in line["message"]["metadata"]:
  384. if line["message"]["metadata"]["finish_details"]["type"] == "stop":
  385. end_turn.end()
  386. except Exception as e:
  387. raise e
  388. if not auto_continue:
  389. break
  390. action = "continue"
  391. await asyncio.sleep(5)
  392. if history_disabled and auto_continue:
  393. await cls._delete_conversation(session, headers, conversation_id)
  394. @classmethod
  395. def _browse_access_token(cls, proxy: str = None, timeout: int = 1200) -> tuple[str, dict]:
  396. """
  397. Browse to obtain an access token.
  398. Args:
  399. proxy (str): Proxy to use for browsing.
  400. Returns:
  401. tuple[str, dict]: A tuple containing the access token and cookies.
  402. """
  403. driver = get_browser(proxy=proxy)
  404. try:
  405. driver.get(f"{cls.url}/")
  406. WebDriverWait(driver, timeout).until(EC.presence_of_element_located((By.ID, "prompt-textarea")))
  407. access_token = driver.execute_script(
  408. "let session = await fetch('/api/auth/session');"
  409. "let data = await session.json();"
  410. "let accessToken = data['accessToken'];"
  411. "let expires = new Date(); expires.setTime(expires.getTime() + 60 * 60 * 24 * 7);"
  412. "document.cookie = 'access_token=' + accessToken + ';expires=' + expires.toUTCString() + ';path=/';"
  413. "return accessToken;"
  414. )
  415. return access_token, get_driver_cookies(driver)
  416. finally:
  417. driver.quit()
  418. @classmethod
  419. async def _get_arkose_token(cls, session: StreamSession) -> str:
  420. """
  421. Obtain an Arkose token for the session.
  422. Args:
  423. session (StreamSession): The session object.
  424. Returns:
  425. str: The Arkose token.
  426. Raises:
  427. RuntimeError: If unable to retrieve the token.
  428. """
  429. config = {
  430. "pkey": "3D86FBBA-9D22-402A-B512-3420086BA6CC",
  431. "surl": "https://tcr9i.chat.openai.com",
  432. "headers": {
  433. "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
  434. },
  435. "site": cls.url,
  436. }
  437. args_for_request = get_values_for_request(config)
  438. async with session.post(**args_for_request) as response:
  439. response.raise_for_status()
  440. decoded_json = await response.json()
  441. if "token" in decoded_json:
  442. return decoded_json["token"]
  443. raise RuntimeError(f"Response: {decoded_json}")
  444. class EndTurn:
  445. """
  446. Class to represent the end of a conversation turn.
  447. """
  448. def __init__(self):
  449. self.is_end = False
  450. def end(self):
  451. self.is_end = True
  452. class ResponseFields:
  453. """
  454. Class to encapsulate response fields.
  455. """
  456. def __init__(self, conversation_id: str, message_id: str, end_turn: EndTurn):
  457. self.conversation_id = conversation_id
  458. self.message_id = message_id
  459. self._end_turn = end_turn
  460. class Response():
  461. """
  462. Class to encapsulate a response from the chat service.
  463. """
  464. def __init__(
  465. self,
  466. generator: AsyncResult,
  467. action: str,
  468. messages: Messages,
  469. options: dict
  470. ):
  471. self._generator = generator
  472. self.action = action
  473. self.is_end = False
  474. self._message = None
  475. self._messages = messages
  476. self._options = options
  477. self._fields = None
  478. async def generator(self):
  479. if self._generator:
  480. self._generator = None
  481. chunks = []
  482. async for chunk in self._generator:
  483. if isinstance(chunk, ResponseFields):
  484. self._fields = chunk
  485. else:
  486. yield chunk
  487. chunks.append(str(chunk))
  488. self._message = "".join(chunks)
  489. if not self._fields:
  490. raise RuntimeError("Missing response fields")
  491. self.is_end = self._fields._end_turn.is_end
  492. def __aiter__(self):
  493. return self.generator()
  494. @async_cached_property
  495. async def message(self) -> str:
  496. await self.generator()
  497. return self._message
  498. async def get_fields(self):
  499. await self.generator()
  500. return {"conversation_id": self._fields.conversation_id, "parent_id": self._fields.message_id}
  501. async def next(self, prompt: str, **kwargs) -> Response:
  502. return await OpenaiChat.create(
  503. **self._options,
  504. prompt=prompt,
  505. messages=await self.messages,
  506. action="next",
  507. **await self.get_fields(),
  508. **kwargs
  509. )
  510. async def do_continue(self, **kwargs) -> Response:
  511. fields = await self.get_fields()
  512. if self.is_end:
  513. raise RuntimeError("Can't continue message. Message already finished.")
  514. return await OpenaiChat.create(
  515. **self._options,
  516. messages=await self.messages,
  517. action="continue",
  518. **fields,
  519. **kwargs
  520. )
  521. async def variant(self, **kwargs) -> Response:
  522. if self.action != "next":
  523. raise RuntimeError("Can't create variant from continue or variant request.")
  524. return await OpenaiChat.create(
  525. **self._options,
  526. messages=self._messages,
  527. action="variant",
  528. **await self.get_fields(),
  529. **kwargs
  530. )
  531. @async_cached_property
  532. async def messages(self):
  533. messages = self._messages
  534. messages.append({"role": "assistant", "content": await self.message})
  535. return messages