/
palmclient.go
344 lines (313 loc) · 9.67 KB
/
palmclient.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package palmclient
import (
"context"
"errors"
"fmt"
"runtime"
aiplatform "cloud.google.com/go/aiplatform/apiv1"
"cloud.google.com/go/aiplatform/apiv1/aiplatformpb"
"github.com/j178/llms/schema"
"google.golang.org/api/option"
"google.golang.org/protobuf/types/known/structpb"
)
const (
defaultAPIEndpoint = "us-central1-aiplatform.googleapis.com:443"
defaultLocation = "us-central1"
defaultPublisher = "google"
)
var (
// ErrMissingValue is returned when a value is missing.
ErrMissingValue = errors.New("missing value")
// ErrInvalidValue is returned when a value is invalid.
ErrInvalidValue = errors.New("invalid value")
)
var defaultParameters = map[string]interface{}{ //nolint:gochecknoglobals
"temperature": 0.2, //nolint:gomnd
"maxOutputTokens": 256, //nolint:gomnd
"topP": 0.8, //nolint:gomnd
"topK": 40, //nolint:gomnd
}
const (
embeddingModelName = "textembedding-gecko"
TextModelName = "text-bison"
ChatModelName = "chat-bison"
defaultMaxConns = 4
)
// PaLMClient represents a Vertex AI based PaLM API client.
type PaLMClient struct {
client *aiplatform.PredictionClient
projectID string
}
// New returns a new Vertex AI based PaLM API client.
func New(projectID string, opts ...option.ClientOption) (*PaLMClient, error) {
numConns := runtime.GOMAXPROCS(0)
if numConns > defaultMaxConns {
numConns = defaultMaxConns
}
o := []option.ClientOption{
option.WithGRPCConnectionPool(numConns),
option.WithEndpoint(defaultAPIEndpoint),
}
o = append(o, opts...)
ctx := context.Background()
client, err := aiplatform.NewPredictionClient(ctx, o...)
if err != nil {
return nil, err
}
return &PaLMClient{
client: client,
projectID: projectID,
}, nil
}
// ErrEmptyResponse is returned when the OpenAI API returns an empty response.
var ErrEmptyResponse = errors.New("empty response")
// CompletionRequest is a request to create a completion.
type CompletionRequest struct {
Prompts []string `json:"prompts"`
MaxTokens int `json:"max_tokens"`
Temperature float64 `json:"temperature"`
TopP int `json:"top_p,omitempty"`
TopK int `json:"top_k,omitempty"`
StopSequences []string `json:"stop_sequences"`
}
// Completion is a completion.
type Completion struct {
Text string `json:"text"`
}
// CreateCompletion creates a completion.
func (c *PaLMClient) CreateCompletion(ctx context.Context, r *CompletionRequest) ([]*Completion, error) {
params := map[string]interface{}{
"maxOutputTokens": r.MaxTokens,
"temperature": r.Temperature,
"top_p": r.TopP,
"top_k": r.TopK,
"stopSequences": convertArray(r.StopSequences),
}
predictions, err := c.batchPredict(ctx, TextModelName, r.Prompts, params)
if err != nil {
return nil, err
}
completions := []*Completion{}
for _, p := range predictions {
value := p.GetStructValue().AsMap()
text, ok := value["content"].(string)
if !ok {
return nil, fmt.Errorf("%w: %v", ErrMissingValue, "content")
}
completions = append(completions, &Completion{
Text: text,
})
}
return completions, nil
}
// EmbeddingRequest is a request to create an embedding.
type EmbeddingRequest struct {
Input []string `json:"input"`
}
// CreateEmbedding creates embeddings.
func (c *PaLMClient) CreateEmbedding(ctx context.Context, r *EmbeddingRequest) ([][]float32, error) {
params := map[string]interface{}{}
responses, err := c.batchPredict(ctx, embeddingModelName, r.Input, params)
if err != nil {
return nil, err
}
embeddings := [][]float32{}
for _, res := range responses {
value := res.GetStructValue().AsMap()
embedding, ok := value["embeddings"].(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%w: %v", ErrMissingValue, "embeddings")
}
values, ok := embedding["values"].([]interface{})
if !ok {
return nil, fmt.Errorf("%w: %v", ErrMissingValue, "values")
}
floatValues := []float32{}
for _, v := range values {
val, ok := v.(float32)
if !ok {
valF64, ok := v.(float64)
if !ok {
return nil, fmt.Errorf("%w: %v is not a float64 or float32, it is a %T", ErrInvalidValue, "value", v)
}
val = float32(valF64)
}
floatValues = append(floatValues, val)
}
embeddings = append(embeddings, floatValues)
}
return embeddings, nil
}
// ChatRequest is a request to create an embedding.
type ChatRequest struct {
Context string `json:"context"`
Messages []*ChatMessage `json:"messages"`
Temperature float64 `json:"temperature"`
TopP int `json:"top_p,omitempty"`
TopK int `json:"top_k,omitempty"`
CandidateCount int `json:"candidate_count,omitempty"`
}
// ChatMessage is a message in a chat.
type ChatMessage struct {
// The content of the message.
Content string `json:"content"`
// The name of the author of this message. user or bot
Author string `json:"author,omitempty"`
}
// Statically assert that the types implement the interface.
var _ schema.ChatMessage = ChatMessage{}
// GetType returns the type of the message.
func (m ChatMessage) GetType() schema.ChatMessageType {
switch m.Author {
case "user":
return schema.ChatMessageTypeHuman
default:
return schema.ChatMessageTypeAI
}
}
// GetText returns the text of the message.
func (m ChatMessage) GetContent() string {
return m.Content
}
// ChatResponse is a response to a chat request.
type ChatResponse struct {
Candidates []ChatMessage
}
// CreateChat creates chat request.
func (c *PaLMClient) CreateChat(ctx context.Context, r *ChatRequest) (*ChatResponse, error) {
responses, err := c.chat(ctx, r)
if err != nil {
return nil, err
}
chatResponse := &ChatResponse{}
res := responses[0]
value := res.GetStructValue().AsMap()
candidates, ok := value["candidates"].([]interface{})
if !ok {
return nil, fmt.Errorf("%w: %v", ErrMissingValue, "candidates")
}
for _, c := range candidates {
candidate, ok := c.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("%w: %v is not a map[string]interface{}", ErrInvalidValue, "candidate")
}
author, ok := candidate["author"].(string)
if !ok {
return nil, fmt.Errorf("%w: %v is not a string", ErrInvalidValue, "author")
}
content, ok := candidate["content"].(string)
if !ok {
return nil, fmt.Errorf("%w: %v is not a string", ErrInvalidValue, "content")
}
chatResponse.Candidates = append(chatResponse.Candidates, ChatMessage{
Author: author,
Content: content,
})
}
return chatResponse, nil
}
func mergeParams(defaultParams, params map[string]interface{}) *structpb.Struct {
mergedParams := cloneDefaultParameters()
for paramKey, paramValue := range params {
switch value := paramValue.(type) {
case float64:
if value != 0 {
mergedParams[paramKey] = value
}
case int:
case int32:
case int64:
if value != 0 {
mergedParams[paramKey] = value
}
case []interface{}:
mergedParams[paramKey] = value
}
}
return convertToOutputStruct(defaultParams, mergedParams)
}
func convertToOutputStruct(defaultParams map[string]interface{}, mergedParams map[string]interface{}) *structpb.Struct {
smergedParams, err := structpb.NewStruct(mergedParams)
if err != nil {
smergedParams, _ = structpb.NewStruct(defaultParams)
return smergedParams
}
return smergedParams
}
func cloneDefaultParameters() map[string]interface{} {
mergedParams := map[string]interface{}{}
for paramKey, paramValue := range defaultParameters {
mergedParams[paramKey] = paramValue
}
return mergedParams
}
func convertArray(value []string) interface{} {
newArray := make([]interface{}, len(value))
for i, v := range value {
newArray[i] = v
}
return newArray
}
func (c *PaLMClient) batchPredict(ctx context.Context, model string, prompts []string, params map[string]interface{}) ([]*structpb.Value, error) { //nolint:lll
mergedParams := mergeParams(defaultParameters, params)
instances := []*structpb.Value{}
for _, prompt := range prompts {
content, _ := structpb.NewStruct(map[string]interface{}{
"content": prompt,
})
instances = append(instances, structpb.NewStructValue(content))
}
resp, err := c.client.Predict(ctx, &aiplatformpb.PredictRequest{
Endpoint: c.projectLocationPublisherModelPath(c.projectID, "us-central1", "google", model),
Instances: instances,
Parameters: structpb.NewStructValue(mergedParams),
})
if err != nil {
return nil, err
}
if len(resp.GetPredictions()) == 0 {
return nil, ErrEmptyResponse
}
return resp.GetPredictions(), nil
}
func (c *PaLMClient) chat(ctx context.Context, r *ChatRequest) ([]*structpb.Value, error) {
params := map[string]interface{}{
"temperature": r.Temperature,
"top_p": r.TopP,
"top_k": r.TopK,
}
mergedParams := mergeParams(defaultParameters, params)
messages := []interface{}{}
for _, msg := range r.Messages {
msgMap := map[string]interface{}{
"author": msg.Author,
"content": msg.Content,
}
messages = append(messages, msgMap)
}
instance, err := structpb.NewStruct(map[string]interface{}{
"context": r.Context,
"messages": messages,
})
if err != nil {
return nil, err
}
instances := []*structpb.Value{
structpb.NewStructValue(instance),
}
resp, err := c.client.Predict(ctx, &aiplatformpb.PredictRequest{
Endpoint: c.projectLocationPublisherModelPath(c.projectID, "us-central1", "google", ChatModelName),
Instances: instances,
Parameters: structpb.NewStructValue(mergedParams),
})
if err != nil {
return nil, err
}
if len(resp.GetPredictions()) == 0 {
return nil, ErrEmptyResponse
}
return resp.GetPredictions(), nil
}
func (c *PaLMClient) projectLocationPublisherModelPath(projectID, location, publisher, model string) string {
return fmt.Sprintf("projects/%s/locations/%s/publishers/%s/models/%s", projectID, location, publisher, model)
}