-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchathistory.go
196 lines (178 loc) · 6.26 KB
/
chathistory.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
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
package redis4rag
import (
"context"
"encoding/json"
"fmt"
"strconv"
"github.com/redis/go-redis/v9"
)
var (
ChatHistorySchema []*redis.FieldSchema = []*redis.FieldSchema{
ChatMessageUserId,
ChatMessageSessionId,
ChatMessageType,
ChatMessageContent,
ChatMessageTimestamp,
ChatMessageContentVec,
}
ChatMessageDefaultReturn = []redis.FTSearchReturn{
{FieldName: ChatMessageUserId.FieldName},
{FieldName: ChatMessageSessionId.FieldName},
{FieldName: ChatMessageType.FieldName},
{FieldName: ChatMessageContent.FieldName},
{FieldName: ChatMessageTimestamp.FieldName},
}
ChatMessageUserId = &redis.FieldSchema{
FieldName: "$.user_id", As: "user_id", FieldType: redis.SearchFieldTypeText, NoStem: true,
}
ChatMessageSessionId = &redis.FieldSchema{
FieldName: "$.session_id", As: "session_id", FieldType: redis.SearchFieldTypeText,
}
ChatMessageType = &redis.FieldSchema{
FieldName: "$.type", As: "type", FieldType: redis.SearchFieldTypeTag, Separator: ",",
}
ChatMessageContent = &redis.FieldSchema{
FieldName: "$.content", As: "content", FieldType: redis.SearchFieldTypeText,
}
ChatMessageTimestamp = &redis.FieldSchema{
FieldName: "$.timestamp", As: "timestamp", FieldType: redis.SearchFieldTypeNumeric, Sortable: true,
}
ChatMessageContentVec = &redis.FieldSchema{
FieldName: "$.content_vec", As: "content_vec", FieldType: redis.SearchFieldTypeVector,
VectorArgs: &redis.FTVectorArgs{
FlatOptions: &redis.FTFlatOptions{
Type: "FLOAT64",
Dim: 1024,
DistanceMetric: "COSINE",
},
},
}
)
type (
ChatHistory struct {
indexName string
docPrefix string
redisCli *redis.Client
}
ChatMessage struct {
Typ string `json:"type"`
UserId string `json:"user_id"`
SessionId string `json:"session_id"`
Content string `json:"content"`
Timestamp int64 `json:"timestamp"`
}
)
func (history *ChatHistory) Add(ctx context.Context, msg *ChatMessage, embedder Embedder) (err error) {
var vec []float64
if vec, err = embedder(ctx, msg.Content); err != nil {
return
}
var jsondata []byte
if jsondata, err = json.Marshal(msg); err != nil {
return
}
pipeline := history.redisCli.Pipeline()
// key pattern: {ChatHistory.DocPrefix}:{Message.UserId}:{Message.SessionId}
key := fmt.Sprintf("%s:%s:%s:%d", history.docPrefix, msg.UserId, msg.SessionId, msg.Timestamp)
pipeline.JSONSet(ctx, key, "$", string(jsondata))
pipeline.JSONSet(ctx, key, ChatMessageContentVec.FieldName, vec)
_, err = pipeline.Exec(ctx)
return err
}
func (history *ChatHistory) ListByUserId(ctx context.Context, from int64, userId string) (msgs []*ChatMessage, err error) {
return history.list(ctx, from, ChatMessageUserId.As, userId)
}
func (history *ChatHistory) ListBySessionId(ctx context.Context, from int64, sessionId string) (msgs []*ChatMessage, err error) {
return history.list(ctx, from, ChatMessageSessionId.As, sessionId)
}
func (history *ChatHistory) SearchWithUserId(ctx context.Context, from int64, userId string, text string, embedder Embedder) (msgs []*ChatMessage, err error) {
return history.search(ctx, from, ChatMessageUserId.As, userId, text, embedder)
}
func (history *ChatHistory) SearchWithSessionId(ctx context.Context, from int64, sessionId string, text string, embedder Embedder) (msgs []*ChatMessage, err error) {
return history.search(ctx, from, ChatMessageUserId.As, sessionId, text, embedder)
}
func (history *ChatHistory) DeleteByUserId(ctx context.Context, userId string) error {
return history.delete(ctx, ChatMessageUserId.As, userId)
}
func (history *ChatHistory) DeleteBySessionId(ctx context.Context, sessionId string) error {
return history.delete(ctx, ChatMessageSessionId.As, sessionId)
}
func (history *ChatHistory) list(ctx context.Context, from int64, key, val string) (msgs []*ChatMessage, err error) {
opts := &redis.FTSearchOptions{
Return: ChatMessageDefaultReturn,
DialectVersion: 2,
}
query := fmt.Sprintf("@%s:%s @%s:[%d inf]", key, val, ChatMessageTimestamp.As, from)
cmd := history.redisCli.FTSearchWithArgs(ctx, history.indexName, query, opts)
var result redis.FTSearchResult
if result, err = cmd.Result(); err == nil && result.Total > 0 {
for _, doc := range result.Docs {
msg := parseChatMessage(&doc)
msgs = append(msgs, msg)
}
}
return
}
func (history *ChatHistory) search(ctx context.Context, from int64, key, val string, text string, embedder Embedder) (msgs []*ChatMessage, err error) {
var vec []float64
if vec, err = embedder(ctx, text); err != nil {
return
}
opts := &redis.FTSearchOptions{
Return: ChatMessageDefaultReturn,
DialectVersion: 2,
Params: map[string]interface{}{"vec": []byte(vector2string(vec))},
SortBy: []redis.FTSearchSortBy{
{FieldName: "score", Asc: true},
},
}
filter := fmt.Sprintf("@%s:%s @%s:[%d inf]", key, val, ChatMessageTimestamp.As, from)
query := fmt.Sprintf("(%s)=>[KNN %d @%s $vec AS %s]", filter, 1, ChatMessageContentVec.As, "score")
cmd := history.redisCli.FTSearchWithArgs(ctx, history.indexName, query, opts)
var result redis.FTSearchResult
if result, err = cmd.Result(); err == nil && result.Total > 0 {
for _, doc := range result.Docs {
msg := parseChatMessage(&doc)
msgs = append(msgs, msg)
}
}
return
}
func (history *ChatHistory) delete(ctx context.Context, field string, value string) error {
var keypattern string
if field == ChatMessageSessionId.As {
keypattern = fmt.Sprintf("%s:*:%s:*", history.docPrefix, value)
} else if field == ChatMessageUserId.As {
keypattern = fmt.Sprintf("%s:%s:*", history.docPrefix, value)
} else {
panic("unkown field name")
}
keys, err := history.redisCli.Keys(ctx, keypattern).Result()
if err != nil {
return err
}
if len(keys) > 0 {
return history.redisCli.Del(ctx, keys...).Err()
} else {
return nil
}
}
func parseChatMessage(doc *redis.Document) *ChatMessage {
var chatMessage ChatMessage
for key, val := range doc.Fields {
switch key {
case ChatMessageUserId.FieldName:
chatMessage.UserId = val
case ChatMessageSessionId.FieldName:
chatMessage.SessionId = val
case ChatMessageType.FieldName:
chatMessage.Typ = val
case ChatMessageContent.FieldName:
chatMessage.Content = val
case ChatMessageTimestamp.FieldName:
timestamp, _ := strconv.ParseInt(val, 10, 64)
chatMessage.Timestamp = timestamp
}
}
return &chatMessage
}