gpt4free/g4f/Provider/ChatgptAi.py

78 lines
3.1 KiB
Python
Raw Normal View History

from __future__ import annotations
2023-07-28 10:07:17 +00:00
2023-10-22 15:13:13 +00:00
import re, html, json, string, random
from aiohttp import ClientSession
2023-10-22 15:13:13 +00:00
from ..typing import Messages, AsyncResult
from .base_provider import AsyncGeneratorProvider
2023-07-28 10:07:17 +00:00
2023-10-22 15:13:13 +00:00
class ChatgptAi(AsyncGeneratorProvider):
url: str = "https://chatgpt.ai"
working = True
supports_gpt_35_turbo = True
2023-10-22 15:13:13 +00:00
_system = None
2023-07-28 10:07:17 +00:00
@classmethod
2023-10-22 15:13:13 +00:00
async def create_async_generator(
cls,
2023-07-28 10:07:17 +00:00
model: str,
2023-10-09 08:22:17 +00:00
messages: Messages,
proxy: str = None,
**kwargs
2023-10-22 15:13:13 +00:00
) -> AsyncResult:
2023-07-28 10:07:17 +00:00
headers = {
2023-08-27 15:37:44 +00:00
"authority" : "chatgpt.ai",
"accept" : "*/*",
2023-10-22 15:13:13 +00:00
"accept-language" : "en-US",
2023-08-27 15:37:44 +00:00
"cache-control" : "no-cache",
2023-10-22 15:13:13 +00:00
"origin" : cls.url,
2023-08-27 15:37:44 +00:00
"pragma" : "no-cache",
2023-10-22 15:13:13 +00:00
"referer" : f"{cls.url}/",
2023-08-27 15:37:44 +00: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 10:07:17 +00:00
}
async with ClientSession(
headers=headers
) as session:
2023-10-22 15:13:13 +00:00
if not cls._system:
async with session.get(cls.url, proxy=proxy) as response:
response.raise_for_status()
text = await response.text()
if result := re.search(r"data-system='(.*?)'", text):
2023-10-22 15:13:13 +00:00
cls._system = json.loads(html.unescape(result.group(1)))
if not cls._system:
raise RuntimeError("System args not found")
data = {
2023-10-22 15:13:13 +00:00
"botId": cls._system["botId"],
"customId": cls._system["customId"],
"session": cls._system["sessionId"],
"chatId": "".join(random.choices(f"{string.ascii_lowercase}{string.digits}", k=11)),
"contextId": cls._system["contextId"],
"messages": messages,
"newMessage": messages[-1]["content"],
"stream": True
}
async with session.post(
2023-10-22 15:13:13 +00:00
f"{cls.url}/wp-json/mwai-ui/v1/chats/submit",
proxy=proxy,
2023-10-22 15:13:13 +00:00
json=data
) as response:
response.raise_for_status()
2023-10-22 15:13:13 +00: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"] == "live":
yield line["data"]
elif line["type"] == "end":
break