XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet
公开
关注 0 Fork 0 Star 1
返回提交历史

XFEstudio/gpt4free

Add Myshell Provider Remove auto proxy prefix

f1b6880f
Heiner Lohaus <heiner@lohaus.eu>
提交于

代码差异

6 个文件 +189 -22
Modified g4f/Provider/Liaobots.py +0 -2
@@ -46,8 +46,6 @@ class Liaobots(AsyncGeneratorProvider):
46 46 **kwargs
47 47 ) -> AsyncGenerator:
48 48 model = model if model in models else "gpt-3.5-turbo"
49 if proxy and "://" not in proxy:
50 proxy = f"http://{proxy}"
51 49 headers = {
52 50 "authority": "liaobots.com",
53 51 "content-type": "application/json",
Added g4f/Provider/Myshell.py +172 -0
@@ -0,0 +1,172 @@
1 from __future__ import annotations
2
3 import json, uuid, hashlib, time, random
4
5 from aiohttp import ClientSession
6 from aiohttp.http import WSMsgType
7 import asyncio
8
9 from ..typing import AsyncGenerator
10 from .base_provider import AsyncGeneratorProvider, format_prompt
11
12
13 models = {
14 "samantha": "1e3be7fe89e94a809408b1154a2ee3e1",
15 "gpt-3.5-turbo": "8077335db7cd47e29f7de486612cc7fd",
16 "gpt-4": "01c8de4fbfc548df903712b0922a4e01",
17 }
18
19
20 class Myshell(AsyncGeneratorProvider):
21 url = "https://app.myshell.ai/chat"
22 working = True
23 supports_gpt_35_turbo = True
24 supports_gpt_4 = True
25
26 @classmethod
27 async def create_async_generator(
28 cls,
29 model: str,
30 messages: list[dict[str, str]],
31 **kwargs
32 ) -> AsyncGenerator:
33 if not model:
34 bot_id = models["samantha"]
35 elif model in models:
36 bot_id = models[model]
37 else:
38 raise ValueError(f"Model are not supported: {model}")
39
40 user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36'
41 visitor_id = generate_visitor_id(user_agent)
42
43 async with ClientSession(
44 headers={'User-Agent': user_agent}
45 ) as session:
46 async with session.ws_connect(
47 "wss://api.myshell.ai/ws/?EIO=4&transport=websocket",
48 autoping=False,
49 timeout=90
50 ) as wss:
51 # Send and receive hello message
52 await wss.receive_str()
53 message = json.dumps({"token": None, "visitorId": visitor_id})
54 await wss.send_str(f"40/chat,{message}")
55 await wss.receive_str()
56
57 # Fix "need_verify_captcha" issue
58 await asyncio.sleep(5)
59
60 # Create chat message
61 text = format_prompt(messages)
62 chat_data = json.dumps(["text_chat",{
63 "reqId": str(uuid.uuid4()),
64 "botUid": bot_id,
65 "sourceFrom": "myshellWebsite",
66 "text": text,
67 **generate_signature(text)
68 }])
69
70 # Send chat message
71 chat_start = "42/chat,"
72 chat_message = f"{chat_start}{chat_data}"
73 await wss.send_str(chat_message)
74
75 # Receive messages
76 async for message in wss:
77 if message.type != WSMsgType.TEXT:
78 continue
79 # Ping back
80 if message.data == "2":
81 await wss.send_str("3")
82 continue
83 # Is not chat message
84 if not message.data.startswith(chat_start):
85 continue
86 data_type, data = json.loads(message.data[len(chat_start):])
87 if data_type == "text_stream":
88 if data["data"]["text"]:
89 yield data["data"]["text"]
90 elif data["data"]["isFinal"]:
91 break
92 elif data_type in ("message_replied", "need_verify_captcha"):
93 raise RuntimeError(f"Received unexpected message: {data_type}")
94
95
96 @classmethod
97 @property
98 def params(cls):
99 params = [
100 ("model", "str"),
101 ("messages", "list[dict[str, str]]"),
102 ("stream", "bool"),
103 ]
104 param = ", ".join([": ".join(p) for p in params])
105 return f"g4f.provider.{cls.__name__} supports: ({param})"
106
107
108 def generate_timestamp() -> str:
109 return str(
110 int(
111 str(int(time.time() * 1000))[:-1]
112 + str(
113 sum(
114 2 * int(digit)
115 if idx % 2 == 0
116 else 3 * int(digit)
117 for idx, digit in enumerate(str(int(time.time() * 1000))[:-1])
118 )
119 % 10
120 )
121 )
122 )
123
124 def generate_signature(text: str):
125 timestamp = generate_timestamp()
126 version = 'v1.0.0'
127 secret = '8@VXGK3kKHr!u2gA'
128 data = f"{version}#{text}#{timestamp}#{secret}"
129 signature = hashlib.md5(data.encode()).hexdigest()
130 signature = signature[::-1]
131 return {
132 "signature": signature,
133 "timestamp": timestamp,
134 "version": version
135 }
136
137 def xor_hash(B: str):
138 r = []
139 i = 0
140
141 def o(e, t):
142 o_val = 0
143 for i in range(len(t)):
144 o_val |= r[i] << (8 * i)
145 return e ^ o_val
146
147 for e in range(len(B)):
148 t = ord(B[e])
149 r.insert(0, 255 & t)
150
151 if len(r) >= 4:
152 i = o(i, r)
153 r = []
154
155 if len(r) > 0:
156 i = o(i, r)
157
158 return hex(i)[2:]
159
160 def performance() -> str:
161 t = int(time.time() * 1000)
162 e = 0
163 while t == int(time.time() * 1000):
164 e += 1
165 return hex(t)[2:] + hex(e)[2:]
166
167 def generate_visitor_id(user_agent: str) -> str:
168 f = performance()
169 r = hex(int(random.random() * (16**16)))[2:-2]
170 d = xor_hash(user_agent)
171 e = hex(1080 * 1920)[2:]
172 return f"{f}-{r}-{d}-{e}-{f}"
Modified g4f/Provider/OpenAssistant.py +0 -2
@@ -23,8 +23,6 @@ class OpenAssistant(AsyncGeneratorProvider):
23 23 cookies: dict = None,
24 24 **kwargs: Any
25 25 ) -> AsyncGenerator:
26 if proxy and "://" not in proxy:
27 proxy = f"http://{proxy}"
28 26 if not cookies:
29 27 cookies = get_cookies("open-assistant.io")
30 28
Modified g4f/Provider/OpenaiChat.py +7 -13
@@ -25,14 +25,7 @@ class OpenaiChat(AsyncProvider):
25 25 cookies: dict = None,
26 26 **kwargs: dict
27 27 ) -> AsyncGenerator:
28 proxies = None
29 if proxy:
30 if "://" not in proxy:
31 proxy = f"http://{proxy}"
32 proxies = {
33 "http": proxy,
34 "https": proxy
35 }
28 proxies = {"https": proxy}
36 29 if not access_token:
37 30 access_token = await cls.get_access_token(cookies, proxies)
38 31 headers = {
@@ -61,15 +54,16 @@ class OpenaiChat(AsyncProvider):
61 54 for line in response.content.decode().splitlines():
62 55 if line.startswith("data: "):
63 56 line = line[6:]
64 if line != "[DONE]":
65 line = json.loads(line)
66 if "message" in line:
67 last_message = line["message"]["content"]["parts"][0]
57 if line == "[DONE]":
58 break
59 line = json.loads(line)
60 if "message" in line:
61 last_message = line["message"]["content"]["parts"][0]
68 62 return last_message
69 63
70 64
71 65 @classmethod
72 async def get_access_token(cls, cookies: dict = None, proxies: dict = None):
66 async def get_access_token(cls, cookies: dict = None, proxies: dict = None) -> str:
73 67 if not cls._access_token:
74 68 cookies = cookies if cookies else get_cookies("chat.openai.com")
75 69 async with AsyncSession(proxies=proxies, cookies=cookies, impersonate="chrome107") as session:
Modified g4f/Provider/__init__.py +2 -0
@@ -21,6 +21,7 @@ from .H2o import H2o
21 21 from .HuggingChat import HuggingChat
22 22 from .Liaobots import Liaobots
23 23 from .Lockchat import Lockchat
24 from .Myshell import Myshell
24 25 from .Opchatgpts import Opchatgpts
25 26 from .OpenaiChat import OpenaiChat
26 27 from .OpenAssistant import OpenAssistant
@@ -68,6 +69,7 @@ __all__ = [
68 69 'HuggingChat',
69 70 'Liaobots',
70 71 'Lockchat',
72 'Myshell',
71 73 'Opchatgpts',
72 74 'Raycast',
73 75 'OpenaiChat',
Modified g4f/models.py +8 -5
@@ -18,6 +18,7 @@ from .Provider import (
18 18 Yqcloud,
19 19 AItianhu,
20 20 Aichat,
21 Myshell,
21 22 )
22 23
23 24 @dataclass(unsafe_hash=True)
@@ -37,7 +38,7 @@ default = Model(
37 38 Wewordle, # Responds with markdown
38 39 Yqcloud, # Answers short questions in chinese
39 40 ChatBase, # Don't want to answer creatively
40 DeepAi, ChatgptLogin, ChatgptAi, Aivvm, GptGo, AItianhu, Aichat,
41 DeepAi, ChatgptLogin, ChatgptAi, Aivvm, GptGo, AItianhu, Aichat, Myshell,
41 42 ])
42 43 )
43 44
@@ -46,7 +47,7 @@ gpt_35_turbo = Model(
46 47 name = 'gpt-3.5-turbo',
47 48 base_provider = 'openai',
48 49 best_provider = RetryProvider([
49 DeepAi, ChatgptLogin, ChatgptAi, Aivvm, GptGo, AItianhu, Aichat,
50 DeepAi, ChatgptLogin, ChatgptAi, Aivvm, GptGo, AItianhu, Aichat, Myshell,
50 51 ])
51 52 )
52 53
@@ -54,7 +55,7 @@ gpt_4 = Model(
54 55 name = 'gpt-4',
55 56 base_provider = 'openai',
56 57 best_provider = RetryProvider([
57 Aivvm
58 Aivvm, Myshell
58 59 ])
59 60 )
60 61
@@ -153,8 +154,10 @@ gpt_35_turbo_16k_0613 = Model(
153 154 gpt_35_turbo_0613 = Model(
154 155 name = 'gpt-3.5-turbo-0613',
155 156 base_provider = 'openai',
156 best_provider = [
157 Aivvm, ChatgptLogin])
157 best_provider = RetryProvider([
158 Aivvm, ChatgptLogin
159 ])
160 )
158 161
159 162 gpt_4_0613 = Model(
160 163 name = 'gpt-4-0613',