-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathapi.py
1295 lines (1214 loc) · 51.9 KB
/
api.py
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# type: ignore[pb2]
import concurrent.futures as cf
import copy
import os
import time
from typing import Dict, List, Optional, Tuple, Union
from google.protobuf.json_format import MessageToDict
from google.protobuf.wrappers_pb2 import BoolValue, DoubleValue
from requests_futures.sessions import FuturesSession
from arize.utils.constants import (
API_KEY_ENVVAR_NAME,
LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME,
LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME,
LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME,
LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME,
MAX_FUTURE_YEARS_FROM_CURRENT_TIME,
MAX_LLM_MODEL_NAME_LENGTH,
MAX_LLM_MODEL_NAME_LENGTH_TRUNCATION,
MAX_NUMBER_OF_EMBEDDINGS,
MAX_PAST_YEARS_FROM_CURRENT_TIME,
MAX_PREDICTION_ID_LEN,
MAX_PROMPT_TEMPLATE_LENGTH,
MAX_PROMPT_TEMPLATE_LENGTH_TRUNCATION,
MAX_PROMPT_TEMPLATE_VERSION_LENGTH,
MAX_PROMPT_TEMPLATE_VERSION_LENGTH_TRUNCATION,
MAX_TAG_LENGTH,
MAX_TAG_LENGTH_TRUNCATION,
MIN_PREDICTION_ID_LEN,
RESERVED_TAG_COLS,
SPACE_ID_ENVVAR_NAME,
SPACE_KEY_ENVVAR_NAME,
)
from arize.utils.errors import (
InvalidAdditionalHeaders,
InvalidNumberOfEmbeddings,
)
from arize.version import __version__
from . import public_pb2 as pb2
from .bounded_executor import BoundedExecutor
from .single_log.casting import cast_dictionary
from .utils.errors import (
AuthError,
InvalidCertificateFile,
InvalidStringLength,
InvalidValueType,
)
from .utils.logging import get_truncation_warning_message, logger
from .utils.types import (
CATEGORICAL_MODEL_TYPES,
NUMERIC_MODEL_TYPES,
Embedding,
Environments,
InstanceSegmentationActualLabel,
InstanceSegmentationPredictionLabel,
LLMRunMetadata,
ModelTypes,
MultiClassActualLabel,
MultiClassPredictionLabel,
ObjectDetectionLabel,
RankingActualLabel,
RankingPredictionLabel,
SemanticSegmentationLabel,
TypedValue,
_PromptOrResponseText,
is_list_of,
)
from .utils.utils import (
convert_dictionary,
convert_element,
get_python_version,
get_timestamp,
is_timestamp_in_range,
)
PredictionLabelTypes = Union[
str,
bool,
int,
float,
Tuple[str, float],
ObjectDetectionLabel,
RankingPredictionLabel,
MultiClassPredictionLabel,
]
ActualLabelTypes = Union[
str,
bool,
int,
float,
Tuple[str, float],
ObjectDetectionLabel,
RankingActualLabel,
MultiClassActualLabel,
]
class Client:
"""
Arize API Client to log model predictions and actuals to the Arize AI platform
"""
def __init__(
self,
api_key: Optional[str] = None,
space_id: Optional[str] = None,
space_key: Optional[str] = None,
uri: Optional[str] = "https://api.arize.com/v1",
max_workers: Optional[int] = 8,
max_queue_bound: Optional[int] = 5000,
timeout: Optional[int] = 200,
additional_headers: Optional[Dict[str, str]] = None,
request_verify: Union[bool, str] = True,
) -> None:
"""
Initializes the Arize Client
Arguments:
---------
api_key (str): Arize provided API key associated with your account. Located on the
data upload page.
space_id (str): Arize provided identifier to connect records to spaces. Located on
the space settings.
space_key (str): [Deprecated] Arize provided identifier to connect records to spaces.
Located on the space settings.
uri (str, optional): URI to send your records to Arize AI. Defaults to
"https://api.arize.com/v1".
max_workers (int, optional): maximum number of concurrent requests to Arize. Defaults
to 8.
max_queue_bound (int, optional): maximum number of concurrent future objects
generated for publishing to Arize. Defaults to 5000.
timeout (int, optional): How long to wait for the server to send data before giving
up. Defaults to 200.
additional_headers (Dict[str, str], optional): Dictionary of additional headers to
append to request
"""
self._api_key = api_key or os.getenv(API_KEY_ENVVAR_NAME)
self._space_id = space_id or os.getenv(SPACE_ID_ENVVAR_NAME)
self._space_key = space_key or os.getenv(SPACE_KEY_ENVVAR_NAME)
if self._space_key is not None:
logger.warning(
"The space_key parameter is deprecated and will be removed in a future release. "
"Please use the space_id parameter instead."
)
if isinstance(request_verify, str) and not os.path.isfile(
request_verify
):
raise InvalidCertificateFile(request_verify)
self._request_verify = request_verify
self._uri = f"{uri}/log"
self._timeout = timeout
self._session = FuturesSession(
executor=BoundedExecutor(max_queue_bound, max_workers)
)
# Grpc-Metadata prefix is required to pass non-standard md through via grpc-gateway
self._headers = {
"authorization": api_key,
"Grpc-Metadata-arize-space-id": space_id,
"Grpc-Metadata-space_id": space_id, # deprecated, will be removed in future release
"Grpc-Metadata-space": space_key, # deprecated, will be removed in future release
"Grpc-Metadata-arize-space-key": space_key, # deprecated, will be removed in future release
"Grpc-Metadata-arize-interface": "stream",
"Grpc-Metadata-sdk-language": "python",
"Grpc-Metadata-language-version": get_python_version(),
"Grpc-Metadata-sdk-version": __version__,
}
if additional_headers is not None:
conflicting_keys = self._headers.keys() & additional_headers.keys()
if conflicting_keys:
raise InvalidAdditionalHeaders(conflicting_keys)
self._headers.update(additional_headers)
def log(
self,
model_id: str,
model_type: ModelTypes,
environment: Environments,
model_version: Optional[str] = None,
prediction_id: Optional[Union[str, int, float]] = None,
prediction_timestamp: Optional[int] = None,
prediction_label: Optional[PredictionLabelTypes] = None,
actual_label: Optional[ActualLabelTypes] = None,
features: Optional[
Dict[str, Union[str, bool, float, int, List[str], TypedValue]]
] = None,
embedding_features: Optional[Dict[str, Embedding]] = None,
shap_values: Optional[Dict[str, float]] = None,
tags: Optional[
Dict[str, Union[str, bool, float, int, TypedValue]]
] = None,
batch_id: Optional[str] = None,
prompt: Optional[Union[str, Embedding]] = None,
response: Optional[Union[str, Embedding]] = None,
prompt_template: Optional[str] = None,
prompt_template_version: Optional[str] = None,
llm_model_name: Optional[str] = None,
llm_params: Optional[Dict[str, Union[str, bool, float, int]]] = None,
llm_run_metadata: Optional[LLMRunMetadata] = None,
) -> cf.Future:
"""
Logs a record to Arize via a POST request.
Args:
model_id (str): A unique name to identify your model in the Arize platform.
model_type (ModelTypes): Declare your model type. Can check the supported model types
running `ModelTypes.list_types()`
environment (Environments): The environment that this dataframe is for (Production,
Training, Validation).
model_version (str, optional): Used to group together a subset of predictions
and actuals for a given model_id to track and compare changes. Defaults to None.
prediction_id (str, int, or float, optional): A unique string to identify a
prediction event. This value is used to match a prediction to delayed actuals in Arize. If
prediction id is not provided, Arize will, when possible, create a random prediction
id on the server side.
prediction_timestamp (int, optional): Unix timestamp in seconds. If None, prediction
uses current timestamp. Defaults to None.
prediction_label (bool, int, float, str, Tuple(str, float), ObjectDetectionLabel,
RankingPredictionLabel or MultiClassPredictionLabel; optional):
The predicted value for a given model input. Defaults to None.
actual_label (
bool, int, float, str, Tuple[str, float],
ObjectDetectionLabel, RankingActualLabel, MultiClassActualLabel,
optional
):
The ground truth value for a given model input. This will be matched to the
prediction with the same prediction_id as the one in this call. Defaults to None.
features (Dict[str, Union[str, bool, float, int]], optional): Dictionary containing
human readable and debuggable model features. Defaults to None.
embedding_features (Dict[str, Embedding], optional): Dictionary containing model
embedding features. Keys must be strings. Values must be of type Embedding. Defaults to
None.
shap_values (Dict[str, float], optional): Dictionary containing human readable and
debuggable model features keys, along with SHAP feature importance values. Defaults to None.
tags (Dict[str, Union[str, bool, float, int]], optional): Dictionary containing human
readable and debuggable model tags. Defaults to None.
batch_id (str, optional): Used to distinguish different batch of data under the same
model_id and model_version. Required for VALIDATION environments. Defaults to None.
prompt (str or Embedding, optional): input text on which the GENERATIVE_LLM model acts. It
accepts a string or Embedding object (if sending embedding vectors is desired). Required
for GENERATIVE_LLM models. Defaults to None.
response (str or Embedding, optional): output text from GENERATIVE_LLM model. It accepts
a string or Embedding object (if sending embedding vectors is desired). Required for
GENERATIVE_LLM models. Defaults to None.
prompt_template (str, optional): template used to construct the prompt passed to a large language
model. It can include variable using the double braces notation. Example: 'Given the context
{{context}}, answer the following question {{user_question}}.
prompt_template_version (str, optional): version of the template used.
llm_model_name (str, optional): name of the llm used. Example: 'gpt-4'.
llm_params (str, optional): hyperparameters passed to the large language model.
llm_run_metadata (LLMRunMetadata, optional): run metadata for llm calls.
Returns:
`concurrent.futures.Future` object
"""
# This method requires the API key and either space ID or space key to be set
# api_key and one of space_id or space_key must be provided
if not self._api_key or not (self._space_id or self._space_key):
raise AuthError(
missing_space_id=not (self._space_id or self._space_key),
missing_api_key=not self._api_key,
method_name="log",
)
# Validate model_id
if not isinstance(model_id, str):
raise InvalidValueType("model_id", model_id, "str")
# Validate model_type
if not isinstance(model_type, ModelTypes):
raise InvalidValueType(
"model_type", model_type, "arize.utils.ModelTypes"
)
# Validate environment
if not isinstance(environment, Environments):
raise InvalidValueType(
"environment", environment, "arize.utils.Environments"
)
# Validate batch_id
if environment == Environments.VALIDATION and (
batch_id is None
or not isinstance(batch_id, str)
or len(batch_id.strip()) == 0
):
raise ValueError(
"Batch ID must be a nonempty string if logging to validation environment."
)
# Convert & Validate prediction_id
prediction_id = _validate_and_convert_prediction_id(
prediction_id,
environment,
prediction_label,
actual_label,
shap_values,
)
# Cast feature & tag values
features = cast_dictionary(features)
tags = cast_dictionary(tags)
# Validate feature types
if features:
if not isinstance(features, dict):
raise InvalidValueType("features", features, "dict")
for feat_name, feat_value in features.items():
_validate_mapping_key(feat_name, "features")
if is_list_of(feat_value, str):
continue
else:
val = convert_element(feat_value)
if val is not None and not isinstance(
val, (str, bool, float, int)
):
raise InvalidValueType(
f"feature '{feat_name}'",
feat_value,
"one of: bool, int, float, str",
)
# Validate embedding_features type
if embedding_features:
if not isinstance(embedding_features, dict):
raise InvalidValueType(
"embedding_features", embedding_features, "dict"
)
if len(embedding_features) > MAX_NUMBER_OF_EMBEDDINGS:
raise InvalidNumberOfEmbeddings(len(embedding_features))
if (
model_type == ModelTypes.OBJECT_DETECTION
and len(embedding_features.keys()) > 1
):
# Check that there is only 1 embedding feature for OD model types
raise ValueError(
"Object Detection models only support one embedding feature"
)
if model_type == ModelTypes.GENERATIVE_LLM:
# Check reserved keys are not used
reserved_emb_feat_names = {"prompt", "response"}
if reserved_emb_feat_names & embedding_features.keys():
raise KeyError(
"embedding features cannot use the reserved feature names ('prompt', 'response') "
"for GENERATIVE_LLM models"
)
for emb_name, emb_obj in embedding_features.items():
_validate_mapping_key(emb_name, "embedding features")
# Must verify embedding type
if not isinstance(emb_obj, Embedding):
raise InvalidValueType(
f"embedding feature '{emb_name}'", emb_obj, "Embedding"
)
emb_obj.validate(emb_name)
# Validate tag types
if tags:
if not isinstance(tags, dict):
raise InvalidValueType("tags", tags, "dict")
wrong_tags = [
tag_name for tag_name in tags if tag_name in RESERVED_TAG_COLS
]
if wrong_tags:
raise KeyError(
f"The following tag names are not allowed as they are reserved: {wrong_tags}"
)
for tag_name, tag_value in tags.items():
_validate_mapping_key(tag_name, "tags")
val = convert_element(tag_value)
if val is not None and not isinstance(
val, (str, bool, float, int)
):
raise InvalidValueType(
f"tag '{tag_name}'",
tag_value,
"one of: bool, int, float, str",
)
if isinstance(tag_name, str) and tag_name.endswith("_shap"):
raise ValueError(
f"tag {tag_name} must not be named with a `_shap` suffix"
)
if len(str(val)) > MAX_TAG_LENGTH:
raise ValueError(
f"The number of characters for each tag must be less than or equal to "
f"{MAX_TAG_LENGTH}. The tag {tag_name} with value {tag_value} has "
f"{len(str(val))} characters."
)
elif len(str(val)) > MAX_TAG_LENGTH_TRUNCATION:
logger.warning(
get_truncation_warning_message(
"tags", MAX_TAG_LENGTH_TRUNCATION
)
)
# Check the timestamp present on the event
if prediction_timestamp is not None:
if not isinstance(prediction_timestamp, int):
raise InvalidValueType(
"prediction_timestamp", prediction_timestamp, "int"
)
# Send warning if prediction is sent with future timestamp
now = int(time.time())
if prediction_timestamp > now:
logger.warning(
"Caution when sending a prediction with future timestamp."
"Arize only stores 2 years worth of data. For example, if you sent a prediction "
"to Arize from 1.5 years ago, and now send a prediction with timestamp of a year in "
"the future, the oldest 0.5 years will be dropped to maintain the 2 years worth of data "
"requirement."
)
if not is_timestamp_in_range(now, prediction_timestamp):
raise ValueError(
f"prediction_timestamp: {prediction_timestamp} is out of range."
f"Prediction timestamps must be within {MAX_FUTURE_YEARS_FROM_CURRENT_TIME} year in the "
f"future and {MAX_PAST_YEARS_FROM_CURRENT_TIME} years in the past from the current time."
)
# Validate GENERATIVE_LLM models requirements
if model_type == ModelTypes.GENERATIVE_LLM:
if prompt is not None:
if not isinstance(prompt, (str, Embedding)):
raise TypeError(
f"prompt must be of type str or Embedding, but found {type(val)}"
)
if isinstance(prompt, str):
prompt = _PromptOrResponseText(data=prompt)
# Validate content of prompt, type is either Embedding or _PromptOrResponseText
prompt.validate("prompt")
if response is not None:
if not isinstance(response, (str, Embedding)):
raise TypeError(
f"response must be of type str or Embedding, but found {type(val)}"
)
if isinstance(response, str):
response = _PromptOrResponseText(data=response)
# Validate content of response, type is either Embedding or _PromptOrResponseText
response.validate("response")
# Validate prompt templates workflow information
_validate_prompt_templates_and_llm_config(
prompt_template,
prompt_template_version,
llm_model_name,
llm_params,
)
# Validate llm run metadata
if llm_run_metadata is not None:
llm_run_metadata.validate()
else:
if prompt is not None or response is not None:
raise ValueError(
"The fields 'prompt' and 'response' must be None for model types other "
"than GENERATIVE_LLM"
)
# Construct the prediction
p = None
# Only set a default prediction label for generative LLM models if there is no explicit prediction
# label AND no actual label to ensure that generative LLM model prediction records will have a
# prediction label that can be used for metrics in the platform (as users will generally pass in
# actuals/user feedback only). We do not want to add the default prediction label in if actual labels
# are present so that latent actuals will still work.
if (
model_type == ModelTypes.GENERATIVE_LLM
and prediction_label is None
and actual_label is None
):
prediction_label = "1"
if prediction_label is not None:
if model_version is not None and not isinstance(model_version, str):
raise InvalidValueType("model_version", model_version, "str")
_validate_label(
prediction_or_actual="prediction",
model_type=model_type,
label=convert_element(prediction_label),
embedding_features=embedding_features,
)
p = pb2.Prediction(
prediction_label=_get_label(
prediction_or_actual="prediction",
value=prediction_label,
model_type=model_type,
),
model_version=model_version,
)
if features is not None:
converted_feats = convert_dictionary(features)
feats = pb2.Prediction(features=converted_feats)
p.MergeFrom(feats)
if embedding_features or prompt or response:
# NOTE: Deep copy is necessary to avoid side effects on the original input dictionary
combined_embedding_features = (
{k: v for k, v in embedding_features.items()}
if embedding_features
else {}
)
# Map prompt as embedding features for generative models
if prompt is not None:
combined_embedding_features.update({"prompt": prompt})
# Map response as embedding features for generative models
if response is not None:
combined_embedding_features.update({"response": response})
converted_embedding_feats = convert_dictionary(
combined_embedding_features
)
embedding_feats = pb2.Prediction(
features=converted_embedding_feats
)
p.MergeFrom(embedding_feats)
if tags or llm_run_metadata:
joined_tags = copy.deepcopy(tags)
if llm_run_metadata:
if llm_run_metadata.total_token_count is not None:
joined_tags[
LLM_RUN_METADATA_TOTAL_TOKEN_COUNT_TAG_NAME
] = llm_run_metadata.total_token_count
if llm_run_metadata.prompt_token_count is not None:
joined_tags[
LLM_RUN_METADATA_PROMPT_TOKEN_COUNT_TAG_NAME
] = llm_run_metadata.prompt_token_count
if llm_run_metadata.response_token_count is not None:
joined_tags[
LLM_RUN_METADATA_RESPONSE_TOKEN_COUNT_TAG_NAME
] = llm_run_metadata.response_token_count
if llm_run_metadata.response_latency_ms is not None:
joined_tags[
LLM_RUN_METADATA_RESPONSE_LATENCY_MS_TAG_NAME
] = llm_run_metadata.response_latency_ms
converted_tags = convert_dictionary(joined_tags)
tgs = pb2.Prediction(tags=converted_tags)
p.MergeFrom(tgs)
if (
prompt_template
or prompt_template_version
or llm_model_name
or llm_params
):
llm_fields = pb2.LLMFields(
prompt_template=prompt_template or "",
prompt_template_name=prompt_template_version or "",
llm_model_name=llm_model_name or "",
llm_params=convert_dictionary(llm_params),
)
p.MergeFrom(pb2.Prediction(llm_fields=llm_fields))
if prediction_timestamp is not None:
p.timestamp.MergeFrom(get_timestamp(prediction_timestamp))
# Validate and construct the optional actual
is_latent_tags = prediction_label is None and tags is not None
a = None
if actual_label or is_latent_tags:
a = pb2.Actual()
if actual_label is not None:
_validate_label(
prediction_or_actual="actual",
model_type=model_type,
label=convert_element(actual_label),
embedding_features=embedding_features,
)
a.MergeFrom(
pb2.Actual(
actual_label=_get_label(
prediction_or_actual="actual",
value=actual_label,
model_type=model_type,
)
)
)
# Added to support delayed tags on actuals.
if tags is not None:
converted_tags = convert_dictionary(tags)
a.MergeFrom(pb2.Actual(tags=converted_tags))
# Validate and construct the optional feature importances
fi = None
if shap_values is not None and bool(shap_values):
for k, v in shap_values.items():
if not isinstance(convert_element(v), float):
raise InvalidValueType(f"feature '{k}'", v, "float")
if isinstance(k, str) and k.endswith("_shap"):
raise ValueError(
f"feature {k} must not be named with a `_shap` suffix"
)
fi = pb2.FeatureImportances(feature_importances=shap_values)
if p is None and a is None and fi is None:
raise ValueError(
"must provide at least one of prediction_label, actual_label, tags, or shap_values"
)
env_params = None
if environment == Environments.TRAINING:
if p is None or a is None:
raise ValueError(
"Training records must have both Prediction and Actual"
)
env_params = pb2.Record.EnvironmentParams(
training=pb2.Record.EnvironmentParams.Training()
)
elif environment == Environments.VALIDATION:
if p is None or a is None:
raise ValueError(
"Validation records must have both Prediction and Actual"
)
env_params = pb2.Record.EnvironmentParams(
validation=pb2.Record.EnvironmentParams.Validation(
batch_id=batch_id
)
)
elif environment == Environments.PRODUCTION:
env_params = pb2.Record.EnvironmentParams(
production=pb2.Record.EnvironmentParams.Production()
)
rec = pb2.Record(
space_key=self._space_key,
model_id=model_id,
prediction_id=prediction_id,
prediction=p,
actual=a,
feature_importances=fi,
environment_params=env_params,
is_generative_llm_record=BoolValue(
value=model_type == ModelTypes.GENERATIVE_LLM
),
)
return self._post(record=rec, uri=self._uri, indexes=None)
def _post(self, record, uri, indexes):
resp = self._session.post(
uri,
headers=self._headers,
timeout=self._timeout,
json=MessageToDict(
message=record, preserving_proto_field_name=True
),
verify=self._request_verify,
)
if indexes is not None and len(indexes) == 2:
resp.starting_index = indexes[0]
resp.ending_index = indexes[1]
return resp
def _validate_label(
prediction_or_actual: str,
model_type: ModelTypes,
label: Union[
str,
bool,
int,
float,
Tuple[Union[str, bool], float],
ObjectDetectionLabel,
RankingPredictionLabel,
RankingActualLabel,
SemanticSegmentationLabel,
InstanceSegmentationPredictionLabel,
InstanceSegmentationActualLabel,
MultiClassPredictionLabel,
MultiClassActualLabel,
],
embedding_features: Dict[str, Embedding],
):
if model_type in NUMERIC_MODEL_TYPES:
_validate_numeric_label(model_type, label)
elif model_type in CATEGORICAL_MODEL_TYPES:
_validate_categorical_label(model_type, label)
elif model_type == ModelTypes.OBJECT_DETECTION:
_validate_cv_label(prediction_or_actual, label, embedding_features)
elif model_type == ModelTypes.RANKING:
_validate_ranking_label(label)
elif model_type == ModelTypes.GENERATIVE_LLM:
_validate_generative_llm_label(label)
elif model_type == ModelTypes.MULTI_CLASS:
_validate_multi_class_label(label)
else:
raise InvalidValueType(
"model_type", model_type, "arize.utils.ModelTypes"
)
def _validate_numeric_label(
model_type: ModelTypes,
label: Union[str, bool, int, float, Tuple[Union[str, bool], float]],
):
if not isinstance(label, (float, int)):
raise InvalidValueType(
f"label {label}",
label,
f"either float or int for model_type {model_type}",
)
def _validate_categorical_label(
model_type: ModelTypes,
label: Union[str, bool, int, float, Tuple[Union[str, bool], float]],
):
is_valid = isinstance(label, (str, bool, int, float)) or (
isinstance(label, tuple)
and isinstance(label[0], (str, bool))
and isinstance(label[1], float)
)
if not is_valid:
raise InvalidValueType(
f"label {label}",
label,
f"one of: bool, int, float, str or Tuple[str, float] for model type {model_type}",
)
def _validate_cv_label(
prediction_or_actual: str,
label: Union[
ObjectDetectionLabel,
SemanticSegmentationLabel,
InstanceSegmentationPredictionLabel,
InstanceSegmentationActualLabel,
],
embedding_features: Dict[str, Embedding],
):
if (
not isinstance(label, ObjectDetectionLabel)
and not isinstance(label, SemanticSegmentationLabel)
and not isinstance(label, InstanceSegmentationPredictionLabel)
and not isinstance(label, InstanceSegmentationActualLabel)
):
raise InvalidValueType(
f"label {label}",
label,
"one of: ObjectDetectionLabel, SemanticSegmentationLabel, InstanceSegmentationPredictionLabel, "
f"or InstanceSegmentationActualLabel for model type {ModelTypes.OBJECT_DETECTION}",
)
if embedding_features is None:
raise ValueError(
f"Cannot use {type(label)} without an embedding feature"
)
if len(embedding_features.keys()) != 1:
raise ValueError(
f"{type(label)} must be sent with exactly one embedding feature"
)
if isinstance(label, ObjectDetectionLabel):
label.validate(prediction_or_actual=prediction_or_actual)
else:
label.validate()
def _validate_ranking_label(
label: Union[RankingPredictionLabel, RankingActualLabel],
):
if not isinstance(label, (RankingPredictionLabel, RankingActualLabel)):
raise InvalidValueType(
f"label {label}",
label,
f"RankingPredictionLabel or RankingActualLabel for model type {ModelTypes.RANKING}",
)
label.validate()
def _validate_generative_llm_label(
label: Union[str, bool, int, float],
):
is_valid = isinstance(label, (str, bool, int, float))
if not is_valid:
raise InvalidValueType(
f"label {label}",
label,
f"one of: bool, int, float, str for model type {ModelTypes.GENERATIVE_LLM}",
)
def _validate_multi_class_label(
label: Union[MultiClassPredictionLabel, MultiClassActualLabel],
):
if not isinstance(
label, (MultiClassPredictionLabel, MultiClassActualLabel)
):
raise InvalidValueType(
f"label {label}",
label,
f"MultiClassPredictionLabel or MultiClassActualLabel for model type {ModelTypes.MULTI_CLASS}",
)
label.validate()
def _get_label(
prediction_or_actual: str,
value: Union[
str,
bool,
int,
float,
Tuple[str, float],
ObjectDetectionLabel,
SemanticSegmentationLabel,
InstanceSegmentationPredictionLabel,
InstanceSegmentationActualLabel,
RankingPredictionLabel,
RankingActualLabel,
MultiClassPredictionLabel,
MultiClassActualLabel,
],
model_type: ModelTypes,
) -> Union[pb2.PredictionLabel, pb2.ActualLabel]:
value = convert_element(value)
if model_type in NUMERIC_MODEL_TYPES:
return _get_numeric_label(prediction_or_actual, value)
elif (
model_type in CATEGORICAL_MODEL_TYPES
or model_type == ModelTypes.GENERATIVE_LLM
):
return _get_score_categorical_label(prediction_or_actual, value)
elif model_type == ModelTypes.OBJECT_DETECTION:
return _get_cv_label(prediction_or_actual, value)
elif model_type == ModelTypes.RANKING:
return _get_ranking_label(value)
elif model_type == ModelTypes.MULTI_CLASS:
return _get_multi_class_label(value)
raise ValueError(
f"model_type must be one of: {[mt.prediction_or_actual for mt in ModelTypes]} "
f"Got "
f"{model_type} instead."
)
def _get_numeric_label(
prediction_or_actual: str,
value: Union[int, float],
) -> Union[pb2.PredictionLabel, pb2.ActualLabel]:
if not isinstance(value, (int, float)):
raise TypeError(
f"Received {prediction_or_actual}_label = {value}, of type {type(value)}. "
+ f"{[mt.prediction_or_actual for mt in NUMERIC_MODEL_TYPES]} models accept labels of "
f"type int or float"
)
if prediction_or_actual == "prediction":
return pb2.PredictionLabel(numeric=value)
elif prediction_or_actual == "actual":
return pb2.ActualLabel(numeric=value)
def _get_score_categorical_label(
prediction_or_actual: str,
value: Union[bool, str, Tuple[str, float]],
) -> Union[pb2.PredictionLabel, pb2.ActualLabel]:
sc = pb2.ScoreCategorical()
if isinstance(value, bool):
sc.category.category = str(value)
elif isinstance(value, str):
sc.category.category = value
elif isinstance(value, (int, float)):
sc.score_value.value = value
elif isinstance(value, tuple):
# Expect Tuple[str,float]
if value[1] is None:
raise TypeError(
f"Received {prediction_or_actual}_label = {value}, of type "
f"{type(value)}[{type(value[0])}, None]. "
f"{[mt.prediction_or_actual for mt in CATEGORICAL_MODEL_TYPES]} models accept "
"values of type str, bool, or Tuple[str, float]"
)
if not isinstance(value[0], (bool, str)) or not isinstance(
value[1], float
):
raise TypeError(
f"Received {prediction_or_actual}_label = {value}, of type "
f"{type(value)}[{type(value[0])}, {type(value[1])}]. "
f"{[mt.prediction_or_actual for mt in CATEGORICAL_MODEL_TYPES]} models accept "
"values of type str, bool, or Tuple[str or bool, float]"
)
if isinstance(value[0], bool):
sc.score_category.category = str(value[0])
else:
sc.score_category.category = value[0]
sc.score_category.score = value[1]
else:
raise TypeError(
f"Received {prediction_or_actual}_label = {value}, of type {type(value)}. "
+ f"{[mt.prediction_or_actual for mt in CATEGORICAL_MODEL_TYPES]} models accept values "
f"of type str, bool, int, float or Tuple[str, float]"
)
if prediction_or_actual == "prediction":
return pb2.PredictionLabel(score_categorical=sc)
elif prediction_or_actual == "actual":
return pb2.ActualLabel(score_categorical=sc)
def _get_cv_label(
prediction_or_actual: str,
value: Union[
ObjectDetectionLabel,
SemanticSegmentationLabel,
InstanceSegmentationPredictionLabel,
InstanceSegmentationActualLabel,
],
) -> Union[pb2.PredictionLabel, pb2.ActualLabel]:
if isinstance(value, ObjectDetectionLabel):
return _get_object_detection_label(prediction_or_actual, value)
elif isinstance(value, SemanticSegmentationLabel):
return _get_semantic_segmentation_label(prediction_or_actual, value)
elif isinstance(value, InstanceSegmentationPredictionLabel):
return _get_instance_segmentation_prediction_label(value)
elif isinstance(value, InstanceSegmentationActualLabel):
return _get_instance_segmentation_actual_label(value)
else:
raise InvalidValueType(
"cv label",
value,
"ObjectDetectionLabel, SemanticSegmentationLabel, or "
"InstanceSegmentationPredictionLabel for model type "
f"{ModelTypes.OBJECT_DETECTION}",
)
def _get_object_detection_label(
prediction_or_actual: str,
value: ObjectDetectionLabel,
) -> Union[pb2.PredictionLabel, pb2.ActualLabel]:
if not isinstance(value, ObjectDetectionLabel):
raise InvalidValueType(
"object detection label",
value,
f"ObjectDetectionLabel for model type {ModelTypes.OBJECT_DETECTION}",
)
od = pb2.ObjectDetection()
bounding_boxes = []
for i in range(len(value.bounding_boxes_coordinates)):
coordinates = value.bounding_boxes_coordinates[i]
category = value.categories[i]
if value.scores is None:
bounding_boxes.append(
pb2.ObjectDetection.BoundingBox(
coordinates=coordinates, category=category
)
)
else:
score = value.scores[i]
bounding_boxes.append(
pb2.ObjectDetection.BoundingBox(
coordinates=coordinates,
category=category,
score=DoubleValue(value=score),
)
)
od.bounding_boxes.extend(bounding_boxes)
if prediction_or_actual == "prediction":
return pb2.PredictionLabel(object_detection=od)
elif prediction_or_actual == "actual":
return pb2.ActualLabel(object_detection=od)
def _get_semantic_segmentation_label(
prediction_or_actual: str,
value: SemanticSegmentationLabel,
) -> Union[pb2.PredictionLabel, pb2.ActualLabel]:
if not isinstance(value, SemanticSegmentationLabel):
raise InvalidValueType(
"semantic segmentation label",
value,
f"SemanticSegmentationLabel for model type {ModelTypes.OBJECT_DETECTION}",
)
polygons = []
for i in range(len(value.polygon_coordinates)):
coordinates = value.polygon_coordinates[i]
category = value.categories[i]
polygons.append(
pb2.SemanticSegmentationPolygon(
coordinates=coordinates, category=category
)
)
if prediction_or_actual == "prediction":
cv_label = pb2.CVPredictionLabel()
cv_label.semantic_segmentation_label.polygons.extend(polygons)
return pb2.PredictionLabel(cv_label=cv_label)
elif prediction_or_actual == "actual":
cv_label = pb2.CVActualLabel()
cv_label.semantic_segmentation_label.polygons.extend(polygons)
return pb2.ActualLabel(cv_label=cv_label)
def _get_instance_segmentation_prediction_label(
value: InstanceSegmentationPredictionLabel,
) -> Union[pb2.PredictionLabel, pb2.ActualLabel]:
if not isinstance(value, InstanceSegmentationPredictionLabel):
raise InvalidValueType(
"instance segmentation prediction label",
value,
f"InstanceSegmentationPredictionLabel for model type {ModelTypes.OBJECT_DETECTION}",
)
polygons = []
for i in range(len(value.polygon_coordinates)):
coordinates = value.polygon_coordinates[i]
category = value.categories[i]
score = (
DoubleValue(value=value.scores[i])