-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversation.go
More file actions
387 lines (325 loc) · 10.1 KB
/
conversation.go
File metadata and controls
387 lines (325 loc) · 10.1 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
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package main
import (
"log"
"sync"
"time"
)
// ConversationNode represents a single message in the conversation tree
type ConversationNode struct {
MessageID int // Telegram message ID
ParentID int // Parent message ID (0 for root messages)
ChatID int64 // Chat ID where message was sent
UserID int // User who sent the message
Text string // Message text
Role string // "user" or "assistant"
SystemPrompt string // System prompt used for this conversation branch
Timestamp time.Time // When the message was created
ApproxSize int // Approximate size in bytes for cache management
}
// ConversationCache manages the conversation tree
type ConversationCache struct {
nodes map[int]*ConversationNode // Map of messageID -> node
maxCacheBytes int // Maximum cache size in bytes
currentBytes int // Current cache size in bytes
mu sync.RWMutex // Thread-safe access
}
var conversationCache *ConversationCache
func initConversationCache() {
conversationCache = &ConversationCache{
nodes: make(map[int]*ConversationNode),
maxCacheBytes: 20 * 1024 * 1024, // 20MB
currentBytes: 0,
}
log.Println("[INFO] Conversation cache initialized with 20MB limit")
// Initialize database table
err := initConversationDatabase()
if err != nil {
log.Printf("[ERROR] Failed to initialize conversation database: %v", err)
}
// Clean up old messages on startup
err = cleanupOldConversations()
if err != nil {
log.Printf("[ERROR] Failed to cleanup old conversations: %v", err)
}
// Load conversations from database
err = loadConversationsFromDatabase()
if err != nil {
log.Printf("[ERROR] Failed to load conversations from database: %v", err)
}
// Start periodic save every 5 minutes
go periodicSaveConversations()
}
// AddMessage adds a message to the conversation tree
func (cc *ConversationCache) AddMessage(node *ConversationNode) {
cc.mu.Lock()
defer cc.mu.Unlock()
// Calculate approximate size
node.ApproxSize = len(node.Text) + len(node.SystemPrompt) + 100 // +100 for metadata
// Add to cache
cc.nodes[node.MessageID] = node
cc.currentBytes += node.ApproxSize
// Check if we need to evict old messages
cc.evictIfNeeded()
log.Printf("[DEBUG] Added message %d to conversation cache (parent: %d, size: %d bytes, total: %d bytes)",
node.MessageID, node.ParentID, node.ApproxSize, cc.currentBytes)
}
// GetMessage retrieves a message from the cache
func (cc *ConversationCache) GetMessage(messageID int) (*ConversationNode, bool) {
cc.mu.RLock()
defer cc.mu.RUnlock()
node, exists := cc.nodes[messageID]
return node, exists
}
// BuildConversationHistory walks up the tree to collect the last N exchanges
// Returns messages in chronological order (oldest first)
func (cc *ConversationCache) BuildConversationHistory(messageID int, maxExchanges int) []ConversationNode {
cc.mu.RLock()
defer cc.mu.RUnlock()
var history []ConversationNode
currentID := messageID
// Walk up the tree collecting messages
for currentID != 0 && len(history) < maxExchanges*2 {
node, exists := cc.nodes[currentID]
if !exists {
break
}
// Prepend to maintain chronological order
history = append([]ConversationNode{*node}, history...)
currentID = node.ParentID
}
// Limit to last maxExchanges exchanges (user+assistant pairs)
if len(history) > maxExchanges*2 {
history = history[len(history)-maxExchanges*2:]
}
log.Printf("[DEBUG] Built conversation history: %d messages for messageID %d", len(history), messageID)
return history
}
// evictIfNeeded removes oldest messages when cache exceeds limit
func (cc *ConversationCache) evictIfNeeded() {
if cc.currentBytes <= cc.maxCacheBytes {
return
}
// Find oldest messages to evict
type nodeTime struct {
id int
time time.Time
size int
}
var nodes []nodeTime
for id, node := range cc.nodes {
nodes = append(nodes, nodeTime{id: id, time: node.Timestamp, size: node.ApproxSize})
}
// Sort by timestamp (oldest first)
for i := 0; i < len(nodes)-1; i++ {
for j := i + 1; j < len(nodes); j++ {
if nodes[i].time.After(nodes[j].time) {
nodes[i], nodes[j] = nodes[j], nodes[i]
}
}
}
// Evict oldest until we're under limit
bytesToFree := cc.currentBytes - (cc.maxCacheBytes * 3 / 4) // Free to 75% capacity
freed := 0
evicted := 0
for _, nt := range nodes {
if freed >= bytesToFree {
break
}
delete(cc.nodes, nt.id)
freed += nt.size
evicted++
}
cc.currentBytes -= freed
log.Printf("[INFO] Evicted %d old messages, freed %d bytes (current: %d bytes)",
evicted, freed, cc.currentBytes)
}
// GetSystemPrompt retrieves the system prompt from the conversation root
func (cc *ConversationCache) GetSystemPrompt(messageID int) string {
cc.mu.RLock()
defer cc.mu.RUnlock()
// Walk up to find the root or first message with system prompt
currentID := messageID
for currentID != 0 {
node, exists := cc.nodes[currentID]
if !exists {
break
}
if node.SystemPrompt != "" {
return node.SystemPrompt
}
currentID = node.ParentID
}
return ""
}
// Database persistence functions
const conversationRetentionDays = 7
// initConversationDatabase creates the conversation_messages table
func initConversationDatabase() error {
_, err := db.Exec(`CREATE TABLE IF NOT EXISTS conversation_messages (
message_id INTEGER PRIMARY KEY,
parent_id INTEGER NOT NULL,
chat_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
text TEXT NOT NULL,
role TEXT NOT NULL,
system_prompt TEXT,
timestamp TIMESTAMP NOT NULL
)`)
if err != nil {
return err
}
// Create index on timestamp for faster cleanup
_, err = db.Exec(`CREATE INDEX IF NOT EXISTS idx_conversation_timestamp
ON conversation_messages(timestamp)`)
return err
}
// cleanupOldConversations removes messages older than retention period
func cleanupOldConversations() error {
cutoffTime := time.Now().Add(-conversationRetentionDays * 24 * time.Hour)
result, err := db.Exec("DELETE FROM conversation_messages WHERE timestamp < ?", cutoffTime)
if err != nil {
return err
}
rowsAffected, _ := result.RowsAffected()
if rowsAffected > 0 {
log.Printf("[INFO] Cleaned up %d old conversation messages (older than %d days)",
rowsAffected, conversationRetentionDays)
}
return nil
}
// saveConversationsToDatabase saves current cache to database
func saveConversationsToDatabase() error {
if conversationCache == nil {
return nil
}
conversationCache.mu.RLock()
defer conversationCache.mu.RUnlock()
// Begin transaction for better performance
tx, err := db.Begin()
if err != nil {
return err
}
defer tx.Rollback()
// Clear existing data (we'll save the entire current state)
_, err = tx.Exec("DELETE FROM conversation_messages")
if err != nil {
return err
}
// Insert all current nodes
stmt, err := tx.Prepare(`INSERT INTO conversation_messages
(message_id, parent_id, chat_id, user_id, text, role, system_prompt, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
if err != nil {
return err
}
defer stmt.Close()
count := 0
for _, node := range conversationCache.nodes {
_, err = stmt.Exec(
node.MessageID,
node.ParentID,
node.ChatID,
node.UserID,
node.Text,
node.Role,
node.SystemPrompt,
node.Timestamp,
)
if err != nil {
return err
}
count++
}
// Commit transaction
err = tx.Commit()
if err != nil {
return err
}
log.Printf("[DEBUG] Saved %d conversation messages to database", count)
// Cleanup old messages after save
return cleanupOldConversations()
}
// loadConversationsFromDatabase loads conversations from database into cache
func loadConversationsFromDatabase() error {
if conversationCache == nil {
return nil
}
rows, err := db.Query(`SELECT message_id, parent_id, chat_id, user_id, text, role,
system_prompt, timestamp FROM conversation_messages ORDER BY timestamp ASC`)
if err != nil {
return err
}
defer rows.Close()
count := 0
totalBytes := 0
uniqueChats := make(map[int64]bool)
uniqueUsers := make(map[int]bool)
oldestTime := time.Now()
newestTime := time.Time{}
for rows.Next() {
var node ConversationNode
err = rows.Scan(
&node.MessageID,
&node.ParentID,
&node.ChatID,
&node.UserID,
&node.Text,
&node.Role,
&node.SystemPrompt,
&node.Timestamp,
)
if err != nil {
log.Printf("[ERROR] Failed to scan conversation row: %v", err)
continue
}
// Calculate size
node.ApproxSize = len(node.Text) + len(node.SystemPrompt) + 100
// Track stats
totalBytes += node.ApproxSize
uniqueChats[node.ChatID] = true
uniqueUsers[node.UserID] = true
if node.Timestamp.Before(oldestTime) {
oldestTime = node.Timestamp
}
if node.Timestamp.After(newestTime) {
newestTime = node.Timestamp
}
// Add to cache (without locking since we're in init)
conversationCache.mu.Lock()
conversationCache.nodes[node.MessageID] = &node
conversationCache.currentBytes += node.ApproxSize
conversationCache.mu.Unlock()
count++
}
if count > 0 {
cacheUsagePercent := float64(totalBytes) / float64(conversationCache.maxCacheBytes) * 100
log.Printf("[INFO] Loaded %d conversation messages from database", count)
log.Printf("[INFO] - Cache usage: %d bytes (%.1f%% of 20MB limit)", totalBytes, cacheUsagePercent)
log.Printf("[INFO] - Unique chats: %d, unique users: %d", len(uniqueChats), len(uniqueUsers))
log.Printf("[INFO] - Time range: %s to %s",
oldestTime.Format("2006-01-02 15:04"),
newestTime.Format("2006-01-02 15:04"))
}
return rows.Err()
}
// periodicSaveConversations saves cache to database every 5 minutes
func periodicSaveConversations() {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for range ticker.C {
err := saveConversationsToDatabase()
if err != nil {
log.Printf("[ERROR] Failed to save conversations to database: %v", err)
}
}
}
// SaveConversationsOnShutdown should be called before the bot exits
func SaveConversationsOnShutdown() {
log.Println("[INFO] Saving conversations to database before shutdown...")
err := saveConversationsToDatabase()
if err != nil {
log.Printf("[ERROR] Failed to save conversations on shutdown: %v", err)
} else {
log.Println("[INFO] Conversations saved successfully")
}
}