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

XFEstudio/gpt4free

add provider and helper

25870e75
Bagus Indrayana <bagusindrayanaindo@gmail.com>
提交于

代码差异

4 个文件 +261 -0
Added .vscode/settings.json +6 -0
@@ -0,0 +1,6 @@
1 {
2 "[python]": {
3 "editor.defaultFormatter": "ms-python.autopep8"
4 },
5 "python.formatting.provider": "none"
6 }
Added testing/binghuan/BingHuan.py +49 -0
@@ -0,0 +1,49 @@
1 import os,sys
2 import json
3 import subprocess
4 # from ...typing import sha256, Dict, get_type_hints
5
6 url = 'https://b.ai-huan.xyz'
7 model = ['gpt-3.5-turbo', 'gpt-4']
8 supports_stream = True
9 needs_auth = False
10
11 def _create_completion(model: str, messages: list, stream: bool, **kwargs):
12 path = os.path.dirname(os.path.realpath(__file__))
13 config = json.dumps({
14 'messages': messages,
15 'model': model}, separators=(',', ':'))
16
17 cmd = ['python', f'{path}/helpers/binghuan.py', config]
18
19 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
20
21 for line in iter(p.stdout.readline, b''):
22 yield line.decode('cp1252') #[:-1]
23
24
25 # params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \
26 # '(%s)' % ', '.join(
27 # [f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])
28
29
30 # Temporary For ChatCompletion Class
31 class ChatCompletion:
32 @staticmethod
33 def create(model: str, messages: list, provider: None or str, stream: bool = False, auth: str = False, **kwargs):
34 kwargs['auth'] = auth
35
36 if provider and needs_auth and not auth:
37 print(
38 f'ValueError: {provider} requires authentication (use auth="cookie or token or jwt ..." param)', file=sys.stderr)
39 sys.exit(1)
40
41 try:
42 return (_create_completion(model, messages, stream, **kwargs)
43 if stream else ''.join(_create_completion(model, messages, stream, **kwargs)))
44 except TypeError as e:
45 print(e)
46 arg: str = str(e).split("'")[1]
47 print(
48 f"ValueError: {provider} does not support '{arg}' argument", file=sys.stderr)
49 sys.exit(1)
Added testing/binghuan/helpers/binghuan.py +206 -0
@@ -0,0 +1,206 @@
1 import sys
2 import ssl
3 import uuid
4 import json
5 import time
6 import random
7 import asyncio
8 import certifi
9 # import requests
10 from curl_cffi import requests
11 import websockets
12 import browser_cookie3
13
14 config = json.loads(sys.argv[1])
15
16 ssl_context = ssl.create_default_context()
17 ssl_context.load_verify_locations(certifi.where())
18
19
20
21 conversationstyles = {
22 'gpt-4': [ #'precise'
23 "nlu_direct_response_filter",
24 "deepleo",
25 "disable_emoji_spoken_text",
26 "responsible_ai_policy_235",
27 "enablemm",
28 "h3precise",
29 "rcsprtsalwlst",
30 "dv3sugg",
31 "autosave",
32 "clgalileo",
33 "gencontentv3"
34 ],
35 'balanced': [
36 "nlu_direct_response_filter",
37 "deepleo",
38 "disable_emoji_spoken_text",
39 "responsible_ai_policy_235",
40 "enablemm",
41 "harmonyv3",
42 "rcsprtsalwlst",
43 "dv3sugg",
44 "autosave"
45 ],
46 'gpt-3.5-turbo': [ #'precise'
47 "nlu_direct_response_filter",
48 "deepleo",
49 "disable_emoji_spoken_text",
50 "responsible_ai_policy_235",
51 "enablemm",
52 "h3imaginative",
53 "rcsprtsalwlst",
54 "dv3sugg",
55 "autosave",
56 "gencontentv3"
57 ]
58 }
59
60 def format(msg: dict) -> str:
61 return json.dumps(msg) + '\x1e'
62
63 def get_token():
64 return
65
66 try:
67 cookies = {c.name: c.value for c in browser_cookie3.edge(domain_name='bing.com')}
68 return cookies['_U']
69 except:
70 print('Error: could not find bing _U cookie in edge browser.')
71 exit(1)
72
73 class AsyncCompletion:
74 async def create(
75 prompt : str = None,
76 optionSets : list = None,
77 token : str = None): # No auth required anymore
78
79 create = None
80 for _ in range(5):
81 try:
82 create = requests.get('https://b.ai-huan.xyz/turing/conversation/create',
83 headers = {
84 'host': 'b.ai-huan.xyz',
85 'accept-encoding': 'gzip, deflate, br',
86 'connection': 'keep-alive',
87 'authority': 'b.ai-huan.xyz',
88 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
89 'accept-language': 'en-US,en;q=0.9',
90 'cache-control': 'max-age=0',
91 'sec-ch-ua': '"Chromium";v="110", "Not A(Brand";v="24", "Microsoft Edge";v="110"',
92 'sec-ch-ua-arch': '"x86"',
93 'sec-ch-ua-bitness': '"64"',
94 'sec-ch-ua-full-version': '"110.0.1587.69"',
95 'sec-ch-ua-full-version-list': '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
96 'sec-ch-ua-mobile': '?0',
97 'sec-ch-ua-model': '""',
98 'sec-ch-ua-platform': '"Windows"',
99 'sec-ch-ua-platform-version': '"15.0.0"',
100 'sec-fetch-dest': 'document',
101 'sec-fetch-mode': 'navigate',
102 'sec-fetch-site': 'none',
103 'sec-fetch-user': '?1',
104 'upgrade-insecure-requests': '1',
105 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.69',
106 'x-edge-shopping-flag': '1',
107 'x-forwarded-for': f'13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}'
108 }
109 )
110
111 conversationId = create.json()['conversationId']
112 clientId = create.json()['clientId']
113 conversationSignature = create.json()['conversationSignature']
114
115 except Exception as e:
116 time.sleep(0.5)
117 continue
118
119 if create == None: raise Exception('Failed to create conversation.')
120
121 wss: websockets.WebSocketClientProtocol or None = None
122
123 wss = await websockets.connect('wss://sydney.vcanbb.chat/sydney/ChatHub', max_size = None, ssl = ssl_context,
124 extra_headers = {
125 'accept': 'application/json',
126 'accept-language': 'en-US,en;q=0.9',
127 'content-type': 'application/json',
128 'sec-ch-ua': '"Not_A Brand";v="99", Microsoft Edge";v="110", "Chromium";v="110"',
129 'sec-ch-ua-arch': '"x86"',
130 'sec-ch-ua-bitness': '"64"',
131 'sec-ch-ua-full-version': '"109.0.1518.78"',
132 'sec-ch-ua-full-version-list': '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
133 'sec-ch-ua-mobile': '?0',
134 'sec-ch-ua-model': "",
135 'sec-ch-ua-platform': '"Windows"',
136 'sec-ch-ua-platform-version': '"15.0.0"',
137 'sec-fetch-dest': 'empty',
138 'sec-fetch-mode': 'cors',
139 'sec-fetch-site': 'same-origin',
140 'x-ms-client-request-id': str(uuid.uuid4()),
141 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
142 'Referer': 'https://b.ai-huan.xyz/search?q=Bing+AI&showconv=1&FORM=hpcodx',
143 'Referrer-Policy': 'origin-when-cross-origin',
144 'x-forwarded-for': f'13.{random.randint(104, 107)}.{random.randint(0, 255)}.{random.randint(0, 255)}'
145 }
146 )
147
148 await wss.send(format({'protocol': 'json', 'version': 1}))
149 await wss.recv()
150
151 struct = {
152 'arguments': [
153 {
154 'source': 'cib',
155 'optionsSets': optionSets,
156 'isStartOfSession': True,
157 'message': {
158 'author': 'user',
159 'inputMethod': 'Keyboard',
160 'text': prompt,
161 'messageType': 'Chat'
162 },
163 'conversationSignature': conversationSignature,
164 'participant': {
165 'id': clientId
166 },
167 'conversationId': conversationId
168 }
169 ],
170 'invocationId': '0',
171 'target': 'chat',
172 'type': 4
173 }
174
175 await wss.send(format(struct))
176
177 base_string = ''
178
179 final = False
180 while not final:
181 objects = str(await wss.recv()).split('\x1e')
182 for obj in objects:
183 if obj is None or obj == '':
184 continue
185
186 response = json.loads(obj)
187 #print(response, flush=True, end='')
188 if response.get('type') == 1 and response['arguments'][0].get('messages',):
189 response_text = response['arguments'][0]['messages'][0]['adaptiveCards'][0]['body'][0].get('text')
190
191 yield (response_text.replace(base_string, ''))
192 base_string = response_text
193
194 elif response.get('type') == 2:
195 final = True
196
197 await wss.close()
198
199 async def run(optionSets, messages):
200 async for value in AsyncCompletion.create(prompt=messages[-1]['content'],
201 optionSets=optionSets):
202
203 print(value, flush=True, end = '')
204
205 optionSet = conversationstyles[config['model']]
206 asyncio.run(run(optionSet, config['messages']))
Added testing/binghuan/testing.py +0 -0
此文件没有可显示的逐行差异。