Chatgpt4Online.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. from __future__ import annotations
  2. import re
  3. import json
  4. from aiohttp import ClientSession
  5. from ..typing import Messages, AsyncResult
  6. from .base_provider import AsyncGeneratorProvider
  7. from .helper import get_random_string
  8. class Chatgpt4Online(AsyncGeneratorProvider):
  9. url = "https://chatgpt4online.org"
  10. supports_message_history = True
  11. supports_gpt_35_turbo = True
  12. working = True
  13. _wpnonce = None
  14. @classmethod
  15. async def create_async_generator(
  16. cls,
  17. model: str,
  18. messages: Messages,
  19. proxy: str = None,
  20. **kwargs
  21. ) -> AsyncResult:
  22. headers = {
  23. "accept": "*/*",
  24. "accept-language": "en-US",
  25. "content-type": "application/json",
  26. "sec-ch-ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
  27. "sec-ch-ua-mobile": "?0",
  28. "sec-ch-ua-platform": "\"Windows\"",
  29. "sec-fetch-dest": "empty",
  30. "sec-fetch-mode": "cors",
  31. "sec-fetch-site": "same-origin",
  32. "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
  33. "referer": "https://chatgpt4online.org/",
  34. "referrer-policy": "strict-origin-when-cross-origin"
  35. }
  36. async with ClientSession(headers=headers) as session:
  37. if not cls._wpnonce:
  38. async with session.get(f"{cls.url}/", proxy=proxy) as response:
  39. response.raise_for_status()
  40. response = await response.text()
  41. result = re.search(r'restNonce":"(.*?)"', response)
  42. if result:
  43. cls._wpnonce = result.group(1)
  44. else:
  45. raise RuntimeError("No nonce found")
  46. data = {
  47. "botId":"default",
  48. "customId":None,
  49. "session":"N/A",
  50. "chatId":get_random_string(11),
  51. "contextId":58,
  52. "messages":messages[:-1],
  53. "newMessage":messages[-1]["content"],
  54. "newImageId":None,
  55. "stream":True
  56. }
  57. async with session.post(
  58. f"{cls.url}/wp-json/mwai-ui/v1/chats/submit",
  59. json=data,
  60. proxy=proxy,
  61. headers={"x-wp-nonce": cls._wpnonce}
  62. ) as response:
  63. response.raise_for_status()
  64. async for line in response.content:
  65. if line.startswith(b"data: "):
  66. line = json.loads(line[6:])
  67. if "type" not in line:
  68. raise RuntimeError(f"Response: {line}")
  69. elif line["type"] == "live":
  70. yield line["data"]
  71. elif line["type"] == "end":
  72. break