-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
71 lines (64 loc) · 1.51 KB
/
redis.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
package main
import (
"context"
"encoding/json"
"github.com/go-redis/redis/v8"
"github.com/sirupsen/logrus"
"time"
)
var Connection *redis.Client
func InitRedis() {
Connection = redis.NewClient(&redis.Options{
Addr: GlobalConfig.Redis.Address,
Password: GlobalConfig.Redis.Password,
DB: GlobalConfig.Redis.Database,
})
pong, err := Connection.Ping(context.Background()).Result()
if err != nil {
panic(err)
}
logrus.Info("initiate GoRedis Client success: ", pong)
}
func StoreRecord(key string, record *Record) error {
// Convert the Record struct to JSON
recordJSON, err := json.Marshal(record)
if err != nil {
return err
}
// Store the JSON in Redis
err = Connection.Set(context.Background(), key, recordJSON, 0).Err()
if err != nil {
return err
}
return nil
}
func RetrieveOrDefaultRecord(key string) (*Record, error) {
// Get the stored JSON from Redis
recordJSON, err := Connection.Get(context.Background(), key).Bytes()
if err == redis.Nil {
ori := Record{
Messages: []ChatMessage{
{
Role: "system",
Content: GlobalConfig.AI.InitialPrompts,
},
},
TotalTokens: 0,
LastRequest: time.UnixMicro(0),
Temperature: GlobalConfig.AI.DefaultTemperature,
}
return &ori, nil
} else if err != nil {
return nil, err
}
// Convert the JSON to a Record struct
var record Record
err = json.Unmarshal(recordJSON, &record)
if err != nil {
return nil, err
}
return &record, err
}
func DeleteRecord(key string) {
Connection.Del(context.Background(), key)
}