Skip to content

Commit 59a1be8

Browse files
author
Chris
committed
penAIResponse struct and adjust API request headers
1 parent 6e10edb commit 59a1be8

File tree

1 file changed

+16
-18
lines changed

1 file changed

+16
-18
lines changed

gitcommit.go

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -56,18 +56,27 @@ func main() {
5656
}
5757
}
5858

59+
type OpenAIResponse struct {
60+
Choices []struct {
61+
Text string `json:"text"`
62+
} `json:"choices"`
63+
}
64+
5965
func generateCommitMessage(prompt, modelEngine, openaiAPIKey string) (string, error) {
6066
client := resty.New()
6167

6268
resp, err := client.R().
63-
SetHeader("Authorization", fmt.Sprintf("Bearer %s", openaiAPIKey)).
69+
SetHeaders(map[string]string{
70+
"Content-Type": "application/json",
71+
"Authorization": fmt.Sprintf("Bearer %s", openaiAPIKey),
72+
}).
6473
SetBody(map[string]interface{}{
6574
"model": modelEngine,
66-
"prompt": prompt,
75+
"prompt": prompt,
6776
"max_tokens": 50, // Adjust the max tokens and other parameters as needed
6877
"temperature": 0.5, // Adjust the temperature value as needed
6978
}).
70-
SetResult(map[string]interface{}{}).
79+
SetResult(&OpenAIResponse{}).
7180
Post("https://api.openai.com/v1/completions")
7281

7382
if err != nil {
@@ -78,27 +87,16 @@ func generateCommitMessage(prompt, modelEngine, openaiAPIKey string) (string, er
7887
return "", fmt.Errorf("API request failed with status code: %d", resp.StatusCode())
7988
}
8089

81-
result, ok := resp.Result().(map[string]interface{})
90+
openAIResp, ok := resp.Result().(*OpenAIResponse)
8291
if !ok {
8392
return "", fmt.Errorf("Unable to access the desired fields from resp.Result()")
8493
}
8594

86-
choices, ok := result["choices"].([]interface{})
87-
if !ok || len(choices) == 0 {
88-
return "", fmt.Errorf("Unable to access the choices field or choices is empty")
89-
}
90-
91-
choice, ok := choices[0].(map[string]interface{})
92-
if !ok {
93-
return "", fmt.Errorf("Unable to access the choice element")
94-
}
95-
96-
text, ok := choice["text"].(string)
97-
if !ok {
98-
return "", fmt.Errorf("Unable to access the text field")
95+
if len(openAIResp.Choices) == 0 {
96+
return "", fmt.Errorf("No choices returned in the response")
9997
}
10098

101-
return text, nil
99+
return openAIResp.Choices[0].Text, nil
102100
}
103101

104102
func commitChanges(commitMessage string) {

0 commit comments

Comments
 (0)