29 lines
935 B
Python
29 lines
935 B
Python
"""
|
|
FILE: modules/web_api/llm/db/db_chat.py
|
|
"""
|
|
from typing import List, Dict, Any
|
|
from .connection import get_db_connection
|
|
|
|
def db_save_chat_message(session_id: str, role: str, content: str):
|
|
if not content:
|
|
return
|
|
conn = get_db_connection()
|
|
cursor = conn.cursor()
|
|
cursor.execute("""
|
|
INSERT INTO chat_messages (session_id, role, content, created_at)
|
|
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
|
""", (session_id, role, content))
|
|
conn.commit()
|
|
conn.close()
|
|
|
|
def db_get_chat_history(session_id: str, limit: int = 20) -> List[Dict[str, Any]]:
|
|
conn = get_db_connection()
|
|
cursor = conn.cursor()
|
|
cursor.execute("""
|
|
SELECT role, content FROM chat_messages
|
|
WHERE session_id = ?
|
|
ORDER BY id DESC LIMIT ?
|
|
""", (session_id, limit))
|
|
rows = cursor.fetchall()
|
|
conn.close()
|
|
return [{"role": r["role"], "content": r["content"]} for r in reversed(rows)] |