gpt4free/g4f/Provider/MyShell.py

90 lines
2.7 KiB
Python
Raw Normal View History

2023-10-22 09:57:31 +03:00
from __future__ import annotations
import time, json
2023-10-22 09:57:31 +03:00
from ..typing import CreateResult, Messages
from .base_provider import BaseProvider
2023-11-16 20:51:24 +03:00
from .helper import WebDriver, format_prompt, get_browser
class MyShell(BaseProvider):
2023-10-22 10:04:14 +03:00
url = "https://app.myshell.ai/chat"
2023-10-24 19:58:12 +03:00
working = True
supports_gpt_35_turbo = True
supports_stream = True
2023-10-22 09:57:31 +03:00
@classmethod
def create_completion(
2023-10-22 09:57:31 +03:00
cls,
model: str,
messages: Messages,
stream: bool,
2023-10-22 09:57:31 +03:00
proxy: str = None,
timeout: int = 120,
browser: WebDriver = None,
2023-11-16 20:51:24 +03:00
hidden_display: bool = True,
2023-10-22 09:57:31 +03:00
**kwargs
) -> CreateResult:
if not browser:
2023-11-16 20:51:24 +03:00
if hidden_display:
driver, display = get_browser("", True, proxy)
else:
display = get_browser("", False, proxy)
else:
driver = browser
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver.get(cls.url)
try:
2023-11-16 20:51:24 +03:00
# Wait for page load
WebDriverWait(driver, timeout).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "body:not(.no-js)"))
)
2023-11-16 20:51:24 +03:00
# Send message
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"
})
window.reader = response.body.getReader();
"""
2023-10-22 09:57:31 +03:00
data = {
"botId": "4738",
2023-10-22 09:57:31 +03:00
"conversation_scenario": 3,
"message": format_prompt(messages),
2023-10-22 09:57:31 +03:00
"messageType": 1
}
driver.execute_script(script.replace("{body}", json.dumps(data)))
script = """
chunk = await window.reader.read();
text = await (new Response(chunk['value']).text());
content = '';
text.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;
"""
while chunk := driver.execute_script(script):
yield chunk
finally:
driver.close()
if not browser:
time.sleep(0.1)
driver.quit()
2023-11-16 20:51:24 +03:00
if hidden_display:
display.stop()