gpt4free/g4f/Provider/selenium/MyShell.py

76 lines
2.2 KiB
Python
Raw Normal View History

2023-10-22 06:57:31 +00:00
from __future__ import annotations
import time, json
2023-10-22 06:57:31 +00:00
from ...typing import CreateResult, Messages
from ..base_provider import AbstractProvider
from ..helper import format_prompt
from ...webdriver import WebDriver, WebDriverSession, bypass_cloudflare
class MyShell(AbstractProvider):
2023-10-22 07:04:14 +00:00
url = "https://app.myshell.ai/chat"
2023-10-24 16:58:12 +00:00
working = True
supports_gpt_35_turbo = True
supports_stream = True
2023-10-22 06:57:31 +00:00
@classmethod
def create_completion(
2023-10-22 06:57:31 +00:00
cls,
model: str,
messages: Messages,
stream: bool,
2023-10-22 06:57:31 +00:00
proxy: str = None,
timeout: int = 120,
2023-11-20 13:00:40 +00:00
webdriver: WebDriver = None,
2023-10-22 06:57:31 +00:00
**kwargs
) -> CreateResult:
2023-11-20 13:00:40 +00:00
with WebDriverSession(webdriver, "", proxy=proxy) as driver:
bypass_cloudflare(driver, cls.url, timeout)
# Send request with message
data = {
"botId": "4738",
"conversation_scenario": 3,
"message": format_prompt(messages),
"messageType": 1
}
script = """
response = await fetch("https://api.myshell.ai/v1/bot/chat/send_message", {
"headers": {
"accept": "application/json",
"content-type": "application/json",
"myshell-service-name": "organics-api",
"visitor-id": localStorage.getItem("mix_visitorId")
},
"body": '{body}',
"method": "POST"
})
2023-11-20 13:00:40 +00:00
window._reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
"""
driver.execute_script(script.replace("{body}", json.dumps(data)))
script = """
2023-11-20 13:00:40 +00:00
chunk = await window._reader.read();
if (chunk.done) {
2023-11-20 13:00:40 +00:00
return null;
}
content = '';
chunk.value.split('\\n').forEach((line, index) => {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.substring('data: '.length));
if ('content' in data) {
content += data['content'];
}
} catch(e) {}
}
});
return content;
"""
2023-11-16 17:54:59 +00:00
while True:
chunk = driver.execute_script(script)
2023-11-16 17:54:59 +00:00
if chunk:
yield chunk
elif chunk != "":
break
else:
time.sleep(0.1)