-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai.go
88 lines (76 loc) · 1.8 KB
/
openai.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 summaraizer
import (
"bytes"
"encoding/json"
"io"
"net/http"
)
// OpenAi is a provider that uses OpenAI API as an AI provider.
type OpenAi struct {
Model string // The Ai model to use.
Prompt string // The prompt to use for the AI model.
ApiToken string // The API Token for OpenAI.
}
func (o *OpenAi) Summarize(reader io.Reader) (string, error) {
return decodeAndSummarize(reader, func(comments Comments) (string, error) {
prompt, err := resolvePrompt(o.Prompt, comments)
if err != nil {
return "", err
}
request := openAiRequest{
Model: o.Model,
Messages: []openAiRequestMessage{
{
Role: "user",
Content: prompt,
},
},
}
reqBodyBytes, err := json.Marshal(request)
if err != nil {
return "", err
}
req, err := http.NewRequest(
"POST",
"https://api.openai.com/v1/chat/completions",
bytes.NewBuffer(reqBodyBytes),
)
if err != nil {
return "", err
}
req.Header.Set("Authorization", "Bearer "+o.ApiToken)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
var response openAiResponse
err = json.Unmarshal(respBody, &response)
if err != nil {
return "", err
}
return response.Choices[0].Message.Content, nil
})
}
type openAiRequest struct {
Model string `json:"model"`
Messages []openAiRequestMessage `json:"messages"`
}
type openAiRequestMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}
type openAiResponse struct {
Choices []struct {
Message struct {
Content string `json:"content"`
Role string `json:"role"`
} `json:"message"`
} `json:"choices"`
}