/
ctx.go
63 lines (51 loc) 路 1.26 KB
/
ctx.go
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
package api
import (
"github.com/asim/turbo/ai"
"github.com/asim/turbo/cache"
"github.com/asim/turbo/db"
)
// saveContext is what we need to maintain our context cache
func saveContext(msg Message, context []ai.Context) {
// we don't save the context of off-the-record data
if msg.OTR {
return
}
// append new prompt to
context = append(context, ai.Context{
Prompt: msg.Prompt,
Reply: msg.Reply,
})
// save the context
cache.Set(msg.ChatID, context)
}
// get the context from cache
func getContext(chatID string) []ai.Context {
// pull context from the cache
var context []ai.Context
cache.Get(chatID, &context)
return context
}
// buildContext from the database
func buildContext(chatID string, limit int) ([]ai.Context, error) {
var messages []Message
// get messages
res := db.Where("chat_id = ?", chatID).Order("created_at desc").Limit(limit).Find(&messages)
if err := res.Error; err != nil {
return nil, err
}
// reset the context
context := []ai.Context{}
// build new context
for i := len(messages); i > 0; i-- {
message := messages[i-1]
// do not use off the record messages
if message.OTR {
continue
}
context = append(context, ai.Context{
Prompt: message.Prompt,
Reply: message.Reply,
})
}
return context, nil
}