-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathclient.go
More file actions
64 lines (50 loc) · 1.81 KB
/
client.go
File metadata and controls
64 lines (50 loc) · 1.81 KB
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
package ai
import (
"os"
"strings"
"github.com/hashicorp/go-retryablehttp"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
"github.com/runmedev/runme/v3/pkg/agent/logs"
"github.com/runmedev/runme/v3/pkg/agent/config"
"github.com/pkg/errors"
)
// NewClient helper function to create a new OpenAI client from a config
func NewClient(cfg config.OpenAIConfig) (*openai.Client, error) {
if cfg.APIKeyFile == "" {
log := logs.NewLogger()
log.Info("OpenAI client configured without APIKeyFile")
return NewClientWithoutKey(), nil
}
b, err := os.ReadFile(cfg.APIKeyFile)
if err != nil {
return nil, errors.Wrapf(err, "failed to read OpenAI API key file: %s", cfg.APIKeyFile)
}
key := strings.TrimSpace(string(b))
return NewClientWithKey(key)
}
func NewClientWithKey(key string) (*openai.Client, error) {
// ************************************************************************
// Setup middleware
// ************************************************************************
// Handle retryable errors
// To handle retryable errors we use hashi corp's retryable client. This client will automatically retry on
// retryable errors like 429; rate limiting
retryClient := retryablehttp.NewClient()
httpClient := retryClient.StandardClient()
client := openai.NewClient(
option.WithAPIKey(key), // defaults to os.LookupEnv("OPENAI_API_KEY")
option.WithHTTPClient(httpClient),
)
return &client, nil
}
// NewClientWithoutKey returns an OpenAI client configured without an API key.
// This is intended for OAuth flows where the caller supplies the Authorization header per-request.
func NewClientWithoutKey() *openai.Client {
retryClient := retryablehttp.NewClient()
httpClient := retryClient.StandardClient()
client := openai.NewClient(
option.WithHTTPClient(httpClient),
)
return &client
}