forked from eryajf/chatgpt-dingtalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
315 lines (284 loc) · 8.5 KB
/
context.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
package chatgpt
import (
"bytes"
"context"
"encoding/base64"
"encoding/gob"
"errors"
"fmt"
"github.com/eryajf/chatgpt-dingtalk/pkg/dingbot"
"github.com/pandodao/tokenizer-go"
"image/png"
"os"
"strings"
"time"
"github.com/eryajf/chatgpt-dingtalk/public"
openai "github.com/sashabaranov/go-openai"
)
var (
DefaultAiRole = "AI"
DefaultHumanRole = "Human"
DefaultCharacter = []string{"helpful", "creative", "clever", "friendly", "lovely", "talkative"}
DefaultBackground = "The following is a conversation with AI assistant. The assistant is %s"
DefaultPreset = "\n%s: 你好,让我们开始愉快的谈话!\n%s: 我是 AI assistant ,请问你有什么问题?"
)
type (
ChatContext struct {
background string // 对话背景
preset string // 预设对话
maxSeqTimes int // 最大对话次数
aiRole *role // AI角色
humanRole *role // 人类角色
old []conversation // 旧对话
restartSeq string // 重新开始对话的标识
startSeq string // 开始对话的标识
seqTimes int // 对话次数
maintainSeqTimes bool // 是否维护对话次数 (自动移除旧对话)
}
ChatContextOption func(*ChatContext)
conversation struct {
Role *role
Prompt string
}
role struct {
Name string
}
)
func NewContext(options ...ChatContextOption) *ChatContext {
ctx := &ChatContext{
aiRole: &role{Name: DefaultAiRole},
humanRole: &role{Name: DefaultHumanRole},
background: "",
maxSeqTimes: 1000,
preset: "",
old: []conversation{},
seqTimes: 0,
restartSeq: "\n" + DefaultHumanRole + ": ",
startSeq: "\n" + DefaultAiRole + ": ",
maintainSeqTimes: false,
}
for _, option := range options {
option(ctx)
}
return ctx
}
// PollConversation 移除最旧的一则对话
func (c *ChatContext) PollConversation() {
c.old = c.old[1:]
c.seqTimes--
}
// ResetConversation 重置对话
func (c *ChatContext) ResetConversation(userid string) {
public.UserService.ClearUserSessionContext(userid)
}
// SaveConversation 保存对话
func (c *ChatContext) SaveConversation(userid string) error {
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
err := enc.Encode(c.old)
if err != nil {
return err
}
public.UserService.SetUserSessionContext(userid, buffer.String())
return nil
}
// LoadConversation 加载对话
func (c *ChatContext) LoadConversation(userid string) error {
dec := gob.NewDecoder(strings.NewReader(public.UserService.GetUserSessionContext(userid)))
err := dec.Decode(&c.old)
if err != nil {
return err
}
c.seqTimes = len(c.old)
return nil
}
func (c *ChatContext) SetHumanRole(role string) {
c.humanRole.Name = role
c.restartSeq = "\n" + c.humanRole.Name + ": "
}
func (c *ChatContext) SetAiRole(role string) {
c.aiRole.Name = role
c.startSeq = "\n" + c.aiRole.Name + ": "
}
func (c *ChatContext) SetMaxSeqTimes(times int) {
c.maxSeqTimes = times
}
func (c *ChatContext) GetMaxSeqTimes() int {
return c.maxSeqTimes
}
func (c *ChatContext) SetBackground(background string) {
c.background = background
}
func (c *ChatContext) SetPreset(preset string) {
c.preset = preset
}
func (c *ChatGPT) ChatWithContext(question string) (answer string, err error) {
question = question + "."
if tokenizer.MustCalToken(question) > c.maxQuestionLen {
return "", OverMaxQuestionLength
}
if c.ChatContext.seqTimes >= c.ChatContext.maxSeqTimes {
if c.ChatContext.maintainSeqTimes {
c.ChatContext.PollConversation()
} else {
return "", OverMaxSequenceTimes
}
}
var promptTable []string
promptTable = append(promptTable, c.ChatContext.background)
promptTable = append(promptTable, c.ChatContext.preset)
for _, v := range c.ChatContext.old {
if v.Role == c.ChatContext.humanRole {
promptTable = append(promptTable, "\n"+v.Role.Name+": "+v.Prompt)
} else {
promptTable = append(promptTable, v.Role.Name+": "+v.Prompt)
}
}
promptTable = append(promptTable, "\n"+c.ChatContext.restartSeq+question)
prompt := strings.Join(promptTable, "\n")
prompt += c.ChatContext.startSeq
// 删除对话,直到prompt的长度满足条件
for tokenizer.MustCalToken(prompt) > c.maxText {
if len(c.ChatContext.old) > 1 { // 至少保留一条记录
c.ChatContext.PollConversation() // 删除最旧的一条对话
// 重新构建 prompt,计算长度
promptTable = promptTable[1:] // 删除promptTable中对应的对话
prompt = strings.Join(promptTable, "\n") + c.ChatContext.startSeq
} else {
break // 如果已经只剩一条记录,那么跳出循环
}
}
// if tokenizer.MustCalToken(prompt) > c.maxText-c.maxAnswerLen {
// return "", OverMaxTextLength
// }
model := public.Config.Model
userId := c.userId
if public.Config.AzureOn {
userId = ""
}
if model == openai.GPT3Dot5Turbo0301 ||
model == openai.GPT3Dot5Turbo ||
model == openai.GPT4 || model == openai.GPT40314 ||
model == openai.GPT432K || model == openai.GPT432K0314 {
req := openai.ChatCompletionRequest{
Model: model,
Messages: []openai.ChatCompletionMessage{
{
Role: "user",
Content: prompt,
},
},
MaxTokens: c.maxAnswerLen,
Temperature: 0.6,
User: userId,
}
resp, err := c.client.CreateChatCompletion(c.ctx, req)
if err != nil {
return "", err
}
resp.Choices[0].Message.Content = formatAnswer(resp.Choices[0].Message.Content)
c.ChatContext.old = append(c.ChatContext.old, conversation{
Role: c.ChatContext.humanRole,
Prompt: question,
})
c.ChatContext.old = append(c.ChatContext.old, conversation{
Role: c.ChatContext.aiRole,
Prompt: resp.Choices[0].Message.Content,
})
c.ChatContext.seqTimes++
return resp.Choices[0].Message.Content, nil
} else {
req := openai.CompletionRequest{
Model: model,
MaxTokens: c.maxAnswerLen,
Prompt: prompt,
Temperature: 0.6,
User: c.userId,
Stop: []string{c.ChatContext.aiRole.Name + ":", c.ChatContext.humanRole.Name + ":"},
}
resp, err := c.client.CreateCompletion(c.ctx, req)
if err != nil {
return "", err
}
resp.Choices[0].Text = formatAnswer(resp.Choices[0].Text)
c.ChatContext.old = append(c.ChatContext.old, conversation{
Role: c.ChatContext.humanRole,
Prompt: question,
})
c.ChatContext.old = append(c.ChatContext.old, conversation{
Role: c.ChatContext.aiRole,
Prompt: resp.Choices[0].Text,
})
c.ChatContext.seqTimes++
return resp.Choices[0].Text, nil
}
}
func (c *ChatGPT) GenreateImage(ctx context.Context, prompt string) (string, error) {
model := public.Config.Model
if model == openai.GPT3Dot5Turbo0301 ||
model == openai.GPT3Dot5Turbo ||
model == openai.GPT4 || model == openai.GPT40314 ||
model == openai.GPT432K || model == openai.GPT432K0314 {
req := openai.ImageRequest{
Prompt: prompt,
Size: openai.CreateImageSize1024x1024,
ResponseFormat: openai.CreateImageResponseFormatB64JSON,
N: 1,
User: c.userId,
}
respBase64, err := c.client.CreateImage(c.ctx, req)
if err != nil {
return "", err
}
imgBytes, err := base64.StdEncoding.DecodeString(respBase64.Data[0].B64JSON)
if err != nil {
return "", err
}
r := bytes.NewReader(imgBytes)
imgData, err := png.Decode(r)
if err != nil {
return "", err
}
imageName := time.Now().Format("20060102-150405") + ".png"
clientId, _ := ctx.Value(public.DingTalkClientIdKeyName).(string)
client := public.DingTalkClientManager.GetClientByOAuthClientID(clientId)
mediaResult, uploadErr := &dingbot.MediaUploadResult{}, errors.New(fmt.Sprintf("unknown clientId: %s", clientId))
if client != nil {
mediaResult, uploadErr = client.UploadMedia(imgBytes, imageName, dingbot.MediaTypeImage, dingbot.MimeTypeImagePng)
}
err = os.MkdirAll("data/images", 0755)
if err != nil {
return "", err
}
file, err := os.Create("data/images/" + imageName)
if err != nil {
return "", err
}
defer file.Close()
if err := png.Encode(file, imgData); err != nil {
return "", err
}
if uploadErr == nil {
return mediaResult.MediaID, nil
} else {
return public.Config.ServiceURL + "/images/" + imageName, nil
}
}
return "", nil
}
func WithMaxSeqTimes(times int) ChatContextOption {
return func(c *ChatContext) {
c.SetMaxSeqTimes(times)
}
}
// WithOldConversation 从文件中加载对话
func WithOldConversation(userid string) ChatContextOption {
return func(c *ChatContext) {
_ = c.LoadConversation(userid)
}
}
func WithMaintainSeqTimes(maintain bool) ChatContextOption {
return func(c *ChatContext) {
c.maintainSeqTimes = maintain
}
}