-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathclient.go
111 lines (89 loc) · 2.21 KB
/
client.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
package main
import (
"bytes"
"context"
"encoding/json"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"io"
"net/http"
"strings"
)
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatCompleteRequest struct {
Model string `json:"model"`
Messages []*Message `json:"messages"`
}
type GptClient struct {
apiKey string
model string
httpClient *http.Client
totalToken uint64
}
const chatEndpoint = "https://api.openai.com/v1/chat/completions"
func NewGptClient(apiKey string, model string) *GptClient {
return &GptClient{
totalToken: 0,
apiKey: apiKey,
model: model,
httpClient: http.DefaultClient,
}
}
func handleAPIError(res *http.Response, body []byte) error {
if res.StatusCode != http.StatusOK {
errorMessage := gjson.GetBytes(body, "error.message").String()
if errorMessage == "" {
errorMessage = string(body)
}
return errors.New(errorMessage)
}
return nil
}
func (c *GptClient) ChatComplete(ctx context.Context, messages []*Message) (string, error) {
request := &ChatCompleteRequest{
Model: c.model,
Messages: messages,
}
payload, _ := json.Marshal(request)
payloadReader := bytes.NewReader(payload)
req, err := http.NewRequestWithContext(ctx, "POST", chatEndpoint, payloadReader)
if err != nil {
return "", err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+c.apiKey)
res, err := c.httpClient.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
if err := handleAPIError(res, body); err != nil {
return "", err
}
c.totalToken += gjson.GetBytes(body, "usage.total_tokens").Uint()
answer := gjson.GetBytes(body, "choices.0.message.content").String()
answer = strings.TrimSpace(answer)
answer = strings.Trim(answer, `"`)
return answer, nil
}
// SingleQuestion asks a single question to the user
func (c *GptClient) SingleQuestion(question string) (string, error) {
message := []*Message{
{
Role: "user",
Content: question,
},
}
response, err := c.ChatComplete(context.Background(), message)
if err != nil {
return "", err
}
return response, nil
}