-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.bicep
More file actions
1357 lines (1227 loc) · 54 KB
/
Copy pathmain.bicep
File metadata and controls
1357 lines (1227 loc) · 54 KB
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
// ========== main.bicep ========== //
targetScope = 'resourceGroup'
@minLength(3)
@maxLength(20)
@description('Required. A unique prefix for all resources in this deployment. This should be 3-20 characters long:')
param solutionName string = 'clientadvisor'
@description('Optional. Existing Log Analytics Workspace Resource ID')
param existingLogAnalyticsWorkspaceId string = ''
@description('Optional. CosmosDB Location')
param cosmosLocation string = 'eastus2'
@minLength(1)
@description('Optional. GPT model deployment type:')
@allowed([
'Standard'
'GlobalStandard'
])
param gptModelDeploymentType string = 'GlobalStandard'
@minLength(1)
@description('Optional. Name of the GPT model to deploy:')
@allowed([
'gpt-4o-mini'
])
param gptModelName string = 'gpt-4o-mini'
@description('Optional. Version of the GPT model to deploy.')
param gptModelVersion string = '2024-07-18'
@description('Optional. Version of the GPT model to deploy.')
param embeddingModelVersion string = '2'
@description('Optional. API version for the Azure OpenAI service.')
param azureOpenaiAPIVersion string = '2025-04-01-preview'
@minValue(10)
@description('Optional. Capacity of the GPT deployment:')
// You can increase this, but capacity is limited per model/region, so you will get errors if you go over
// https://learn.microsoft.com/en-us/azure/ai-services/openai/quotas-limits
param gptModelCapacity int = 200
@minLength(1)
@description('Optional. Name of the Text Embedding model to deploy:')
@allowed([
'text-embedding-ada-002'
])
param embeddingModel string = 'text-embedding-ada-002'
@minValue(10)
@description('Optional. Capacity of the Embedding Model deployment')
param embeddingDeploymentCapacity int = 80
// @description('Fabric Workspace Id if you have one, else leave it empty. ')
// param fabricWorkspaceId string
//restricting to these regions because assistants api for gpt-4o-mini is available only in these regions
@allowed([
'australiaeast'
'eastus'
'eastus2'
'francecentral'
'japaneast'
'swedencentral'
'uksouth'
'westus'
'westus3'
])
// @description('Azure OpenAI Location')
// param AzureOpenAILocation string = 'eastus2'
@metadata({
azd: {
type: 'location'
usageName: [
'OpenAI.GlobalStandard.gpt-4o-mini,200'
'OpenAI.GlobalStandard.text-embedding-ada-002,80'
]
}
})
@description('Required. Location for AI Foundry deployment. This is the location where the AI Foundry resources will be deployed.')
param azureAiServiceLocation string
@description('Optional. Set this if you want to deploy to a different region than the resource group. Otherwise, it will use the resource group location by default.')
param AZURE_LOCATION string = ''
var solutionLocation = empty(AZURE_LOCATION) ? resourceGroup().location : AZURE_LOCATION
@maxLength(5)
@description('Optional. A unique token for the solution. This is used to ensure resource names are unique for global resources. Defaults to a 5-character substring of the unique string generated from the subscription ID, resource group name, and solution name.')
param solutionUniqueToken string = substring(uniqueString(subscription().id, resourceGroup().name, solutionName), 0, 5)
var solutionSuffix= toLower(trim(replace(
replace(
replace(replace(replace(replace('${solutionName}${solutionUniqueToken}', '-', ''), '_', ''), '.', ''), '/', ''),
' ',
''
),
'*',
''
)))
@description('Optional. Enable private networking for applicable resources, aligned with the Well Architected Framework recommendations. Defaults to false.')
param enablePrivateNetworking bool = false
@description('Optional. Enable monitoring applicable resources, aligned with the Well Architected Framework recommendations. This setting enables Application Insights and Log Analytics and configures all the resources applicable resources to send logs. Defaults to false.')
param enableMonitoring bool = false
@description('Optional. Enable scalability for applicable resources, aligned with the Well Architected Framework recommendations. Defaults to false.')
param enableScalability bool = false
@description('Optional. Enable/Disable usage telemetry for module.')
param enableTelemetry bool = true
@description('Optional. Enable redundancy for applicable resources, aligned with the Well Architected Framework recommendations. Defaults to false.')
param enableRedundancy bool = false
@description('Optional. The Container Registry hostname where the docker images for the frontend are located.')
param containerRegistryHostname string = 'bycwacontainerreg.azurecr.io'
@description('Optional. The Container Image Name to deploy on the webapp.')
param containerImageName string = 'byc-wa-app'
@description('Optional. The Container Image Tag to deploy on the webapp.')
param containerImageTag string = 'latest'
@description('Optional. Resource ID of an existing Foundry project')
param existingFoundryProjectResourceId string = ''
@description('Optional. Enable purge protection for the Key Vault')
param enablePurgeProtection bool = false
// Load the abbrevations file required to name the azure resources.
//var abbrs = loadJsonContent('./abbreviations.json')
var appEnvironment = 'Prod'
var azureSearchIndex = 'transcripts_index'
var azureSearchUseSemanticSearch = 'True'
var azureSearchSemanticSearchConfig = 'my-semantic-config'
var azureSearchTopK = '5'
var azureSearchContentColumns = 'content'
var azureSearchFilenameColumn = 'chunk_id'
var azureSearchTitleColumn = 'client_id'
var azureSearchUrlColumn = 'sourceurl'
var azureOpenAITemperature = '0'
var azureOpenAITopP = '1'
var azureOpenAIMaxTokens = '1000'
var azureOpenAIStopSequence = '\n'
var azureOpenAISystemMessage = '''You are a helpful Wealth Advisor assistant'''
var azureOpenAIStream = 'True'
var azureSearchQueryType = 'simple'
var azureSearchVectorFields = 'contentVector'
var azureSearchPermittedGroupsField = ''
var azureSearchStrictness = '3'
var azureSearchEnableInDomain = 'False' // Set to 'True' if you want to enable in-domain search
var azureCosmosDbEnableFeedback = 'True'
var useInternalStream = 'True'
var useAIProjectClientFlag = 'False'
var sqlServerFqdn = 'sql-${solutionSuffix}.database.windows.net'
@description('Optional. Size of the Jumpbox Virtual Machine when created. Set to custom value if enablePrivateNetworking is true.')
param vmSize string?
@description('Optional. Admin username for the Jumpbox Virtual Machine. Set to custom value if enablePrivateNetworking is true.')
@secure()
//param vmAdminUsername string = take(newGuid(), 20)
param vmAdminUsername string?
@description('Optional. Admin password for the Jumpbox Virtual Machine. Set to custom value if enablePrivateNetworking is true.')
@secure()
//param vmAdminPassword string = newGuid()
param vmAdminPassword string?
var functionAppSqlPrompt = '''Generate a valid T-SQL query to find {query} for tables and columns provided below:
1. Table: Clients
Columns: ClientId, Client, Email, Occupation, MaritalStatus, Dependents
2. Table: InvestmentGoals
Columns: ClientId, InvestmentGoal
3. Table: Assets
Columns: ClientId, AssetDate, Investment, ROI, Revenue, AssetType
4. Table: ClientSummaries
Columns: ClientId, ClientSummary
5. Table: InvestmentGoalsDetails
Columns: ClientId, InvestmentGoal, TargetAmount, Contribution
6. Table: Retirement
Columns: ClientId, StatusDate, RetirementGoalProgress, EducationGoalProgress
7. Table: ClientMeetings
Columns: ClientId, ConversationId, Title, StartTime, EndTime, Advisor, ClientEmail
Always use the Investment column from the Assets table as the value.
Assets table has snapshots of values by date. Do not add numbers across different dates for total values.
Do not use client name in filters.
Do not include assets values unless asked for.
ALWAYS use ClientId = {clientid} in the query filter.
ALWAYS select Client Name (Column: Client) in the query.
Query filters are IMPORTANT. Add filters like AssetType, AssetDate, etc. if needed.
When answering scheduling or time-based meeting questions, always use the StartTime column from ClientMeetings table. Use correct logic to return the most recent past meeting (last/previous) or the nearest future meeting (next/upcoming), and ensure only StartTime column is used for meeting timing comparisons.
For asset values: If the question is about "asset value", "total asset value", "portfolio value", or "AUM" → ALWAYS return the SUM of the latest investments (do not return individual rows). If the question is about "current asset value" or "current investment value" → return all latest investments without SUM.
For trend queries: If the question contains "how did change", "over the last", "trend", or "progression" → return time series data for the requested period with SUM for each time period and show chronological progression.
Only return the generated SQL query. Do not return anything else.'''
var functionAppCallTranscriptSystemPrompt = '''You are an assistant who supports wealth advisors in preparing for client meetings.
You have access to the client’s past meeting call transcripts.
When answering questions, especially summary requests, provide a detailed and structured response that includes key topics, concerns, decisions, and trends.
If no data is available, state 'No relevant data found for previous meetings.'''
var functionAppStreamTextSystemPrompt = '''The currently selected client's name is '{SelectedClientName}'. Treat any case-insensitive or partial mention as referring to this client.
If the user mentions no name, assume they are asking about '{SelectedClientName}'.
If the user references a name that clearly differs from '{SelectedClientName}' or comparing with other clients, respond only with: 'Please only ask questions about the selected client or select another client.' Otherwise, provide thorough answers for every question using only data from SQL or call transcripts.'
If no data is found, respond with 'No data found for that client.' Remove any client identifiers from the final response.
Always send clientId as '{client_id}'.'''
// Replica regions list based on article in [Azure regions list](https://learn.microsoft.com/azure/reliability/regions-list) and [Enhance resilience by replicating your Log Analytics workspace across regions](https://learn.microsoft.com/azure/azure-monitor/logs/workspace-replication#supported-regions) for supported regions for Log Analytics Workspace.
var replicaRegionPairs = {
australiaeast: 'australiasoutheast'
centralus: 'westus'
eastasia: 'japaneast'
eastus: 'centralus'
eastus2: 'centralus'
japaneast: 'eastasia'
northeurope: 'westeurope'
southeastasia: 'eastasia'
uksouth: 'westeurope'
westeurope: 'northeurope'
}
var replicaLocation = replicaRegionPairs[resourceGroup().location]
@description('Optional. The tags to apply to all deployed Azure resources.')
param tags resourceInput<'Microsoft.Resources/resourceGroups@2025-04-01'>.tags = {}
// Region pairs list based on article in [Azure Database for MySQL Flexible Server - Azure Regions](https://learn.microsoft.com/azure/mysql/flexible-server/overview#azure-regions) for supported high availability regions for CosmosDB.
var cosmosDbZoneRedundantHaRegionPairs = {
australiaeast: 'uksouth' //'southeastasia'
centralus: 'eastus2'
eastasia: 'southeastasia'
eastus: 'centralus'
eastus2: 'centralus'
japaneast: 'australiaeast'
northeurope: 'westeurope'
southeastasia: 'eastasia'
uksouth: 'westeurope'
westeurope: 'northeurope'
}
var allTags = union(
{
'azd-env-name': solutionName
},
tags
)
// Paired location calculated based on 'location' parameter. This location will be used by applicable resources if `enableScalability` is set to `true`
var cosmosDbHaLocation = cosmosDbZoneRedundantHaRegionPairs[resourceGroup().location]
// Extracts subscription, resource group, and workspace name from the resource ID when using an existing Log Analytics workspace
var useExistingLogAnalytics = !empty(existingLogAnalyticsWorkspaceId)
var existingLawSubscription = useExistingLogAnalytics ? split(existingLogAnalyticsWorkspaceId, '/')[2] : ''
var existingLawResourceGroup = useExistingLogAnalytics ? split(existingLogAnalyticsWorkspaceId, '/')[4] : ''
var existingLawName = useExistingLogAnalytics ? split(existingLogAnalyticsWorkspaceId, '/')[8] : ''
resource existingLogAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2020-08-01' existing = if (useExistingLogAnalytics) {
name: existingLawName
scope: resourceGroup(existingLawSubscription, existingLawResourceGroup)
}
var logAnalyticsWorkspaceResourceId = useExistingLogAnalytics ? existingLogAnalyticsWorkspaceId : logAnalyticsWorkspace!.outputs.resourceId
@description('Optional created by user name')
param createdBy string = empty(deployer().userPrincipalName) ? '' : split(deployer().userPrincipalName, '@')[0]
// ========== Resource Group Tag ========== //
resource resourceGroupTags 'Microsoft.Resources/tags@2021-04-01' = {
name: 'default'
properties: {
tags: {
...tags
TemplateName: 'Client Advisor'
CreatedBy: createdBy
}
}
}
// ========== Log Analytics Workspace ========== //
// WAF best practices for Log Analytics: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-log-analytics
// WAF PSRules for Log Analytics: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#azure-monitor-logs
var logAnalyticsWorkspaceResourceName = 'log-${solutionSuffix}'
module logAnalyticsWorkspace 'br/public:avm/res/operational-insights/workspace:0.12.0' = if (enableMonitoring && !useExistingLogAnalytics) {
name: take('avm.res.operational-insights.workspace.${logAnalyticsWorkspaceResourceName}', 64)
params: {
name: logAnalyticsWorkspaceResourceName
tags: tags
location: solutionLocation
enableTelemetry: enableTelemetry
skuName: 'PerGB2018'
dataRetention: 365
features: { enableLogAccessUsingOnlyResourcePermissions: true }
diagnosticSettings: [{ useThisWorkspace: true }]
// WAF aligned configuration for Redundancy
dailyQuotaGb: enableRedundancy ? 10 : null //WAF recommendation: 10 GB per day is a good starting point for most workloads
replication: enableRedundancy
? {
enabled: true
location: replicaLocation
}
: null
// WAF aligned configuration for Private Networking
publicNetworkAccessForIngestion: enablePrivateNetworking ? 'Disabled' : 'Enabled'
publicNetworkAccessForQuery: enablePrivateNetworking ? 'Disabled' : 'Enabled'
dataSources: enablePrivateNetworking
? [
{
tags: tags
eventLogName: 'Application'
eventTypes: [
{
eventType: 'Error'
}
{
eventType: 'Warning'
}
{
eventType: 'Information'
}
]
kind: 'WindowsEvent'
name: 'applicationEvent'
}
{
counterName: '% Processor Time'
instanceName: '*'
intervalSeconds: 60
kind: 'WindowsPerformanceCounter'
name: 'windowsPerfCounter1'
objectName: 'Processor'
}
{
kind: 'IISLogs'
name: 'sampleIISLog1'
state: 'OnPremiseEnabled'
}
]
: null
}
}
// ========== Application Insights ========== //
// WAF best practices for Application Insights: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/application-insights
// WAF PSRules for Application Insights: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#application-insights
var applicationInsightsResourceName = 'appi-${solutionSuffix}'
module applicationInsights 'br/public:avm/res/insights/component:0.6.0' = if (enableMonitoring) {
name: take('avm.res.insights.component.${applicationInsightsResourceName}', 64)
params: {
name: applicationInsightsResourceName
tags: tags
location: solutionLocation
enableTelemetry: enableTelemetry
retentionInDays: 365
kind: 'web'
disableIpMasking: false
flowType: 'Bluefield'
// WAF aligned configuration for Monitoring
workspaceResourceId: enableMonitoring ? logAnalyticsWorkspaceResourceId : ''
diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null
}
}
// ========== User Assigned Identity ========== //
// WAF best practices for identity and access management: https://learn.microsoft.com/en-us/azure/well-architected/security/identity-access
var userAssignedIdentityResourceName = 'id-${solutionSuffix}'
module userAssignedIdentity 'br/public:avm/res/managed-identity/user-assigned-identity:0.4.1' = {
name: take('avm.res.managed-identity.user-assigned-identity.${userAssignedIdentityResourceName}', 64)
params: {
name: userAssignedIdentityResourceName
location: solutionLocation
tags: tags
enableTelemetry: enableTelemetry
}
}
// ========== Network Module ========== //
module network 'modules/network.bicep' = if (enablePrivateNetworking) {
name: take('network-${solutionSuffix}-deployment', 64)
params: {
resourcesName: solutionSuffix
// logAnalyticsWorkSpaceResourceId: logAnalyticsWorkspace.outputs.resourceId
logAnalyticsWorkSpaceResourceId: logAnalyticsWorkspaceResourceId
vmAdminUsername: vmAdminUsername ?? 'JumpboxAdminUser'
vmAdminPassword: vmAdminPassword ?? 'JumpboxAdminP@ssw0rd1234!'
vmSize: vmSize ?? 'Standard_DS2_v2' // Default VM size
location: solutionLocation
tags: allTags
enableTelemetry: enableTelemetry
}
}
// ========== Private DNS Zones ========== //
var privateDnsZones = [
'privatelink.cognitiveservices.azure.com'
'privatelink.openai.azure.com'
'privatelink.services.ai.azure.com'
'privatelink.azurewebsites.net'
'privatelink.blob.${environment().suffixes.storage}'
'privatelink.queue.${environment().suffixes.storage}'
'privatelink.file.${environment().suffixes.storage}'
'privatelink.documents.azure.com'
'privatelink.vaultcore.azure.net'
'privatelink${environment().suffixes.sqlServerHostname}'
'privatelink.search.windows.net'
]
// DNS Zone Index Constants
var dnsZoneIndex = {
cognitiveServices: 0
openAI: 1
aiServices: 2
appService: 3
storageBlob: 4
storageQueue: 5
storageFile: 6
cosmosDB: 7
keyVault: 8
sqlServer: 9
searchService: 10
}
// List of DNS zone indices that correspond to AI-related services.
var aiRelatedDnsZoneIndices = [
dnsZoneIndex.cognitiveServices
dnsZoneIndex.openAI
dnsZoneIndex.aiServices
]
// ===================================================
// DEPLOY PRIVATE DNS ZONES
// - Deploys all zones if no existing Foundry project is used
// - Excludes AI-related zones when using with an existing Foundry project
// ===================================================
@batchSize(5)
module avmPrivateDnsZones 'br/public:avm/res/network/private-dns-zone:0.7.1' = [
for (zone, i) in privateDnsZones: if (enablePrivateNetworking && (empty(existingFoundryProjectResourceId) || !contains(aiRelatedDnsZoneIndices, i))) {
name: 'dns-zone-${i}'
params: {
name: zone
tags: tags
enableTelemetry: enableTelemetry
virtualNetworkLinks: [
{
name: take('vnetlink-${network!.outputs.vnetName}-${split(zone, '.')[1]}', 80)
virtualNetworkResourceId: network!.outputs.vnetResourceId
}
]
}
}
]
// ==========Key Vault Module ========== //
var keyVaultName = 'KV-${solutionSuffix}'
module keyvault 'br/public:avm/res/key-vault/vault:0.12.1' = {
name: take('avm.res.key-vault.vault.${keyVaultName}', 64)
params: {
name: keyVaultName
location: solutionLocation
tags: tags
sku: 'standard'
publicNetworkAccess: enablePrivateNetworking ? 'Disabled' : 'Enabled'
networkAcls: {
defaultAction: 'Allow'
}
enableVaultForDeployment: true
enableVaultForDiskEncryption: true
enableVaultForTemplateDeployment: true
enableRbacAuthorization: true
enableSoftDelete: true
enablePurgeProtection: enablePurgeProtection
softDeleteRetentionInDays: 7
diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : []
// WAF aligned configuration for Private Networking
privateEndpoints: enablePrivateNetworking
? [
{
name: 'pep-${keyVaultName}'
customNetworkInterfaceName: 'nic-${keyVaultName}'
privateDnsZoneGroup: {
privateDnsZoneGroupConfigs: [
{ privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.keyVault]!.outputs.resourceId }
]
}
service: 'vault'
subnetResourceId: network!.outputs.subnetPrivateEndpointsResourceId
}
]
: []
// WAF aligned configuration for Role-based Access Control
roleAssignments: [
{
principalId: userAssignedIdentity.outputs.principalId
principalType: 'ServicePrincipal'
roleDefinitionIdOrName: 'Key Vault Administrator'
}
]
secrets: [
{
name: 'SQLDB-SERVER'
value: sqlServerFqdn
}
{
name: 'SQLDB-DATABASE'
value: sqlDbName
}
{
name: 'AZURE-OPENAI-PREVIEW-API-VERSION'
value: azureOpenaiAPIVersion
}
{
name: 'AZURE-OPENAI-ENDPOINT'
value: aiFoundryAiServices.outputs.endpoints['OpenAI Language Model Instance API']
}
{
name: 'AZURE-OPENAI-EMBEDDING-MODEL'
value: embeddingModel
}
{
name: 'AZURE-SEARCH-INDEX'
value: azureSearchIndex
}
{
name: 'AZURE-SEARCH-ENDPOINT'
value: 'https://${aiSearchName}.search.windows.net'
}
]
enableTelemetry: enableTelemetry
}
}
// ========== AI Foundry: AI Services ========== //
// WAF best practices for Open AI: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-openai
var useExistingAiFoundryAiProject = !empty(existingFoundryProjectResourceId)
var aiFoundryAiServicesSubscriptionId = useExistingAiFoundryAiProject
? split(existingFoundryProjectResourceId, '/')[2]
: subscription().id
var aiFoundryAiServicesResourceGroupName = useExistingAiFoundryAiProject
? split(existingFoundryProjectResourceId, '/')[4]
: 'rg-${solutionSuffix}'
var aiFoundryAiServicesResourceName = useExistingAiFoundryAiProject
? split(existingFoundryProjectResourceId, '/')[8]
: 'aif-${solutionSuffix}'
var aiFoundryAiProjectResourceName = useExistingAiFoundryAiProject
? split(existingFoundryProjectResourceId, '/')[10]
: 'proj-${solutionSuffix}'
// AI Project resource id: /subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.CognitiveServices/accounts/<ai-services-name>/projects/<project-name>
// NOTE: Required version 'Microsoft.CognitiveServices/accounts@2024-04-01-preview' not available in AVM
// var aiFoundryAiServicesResourceName = 'aif-${solutionSuffix}'
var aiFoundryAiServicesAiProjectResourceName = 'proj-${solutionSuffix}'
var aiFoundryAIservicesEnabled = true
var aiFoundryAiServicesModelDeployment = {
format: 'OpenAI'
name: gptModelName
version: gptModelVersion
sku: {
name: gptModelDeploymentType
capacity: gptModelCapacity
}
raiPolicyName: 'Microsoft.Default'
}
var aiFoundryAiServicesEmbeddingModel = {
name: embeddingModel
version: embeddingModelVersion
sku: {
name: 'GlobalStandard'
capacity: embeddingDeploymentCapacity
}
raiPolicyName: 'Microsoft.Default'
}
module aiFoundryAiServices 'modules/ai-services.bicep' = if (aiFoundryAIservicesEnabled) {
name: take('avm.res.cognitive-services.account.${aiFoundryAiServicesResourceName}', 64)
params: {
name: aiFoundryAiServicesResourceName
location: azureAiServiceLocation
tags: tags
existingFoundryProjectResourceId: existingFoundryProjectResourceId
projectName: aiFoundryAiServicesAiProjectResourceName
projectDescription: 'AI Foundry Project'
sku: 'S0'
kind: 'AIServices'
disableLocalAuth: true
customSubDomainName: aiFoundryAiServicesResourceName
apiProperties: {
//staticsEnabled: false
}
networkAcls: {
defaultAction: 'Allow'
virtualNetworkRules: []
ipRules: []
}
managedIdentities: { userAssignedResourceIds: [userAssignedIdentity!.outputs.resourceId] } //To create accounts or projects, you must enable a managed identity on your resource
roleAssignments: [
{
roleDefinitionIdOrName: '53ca6127-db72-4b80-b1b0-d745d6d5456d' // Azure AI User
principalId: userAssignedIdentity.outputs.principalId
principalType: 'ServicePrincipal'
}
{
roleDefinitionIdOrName: '64702f94-c441-49e6-a78b-ef80e0188fee' // Azure AI Developer
principalId: userAssignedIdentity.outputs.principalId
principalType: 'ServicePrincipal'
}
{
roleDefinitionIdOrName: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' // Cognitive Services OpenAI User
principalId: userAssignedIdentity.outputs.principalId
principalType: 'ServicePrincipal'
}
]
// WAF aligned configuration for Monitoring
diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null
publicNetworkAccess: enablePrivateNetworking ? 'Disabled' : 'Enabled'
privateEndpoints: (enablePrivateNetworking && empty(existingFoundryProjectResourceId))
? ([
{
name: 'pep-${aiFoundryAiServicesResourceName}'
customNetworkInterfaceName: 'nic-${aiFoundryAiServicesResourceName}'
subnetResourceId: network!.outputs.subnetPrivateEndpointsResourceId
privateDnsZoneGroup: {
privateDnsZoneGroupConfigs: [
{
name: 'ai-services-dns-zone-cognitiveservices'
privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.cognitiveServices]!.outputs.resourceId
}
{
name: 'ai-services-dns-zone-openai'
privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.openAI]!.outputs.resourceId
}
{
name: 'ai-services-dns-zone-aiservices'
privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.aiServices]!.outputs.resourceId
}
]
}
}
])
: []
deployments: [
{
name: aiFoundryAiServicesModelDeployment.name
model: {
format: aiFoundryAiServicesModelDeployment.format
name: aiFoundryAiServicesModelDeployment.name
version: aiFoundryAiServicesModelDeployment.version
}
raiPolicyName: aiFoundryAiServicesModelDeployment.raiPolicyName
sku: {
name: aiFoundryAiServicesModelDeployment.sku.name
capacity: aiFoundryAiServicesModelDeployment.sku.capacity
}
}
{
name: aiFoundryAiServicesEmbeddingModel.name
model: {
format: 'OpenAI'
name: aiFoundryAiServicesEmbeddingModel.name
version: aiFoundryAiServicesEmbeddingModel.version
}
raiPolicyName: aiFoundryAiServicesEmbeddingModel.raiPolicyName
sku: {
name: aiFoundryAiServicesEmbeddingModel.sku.name
capacity: aiFoundryAiServicesEmbeddingModel.sku.capacity
}
}
]
}
}
//========== AVM WAF ========== //
//========== Cosmos DB module ========== //
var cosmosDbResourceName = 'cosmos-${solutionSuffix}'
var cosmosDbDatabaseName = 'db_conversation_history'
var collectionName = 'conversations'
module cosmosDb 'br/public:avm/res/document-db/database-account:0.15.0' = {
name: take('avm.res.document-db.database-account.${cosmosDbResourceName}', 64)
params: {
// Required parameters
name: cosmosDbResourceName
location: cosmosLocation
tags: tags
enableTelemetry: enableTelemetry
sqlDatabases: [
{
name: cosmosDbDatabaseName
containers: [
{
name: collectionName
paths: [
'/userId'
]
}
]
}
]
dataPlaneRoleDefinitions: [
{
// Cosmos DB Built-in Data Contributor: https://docs.azure.cn/en-us/cosmos-db/nosql/security/reference-data-plane-roles#cosmos-db-built-in-data-contributor
roleName: 'Cosmos DB SQL Data Contributor'
dataActions: [
'Microsoft.DocumentDB/databaseAccounts/readMetadata'
'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*'
'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*'
]
assignments: [{ principalId: userAssignedIdentity.outputs.principalId }]
}
]
// WAF aligned configuration for Monitoring
diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null
// WAF aligned configuration for Private Networking
networkRestrictions: {
networkAclBypass: 'None'
publicNetworkAccess: enablePrivateNetworking ? 'Disabled' : 'Enabled'
}
privateEndpoints: enablePrivateNetworking
? [
{
name: 'pep-${cosmosDbResourceName}'
customNetworkInterfaceName: 'nic-${cosmosDbResourceName}'
privateDnsZoneGroup: {
privateDnsZoneGroupConfigs: [
{ privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.cosmosDB]!.outputs.resourceId }
]
}
service: 'Sql'
subnetResourceId: network!.outputs.subnetPrivateEndpointsResourceId
}
]
: []
// WAF aligned configuration for Redundancy
zoneRedundant: enableRedundancy ? true : false
capabilitiesToAdd: enableRedundancy ? null : ['EnableServerless']
automaticFailover: enableRedundancy ? true : false
failoverLocations: enableRedundancy
? [
{
failoverPriority: 0
isZoneRedundant: true
locationName: solutionLocation
}
{
failoverPriority: 1
isZoneRedundant: true
locationName: cosmosDbHaLocation
}
]
: [
{
locationName: solutionLocation
failoverPriority: 0
isZoneRedundant: enableRedundancy
}
]
}
dependsOn: [keyvault, avmStorageAccount]
}
// ========== AVM WAF ========== //
// ========== Storage account module ========== //
var storageAccountName = 'st${solutionSuffix}'
module avmStorageAccount 'br/public:avm/res/storage/storage-account:0.20.0' = {
name: take('avm.res.storage.storage-account.${storageAccountName}', 64)
params: {
name: storageAccountName
location: solutionLocation
managedIdentities: { systemAssigned: true }
minimumTlsVersion: 'TLS1_2'
enableTelemetry: enableTelemetry
tags: tags
accessTier: 'Hot'
supportsHttpsTrafficOnly: true
roleAssignments: [
{
principalId: userAssignedIdentity.outputs.principalId
roleDefinitionIdOrName: 'Storage Blob Data Contributor'
principalType: 'ServicePrincipal'
}
]
// WAF aligned networking
networkAcls: {
bypass: 'AzureServices'
defaultAction: enablePrivateNetworking ? 'Deny' : 'Allow'
}
allowBlobPublicAccess: enablePrivateNetworking ? true : false
publicNetworkAccess: enablePrivateNetworking ? 'Disabled' : 'Enabled'
// Private endpoints for blob and queue
privateEndpoints: enablePrivateNetworking
? [
{
name: 'pep-blob-${solutionSuffix}'
privateDnsZoneGroup: {
privateDnsZoneGroupConfigs: [
{
name: 'storage-dns-zone-group-blob'
privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.storageBlob]!.outputs.resourceId
}
]
}
subnetResourceId: network!.outputs.subnetPrivateEndpointsResourceId
service: 'blob'
}
{
name: 'pep-queue-${solutionSuffix}'
privateDnsZoneGroup: {
privateDnsZoneGroupConfigs: [
{
name: 'storage-dns-zone-group-queue'
privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.storageQueue]!.outputs.resourceId
}
]
}
subnetResourceId: network!.outputs.subnetPrivateEndpointsResourceId
service: 'queue'
}
]
: []
blobServices: {
corsRules: []
deleteRetentionPolicyEnabled: false
containers: [
{
name: 'data'
publicAccess: 'None'
denyEncryptionScopeOverride: false
defaultEncryptionScope: '$account-encryption-key'
}
]
}
}
dependsOn: [keyvault]
}
// working version of saving storage account secrets in key vault using AVM module
module saveStorageAccountSecretsInKeyVault 'br/public:avm/res/key-vault/vault:0.12.1' = {
name: take('saveStorageAccountSecretsInKeyVault.${keyVaultName}', 64)
params: {
name: keyVaultName
enablePurgeProtection: enablePurgeProtection
enableVaultForDeployment: true
enableVaultForDiskEncryption: true
enableVaultForTemplateDeployment: true
enableRbacAuthorization: true
enableSoftDelete: true
softDeleteRetentionInDays: 7
secrets: [
{
name: 'ADLS-ACCOUNT-NAME'
value: storageAccountName
}
{
name: 'ADLS-ACCOUNT-CONTAINER'
value: 'data'
}
{
name: 'ADLS-ACCOUNT-KEY'
value: avmStorageAccount.outputs.primaryAccessKey
}
]
}
}
// ========== AVM WAF ========== //
// ========== SQL module ========== //
var sqlDbName = 'sqldb-${solutionSuffix}'
module sqlDBModule 'br/public:avm/res/sql/server:0.20.1' = {
name: take('avm.res.sql.server.${sqlDbName}', 64)
params: {
// Required parameters
name: 'sql-${solutionSuffix}'
// Non-required parameters
administrators: {
azureADOnlyAuthentication: true
login: userAssignedIdentity.outputs.name
principalType: 'Application'
sid: userAssignedIdentity.outputs.principalId
tenantId: subscription().tenantId
}
connectionPolicy: 'Redirect'
databases: [
{
availabilityZone: enableRedundancy ? 1 : -1
collation: 'SQL_Latin1_General_CP1_CI_AS'
diagnosticSettings: enableMonitoring
? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }]
: null
licenseType: 'LicenseIncluded'
maxSizeBytes: 34359738368
name: 'sqldb-${solutionSuffix}'
minCapacity: '1'
sku: {
name: 'GP_S_Gen5'
tier: 'GeneralPurpose'
family: 'Gen5'
capacity: 2
}
}
]
location: solutionLocation
managedIdentities: {
systemAssigned: true
userAssignedResourceIds: [
userAssignedIdentity.outputs.resourceId
]
}
primaryUserAssignedIdentityResourceId: userAssignedIdentity.outputs.resourceId
privateEndpoints: enablePrivateNetworking
? [
{
privateDnsZoneGroup: {
privateDnsZoneGroupConfigs: [
{
privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.sqlServer]!.outputs.resourceId
}
]
}
service: 'sqlServer'
subnetResourceId: network!.outputs.subnetPrivateEndpointsResourceId
tags: tags
}
]
: []
firewallRules: (!enablePrivateNetworking) ? [
{
endIpAddress: '255.255.255.255'
name: 'AllowSpecificRange'
startIpAddress: '0.0.0.0'
}
{
endIpAddress: '0.0.0.0'
name: 'AllowAllWindowsAzureIps'
startIpAddress: '0.0.0.0'
}
] : []
tags: tags
}
}
// ========== Frontend server farm ========== //
// WAF best practices for Web Application Services: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/app-service-web-apps
// PSRule for Web Server Farm: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#app-service
var webServerFarmResourceName = 'asp-${solutionSuffix}'
module webServerFarm 'br/public:avm/res/web/serverfarm:0.5.0' = {
name: take('avm.res.web.serverfarm.${webServerFarmResourceName}', 64)
params: {
name: webServerFarmResourceName
tags: tags
enableTelemetry: enableTelemetry
location: solutionLocation
reserved: true
kind: 'linux'
// WAF aligned configuration for Monitoring
diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null
// WAF aligned configuration for Scalability
skuName: enableScalability || enableRedundancy ? 'P1v3' : 'B3'
skuCapacity: enableScalability ? 3 : 1
// WAF aligned configuration for Redundancy
zoneRedundant: enableRedundancy ? true : false
}
}
// ========== Frontend web site ========== //
// WAF best practices for web app service: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/app-service-web-apps
// PSRule for Web Server Farm: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#app-service
//NOTE: AVM module adds 1 MB of overhead to the template. Keeping vanilla resource to save template size.
var webSiteResourceName = 'app-${solutionSuffix}'
module webSite 'modules/web-sites.bicep' = {
name: take('module.web-sites.${webSiteResourceName}', 64)
params: {
name: webSiteResourceName
tags: tags
location: solutionLocation
managedIdentities: { userAssignedResourceIds: [userAssignedIdentity!.outputs.resourceId] }
kind: 'app,linux,container'
serverFarmResourceId: webServerFarm.?outputs.resourceId
siteConfig: {
linuxFxVersion: 'DOCKER|${containerRegistryHostname}/${containerImageName}:${containerImageTag}'
minTlsVersion: '1.2'
}
configs: [
{
name: 'appsettings'
properties: {
APP_ENV: appEnvironment
APPINSIGHTS_INSTRUMENTATIONKEY: enableMonitoring ? applicationInsights!.outputs.instrumentationKey : ''
APPLICATIONINSIGHTS_CONNECTION_STRING: enableMonitoring ? applicationInsights!.outputs.connectionString : ''
AZURE_SEARCH_SERVICE: aiSearchName
AZURE_SEARCH_INDEX: azureSearchIndex
AZURE_SEARCH_USE_SEMANTIC_SEARCH: azureSearchUseSemanticSearch
AZURE_SEARCH_SEMANTIC_SEARCH_CONFIG: azureSearchSemanticSearchConfig
AZURE_SEARCH_TOP_K: azureSearchTopK
AZURE_SEARCH_ENABLE_IN_DOMAIN: azureSearchEnableInDomain
AZURE_SEARCH_CONTENT_COLUMNS: azureSearchContentColumns
AZURE_SEARCH_FILENAME_COLUMN: azureSearchFilenameColumn