Skip to content

Commit 3f046f9

Browse files
committed
official openai api
1 parent fbfd5cc commit 3f046f9

File tree

4 files changed

+36
-36
lines changed

4 files changed

+36
-36
lines changed

client/html/index.html

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -110,10 +110,10 @@
110110
</div>
111111
<div class="field">
112112
<select name="model" id="model">
113-
<option value="text-gpt-0035-render-sha-0" selected>gpt-3.5-turbo</option>
114-
<option value="text-gpt-0040-render-sha-0">gpt-4</option>
115-
<option value="text-gpt-0035-render-sha-0301">gpt-3.5-turbo-0301</option>
116-
<option value="text-gpt-0004-render-sha-0314">gpt-4-0314</option>
113+
<option value="gpt-3.5-turbo" selected>gpt-3.5-turbo</option>
114+
<option value="gpt-4">gpt-4</option>
115+
<option value="gpt-3.5-turbo-0301">gpt-3.5-turbo-0301</option>
116+
<option value="gpt-4-0314">gpt-4-0314</option>
117117
</select>
118118
<!-- <span class="about">Model</span> -->
119119
</div>

config.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"site_config": {
3+
"host" : "0.0.0.0",
4+
"port" : 1338,
5+
"debug": false
6+
},
7+
"openai_key": "sk-..."
8+
}

run.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,11 @@
22
from server.website import Website
33
from server.backend import Backend_Api
44

5+
from json import load
6+
57
if __name__ == '__main__':
6-
config = {
7-
'host' : '0.0.0.0',
8-
'port' : 1337,
9-
'debug': False
10-
}
8+
config = load(open('config.json', 'r'))
9+
site_config = config['site_config']
1110

1211
site = Website(app)
1312
for route in site.routes:
@@ -17,14 +16,14 @@
1716
methods = site.routes[route]['methods'],
1817
)
1918

20-
backend_api = Backend_Api(app)
19+
backend_api = Backend_Api(app, config)
2120
for route in backend_api.routes:
2221
app.add_url_rule(
2322
route,
2423
view_func = backend_api.routes[route]['function'],
2524
methods = backend_api.routes[route]['methods'],
2625
)
2726

28-
print(f"Running on port {config['port']}")
29-
app.run(**config)
30-
print(f"Closing port {config['port']}")
27+
print(f"Running on port {site_config['port']}")
28+
app.run(**site_config)
29+
print(f"Closing port {site_config['port']}")

server/backend.py

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,15 @@
55
from datetime import datetime
66
from requests import get
77
from requests import post
8+
from json import loads
89

910
from server.config import special_instructions
1011

1112

1213
class Backend_Api:
13-
def __init__(self, app) -> None:
14+
def __init__(self, app, config: dict) -> None:
1415
self.app = app
16+
self.openai_key = config['openai_key']
1517
self.routes = {
1618
'/backend-api/v2/conversation': {
1719
'function': self._conversation,
@@ -26,10 +28,7 @@ def _conversation(self):
2628
_conversation = request.json['meta']['content']['conversation']
2729
prompt = request.json['meta']['content']['parts'][0]
2830
current_date = datetime.now().strftime("%Y-%m-%d")
29-
system_message = f'You are GPT-3.5 also known as ChatGPT, a large language model trained by OpenAI. Strictly follow the users instructions. Knowledge cutoff: 2021-09-01 Current date: {current_date}'
30-
31-
if '0040' in request.json['model']:
32-
system_message = f'You are GPT-4, newest generation of OpenAI GPT series. Strictly follow the users instructions. Knowledge cutoff: 2021-09-01 Current date: {current_date}'
31+
system_message = f'You are ChatGPT also known as ChatGPT, a large language model trained by OpenAI. Strictly follow the users instructions. Knowledge cutoff: 2021-09-01 Current date: {current_date}'
3332

3433
extra = []
3534
if internet_access:
@@ -53,28 +52,22 @@ def _conversation(self):
5352
extra + special_instructions[jailbreak] + \
5453
_conversation + [prompt]
5554

56-
timestamp = int(time() * 1000)
57-
headers = {
58-
'authority' : 'chatforai.com',
59-
'origin' : 'https://chatforai.com',
60-
'referer' : 'https://chatforai.com/',
61-
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
62-
}
63-
64-
gpt_resp = post('https://chatforai.com/api/generate', headers=headers, stream=True,
65-
data = dumps(separators=(',', ':'), obj={
66-
'messages': conversation,
67-
'time': timestamp,
68-
'pass': None,
69-
'sign': sha256(f'{timestamp}:{conversation[-1]["content"]}:k6zeE77ge7XF'.encode()).hexdigest(), 'key': ''}))
55+
gpt_resp = post('https://api.openai.com/v1/chat/completions',
56+
headers = {'Authorization': 'Bearer %s' % self.openai_key},
57+
json = {
58+
'model' : request.json['model'],
59+
'messages' : conversation,
60+
'stream' : True}, stream = True)
7061

7162
def stream():
72-
answer = ''
73-
for chunk in gpt_resp.iter_content(chunk_size=1024):
63+
for chunk in gpt_resp.iter_lines():
7464
try:
75-
answer += chunk.decode()
76-
yield chunk.decode()
65+
decoded_line = loads(chunk.decode("utf-8").split("data: ")[1])
66+
token = decoded_line["choices"][0]['delta'].get('content')
7767

68+
if token != None:
69+
yield token
70+
7871
except GeneratorExit:
7972
break
8073

0 commit comments

Comments
 (0)