-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
Copy pathmain.bicep
1235 lines (1120 loc) · 46.2 KB
/
main.bicep
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
targetScope = 'subscription'
@minLength(1)
@maxLength(64)
@description('Name of the the environment which is used to generate a short unique hash used in all resources.')
param environmentName string
@minLength(1)
@description('Primary location for all resources')
param location string
param appServicePlanName string = '' // Set in main.parameters.json
param backendServiceName string = '' // Set in main.parameters.json
param resourceGroupName string = '' // Set in main.parameters.json
param applicationInsightsDashboardName string = '' // Set in main.parameters.json
param applicationInsightsName string = '' // Set in main.parameters.json
param logAnalyticsName string = '' // Set in main.parameters.json
param searchServiceName string = '' // Set in main.parameters.json
param searchServiceResourceGroupName string = '' // Set in main.parameters.json
param searchServiceLocation string = '' // Set in main.parameters.json
// The free tier does not support managed identity (required) or semantic search (optional)
@allowed(['free', 'basic', 'standard', 'standard2', 'standard3', 'storage_optimized_l1', 'storage_optimized_l2'])
param searchServiceSkuName string // Set in main.parameters.json
param searchIndexName string // Set in main.parameters.json
param searchQueryLanguage string // Set in main.parameters.json
param searchQuerySpeller string // Set in main.parameters.json
param searchServiceSemanticRankerLevel string // Set in main.parameters.json
var actualSearchServiceSemanticRankerLevel = (searchServiceSkuName == 'free')
? 'disabled'
: searchServiceSemanticRankerLevel
param storageAccountName string = '' // Set in main.parameters.json
param storageResourceGroupName string = '' // Set in main.parameters.json
param storageResourceGroupLocation string = location
param storageContainerName string = 'content'
param storageSkuName string // Set in main.parameters.json
param userStorageAccountName string = ''
param userStorageContainerName string = 'user-content'
param tokenStorageContainerName string = 'tokens'
param appServiceSkuName string // Set in main.parameters.json
@allowed(['azure', 'openai', 'azure_custom'])
param openAiHost string // Set in main.parameters.json
param isAzureOpenAiHost bool = startsWith(openAiHost, 'azure')
param deployAzureOpenAi bool = openAiHost == 'azure'
param azureOpenAiCustomUrl string = ''
param azureOpenAiApiVersion string = ''
@secure()
param azureOpenAiApiKey string = ''
param azureOpenAiDisableKeys bool = true
param openAiServiceName string = ''
param openAiResourceGroupName string = ''
param speechServiceResourceGroupName string = ''
param speechServiceLocation string = ''
param speechServiceName string = ''
param speechServiceSkuName string // Set in main.parameters.json
param speechServiceVoice string = ''
param useGPT4V bool = false
@allowed(['free', 'provisioned', 'serverless'])
param cosmosDbSkuName string // Set in main.parameters.json
param cosmodDbResourceGroupName string = ''
param cosmosDbLocation string = ''
param cosmosDbAccountName string = ''
param cosmosDbThroughput int = 400
param chatHistoryDatabaseName string = 'chat-database'
param chatHistoryContainerName string = 'chat-history-v2'
param chatHistoryVersion string = 'cosmosdb-v2'
// https://learn.microsoft.com/azure/ai-services/openai/concepts/models?tabs=python-secure%2Cstandard%2Cstandard-chat-completions#standard-deployment-model-availability
@description('Location for the OpenAI resource group')
@allowed([
'canadaeast'
'eastus'
'eastus2'
'francecentral'
'switzerlandnorth'
'uksouth'
'japaneast'
'northcentralus'
'australiaeast'
'swedencentral'
])
@metadata({
azd: {
type: 'location'
}
})
param openAiLocation string
param openAiSkuName string = 'S0'
@secure()
param openAiApiKey string = ''
param openAiApiOrganization string = ''
param documentIntelligenceServiceName string = '' // Set in main.parameters.json
param documentIntelligenceResourceGroupName string = '' // Set in main.parameters.json
// Limited regions for new version:
// https://learn.microsoft.com/azure/ai-services/document-intelligence/concept-layout
@description('Location for the Document Intelligence resource group')
@allowed(['eastus', 'westus2', 'westeurope'])
@metadata({
azd: {
type: 'location'
}
})
param documentIntelligenceResourceGroupLocation string
param documentIntelligenceSkuName string // Set in main.parameters.json
param computerVisionServiceName string = '' // Set in main.parameters.json
param computerVisionResourceGroupName string = '' // Set in main.parameters.json
param computerVisionResourceGroupLocation string = '' // Set in main.parameters.json
param computerVisionSkuName string // Set in main.parameters.json
param contentUnderstandingServiceName string = '' // Set in main.parameters.json
param contentUnderstandingResourceGroupName string = '' // Set in main.parameters.json
param chatGptModelName string = ''
param chatGptDeploymentName string = ''
param chatGptDeploymentVersion string = ''
param chatGptDeploymentSkuName string = ''
param chatGptDeploymentCapacity int = 0
var chatGpt = {
modelName: !empty(chatGptModelName)
? chatGptModelName
: startsWith(openAiHost, 'azure') ? 'gpt-35-turbo' : 'gpt-3.5-turbo'
deploymentName: !empty(chatGptDeploymentName) ? chatGptDeploymentName : 'chat'
deploymentVersion: !empty(chatGptDeploymentVersion) ? chatGptDeploymentVersion : '0125'
deploymentSkuName: !empty(chatGptDeploymentSkuName) ? chatGptDeploymentSkuName : 'Standard'
deploymentCapacity: chatGptDeploymentCapacity != 0 ? chatGptDeploymentCapacity : 30
}
param embeddingModelName string = ''
param embeddingDeploymentName string = ''
param embeddingDeploymentVersion string = ''
param embeddingDeploymentSkuName string = ''
param embeddingDeploymentCapacity int = 0
param embeddingDimensions int = 0
var embedding = {
modelName: !empty(embeddingModelName) ? embeddingModelName : 'text-embedding-ada-002'
deploymentName: !empty(embeddingDeploymentName) ? embeddingDeploymentName : 'embedding'
deploymentVersion: !empty(embeddingDeploymentVersion) ? embeddingDeploymentVersion : '2'
deploymentSkuName: !empty(embeddingDeploymentSkuName) ? embeddingDeploymentSkuName : 'Standard'
deploymentCapacity: embeddingDeploymentCapacity != 0 ? embeddingDeploymentCapacity : 30
dimensions: embeddingDimensions != 0 ? embeddingDimensions : 1536
}
param gpt4vModelName string = ''
param gpt4vDeploymentName string = ''
param gpt4vModelVersion string = ''
param gpt4vDeploymentSkuName string = ''
param gpt4vDeploymentCapacity int = 0
var gpt4v = {
modelName: !empty(gpt4vModelName) ? gpt4vModelName : 'gpt-4o'
deploymentName: !empty(gpt4vDeploymentName) ? gpt4vDeploymentName : 'gpt-4o'
deploymentVersion: !empty(gpt4vModelVersion) ? gpt4vModelVersion : '2024-08-06'
deploymentSkuName: !empty(gpt4vDeploymentSkuName) ? gpt4vDeploymentSkuName : 'Standard'
deploymentCapacity: gpt4vDeploymentCapacity != 0 ? gpt4vDeploymentCapacity : 10
}
param tenantId string = tenant().tenantId
param authTenantId string = ''
// Used for the optional login and document level access control system
param useAuthentication bool = false
param enforceAccessControl bool = false
// Force using MSAL app authentication instead of built-in App Service authentication
// https://learn.microsoft.com/azure/app-service/overview-authentication-authorization
param disableAppServicesAuthentication bool = false
param enableGlobalDocuments bool = false
param enableUnauthenticatedAccess bool = false
param serverAppId string = ''
@secure()
param serverAppSecret string = ''
param clientAppId string = ''
@secure()
param clientAppSecret string = ''
// Used for optional CORS support for alternate frontends
param allowedOrigin string = '' // should start with https://, shouldn't end with a /
@allowed(['None', 'AzureServices'])
@description('If allowedIp is set, whether azure services are allowed to bypass the storage and AI services firewall.')
param bypass string = 'AzureServices'
@description('Public network access value for all deployed resources')
@allowed(['Enabled', 'Disabled'])
param publicNetworkAccess string = 'Enabled'
@description('Add a private endpoints for network connectivity')
param usePrivateEndpoint bool = false
@description('Id of the user or app to assign application roles')
param principalId string = ''
@description('Use Application Insights for monitoring and performance tracing')
param useApplicationInsights bool = false
@description('Enable language picker')
param enableLanguagePicker bool = false
@description('Use speech recognition feature in browser')
param useSpeechInputBrowser bool = false
@description('Use speech synthesis in browser')
param useSpeechOutputBrowser bool = false
@description('Use Azure speech service for reading out text')
param useSpeechOutputAzure bool = false
@description('Use chat history feature in browser')
param useChatHistoryBrowser bool = false
@description('Use chat history feature in CosmosDB')
param useChatHistoryCosmos bool = false
@description('Show options to use vector embeddings for searching in the app UI')
param useVectors bool = false
@description('Use Built-in integrated Vectorization feature of AI Search to vectorize and ingest documents')
param useIntegratedVectorization bool = false
@description('Use media description feature with Azure Content Understanding during ingestion')
param useMediaDescriberAzureCU bool = true
@description('Enable user document upload feature')
param useUserUpload bool = false
param useLocalPdfParser bool = false
param useLocalHtmlParser bool = false
var abbrs = loadJsonContent('abbreviations.json')
var resourceToken = toLower(uniqueString(subscription().id, environmentName, location))
var tags = { 'azd-env-name': environmentName }
var tenantIdForAuth = !empty(authTenantId) ? authTenantId : tenantId
var authenticationIssuerUri = '${environment().authentication.loginEndpoint}${tenantIdForAuth}/v2.0'
@description('Whether the deployment is running on GitHub Actions')
param runningOnGh string = ''
@description('Whether the deployment is running on Azure DevOps Pipeline')
param runningOnAdo string = ''
@description('Used by azd for containerapps deployment')
param webAppExists bool
@allowed(['Consumption', 'D4', 'D8', 'D16', 'D32', 'E4', 'E8', 'E16', 'E32', 'NC24-A100', 'NC48-A100', 'NC96-A100'])
param azureContainerAppsWorkloadProfile string
@allowed(['appservice', 'containerapps'])
param deploymentTarget string = 'appservice'
param acaIdentityName string = deploymentTarget == 'containerapps' ? '${environmentName}-aca-identity' : ''
param acaManagedEnvironmentName string = deploymentTarget == 'containerapps' ? '${environmentName}-aca-env' : ''
param containerRegistryName string = deploymentTarget == 'containerapps'
? '${replace(toLower(environmentName), '-', '')}acr'
: ''
// Configure CORS for allowing different web apps to use the backend
// For more information please see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
var msftAllowedOrigins = [ 'https://portal.azure.com', 'https://ms.portal.azure.com' ]
var loginEndpoint = environment().authentication.loginEndpoint
var loginEndpointFixed = lastIndexOf(loginEndpoint, '/') == length(loginEndpoint) - 1 ? substring(loginEndpoint, 0, length(loginEndpoint) - 1) : loginEndpoint
var allMsftAllowedOrigins = !(empty(clientAppId)) ? union(msftAllowedOrigins, [ loginEndpointFixed ]) : msftAllowedOrigins
// Combine custom origins with Microsoft origins, remove any empty origin strings and remove any duplicate origins
var allowedOrigins = reduce(filter(union(split(allowedOrigin, ';'), allMsftAllowedOrigins), o => length(trim(o)) > 0), [], (cur, next) => union(cur, [next]))
// Organize resources in a resource group
resource resourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' = {
name: !empty(resourceGroupName) ? resourceGroupName : '${abbrs.resourcesResourceGroups}${environmentName}'
location: location
tags: tags
}
resource openAiResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(openAiResourceGroupName)) {
name: !empty(openAiResourceGroupName) ? openAiResourceGroupName : resourceGroup.name
}
resource documentIntelligenceResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(documentIntelligenceResourceGroupName)) {
name: !empty(documentIntelligenceResourceGroupName) ? documentIntelligenceResourceGroupName : resourceGroup.name
}
resource computerVisionResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(computerVisionResourceGroupName)) {
name: !empty(computerVisionResourceGroupName) ? computerVisionResourceGroupName : resourceGroup.name
}
resource contentUnderstandingResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(contentUnderstandingResourceGroupName)) {
name: !empty(contentUnderstandingResourceGroupName) ? contentUnderstandingResourceGroupName : resourceGroup.name
}
resource searchServiceResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(searchServiceResourceGroupName)) {
name: !empty(searchServiceResourceGroupName) ? searchServiceResourceGroupName : resourceGroup.name
}
resource storageResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(storageResourceGroupName)) {
name: !empty(storageResourceGroupName) ? storageResourceGroupName : resourceGroup.name
}
resource speechResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(speechServiceResourceGroupName)) {
name: !empty(speechServiceResourceGroupName) ? speechServiceResourceGroupName : resourceGroup.name
}
resource cosmosDbResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = if (!empty(cosmodDbResourceGroupName)) {
name: !empty(cosmodDbResourceGroupName) ? cosmodDbResourceGroupName : resourceGroup.name
}
// Monitor application with Azure Monitor
module monitoring 'core/monitor/monitoring.bicep' = if (useApplicationInsights) {
name: 'monitoring'
scope: resourceGroup
params: {
location: location
tags: tags
applicationInsightsName: !empty(applicationInsightsName)
? applicationInsightsName
: '${abbrs.insightsComponents}${resourceToken}'
logAnalyticsName: !empty(logAnalyticsName)
? logAnalyticsName
: '${abbrs.operationalInsightsWorkspaces}${resourceToken}'
publicNetworkAccess: publicNetworkAccess
}
}
module applicationInsightsDashboard 'backend-dashboard.bicep' = if (useApplicationInsights) {
name: 'application-insights-dashboard'
scope: resourceGroup
params: {
name: !empty(applicationInsightsDashboardName)
? applicationInsightsDashboardName
: '${abbrs.portalDashboards}${resourceToken}'
location: location
applicationInsightsName: useApplicationInsights ? monitoring.outputs.applicationInsightsName : ''
}
}
// Create an App Service Plan to group applications under the same payment plan and SKU
module appServicePlan 'core/host/appserviceplan.bicep' = if (deploymentTarget == 'appservice') {
name: 'appserviceplan'
scope: resourceGroup
params: {
name: !empty(appServicePlanName) ? appServicePlanName : '${abbrs.webServerFarms}${resourceToken}'
location: location
tags: tags
sku: {
name: appServiceSkuName
capacity: 1
}
kind: 'linux'
}
}
var appEnvVariables = {
AZURE_STORAGE_ACCOUNT: storage.outputs.name
AZURE_STORAGE_CONTAINER: storageContainerName
AZURE_SEARCH_INDEX: searchIndexName
AZURE_SEARCH_SERVICE: searchService.outputs.name
AZURE_SEARCH_SEMANTIC_RANKER: actualSearchServiceSemanticRankerLevel
AZURE_VISION_ENDPOINT: useGPT4V ? computerVision.outputs.endpoint : ''
AZURE_SEARCH_QUERY_LANGUAGE: searchQueryLanguage
AZURE_SEARCH_QUERY_SPELLER: searchQuerySpeller
APPLICATIONINSIGHTS_CONNECTION_STRING: useApplicationInsights
? monitoring.outputs.applicationInsightsConnectionString
: ''
AZURE_SPEECH_SERVICE_ID: useSpeechOutputAzure ? speech.outputs.resourceId : ''
AZURE_SPEECH_SERVICE_LOCATION: useSpeechOutputAzure ? speech.outputs.location : ''
AZURE_SPEECH_SERVICE_VOICE: useSpeechOutputAzure ? speechServiceVoice : ''
ENABLE_LANGUAGE_PICKER: enableLanguagePicker
USE_SPEECH_INPUT_BROWSER: useSpeechInputBrowser
USE_SPEECH_OUTPUT_BROWSER: useSpeechOutputBrowser
USE_SPEECH_OUTPUT_AZURE: useSpeechOutputAzure
// Chat history settings
USE_CHAT_HISTORY_BROWSER: useChatHistoryBrowser
USE_CHAT_HISTORY_COSMOS: useChatHistoryCosmos
AZURE_COSMOSDB_ACCOUNT: (useAuthentication && useChatHistoryCosmos) ? cosmosDb.outputs.name : ''
AZURE_CHAT_HISTORY_DATABASE: chatHistoryDatabaseName
AZURE_CHAT_HISTORY_CONTAINER: chatHistoryContainerName
AZURE_CHAT_HISTORY_VERSION: chatHistoryVersion
// Shared by all OpenAI deployments
OPENAI_HOST: openAiHost
AZURE_OPENAI_EMB_MODEL_NAME: embedding.modelName
AZURE_OPENAI_EMB_DIMENSIONS: embedding.dimensions
AZURE_OPENAI_CHATGPT_MODEL: chatGpt.modelName
AZURE_OPENAI_GPT4V_MODEL: gpt4v.modelName
// Specific to Azure OpenAI
AZURE_OPENAI_SERVICE: isAzureOpenAiHost && deployAzureOpenAi ? openAi.outputs.name : ''
AZURE_OPENAI_CHATGPT_DEPLOYMENT: chatGpt.deploymentName
AZURE_OPENAI_EMB_DEPLOYMENT: embedding.deploymentName
AZURE_OPENAI_GPT4V_DEPLOYMENT: useGPT4V ? gpt4v.deploymentName : ''
AZURE_OPENAI_API_VERSION: azureOpenAiApiVersion
AZURE_OPENAI_API_KEY_OVERRIDE: azureOpenAiApiKey
AZURE_OPENAI_CUSTOM_URL: azureOpenAiCustomUrl
// Used only with non-Azure OpenAI deployments
OPENAI_API_KEY: openAiApiKey
OPENAI_ORGANIZATION: openAiApiOrganization
// Optional login and document level access control system
AZURE_USE_AUTHENTICATION: useAuthentication
AZURE_ENFORCE_ACCESS_CONTROL: enforceAccessControl
AZURE_ENABLE_GLOBAL_DOCUMENT_ACCESS: enableGlobalDocuments
AZURE_ENABLE_UNAUTHENTICATED_ACCESS: enableUnauthenticatedAccess
AZURE_SERVER_APP_ID: serverAppId
AZURE_CLIENT_APP_ID: clientAppId
AZURE_TENANT_ID: tenantId
AZURE_AUTH_TENANT_ID: tenantIdForAuth
AZURE_AUTHENTICATION_ISSUER_URI: authenticationIssuerUri
// CORS support, for frontends on other hosts
ALLOWED_ORIGIN: join(allowedOrigins, ';')
USE_VECTORS: useVectors
USE_GPT4V: useGPT4V
USE_USER_UPLOAD: useUserUpload
AZURE_USERSTORAGE_ACCOUNT: useUserUpload ? userStorage.outputs.name : ''
AZURE_USERSTORAGE_CONTAINER: useUserUpload ? userStorageContainerName : ''
AZURE_DOCUMENTINTELLIGENCE_SERVICE: documentIntelligence.outputs.name
USE_LOCAL_PDF_PARSER: useLocalPdfParser
USE_LOCAL_HTML_PARSER: useLocalHtmlParser
USE_MEDIA_DESCRIBER_AZURE_CU: useMediaDescriberAzureCU
AZURE_CONTENTUNDERSTANDING_ENDPOINT: useMediaDescriberAzureCU ? contentUnderstanding.outputs.endpoint : ''
RUNNING_IN_PRODUCTION: 'true'
}
// App Service for the web application (Python Quart app with JS frontend)
module backend 'core/host/appservice.bicep' = if (deploymentTarget == 'appservice') {
name: 'web'
scope: resourceGroup
params: {
name: !empty(backendServiceName) ? backendServiceName : '${abbrs.webSitesAppService}backend-${resourceToken}'
location: location
tags: union(tags, { 'azd-service-name': 'backend' })
// Need to check deploymentTarget again due to https://github.com/Azure/bicep/issues/3990
appServicePlanId: deploymentTarget == 'appservice' ? appServicePlan.outputs.id : ''
runtimeName: 'python'
runtimeVersion: '3.11'
appCommandLine: 'python3 -m gunicorn main:app'
scmDoBuildDuringDeployment: true
managedIdentity: true
virtualNetworkSubnetId: isolation.outputs.appSubnetId
publicNetworkAccess: publicNetworkAccess
allowedOrigins: allowedOrigins
clientAppId: clientAppId
serverAppId: serverAppId
enableUnauthenticatedAccess: enableUnauthenticatedAccess
disableAppServicesAuthentication: disableAppServicesAuthentication
clientSecretSettingName: !empty(clientAppSecret) ? 'AZURE_CLIENT_APP_SECRET' : ''
authenticationIssuerUri: authenticationIssuerUri
use32BitWorkerProcess: appServiceSkuName == 'F1'
alwaysOn: appServiceSkuName != 'F1'
appSettings: union(appEnvVariables, {
AZURE_SERVER_APP_SECRET: serverAppSecret
AZURE_CLIENT_APP_SECRET: clientAppSecret
})
}
}
// Azure container apps resources (Only deployed if deploymentTarget is 'containerapps')
// User-assigned identity for pulling images from ACR
module acaIdentity 'core/security/aca-identity.bicep' = if (deploymentTarget == 'containerapps') {
name: 'aca-identity'
scope: resourceGroup
params: {
identityName: acaIdentityName
location: location
}
}
module containerApps 'core/host/container-apps.bicep' = if (deploymentTarget == 'containerapps') {
name: 'container-apps'
scope: resourceGroup
params: {
name: 'app'
tags: tags
location: location
workloadProfile: azureContainerAppsWorkloadProfile
containerAppsEnvironmentName: acaManagedEnvironmentName
containerRegistryName: '${containerRegistryName}${resourceToken}'
logAnalyticsWorkspaceResourceId: useApplicationInsights ? monitoring.outputs.logAnalyticsWorkspaceId : ''
}
}
// Container Apps for the web application (Python Quart app with JS frontend)
module acaBackend 'core/host/container-app-upsert.bicep' = if (deploymentTarget == 'containerapps') {
name: 'aca-web'
scope: resourceGroup
dependsOn: [
containerApps
acaIdentity
]
params: {
name: !empty(backendServiceName) ? backendServiceName : '${abbrs.webSitesContainerApps}backend-${resourceToken}'
location: location
identityName: (deploymentTarget == 'containerapps') ? acaIdentityName : ''
exists: webAppExists
workloadProfile: azureContainerAppsWorkloadProfile
containerRegistryName: (deploymentTarget == 'containerapps') ? containerApps.outputs.registryName : ''
containerAppsEnvironmentName: (deploymentTarget == 'containerapps') ? containerApps.outputs.environmentName : ''
identityType: 'UserAssigned'
tags: union(tags, { 'azd-service-name': 'backend' })
targetPort: 8000
containerCpuCoreCount: '1.0'
containerMemory: '2Gi'
allowedOrigins: allowedOrigins
env: union(appEnvVariables, {
// For using managed identity to access Azure resources. See https://github.com/microsoft/azure-container-apps/issues/442
AZURE_CLIENT_ID: (deploymentTarget == 'containerapps') ? acaIdentity.outputs.clientId : ''
})
secrets: useAuthentication ? {
azureclientappsecret: clientAppSecret
azureserverappsecret: serverAppSecret
} : {}
envSecrets: useAuthentication ? [
{
name: 'AZURE_CLIENT_APP_SECRET'
secretRef: 'azureclientappsecret'
}
{
name: 'AZURE_SERVER_APP_SECRET'
secretRef: 'azureserverappsecret'
}
] : []
}
}
module acaAuth 'core/host/container-apps-auth.bicep' = if (deploymentTarget == 'containerapps' && !empty(clientAppId)) {
name: 'aca-auth'
scope: resourceGroup
params: {
name: acaBackend.outputs.name
clientAppId: clientAppId
serverAppId: serverAppId
clientSecretSettingName: !empty(clientAppSecret) ? 'azureclientappsecret' : ''
authenticationIssuerUri: authenticationIssuerUri
enableUnauthenticatedAccess: enableUnauthenticatedAccess
blobContainerUri: 'https://${storageAccountName}.blob.${environment().suffixes.storage}/${tokenStorageContainerName}'
appIdentityResourceId: (deploymentTarget == 'appservice') ? '' : acaBackend.outputs.identityResourceId
}
}
var defaultOpenAiDeployments = [
{
name: chatGpt.deploymentName
model: {
format: 'OpenAI'
name: chatGpt.modelName
version: chatGpt.deploymentVersion
}
sku: {
name: chatGpt.deploymentSkuName
capacity: chatGpt.deploymentCapacity
}
}
{
name: embedding.deploymentName
model: {
format: 'OpenAI'
name: embedding.modelName
version: embedding.deploymentVersion
}
sku: {
name: embedding.deploymentSkuName
capacity: embedding.deploymentCapacity
}
}
]
var openAiDeployments = concat(
defaultOpenAiDeployments,
useGPT4V
? [
{
name: gpt4v.deploymentName
model: {
format: 'OpenAI'
name: gpt4v.modelName
version: gpt4v.deploymentVersion
}
sku: {
name: gpt4v.deploymentSkuName
capacity: gpt4v.deploymentCapacity
}
}
]
: []
)
module openAi 'br/public:avm/res/cognitive-services/account:0.7.2' = if (isAzureOpenAiHost && deployAzureOpenAi) {
name: 'openai'
scope: openAiResourceGroup
params: {
name: !empty(openAiServiceName) ? openAiServiceName : '${abbrs.cognitiveServicesAccounts}${resourceToken}'
location: openAiLocation
tags: tags
kind: 'OpenAI'
customSubDomainName: !empty(openAiServiceName)
? openAiServiceName
: '${abbrs.cognitiveServicesAccounts}${resourceToken}'
publicNetworkAccess: publicNetworkAccess
networkAcls: {
defaultAction: 'Allow'
bypass: bypass
}
sku: openAiSkuName
deployments: openAiDeployments
disableLocalAuth: azureOpenAiDisableKeys
}
}
// Formerly known as Form Recognizer
// Does not support bypass
module documentIntelligence 'br/public:avm/res/cognitive-services/account:0.7.2' = {
name: 'documentintelligence'
scope: documentIntelligenceResourceGroup
params: {
name: !empty(documentIntelligenceServiceName)
? documentIntelligenceServiceName
: '${abbrs.cognitiveServicesDocumentIntelligence}${resourceToken}'
kind: 'FormRecognizer'
customSubDomainName: !empty(documentIntelligenceServiceName)
? documentIntelligenceServiceName
: '${abbrs.cognitiveServicesDocumentIntelligence}${resourceToken}'
publicNetworkAccess: publicNetworkAccess
networkAcls: {
defaultAction: 'Allow'
}
location: documentIntelligenceResourceGroupLocation
disableLocalAuth: true
tags: tags
sku: documentIntelligenceSkuName
}
}
module computerVision 'br/public:avm/res/cognitive-services/account:0.7.2' = if (useGPT4V) {
name: 'computerVision'
scope: computerVisionResourceGroup
params: {
name: !empty(computerVisionServiceName)
? computerVisionServiceName
: '${abbrs.cognitiveServicesComputerVision}${resourceToken}'
kind: 'ComputerVision'
networkAcls: {
defaultAction: 'Allow'
}
customSubDomainName: !empty(computerVisionServiceName)
? computerVisionServiceName
: '${abbrs.cognitiveServicesComputerVision}${resourceToken}'
location: computerVisionResourceGroupLocation
tags: tags
sku: computerVisionSkuName
}
}
module contentUnderstanding 'br/public:avm/res/cognitive-services/account:0.7.2' = if (useMediaDescriberAzureCU) {
name: 'content-understanding'
scope: contentUnderstandingResourceGroup
params: {
name: !empty(contentUnderstandingServiceName)
? contentUnderstandingServiceName
: '${abbrs.cognitiveServicesContentUnderstanding}${resourceToken}'
kind: 'AIServices'
networkAcls: {
defaultAction: 'Allow'
}
customSubDomainName: !empty(contentUnderstandingServiceName)
? contentUnderstandingServiceName
: '${abbrs.cognitiveServicesContentUnderstanding}${resourceToken}'
// Hard-coding to westus for now, due to limited availability and no overlap with Document Intelligence
location: 'westus'
tags: tags
sku: 'S0'
}
}
module speech 'br/public:avm/res/cognitive-services/account:0.7.2' = if (useSpeechOutputAzure) {
name: 'speech-service'
scope: speechResourceGroup
params: {
name: !empty(speechServiceName) ? speechServiceName : '${abbrs.cognitiveServicesSpeech}${resourceToken}'
kind: 'SpeechServices'
networkAcls: {
defaultAction: 'Allow'
}
customSubDomainName: !empty(speechServiceName)
? speechServiceName
: '${abbrs.cognitiveServicesSpeech}${resourceToken}'
location: !empty(speechServiceLocation) ? speechServiceLocation : location
tags: tags
sku: speechServiceSkuName
}
}
module searchService 'core/search/search-services.bicep' = {
name: 'search-service'
scope: searchServiceResourceGroup
params: {
name: !empty(searchServiceName) ? searchServiceName : 'gptkb-${resourceToken}'
location: !empty(searchServiceLocation) ? searchServiceLocation : location
tags: tags
disableLocalAuth: true
sku: {
name: searchServiceSkuName
}
semanticSearch: actualSearchServiceSemanticRankerLevel
publicNetworkAccess: publicNetworkAccess == 'Enabled'
? 'enabled'
: (publicNetworkAccess == 'Disabled' ? 'disabled' : null)
sharedPrivateLinkStorageAccounts: usePrivateEndpoint ? [storage.outputs.id] : []
}
}
module searchDiagnostics 'core/search/search-diagnostics.bicep' = if (useApplicationInsights) {
name: 'search-diagnostics'
scope: searchServiceResourceGroup
params: {
searchServiceName: searchService.outputs.name
workspaceId: useApplicationInsights ? monitoring.outputs.logAnalyticsWorkspaceId : ''
}
}
module storage 'core/storage/storage-account.bicep' = {
name: 'storage'
scope: storageResourceGroup
params: {
name: !empty(storageAccountName) ? storageAccountName : '${abbrs.storageStorageAccounts}${resourceToken}'
location: storageResourceGroupLocation
tags: tags
publicNetworkAccess: publicNetworkAccess
bypass: bypass
allowBlobPublicAccess: false
allowSharedKeyAccess: false
sku: {
name: storageSkuName
}
deleteRetentionPolicy: {
enabled: true
days: 2
}
containers: [
{
name: storageContainerName
publicAccess: 'None'
}
{
name: tokenStorageContainerName
publicAccess: 'None'
}
]
}
}
module userStorage 'core/storage/storage-account.bicep' = if (useUserUpload) {
name: 'user-storage'
scope: storageResourceGroup
params: {
name: !empty(userStorageAccountName)
? userStorageAccountName
: 'user${abbrs.storageStorageAccounts}${resourceToken}'
location: storageResourceGroupLocation
tags: tags
publicNetworkAccess: publicNetworkAccess
bypass: bypass
allowBlobPublicAccess: false
allowSharedKeyAccess: false
isHnsEnabled: true
sku: {
name: storageSkuName
}
containers: [
{
name: userStorageContainerName
publicAccess: 'None'
}
]
}
}
module cosmosDb 'br/public:avm/res/document-db/database-account:0.6.1' = if (useAuthentication && useChatHistoryCosmos) {
name: 'cosmosdb'
scope: cosmosDbResourceGroup
params: {
name: !empty(cosmosDbAccountName) ? cosmosDbAccountName : '${abbrs.documentDBDatabaseAccounts}${resourceToken}'
location: !empty(cosmosDbLocation) ? cosmosDbLocation : location
locations: [
{
locationName: !empty(cosmosDbLocation) ? cosmosDbLocation : location
failoverPriority: 0
isZoneRedundant: false
}
]
enableFreeTier: cosmosDbSkuName == 'free'
capabilitiesToAdd: cosmosDbSkuName == 'serverless' ? ['EnableServerless'] : []
networkRestrictions: {
ipRules: []
networkAclBypass: bypass
publicNetworkAccess: publicNetworkAccess
virtualNetworkRules: []
}
sqlDatabases: [
{
name: chatHistoryDatabaseName
throughput: (cosmosDbSkuName == 'serverless') ? null : cosmosDbThroughput
containers: [
{
name: chatHistoryContainerName
kind: 'MultiHash'
paths: [
'/entra_oid'
'/session_id'
]
indexingPolicy: {
indexingMode: 'consistent'
automatic: true
includedPaths: [
{
path: '/entra_oid/?'
}
{
path: '/session_id/?'
}
{
path: '/timestamp/?'
}
{
path: '/type/?'
}
]
excludedPaths: [
{
path: '/*'
}
]
}
}
]
}
]
}
}
// USER ROLES
var principalType = empty(runningOnGh) && empty(runningOnAdo) ? 'User' : 'ServicePrincipal'
module openAiRoleUser 'core/security/role.bicep' = if (isAzureOpenAiHost && deployAzureOpenAi) {
scope: openAiResourceGroup
name: 'openai-role-user'
params: {
principalId: principalId
roleDefinitionId: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd'
principalType: principalType
}
}
// For both document intelligence and computer vision
module cognitiveServicesRoleUser 'core/security/role.bicep' = {
scope: resourceGroup
name: 'cognitiveservices-role-user'
params: {
principalId: principalId
roleDefinitionId: 'a97b65f3-24c7-4388-baec-2e87135dc908'
principalType: principalType
}
}
module speechRoleUser 'core/security/role.bicep' = {
scope: speechResourceGroup
name: 'speech-role-user'
params: {
principalId: principalId
roleDefinitionId: 'f2dc8367-1007-4938-bd23-fe263f013447'
principalType: principalType
}
}
module storageRoleUser 'core/security/role.bicep' = {
scope: storageResourceGroup
name: 'storage-role-user'
params: {
principalId: principalId
roleDefinitionId: '2a2b9908-6ea1-4ae2-8e65-a410df84e7d1'
principalType: principalType
}
}
module storageContribRoleUser 'core/security/role.bicep' = {
scope: storageResourceGroup
name: 'storage-contrib-role-user'
params: {
principalId: principalId
roleDefinitionId: 'ba92f5b4-2d11-453d-a403-e96b0029c9fe'
principalType: principalType
}
}
module storageOwnerRoleUser 'core/security/role.bicep' = if (useUserUpload) {
scope: storageResourceGroup
name: 'storage-owner-role-user'
params: {
principalId: principalId
roleDefinitionId: 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b'
principalType: principalType
}
}
module searchRoleUser 'core/security/role.bicep' = {
scope: searchServiceResourceGroup
name: 'search-role-user'
params: {
principalId: principalId
roleDefinitionId: '1407120a-92aa-4202-b7e9-c0e197c71c8f'
principalType: principalType
}
}
module searchContribRoleUser 'core/security/role.bicep' = {
scope: searchServiceResourceGroup
name: 'search-contrib-role-user'
params: {
principalId: principalId
roleDefinitionId: '8ebe5a00-799e-43f5-93ac-243d3dce84a7'
principalType: principalType
}
}
module searchSvcContribRoleUser 'core/security/role.bicep' = {
scope: searchServiceResourceGroup
name: 'search-svccontrib-role-user'
params: {
principalId: principalId
roleDefinitionId: '7ca78c08-252a-4471-8644-bb5ff32d4ba0'
principalType: principalType
}
}
module cosmosDbAccountContribRoleUser 'core/security/role.bicep' = if (useAuthentication && useChatHistoryCosmos) {
scope: cosmosDbResourceGroup
name: 'cosmosdb-account-contrib-role-user'
params: {
principalId: principalId
roleDefinitionId: '5bd9cd88-fe45-4216-938b-f97437e15450'
principalType: principalType
}
}
// RBAC for Cosmos DB
// https://learn.microsoft.com/azure/cosmos-db/nosql/security/how-to-grant-data-plane-role-based-access
module cosmosDbDataContribRoleUser 'core/security/documentdb-sql-role.bicep' = if (useAuthentication && useChatHistoryCosmos) {
scope: cosmosDbResourceGroup
name: 'cosmosdb-data-contrib-role-user'
params: {
databaseAccountName: (useAuthentication && useChatHistoryCosmos) ? cosmosDb.outputs.name : ''
principalId: principalId
// Cosmos DB Built-in Data Contributor role
roleDefinitionId: (useAuthentication && useChatHistoryCosmos)
? '/${subscription().id}/resourceGroups/${cosmosDb.outputs.resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/${cosmosDb.outputs.name}/sqlRoleDefinitions/00000000-0000-0000-0000-000000000002'
: ''
}
}
// SYSTEM IDENTITIES
module openAiRoleBackend 'core/security/role.bicep' = if (isAzureOpenAiHost && deployAzureOpenAi) {
scope: openAiResourceGroup
name: 'openai-role-backend'
params: {
principalId: (deploymentTarget == 'appservice')
? backend.outputs.identityPrincipalId
: acaBackend.outputs.identityPrincipalId
roleDefinitionId: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd'
principalType: 'ServicePrincipal'
}
}
module openAiRoleSearchService 'core/security/role.bicep' = if (isAzureOpenAiHost && deployAzureOpenAi && useIntegratedVectorization) {
scope: openAiResourceGroup
name: 'openai-role-searchservice'
params: {
principalId: searchService.outputs.principalId
roleDefinitionId: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd'
principalType: 'ServicePrincipal'
}
}
module storageRoleBackend 'core/security/role.bicep' = {
scope: storageResourceGroup
name: 'storage-role-backend'
params: {
principalId: (deploymentTarget == 'appservice')
? backend.outputs.identityPrincipalId
: acaBackend.outputs.identityPrincipalId
roleDefinitionId: '2a2b9908-6ea1-4ae2-8e65-a410df84e7d1'
principalType: 'ServicePrincipal'
}
}
module storageOwnerRoleBackend 'core/security/role.bicep' = if (useUserUpload) {
scope: storageResourceGroup
name: 'storage-owner-role-backend'
params: {
principalId: (deploymentTarget == 'appservice')
? backend.outputs.identityPrincipalId
: acaBackend.outputs.identityPrincipalId
roleDefinitionId: 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b'