-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
298 lines (263 loc) · 7.85 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
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
package arize
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"runtime"
"strconv"
"strings"
"time"
pb "github.com/Arize-ai/client_golang/receiver/protocol/public"
"google.golang.org/protobuf/types/known/wrapperspb"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/pkg/errors"
)
const (
baseURL = "https://api.arize.com"
sdkVersion = "0.1.1"
)
// Client for Arize api.
type Client struct {
client httpClient
baseURL string
spaceKey string
apiKey string
headers map[string][]string
}
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
func NewClient(spaceKey, apiKey string) *Client {
heads := map[string][]string{
"authorization": {apiKey},
"Grpc-Metadata-space": {spaceKey},
"Grpc-Metadata-sdk-language": {"golang"},
"Grpc-Metadata-language-version": {get_golang_version()},
"Grpc-Metadata-sdk-version": {sdkVersion},
}
return &Client{
client: http.DefaultClient,
apiKey: apiKey,
spaceKey: spaceKey,
baseURL: baseURL,
headers: heads,
}
}
func (c *Client) Log(ctx context.Context, modelID string, modelVersion *string, predictionID string, features, tags map[string]interface{}, shapValues map[string]float64, prediction, actual interface{}, timestamp *time.Time, embeddingFeatures map[string]*Embeddings) (*Response, error) {
if modelID == "" {
return nil, errors.New("modelID can not be empty")
}
if predictionID == "" {
return nil, errors.New("predictionID can not be empty")
}
predictionLabel, err := parseLabel(prediction)
if err != nil {
return nil, err
}
actualLabel, err := parseLabel(actual)
if err != nil {
return nil, err
}
if err = validateLabels(predictionLabel, actualLabel); err != nil {
return nil, err
}
var ts *timestamppb.Timestamp
if timestamp == nil {
ts = timestamppb.Now()
} else {
ts = timestamppb.New(*timestamp)
}
tagsM, err := parseDimensions(tags)
if err != nil {
return nil, err
}
rec := &pb.Record{
SpaceKey: c.spaceKey,
ModelId: modelID,
PredictionId: predictionID,
}
var mv string
if modelVersion != nil {
mv = *modelVersion
}
// set prediction message if applicable
if predictionLabel != nil {
fs, err := parseDimensions(features)
if err != nil {
return nil, err
}
es, err := parseEmbeddings(embeddingFeatures)
if err != nil {
return nil, err
}
for k, v := range es {
fs[k] = v
}
pred := &pb.Prediction{
Timestamp: ts,
ModelVersion: mv,
Label: predictionLabel,
Features: fs,
Tags: tagsM,
}
rec.Prediction = pred
}
// set actual label if applicable
if actualLabel != nil {
a := &pb.Actual{
Label: actualLabel,
Tags: tagsM,
Timestamp: ts,
}
rec.Actual = a
}
if shapValues != nil && len(shapValues) > 0 {
fi := &pb.FeatureImportances{
FeatureImportances: shapValues,
ModelVersion: mv,
Timestamp: ts,
}
rec.FeatureImportances = fi
}
body, err := protojson.Marshal(rec)
if err != nil {
return nil, fmt.Errorf("error creating request body: %w", err)
}
uri := fmt.Sprintf("%s/v1/%s", c.baseURL, "log")
req, err := http.NewRequestWithContext(ctx, "POST", uri, bytes.NewBuffer(body))
if err != nil {
return nil, errors.Wrap(err, "error creating new request to arize")
}
req.Header = c.headers
resp, err := c.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "HTTP request failure on request to arize")
}
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
return &Response{StatusCode: resp.StatusCode, Body: string(b)}, nil
}
func validateLabels(pl, al *pb.Label) error {
// this validation is only be evaluated if both labels are non-nil
if pl == nil || al == nil {
return nil
}
switch pl.GetData().(type) {
case *pb.Label_ScoreCategorical:
if _, ok := al.GetData().(*pb.Label_ScoreCategorical); !ok {
return errors.Errorf("prediction and actual labels need to be the same type. prediction = %v, actual = %v", pl, al)
}
case *pb.Label_Numeric:
if _, ok := al.GetData().(*pb.Label_Numeric); !ok {
return errors.Errorf("prediction and actual labels need to be the same type. prediction = %v, actual = %v", pl, al)
}
default:
return errors.Errorf("unknown prediciton label. prediction = %v", pl)
}
return nil
}
func parseLabel(labelValue interface{}) (*pb.Label, error) {
if labelValue == nil {
return nil, nil
}
switch labelValue.(type) {
case *ScoreCategorical:
lv := labelValue.(*ScoreCategorical)
st := &pb.ScoreCategorical_ScoreCategory_{ScoreCategory: &pb.ScoreCategorical_ScoreCategory{Category: lv.Category, Score: lv.Score, NumericSequence: lv.NumericSequence}}
scc := &pb.ScoreCategorical{Type: st}
return &pb.Label{Data: &pb.Label_ScoreCategorical{ScoreCategorical: scc}}, nil
case string:
st := &pb.ScoreCategorical_Category_{Category: &pb.ScoreCategorical_Category{Category: labelValue.(string)}}
scc := &pb.ScoreCategorical{Type: st}
return &pb.Label{Data: &pb.Label_ScoreCategorical{ScoreCategorical: scc}}, nil
case bool:
st := &pb.ScoreCategorical_Category_{Category: &pb.ScoreCategorical_Category{Category: strconv.FormatBool(labelValue.(bool))}}
scc := &pb.ScoreCategorical{Type: st}
return &pb.Label{Data: &pb.Label_ScoreCategorical{ScoreCategorical: scc}}, nil
case int:
return &pb.Label{Data: &pb.Label_Numeric{Numeric: float64(labelValue.(int))}}, nil
case int64:
return &pb.Label{Data: &pb.Label_Numeric{Numeric: float64(labelValue.(int64))}}, nil
case int32:
return &pb.Label{Data: &pb.Label_Numeric{Numeric: float64(labelValue.(int32))}}, nil
case float64:
return &pb.Label{Data: &pb.Label_Numeric{Numeric: labelValue.(float64)}}, nil
case float32:
return &pb.Label{Data: &pb.Label_Numeric{Numeric: float64(labelValue.(float32))}}, nil
default:
return nil, errors.Errorf("unknown type for labelValue = %v", labelValue)
}
}
func parseDimensions(dims map[string]interface{}) (map[string]*pb.Value, error) {
dms := make(map[string]*pb.Value)
for k, v := range dims {
pv, err := parseValue(v)
if err != nil {
return nil, err
}
dms[k] = pv
}
return dms, nil
}
func parseValue(val interface{}) (*pb.Value, error) {
switch val.(type) {
case string:
return &pb.Value{Data: &pb.Value_String_{String_: val.(string)}}, nil
case bool:
return &pb.Value{Data: &pb.Value_String_{String_: strconv.FormatBool(val.(bool))}}, nil
case float64:
return &pb.Value{Data: &pb.Value_Double{Double: val.(float64)}}, nil
case float32:
return &pb.Value{Data: &pb.Value_Double{Double: float64(val.(float32))}}, nil
case int:
return &pb.Value{Data: &pb.Value_Int{Int: int64(val.(int))}}, nil
case int32:
return &pb.Value{Data: &pb.Value_Int{Int: int64(val.(int32))}}, nil
case int64:
return &pb.Value{Data: &pb.Value_Int{Int: val.(int64)}}, nil
default:
return nil, errors.Errorf("unknown type for value = %v ", val)
}
}
func parseEmbeddings(es map[string]*Embeddings) (map[string]*pb.Value, error) {
ret := make(map[string]*pb.Value, len(es))
for k, e := range es {
if len(e.Vector) == 0 {
return nil, errors.Errorf("embeddings.vector can not be empty")
}
emb := &pb.Embedding{}
emb.Vector = e.Vector
if e.LinkToData != nil {
emb.LinkToData = wrapperspb.String(*e.LinkToData)
}
tok := &pb.Embedding_TokenArray{}
for _, v := range e.Data {
tok.Tokens = append(tok.Tokens, v)
}
rd := &pb.Embedding_RawData_TokenArray{TokenArray: tok}
raw := &pb.Embedding_RawData{Type: rd}
emb.RawData = raw
ret[k] = &pb.Value{Data: &pb.Value_Embedding{Embedding: emb}}
}
return ret, nil
}
type ScoreCategorical struct {
Score float64
Category string
NumericSequence []float64
}
type Embeddings struct {
Vector []float64
Data []string
LinkToData *string
}
type Response struct {
StatusCode int
Body string
}
func get_golang_version() string {
return strings.Split(runtime.Version(), "go")[1]
}