-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai.go
85 lines (72 loc) · 1.91 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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type OpenAIResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []OpenAIChoice `json:"choices"`
}
type OpenAIChoice struct {
Index int `json:"index"`
Message OpenAIMessage `json:"message"`
LogProbs any `json:"logprobs"`
FinishReason string `json:"finish_reason"`
}
type OpenAIMessage struct {
Role string `json:"role"`
Content string `json:"content"`
Refusal any `json:"refusal"`
Annotations []any `json:"annotations"`
}
func openai(commitMessage string, systemPrompt string, openaiApiKey string) (string, error) {
payload := map[string]any{
"model": "gpt-4o",
"messages": []map[string]string{
{
"role": "developer",
"content": systemPrompt,
},
{
"role": "user",
"content": commitMessage,
},
},
}
jsonData, err := json.Marshal(payload)
if err != nil {
return "Error: marshalling JSON", err
}
req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(jsonData))
if err != nil {
return "Error: creating request", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", openaiApiKey))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "Error: making request", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "Error: reading response", err
}
var response OpenAIResponse
err = json.Unmarshal(body, &response)
if err != nil {
return "Error: parsing JSON", err
}
if len(response.Choices) == 0 {
return "Error: No messages returned from LLM", errors.New("No messages")
}
return response.Choices[0].Message.Content, nil
}