-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
200 lines (166 loc) · 7.05 KB
/
database.py
File metadata and controls
200 lines (166 loc) · 7.05 KB
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
"""
Database module for Obelisk chat sessions
Handles SQLite operations for storing and retrieving chat sessions and messages.
"""
import uuid
import aiosqlite
from typing import List, Optional
# Database configuration
DATABASE_PATH = "chat_sessions.db"
class DatabaseManager:
def __init__(self, db_path: str = DATABASE_PATH):
self.db_path = db_path
async def init_database(self):
"""Initialize the database with required tables"""
async with aiosqlite.connect(self.db_path) as db:
# Create sessions table
await db.execute("""
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create messages table
await db.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,
FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE CASCADE
)
""")
# Create models table
await db.execute("""
CREATE TABLE IF NOT EXISTS models (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
is_tool_call BOOLEAN NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Create index for faster queries
await db.execute("""
CREATE INDEX IF NOT EXISTS idx_messages_session_timestamp
ON messages (session_id, timestamp DESC)
""")
await db.commit()
async def create_session(self) -> str:
"""Create a new chat session and return its UUID"""
session_id = str(uuid.uuid4())
async with aiosqlite.connect(self.db_path) as db:
await db.execute(
"INSERT INTO sessions (session_id) VALUES (?)",
(session_id,)
)
await db.commit()
return session_id
async def get_session_history(self, session_id: str, limit: int = 5) -> List[dict]:
"""Get the last N messages from a session for context"""
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute("""
SELECT role, content, timestamp FROM messages
WHERE session_id = ?
ORDER BY timestamp DESC
LIMIT ?
""", (session_id, limit))
rows = await cursor.fetchall()
# Reverse to get chronological order (oldest first)
messages = []
for row in reversed(list(rows)):
messages.append({
"role": row[0],
"content": row[1],
"timestamp": row[2]
})
return messages
async def add_message(self, session_id: str, role: str, content: str):
"""Add a message to a session and update session timestamp"""
async with aiosqlite.connect(self.db_path) as db:
# Add the message
await db.execute(
"INSERT INTO messages (session_id, role, content) VALUES (?, ?, ?)",
(session_id, role, content)
)
# Update session timestamp
await db.execute(
"UPDATE sessions SET updated_at = CURRENT_TIMESTAMP WHERE session_id = ?",
(session_id,)
)
await db.commit()
async def session_exists(self, session_id: str) -> bool:
"""Check if a session exists"""
async with aiosqlite.connect(self.db_path) as db:
cursor = await db.execute(
"SELECT 1 FROM sessions WHERE session_id = ? LIMIT 1",
(session_id,)
)
result = await cursor.fetchone()
return result is not None
async def get_session_info(self, session_id: str) -> Optional[dict]:
"""Get session information with full message history"""
async with aiosqlite.connect(self.db_path) as db:
# Get session info
session_cursor = await db.execute(
"SELECT session_id, created_at, updated_at FROM sessions WHERE session_id = ?",
(session_id,)
)
session_data = await session_cursor.fetchone()
if not session_data:
return None
# Get all messages
messages_cursor = await db.execute("""
SELECT role, content, timestamp FROM messages
WHERE session_id = ?
ORDER BY timestamp ASC
""", (session_id,))
messages = []
async for row in messages_cursor:
messages.append({
"role": row[0],
"content": row[1],
"timestamp": row[2]
})
return {
"session_id": session_data[0],
"created_at": session_data[1],
"updated_at": session_data[2],
"messages": messages
}
async def save_models(self, models: List[dict]):
"""Save or update models in the database"""
async with aiosqlite.connect(self.db_path) as db:
# Clear existing models
await db.execute("DELETE FROM models")
# Insert new models
for model in models:
await db.execute("""
INSERT INTO models (id, name, is_tool_call)
VALUES (?, ?, ?)
""", (
model['id'],
model['name'],
model.get('is_tool_call', False)
))
await db.commit()
async def get_models(self, tools_only: bool = False) -> List[dict]:
"""Get all models, optionally filtered by tool call capability"""
async with aiosqlite.connect(self.db_path) as db:
query = "SELECT id, name, is_tool_call FROM models"
params = ()
if tools_only:
query += " WHERE is_tool_call = 1"
query += " ORDER BY name"
cursor = await db.execute(query, params)
rows = await cursor.fetchall()
return [
{
"id": row[0],
"name": row[1],
"is_tool_call": bool(row[2])
}
for row in rows
]