AchyuthGamer commited on
Commit
3e3d077
1 Parent(s): 42d6abd

Create Bard.py

Browse files
Files changed (1) hide show
  1. g4f/Provider/Providers/Bard.py +74 -0
g4f/Provider/Providers/Bard.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, requests, json, browser_cookie3, re, random
2
+ from ...typing import sha256, Dict, get_type_hints
3
+
4
+ url = 'https://bard.google.com'
5
+ model = ['Palm2']
6
+ supports_stream = False
7
+ needs_auth = True
8
+
9
+ def _create_completion(model: str, messages: list, stream: bool, **kwargs):
10
+ psid = {cookie.name: cookie.value for cookie in browser_cookie3.chrome(
11
+ domain_name='.google.com')}['__Secure-1PSID']
12
+
13
+ formatted = '\n'.join([
14
+ '%s: %s' % (message['role'], message['content']) for message in messages
15
+ ])
16
+ prompt = f'{formatted}\nAssistant:'
17
+
18
+ proxy = kwargs.get('proxy', False)
19
+ if proxy == False:
20
+ print('warning!, you did not give a proxy, a lot of countries are banned from Google Bard, so it may not work')
21
+
22
+ snlm0e = None
23
+ conversation_id = None
24
+ response_id = None
25
+ choice_id = None
26
+
27
+ client = requests.Session()
28
+ client.proxies = {
29
+ 'http': f'http://{proxy}',
30
+ 'https': f'http://{proxy}'} if proxy else None
31
+
32
+ client.headers = {
33
+ 'authority': 'bard.google.com',
34
+ 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
35
+ 'origin': 'https://bard.google.com',
36
+ 'referer': 'https://bard.google.com/',
37
+ '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',
38
+ 'x-same-domain': '1',
39
+ 'cookie': f'__Secure-1PSID={psid}'
40
+ }
41
+
42
+ snlm0e = re.search(r'SNlM0e\":\"(.*?)\"',
43
+ client.get('https://bard.google.com/').text).group(1) if not snlm0e else snlm0e
44
+
45
+ params = {
46
+ 'bl': 'boq_assistant-bard-web-server_20230326.21_p0',
47
+ '_reqid': random.randint(1111, 9999),
48
+ 'rt': 'c'
49
+ }
50
+
51
+ data = {
52
+ 'at': snlm0e,
53
+ 'f.req': json.dumps([None, json.dumps([[prompt], None, [conversation_id, response_id, choice_id]])])}
54
+
55
+ intents = '.'.join([
56
+ 'assistant',
57
+ 'lamda',
58
+ 'BardFrontendService'
59
+ ])
60
+
61
+ response = client.post(f'https://bard.google.com/_/BardChatUi/data/{intents}/StreamGenerate',
62
+ data=data, params=params)
63
+
64
+ chat_data = json.loads(response.content.splitlines()[3])[0][2]
65
+ if chat_data:
66
+ json_chat_data = json.loads(chat_data)
67
+
68
+ yield json_chat_data[0][0]
69
+
70
+ else:
71
+ yield 'error'
72
+
73
+ params = f'g4f.Providers.{os.path.basename(__file__)[:-3]} supports: ' + \
74
+ '(%s)' % ', '.join([f"{name}: {get_type_hints(_create_completion)[name].__name__}" for name in _create_completion.__code__.co_varnames[:_create_completion.__code__.co_argcount]])