-
Notifications
You must be signed in to change notification settings - Fork 0
/
pca-main.template
1387 lines (1267 loc) · 50.8 KB
/
pca-main.template
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
AWSTemplateFormatVersion: "2010-09-09"
Description: Amazon Transcribe Post Call Analytics - PCA (v0.7.11) (uksb-1sn29lk73, SO9071)
Parameters:
AdminUsername:
Type: String
Default: "admin"
Description: (Required) Username for admin user
AdminEmail:
Type: String
Description: >-
(Required) Email address for the admin user. Will be used for logging in and for setting the admin password.
This email will receive the temporary password for the admin user.
AllowedPattern: ".+\\@.+\\..+"
ConstraintDescription: Must be valid email address eg. [email protected]
AllowedSignUpEmailDomain:
Type: String
Default: ""
Description: >-
Email address domain (example.com) or comma separated list of email domains (example1.com,
example2.com) allowed to signin and signup using the web UI. To allow signup from any domain,
enter *.
If left empty, signup via the web UI is disabled and users will have to be created
using
Cognito.
AllowedPattern: '^(\*||([\w-]+\.)+[\w-]{2,6}(, *([\w-]+\.)+[\w-]{2,6})*)$'
BulkUploadBucketName:
Type: String
Default: ""
Description: >-
(Optional) Existing bucket where files can be dropped, and a secondary Step Function can be
manually enabled to drip feed them into the system.
Leave blank to automatically create new bucket.
BulkUploadMaxDripRate:
Type: String
Default: "25"
Description: Maximum number of files that the bulk uploader will move to the PCA source bucket in one pass
BulkUploadMaxTranscribeJobs:
Type: String
Default: "50"
Description: Number of concurrent Transcribe jobs (executing or queuing) where bulk upload will pause
ComprehendLanguages:
Type: String
Default: de | en | es | it | pt | fr | ja | ko | hi | ar | zh | zh-TW
Description: Languages supported by Comprehend's standard calls, separated by " | "
ContentRedactionLanguages:
Type: String
Default: en-US
Description: Languages supported by Transcribe's Content Redaction feature, separated by " | "
ConversationLocation:
Type: String
AllowedPattern: "[+-_\/a-zA-Z0-9]*"
Default: America/New_York
Description: Name of the timezone location for the call source - this is the TZ database name from https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
EntityRecognizerEndpoint:
Type: String
Default: undefined
Description: Name of the custom entity recognizer for Amazon Comprehend (not including language suffix, e.g. -en). If one cannot be found then simple entity string matching is attempted instead
EntityStringMap:
Type: String
Default: sample-entities.csv
Description: Basename of a CSV file containing item/Entity maps for when we don't have data for Comprehend Custom Entities (not including language suffix, e.g. -en)
EntityThreshold:
Type: String
Default: "0.6"
Description: Confidence threshold where we accept the custom entity detection result
EntityTypes:
Type: String
Default: PERSON | LOCATION | ORGANIZATION | COMMERCIAL_ITEM | EVENT | DATE | QUANTITY | TITLE
Description: Entity types supported by Comprehend's standard entity detection, separated by " | "
InputBucketAudioPlayback:
Type: String
Default: playbackAudio
Description: Folder that holds the audio files to playback in the browser.
InputBucketFailedTranscriptions:
Type: String
Default: failedAudio
Description: Folder that holds the audio files that for some reason failed transcription
InputBucketName:
Type: String
Default: ""
Description: >-
(Optional) Existing bucket holding all audio files for the system.
Leave blank to automatically create new bucket with intelligent tiering storage and automated retention policy.
InputBucketRawAudio:
Type: String
Default: originalAudio
Description: Prefix/Folder that holds the audio files to be ingested into the system
InputBucketOrigTranscripts:
Type: String
Default: originalTranscripts
Description: >
Folder that holds Transcripts from other applications (e.g. Live Call Analytics) that are to be
processed as if PCA had processed that audio
MaxSpeakers:
Type: String
Default: "2"
Description: Maximum number of speakers that are expected on a call
MinSentimentNegative:
Type: String
Default: "2.0"
Description: Minimum sentiment level required to declare a phrase as having negative sentiment, in the range 0.0-5.0
MinSentimentPositive:
Type: String
Default: "2.0"
Description: Minimum sentiment level required to declare a phrase as having positive sentiment, in the range 0.0-5.0
OutputBucketName:
Type: String
Default: ""
Description: >-
(Optional) Existing bucket where Transcribe output files are delivered.
Leave blank to automatically create new bucket with intelligent tiering storage and automated retention policy.
OutputBucketTranscribeResults:
Type: String
Default: transcribeResults
Description: Folder within the output S3 bucket where Transcribe results are written
OutputBucketParsedResults:
Type: String
Default: parsedFiles
Description: Folder within the output S3 bucket where parsed results are written
SpeakerNames:
Type: String
Default: Customer | Agent
AllowedValues:
- Customer | Agent
- Agent | Customer
Description: Speaker label assignment order
SpeakerSeparationType:
Type: String
Default: channel
AllowedValues:
- speaker
- channel
Description: Separation mode diarization - typically speaker for mono files, channel for stereo files
StepFunctionName:
Type: String
AllowedPattern: "[-_a-zA-Z0-9]*"
Default: PostCallAnalyticsWorkflow
Description: Name of Step Functions workflow that orchestrates this process
BulkUploadStepFunctionName:
Type: String
AllowedPattern: "[-_a-zA-Z0-9]*"
Default: BulkUploadWorkflow
Description: Name of Step Functions workflow that orchestrates the bulk import process
SupportFilesBucketName:
Type: String
Default: ''
Description: >-
(Optional) Existing bucket that hold supporting files, such as the file-based
entity recognition mapping files. Leave blank to automatically create new bucket.
TranscribeLanguages:
Type: String
Default: en-US
Description: Language to be used for Transcription - multiple entries separated by " | " will trigger Language Detection
VocabFilterMode:
Type: String
Default: mask
AllowedValues:
- mask
- remove
Description: The mode to use for vocabulary filtering - must be one of mask or remove (tag is not supported)
VocabFilterName:
Type: String
Default: undefined
Description: Name of the vocabulary filter to use for Transcribe (not including language suffix, e.g. -en)
VocabularyName:
Type: String
Default: undefined
Description: Name of the custom vocabulary to use for Transcribe (omit the language suffix, e.g. -en-US)
CustomLangModelName:
Type: String
Default: undefined
Description: Name of the custom language model to use for Transcribe (omit the language suffix, e.g. -en-US)
TranscribeApiMode:
Type: String
Default: analytics
AllowedValues:
- standard
- analytics
Description: Set the default operational mode for Transcribe
TelephonyCTRType:
Type: String
Default: none
AllowedValues:
- none
- genesys
Description: Type of telephony system that will deliver Contact Trace Record files along with the audio recordings
TelephonyCTRFileSuffix:
Type: String
Default: "_metadata.json | _call_metadata.json"
Description: >
File name suffixes for the CTR file(s) associated with the chosen telephony type, separated by " | ".
For Genesys, this needs two entries: one for the conversation CTR file, and one for the call-specific file.
Other telephony systems may need fewer or additional entries, please consult the documentation.
CallRedactionTranscript:
Type: String
Default: true
AllowedValues:
- true
- false
Description: Enable or disable Transcribe's redaction feature
CallRedactionAudio:
Type: String
Default: true
AllowedValues:
- true
- false
Description: When transcript redaction is enabled in Call Analytics, only allow playback of the redacted audio
ffmpegDownloadUrl:
Type: String
Default: http://www.johnvansickle.com/ffmpeg/old-releases/ffmpeg-4.4-amd64-static.tar.xz
Description: URL for ffmpeg binary distribution tar file download - see https://www.johnvansickle.com/ffmpeg/
loadSampleAudioFiles:
Type: String
Default: false
AllowedValues:
- true
- false
Description: Set to true to automatically ingest sample audio files.
FilenameDatetimeRegex:
Type: String
Default: '(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})'
Description: >
Regular Expression (regex) used to parse call Date/Time from audio filenames.
Each datetime field (year, month, etc.) must be matched using a separate parenthesized group in the regex.
Example: the regex '(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})' parses
the filename: CallAudioFile-2021-12-01T07-55-51.wav into a value list: [2021, 12, 01, 07, 55, 51]
The next parameter, FilenameDatetimeFieldMap, maps the values to datetime field codes.
If the filename doesn't match the regex pattern, the current time is used as the call timestamp.
FilenameDatetimeFieldMap:
Type: String
Default: '%Y %m %d %H %M %S'
Description: >
Space separated ordered sequence of time field codes as used by Python's datetime.strptime() function.
Each field code refers to a corresponding value parsed by the regex parameter filenameTimestampRegex.
Example: the mapping '%Y %m %d %H %M %S' assembles the regex output values [2021, 12, 01, 07, 55, 51]
into the full datetime: '2021-12-01 07:55:51'.
If the field map doesn't match the value list parsed by the regex, then the current time is used as the call timestamp.
FilenameGUIDRegex:
Type: String
Default: '_GUID_(.*?)_'
Description: >
Regular Expression (regex) used to parse call GUID from audio filenames.
The GUID value must be matched using one or more parenthesized groups in the regex.
Example: the regex '_GUID_(.*?)_' parses
the filename: AutoRepairs1_CUST_12345_GUID_2a602c1a-4ca3-4d37-a933-444d575c0222_AGENT_BobS_DATETIME_07.55.51.067-09-16-2021.wav
to extract the GUID value '2a602c1a-4ca3-4d37-a933-444d575c0222'.
FilenameAgentRegex:
Type: String
Default: '_AGENT_(.*?)_'
Description: >
Regular Expression (regex) used to parse call AGENT from audio filenames.
The AGENT value must be matched using one or more parenthesized groups in the regex.
Example: the regex '_AGENT_(.*?)_' parses
the filename: AutoRepairs1_CUST_12345_GUID_2a602c1a-4ca3-4d37-a933-444d575c0222_AGENT_BobS_DATETIME_07.55.51.067-09-16-2021.wav
to extract the AGENT value 'BobS'.
FilenameCustRegex:
Type: String
Default: '_CUST_(.*?)_'
Description: >
Regular Expression (regex) used to parse Customer from audio filenames.
The customer id value must be matched using one or more parenthesized groups in the regex.
Example: the regex '_CUST_(.*?)_' parses
the filename: AutoRepairs1_CUST_12345_GUID_2a602c1a-4ca3-4d37-a933-444d575c0222_AGENT_BobS_DATETIME_07.55.51.067-09-16-2021.wav
to extract the Customer value '12345'.
EnableGui:
Type: String
Default: "true"
AllowedValues:
- "true"
- "false"
Description: Optionally disable the web GUI that comes with this solution, to deploy server components only.
EnableTranscriptKendraSearch:
Type: String
Default: 'No'
AllowedValues:
- 'No'
- 'Yes, create new Kendra Index (Developer Edition)'
- 'Yes, create new Kendra Index (Enterprise Edition)'
Description: Optionally make call transcripts searchable, using Amazon Kendra. If enabled, EnableGui (above) must also be set to true.
QueryCapacityUnits:
Type: Number
Default: 0
MinValue: 0
MaxValue: 100
Description: >
When Kendra Index (Enterprise Edition) is enabled, the amount of extra query capacity for an index
and GetQuerySuggestions capacity. A single extra capacity unit for an index provides 0.1 queries
per second or approximately 8,000 queries per day. You can add up to 100 extra capacity units.
StorageCapacityUnits:
Type: Number
Default: 0
MinValue: 0
MaxValue: 100
Description: >
When Kendra Index (Enterprise Edition) is enabled, the amount of extra storage capacity for an index.
A single capacity unit provides 30 GB of storage space or 100,000 documents, whichever is reached
first. You can add up to 100 extra capacity units.
QueryCapacityUnits:
Type: Number
Default: 0
MinValue: 0
MaxValue: 100
Description: >
When Kendra Index (Enterprise Edition) is enabled, the amount of extra query capacity for an index
and GetQuerySuggestions capacity. A single extra capacity unit for an index provides 0.1 queries
per second or approximately 8,000 queries per day. You can add up to 100 extra capacity units.
StorageCapacityUnits:
Type: Number
Default: 0
MinValue: 0
MaxValue: 100
Description: >
When Kendra Index (Enterprise Edition) is enabled, the amount of extra storage capacity for an index.
A single capacity unit provides 30 GB of storage space or 100,000 documents, whichever is reached
first. You can add up to 100 extra capacity units.
RetentionDays:
Type: Number
Default: 365
AllowedValues:
- 30
- 60
- 90
- 180
- 365
- 730
- 1460
Description: >
When using auto-provisioned S3 buckets, your audio files and associated call analysis data will be
automatically and permanently deleted after the specified number of retention days. The application
does not currently archive recordings or call data.
Environment:
Description: The type of environment to tag your infrastructure with. You can specify DEV (development), TEST (test), or PROD (production).
Type: String
AllowedValues:
- DEV
- TEST
- PROD
Default: PROD
DatabaseName:
Type: String
Default: 'pca'
Description: Glue catalog database name used to contain tables/views for SQL integration.
EnablePcaDashboards:
Type: String
Default: 'No'
AllowedValues:
- 'No'
- 'Yes'
Description: >
Optionally deploy advanced analytics pipeline and Amazon QuickSight dashboards.
IMPORTANT: Your Amazon QuickSight account MUST be enabled before deploying this stack. See http://www.amazon.com/pca-dashboards for additional
steps required in Amazon QuickSight to (1) enable S3 access to PCA OutputBucket and (2) share dashboard and analytics assets.
GenAIQuery:
Default: 'BEDROCK'
Type: String
AllowedValues:
- 'DISABLED'
- 'BEDROCK'
- 'ANTHROPIC'
Description: >
If enabled, gives the ability to query an individual call for information.
The BEDROCK option requires you to choose one of the supported model IDs from the provided list (GenAIQueryBedrockModelId).
You must also accept access to that model in the Amazon Bedrock > Model Access console.
The ANTHROPIC option is a third party service, and you must enter your Anthropic API key in the
Third Party LLM API Key section.
GenAIQueryBedrockModelId:
Type: String
Default: anthropic.claude-3-haiku-20240307-v1:0
AllowedValues:
- anthropic.claude-3-haiku-20240307-v1:0
- anthropic.claude-3-sonnet-20240229-v1:0
- amazon.titan-text-express-v1
- anthropic.claude-v1
- anthropic.claude-instant-v1
- anthropic.claude-v2
Description: (Optional) If 'GenAIQuery' is BEDROCK, which Bedrock model to use.
CallSummarization:
Default: 'BEDROCK'
Type: String
AllowedValues:
- 'DISABLED'
- 'BEDROCK+TCA'
- 'BEDROCK'
- 'TCA-ONLY'
- 'SAGEMAKER'
- 'ANTHROPIC'
- 'LAMBDA'
Description: >
Set to enable call summarization by a Large Language Model.
The BEDROCK+TCA will use Transcribe Call Analytics for summarization and Bedrock for other analytics, and is available only for English.
The BEDROCK option requires you to choose one of the supported model IDs from the provided list (SummarizationBedrockModelId).
You must also accept access to that model in the Amazon Bedrock > Model Access console.
The TCA-ONLY option will not use Bedrock, but will only use Transcribe Call Analytics summarization, and is available only for English.
The SAGEMAKER option uses a SageMaker endpoint with the pretrained bart-large-cnn-samsum model with a ml.m5.xlarge instance type.
The LAMBDA option requires you to provide a function ARN below.
The ANTHROPIC option is a third party service, and you must enter your Anthropic API key in the Third Party LLM API Key section.
SummarizationBedrockModelId:
Type: String
Default: anthropic.claude-3-haiku-20240307-v1:0
AllowedValues:
- anthropic.claude-3-haiku-20240307-v1:0
- anthropic.claude-3-sonnet-20240229-v1:0
- amazon.titan-text-express-v1
- anthropic.claude-v1
- anthropic.claude-instant-v1
- anthropic.claude-v2
Description: (Optional) If 'CallSummarization' is BEDROCK, which Bedrock model to use.
TestBedrockModelId:
Type: String
Default: true
AllowedValues:
- true
- false
Description: >
Set to false to disable checking if the Bedrock models are enabled.
SummarizationSageMakerInitialInstanceCount:
Type: Number
MinValue: 0
Default: 1
Description: >
(Optional) If 'CallSummarization' is SAGEMAKER, provide initial instance count. Set to '0' to enable Serverless Inference (for cold-start delay tolerant deployments only).
SummarizationLLMThirdPartyApiKey:
Type: String
Description: >
(Optional) If 'CallSummarization' or 'GenAIQuery' is ANTHROPIC, enter the provider API Key. ** Data will leave your AWS account **
Default: undefined
NoEcho: true
SummarizationLambdaFunctionArn:
Default: ''
Type: String
AllowedPattern: '^(|arn:aws:lambda:.*)$'
Description: >
(Optional) If 'CallSummarization' is LAMBDA, provide ARN for a Lambda function.
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: Admin User
Parameters:
- AdminUsername
- AdminEmail
- AllowedSignUpEmailDomain
- Label:
default: Sample Data
Parameters:
- loadSampleAudioFiles
- Label:
default: Enable Call Transcript Search
Parameters:
- EnableGui
- EnableTranscriptKendraSearch
- Label:
default: Call Summarization
Parameters:
- CallSummarization
- SummarizationBedrockModelId
- SummarizationSageMakerInitialInstanceCount
- SummarizationLambdaFunctionArn
- Label:
default: Third Party LLM API Key
Parameters:
- SummarizationLLMThirdPartyApiKey
- Label:
default: Generative AI Query
Parameters:
- GenAIQuery
- GenAIQueryBedrockModelId
- Label:
default: Advanced analytics and reporting
Parameters:
- EnablePcaDashboards
- DatabaseName
- Label:
default: S3 Bucket Names and Retention Policy
Parameters:
- InputBucketName
- BulkUploadBucketName
- OutputBucketName
- SupportFilesBucketName
- RetentionDays
- Label:
default: S3 bucket prefixes
Parameters:
- InputBucketFailedTranscriptions
- InputBucketRawAudio
- InputBucketOrigTranscripts
- InputBucketAudioPlayback
- OutputBucketParsedResults
- OutputBucketTranscribeResults
- Label:
default: Filename metadata parsing
Parameters:
- FilenameDatetimeRegex
- FilenameDatetimeFieldMap
- FilenameGUIDRegex
- FilenameAgentRegex
- FilenameCustRegex
- Label:
default: Transcription
Parameters:
- TranscribeApiMode
- TranscribeLanguages
- VocabFilterMode
- VocabFilterName
- VocabularyName
- CustomLangModelName
- SpeakerSeparationType
- SpeakerNames
- MaxSpeakers
- CallRedactionTranscript
- CallRedactionAudio
- ContentRedactionLanguages
- Label:
default: Telephony system
Parameters:
- TelephonyCTRType
- TelephonyCTRFileSuffix
- Label:
default: Entity detection
Parameters:
- ComprehendLanguages
- EntityThreshold
- EntityTypes
- EntityRecognizerEndpoint
- EntityStringMap
- Label:
default: Sentiment detection
Parameters:
- MinSentimentNegative
- MinSentimentPositive
- Label:
default: Bulk upload
Parameters:
- BulkUploadMaxDripRate
- BulkUploadMaxTranscribeJobs
- BulkUploadStepFunctionName
- Label:
default: Miscellaneous
Parameters:
- ConversationLocation
- Environment
- StepFunctionName
- ffmpegDownloadUrl
- TestBedrockModelId
Conditions:
ShouldCreateBulkUploadBucket: !Equals [!Ref BulkUploadBucketName, '']
ShouldCreateInputBucket: !Equals [!Ref InputBucketName, '']
ShouldCreateOutputBucket: !Equals [!Ref OutputBucketName, '']
ShouldCreateSupportFilesBucket: !Equals [!Ref SupportFilesBucketName, '']
ShouldEnableGui: !Not [!Equals [!Ref EnableGui, "false"]]
ShouldEnableKendraSearch: !Not [!Equals [!Ref EnableTranscriptKendraSearch, 'No']]
ShouldCreateKendraIndexDeveloperEdition: !Equals [!Ref EnableTranscriptKendraSearch, 'Yes, create new Kendra Index (Developer Edition)']
ShouldDeployPcaDashboards: !Equals [!Ref EnablePcaDashboards, 'Yes']
ShouldLoadSampleFiles: !Equals [!Ref loadSampleAudioFiles, 'true']
ShouldDeployBedrockBoto3Layer: !Or [
!Equals [!Ref CallSummarization, 'BEDROCK'],
!Equals [!Ref CallSummarization, 'BEDROCK+TCA'],
!Equals [!Ref CallSummarization, 'TCA-ONLY'],
!Equals [!Ref GenAIQuery, 'BEDROCK'],
]
ShouldDeployLLMThirdPartyApiKey: !And [!Not [!Equals [!Ref SummarizationLLMThirdPartyApiKey, '']], !Not [!Equals [!Ref SummarizationLLMThirdPartyApiKey, undefined]]]
ShouldTestBedrockModelId: !And [
!Or [
!Equals [!Ref CallSummarization, 'BEDROCK'],
!Equals [!Ref CallSummarization, "BEDROCK+TCA"],
!Equals [!Ref GenAIQuery, 'BEDROCK'],
],
!Equals [!Ref TestBedrockModelId, 'true']
]
ShouldTestGenAIQueryBedrockModelId: !And [
!Equals [!Ref GenAIQuery, 'BEDROCK'],
!Equals [!Ref TestBedrockModelId, 'true']
]
ShouldTestSummarizationBedrockModelId: !And [
!Or [
!Equals [!Ref CallSummarization, 'BEDROCK'],
!Equals [!Ref CallSummarization, "BEDROCK+TCA"],
],
!Equals [!Ref TestBedrockModelId, 'true']
]
Rules:
GuiEnabledWithKenda:
RuleCondition: !Not [!Equals [!Ref EnableTranscriptKendraSearch, 'No']]
Assertions:
- Assert: !Not [!Equals [!Ref EnableGui, "false"]]
AssertDescription: If Kendra is enabled, GUI must also be enabled
Resources:
########################################################
# S3 buckets
# TODO: Versioning? Lifecycle Policies? Access Logging?
########################################################
BulkUploadBucket:
Condition: ShouldCreateBulkUploadBucket
Type: 'AWS::S3::Bucket'
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
InputBucket:
Condition: ShouldCreateInputBucket
Type: 'AWS::S3::Bucket'
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
LifecycleConfiguration:
Rules:
- Id: StorageClassAndRetention
Status: Enabled
ExpirationInDays: !Ref RetentionDays
Transitions:
- TransitionInDays: 1
StorageClass: INTELLIGENT_TIERING
OutputBucket:
Condition: ShouldCreateOutputBucket
Type: 'AWS::S3::Bucket'
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
LifecycleConfiguration:
Rules:
- Id: LifecycleRule
Status: Enabled
ExpirationInDays: !Ref RetentionDays
Transitions:
- TransitionInDays: 1
StorageClass: INTELLIGENT_TIERING
SupportFilesBucket:
Condition: ShouldCreateSupportFilesBucket
Type: 'AWS::S3::Bucket'
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
Properties:
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
########################################################
# Kendra Index
########################################################
KendraIndexRole:
Type: 'AWS::IAM::Role'
Condition: ShouldEnableKendraSearch
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Sid: ''
Effect: Allow
Principal:
Service: kendra.amazonaws.com
Action: 'sts:AssumeRole'
Policies:
- PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Resource: '*'
Condition:
StringEquals:
'cloudwatch:namespace': 'Kendra'
Action:
- 'cloudwatch:PutMetricData'
- Effect: Allow
Resource: '*'
Action: 'logs:DescribeLogGroups'
- Effect: Allow
Resource: !Sub
- 'arn:aws:logs:${region}:${account}:log-group:/aws/kendra/*'
- region: !Ref 'AWS::Region'
account: !Ref 'AWS::AccountId'
Action: 'logs:CreateLogGroup'
- Effect: Allow
Resource: !Sub
- 'arn:aws:logs:${region}:${account}:log-group:/aws/kendra/*:log-stream:*'
- region: !Ref 'AWS::Region'
account: !Ref 'AWS::AccountId'
Action:
- 'logs:DescribeLogStreams'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
PolicyName: KendraMediaIndexPolicy
KendraIndex:
Type: 'AWS::Kendra::Index'
Condition: ShouldEnableKendraSearch
Properties:
CapacityUnits: !If
- ShouldCreateKendraIndexDeveloperEdition
- !Ref AWS::NoValue
-
QueryCapacityUnits: !Ref QueryCapacityUnits
StorageCapacityUnits: !Ref StorageCapacityUnits
Description: PCA transcript index
Edition:
!If
- ShouldCreateKendraIndexDeveloperEdition
- 'DEVELOPER_EDITION'
- 'ENTERPRISE_EDITION'
Name: !Join
- ''
- - !Ref 'AWS::StackName'
- '-Index'
RoleArn: !GetAtt KendraIndexRole.Arn
DocumentMetadataConfigurations:
- Name: ANALYSIS_URI
Search:
Displayable: true
Type: 'STRING_VALUE'
- Name: DATETIME
Search:
Displayable: true
Facetable: true
Relevance:
Freshness: true
Type: 'DATE_VALUE'
- Name: GUID
Search:
Displayable: true
Searchable: true
Type: 'STRING_VALUE'
- Name: AGENT
Search:
Displayable: true
Facetable: true
Type: 'STRING_VALUE'
- Name: DURATION
Search:
Displayable: true
Facetable: true
Type: 'STRING_VALUE'
- Name: ENTITY_PERSON
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
- Name: ENTITY_LOCATION
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
- Name: ENTITY_ORGANIZATION
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
- Name: ENTITY_COMMERCIAL_ITEM
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
- Name: ENTITY_EVENT
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
- Name: ENTITY_DATE
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
- Name: ENTITY_QUANTITY
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
- Name: ENTITY_TITLE
Search:
Displayable: true
Facetable: true
Type: 'STRING_LIST_VALUE'
########################################################
# If Bedrock Models are selected, verify that Bedrock
# is available in the region, and that models are enabled
########################################################
TestBedrockModelFunctionRole:
Type: AWS::IAM::Role
Condition: ShouldTestBedrockModelId
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- "bedrock:InvokeModel"
Resource:
- !Sub "arn:${AWS::Partition}:bedrock:*::foundation-model/*"
- !Sub "arn:${AWS::Partition}:bedrock:*:${AWS::AccountId}:custom-model/*"
PolicyName: BedrockPolicy
TestBedrockModelFunction:
Type: AWS::Lambda::Function
Condition: ShouldTestBedrockModelId
Properties:
Handler: index.lambda_handler
Role: !GetAtt 'TestBedrockModelFunctionRole.Arn'
Runtime: python3.11
Timeout: 60
MemorySize: 128
Code:
ZipFile: !Sub |
import cfnresponse
import json
import subprocess
import os
import sys
print("install latest boto3 to get bedrock service support")
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--target', '/tmp', 'boto3'])
sys.path.insert(0,'/tmp')
import boto3
# Defaults
AWS_REGION = os.environ["AWS_REGION_OVERRIDE"] if "AWS_REGION_OVERRIDE" in os.environ else os.environ["AWS_REGION"]
ENDPOINT_URL = os.environ.get("ENDPOINT_URL", f'https://bedrock-runtime.{AWS_REGION}.amazonaws.com')
DEFAULT_MAX_TOKENS = 128
def get_request_body(modelId, parameters, prompt):
provider = modelId.split(".")[0]
request_body = None
if provider == "anthropic":
if 'claude-3' in modelId:
request_body = {
"max_tokens": DEFAULT_MAX_TOKENS,
"messages": [{"role": "user", "content": prompt}],
"anthropic_version": "bedrock-2023-05-31"
}
else:
request_body = {
"prompt": prompt,
"max_tokens_to_sample": DEFAULT_MAX_TOKENS
}
request_body.update(parameters)
elif provider == "ai21":
request_body = {
"prompt": prompt,
"maxTokens": DEFAULT_MAX_TOKENS
}
request_body.update(parameters)
elif provider == "amazon":
textGenerationConfig = {
"maxTokenCount": DEFAULT_MAX_TOKENS
}
textGenerationConfig.update(parameters)
request_body = {
"inputText": prompt,
"textGenerationConfig": textGenerationConfig
}
else:
raise Exception("Unsupported provider: ", provider)
return request_body
def get_generate_text(modelId, response):
provider = modelId.split(".")[0]
generated_text = None
if provider == "anthropic":
if 'claude-3' in modelId:
response_raw = json.loads(response.get("body").read().decode())
generated_text = response_raw.get('content')[0].get('text')
else:
response_body = json.loads(response.get("body").read().decode())
generated_text = response_body.get("completion")
elif provider == "ai21":
response_body = json.loads(response.get("body").read())
generated_text = response_body.get("completions")[0].get("data").get("text")
elif provider == "amazon":
response_body = json.loads(response.get("body").read())
generated_text = response_body.get("results")[0].get("outputText")
else:
raise Exception("Unsupported provider: ", provider)
return generated_text
def call_llm(parameters, prompt):
modelId = parameters.pop("modelId")
body = get_request_body(modelId, parameters, prompt)
print("ModelId", modelId, "- Body: ", body)
client = boto3.client(service_name='bedrock-runtime', region_name=AWS_REGION, endpoint_url=ENDPOINT_URL)
response = client.invoke_model(body=json.dumps(body), modelId=modelId, accept='application/json', contentType='application/json')
generated_text = get_generate_text(modelId, response)
return generated_text
def lambda_handler(event, context):
print("Event: ", json.dumps(event))
global client
status = cfnresponse.SUCCESS
responseData = {}
reason = "Success"
modelId = ""
if event['RequestType'] != 'Delete':
prompt = "\n\nHuman: Why is the sky blue?\n\nAssistant:"
try:
# Test LLMModel
llmModelId = event['ResourceProperties'].get('LLMModelId', '')
modelId = llmModelId
parameters = {
"modelId": modelId,
"temperature": 0
}
print(f"Testing {modelId}")
call_llm(parameters, prompt)
except Exception as e: