-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
68 lines (57 loc) · 1.29 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
package openai
import (
"context"
"errors"
"github.com/josebalius/typechat-go"
"github.com/sashabaranov/go-openai"
)
type Client struct {
client *openai.Client
model string
}
func NewClient(client *openai.Client, model string) *Client {
return &Client{
client: client,
model: model,
}
}
func openaiRole(r typechat.Role) (string, error) {
var role string
switch r {
case typechat.RoleUser:
role = openai.ChatMessageRoleUser
case typechat.RoleSystem:
role = openai.ChatMessageRoleSystem
case typechat.RoleAssistant:
role = openai.ChatMessageRoleAssistant
default:
return "", errors.New("invalid role")
}
return role, nil
}
func (c *Client) Do(ctx context.Context, prompt []typechat.Message) (string, error) {
var messages []openai.ChatCompletionMessage
for _, m := range prompt {
role, err := openaiRole(m.Role)
if err != nil {
return "", err
}
msg := openai.ChatCompletionMessage{
Role: role,
Content: m.Content,
}
messages = append(messages, msg)
}
params := openai.ChatCompletionRequest{
Model: c.model,
Messages: messages,
}
resp, err := c.client.CreateChatCompletion(ctx, params)
if err != nil {
return "", err
}
if len(resp.Choices) == 0 {
return "", errors.New("no choices returned")
}
return resp.Choices[0].Message.Content, nil
}