ChatgptAi.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. from __future__ import annotations
  2. import re, html, json, string, random
  3. from aiohttp import ClientSession
  4. from ..typing import Messages, AsyncResult
  5. from .base_provider import AsyncGeneratorProvider
  6. class ChatgptAi(AsyncGeneratorProvider):
  7. url = "https://chatgpt.ai"
  8. working = True
  9. supports_message_history = True
  10. supports_gpt_35_turbo = True
  11. _system = None
  12. @classmethod
  13. async def create_async_generator(
  14. cls,
  15. model: str,
  16. messages: Messages,
  17. proxy: str = None,
  18. **kwargs
  19. ) -> AsyncResult:
  20. headers = {
  21. "authority" : "chatgpt.ai",
  22. "accept" : "*/*",
  23. "accept-language" : "en-US",
  24. "cache-control" : "no-cache",
  25. "origin" : cls.url,
  26. "pragma" : "no-cache",
  27. "referer" : f"{cls.url}/",
  28. "sec-ch-ua" : '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
  29. "sec-ch-ua-mobile" : "?0",
  30. "sec-ch-ua-platform" : '"Windows"',
  31. "sec-fetch-dest" : "empty",
  32. "sec-fetch-mode" : "cors",
  33. "sec-fetch-site" : "same-origin",
  34. "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
  35. }
  36. async with ClientSession(
  37. headers=headers
  38. ) as session:
  39. if not cls._system:
  40. async with session.get(cls.url, proxy=proxy) as response:
  41. response.raise_for_status()
  42. text = await response.text()
  43. result = re.search(r"data-system='(.*?)'", text)
  44. if result :
  45. cls._system = json.loads(html.unescape(result.group(1)))
  46. if not cls._system:
  47. raise RuntimeError("System args not found")
  48. data = {
  49. "botId": cls._system["botId"],
  50. "customId": cls._system["customId"],
  51. "session": cls._system["sessionId"],
  52. "chatId": "".join(random.choices(f"{string.ascii_lowercase}{string.digits}", k=11)),
  53. "contextId": cls._system["contextId"],
  54. "messages": messages,
  55. "newMessage": messages[-1]["content"],
  56. "stream": True
  57. }
  58. async with session.post(
  59. f"{cls.url}/wp-json/mwai-ui/v1/chats/submit",
  60. proxy=proxy,
  61. json=data,
  62. headers={"X-Wp-Nonce": cls._system["restNonce"]}
  63. ) as response:
  64. response.raise_for_status()
  65. async for line in response.content:
  66. if line.startswith(b"data: "):
  67. try:
  68. line = json.loads(line[6:])
  69. assert "type" in line
  70. except:
  71. raise RuntimeError(f"Broken line: {line.decode()}")
  72. if line["type"] == "live":
  73. yield line["data"]
  74. elif line["type"] == "end":
  75. break