Spaces:
Runtime error
Runtime error
File size: 6,336 Bytes
1813edc | 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | """
Conversation Session Manager - Track conversation history and context
Uses SQLite for lightweight persistence
"""
import sqlite3
import json
from datetime import datetime
from typing import Optional, List, Dict, Any
from pathlib import Path
import uuid
class SessionManager:
"""Manages conversation sessions and history"""
def __init__(self, db_path: str = "data/sessions.db"):
"""Initialize SQLite database for sessions"""
self.db_path = Path(db_path)
self.db_path.parent.mkdir(parents=True, exist_ok=True)
# Create tables if not exist
self._init_db()
def _init_db(self):
"""Initialize database schema"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Sessions table
cursor.execute("""
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
customer_id TEXT NOT NULL,
start_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
end_time TIMESTAMP,
status TEXT DEFAULT 'active',
message_count INTEGER DEFAULT 0,
context TEXT
)
""")
# Messages table
cursor.execute("""
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
intent TEXT,
sentiment TEXT,
kb_context TEXT,
FOREIGN KEY (session_id) REFERENCES sessions(session_id)
)
""")
conn.commit()
def create_session(self, customer_id: str) -> str:
"""
Create new conversation session
Returns:
session_id
"""
session_id = str(uuid.uuid4())
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("""
INSERT INTO sessions (session_id, customer_id, status)
VALUES (?, ?, ?)
""", (session_id, customer_id, 'active'))
conn.commit()
print(f"[SESSION] Created: {session_id[:8]}... for {customer_id}")
return session_id
def add_message(
self,
session_id: str,
role: str,
content: str,
intent: Optional[str] = None,
sentiment: Optional[str] = None,
kb_context: Optional[str] = None
) -> bool:
"""
Add message to session
Args:
session_id: Session ID
role: "user" or "assistant"
content: Message content
intent: Detected intent (optional)
sentiment: Sentiment label (optional)
kb_context: Retrieved KB context (optional)
"""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
# Insert message
cursor.execute("""
INSERT INTO messages
(session_id, role, content, intent, sentiment, kb_context)
VALUES (?, ?, ?, ?, ?, ?)
""", (session_id, role, content, intent, sentiment, kb_context))
# Update message count
cursor.execute("""
UPDATE sessions
SET message_count = message_count + 1
WHERE session_id = ?
""", (session_id,))
conn.commit()
return True
except Exception as e:
print(f"[SESSION] Add message error: {e}")
return False
def get_session_history(self, session_id: str) -> List[Dict[str, Any]]:
"""Retrieve all messages in a session"""
try:
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM messages
WHERE session_id = ?
ORDER BY timestamp ASC
""", (session_id,))
rows = cursor.fetchall()
return [dict(row) for row in rows]
except Exception as e:
print(f"[SESSION] Get history error: {e}")
return []
def close_session(self, session_id: str) -> bool:
"""Close a conversation session"""
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute("""
UPDATE sessions
SET status = 'closed', end_time = CURRENT_TIMESTAMP
WHERE session_id = ?
""", (session_id,))
conn.commit()
print(f"[SESSION] Closed: {session_id[:8]}...")
return True
except Exception as e:
print(f"[SESSION] Close error: {e}")
return False
def get_session_info(self, session_id: str) -> Optional[Dict[str, Any]]:
"""Get session metadata"""
try:
with sqlite3.connect(self.db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("""
SELECT * FROM sessions WHERE session_id = ?
""", (session_id,))
row = cursor.fetchone()
return dict(row) if row else None
except Exception as e:
print(f"[SESSION] Get info error: {e}")
return None
# Global session manager instance
session_manager = None
def get_session_manager() -> SessionManager:
"""Get or create global session manager"""
global session_manager
if session_manager is None:
session_manager = SessionManager()
return session_manager
|