-
Notifications
You must be signed in to change notification settings - Fork 108
/
openai.go
53 lines (43 loc) · 1.06 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
package ai
import (
"context"
"errors"
adminv1 "github.com/rilldata/rill/proto/gen/rill/admin/v1"
"github.com/sashabaranov/go-openai"
)
type openAI struct {
client *openai.Client
apiKey string
}
var _ Client = (*openAI)(nil)
func NewOpenAI(apiKey string) (Client, error) {
c := openai.NewClient(apiKey)
return &openAI{
client: c,
apiKey: apiKey,
}, nil
}
func (c *openAI) Complete(ctx context.Context, msgs []*adminv1.CompletionMessage) (*adminv1.CompletionMessage, error) {
reqMsgs := make([]openai.ChatCompletionMessage, len(msgs))
for i, msg := range msgs {
reqMsgs[i] = openai.ChatCompletionMessage{
Role: msg.Role,
Content: msg.Data,
}
}
res, err := c.client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: reqMsgs,
Temperature: 0.2,
})
if err != nil {
return nil, err
}
if len(res.Choices) == 0 {
return nil, errors.New("no choices returned")
}
return &adminv1.CompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Data: res.Choices[0].Message.Content,
}, nil
}