/
chatgpt.go
109 lines (98 loc) · 2.6 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package aireply
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strings"
)
// ChatGPT GPT回复类
type ChatGPT struct {
u string
k string
b []string
}
// chatGPTResponseBody 响应体
type chatGPTResponseBody struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
Choices []map[string]interface{} `json:"choices"`
Usage map[string]interface{} `json:"usage"`
}
// chatGPTRequestBody 请求体
type chatGPTRequestBody struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
MaxTokens int `json:"max_tokens"`
Temperature float32 `json:"temperature"`
TopP int `json:"top_p"`
FrequencyPenalty int `json:"frequency_penalty"`
PresencePenalty int `json:"presence_penalty"`
}
const (
// ChatGPTURL api地址
ChatGPTURL = "https://api.openai.com/v1/"
)
// NewChatGPT ...
func NewChatGPT(u, key string, banwords ...string) *ChatGPT {
return &ChatGPT{u: u, k: key, b: banwords}
}
// String ...
func (*ChatGPT) String() string {
return "ChatGPT"
}
// Talk 取得带 CQ 码的回复消息
func (c *ChatGPT) Talk(_ int64, msg, _ string) string {
replystr := chat(msg, c.k, c.u)
for _, w := range c.b {
if strings.Contains(replystr, w) {
return "ERROR: 回复可能含有敏感内容"
}
}
return replystr
}
// TalkPlain 取得回复消息
func (c *ChatGPT) TalkPlain(_ int64, msg, nickname string) string {
return c.Talk(0, msg, nickname)
}
func chat(msg string, apiKey string, url string) string {
requestBody := chatGPTRequestBody{
Model: "text-davinci-003",
Prompt: msg,
MaxTokens: 2048,
Temperature: 0.7,
TopP: 1,
FrequencyPenalty: 0,
PresencePenalty: 0,
}
requestData := bytes.NewBuffer(make([]byte, 0, 1024*1024))
err := json.NewEncoder(requestData).Encode(&requestBody)
if err != nil {
return err.Error()
}
req, err := http.NewRequest("POST", url+"completions", requestData)
if err != nil {
return err.Error()
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
return err.Error()
}
defer response.Body.Close()
var gptResponseBody chatGPTResponseBody
err = json.NewDecoder(response.Body).Decode(&gptResponseBody)
if err != nil {
return err.Error()
}
if len(gptResponseBody.Choices) > 0 {
for _, v := range gptResponseBody.Choices {
return fmt.Sprint(v["text"])
}
}
return ""
}