-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (74 loc) · 1.66 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
package gptlib
import (
"context"
"fmt"
"strings"
"time"
"github.com/PullRequestInc/go-gpt3"
)
type Client interface {
SendRequest(RequestData) (string, error)
}
type RequestData struct {
// required
Prompt string
// optional
MaxTokens int // by default: 1000
Role string // by default: user
Timeout time.Duration
UserID string
}
func NewChatGPT(openAIAPIToken string) Client {
return &chatGPT{
conn: gpt3.NewClient(openAIAPIToken),
}
}
type chatGPT struct {
conn gpt3.Client
}
func (c *chatGPT) SendRequest(data RequestData) (string, error) {
if data.Role == "" {
data.Role = "user"
}
if data.MaxTokens == 0 {
data.MaxTokens = 1000
}
ctx := context.Background()
ctxCancel := func() {}
if data.Timeout != 0 {
ctx, ctxCancel = context.WithTimeout(context.Background(), data.Timeout)
}
defer ctxCancel()
response, err := c.conn.ChatCompletion(
ctx,
gpt3.ChatCompletionRequest{
Messages: []gpt3.ChatCompletionRequestMessage{
{
Role: data.Role,
Content: data.Prompt,
},
},
Temperature: 0.6,
MaxTokens: data.MaxTokens,
TopP: 1,
N: 1,
FrequencyPenalty: 1,
PresencePenalty: 1,
User: data.UserID,
},
)
if err != nil {
return "", fmt.Errorf("send chat completion request: %w", err)
}
return getResponseText(response), nil
}
func getResponseText(response *gpt3.ChatCompletionResponse) string {
dataArray := []string{}
for _, data := range response.Choices {
if data.Message.Content != "" {
dataArray = append(dataArray, data.Message.Content)
}
}
result := strings.Join(dataArray, "\n")
return strings.TrimLeft(result, "\n")
}