forked from gptscript-ai/gptscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremote.go
207 lines (178 loc) · 5.38 KB
/
remote.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package remote
import (
"context"
"fmt"
"net/url"
"os"
"sort"
"strings"
"sync"
"github.com/gptscript-ai/gptscript/pkg/cache"
gcontext "github.com/gptscript-ai/gptscript/pkg/context"
"github.com/gptscript-ai/gptscript/pkg/credentials"
"github.com/gptscript-ai/gptscript/pkg/engine"
env2 "github.com/gptscript-ai/gptscript/pkg/env"
"github.com/gptscript-ai/gptscript/pkg/loader"
"github.com/gptscript-ai/gptscript/pkg/openai"
"github.com/gptscript-ai/gptscript/pkg/prompt"
"github.com/gptscript-ai/gptscript/pkg/runner"
"github.com/gptscript-ai/gptscript/pkg/types"
)
type Client struct {
clientsLock sync.Mutex
cache *cache.Client
clients map[string]clientInfo
modelToProvider map[string]string
runner *runner.Runner
envs []string
credStore credentials.CredentialStore
defaultProvider string
}
func New(r *runner.Runner, envs []string, cache *cache.Client, credStore credentials.CredentialStore, defaultProvider string) *Client {
return &Client{
cache: cache,
runner: r,
envs: envs,
credStore: credStore,
defaultProvider: defaultProvider,
modelToProvider: make(map[string]string),
clients: make(map[string]clientInfo),
}
}
func (c *Client) Call(ctx context.Context, messageRequest types.CompletionRequest, status chan<- types.CompletionStatus) (*types.CompletionMessage, error) {
c.clientsLock.Lock()
provider, ok := c.modelToProvider[messageRequest.Model]
c.clientsLock.Unlock()
if !ok {
return nil, fmt.Errorf("failed to find remote model %s", messageRequest.Model)
}
client, err := c.load(ctx, provider)
if err != nil {
return nil, err
}
toolName, modelName := types.SplitToolRef(messageRequest.Model)
if modelName == "" {
// modelName is empty, then the messageRequest.Model is not of the form 'modelName from provider'
// Therefore, the modelName is the toolName
modelName = toolName
}
messageRequest.Model = modelName
return client.Call(ctx, messageRequest, status)
}
func (c *Client) ListModels(ctx context.Context, providers ...string) (result []string, _ error) {
for _, provider := range providers {
client, err := c.load(ctx, provider)
if err != nil {
return nil, err
}
models, err := client.ListModels(ctx, "")
if err != nil {
return nil, err
}
for _, model := range models {
result = append(result, model+" from "+provider)
}
}
sort.Strings(result)
return
}
func (c *Client) parseModel(modelString string) (modelName, providerName string) {
toolName, subTool := types.SplitToolRef(modelString)
if subTool == "" {
// This is just a plain model string "gpt4o"
return toolName, c.defaultProvider
}
// This is a provider string "modelName from provider"
return subTool, toolName
}
func (c *Client) Supports(ctx context.Context, modelString string) (bool, error) {
_, providerName := c.parseModel(modelString)
if providerName == "" {
return false, nil
}
_, err := c.load(ctx, providerName)
if err != nil {
return false, err
}
c.clientsLock.Lock()
defer c.clientsLock.Unlock()
c.modelToProvider[modelString] = providerName
return true, nil
}
func isHTTPURL(toolName string) bool {
return strings.HasPrefix(toolName, "http://") ||
strings.HasPrefix(toolName, "https://")
}
func (c *Client) clientFromURL(ctx context.Context, apiURL string) (*openai.Client, error) {
parsed, err := url.Parse(apiURL)
if err != nil {
return nil, err
}
env := "GPTSCRIPT_PROVIDER_" + env2.ToEnvLike(parsed.Hostname()) + "_API_KEY"
key := os.Getenv(env)
if key == "" && !isLocalhost(apiURL) {
var err error
key, err = c.retrieveAPIKey(ctx, env, apiURL)
if err != nil {
return nil, err
}
}
return openai.NewClient(ctx, c.credStore, openai.Options{
BaseURL: apiURL,
Cache: c.cache,
APIKey: key,
})
}
func (c *Client) load(ctx context.Context, toolName string) (*openai.Client, error) {
c.clientsLock.Lock()
defer c.clientsLock.Unlock()
client, ok := c.clients[toolName]
if ok && !isHTTPURL(toolName) && engine.IsDaemonRunning(client.url) {
return client.client, nil
}
if isHTTPURL(toolName) {
remoteClient, err := c.clientFromURL(ctx, toolName)
if err != nil {
return nil, err
}
c.clients[toolName] = clientInfo{
client: remoteClient,
url: toolName,
}
return remoteClient, nil
}
prg, err := loader.Program(ctx, toolName, "", loader.Options{
Cache: c.cache,
})
if err != nil {
return nil, err
}
url, err := c.runner.Run(engine.WithToolCategory(ctx, engine.ProviderToolCategory), prg.SetBlocking(), c.envs, "")
if err != nil {
return nil, err
}
oClient, err := openai.NewClient(ctx, c.credStore, openai.Options{
BaseURL: strings.TrimSuffix(url, "/") + "/v1",
Cache: c.cache,
CacheKey: prg.EntryToolID,
})
if err != nil {
return nil, err
}
c.clients[toolName] = clientInfo{
client: oClient,
url: url,
}
return client.client, nil
}
func (c *Client) retrieveAPIKey(ctx context.Context, env, url string) (string, error) {
return prompt.GetModelProviderCredential(ctx, c.credStore, url, env, fmt.Sprintf("Please provide your API key for %s", url), append(gcontext.GetEnv(ctx), c.envs...))
}
func isLocalhost(url string) bool {
return strings.HasPrefix(url, "http://localhost") || strings.HasPrefix(url, "http://127.0.0.1") ||
strings.HasPrefix(url, "https://localhost") || strings.HasPrefix(url, "https://127.0.0.1")
}
type clientInfo struct {
client *openai.Client
url string
}