-
Notifications
You must be signed in to change notification settings - Fork 411
/
gemini.go
84 lines (73 loc) · 1.95 KB
/
gemini.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
package chat
import (
"context"
"github.com/google/generative-ai-go/genai"
"github.com/pwh-pwh/aiwechat-vercel/config"
"github.com/pwh-pwh/aiwechat-vercel/db"
"google.golang.org/api/option"
)
const (
GeminiUser = "user"
GeminiBot = "model"
)
type GeminiChat struct {
BaseChat
key string
maxTokens int
}
func (s *GeminiChat) toDbMsg(msg *genai.Content) db.Msg {
text := msg.Parts[0].(genai.Text)
return db.Msg{
Role: msg.Role,
Msg: string(text),
}
}
func (s *GeminiChat) toChatMsg(msg db.Msg) *genai.Content {
return &genai.Content{Parts: []genai.Part{genai.Text(msg.Msg)}, Role: msg.Role}
}
func (s *GeminiChat) getModel(userID string) string {
if model, err := db.GetModel(userID, config.Bot_Type_Gemini); err == nil && model != "" {
return model
}
return "gemini-pro"
}
func (s *GeminiChat) chat(userId, msg string) string {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(s.key))
if err != nil {
return err.Error()
}
defer client.Close()
model := client.GenerativeModel(s.getModel(userId))
if s.maxTokens > 0 {
model.SetMaxOutputTokens(int32(s.maxTokens)) // 参数设置方法参考:https://github.com/google/generative-ai-go
}
// Initialize the chat
cs := model.StartChat()
var msgs = GetMsgListWithDb(config.Bot_Type_Gemini, userId, &genai.Content{
Parts: []genai.Part{
genai.Text(msg),
},
Role: GeminiUser,
}, s.toDbMsg, s.toChatMsg)
if len(msgs) > 1 {
cs.History = msgs[:len(msgs)-1]
}
resp, err := cs.SendMessage(ctx, genai.Text(msg))
if err != nil {
return err.Error()
}
text := resp.Candidates[0].Content.Parts[0].(genai.Text)
msgs = append(msgs, &genai.Content{Parts: []genai.Part{
text,
}, Role: GeminiBot})
SaveMsgListWithDb(config.Bot_Type_Gemini, userId, msgs, s.toDbMsg)
return string(text)
}
func (g *GeminiChat) Chat(userID string, msg string) string {
r, flag := DoAction(userID, msg)
if flag {
return r
}
return WithTimeChat(userID, msg, g.chat)
}