-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenai.go
60 lines (51 loc) · 1.04 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
package main
import (
"context"
"errors"
"io"
"github.com/sashabaranov/go-openai"
)
type OpenAIConfig struct {
ApiKey string `env:"OPENAI_TOKEN"`
Model string `env:"OPENAI_MODEL"`
}
type OpenAI struct {
client *openai.Client
}
func NewOpenAI(config *OpenAIConfig) *OpenAI {
return &OpenAI{
client: openai.NewClient(config.ApiKey),
}
}
func (o *OpenAI) Generate(ctx context.Context, system, prompt string, ch chan string, errCh chan error) error {
stream, err := o.client.CreateChatCompletionStream(ctx, openai.ChatCompletionRequest{
Model: openai.GPT4o,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: system,
},
{
Role: openai.ChatMessageRoleUser,
Content: prompt,
},
},
Stream: true,
})
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
if len(resp.Choices) == 0 {
return errors.New("no response")
}
ch <- resp.Choices[0].Delta.Content
}
}