Update app.py
Browse files
app.py
CHANGED
|
@@ -2,62 +2,76 @@ from flask import Flask, render_template, request, jsonify
|
|
| 2 |
import sqlite3
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
| 10 |
def get_db_connection():
|
| 11 |
-
"""Tạo một kết nối SQLite mới cho mỗi request."""
|
| 12 |
conn = sqlite3.connect('chat_messages.db', check_same_thread=False)
|
| 13 |
-
conn.row_factory = sqlite3.Row
|
| 14 |
return conn
|
| 15 |
|
|
|
|
|
|
|
|
|
|
| 16 |
def getAnswer(role, text):
|
| 17 |
try:
|
| 18 |
conn = get_db_connection()
|
| 19 |
c = conn.cursor()
|
| 20 |
-
|
| 21 |
-
#
|
| 22 |
c.execute("INSERT INTO messages VALUES (?, ?)", (role, text))
|
| 23 |
conn.commit()
|
| 24 |
-
|
| 25 |
# Lấy 5 tin nhắn gần nhất
|
| 26 |
c.execute("SELECT * FROM messages ORDER BY rowid DESC LIMIT 5")
|
| 27 |
previous_messages = [{"role": row[0], "content": row[1]} for row in c.fetchall()]
|
| 28 |
-
|
|
|
|
| 29 |
# Đảo ngược thứ tự tin nhắn
|
| 30 |
previous_messages.reverse()
|
| 31 |
-
|
| 32 |
# Kiểm tra nếu chưa có system prompt thì thêm vào
|
| 33 |
if not any(msg["role"] == "system" for msg in previous_messages):
|
| 34 |
previous_messages.insert(0, {"role": "system", "content": system_prompt})
|
| 35 |
-
|
| 36 |
-
# Kết nối API OpenAI
|
| 37 |
-
client = OpenAI(base_url="http://localhost:8000/v1", api_key="ollama")
|
| 38 |
response = client.chat.completions.create(
|
| 39 |
model="llama3",
|
| 40 |
messages=previous_messages,
|
| 41 |
temperature=0.7,
|
| 42 |
)
|
| 43 |
-
|
| 44 |
bot_response = response.choices[0].message.content.strip()
|
| 45 |
-
|
| 46 |
# Lưu phản hồi của bot vào database
|
|
|
|
|
|
|
| 47 |
c.execute("INSERT INTO messages VALUES (?, ?)", ("assistant", bot_response))
|
| 48 |
conn.commit()
|
| 49 |
conn.close()
|
| 50 |
-
|
| 51 |
return bot_response
|
| 52 |
except Exception as e:
|
| 53 |
return f"Error: {str(e)}"
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
@app.route('/')
|
| 56 |
def index():
|
| 57 |
return render_template('index.html')
|
| 58 |
|
| 59 |
@app.route('/echo', methods=['POST'])
|
| 60 |
-
def
|
| 61 |
data = request.json
|
| 62 |
message = data.get('message', '')
|
| 63 |
return jsonify({'FROM': 'Echobot', 'MESSAGE': message})
|
|
@@ -79,4 +93,4 @@ def history():
|
|
| 79 |
return jsonify(previous_messages)
|
| 80 |
|
| 81 |
if __name__ == '__main__':
|
| 82 |
-
app.run(host=
|
|
|
|
| 2 |
import sqlite3
|
| 3 |
from openai import OpenAI
|
| 4 |
|
| 5 |
+
# Hàm tạo database nếu chưa tồn tại
|
| 6 |
+
def init_db():
|
| 7 |
+
with sqlite3.connect('chat_messages.db') as conn:
|
| 8 |
+
c = conn.cursor()
|
| 9 |
+
c.execute('''CREATE TABLE IF NOT EXISTS messages
|
| 10 |
+
(role TEXT, content TEXT)''')
|
| 11 |
+
conn.commit()
|
| 12 |
|
| 13 |
+
# Hàm lấy kết nối database
|
| 14 |
def get_db_connection():
|
|
|
|
| 15 |
conn = sqlite3.connect('chat_messages.db', check_same_thread=False)
|
|
|
|
| 16 |
return conn
|
| 17 |
|
| 18 |
+
# Prompt hệ thống
|
| 19 |
+
system_prompt = "You are name Oshi no Ko"
|
| 20 |
+
|
| 21 |
def getAnswer(role, text):
|
| 22 |
try:
|
| 23 |
conn = get_db_connection()
|
| 24 |
c = conn.cursor()
|
| 25 |
+
|
| 26 |
+
# Lưu tin nhắn vào database
|
| 27 |
c.execute("INSERT INTO messages VALUES (?, ?)", (role, text))
|
| 28 |
conn.commit()
|
| 29 |
+
|
| 30 |
# Lấy 5 tin nhắn gần nhất
|
| 31 |
c.execute("SELECT * FROM messages ORDER BY rowid DESC LIMIT 5")
|
| 32 |
previous_messages = [{"role": row[0], "content": row[1]} for row in c.fetchall()]
|
| 33 |
+
conn.close()
|
| 34 |
+
|
| 35 |
# Đảo ngược thứ tự tin nhắn
|
| 36 |
previous_messages.reverse()
|
| 37 |
+
|
| 38 |
# Kiểm tra nếu chưa có system prompt thì thêm vào
|
| 39 |
if not any(msg["role"] == "system" for msg in previous_messages):
|
| 40 |
previous_messages.insert(0, {"role": "system", "content": system_prompt})
|
| 41 |
+
|
| 42 |
+
# Kết nối API OpenAI
|
| 43 |
+
client = OpenAI(base_url="http://localhost:8000/v1", api_key="ollama")
|
| 44 |
response = client.chat.completions.create(
|
| 45 |
model="llama3",
|
| 46 |
messages=previous_messages,
|
| 47 |
temperature=0.7,
|
| 48 |
)
|
| 49 |
+
|
| 50 |
bot_response = response.choices[0].message.content.strip()
|
| 51 |
+
|
| 52 |
# Lưu phản hồi của bot vào database
|
| 53 |
+
conn = get_db_connection()
|
| 54 |
+
c = conn.cursor()
|
| 55 |
c.execute("INSERT INTO messages VALUES (?, ?)", ("assistant", bot_response))
|
| 56 |
conn.commit()
|
| 57 |
conn.close()
|
| 58 |
+
|
| 59 |
return bot_response
|
| 60 |
except Exception as e:
|
| 61 |
return f"Error: {str(e)}"
|
| 62 |
|
| 63 |
+
# Khởi tạo Flask app
|
| 64 |
+
app = Flask(__name__)
|
| 65 |
+
|
| 66 |
+
# Tạo database khi ứng dụng khởi động
|
| 67 |
+
init_db()
|
| 68 |
+
|
| 69 |
@app.route('/')
|
| 70 |
def index():
|
| 71 |
return render_template('index.html')
|
| 72 |
|
| 73 |
@app.route('/echo', methods=['POST'])
|
| 74 |
+
def echo():
|
| 75 |
data = request.json
|
| 76 |
message = data.get('message', '')
|
| 77 |
return jsonify({'FROM': 'Echobot', 'MESSAGE': message})
|
|
|
|
| 93 |
return jsonify(previous_messages)
|
| 94 |
|
| 95 |
if __name__ == '__main__':
|
| 96 |
+
app.run(host='0.0.0.0', port=7860, debug=True)
|