-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathopenai.go
66 lines (56 loc) · 1.26 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
package openai
import (
"context"
_ "embed"
"errors"
"fmt"
"time"
"github.com/sashabaranov/go-openai"
)
//go:embed prompts/review
var PromptReview string
//go:embed prompts/describe_changes
var PromptDescribeChanges string
//go:embed prompts/describe_overall
var PromptDescribeOverall string
type Client struct {
client *openai.Client
model string
}
func NewClient(token, model string) *Client {
return &Client{
client: openai.NewClient(token),
model: model,
}
}
func (c *Client) ChatCompletion(ctx context.Context, messages []openai.ChatCompletionMessage) (string, error) {
resp, err := c.client.CreateChatCompletion(
ctx,
openai.ChatCompletionRequest{
Model: c.model,
Messages: messages,
Temperature: 0.1,
},
)
if err != nil {
if errors.Is(err, context.Canceled) {
return "", err
}
fmt.Println("Error completing prompt:", err)
fmt.Println("Retrying after 1 minute")
// retry once after 1 minute
time.Sleep(time.Minute)
resp, err = c.client.CreateChatCompletion(
ctx,
openai.ChatCompletionRequest{
Model: c.model,
Messages: messages,
Temperature: 0.1,
},
)
if err != nil {
return "", fmt.Errorf("error completing prompt: %w", err)
}
}
return resp.Choices[0].Message.Content, nil
}