-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathopenai.go
98 lines (83 loc) · 2.62 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
89
90
91
92
93
94
95
96
97
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
)
// Message structure for the OpenAI chat format
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
// ChatCompletionResponse structure for parsing the response from OpenAI API
type ChatCompletionResponse struct {
Choices []struct {
Message struct {
Role string `json:"role"`
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
func generateContentUsingGPT(apiKey string, prompt string, config *Config) string {
logToFile(config.General.LogFile, "This is where the prompt goes from the config file input: "+prompt)
// Prepare the messages payload for the request
messages := []Message{
{"system", "You will respond exactly as requested with real information, do not wrap codeblocks like ```yaml, only return the raw yaml file."},
{"user", prompt},
}
// Prepare the JSON payload for the request
payload := map[string]interface{}{
"model": "gpt-4-turbo-preview",
"messages": messages,
"max_tokens": 2048,
"temperature": 0.3,
}
payloadBytes, err := json.Marshal(payload)
if err != nil {
logToFile(config.General.LogFile, "Error marshalling payload: "+err.Error())
return ""
}
// Create a new request
req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewReader(payloadBytes))
if err != nil {
logToFile(config.General.LogFile, "Error creating request: "+err.Error())
return ""
}
// Set headers
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+apiKey)
// Execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
logToFile(config.General.LogFile, "Error making request to OpenAI: "+err.Error())
return ""
}
defer resp.Body.Close()
// Read the response body
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
logToFile(config.General.LogFile, "Error reading response body: "+err.Error())
return ""
}
// Parse the response
var chatResponse ChatCompletionResponse
if err := json.Unmarshal(respBody, &chatResponse); err != nil {
logToFile(config.General.LogFile, "Error parsing response JSON: "+err.Error())
return ""
}
// Extract generated content
var generatedContent string
for _, choice := range chatResponse.Choices {
if choice.Message.Role == "assistant" {
generatedContent = choice.Message.Content
logToFile(config.General.LogFile, "Generated Content: "+generatedContent)
break
}
}
if generatedContent == "" {
logToFile(config.General.LogFile, "No choices returned from OpenAI API")
}
return generatedContent
}