gpt4free/g4f/Provider/Chatgpt4Online.py

71 lines
2.6 KiB
Python
Raw Permalink Normal View History

from __future__ import annotations
2023-11-13 17:58:52 +00:00
import re
2023-12-31 22:35:11 +00:00
import json
from aiohttp import ClientSession
2023-12-31 22:35:11 +00:00
from ..typing import Messages, AsyncResult
from ..requests import get_args_from_browser
2023-12-31 22:35:11 +00:00
from .base_provider import AsyncGeneratorProvider
from .helper import get_random_string
2023-12-31 22:35:11 +00:00
class Chatgpt4Online(AsyncGeneratorProvider):
2023-10-27 20:59:14 +00:00
url = "https://chatgpt4online.org"
supports_message_history = True
supports_gpt_35_turbo = True
working = False
2023-11-13 17:58:52 +00:00
_wpnonce = None
_context_id = None
@classmethod
2023-12-31 22:35:11 +00:00
async def create_async_generator(
cls,
model: str,
2023-10-09 08:22:17 +00:00
messages: Messages,
proxy: str = None,
**kwargs
2023-12-31 22:35:11 +00:00
) -> AsyncResult:
args = get_args_from_browser(f"{cls.url}/chat/", proxy=proxy)
async with ClientSession(**args) as session:
2023-11-13 17:58:52 +00:00
if not cls._wpnonce:
async with session.get(f"{cls.url}/chat/", proxy=proxy) as response:
2023-11-13 17:58:52 +00:00
response.raise_for_status()
response = await response.text()
2023-12-31 22:35:11 +00:00
result = re.search(r'restNonce":"(.*?)"', response)
2023-11-20 18:40:55 +00:00
if result:
2023-11-13 17:58:52 +00:00
cls._wpnonce = result.group(1)
else:
raise RuntimeError("No nonce found")
result = re.search(r'contextId":(.*?),', response)
if result:
cls._context_id = result.group(1)
else:
raise RuntimeError("No contextId found")
data = {
2023-12-31 22:35:11 +00:00
"botId":"default",
"customId":None,
"session":"N/A",
"chatId":get_random_string(11),
"contextId":cls._context_id,
2023-12-31 22:35:11 +00:00
"messages":messages[:-1],
"newMessage":messages[-1]["content"],
"newImageId":None,
"stream":True
}
2023-12-31 22:35:11 +00:00
async with session.post(
f"{cls.url}/wp-json/mwai-ui/v1/chats/submit",
json=data,
proxy=proxy,
headers={"x-wp-nonce": cls._wpnonce}
) as response:
response.raise_for_status()
2023-12-31 22:35:11 +00:00
async for line in response.content:
if line.startswith(b"data: "):
line = json.loads(line[6:])
if "type" not in line:
raise RuntimeError(f"Response: {line}")
elif line["type"] == "live":
yield line["data"]
elif line["type"] == "end":
break