gpt4free/g4f/Provider/ChatgptAi.py

88 lines
3.5 KiB
Python
Raw Normal View History

from __future__ import annotations
2023-07-28 13:07:17 +03:00
2023-10-22 18:13:13 +03:00
import re, html, json, string, random
from aiohttp import ClientSession
2023-10-22 18:13:13 +03:00
from ..typing import Messages, AsyncResult
from ..errors import RateLimitError
2023-10-22 18:13:13 +03:00
from .base_provider import AsyncGeneratorProvider
from .helper import get_random_string
2023-07-28 13:07:17 +03:00
2023-10-22 18:13:13 +03:00
class ChatgptAi(AsyncGeneratorProvider):
2023-10-27 23:59:14 +03:00
url = "https://chatgpt.ai"
working = True
2023-10-27 23:59:14 +03:00
supports_message_history = True
supports_system_message = True,
supports_gpt_4 = True,
2023-10-22 18:13:13 +03:00
_system = None
2023-07-28 13:07:17 +03:00
@classmethod
2023-10-22 18:13:13 +03:00
async def create_async_generator(
cls,
2023-07-28 13:07:17 +03:00
model: str,
2023-10-09 11:22:17 +03:00
messages: Messages,
proxy: str = None,
**kwargs
2023-10-22 18:13:13 +03:00
) -> AsyncResult:
2023-07-28 13:07:17 +03:00
headers = {
2023-08-27 18:37:44 +03:00
"authority" : "chatgpt.ai",
"accept" : "*/*",
2023-10-22 18:13:13 +03:00
"accept-language" : "en-US",
2023-08-27 18:37:44 +03:00
"cache-control" : "no-cache",
2023-10-22 18:13:13 +03:00
"origin" : cls.url,
2023-08-27 18:37:44 +03:00
"pragma" : "no-cache",
2023-10-22 18:13:13 +03:00
"referer" : f"{cls.url}/",
2023-08-27 18:37:44 +03:00
"sec-ch-ua" : '"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
"sec-ch-ua-mobile" : "?0",
"sec-ch-ua-platform" : '"Windows"',
"sec-fetch-dest" : "empty",
"sec-fetch-mode" : "cors",
"sec-fetch-site" : "same-origin",
"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",
2023-07-28 13:07:17 +03:00
}
async with ClientSession(
headers=headers
) as session:
2023-10-22 18:13:13 +03:00
if not cls._system:
async with session.get(cls.url, proxy=proxy) as response:
response.raise_for_status()
text = await response.text()
2023-11-20 21:40:55 +03:00
result = re.search(r"data-system='(.*?)'", text)
if result :
2023-10-22 18:13:13 +03:00
cls._system = json.loads(html.unescape(result.group(1)))
if not cls._system:
raise RuntimeError("System args not found")
data = {
2023-10-22 18:13:13 +03:00
"botId": cls._system["botId"],
"customId": cls._system["customId"],
"session": cls._system["sessionId"],
"chatId": get_random_string(),
2023-10-22 18:13:13 +03:00
"contextId": cls._system["contextId"],
"messages": messages[:-1],
2023-10-22 18:13:13 +03:00
"newMessage": messages[-1]["content"],
"newFileId": None,
"stream":True
}
async with session.post(
"https://chatgate.ai/wp-json/mwai-ui/v1/chats/submit",
proxy=proxy,
2023-11-22 23:21:57 +03:00
json=data,
headers={"X-Wp-Nonce": cls._system["restNonce"]}
) as response:
response.raise_for_status()
2023-10-22 18:13:13 +03:00
async for line in response.content:
if line.startswith(b"data: "):
try:
line = json.loads(line[6:])
assert "type" in line
except:
raise RuntimeError(f"Broken line: {line.decode()}")
if line["type"] == "error":
if "https://chatgate.ai/login" in line["data"]:
raise RateLimitError("Rate limit reached")
raise RuntimeError(line["data"])
2023-10-22 18:13:13 +03:00
if line["type"] == "live":
yield line["data"]
elif line["type"] == "end":
break