59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
"""Conversation CRUD with unchanged response data."""
|
|
|
|
from .db import connect, now_str
|
|
|
|
|
|
WELCOME_TEXT = '您好!欢迎咨询柏悦物流智能客服,请问有什么可以帮您?输入订单号、入仓码或 Shipment ID 可查订单,或点击下方快捷选项。'
|
|
|
|
|
|
def new_chat():
|
|
now = now_str()
|
|
conn = connect()
|
|
cur = conn.cursor()
|
|
cur.execute('INSERT INTO chat_history(title, ctime, utime) VALUES (?,?,?)', ('新对话', now, now))
|
|
conv_id = cur.lastrowid
|
|
cur.execute('INSERT INTO messages(conv_id, role, content, ctime) VALUES (?,?,?,?)',
|
|
(conv_id, 'assistant', WELCOME_TEXT, now))
|
|
conn.commit()
|
|
conn.close()
|
|
return {'id': conv_id, 'welcome': WELCOME_TEXT}
|
|
|
|
|
|
def get_history():
|
|
conn = connect()
|
|
rows = conn.execute('SELECT id, title, ctime, COALESCE(utime, ctime) FROM chat_history ORDER BY COALESCE(utime, ctime) DESC, id DESC').fetchall()
|
|
conn.close()
|
|
return [{'id': r[0], 'title': r[1], 'ctime': r[2], 'utime': r[3]} for r in rows]
|
|
|
|
|
|
def get_messages(conv_id):
|
|
conn = connect()
|
|
rows = conn.execute('SELECT role, content, ctime FROM messages WHERE conv_id=? ORDER BY id DESC LIMIT 100', (conv_id,)).fetchall()
|
|
conn.close()
|
|
rows = rows[::-1]
|
|
return [{'role': r[0], 'content': r[1], 'ctime': r[2]} for r in rows]
|
|
|
|
|
|
def del_history(hid):
|
|
conn = connect()
|
|
cur = conn.cursor()
|
|
cur.execute('DELETE FROM human_messages WHERE session_id IN (SELECT id FROM human_sessions WHERE conv_id=?)', (hid,))
|
|
cur.execute('DELETE FROM human_sessions WHERE conv_id=?', (hid,))
|
|
cur.execute('DELETE FROM messages WHERE conv_id=?', (hid,))
|
|
cur.execute('DELETE FROM chat_history WHERE id=?', (hid,))
|
|
conn.commit()
|
|
conn.close()
|
|
return {'ok': True}
|
|
|
|
|
|
def clear_all():
|
|
conn = connect()
|
|
cur = conn.cursor()
|
|
cur.execute('DELETE FROM human_messages')
|
|
cur.execute('DELETE FROM human_sessions')
|
|
cur.execute('DELETE FROM messages')
|
|
cur.execute('DELETE FROM chat_history')
|
|
conn.commit()
|
|
conn.close()
|
|
return {'ok': True}
|