-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
101 lines (90 loc) · 3.44 KB
/
db.py
File metadata and controls
101 lines (90 loc) · 3.44 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
import sqlite3
from typing import Dict, List, Optional
def init_db():
"""Initialize SQLite database for conversations."""
conn = sqlite3.connect("conversations.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS conversations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT
)
""")
cursor.execute("""
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
conversation_id INTEGER,
role TEXT,
content TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (conversation_id) REFERENCES conversations(id)
)
""")
conn.commit()
conn.close()
def create_conversation(title: str) -> int:
"""Create a new conversation and return its ID."""
conn = sqlite3.connect("conversations.db")
cursor = conn.cursor()
cursor.execute("INSERT INTO conversations (title) VALUES (?)", (title,))
conversation_id = cursor.lastrowid
conn.commit()
conn.close()
return conversation_id
def add_message(conversation_id: int, role: str, content: str):
"""Add a message to a conversation."""
conn = sqlite3.connect("conversations.db")
cursor = conn.cursor()
cursor.execute(
"INSERT INTO messages (conversation_id, role, content) VALUES (?, ?, ?)",
(conversation_id, role, content)
)
conn.commit()
conn.close()
def get_conversation(conversation_id: int) -> Optional[Dict]:
"""Retrieve a conversation by ID."""
conn = sqlite3.connect("conversations.db")
cursor = conn.cursor()
cursor.execute("SELECT title FROM conversations WHERE id = ?", (conversation_id,))
title = cursor.fetchone()
if not title:
conn.close()
return None
title = title[0]
cursor.execute(
"SELECT role, content, timestamp FROM messages WHERE conversation_id = ? ORDER BY timestamp",
(conversation_id,)
)
messages = [{"role": row[0], "content": row[1], "timestamp": row[2]} for row in cursor.fetchall()]
conn.close()
return {"id": conversation_id, "title": title, "messages": messages}
def delete_conversation(conversation_id: int):
"""Delete a conversation and its messages."""
conn = sqlite3.connect("conversations.db")
cursor = conn.cursor()
cursor.execute("DELETE FROM messages WHERE conversation_id = ?", (conversation_id,))
cursor.execute("DELETE FROM conversations WHERE id = ?", (conversation_id,))
conn.commit()
conn.close()
def search_conversations(query: str) -> List[Dict]:
"""Search conversations by title or message content."""
conn = sqlite3.connect("conversations.db")
cursor = conn.cursor()
search_query = f"%{query}%"
cursor.execute("""
SELECT DISTINCT c.id, c.title
FROM conversations c
LEFT JOIN messages m ON c.id = m.conversation_id
WHERE c.title LIKE ? OR m.content LIKE ?
""", (search_query, search_query))
results = [{"id": row[0], "title": row[1]} for row in cursor.fetchall()]
conn.close()
return results
def get_all_conversations() -> List[Dict]:
"""Get all conversations ordered by most recent."""
conn = sqlite3.connect("conversations.db")
cursor = conn.cursor()
cursor.execute("SELECT id, title FROM conversations ORDER BY id DESC")
conversations = [{"id": row[0], "title": row[1]} for row in cursor.fetchall()]
conn.close()
return conversations