gpt4free/g4f/Provider/Chatgpt4Online.py

71 lines
2.6 KiB
Python
Raw Normal View History

from __future__ import annotations
2023-11-13 20:58:52 +03:00
import re
2024-01-01 01:35:11 +03:00
import json
from aiohttp import ClientSession
2024-01-01 01:35:11 +03:00
from ..typing import Messages, AsyncResult
from ..requests import get_args_from_browser
2024-01-01 01:35:11 +03:00
from .base_provider import AsyncGeneratorProvider
from .helper import get_random_string
2024-01-01 01:35:11 +03:00
class Chatgpt4Online(AsyncGeneratorProvider):
2023-10-27 23:59:14 +03:00
url = "https://chatgpt4online.org"
supports_message_history = True
supports_gpt_35_turbo = True
working = True
2023-11-13 20:58:52 +03:00
_wpnonce = None
_context_id = None
@classmethod
2024-01-01 01:35:11 +03:00
async def create_async_generator(
cls,
model: str,
2023-10-09 11:22:17 +03:00
messages: Messages,
proxy: str = None,
**kwargs
2024-01-01 01:35:11 +03:00
) -> AsyncResult:
args = get_args_from_browser(f"{cls.url}/chat/", proxy=proxy)
async with ClientSession(**args) as session:
2023-11-13 20:58:52 +03:00
if not cls._wpnonce:
async with session.get(f"{cls.url}/chat/", proxy=proxy) as response:
2023-11-13 20:58:52 +03:00
response.raise_for_status()
response = await response.text()
2024-01-01 01:35:11 +03:00
result = re.search(r'restNonce":"(.*?)"', response)
2023-11-20 21:40:55 +03:00
if result:
2023-11-13 20:58:52 +03: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 = {
2024-01-01 01:35:11 +03:00
"botId":"default",
"customId":None,
"session":"N/A",
"chatId":get_random_string(11),
"contextId":cls._context_id,
2024-01-01 01:35:11 +03:00
"messages":messages[:-1],
"newMessage":messages[-1]["content"],
"newImageId":None,
"stream":True
}
2024-01-01 01:35:11 +03: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()
2024-01-01 01:35:11 +03: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