-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
conversation_manager.py
266 lines (232 loc) · 7.84 KB
/
conversation_manager.py
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
258
259
260
261
262
263
264
265
266
import os
import sqlite3
import uuid
class ConversationManager():
"""
Conversation manager
"""
def __init__(self, database: str = None) -> None:
"""
Initialize conversation manager
Parameters:
database (str): SQLite database file. If None, will use the environment
variable SQLITE_DATABASE.
"""
if database is None:
database = os.getenv('SQLITE_DATABASE')
if database is None or database == '':
database = 'conversations.db'
self.conn = sqlite3.connect(database)
self.conn.row_factory = sqlite3.Row
self._initialize_tables()
self.conversation_id = None
self.parent_id = None
def _initialize_tables(self) -> None:
"""
Initialize tables
"""
c = self.conn.cursor()
query = '''
CREATE TABLE IF NOT EXISTS messages (
id UUID PRIMARY KEY,
parent_id UUID,
conversation_id UUID,
message TEXT,
role TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
'''
c.execute(query)
query = '''
CREATE TABLE IF NOT EXISTS conversations (
id UUID PRIMARY KEY,
title TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
'''
c.execute(query)
self.conn.commit()
def set_conversation_id(self, conversation_id: uuid.UUID) -> None:
"""
Set conversation ID
Parameters:
conversation_id (uuid.UUID): conversation ID
"""
self.conversation_id = conversation_id
def add_conversation(self, title: str = None) -> uuid.UUID:
"""
Add conversation
Parameters:
title (str): title
Returns:
uuid.UUID: conversation ID
"""
c = self.conn.cursor()
conversation_id = uuid.uuid4()
query = '''
INSERT INTO conversations (id, title) VALUES (?, ?)
'''
if title == None:
title = 'New Chat'
c.execute(query, (str(conversation_id), title))
self.conn.commit()
self.conversation_id = conversation_id
return conversation_id
def add_message(self, message: str, role: str, parent_id: uuid.UUID = None, conversation_id: uuid.UUID = None, mode: str = 'openai') -> uuid.UUID:
"""
Add message
Parameters:
message (str): message
role (str): role (user/human or assistant)
parent_id (uuid.UUID): parent ID
conversation_id (uuid.UUID): conversation ID
Returns:
uuid.UUID: message ID
"""
assert role in ['user', 'human', 'assistant'], "Role must be 'user' or 'assistant'"
if mode == 'local' and role == 'user':
role = 'human'
c = self.conn.cursor()
message_id = uuid.uuid4()
if parent_id == None:
parent_id = self.parent_id
if conversation_id == None:
conversation_id = self.conversation_id
if conversation_id == None:
conversation_id = self.add_conversation()
query = '''
INSERT INTO messages (id, parent_id, conversation_id, message, role) VALUES (?, ?, ?, ?, ?)
'''
c.execute(query, (str(message_id), str(parent_id), str(conversation_id), message, role))
self.conn.commit()
self.parent_id = message_id
return message_id
def rename_conversation(self, conversation_id: uuid.UUID, title: str) -> None:
"""
Rename conversation
Parameters:
conversation_id (uuid.UUID): conversation ID
title (str): title
"""
c = self.conn.cursor()
query = '''
UPDATE conversations SET title = ? WHERE id = ?
'''
c.execute(query, (title, str(conversation_id)))
self.conn.commit()
def get_conversation(self, conversation_id: uuid.UUID) -> dict:
"""
Get conversation
Parameters:
conversation_id (uuid.UUID): conversation ID
Returns:
dict: conversation
"""
c = self.conn.cursor()
query = '''
SELECT * FROM messages WHERE conversation_id = ?
'''
c.execute(query, (str(conversation_id),))
conversation = c.fetchall()
# create a dictionary of messages, with column names as keys
conversation = [{column: message[i] for i, column in enumerate(message.keys())} for message in conversation]
# create a dictionary of messages, with message parent_ids as keys
messages = {message['parent_id']: message for message in conversation}
# create a list of ordered messages
ordered_conversation = []
try:
root_message = messages[None]
except:
root_message = messages['None']
ordered_conversation.append(root_message)
next_id = root_message['id']
while next_id in messages:
# find the next message in the chain by looking for the message with a parent_id equal to the current message's id
next_message = messages[next_id]
ordered_conversation.append(next_message)
next_id = next_message['id']
self.parent_id = next_id
return ordered_conversation
def get_messages(self, conversation_id: uuid.UUID) -> dict:
"""
Get conversation
Parameters:
conversation_id (uuid.UUID): conversation ID
Returns:
dict: conversation
"""
return self.get_conversation(conversation_id)
def get_conversations(self) -> list:
"""
Get conversations
Returns:
list: conversations
"""
c = self.conn.cursor()
query = '''
SELECT * FROM conversations
ORDER BY created_at DESC
'''
c.execute(query)
conversations = c.fetchall()
# create a dictionary of messages, with column names as keys
conversations = [{column: conversation[i] for i, column in enumerate(conversation.keys())} for conversation in conversations]
return conversations
def delete_conversation(self, conversation_id: uuid.UUID) -> None:
"""
Delete conversation
Parameters:
conversation_id (uuid.UUID): conversation ID
"""
c = self.conn.cursor()
query = '''
DELETE FROM conversations WHERE id = ?
'''
c.execute(query, (str(conversation_id),))
self.conn.commit()
def delete_message(self, message_id: uuid.UUID) -> None:
"""
Delete message
Parameters:
message_id (uuid.UUID): message ID
"""
c = self.conn.cursor()
query = '''
DELETE FROM messages WHERE id = ?
'''
c.execute(query, (str(message_id),))
self.conn.commit()
def delete_messages(self, conversation_id: uuid.UUID) -> None:
"""
Delete messages
Parameters:
conversation_id (uuid.UUID): conversation ID
"""
c = self.conn.cursor()
query = '''
DELETE FROM messages WHERE conversation_id = ?
'''
c.execute(query, (str(conversation_id),))
self.conn.commit()
def delete_all_messages(self) -> None:
"""
Delete all messages
"""
c = self.conn.cursor()
query = '''
DELETE FROM messages
'''
c.execute(query)
self.conn.commit()
def delete_all_conversations(self) -> None:
"""
Delete all conversations
"""
c = self.conn.cursor()
# delete all messages
self.delete_all_messages()
query = '''
DELETE FROM conversations
'''
c.execute(query)
self.conn.commit()