-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathtest_resources_codegen.py
1825 lines (1574 loc) · 81.7 KB
/
test_resources_codegen.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
import json
from sagemaker_core.tools.method import Method
from sagemaker_core.tools.resources_codegen import ResourcesCodeGen
from sagemaker_core.tools.constants import SERVICE_JSON_FILE_PATH
class TestGenerateResource:
@classmethod
def setup_class(cls):
# TODO: leverage pytest fixtures
with open(SERVICE_JSON_FILE_PATH, "r") as file:
service_json = json.load(file)
# Initialize parameters here
cls.resource_generator = ResourcesCodeGen(service_json)
# create a unit test for generate_create_method()
def test_generate_create_method(self):
expected_output = '''
@classmethod
@Base.add_validate_call
def create(
cls,
compilation_job_name: str,
role_arn: str,
output_config: OutputConfig,
stopping_condition: StoppingCondition,
model_package_version_arn: Optional[str] = Unassigned(),
input_config: Optional[InputConfig] = Unassigned(),
vpc_config: Optional[NeoVpcConfig] = Unassigned(),
tags: Optional[List[Tag]] = Unassigned(),
session: Optional[Session] = None,
region: Optional[str] = None,
) -> Optional["CompilationJob"]:
"""
Create a CompilationJob resource
Parameters:
compilation_job_name: A name for the model compilation job. The name must be unique within the Amazon Web Services Region and within your Amazon Web Services account.
role_arn: The Amazon Resource Name (ARN) of an IAM role that enables Amazon SageMaker to perform tasks on your behalf. During model compilation, Amazon SageMaker needs your permission to: Read input data from an S3 bucket Write model artifacts to an S3 bucket Write logs to Amazon CloudWatch Logs Publish metrics to Amazon CloudWatch You grant permissions for all of these tasks to an IAM role. To pass this role to Amazon SageMaker, the caller of this API must have the iam:PassRole permission. For more information, see Amazon SageMaker Roles.
output_config: Provides information about the output location for the compiled model and the target device the model runs on.
stopping_condition: Specifies a limit to how long a model compilation job can run. When the job reaches the time limit, Amazon SageMaker ends the compilation job. Use this API to cap model training costs.
model_package_version_arn: The Amazon Resource Name (ARN) of a versioned model package. Provide either a ModelPackageVersionArn or an InputConfig object in the request syntax. The presence of both objects in the CreateCompilationJob request will return an exception.
input_config: Provides information about the location of input model artifacts, the name and shape of the expected data inputs, and the framework in which the model was trained.
vpc_config: A VpcConfig object that specifies the VPC that you want your compilation job to connect to. Control access to your models by configuring the VPC. For more information, see Protect Compilation Jobs by Using an Amazon Virtual Private Cloud.
tags: An array of key-value pairs. You can use tags to categorize your Amazon Web Services resources in different ways, for example, by purpose, owner, or environment. For more information, see Tagging Amazon Web Services Resources.
session: Boto3 session.
region: Region name.
Returns:
The CompilationJob resource.
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceInUse: Resource being accessed is in use.
ResourceLimitExceeded: You have exceeded an SageMaker resource limit. For example, you might have too many training jobs created.
ConfigSchemaValidationError: Raised when a configuration file does not adhere to the schema
LocalConfigNotFoundError: Raised when a configuration file is not found in local file system
S3ConfigNotFoundError: Raised when a configuration file is not found in S3
"""
logger.info("Creating compilation_job resource.")
client =Base.get_sagemaker_client(session=session, region_name=region, service_name='sagemaker')
operation_input_args = {
'CompilationJobName': compilation_job_name,
'RoleArn': role_arn,
'ModelPackageVersionArn': model_package_version_arn,
'InputConfig': input_config,
'OutputConfig': output_config,
'VpcConfig': vpc_config,
'StoppingCondition': stopping_condition,
'Tags': tags,
}
operation_input_args = Base.populate_chained_attributes(resource_name='CompilationJob', operation_input_args=operation_input_args)
logger.debug(f"Input request: {operation_input_args}")
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
# create the resource
response = client.create_compilation_job(**operation_input_args)
logger.debug(f"Response: {response}")
return cls.get(compilation_job_name=compilation_job_name, session=session, region=region)
'''
assert (
self.resource_generator.generate_create_method(
"CompilationJob", needs_defaults_decorator=False
)
== expected_output
)
def test_generate_import_method(self):
expected_output = '''
@classmethod
@Base.add_validate_call
def load(
cls,
hub_content_name: str,
hub_content_type: str,
document_schema_version: str,
hub_name: str,
hub_content_document: str,
hub_content_version: Optional[str] = Unassigned(),
hub_content_display_name: Optional[str] = Unassigned(),
hub_content_description: Optional[str] = Unassigned(),
hub_content_markdown: Optional[str] = Unassigned(),
hub_content_search_keywords: Optional[List[str]] = Unassigned(),
tags: Optional[List[Tag]] = Unassigned(),
session: Optional[Session] = None,
region: Optional[str] = None,
) -> Optional["HubContent"]:
"""
Import a HubContent resource
Parameters:
hub_content_name: The name of the hub content to import.
hub_content_type: The type of hub content to import.
document_schema_version: The version of the hub content schema to import.
hub_name: The name of the hub to import content into.
hub_content_document: The hub content document that describes information about the hub content such as type, associated containers, scripts, and more.
hub_content_version: The version of the hub content to import.
hub_content_display_name: The display name of the hub content to import.
hub_content_description: A description of the hub content to import.
hub_content_markdown: A string that provides a description of the hub content. This string can include links, tables, and standard markdown formating.
hub_content_search_keywords: The searchable keywords of the hub content.
tags: Any tags associated with the hub content.
session: Boto3 session.
region: Region name.
Returns:
The HubContent resource.
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceInUse: Resource being accessed is in use.
ResourceLimitExceeded: You have exceeded an SageMaker resource limit. For example, you might have too many training jobs created.
ResourceNotFound: Resource being access is not found.
"""
logger.info(f"Importing hub_content resource.")
client = SageMakerClient(session=session, region_name=region, service_name='sagemaker').client
operation_input_args = {
'HubContentName': hub_content_name,
'HubContentVersion': hub_content_version,
'HubContentType': hub_content_type,
'DocumentSchemaVersion': document_schema_version,
'HubName': hub_name,
'HubContentDisplayName': hub_content_display_name,
'HubContentDescription': hub_content_description,
'HubContentMarkdown': hub_content_markdown,
'HubContentDocument': hub_content_document,
'HubContentSearchKeywords': hub_content_search_keywords,
'Tags': tags,
}
logger.debug(f"Input request: {operation_input_args}")
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
# import the resource
response = client.import_hub_content(**operation_input_args)
logger.debug(f"Response: {response}")
return cls.get(hub_name=hub_name, hub_content_type=hub_content_type, hub_content_name=hub_content_name, session=session, region=region)
'''
assert self.resource_generator.generate_import_method("HubContent") == expected_output
def test_generate_update_method_with_decorator(self):
expected_output = '''
@populate_inputs_decorator
@Base.add_validate_call
def update(
self,
retain_all_variant_properties: Optional[bool] = Unassigned(),
exclude_retained_variant_properties: Optional[List[VariantProperty]] = Unassigned(),
deployment_config: Optional[DeploymentConfig] = Unassigned(),
retain_deployment_config: Optional[bool] = Unassigned(),
) -> Optional["Endpoint"]:
"""
Update a Endpoint resource
Parameters:
retain_all_variant_properties: When updating endpoint resources, enables or disables the retention of variant properties, such as the instance count or the variant weight. To retain the variant properties of an endpoint when updating it, set RetainAllVariantProperties to true. To use the variant properties specified in a new EndpointConfig call when updating an endpoint, set RetainAllVariantProperties to false. The default is false.
exclude_retained_variant_properties: When you are updating endpoint resources with RetainAllVariantProperties, whose value is set to true, ExcludeRetainedVariantProperties specifies the list of type VariantProperty to override with the values provided by EndpointConfig. If you don't specify a value for ExcludeRetainedVariantProperties, no variant properties are overridden.
deployment_config: The deployment configuration for an endpoint, which contains the desired deployment strategy and rollback configurations.
retain_deployment_config: Specifies whether to reuse the last deployment configuration. The default value is false (the configuration is not reused).
Returns:
The Endpoint resource.
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceLimitExceeded: You have exceeded an SageMaker resource limit. For example, you might have too many training jobs created.
"""
logger.info("Updating endpoint resource.")
client = Base.get_sagemaker_client()
operation_input_args = {
'EndpointName': self.endpoint_name,
'EndpointConfigName': self.endpoint_config_name,
'RetainAllVariantProperties': retain_all_variant_properties,
'ExcludeRetainedVariantProperties': exclude_retained_variant_properties,
'DeploymentConfig': deployment_config,
'RetainDeploymentConfig': retain_deployment_config,
}
logger.debug(f"Input request: {operation_input_args}")
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
# create the resource
response = client.update_endpoint(**operation_input_args)
logger.debug(f"Response: {response}")
self.refresh()
return self
'''
class_attributes = self.resource_generator._get_class_attributes("Endpoint", ["get"])
resource_attributes = list(class_attributes[0].keys())
assert (
self.resource_generator.generate_update_method(
"Endpoint", resource_attributes=resource_attributes, needs_defaults_decorator=True
)
== expected_output
)
def test_generate_update_method(self):
expected_output = '''
@Base.add_validate_call
def update(
self,
retain_all_variant_properties: Optional[bool] = Unassigned(),
exclude_retained_variant_properties: Optional[List[VariantProperty]] = Unassigned(),
deployment_config: Optional[DeploymentConfig] = Unassigned(),
retain_deployment_config: Optional[bool] = Unassigned(),
) -> Optional["Endpoint"]:
"""
Update a Endpoint resource
Parameters:
retain_all_variant_properties: When updating endpoint resources, enables or disables the retention of variant properties, such as the instance count or the variant weight. To retain the variant properties of an endpoint when updating it, set RetainAllVariantProperties to true. To use the variant properties specified in a new EndpointConfig call when updating an endpoint, set RetainAllVariantProperties to false. The default is false.
exclude_retained_variant_properties: When you are updating endpoint resources with RetainAllVariantProperties, whose value is set to true, ExcludeRetainedVariantProperties specifies the list of type VariantProperty to override with the values provided by EndpointConfig. If you don't specify a value for ExcludeRetainedVariantProperties, no variant properties are overridden.
deployment_config: The deployment configuration for an endpoint, which contains the desired deployment strategy and rollback configurations.
retain_deployment_config: Specifies whether to reuse the last deployment configuration. The default value is false (the configuration is not reused).
Returns:
The Endpoint resource.
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceLimitExceeded: You have exceeded an SageMaker resource limit. For example, you might have too many training jobs created.
"""
logger.info("Updating endpoint resource.")
client = Base.get_sagemaker_client()
operation_input_args = {
'EndpointName': self.endpoint_name,
'EndpointConfigName': self.endpoint_config_name,
'RetainAllVariantProperties': retain_all_variant_properties,
'ExcludeRetainedVariantProperties': exclude_retained_variant_properties,
'DeploymentConfig': deployment_config,
'RetainDeploymentConfig': retain_deployment_config,
}
logger.debug(f"Input request: {operation_input_args}")
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
# create the resource
response = client.update_endpoint(**operation_input_args)
logger.debug(f"Response: {response}")
self.refresh()
return self
'''
class_attributes = self.resource_generator._get_class_attributes("Endpoint", ["get"])
resource_attributes = list(class_attributes[0].keys())
assert (
self.resource_generator.generate_update_method(
"Endpoint", resource_attributes=resource_attributes, needs_defaults_decorator=False
)
== expected_output
)
def test_generate_get_method(self):
expected_output = '''
@classmethod
@Base.add_validate_call
def get(
cls,
domain_id: str,
app_type: str,
app_name: str,
user_profile_name: Optional[str] = Unassigned(),
space_name: Optional[str] = Unassigned(),
session: Optional[Session] = None,
region: Optional[str] = None,
) -> Optional["App"]:
"""
Get a App resource
Parameters:
domain_id: The domain ID.
app_type: The type of app.
app_name: The name of the app.
user_profile_name: The user profile name. If this value is not set, then SpaceName must be set.
space_name: The name of the space.
session: Boto3 session.
region: Region name.
Returns:
The App resource.
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceNotFound: Resource being access is not found.
"""
operation_input_args = {
'DomainId': domain_id,
'UserProfileName': user_profile_name,
'SpaceName': space_name,
'AppType': app_type,
'AppName': app_name,
}
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
client = Base.get_sagemaker_client(session=session, region_name=region, service_name='sagemaker')
response = client.describe_app(**operation_input_args)
logger.debug(response)
# deserialize the response
transformed_response = transform(response, 'DescribeAppResponse')
app = cls(**transformed_response)
return app
'''
assert self.resource_generator.generate_get_method("App") == expected_output
def test_generate_refresh_method(self):
expected_output = '''
@Base.add_validate_call
def refresh(
self,
) -> Optional["App"]:
"""
Refresh a App resource
Returns:
The App resource.
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceNotFound: Resource being access is not found.
"""
operation_input_args = {
'DomainId': self.domain_id,
'UserProfileName': self.user_profile_name,
'SpaceName': self.space_name,
'AppType': self.app_type,
'AppName': self.app_name,
}
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
client = Base.get_sagemaker_client()
response = client.describe_app(**operation_input_args)
# deserialize response and update self
transform(response, 'DescribeAppResponse', self)
return self
'''
assert (
self.resource_generator.generate_refresh_method(
"App",
resource_attributes=[
"app_name",
"domain_id",
"user_profile_name",
"space_name",
"app_type",
"app_name",
],
)
== expected_output
)
def test_generate_delete_method(self):
expected_output = '''
@Base.add_validate_call
def delete(
self,
) -> None:
"""
Delete a CompilationJob resource
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceNotFound: Resource being access is not found.
"""
client = Base.get_sagemaker_client()
operation_input_args = {
'CompilationJobName': self.compilation_job_name,
}
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
client.delete_compilation_job(**operation_input_args)
logger.info(f"Deleting {self.__class__.__name__} - {self.get_name()}")
'''
assert (
self.resource_generator.generate_delete_method(
"CompilationJob", resource_attributes=["compilation_job_name"]
)
== expected_output
)
# create a unit test for generate_stop_method
def test_generate_stop_method(self):
expected_output = '''
@Base.add_validate_call
def stop(self) -> None:
"""
Stop a CompilationJob resource
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
ResourceNotFound: Resource being access is not found.
"""
client = SageMakerClient().client
operation_input_args = {
'CompilationJobName': self.compilation_job_name,
}
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
client.stop_compilation_job(**operation_input_args)
logger.info(f"Stopping {self.__class__.__name__} - {self.get_name()}")
'''
assert self.resource_generator.generate_stop_method("CompilationJob") == expected_output
def test_generate_wait_method(self):
expected_output = '''
@Base.add_validate_call
def wait(
self,
poll: int = 5,
timeout: Optional[int] = None
) -> None:
"""
Wait for a TrainingJob resource.
Parameters:
poll: The number of seconds to wait between each poll.
timeout: The maximum number of seconds to wait before timing out.
Raises:
TimeoutExceededError: If the resource does not reach a terminal state before the timeout.
FailedStatusError: If the resource reaches a failed state.
WaiterError: Raised when an error occurs while waiting.
"""
terminal_states = ['Completed', 'Failed', 'Stopped']
start_time = time.time()
progress = Progress(SpinnerColumn("bouncingBar"),
TextColumn("{task.description}"),
TimeElapsedColumn(),
)
progress.add_task("Waiting for TrainingJob...")
status = Status("Current status:")
with Live(Panel(Group(progress, status), title="Wait Log Panel", border_style=Style(color=Color.BLUE.value))):
while True:
self.refresh()
current_status = self.training_job_status
status.update(f"Current status: [bold]{current_status}")
if current_status in terminal_states:
logger.info(f"Final Resource Status: [bold]{current_status}")
if "failed" in current_status.lower():
raise FailedStatusError(resource_type="TrainingJob", status=current_status, reason=self.failure_reason)
return
if timeout is not None and time.time() - start_time >= timeout:
raise TimeoutExceededError(resouce_type="TrainingJob", status=current_status)
time.sleep(poll)
'''
assert self.resource_generator.generate_wait_method("TrainingJob") == expected_output
def test_generate_wait_for_status_method(self):
expected_output = '''
@Base.add_validate_call
def wait_for_status(
self,
target_status: Literal['InService', 'Creating', 'Updating', 'Failed', 'Deleting'],
poll: int = 5,
timeout: Optional[int] = None
) -> None:
"""
Wait for a InferenceComponent resource to reach certain status.
Parameters:
target_status: The status to wait for.
poll: The number of seconds to wait between each poll.
timeout: The maximum number of seconds to wait before timing out.
Raises:
TimeoutExceededError: If the resource does not reach a terminal state before the timeout.
FailedStatusError: If the resource reaches a failed state.
WaiterError: Raised when an error occurs while waiting.
"""
start_time = time.time()
progress = Progress(SpinnerColumn("bouncingBar"),
TextColumn("{task.description}"),
TimeElapsedColumn(),
)
progress.add_task(f"Waiting for InferenceComponent to reach [bold]{target_status} status...")
status = Status("Current status:")
with Live(Panel(Group(progress, status), title="Wait Log Panel", border_style=Style(color=Color.BLUE.value))):
while True:
self.refresh()
current_status = self.inference_component_status
status.update(f"Current status: [bold]{current_status}")
if target_status == current_status:
logger.info(f"Final Resource Status: [bold]{current_status}")
return
if "failed" in current_status.lower():
raise FailedStatusError(resource_type="InferenceComponent", status=current_status, reason=self.failure_reason)
if timeout is not None and time.time() - start_time >= timeout:
raise TimeoutExceededError(resouce_type="InferenceComponent", status=current_status)
time.sleep(poll)
'''
assert (
self.resource_generator.generate_wait_for_status_method("InferenceComponent")
== expected_output
)
def test_generate_wait_for_status_method_without_failed_state(self):
expected_output = '''
@Base.add_validate_call
def wait_for_status(
self,
target_status: Literal['Creating', 'Created', 'Updating', 'Running', 'Starting', 'Stopping', 'Completed', 'Cancelled'],
poll: int = 5,
timeout: Optional[int] = None
) -> None:
"""
Wait for a InferenceExperiment resource to reach certain status.
Parameters:
target_status: The status to wait for.
poll: The number of seconds to wait between each poll.
timeout: The maximum number of seconds to wait before timing out.
Raises:
TimeoutExceededError: If the resource does not reach a terminal state before the timeout.
FailedStatusError: If the resource reaches a failed state.
WaiterError: Raised when an error occurs while waiting.
"""
start_time = time.time()
progress = Progress(SpinnerColumn("bouncingBar"),
TextColumn("{task.description}"),
TimeElapsedColumn(),
)
progress.add_task(f"Waiting for InferenceExperiment to reach [bold]{target_status} status...")
status = Status("Current status:")
with Live(Panel(Group(progress, status), title="Wait Log Panel", border_style=Style(color=Color.BLUE.value))):
while True:
self.refresh()
current_status = self.status
status.update(f"Current status: [bold]{current_status}")
if target_status == current_status:
logger.info(f"Final Resource Status: [bold]{current_status}")
return
if timeout is not None and time.time() - start_time >= timeout:
raise TimeoutExceededError(resouce_type="InferenceExperiment", status=current_status)
time.sleep(poll)
'''
assert (
self.resource_generator.generate_wait_for_status_method("InferenceExperiment")
== expected_output
)
def test_generate_invoke_method(self):
expected_output = '''
@Base.add_validate_call
def invoke_with_response_stream(
self,
body: Any,
content_type: Optional[str] = Unassigned(),
accept: Optional[str] = Unassigned(),
custom_attributes: Optional[str] = Unassigned(),
target_variant: Optional[str] = Unassigned(),
target_container_hostname: Optional[str] = Unassigned(),
inference_id: Optional[str] = Unassigned(),
inference_component_name: Optional[str] = Unassigned(),
session: Optional[Session] = None,
region: Optional[str] = None,
) -> Optional[InvokeEndpointWithResponseStreamOutput]:
"""
Invokes a model at the specified endpoint to return the inference response as a stream.
Parameters:
body: Provides input data, in the format specified in the ContentType request header. Amazon SageMaker passes all of the data in the body to the model. For information about the format of the request body, see Common Data Formats-Inference.
content_type: The MIME type of the input data in the request body.
accept: The desired MIME type of the inference response from the model container.
custom_attributes: Provides additional information about a request for an inference submitted to a model hosted at an Amazon SageMaker endpoint. The information is an opaque value that is forwarded verbatim. You could use this value, for example, to provide an ID that you can use to track a request or to provide other metadata that a service endpoint was programmed to process. The value must consist of no more than 1024 visible US-ASCII characters as specified in Section 3.3.6. Field Value Components of the Hypertext Transfer Protocol (HTTP/1.1). The code in your model is responsible for setting or updating any custom attributes in the response. If your code does not set this value in the response, an empty value is returned. For example, if a custom attribute represents the trace ID, your model can prepend the custom attribute with Trace ID: in your post-processing function. This feature is currently supported in the Amazon Web Services SDKs but not in the Amazon SageMaker Python SDK.
target_variant: Specify the production variant to send the inference request to when invoking an endpoint that is running two or more variants. Note that this parameter overrides the default behavior for the endpoint, which is to distribute the invocation traffic based on the variant weights. For information about how to use variant targeting to perform a/b testing, see Test models in production
target_container_hostname: If the endpoint hosts multiple containers and is configured to use direct invocation, this parameter specifies the host name of the container to invoke.
inference_id: An identifier that you assign to your request.
inference_component_name: If the endpoint hosts one or more inference components, this parameter specifies the name of inference component to invoke for a streaming response.
session: Boto3 session.
region: Region name.
Returns:
InvokeEndpointWithResponseStreamOutput
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
InternalFailure: An internal failure occurred. Try your request again. If the problem persists, contact Amazon Web Services customer support.
InternalStreamFailure: The stream processing failed because of an unknown error, exception or failure. Try your request again.
ModelError: Model (owned by the customer in the container) returned 4xx or 5xx error code.
ModelStreamError: An error occurred while streaming the response body. This error can have the following error codes: ModelInvocationTimeExceeded The model failed to finish sending the response within the timeout period allowed by Amazon SageMaker. StreamBroken The Transmission Control Protocol (TCP) connection between the client and the model was reset or closed.
ServiceUnavailable: The service is currently unavailable.
ValidationError: There was an error validating your request.
"""
operation_input_args = {
'EndpointName': self.endpoint_name,
'Body': body,
'ContentType': content_type,
'Accept': accept,
'CustomAttributes': custom_attributes,
'TargetVariant': target_variant,
'TargetContainerHostname': target_container_hostname,
'InferenceId': inference_id,
'InferenceComponentName': inference_component_name,
}
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
client = Base.get_sagemaker_client(session=session, region_name=region, service_name='sagemaker-runtime')
logger.debug(f"Calling invoke_endpoint_with_response_stream API")
response = client.invoke_endpoint_with_response_stream(**operation_input_args)
logger.debug(f"Response: {response}")
transformed_response = transform(response, 'InvokeEndpointWithResponseStreamOutput')
return InvokeEndpointWithResponseStreamOutput(**transformed_response)
'''
method = Method(
**{
"operation_name": "InvokeEndpointWithResponseStream",
"resource_name": "Endpoint",
"method_name": "invoke_with_response_stream",
"return_type": "InvokeEndpointWithResponseStreamOutput",
"method_type": "object",
"service_name": "sagemaker-runtime",
}
)
method.get_docstring_title(
self.resource_generator.operations["InvokeEndpointWithResponseStream"]
)
assert self.resource_generator.generate_method(method, ["endpoint_name"]) == expected_output
def test_generate_invoke_async_method(self):
expected_output = '''
@Base.add_validate_call
def invoke_async(
self,
input_location: str,
content_type: Optional[str] = Unassigned(),
accept: Optional[str] = Unassigned(),
custom_attributes: Optional[str] = Unassigned(),
inference_id: Optional[str] = Unassigned(),
request_ttl_seconds: Optional[int] = Unassigned(),
invocation_timeout_seconds: Optional[int] = Unassigned(),
session: Optional[Session] = None,
region: Optional[str] = None,
) -> Optional[InvokeEndpointAsyncOutput]:
"""
After you deploy a model into production using Amazon SageMaker hosting services, your client applications use this API to get inferences from the model hosted at the specified endpoint in an asynchronous manner.
Parameters:
input_location: The Amazon S3 URI where the inference request payload is stored.
content_type: The MIME type of the input data in the request body.
accept: The desired MIME type of the inference response from the model container.
custom_attributes: Provides additional information about a request for an inference submitted to a model hosted at an Amazon SageMaker endpoint. The information is an opaque value that is forwarded verbatim. You could use this value, for example, to provide an ID that you can use to track a request or to provide other metadata that a service endpoint was programmed to process. The value must consist of no more than 1024 visible US-ASCII characters as specified in Section 3.3.6. Field Value Components of the Hypertext Transfer Protocol (HTTP/1.1). The code in your model is responsible for setting or updating any custom attributes in the response. If your code does not set this value in the response, an empty value is returned. For example, if a custom attribute represents the trace ID, your model can prepend the custom attribute with Trace ID: in your post-processing function. This feature is currently supported in the Amazon Web Services SDKs but not in the Amazon SageMaker Python SDK.
inference_id: The identifier for the inference request. Amazon SageMaker will generate an identifier for you if none is specified.
request_ttl_seconds: Maximum age in seconds a request can be in the queue before it is marked as expired. The default is 6 hours, or 21,600 seconds.
invocation_timeout_seconds: Maximum amount of time in seconds a request can be processed before it is marked as expired. The default is 15 minutes, or 900 seconds.
session: Boto3 session.
region: Region name.
Returns:
InvokeEndpointAsyncOutput
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
InternalFailure: An internal failure occurred. Try your request again. If the problem persists, contact Amazon Web Services customer support.
ServiceUnavailable: The service is currently unavailable.
ValidationError: There was an error validating your request.
"""
operation_input_args = {
'EndpointName': self.endpoint_name,
'ContentType': content_type,
'Accept': accept,
'CustomAttributes': custom_attributes,
'InferenceId': inference_id,
'InputLocation': input_location,
'RequestTTLSeconds': request_ttl_seconds,
'InvocationTimeoutSeconds': invocation_timeout_seconds,
}
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
client = Base.get_sagemaker_client(session=session, region_name=region, service_name='sagemaker-runtime')
logger.debug(f"Calling invoke_endpoint_async API")
response = client.invoke_endpoint_async(**operation_input_args)
logger.debug(f"Response: {response}")
transformed_response = transform(response, 'InvokeEndpointAsyncOutput')
return InvokeEndpointAsyncOutput(**transformed_response)
'''
method = Method(
**{
"operation_name": "InvokeEndpointAsync",
"resource_name": "Endpoint",
"method_name": "invoke_async",
"return_type": "InvokeEndpointAsyncOutput",
"method_type": "object",
"service_name": "sagemaker-runtime",
}
)
method.get_docstring_title(self.resource_generator.operations["InvokeEndpointAsync"])
assert self.resource_generator.generate_method(method, ["endpoint_name"]) == expected_output
def test_generate_invoke_with_response_stream_method(self):
expected_output = '''
@Base.add_validate_call
def invoke_with_response_stream(
self,
body: Any,
content_type: Optional[str] = Unassigned(),
accept: Optional[str] = Unassigned(),
custom_attributes: Optional[str] = Unassigned(),
target_variant: Optional[str] = Unassigned(),
target_container_hostname: Optional[str] = Unassigned(),
inference_id: Optional[str] = Unassigned(),
inference_component_name: Optional[str] = Unassigned(),
session: Optional[Session] = None,
region: Optional[str] = None,
) -> Optional[object]:
"""
Invokes a model at the specified endpoint to return the inference response as a stream.
Parameters:
body: Provides input data, in the format specified in the ContentType request header. Amazon SageMaker passes all of the data in the body to the model. For information about the format of the request body, see Common Data Formats-Inference.
content_type: The MIME type of the input data in the request body.
accept: The desired MIME type of the inference response from the model container.
custom_attributes: Provides additional information about a request for an inference submitted to a model hosted at an Amazon SageMaker endpoint. The information is an opaque value that is forwarded verbatim. You could use this value, for example, to provide an ID that you can use to track a request or to provide other metadata that a service endpoint was programmed to process. The value must consist of no more than 1024 visible US-ASCII characters as specified in Section 3.3.6. Field Value Components of the Hypertext Transfer Protocol (HTTP/1.1). The code in your model is responsible for setting or updating any custom attributes in the response. If your code does not set this value in the response, an empty value is returned. For example, if a custom attribute represents the trace ID, your model can prepend the custom attribute with Trace ID: in your post-processing function. This feature is currently supported in the Amazon Web Services SDKs but not in the Amazon SageMaker Python SDK.
target_variant: Specify the production variant to send the inference request to when invoking an endpoint that is running two or more variants. Note that this parameter overrides the default behavior for the endpoint, which is to distribute the invocation traffic based on the variant weights. For information about how to use variant targeting to perform a/b testing, see Test models in production
target_container_hostname: If the endpoint hosts multiple containers and is configured to use direct invocation, this parameter specifies the host name of the container to invoke.
inference_id: An identifier that you assign to your request.
inference_component_name: If the endpoint hosts one or more inference components, this parameter specifies the name of inference component to invoke for a streaming response.
session: Boto3 session.
region: Region name.
Returns:
object
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
InternalFailure: An internal failure occurred. Try your request again. If the problem persists, contact Amazon Web Services customer support.
InternalStreamFailure: The stream processing failed because of an unknown error, exception or failure. Try your request again.
ModelError: Model (owned by the customer in the container) returned 4xx or 5xx error code.
ModelStreamError: An error occurred while streaming the response body. This error can have the following error codes: ModelInvocationTimeExceeded The model failed to finish sending the response within the timeout period allowed by Amazon SageMaker. StreamBroken The Transmission Control Protocol (TCP) connection between the client and the model was reset or closed.
ServiceUnavailable: The service is currently unavailable.
ValidationError: There was an error validating your request.
"""
operation_input_args = {
'EndpointName': self.endpoint_name,
'Body': body,
'ContentType': content_type,
'Accept': accept,
'CustomAttributes': custom_attributes,
'TargetVariant': target_variant,
'TargetContainerHostname': target_container_hostname,
'InferenceId': inference_id,
'InferenceComponentName': inference_component_name,
}
# serialize the input request
operation_input_args = serialize(operation_input_args)
logger.debug(f"Serialized input request: {operation_input_args}")
client = Base.get_sagemaker_client(session=session, region_name=region, service_name='sagemaker-runtime')
logger.debug(f"Calling invoke_endpoint_with_response_stream API")
response = client.invoke_endpoint_with_response_stream(**operation_input_args)
logger.debug(f"Response: {response}")
return response
'''
method = Method(
**{
"operation_name": "InvokeEndpointWithResponseStream",
"resource_name": "Endpoint",
"method_name": "invoke_with_response_stream",
"return_type": "object",
"method_type": "object",
"service_name": "sagemaker-runtime",
}
)
method.get_docstring_title(
self.resource_generator.operations["InvokeEndpointWithResponseStream"]
)
assert self.resource_generator.generate_method(method, ["endpoint_name"]) == expected_output
def test_get_all_method(self):
expected_output = '''
@classmethod
@Base.add_validate_call
def get_all(
cls,
sort_order: Optional[str] = Unassigned(),
sort_by: Optional[str] = Unassigned(),
domain_id_equals: Optional[str] = Unassigned(),
user_profile_name_equals: Optional[str] = Unassigned(),
space_name_equals: Optional[str] = Unassigned(),
session: Optional[Session] = None,
region: Optional[str] = None,
) -> ResourceIterator["App"]:
"""
Get all App resources
Parameters:
next_token: If the previous response was truncated, you will receive this token. Use it in your next request to receive the next set of results.
max_results: This parameter defines the maximum number of results that can be return in a single response. The MaxResults parameter is an upper bound, not a target. If there are more results available than the value specified, a NextToken is provided in the response. The NextToken indicates that the user should get the next set of results by providing this token as a part of a subsequent call. The default value for MaxResults is 10.
sort_order: The sort order for the results. The default is Ascending.
sort_by: The parameter by which to sort the results. The default is CreationTime.
domain_id_equals: A parameter to search for the domain ID.
user_profile_name_equals: A parameter to search by user profile name. If SpaceNameEquals is set, then this value cannot be set.
space_name_equals: A parameter to search by space name. If UserProfileNameEquals is set, then this value cannot be set.
session: Boto3 session.
region: Region name.
Returns:
Iterator for listed App resources.
Raises:
botocore.exceptions.ClientError: This exception is raised for AWS service related errors.
The error message and error code can be parsed from the exception as follows:
```
try:
# AWS service call here
except botocore.exceptions.ClientError as e:
error_message = e.response['Error']['Message']
error_code = e.response['Error']['Code']
```
"""
client = Base.get_sagemaker_client(session=session, region_name=region, service_name="sagemaker")
operation_input_args = {
'SortOrder': sort_order,
'SortBy': sort_by,
'DomainIdEquals': domain_id_equals,