forked from solywsh/chatgpt
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatgpt.go
92 lines (85 loc) · 2.3 KB
/
chatgpt.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
package chatgpt
import (
"context"
gogpt "github.com/sashabaranov/go-gpt3"
"time"
)
type ChatGPT struct {
client *gogpt.Client
ctx context.Context
userId string
maxQuestionLen int
maxText int
maxAnswerLen int
timeOut time.Duration // 超时时间, 0表示不超时
doneChan chan struct{}
cancel func()
ChatContext *ChatContext
}
func New(ApiKey, UserId string, timeOut time.Duration) *ChatGPT {
var ctx context.Context
var cancel func()
if timeOut == 0 {
ctx, cancel = context.WithCancel(context.Background())
} else {
ctx, cancel = context.WithTimeout(context.Background(), timeOut)
}
timeOutChan := make(chan struct{}, 1)
go func() {
<-ctx.Done()
timeOutChan <- struct{}{} // 发送超时信号,或是提示结束,用于聊天机器人场景,配合GetTimeOutChan() 使用
}()
return &ChatGPT{
client: gogpt.NewClient(ApiKey),
ctx: ctx,
userId: UserId,
maxQuestionLen: 1024, // 最大问题长度
maxAnswerLen: 1024, // 最大答案长度
maxText: 4096, // 最大文本 = 问题 + 回答, 接口限制
timeOut: timeOut,
doneChan: timeOutChan,
cancel: func() {
cancel()
},
ChatContext: NewContext(),
}
}
func (c *ChatGPT) Close() {
c.cancel()
}
func (c *ChatGPT) GetDoneChan() chan struct{} {
return c.doneChan
}
func (c *ChatGPT) SetMaxQuestionLen(maxQuestionLen int) int {
if maxQuestionLen > c.maxText-c.maxAnswerLen {
maxQuestionLen = c.maxText - c.maxAnswerLen
}
c.maxQuestionLen = maxQuestionLen
return c.maxQuestionLen
}
func (c *ChatGPT) Chat(question string) (answer string, err error) {
question = question + "."
if len(question) > c.maxQuestionLen {
return "", OverMaxQuestionLength
}
if len(question)+c.maxAnswerLen > c.maxText {
question = question[:c.maxText-c.maxAnswerLen]
}
req := gogpt.CompletionRequest{
Model: gogpt.GPT3TextDavinci003,
MaxTokens: c.maxAnswerLen,
Prompt: question,
Temperature: 0.9,
TopP: 1,
N: 1,
FrequencyPenalty: 0,
PresencePenalty: 0.5,
User: c.userId,
Stop: []string{},
}
resp, err := c.client.CreateCompletion(c.ctx, req)
if err != nil {
return "", err
}
return formatAnswer(resp.Choices[0].Text), err
}