-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.py
64 lines (48 loc) · 1.73 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import io
import openai
from flask import Flask, request, render_template
server = Flask(__name__, static_url_path="/static")
N = 10
class Conversation:
def __init__(self, prompt, num_of_round):
self.prompt = prompt
self.num_of_round = num_of_round
self.messages = []
self.messages.append({"role": "system", "content": self.prompt})
def ask(self, question):
try:
self.messages.append({"role": "user", "content": question})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=self.messages,
temperature=0.5,
max_tokens=2048,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0,
)
except Exception as e:
print(e)
return e
message = response["choices"][0]["message"]["content"]
self.messages.append({"role": "assistant", "content": message})
if len(self.messages) > self.num_of_round * 2 + 1:
del self.messages[1:3]
return message
converstation = Conversation(prompt="You are a helpful assistant.", num_of_round=N)
@server.route("/chat")
def home():
return render_template("chat.html")
@server.route("/chat/get")
def get_bot_response():
user_text = request.args.get("msg")
return str(converstation.ask(user_text))
@server.route("/chat/upload", methods=["POST"])
def upload():
audio = request.files['audio']
audio.save("tmp.wav")
with open("tmp.wav", "rb") as f:
text = openai.Audio.transcribe("whisper-1", f)["text"]
return {"text": text}
if __name__ == "__main__":
server.run(debug=False, host="0.0.0.0", port=8088)