-
Notifications
You must be signed in to change notification settings - Fork 412
/
chat.go
341 lines (307 loc) · 8.54 KB
/
chat.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
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
package chat
import (
_ "errors"
"fmt"
"github.com/pwh-pwh/aiwechat-vercel/client"
"os"
"strconv"
"strings"
"time"
"github.com/google/generative-ai-go/genai"
"github.com/pwh-pwh/aiwechat-vercel/db"
"github.com/sashabaranov/go-openai"
"github.com/pwh-pwh/aiwechat-vercel/config"
"github.com/silenceper/wechat/v2/officialaccount/message"
)
var actionMap = map[string]func(param, userId string) string{
config.Wx_Command_Help: func(param, userId string) string {
return config.GetWxHelpReply()
},
config.Wx_Command_Gpt: func(param, userId string) string {
return SwitchUserBot(userId, config.Bot_Type_Gpt)
},
config.Wx_Command_Spark: func(param, userId string) string {
return SwitchUserBot(userId, config.Bot_Type_Spark)
},
config.Wx_Command_Qwen: func(param, userId string) string {
return SwitchUserBot(userId, config.Bot_Type_Qwen)
},
config.Wx_Command_Gemini: func(param, userId string) string {
return SwitchUserBot(userId, config.Bot_Type_Gemini)
},
config.Wx_Command_Prompt: SetPrompt,
config.Wx_Command_RmPrompt: RmPrompt,
config.Wx_Command_GetPrompt: GetPrompt,
config.Wx_Command_SetModel: SetModel,
config.Wx_Command_GetModel: GetModel,
config.Wx_Command_Clear: ClearMsg,
config.Wx_Todo_List: GetTodoList,
config.Wx_Todo_Add: AddTodo,
config.Wx_Todo_Del: DelTodo,
config.Wx_Coin: GetCoin,
}
func DoAction(userId, msg string) (r string, flag bool) {
action, param, flag := isAction(msg)
if flag {
f := actionMap[action]
r = f(param, userId)
}
return
}
func isAction(msg string) (string, string, bool) {
for key := range actionMap {
if strings.HasPrefix(msg, key) {
return msg[:len(key)], strings.TrimSpace(msg[len(key):]), true
}
}
return "", "", false
}
type BaseChat interface {
Chat(userID string, msg string) string
HandleMediaMsg(msg *message.MixMessage) string
}
type SimpleChat struct {
}
func (s SimpleChat) Chat(userID string, msg string) string {
panic("implement me")
}
func (s SimpleChat) HandleMediaMsg(msg *message.MixMessage) string {
switch msg.MsgType {
case message.MsgTypeImage:
return msg.PicURL
case message.MsgTypeEvent:
if msg.Event == message.EventSubscribe {
subText := config.GetWxSubscribeReply() + config.GetWxHelpReply()
if subText == "" {
subText = "哇,又有帅哥美女关注我啦😄"
}
return subText
} else if msg.Event == message.EventClick {
switch msg.EventKey {
case config.GetWxEventKeyChatGpt():
return SwitchUserBot(string(msg.FromUserName), config.Bot_Type_Gpt)
case config.GetWxEventKeyChatSpark():
return SwitchUserBot(string(msg.FromUserName), config.Bot_Type_Spark)
case config.GetWxEventKeyChatQwen():
return SwitchUserBot(string(msg.FromUserName), config.Bot_Type_Qwen)
default:
return fmt.Sprintf("unkown event key=%v", msg.EventKey)
}
} else {
return "不支持的类型"
}
default:
return "未支持的类型"
}
}
func SwitchUserBot(userId string, botType string) string {
if _, err := config.CheckBotConfig(botType); err != nil {
return err.Error()
}
db.SetValue(fmt.Sprintf("%v:%v", config.Bot_Type_Key, userId), botType, 0)
return config.GetBotWelcomeReply(botType)
}
func SetPrompt(param, userId string) string {
botType := config.GetUserBotType(userId)
switch botType {
case config.Bot_Type_Gpt:
db.SetPrompt(userId, botType, param)
case config.Bot_Type_Qwen:
db.SetPrompt(userId, botType, param)
case config.Bot_Type_Spark:
db.SetPrompt(userId, botType, param)
default:
return fmt.Sprintf("%s 不支持设置system prompt", botType)
}
return fmt.Sprintf("%s 设置prompt成功", botType)
}
func RmPrompt(param string, userId string) string {
botType := config.GetUserBotType(userId)
db.RemovePrompt(userId, botType)
return fmt.Sprintf("%s 删除prompt成功", botType)
}
func GetPrompt(param string, userId string) string {
botType := config.GetUserBotType(userId)
prompt, err := db.GetPrompt(userId, botType)
if err != nil {
return fmt.Sprintf("%s 当前未设置prompt", botType)
}
return fmt.Sprintf("%s 获取prompt成功,prompt:%s", botType, prompt)
}
func GetTodoList(param string, userId string) string {
list, err := db.GetTodoList(userId)
if err != nil {
return err.Error()
}
return list
}
func AddTodo(param, userId string) string {
err := db.AddTodoList(userId, param)
if err != nil {
return err.Error()
}
return "添加成功"
}
func DelTodo(param, userId string) string {
index, err := strconv.Atoi(param)
if err != nil {
return "传入索引必须为数字"
}
err = db.DelTodoList(userId, index)
if err != nil {
return err.Error()
}
return "删除todo成功"
}
func GetCoin(param, userId string) string {
coinPrice, err := client.GetCoinPrice(param)
if err != nil {
return err.Error()
}
return fmt.Sprintf("代币对:%s 价格:%s", coinPrice.Symbol, coinPrice.Price)
}
func SetModel(param, userId string) string {
botType := config.GetUserBotType(userId)
if botType == config.Bot_Type_Gpt || botType == config.Bot_Type_Gemini || botType == config.Bot_Type_Qwen {
if err := db.SetModel(userId, botType, param); err != nil {
return fmt.Sprintf("%s 设置model失败", botType)
}
return fmt.Sprintf("%s 设置model成功", botType)
}
return fmt.Sprintf("%s 不支持设置model", botType)
}
func GetModel(param string, userId string) string {
botType := config.GetUserBotType(userId)
model, err := db.GetModel(userId, botType)
if err != nil || model == "" {
return fmt.Sprintf("%s 当前未设置model", botType)
}
return fmt.Sprintf("%s 获取model成功,model:%s", botType, model)
}
func ClearMsg(param string, userId string) string {
botType := config.GetUserBotType(userId)
db.DeleteMsgList(botType, userId)
return fmt.Sprintf("%s 清除消息成功", botType)
}
// 加入超时控制
func WithTimeChat(userID, msg string, f func(userID, msg string) string) string {
if _, ok := config.Cache.Load(userID + msg); ok {
rAny, _ := config.Cache.Load(userID + msg)
r := rAny.(string)
config.Cache.Delete(userID + msg)
return r
}
resChan := make(chan string)
go func() {
resChan <- f(userID, msg)
}()
select {
case res := <-resChan:
return res
case <-time.After(5 * time.Second):
config.Cache.Store(userID+msg, <-resChan)
return ""
}
}
type ErrorChat struct {
errMsg string
}
func (e *ErrorChat) HandleMediaMsg(msg *message.MixMessage) string {
return e.errMsg
}
func (e *ErrorChat) Chat(userID string, msg string) string {
return e.errMsg
}
func GetChatBot(botType string) BaseChat {
if botType == "" {
botType = config.GetBotType()
}
var err error
botType, err = config.CheckBotConfig(botType)
if err != nil {
return &ErrorChat{
errMsg: err.Error(),
}
}
maxTokens := config.GetMaxTokens()
switch botType {
case config.Bot_Type_Gpt:
url := os.Getenv("GPT_URL")
if url == "" {
url = "https://api.openai.com/v1/"
}
return &SimpleGptChat{
token: config.GetGptToken(),
url: url,
maxTokens: maxTokens,
BaseChat: SimpleChat{},
}
case config.Bot_Type_Gemini:
return &GeminiChat{
BaseChat: SimpleChat{},
key: config.GetGeminiKey(),
maxTokens: maxTokens,
}
case config.Bot_Type_Spark:
config, _ := config.GetSparkConfig()
return &SparkChat{
BaseChat: SimpleChat{},
Config: config,
maxTokens: maxTokens,
}
case config.Bot_Type_Qwen:
config, _ := config.GetQwenConfig()
return &QwenChat{
BaseChat: SimpleChat{},
Config: config,
maxTokens: maxTokens,
}
default:
return &Echo{}
}
}
type ChatMsg interface {
openai.ChatCompletionMessage | QwenMessage | SparkMessage | *genai.Content
}
func GetMsgListWithDb[T ChatMsg](botType, userId string, msg T, f func(msg T) db.Msg, f2 func(msg db.Msg) T) []T {
var dbList []db.Msg
isSupportPrompt := config.IsSupportPrompt(botType)
if isSupportPrompt {
prompt, err := db.GetPrompt(userId, botType)
if err == nil && prompt != "" {
dbList = append(dbList, db.Msg{
Role: "system",
Msg: prompt,
})
}
}
if db.ChatDbInstance != nil {
list, err := db.ChatDbInstance.GetMsgList(botType, userId)
if err == nil {
// check is contain system prompt
if len(list) > 0 {
if list[0].Role == "system" {
list = list[1:]
}
}
dbList = append(dbList, list...)
}
}
dbList = append(dbList, f(msg))
r := make([]T, 0)
for _, msg := range dbList {
r = append(r, f2(msg))
}
return r
}
func SaveMsgListWithDb[T ChatMsg](botType, userId string, msgList []T, f func(msg T) db.Msg) {
if db.ChatDbInstance != nil {
go func() {
list := make([]db.Msg, 0)
for _, msg := range msgList {
list = append(list, f(msg))
}
db.ChatDbInstance.SetMsgList(botType, userId, list)
}()
}
}