-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
68 lines (51 loc) · 2.04 KB
/
app.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
65
66
67
68
from flask import Flask, request, render_template, redirect, url_for, redirect
import openai
import mysql.connector
from dotenv import load_dotenv
import os
load_dotenv()
app = Flask(__name__)
openai.api_key = os.getenv('OPENAI_API_KEY')
messages = [{"role": "system", "content": "あなたは助けになるアシスタントです。"}]
@app.route('/chat', methods=['GET'])
def get_chat():
conn = mysql.connector.connect(user='user', password='password', host='db', database='chat_db')
cursor = conn.cursor()
# チャットの履歴を取得
cursor.execute('SELECT user_message, bot_response FROM chat')
chat_history = cursor.fetchall()
cursor.close()
conn.close()
return render_template('chat.html', chat_history=chat_history)
@app.route('/chat', methods=['POST'])
def chat():
user_message = request.form['message']
messages.append({'role': 'user', 'content': user_message})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
bot_message = response.choices[0].message['content']
messages.append({'role': 'assistant', 'content': bot_message})
conn = mysql.connector.connect(user='user', password='password', host='db', database='chat_db')
cursor = conn.cursor()
cursor.execute('INSERT INTO chat (user_message, bot_response) VALUES (%s, %s)', (user_message, bot_message))
conn.commit()
cursor.close()
conn.close()
return redirect(url_for('get_chat'))
@app.route('/clear', methods=['POST'])
def clear_chat():
conn = mysql.connector.connect(user='user', password='password', host='db', database='chat_db')
cursor = conn.cursor()
cursor.execute('DELETE FROM chat')
conn.commit()
cursor.close()
conn.close()
# リセットmessages
messages.clear()
# 再度、初期のシステムメッセージを追加
messages.append({"role": "system", "content": "あなたは助けになるアシスタントです。"})
return redirect("/chat")
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)