Spaces:
Sleeping
Sleeping
File size: 6,980 Bytes
a8a231d |
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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
"""Session management utilities for the content generation agent."""
import sqlite3
from datetime import datetime
from pathlib import Path
from typing import Any
from src.profile import PROFILE_DIR
def get_session_db_path() -> Path:
"""Get the path to the session database.
Returns:
Path to sessions.db
"""
return PROFILE_DIR / "sessions.db"
def list_sessions(app_name: str = "scientific-content-agent") -> list[dict[str, Any]]:
"""List all sessions in the database.
Args:
app_name: Application name to filter sessions
Returns:
List of session dictionaries with metadata
"""
db_path = get_session_db_path()
if not db_path.exists():
return []
try:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Query sessions table
# Note: ADK's DatabaseSessionService uses these columns
query = """
SELECT
session_id,
app_name,
user_id,
created_at,
updated_at
FROM sessions
WHERE app_name = ?
ORDER BY updated_at DESC
"""
cursor.execute(query, (app_name,))
rows = cursor.fetchall()
sessions = []
for row in rows:
session = {
"session_id": row["session_id"],
"app_name": row["app_name"],
"user_id": row["user_id"],
"created_at": row["created_at"],
"updated_at": row["updated_at"],
}
# Count messages in this session
cursor.execute(
"""
SELECT COUNT(*) as count
FROM messages
WHERE session_id = ?
""",
(row["session_id"],),
)
message_row = cursor.fetchone()
session["message_count"] = message_row["count"] if message_row else 0
sessions.append(session)
conn.close()
return sessions
except sqlite3.Error as e:
print(f"Database error: {e}")
return []
def delete_session(session_id: str, app_name: str = "scientific-content-agent") -> dict[str, Any]:
"""Delete a session and its messages.
Args:
session_id: The session ID to delete
app_name: Application name for verification
Returns:
Dictionary with status and message
"""
db_path = get_session_db_path()
if not db_path.exists():
return {"status": "error", "message": "Session database not found"}
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Verify session exists and belongs to this app
cursor.execute(
"""
SELECT session_id
FROM sessions
WHERE session_id = ? AND app_name = ?
""",
(session_id, app_name),
)
if not cursor.fetchone():
conn.close()
return {"status": "error", "message": f"Session '{session_id}' not found"}
# Delete messages first (foreign key constraint)
cursor.execute("DELETE FROM messages WHERE session_id = ?", (session_id,))
messages_deleted = cursor.rowcount
# Delete session
cursor.execute("DELETE FROM sessions WHERE session_id = ?", (session_id,))
session_deleted = cursor.rowcount
conn.commit()
conn.close()
if session_deleted > 0:
return {
"status": "success",
"message": f"Deleted session '{session_id}' and {messages_deleted} message(s)",
}
return {"status": "error", "message": "Failed to delete session"}
except sqlite3.Error as e:
return {"status": "error", "message": f"Database error: {str(e)}"}
def get_session_info(
session_id: str, app_name: str = "scientific-content-agent"
) -> dict[str, Any] | None:
"""Get detailed information about a specific session.
Args:
session_id: The session ID to query
app_name: Application name for verification
Returns:
Dictionary with session details or None if not found
"""
db_path = get_session_db_path()
if not db_path.exists():
return None
try:
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get session info
cursor.execute(
"""
SELECT
session_id,
app_name,
user_id,
created_at,
updated_at
FROM sessions
WHERE session_id = ? AND app_name = ?
""",
(session_id, app_name),
)
row = cursor.fetchone()
if not row:
conn.close()
return None
session = dict(row)
# Get messages
cursor.execute(
"""
SELECT
content,
role,
created_at
FROM messages
WHERE session_id = ?
ORDER BY created_at ASC
""",
(session_id,),
)
messages = [dict(msg) for msg in cursor.fetchall()]
session["messages"] = messages
session["message_count"] = len(messages)
conn.close()
return session
except sqlite3.Error as e:
print(f"Database error: {e}")
return None
def format_session_list(sessions: list[dict[str, Any]]) -> str:
"""Format sessions list as a pretty table.
Args:
sessions: List of session dictionaries
Returns:
Formatted string table
"""
if not sessions:
return "No sessions found."
# Calculate column widths
max_user_len = max((len(s.get("user_id", "")) for s in sessions), default=10)
max_user_len = max(max_user_len, 10) # Minimum width
output = []
output.append("\n" + "=" * 100)
output.append(
f"{'Session ID':<40} {'User':<{max_user_len}} {'Messages':<10} {'Last Updated':<20}"
)
output.append("=" * 100)
for session in sessions:
session_id = session["session_id"][:37] + "..." # Truncate long UUIDs
user_id = session.get("user_id", "Unknown")[:max_user_len]
message_count = str(session.get("message_count", 0))
updated_at = session.get("updated_at", "Unknown")
# Parse timestamp if it's in ISO format
try:
if "T" in updated_at:
dt = datetime.fromisoformat(updated_at.replace("Z", "+00:00"))
updated_at = dt.strftime("%Y-%m-%d %H:%M:%S")
except (ValueError, AttributeError):
pass
output.append(
f"{session_id:<40} {user_id:<{max_user_len}} {message_count:<10} {updated_at:<20}"
)
output.append("=" * 100 + "\n")
return "\n".join(output)
|