-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
70 lines (61 loc) · 1.39 KB
/
client.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
69
70
package main
import (
"context"
"io"
"strings"
"github.com/sashabaranov/go-openai"
)
func NewClient(opt *BackendOption) *Client {
cfg := openai.DefaultConfig(opt.APIKey)
cfg.BaseURL = opt.BaseURL
return &Client{BackendOption: opt, Client: openai.NewClientWithConfig(cfg)}
}
type Client struct {
*BackendOption
*openai.Client
}
func (c *Client) Stream(s *Session, input string) error {
defer Pln()
s.Append(openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: input,
})
// https://platform.openai.com/docs/api-reference/chat
stream, err := c.CreateChatCompletionStream(context.Background(), openai.ChatCompletionRequest{
Messages: s.Get(),
Model: c.Model,
MaxTokens: c.MaxTokens,
Temperature: c.Temperature,
TopP: c.TopP,
Stream: true,
PresencePenalty: c.PresencePenalty,
FrequencyPenalty: c.FrequencyPenalty,
})
if err != nil {
return err
}
defer stream.Close()
builder := strings.Builder{}
for {
r, err := stream.Recv()
if err != nil {
if err == io.EOF {
break
}
return err
}
if len(r.Choices) == 0 {
continue
}
choice := r.Choices[0]
if str := choice.Delta.Content; str != "" {
P(str)
builder.WriteString(str)
}
}
s.Append(openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: builder.String(),
})
return s.Save()
}