-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (55 loc) · 1.25 KB
/
main.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
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"github.com/amirfakhrullah/go-chat/pkg/cli"
"github.com/amirfakhrullah/go-chat/pkg/helpers"
_ "github.com/joho/godotenv/autoload"
openai "github.com/sashabaranov/go-openai"
)
var apiKeyName = "OPEN_AI_API_KEY"
func main() {
var apiKey string
apiKey = os.Getenv(apiKeyName)
if len(apiKey) == 0 {
var err error
apiKey, err = cli.GetApiKey(apiKeyName)
helpers.HandlePanic(err)
}
c := openai.NewClient(apiKey)
ctx := context.Background()
var input string
var inputErr error
input, inputErr = cli.GetQuestion(true)
helpers.HandlePanic(inputErr)
for input != ":q!" {
req := openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleUser,
Content: input,
},
},
Stream: true,
}
stream, err := c.CreateChatCompletionStream(ctx, req)
helpers.HandlePanic(err)
defer stream.Close()
fmt.Print("Response: ")
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
fmt.Print("\n")
break
}
helpers.HandlePanic(err)
fmt.Printf(response.Choices[0].Delta.Content)
}
input, inputErr = cli.GetQuestion(false)
helpers.HandlePanic(inputErr)
}
}