返回提交历史
Added
gpt4free/forefront/README.md
+13
-0
Added
gpt4free/forefront/__init__.py
+194
-0
Added
gpt4free/forefront/typing.py
+25
-0
XFEstudio/gpt4free
forefront
b4aadbba
代码差异
3 个文件
+232
-0
@@ -0,0 +1,13 @@
1
### Example: `forefront` (use like openai pypi package) <a name="example-forefront"></a>
2
3
```python
4
from gpt4free import forefront
5
# create an account
6
token = forefront.Account.create(logging=False)
7
print(token)
8
# get a response
9
for response in forefront.StreamingCompletion.create(token=token,
10
prompt='hello world', model='gpt-4'):
11
print(response.completion.choices[0].text, end='')
12
print("")
13
```
@@ -0,0 +1,194 @@
1
from json import loads
2
from re import findall
3
from time import time, sleep
4
from typing import Generator, Optional
5
from uuid import uuid4
6
7
from fake_useragent import UserAgent
8
from requests import post
9
from pymailtm import MailTm, Message
10
from tls_client import Session
11
12
from .typing import ForeFrontResponse
13
14
15
class Account:
16
@staticmethod
17
def create(proxy: Optional[str] = None, logging: bool = False):
18
proxies = {'http': 'http://' + proxy, 'https': 'http://' + proxy} if proxy else False
19
20
start = time()
21
22
mail_client = MailTm().get_account()
23
mail_address = mail_client.address
24
25
client = Session(client_identifier='chrome110')
26
client.proxies = proxies
27
client.headers = {
28
'origin': 'https://accounts.forefront.ai',
29
'user-agent': UserAgent().random,
30
}
31
32
response = client.post(
33
'https://clerk.forefront.ai/v1/client/sign_ups?_clerk_js_version=4.38.4',
34
data={'email_address': mail_address},
35
)
36
37
try:
38
trace_token = response.json()['response']['id']
39
if logging:
40
print(trace_token)
41
except KeyError:
42
return 'Failed to create account!'
43
44
response = client.post(
45
f'https://clerk.forefront.ai/v1/client/sign_ups/{trace_token}/prepare_verification?_clerk_js_version=4.38.4',
46
data={
47
'strategy': 'email_link',
48
'redirect_url': 'https://accounts.forefront.ai/sign-up/verify'
49
},
50
)
51
52
if logging:
53
print(response.text)
54
55
if 'sign_up_attempt' not in response.text:
56
return 'Failed to create account!'
57
58
while True:
59
sleep(1)
60
new_message: Message = mail_client.wait_for_message()
61
if logging:
62
print(new_message.data['id'])
63
64
verification_url = findall(r'https:\/\/clerk\.forefront\.ai\/v1\/verify\?token=\w.+', new_message.text)[0]
65
66
if verification_url:
67
break
68
69
if logging:
70
print(verification_url)
71
72
response = client.get(verification_url)
73
74
response = client.get('https://clerk.forefront.ai/v1/client?_clerk_js_version=4.38.4')
75
76
token = response.json()['response']['sessions'][0]['last_active_token']['jwt']
77
78
with open('accounts.txt', 'a') as f:
79
f.write(f'{mail_address}:{token}\n')
80
81
if logging:
82
print(time() - start)
83
84
return token
85
86
87
class StreamingCompletion:
88
@staticmethod
89
def create(
90
token=None,
91
chat_id=None,
92
prompt='',
93
action_type='new',
94
default_persona='607e41fe-95be-497e-8e97-010a59b2e2c0', # default
95
model='gpt-4',
96
proxy=None
97
) -> Generator[ForeFrontResponse, None, None]:
98
if not token:
99
raise Exception('Token is required!')
100
if not chat_id:
101
chat_id = str(uuid4())
102
103
proxies = { 'http': 'http://' + proxy, 'https': 'http://' + proxy } if proxy else None
104
105
headers = {
106
'authority': 'chat-server.tenant-forefront-default.knative.chi.coreweave.com',
107
'accept': '*/*',
108
'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
109
'authorization': 'Bearer ' + token,
110
'cache-control': 'no-cache',
111
'content-type': 'application/json',
112
'origin': 'https://chat.forefront.ai',
113
'pragma': 'no-cache',
114
'referer': 'https://chat.forefront.ai/',
115
'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
116
'sec-ch-ua-mobile': '?0',
117
'sec-ch-ua-platform': '"macOS"',
118
'sec-fetch-dest': 'empty',
119
'sec-fetch-mode': 'cors',
120
'sec-fetch-site': 'cross-site',
121
'user-agent': UserAgent().random,
122
}
123
124
json_data = {
125
'text': prompt,
126
'action': action_type,
127
'parentId': chat_id,
128
'workspaceId': chat_id,
129
'messagePersona': default_persona,
130
'model': model,
131
}
132
133
for chunk in post(
134
'https://chat-server.tenant-forefront-default.knative.chi.coreweave.com/chat',
135
headers=headers,
136
proxies=proxies,
137
json=json_data,
138
stream=True,
139
).iter_lines():
140
if b'finish_reason":null' in chunk:
141
data = loads(chunk.decode('utf-8').split('data: ')[1])
142
token = data['choices'][0]['delta'].get('content')
143
144
if token is not None:
145
yield ForeFrontResponse(
146
**{
147
'id': chat_id,
148
'object': 'text_completion',
149
'created': int(time()),
150
'text': token,
151
'model': model,
152
'choices': [{'text': token, 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}],
153
'usage': {
154
'prompt_tokens': len(prompt),
155
'completion_tokens': len(token),
156
'total_tokens': len(prompt) + len(token),
157
},
158
}
159
)
160
161
162
class Completion:
163
@staticmethod
164
def create(
165
token=None,
166
chat_id=None,
167
prompt='',
168
action_type='new',
169
default_persona='607e41fe-95be-497e-8e97-010a59b2e2c0', # default
170
model='gpt-4',
171
proxy=None
172
) -> ForeFrontResponse:
173
text = ''
174
final_response = None
175
for response in StreamingCompletion.create(
176
token=token,
177
chat_id=chat_id,
178
prompt=prompt,
179
action_type=action_type,
180
default_persona=default_persona,
181
model=model,
182
proxy=proxy
183
):
184
if response:
185
final_response = response
186
text += response.text
187
188
if final_response:
189
final_response.text = text
190
else:
191
raise Exception('Unable to get the response, Please try again')
192
193
return final_response
194
@@ -0,0 +1,25 @@
1
from typing import Any, List
2
from pydantic import BaseModel
3
4
5
class Choice(BaseModel):
6
text: str
7
index: int
8
logprobs: Any
9
finish_reason: str
10
11
12
class Usage(BaseModel):
13
prompt_tokens: int
14
completion_tokens: int
15
total_tokens: int
16
17
18
class ForeFrontResponse(BaseModel):
19
id: str
20
object: str
21
created: int
22
model: str
23
choices: List[Choice]
24
usage: Usage
25
text: str