返回提交历史
Modified
g4f/Provider/Bard.py
+67
-69
XFEstudio/gpt4free
Fix bard provider, add async support
24e4b5b6
代码差异
1 个文件
+67
-69
@@ -3,99 +3,97 @@ import random
3
3
import re
4
4
5
5
import browser_cookie3
6
import requests
6
from aiohttp import ClientSession
7
import asyncio
7
8
8
9
from ..typing import Any, CreateResult
9
10
from .base_provider import BaseProvider
10
11
11
12
12
class Bard(BaseProvider):
13
13
url = "https://bard.google.com"
14
14
needs_auth = True
15
15
working = True
16
16
17
@staticmethod
17
@classmethod
18
18
def create_completion(
19
cls,
19
20
model: str,
20
21
messages: list[dict[str, str]],
21
22
stream: bool,
23
proxy: str = None,
24
cookies: dict = {},
22
25
**kwargs: Any,
23
26
) -> CreateResult:
24
psid = {
25
cookie.name: cookie.value
26
for cookie in browser_cookie3.chrome(domain_name=".google.com")
27
}["__Secure-1PSID"]
27
yield asyncio.run(cls.create_async(str, messages, proxy, cookies))
28
29
@classmethod
30
async def create_async(
31
cls,
32
model: str,
33
messages: list[dict[str, str]],
34
proxy: str = None,
35
cookies: dict = {},
36
**kwargs: Any,
37
) -> str:
38
if not cookies:
39
for cookie in browser_cookie3.load(domain_name='.google.com'):
40
cookies[cookie.name] = cookie.value
28
41
29
42
formatted = "\n".join(
30
43
["%s: %s" % (message["role"], message["content"]) for message in messages]
31
44
)
32
45
prompt = f"{formatted}\nAssistant:"
33
46
34
proxy = kwargs.get("proxy", False)
35
if proxy == False:
36
print(
37
"warning!, you did not give a proxy, a lot of countries are banned from Google Bard, so it may not work"
38
)
39
40
snlm0e = None
41
conversation_id = None
42
response_id = None
43
choice_id = None
44
45
client = requests.Session()
46
client.proxies = (
47
{"http": f"http://{proxy}", "https": f"http://{proxy}"} if proxy else {}
48
)
47
if proxy and "://" not in proxy:
48
proxy = f"http://{proxy}"
49
49
50
client.headers = {
51
"authority": "bard.google.com",
52
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
53
"origin": "https://bard.google.com",
54
"referer": "https://bard.google.com/",
55
"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",
56
"x-same-domain": "1",
57
"cookie": f"__Secure-1PSID={psid}",
50
headers = {
51
'authority': 'bard.google.com',
52
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
53
'origin': 'https://bard.google.com',
54
'referer': 'https://bard.google.com/',
55
'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',
56
'x-same-domain': '1',
58
57
}
59
58
60
if snlm0e is not None:
61
result = re.search(
62
r"SNlM0e\":\"(.*?)\"", client.get("https://bard.google.com/").text
63
)
64
if result is not None:
65
snlm0e = result.group(1)
66
67
params = {
68
"bl": "boq_assistant-bard-web-server_20230326.21_p0",
69
"_reqid": random.randint(1111, 9999),
70
"rt": "c",
71
}
72
73
data = {
74
"at": snlm0e,
75
"f.req": json.dumps(
76
[
77
None,
78
json.dumps(
79
[[prompt], None, [conversation_id, response_id, choice_id]]
80
),
81
]
82
),
83
}
84
85
intents = ".".join(["assistant", "lamda", "BardFrontendService"])
86
87
response = client.post(
88
f"https://bard.google.com/_/BardChatUi/data/{intents}/StreamGenerate",
89
data=data,
90
params=params,
91
)
92
response.raise_for_status()
93
94
chat_data = json.loads(response.content.splitlines()[3])[0][2]
95
if chat_data:
96
json_chat_data = json.loads(chat_data)
97
98
yield json_chat_data[0][0]
59
async with ClientSession(
60
cookies=cookies,
61
headers=headers
62
) as session:
63
async with session.get(cls.url, proxy=proxy) as response:
64
text = await response.text()
65
66
match = re.search(r'SNlM0e\":\"(.*?)\"', text)
67
if match:
68
snlm0e = match.group(1)
69
70
params = {
71
'bl': 'boq_assistant-bard-web-server_20230326.21_p0',
72
'_reqid': random.randint(1111, 9999),
73
'rt': 'c'
74
}
75
76
data = {
77
'at': snlm0e,
78
'f.req': json.dumps([None, json.dumps([[prompt]])])
79
}
80
81
intents = '.'.join([
82
'assistant',
83
'lamda',
84
'BardFrontendService'
85
])
86
87
async with session.post(
88
f'{cls.url}/_/BardChatUi/data/{intents}/StreamGenerate',
89
data=data,
90
params=params,
91
proxy=proxy
92
) as response:
93
response = await response.text()
94
response = json.loads(response.splitlines()[3])[0][2]
95
response = json.loads(response)[4][0][1][0]
96
return response
99
97
100
98
@classmethod
101
99
@property