-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
274 lines (244 loc) · 7.39 KB
/
main.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
package main
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"image/png"
"os"
"strings"
"time"
"github.com/eatmoreapple/openwechat"
openai "github.com/sashabaranov/go-openai"
)
// OpenaiWechat
type OpenaiWechat struct {
ChatBot *openwechat.Bot // chat bot
Openai *openai.Client // openai client
userDialogue map[string][]openai.ChatCompletionMessage // save user gialogue context
}
var singleton *OpenaiWechat
// firstUserDialogue
var firstUserDialogue = []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: "你是一个非常有帮助的助手",
},
{
Role: openai.ChatMessageRoleUser,
Content: "请问我怎么规划我的职业发展呢?",
},
{
Role: openai.ChatMessageRoleAssistant,
Content: `你好,我很高兴能帮助你。职业发展是一个非常重要的话题,你可以从以下几个方面考虑:
你的兴趣爱好和技能:你可以考虑你的兴趣爱好和技能,看看哪些职业与你的兴趣爱好和技能相匹配。这样可以让你在工作中感到更有成就感和满足感。
行业前景:你可以考虑一些行业的前景,看看哪些行业在未来几年内会有更好的发展前景。这样可以让你在职业发展中更有保障。
学历和培训:你可以考虑你的学历和培训,看看哪些职业需要更高的学历和培训。这样可以让你更好地规划你的职业发展。
希望这些建议能帮到你。你还有其他问题吗?`,
},
}
func init() {
//bot := openwechat.DefaultBot()
bot := openwechat.DefaultBot(openwechat.Desktop) // deskop mode,you can switch deskop mode if defualt can not login
// Register message handler function
bot.MessageHandler = func(msg *openwechat.Message) {
replyChatMsg(msg)
}
// Register login QR code callback
bot.UUIDCallback = openwechat.PrintlnQrcodeUrl
// login
if err := bot.Login(); err != nil {
fmt.Println(err)
return
}
client := openai.NewClient(os.Getenv("OPENAI_KEY")) // your openai key
//client := openai.NewClient("")
singleton = &OpenaiWechat{
Openai: client,
ChatBot: bot,
}
singleton.userDialogue = make(map[string][]openai.ChatCompletionMessage)
// lock goroutine, until an exception occurs or the user actively exits
bot.Block()
}
func main() {
}
// replyChatMsg
func replyChatMsg(msg *openwechat.Message) error {
if msg.IsSendByGroup() { // only accept group messages and send them to yourself
if !msg.IsAt() {
return nil
}
} else if !msg.IsSendByFriend() { // non-group messages only accept messages from your own friends
return nil
}
if msg.IsSendBySelf() { // self sent to self no reply
return nil
}
// only handle text messages
if msg.IsText() {
msg.Content = strings.Replace(msg.Content, "@GPT3.5 ", "", 1)
fmt.Println(msg.Content)
// simple match processing
if isImage, _ := isImageContent(msg.Content); isImage {
return replyImage(msg)
}
return replyText(msg)
}
return nil
}
// 图片生成校验
var imageMessage = []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: "你现在是一个语义识别助手,用户输入一个文本,你根据文本的内容来判断用户是不是想生成图片,是的话你就回复是,不是的话你就回复否,记住只能回复:是 或者 否",
},
{
Role: openai.ChatMessageRoleUser,
Content: "我想生成一张小花猫的图片",
},
{
Role: openai.ChatMessageRoleAssistant,
Content: "是",
},
{
Role: openai.ChatMessageRoleUser,
Content: "请问冬天下雨我该穿什么衣服",
},
{
Role: openai.ChatMessageRoleAssistant,
Content: "否",
},
}
// isImageConntent
func isImageContent(content string) (bool, error) {
temp := append(imageMessage, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: content,
})
result, err := callOpenaiChat(temp)
if err != nil {
fmt.Printf("isImageConntent callOpenaiChat error: %v\n", err)
return false, err
}
fmt.Printf("isImageContent result: %s", result)
if strings.TrimSpace(result) == "是" {
return true, nil
}
return false, nil
}
// replyImage
func replyImage(msg *openwechat.Message) error {
path, err := generateImage(msg)
if err != nil {
fmt.Printf("replyImage generateImage error: %v\n", err)
return err
}
img, err := os.Open(path)
if err != nil {
fmt.Printf("replyImage Open error: %v\n", err)
return err
}
defer img.Close()
msg.ReplyImage(img)
return nil
}
// replyText
func replyText(msg *openwechat.Message) error {
messages, err := genMessage(msg)
if err != nil {
return err
}
result, err := callOpenaiChat(messages)
if err != nil {
fmt.Println(err)
return err
}
msg.ReplyText(result)
addResultToMessage(result, msg)
return nil
}
// dialogue context max length
const maxLength = 33
// temporary folder to save pictures
const filePath = "./images/"
// genMessage
func genMessage(msg *openwechat.Message) ([]openai.ChatCompletionMessage, error) {
// TODO
if _, ok := singleton.userDialogue[msg.FromUserName]; !ok {
singleton.userDialogue[msg.FromUserName] = firstUserDialogue
} else if len(singleton.userDialogue[msg.FromUserName]) >= maxLength {
singleton.userDialogue[msg.FromUserName] = singleton.userDialogue[msg.FromUserName][2:]
}
element := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: msg.Content,
}
singleton.userDialogue[msg.FromUserName] = append(singleton.userDialogue[msg.FromUserName], element)
return singleton.userDialogue[msg.FromUserName], nil
}
// addResultToMessage
func addResultToMessage(result string, msg *openwechat.Message) error {
element := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: result,
}
singleton.userDialogue[msg.FromUserName] = append(singleton.userDialogue[msg.FromUserName], element)
return nil
}
// generateImage
func generateImage(msg *openwechat.Message) (string, error) {
ctx := context.Background()
// Sample image by link
reqUrl := openai.ImageRequest{
Prompt: msg.Content,
Size: openai.CreateImageSize512x512,
ResponseFormat: openai.CreateImageResponseFormatB64JSON,
N: 1,
}
respBase64, err := singleton.Openai.CreateImage(ctx, reqUrl)
if err != nil {
fmt.Printf("Image creation error: %v\n", err)
return "", err
}
imgBytes, err := base64.StdEncoding.DecodeString(respBase64.Data[0].B64JSON)
if err != nil {
fmt.Printf("Base64 decode error: %v\n", err)
return "", err
}
r := bytes.NewReader(imgBytes)
imgData, err := png.Decode(r)
if err != nil {
fmt.Printf("PNG decode error: %v\n", err)
return "", err
}
filePath := fmt.Sprintf("%s%d.png", filePath, time.Now().UnixMicro())
file, err := os.Create(filePath)
if err != nil {
fmt.Printf("File creation error: %v\n", err)
return "", err
}
defer file.Close()
if err := png.Encode(file, imgData); err != nil {
fmt.Printf("PNG encode error: %v\n", err)
return "", err
}
return filePath, nil
}
// callOpenaiChat
func callOpenaiChat(messages []openai.ChatCompletionMessage) (string, error) {
resp, err := singleton.Openai.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: messages,
MaxTokens: 512,
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return "", err
}
fmt.Println(resp.Choices[0].Message.Content)
return resp.Choices[0].Message.Content, nil
}