-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
chat_completion.go
88 lines (77 loc) · 1.97 KB
/
chat_completion.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 openai
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
)
type ChatCompletionMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ChatCompletionChoice struct {
Message *ChatCompletionMessage `json:"message"`
}
type ChatCompletionResponse struct {
Error any `json:"error"`
Model string `json:"model"`
Choices []ChatCompletionChoice `json:"choices"`
}
func PostChatCompletion(messages []ChatCompletionMessage, apiKey string, apiHost string) (string, error) {
if apiHost == "" {
apiHost = "https://api.openai.com"
}
url, err := url.JoinPath(apiHost, "/v1/chat/completions")
if err != nil {
return "", err
}
values := map[string]any{
"model": "gpt-3.5-turbo",
"messages": messages,
"max_tokens": 2000,
"temperature": 0,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
}
jsonValue, err := json.Marshal(values)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
if err != nil {
return "", err
}
// Set the API key in the request header
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
// Send the request to OpenAI's API
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Read the response body
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
chatCompletionResponse := ChatCompletionResponse{}
err = json.Unmarshal(responseBody, &chatCompletionResponse)
if err != nil {
return "", err
}
if chatCompletionResponse.Error != nil {
errorBytes, err := json.Marshal(chatCompletionResponse.Error)
if err != nil {
return "", err
}
return "", errors.New(string(errorBytes))
}
if len(chatCompletionResponse.Choices) == 0 {
return "", nil
}
return chatCompletionResponse.Choices[0].Message.Content, nil
}