diff --git a/infra/ai-gateway/github-connection.bicep b/infra/ai-gateway/github-connection.bicep new file mode 100644 index 0000000..5cb6bb3 --- /dev/null +++ b/infra/ai-gateway/github-connection.bicep @@ -0,0 +1,44 @@ +targetScope = 'resourceGroup' + +@description('AI Gateway resource name in the current resource group.') +param gatewayName string + +@description('AI Gateway default hostname (without scheme).') +param runtimeHostname string + +@description('AI Gateway API key resource name.') +param apiKeyName string = 'default' + +@description('Resource group containing the Foundry project.') +param foundryAgentsResourceGroupName string + +@description('Foundry AI Services account name.') +param foundryAgentsAccountName string + +@description('Foundry project name.') +param foundryAgentsProjectName string + +#disable-next-line BCP081 +resource aiGateway 'Microsoft.ApiManagement/aigateways@2025-09-01-preview' existing = { + name: gatewayName +} + +#disable-next-line BCP081 +resource runtimeApiKey 'Microsoft.ApiManagement/aigateways/apiKeys@2025-09-01-preview' existing = { + parent: aiGateway + name: apiKeyName +} + +module githubConnection '../foundry-agents/github-connection.bicep' = { + name: 'github-connection-${uniqueString(gatewayName, foundryAgentsProjectName)}' + scope: resourceGroup(foundryAgentsResourceGroupName) + params: { + aiServicesName: foundryAgentsAccountName + aiProjectName: foundryAgentsProjectName + gatewayUrl: 'https://${runtimeHostname}' + gatewayApiKey: runtimeApiKey.listSecrets().key + } +} + +output connectionId string = githubConnection.outputs.connectionId +output connectionName string = githubConnection.outputs.connectionName diff --git a/infra/ai-gateway/monitoring.bicep b/infra/ai-gateway/monitoring.bicep new file mode 100644 index 0000000..f6c6707 --- /dev/null +++ b/infra/ai-gateway/monitoring.bicep @@ -0,0 +1,40 @@ +targetScope = 'resourceGroup' + +param location string +param tags object = {} +param enableMonitoring bool = true +param appInsightsName string +param logAnalyticsWorkspaceName string + +resource logAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2023-09-01' = if (enableMonitoring) { + name: logAnalyticsWorkspaceName + location: location + tags: tags + properties: { + retentionInDays: 30 + features: { + enableLogAccessUsingOnlyResourcePermissions: true + } + sku: { + name: 'PerGB2018' + } + } +} + +resource appInsights 'Microsoft.Insights/components@2020-02-02' = if (enableMonitoring) { + name: appInsightsName + location: location + kind: 'web' + tags: tags + properties: { + Application_Type: 'web' + WorkspaceResourceId: logAnalyticsWorkspace.id + #disable-next-line BCP037 + AzureMonitorWorkspaceIngestionMode: 'Enabled' + } +} + +output appInsightsId string = enableMonitoring ? appInsights.id : '' +output appInsightsName string = enableMonitoring ? appInsights.name : '' +output logAnalyticsWorkspaceId string = enableMonitoring ? logAnalyticsWorkspace.id : '' +output logAnalyticsWorkspaceName string = enableMonitoring ? logAnalyticsWorkspace.name : '' diff --git a/infra/avm/res/api-management/aigateway/api-key/main.bicep b/infra/avm/res/api-management/aigateway/api-key/main.bicep new file mode 100644 index 0000000..5b612f5 --- /dev/null +++ b/infra/avm/res/api-management/aigateway/api-key/main.bicep @@ -0,0 +1,64 @@ +metadata name = 'AI Gateway API Key' +metadata description = 'Configures a gateway-level API key without returning its secret values.' + +@description('Required. Parent gateway name.') +param aiGatewayName string +@description('Required. API key resource name.') +param name string +@description('Optional. API key properties.') +param properties apiKeyPropertiesType = {} +@secure() +@description('Optional. Secure values for explicit primary and secondary key references.') +param secrets { *: string } = {} + +#disable-next-line BCP081 +resource gateway 'Microsoft.ApiManagement/aigateways@2025-09-01-preview' existing = { + name: aiGatewayName +} +#disable-next-line BCP081 +resource apiKey 'Microsoft.ApiManagement/aigateways/apiKeys@2025-09-01-preview' = { + name: name + parent: gateway + properties: union( + { + displayName: properties.?displayName + state: properties.?state + expirationDate: properties.?expirationDate + }, + properties.?primaryKeySecretName == null + ? {} + : { + primaryKey: secrets[properties.primaryKeySecretName!] + }, + properties.?secondaryKeySecretName == null + ? {} + : { + secondaryKey: secrets[properties.secondaryKeySecretName!] + } + ) +} + +@description('The API key resource ID, not the key value.') +output resourceId string = apiKey.id +@description('The API key resource name.') +output name string = apiKey.name +@description('The resource group name.') +output resourceGroupName string = resourceGroup().name + +@export() +@sealed() +@description('API key resource configuration.') +type apiKeyType = { + name: string + properties: apiKeyPropertiesType? +} +@export() +@sealed() +@description('API key metadata and optional secure input references.') +type apiKeyPropertiesType = { + displayName: string? + state: string? + expirationDate: string? + primaryKeySecretName: string? + secondaryKeySecretName: string? +} diff --git a/infra/avm/res/api-management/aigateway/main.bicep b/infra/avm/res/api-management/aigateway/main.bicep new file mode 100644 index 0000000..8198d2c --- /dev/null +++ b/infra/avm/res/api-management/aigateway/main.bicep @@ -0,0 +1,275 @@ +metadata name = 'API Management AI Gateway' +metadata description = 'Deploys a standalone AI Gateway and its workspace-scoped model and tool configuration.' + +import { managedIdentityAllType, roleAssignmentType, lockType } from 'br/public:avm/utl/types/avm-common-types:0.7.0' +import { apiKeyType as childApiKeyType } from './api-key/main.bicep' +import { workspaceType as childWorkspaceType } from './workspace/main.bicep' +import { modelProviderType as childModelProviderType, authenticationType as childAuthenticationType } from './workspace/model-provider/main.bicep' +import { + modelType as childModelType + policyType as childPolicyType + tokenLimitPolicyType as childTokenLimitPolicyType + costLimitPolicyType as childCostLimitPolicyType + contentSafetyPolicyType as childContentSafetyPolicyType +} from './workspace/model-provider/model/main.bicep' +import { aliasType as childAliasType, routeType as childRouteType } from './workspace/alias/main.bicep' +import { toolServerType as childToolServerType, toolEndpointType as childToolEndpointType } from './workspace/tool-server/main.bicep' +import { telemetryExporterType as childTelemetryExporterType } from './workspace/telemetry-exporter/main.bicep' + +@description('Required. The name of the AI Gateway. Use lowercase letters, numbers and hyphens.') +@minLength(3) +@maxLength(24) +param name string + +@description('Optional. Azure region with AI Gateway preview availability.') +param location string = resourceGroup().location + +@description('Optional. The only SKU accepted by the preview resource provider.') +param sku 'Premium' = 'Premium' + +@description('Optional. Tags of the gateway.') +param tags { *: string } = {} + +@description('Optional. Managed identities assigned to the gateway.') +param managedIdentities managedIdentityAllType = { + systemAssigned: true +} + +@description('Optional. Role assignments scoped to the gateway, not to upstream Foundry accounts.') +param roleAssignments roleAssignmentType[]? + +@description('Optional. Resource lock applied after child configuration is deployed.') +param lock lockType? + +@description('Optional. Enable AVM module usage telemetry. This is independent of runtime telemetry exporters.') +param enableTelemetry bool = true + +@description('Optional. Virtual network configuration. Preview region and subnet requirements apply.') +param virtualNetworkConfiguration virtualNetworkConfigurationType? + +@description('Optional. Gateway-level API keys. Key values are generated by the service unless secret references are supplied.') +param apiKeys apiKeyType[]? + +@description('Optional. Workspace configuration. The service provisions default automatically; omit policies to reference it without a PUT.') +@maxLength(1) +param workspaces workspaceType[] = [ + { + name: 'default' + } +] + +@secure() +@description('Optional. Secret values indexed by the secret names used in child configurations. Supply through secure parameters or Key Vault; never commit values.') +param secrets { *: string } = {} + +var userAssignedIdentities = reduce( + map(managedIdentities.?userAssignedResourceIds ?? [], id => { '${id}': {} }), + {}, + (current, next) => union(current, next) +) +var identity = { + type: (managedIdentities.?systemAssigned ?? false) + ? (!empty(userAssignedIdentities) ? 'SystemAssigned,UserAssigned' : 'SystemAssigned') + : (!empty(userAssignedIdentities) ? 'UserAssigned' : 'None') + userAssignedIdentities: userAssignedIdentities +} + +var builtInRoleNames = { + Contributor: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c') + Owner: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635') + Reader: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7') + 'Role Based Access Control Administrator': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'f58310d9-a9f6-439a-9e8d-f62e7b41a168' + ) + 'User Access Administrator': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '18d7d88d-d35e-4fb5-a5c3-7773c20a72d9' + ) +} +var formattedRoleAssignments = [ + for assignment in (roleAssignments ?? []): union(assignment, { + roleDefinitionId: builtInRoleNames[?assignment.roleDefinitionIdOrName] ?? (contains( + assignment.roleDefinitionIdOrName, + '/providers/Microsoft.Authorization/roleDefinitions/' + ) + ? assignment.roleDefinitionIdOrName + : subscriptionResourceId('Microsoft.Authorization/roleDefinitions', assignment.roleDefinitionIdOrName)) + }) +] + +var telemetryIdPrefix = loadJsonContent('metadata.json', 'telemetryIdPrefix') + +#disable-next-line no-deployments-resources +resource avmTelemetry 'Microsoft.Resources/deployments@2025-04-01' = if (enableTelemetry) { + name: '${telemetryIdPrefix}.${replace('-..--..-', '.', '-')}.${substring(uniqueString(deployment().name, location), 0, 4)}' + properties: { + mode: 'Incremental' + template: { + '$schema': 'https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#' + contentVersion: '1.0.0.0' + resources: [] + outputs: { + telemetry: { + type: 'String' + value: 'For more information, see https://aka.ms/avm/TelemetryInfo' + } + } + } + } +} + +// The preview type is not yet in Bicep's resource type catalog; inputs are explicitly typed below. +#disable-next-line BCP081 +resource gateway 'Microsoft.ApiManagement/aigateways@2025-09-01-preview' = { + name: name + location: location + tags: tags + sku: { + name: sku + } + identity: identity + properties: virtualNetworkConfiguration == null + ? {} + : { + virtualNetworkType: virtualNetworkConfiguration!.virtualNetworkType + virtualNetworkConfiguration: { + subnetResourceId: virtualNetworkConfiguration!.subnetResourceId + } + } +} + +module gateway_apiKeys './api-key/main.bicep' = [ + for (apiKey, index) in (apiKeys ?? []): { + name: '${uniqueString(deployment().name, location)}-ApiKey-${index}' + params: { + aiGatewayName: gateway.name + name: apiKey.name + properties: apiKey.?properties ?? {} + secrets: secrets + } + } +] + +module gateway_workspaces './workspace/main.bicep' = [ + for (workspace, index) in workspaces: { + name: '${uniqueString(deployment().name, location)}-Workspace-${index}' + params: { + aiGatewayName: gateway.name + name: workspace.name + policies: workspace.?policies + modelProviders: workspace.?modelProviders + aliases: workspace.?aliases + toolServers: workspace.?toolServers + telemetryExporters: workspace.?telemetryExporters + secrets: secrets + } + dependsOn: [ + gateway_apiKeys + ] + } +] + +resource gateway_roleAssignments 'Microsoft.Authorization/roleAssignments@2022-04-01' = [ + for assignment in formattedRoleAssignments: { + name: assignment.?name ?? guid(gateway.id, assignment.principalId, assignment.roleDefinitionId) + scope: gateway + properties: { + roleDefinitionId: assignment.roleDefinitionId + principalId: assignment.principalId + principalType: assignment.?principalType + description: assignment.?description + condition: assignment.?condition + conditionVersion: !empty(assignment.?condition) ? (assignment.?conditionVersion ?? '2.0') : null + delegatedManagedIdentityResourceId: assignment.?delegatedManagedIdentityResourceId + } + } +] + +resource gateway_lock 'Microsoft.Authorization/locks@2020-05-01' = if (contains( + ['CanNotDelete', 'ReadOnly'], + lock.?kind ?? 'None' +)) { + name: lock.?name ?? 'lock-${name}' + scope: gateway + properties: { + level: lock.?kind ?? '' + notes: lock.?notes ?? (lock.?kind == 'CanNotDelete' + ? 'Cannot delete resource or child resources.' + : 'Cannot delete or modify the resource or child resources.') + } + dependsOn: [ + gateway_apiKeys + gateway_workspaces + gateway_roleAssignments + ] +} + +@description('The resource ID of the gateway.') +output resourceId string = gateway.id +@description('The name of the gateway.') +output name string = gateway.name +@description('The resource group containing the gateway.') +output resourceGroupName string = resourceGroup().name +@description('The region of the gateway.') +output location string = gateway.location +@description('The system-assigned managed identity principal ID, or null when not enabled.') +output systemAssignedMIPrincipalId string? = gateway.?identity.?principalId +@description('The service-provided default runtime hostname.') +output defaultHostname string = gateway.properties.frontend.defaultHostname +@description('The IDs of the configured API keys. Secret values are never output.') +output apiKeyResourceIds string[] = [for (apiKey, index) in (apiKeys ?? []): gateway_apiKeys[index].outputs.resourceId] +@description('The IDs of the configured workspaces.') +output workspaceResourceIds string[] = [ + for (workspace, index) in workspaces: gateway_workspaces[index].outputs.resourceId +] + +@export() +@description('Gateway-level API key configuration.') +type apiKeyType = childApiKeyType +@export() +@description('Workspace configuration and its nested resources.') +type workspaceType = childWorkspaceType +@export() +@description('Model provider configuration and catalog models.') +type modelProviderType = childModelProviderType +@export() +@description('Provider authentication with secure input references.') +type authenticationType = childAuthenticationType +@export() +@description('Catalog model configuration.') +type modelType = childModelType +@export() +@description('Supported inline model and workspace policies.') +type policyType = childPolicyType +@export() +@description('Token budget policy.') +type tokenLimitPolicyType = childTokenLimitPolicyType +@export() +@description('Cost budget policy.') +type costLimitPolicyType = childCostLimitPolicyType +@export() +@description('Content safety thresholds.') +type contentSafetyPolicyType = childContentSafetyPolicyType +@export() +@description('Client-facing model alias configuration.') +type aliasType = childAliasType +@export() +@description('An alias route to a provider model.') +type routeType = childRouteType +@export() +@description('MCP or OpenAPI tool server configuration.') +type toolServerType = childToolServerType +@export() +@description('A tool server upstream endpoint.') +type toolEndpointType = childToolEndpointType +@export() +@description('Application Insights or OpenTelemetry exporter configuration.') +type telemetryExporterType = childTelemetryExporterType +@export() +@sealed() +@description('Gateway virtual network attachment.') +type virtualNetworkConfigurationType = { + virtualNetworkType: 'External' | 'Internal' + subnetResourceId: string +} diff --git a/infra/avm/res/api-management/aigateway/metadata.json b/infra/avm/res/api-management/aigateway/metadata.json new file mode 100644 index 0000000..cdeac1e --- /dev/null +++ b/infra/avm/res/api-management/aigateway/metadata.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://raw.githubusercontent.com/Azure/azure-verified-modules-tools/main/src/Avm.Authoring/Resources/Schemas/v1/avm-module-metadata.schema.json", + "moduleDisplayName": "API Management AI Gateway", + "moduleDescription": "AVM Resource Module draft for standalone Azure AI Gateway", + "telemetryIdPrefix": "46d3xbcp.res.apimanagement-aigateway", + "canonicalType": "Microsoft.ApiManagement/aigateways", + "owners": ["paulyuk"] +} diff --git a/infra/avm/res/api-management/aigateway/version.json b/infra/avm/res/api-management/aigateway/version.json new file mode 100644 index 0000000..f077f1c --- /dev/null +++ b/infra/avm/res/api-management/aigateway/version.json @@ -0,0 +1,4 @@ +{ + "$schema": "https://aka.ms/bicep-registry-module-version-file-schema#", + "version": "0.1" +} diff --git a/infra/avm/res/api-management/aigateway/workspace/alias/main.bicep b/infra/avm/res/api-management/aigateway/workspace/alias/main.bicep new file mode 100644 index 0000000..cb4d0e2 --- /dev/null +++ b/infra/avm/res/api-management/aigateway/workspace/alias/main.bicep @@ -0,0 +1,75 @@ +metadata name = 'AI Gateway Alias' +metadata description = 'Creates a client-facing alias with priority and weighted routing.' + +import { policyType } from '../model-provider/model/main.bicep' + +@description('Required. Parent gateway name.') +param aiGatewayName string +@description('Required. Parent workspace name.') +param workspaceName string +@description('Required. Alias resource name.') +param name string +@description('Required. Alias routes and policies.') +param properties aliasPropertiesType + +#disable-next-line BCP081 +resource workspace 'Microsoft.ApiManagement/aigateways/workspaces@2025-09-01-preview' existing = { + name: '${aiGatewayName}/${workspaceName}' +} +#disable-next-line BCP081 +resource alias 'Microsoft.ApiManagement/aigateways/workspaces/aliases@2025-09-01-preview' = { + name: name + parent: workspace + properties: { + displayName: properties.displayName + description: properties.?description + routes: [ + for route in properties.routes: { + providerName: route.providerName + modelName: route.modelName + priority: route.?priority ?? 0 + weight: route.?weight ?? 1 + } + ] + policies: properties.?policies + } +} + +@description('The alias resource ID.') +output resourceId string = alias.id +@description('The alias name.') +output name string = alias.name +@description('The resource group name.') +output resourceGroupName string = resourceGroup().name + +@export() +@sealed() +@description('Alias resource configuration.') +type aliasType = { + name: string + properties: aliasPropertiesType +} +@export() +@sealed() +@description('Alias wire properties for the preview routes contract.') +type aliasPropertiesType = { + displayName: string + description: string? + @minLength(1) + @maxLength(30) + routes: routeType[] + policies: policyType[]? +} +@export() +@sealed() +@description('Route to a catalog model. Lower priority wins; weight is relative within a priority group.') +type routeType = { + providerName: string + modelName: string + @minValue(0) + @maxValue(100) + priority: int? + @minValue(1) + @maxValue(100) + weight: int? +} diff --git a/infra/avm/res/api-management/aigateway/workspace/main.bicep b/infra/avm/res/api-management/aigateway/workspace/main.bicep new file mode 100644 index 0000000..d64e4e0 --- /dev/null +++ b/infra/avm/res/api-management/aigateway/workspace/main.bicep @@ -0,0 +1,139 @@ +metadata name = 'AI Gateway Workspace' +metadata description = 'References the service-provisioned default workspace or writes workspace policies, then deploys child configuration.' + +import { modelProviderType } from './model-provider/main.bicep' +import { policyType } from './model-provider/model/main.bicep' +import { aliasType } from './alias/main.bicep' +import { toolServerType } from './tool-server/main.bicep' +import { telemetryExporterType } from './telemetry-exporter/main.bicep' + +@description('Required. Parent gateway name.') +param aiGatewayName string +@description('Optional. The preview service provisions the default workspace automatically.') +param name 'default' = 'default' +@description('Optional. Inline workspace policies. Null leaves existing policies unchanged; an empty array clears policies.') +param policies policyType[]? +@description('Optional. Model providers and their models.') +param modelProviders modelProviderType[]? +@description('Optional. Model aliases.') +param aliases aliasType[]? +@description('Optional. Tool servers.') +param toolServers toolServerType[]? +@description('Optional. Runtime telemetry exporters.') +param telemetryExporters telemetryExporterType[]? +@secure() +@description('Optional. Secure values used by child resource configurations.') +param secrets { *: string } = {} + +#disable-next-line BCP081 +resource gateway 'Microsoft.ApiManagement/aigateways@2025-09-01-preview' existing = { + name: aiGatewayName +} +#disable-next-line BCP081 +resource workspace 'Microsoft.ApiManagement/aigateways/workspaces@2025-09-01-preview' existing = { + name: name + parent: gateway +} +#disable-next-line BCP081 +resource workspacePolicies 'Microsoft.ApiManagement/aigateways/workspaces@2025-09-01-preview' = if (policies != null) { + name: name + parent: gateway + properties: { + policies: policies + } +} + +module workspace_modelProviders './model-provider/main.bicep' = [ + for (provider, index) in (modelProviders ?? []): { + name: '${uniqueString(deployment().name)}-Provider-${index}' + params: { + aiGatewayName: aiGatewayName + workspaceName: workspace.name + name: provider.name + properties: provider.properties + models: provider.?models + secrets: secrets + } + dependsOn: [ + workspacePolicies + ] + } +] +module workspace_aliases './alias/main.bicep' = [ + for (alias, index) in (aliases ?? []): { + name: '${uniqueString(deployment().name)}-Alias-${index}' + params: { + aiGatewayName: aiGatewayName + workspaceName: workspace.name + name: alias.name + properties: alias.properties + } + dependsOn: [ + workspacePolicies + workspace_modelProviders + ] + } +] +module workspace_toolServers './tool-server/main.bicep' = [ + for (toolServer, index) in (toolServers ?? []): { + name: '${uniqueString(deployment().name)}-ToolServer-${index}' + params: { + aiGatewayName: aiGatewayName + workspaceName: workspace.name + name: toolServer.name + properties: toolServer.properties + secrets: secrets + } + dependsOn: [ + workspacePolicies + ] + } +] +module workspace_telemetryExporters './telemetry-exporter/main.bicep' = [ + for (exporter, index) in (telemetryExporters ?? []): { + name: '${uniqueString(deployment().name)}-Exporter-${index}' + params: { + aiGatewayName: aiGatewayName + workspaceName: workspace.name + name: exporter.name + properties: exporter.properties + secrets: secrets + } + dependsOn: [ + workspacePolicies + ] + } +] + +@description('The workspace resource ID.') +output resourceId string = workspace.id +@description('The workspace name.') +output name string = workspace.name +@description('The resource group name.') +output resourceGroupName string = resourceGroup().name +@description('The model provider resource IDs.') +output modelProviderResourceIds string[] = [ + for (provider, index) in (modelProviders ?? []): workspace_modelProviders[index].outputs.resourceId +] +@description('The alias resource IDs.') +output aliasResourceIds string[] = [for (alias, index) in (aliases ?? []): workspace_aliases[index].outputs.resourceId] +@description('The tool server resource IDs.') +output toolServerResourceIds string[] = [ + for (server, index) in (toolServers ?? []): workspace_toolServers[index].outputs.resourceId +] +@description('The runtime telemetry exporter resource IDs.') +output telemetryExporterResourceIds string[] = [ + for (exporter, index) in (telemetryExporters ?? []): workspace_telemetryExporters[index].outputs.resourceId +] + +@export() +@sealed() +@description('Default workspace configuration. Additional named workspaces require preview RP support verification before extending this type.') +type workspaceType = { + name: 'default' + policies: policyType[]? + modelProviders: modelProviderType[]? + aliases: aliasType[]? + toolServers: toolServerType[]? + telemetryExporters: telemetryExporterType[]? +} diff --git a/infra/avm/res/api-management/aigateway/workspace/model-provider/foundry-role-assignment.bicep b/infra/avm/res/api-management/aigateway/workspace/model-provider/foundry-role-assignment.bicep new file mode 100644 index 0000000..fdaa94e --- /dev/null +++ b/infra/avm/res/api-management/aigateway/workspace/model-provider/foundry-role-assignment.bicep @@ -0,0 +1,33 @@ +metadata name = 'AI Gateway Foundry Upstream Role Assignment' +metadata description = 'Grants Azure AI User and Cognitive Services OpenAI User on an upstream Foundry account.' + +@description('Required. Upstream Foundry account name.') +param foundryAccountName string + +@description('Required. Principal ID to receive upstream Foundry access.') +param principalId string + +@description('Required. Gateway resource ID for deterministic role assignment naming.') +param gatewayResourceId string + +var foundryUserRoleDefinitionId = subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '53ca6127-db72-4b80-b1b0-d745d6d5456d' +) + +resource foundryAccount 'Microsoft.CognitiveServices/accounts@2025-06-01' existing = { + name: foundryAccountName +} + +resource foundryUserRoleAssignment 'Microsoft.Authorization/roleAssignments@2022-04-01' = { + name: guid(foundryAccount.id, gatewayResourceId, foundryUserRoleDefinitionId) + scope: foundryAccount + properties: { + principalId: principalId + principalType: 'ServicePrincipal' + roleDefinitionId: foundryUserRoleDefinitionId + } +} + +@description('Role assignment name.') +output roleAssignmentName string = foundryUserRoleAssignment.name diff --git a/infra/avm/res/api-management/aigateway/workspace/model-provider/main.bicep b/infra/avm/res/api-management/aigateway/workspace/model-provider/main.bicep new file mode 100644 index 0000000..6148f2c --- /dev/null +++ b/infra/avm/res/api-management/aigateway/workspace/model-provider/main.bicep @@ -0,0 +1,163 @@ +metadata name = 'AI Gateway Model Provider' +metadata description = 'Configures a Foundry or custom provider and its model catalog.' + +import { modelType } from './model/main.bicep' + +@description('Required. Parent gateway name.') +param aiGatewayName string +@description('Required. Parent workspace name.') +param workspaceName string +@description('Required. Model provider resource name.') +param name string +@description('Required. Typed provider configuration.') +param properties modelProviderPropertiesType +@description('Optional. Models registered under this provider.') +param models modelType[]? +@secure() +@description('Optional. Secure upstream API key values.') +param secrets { *: string } = {} + +var configuration = properties.kind == 'Foundry' ? properties.foundry : properties.custom +var authentication = configuration.authentication +var wireAuthentication = authentication.kind == 'ManagedIdentity' + ? authentication + : { + kind: 'ApiKey' + apiKey: { + headerName: authentication.apiKey.headerName + value: secrets[authentication.apiKey.secretName] + } + } + +#disable-next-line BCP081 +resource gateway 'Microsoft.ApiManagement/aigateways@2025-09-01-preview' existing = { + name: aiGatewayName +} +#disable-next-line BCP081 +resource workspace 'Microsoft.ApiManagement/aigateways/workspaces@2025-09-01-preview' existing = { + parent: gateway + name: workspaceName +} + +var assignUpstreamRole = properties.kind == 'Foundry' && (properties.foundry.?assignUpstreamRole ?? false) +var upstreamFoundryResourceIds = properties.kind == 'Foundry' ? properties.foundry.resourceIds : [] + +module upstreamRoleAssignments './foundry-role-assignment.bicep' = [ + for (foundryResourceId, index) in (assignUpstreamRole ? upstreamFoundryResourceIds : []): { + name: '${uniqueString(deployment().name, foundryResourceId)}-FoundryRole-${index}' + scope: az.resourceGroup(split(foundryResourceId, '/')[2], split(foundryResourceId, '/')[4]) + params: { + foundryAccountName: last(split(foundryResourceId, '/')) + principalId: gateway.identity.principalId + gatewayResourceId: gateway.id + } + } +] + +#disable-next-line BCP081 +resource provider 'Microsoft.ApiManagement/aigateways/workspaces/modelProviders@2025-09-01-preview' = { + name: name + parent: workspace + dependsOn: [ + upstreamRoleAssignments + ] + properties: union( + { + kind: properties.kind + displayName: properties.displayName + description: properties.?description + }, + properties.kind == 'Foundry' + ? { + foundry: { + endpoint: properties.foundry.endpoint + resourceIds: properties.foundry.resourceIds + authentication: wireAuthentication + } + } + : { + custom: { + endpoint: properties.custom.endpoint + authentication: wireAuthentication + } + } + ) +} + +module provider_models './model/main.bicep' = [ + for (model, index) in (models ?? []): { + name: '${uniqueString(deployment().name)}-Model-${index}' + params: { + aiGatewayName: aiGatewayName + workspaceName: workspaceName + modelProviderName: provider.name + name: model.name + properties: model.properties + } + } +] + +@description('The provider resource ID.') +output resourceId string = provider.id +@description('The provider name.') +output name string = provider.name +@description('The resource group name.') +output resourceGroupName string = resourceGroup().name +@description('The registered model resource IDs.') +output modelResourceIds string[] = [for (model, index) in (models ?? []): provider_models[index].outputs.resourceId] + +@export() +@sealed() +@description('Provider configuration and nested catalog models.') +type modelProviderType = { + name: string + properties: modelProviderPropertiesType + models: modelType[]? +} +@export() +@discriminator('kind') +@description('Provider kind selects its required configuration.') +type modelProviderPropertiesType = foundryProviderPropertiesType | customProviderPropertiesType +@sealed() +type foundryProviderPropertiesType = { + kind: 'Foundry' + displayName: string + description: string? + foundry: { + endpoint: string + @minLength(1) + resourceIds: string[] + assignUpstreamRole: bool? + authentication: authenticationType + } +} +@sealed() +type customProviderPropertiesType = { + kind: 'Custom' + displayName: string + description: string? + custom: { + endpoint: string + authentication: apiKeyAuthenticationType + } +} +@export() +@discriminator('kind') +@description('Upstream provider authentication.') +type authenticationType = managedIdentityAuthenticationType | apiKeyAuthenticationType +@sealed() +type managedIdentityAuthenticationType = { + kind: 'ManagedIdentity' + managedIdentity: { + resource: string? + clientId: string? + } +} +@sealed() +type apiKeyAuthenticationType = { + kind: 'ApiKey' + apiKey: { + headerName: string + secretName: string + } +} diff --git a/infra/avm/res/api-management/aigateway/workspace/model-provider/model/main.bicep b/infra/avm/res/api-management/aigateway/workspace/model-provider/model/main.bicep new file mode 100644 index 0000000..ccd461c --- /dev/null +++ b/infra/avm/res/api-management/aigateway/workspace/model-provider/model/main.bicep @@ -0,0 +1,96 @@ +metadata name = 'AI Gateway Model' +metadata description = 'Registers a provider model and applies inline governance policies.' + +@description('Required. Parent gateway name.') +param aiGatewayName string +@description('Required. Parent workspace name.') +param workspaceName string +@description('Required. Parent model provider name.') +param modelProviderName string +@description('Required. Model resource name.') +param name string +@description('Required. Model deployment and runtime configuration.') +param properties modelPropertiesType + +#disable-next-line BCP081 +resource provider 'Microsoft.ApiManagement/aigateways/workspaces/modelProviders@2025-09-01-preview' existing = { + name: '${aiGatewayName}/${workspaceName}/${modelProviderName}' +} +#disable-next-line BCP081 +resource model 'Microsoft.ApiManagement/aigateways/workspaces/modelProviders/models@2025-09-01-preview' = { + name: name + parent: provider + properties: properties +} + +@description('The model resource ID.') +output resourceId string = model.id +@description('The model name.') +output name string = model.name +@description('The resource group name.') +output resourceGroupName string = resourceGroup().name + +@export() +@sealed() +@description('Catalog model configuration.') +type modelType = { + name: string + properties: modelPropertiesType +} +@export() +@sealed() +@description('Model wire properties.') +type modelPropertiesType = { + displayName: string + description: string? + apiFormat: string + @minLength(1) + supportedEndpoints: string[] + deployment: { + resourceId: string? + modelName: string + modelVersion: string? + } + policies: policyType[]? +} +@export() +@discriminator('type') +@description('Typed inline governance policies supported by this draft.') +type policyType = tokenLimitPolicyType | costLimitPolicyType | contentSafetyPolicyType +@export() +@sealed() +@description('Token limit policy with public counter dimensions.') +type tokenLimitPolicyType = { + type: 'tokenLimit' + scope: ('resource' | 'workspace')? + @minValue(1) + count: int + period: 'minute' | 'hour' | 'day' + @minLength(1) + @maxLength(2) + counterKey: ('identity' | 'ipAddress')[] +} +@export() +@sealed() +@description('Cost limit policy. Amounts are whole USD in this draft.') +type costLimitPolicyType = { + type: 'costLimit' + id: string + scope: ('resource' | 'workspace')? + @minValue(1) + amount: int + period: 'hour' | 'day' | 'week' | 'month' | 'year' + @minLength(1) + @maxLength(2) + counterKey: ('identity' | 'ipAddress')[] +} +@export() +@sealed() +@description('Content safety policy thresholds.') +type contentSafetyPolicyType = { + type: 'contentSafety' + hateSeverity: ('Low' | 'Medium' | 'High' | 'None')? + selfHarmSeverity: ('Low' | 'Medium' | 'High' | 'None')? + sexualSeverity: ('Low' | 'Medium' | 'High' | 'None')? + violenceSeverity: ('Low' | 'Medium' | 'High' | 'None')? +} diff --git a/infra/avm/res/api-management/aigateway/workspace/telemetry-exporter/main.bicep b/infra/avm/res/api-management/aigateway/workspace/telemetry-exporter/main.bicep new file mode 100644 index 0000000..abc6441 --- /dev/null +++ b/infra/avm/res/api-management/aigateway/workspace/telemetry-exporter/main.bicep @@ -0,0 +1,118 @@ +metadata name = 'AI Gateway Telemetry Exporter' +metadata description = 'Configures runtime telemetry with payload capture disabled by default.' + +@description('Required. Parent gateway name.') +param aiGatewayName string +@description('Required. Parent workspace name.') +param workspaceName string +@description('Required. Exporter resource name.') +param name string +@description('Required. Export destination configuration.') +param properties telemetryExporterPropertiesType +@secure() +@description('Optional. Secure connection strings and OTLP headers.') +param secrets { *: string } = {} + +var resolveAppInsightsFromResourceId = properties.kind == 'ApplicationInsights' && properties.applicationInsights.?connectionStringSecretName == null && !empty(properties.applicationInsights.?resourceId ?? '') +var appInsightsResourceIdParts = resolveAppInsightsFromResourceId + ? split(properties.applicationInsights!.resourceId!, '/') + : [ + '' + 'subscriptions' + subscription().subscriptionId + 'resourceGroups' + resourceGroup().name + 'providers' + 'Microsoft.Insights' + 'components' + 'placeholder' + ] + +resource existingAppInsights 'Microsoft.Insights/components@2020-02-02' existing = if (resolveAppInsightsFromResourceId) { + name: last(appInsightsResourceIdParts) + scope: az.resourceGroup(appInsightsResourceIdParts[2], appInsightsResourceIdParts[4]) +} + +#disable-next-line BCP081 +resource workspace 'Microsoft.ApiManagement/aigateways/workspaces@2025-09-01-preview' existing = { + name: '${aiGatewayName}/${workspaceName}' +} +#disable-next-line BCP081 +resource exporter 'Microsoft.ApiManagement/aigateways/workspaces/telemetryExporters@2025-09-01-preview' = { + name: name + parent: workspace + properties: union( + { + kind: properties.kind + payloadCapture: properties.?payloadCapture ?? false + }, + properties.kind == 'ApplicationInsights' + ? { + applicationInsights: { + connectionString: properties.applicationInsights.?connectionStringSecretName != null + ? secrets[properties.applicationInsights.connectionStringSecretName!] + : existingAppInsights!.properties.ConnectionString + resourceId: properties.applicationInsights.?resourceId + } + } + : { + openTelemetry: { + metricsEndpoint: properties.openTelemetry.?metricsEndpoint + logsEndpoint: properties.openTelemetry.?logsEndpoint + tracesEndpoint: properties.openTelemetry.?tracesEndpoint + managedIdentity: properties.openTelemetry.?managedIdentity + headers: toObject( + properties.openTelemetry.?headers ?? [], + header => header.name, + header => secrets[header.secretName] + ) + } + } + ) +} + +@description('The exporter resource ID.') +output resourceId string = exporter.id +@description('The exporter name.') +output name string = exporter.name +@description('The resource group name.') +output resourceGroupName string = resourceGroup().name + +@export() +@sealed() +@description('Runtime telemetry exporter configuration.') +type telemetryExporterType = { + name: string + properties: telemetryExporterPropertiesType +} +@export() +@discriminator('kind') +@description('Exporter kind selects its destination.') +type telemetryExporterPropertiesType = applicationInsightsPropertiesType | openTelemetryPropertiesType +@sealed() +type applicationInsightsPropertiesType = { + kind: 'ApplicationInsights' + payloadCapture: bool? + applicationInsights: { + connectionStringSecretName: string? + resourceId: string? + } +} +@sealed() +type openTelemetryPropertiesType = { + kind: 'OpenTelemetry' + payloadCapture: bool? + openTelemetry: { + metricsEndpoint: string? + logsEndpoint: string? + tracesEndpoint: string? + managedIdentity: { + resource: string? + clientId: string? + }? + headers: { + name: string + secretName: string + }[]? + } +} diff --git a/infra/avm/res/api-management/aigateway/workspace/tool-server/main.bicep b/infra/avm/res/api-management/aigateway/workspace/tool-server/main.bicep new file mode 100644 index 0000000..de365ba --- /dev/null +++ b/infra/avm/res/api-management/aigateway/workspace/tool-server/main.bicep @@ -0,0 +1,160 @@ +metadata name = 'AI Gateway Tool Server' +metadata description = 'Configures MCP and OpenAPI upstream endpoints.' + +import { policyType } from '../model-provider/model/main.bicep' + +@description('Required. Parent gateway name.') +param aiGatewayName string +@description('Required. Parent workspace name.') +param workspaceName string +@description('Required. Tool server resource name.') +param name string +@description('Required. Tool server configuration.') +param properties toolServerPropertiesType +@secure() +@description('Optional. Secure upstream header values.') +param secrets { *: string } = {} + +#disable-next-line BCP081 +resource workspace 'Microsoft.ApiManagement/aigateways/workspaces@2025-09-01-preview' existing = { + name: '${aiGatewayName}/${workspaceName}' +} +#disable-next-line BCP081 +resource toolServer 'Microsoft.ApiManagement/aigateways/workspaces/toolServers@2025-09-01-preview' = { + name: name + parent: workspace + properties: { + displayName: properties.?displayName + description: properties.?description + type: properties.type + failureMode: properties.?failureMode + accessState: properties.?accessState + path: properties.?path + subscriptionRequired: properties.?subscriptionRequired ?? true + allowList: properties.?allowList + blocked: properties.?blocked + policies: properties.?policies + endpoints: [ + for endpoint in properties.endpoints: union( + { + id: endpoint.?id + namespace: endpoint.?namespace + tools: endpoint.?tools + required: endpoint.?required ?? false + kind: endpoint.kind + credentials: endpoint.?credentials == null + ? { + type: 'none' + } + : (endpoint.credentials!.type == 'header' + ? { + type: 'header' + headers: toObject( + endpoint.credentials!.headers, + header => header.name, + header => [ + header.?secretName != null ? secrets[header.secretName!] : (header.?value ?? '') + ] + ) + } + : endpoint.credentials!) + }, + endpoint.kind == 'mcp' + ? { + mcp: endpoint.mcp + } + : { + openApi: endpoint.openApi + } + ) + ] + } +} + +@description('The tool server resource ID.') +output resourceId string = toolServer.id +@description('The tool server name.') +output name string = toolServer.name +@description('The resource group name.') +output resourceGroupName string = resourceGroup().name + +@export() +@sealed() +@description('Tool server resource configuration.') +type toolServerType = { + name: string + properties: toolServerPropertiesType +} +@export() +@sealed() +@description('Tool server wire properties. Connector-backed servers are deliberately excluded.') +type toolServerPropertiesType = { + displayName: string? + description: string? + type: 'mcp' | 'openApi' + failureMode: ('failClosed' | 'failOpen')? + accessState: ('active' | 'blocked')? + path: string? + subscriptionRequired: bool? + allowList: string[]? + blocked: string[]? + policies: policyType[]? + @minLength(1) + endpoints: toolEndpointType[] +} +@export() +@discriminator('kind') +@description('MCP or URL-based OpenAPI upstream endpoint.') +type toolEndpointType = mcpEndpointType | openApiEndpointType +@sealed() +type mcpEndpointType = { + id: string? + namespace: string? + kind: 'mcp' + mcp: { + url: string + transport: 'streamableHttp'? + } + credentials: toolCredentialsType? + tools: string[]? + required: bool? +} +@sealed() +type openApiEndpointType = { + id: string? + namespace: string? + kind: 'openApi' + openApi: { + specSource: { + type: 'url' + url: string + } + } + credentials: toolCredentialsType? + tools: string[]? + required: bool? +} +@discriminator('type') +type toolCredentialsType = anonymousCredentialsType | headerCredentialsType | managedIdentityCredentialsType +@sealed() +type anonymousCredentialsType = { + type: 'none' +} +@sealed() +type headerCredentialsType = { + type: 'header' + @minLength(1) + headers: { + name: string + secretName: string? + value: string? + }[] +} +@sealed() +type managedIdentityCredentialsType = { + type: 'managedIdentity' + managedIdentity: { + resource: string + clientId: string? + } +} diff --git a/infra/foundry-agents/github-connection.bicep b/infra/foundry-agents/github-connection.bicep index 39bcd15..dde70f6 100644 --- a/infra/foundry-agents/github-connection.bicep +++ b/infra/foundry-agents/github-connection.bicep @@ -35,3 +35,6 @@ resource githubConnection 'Microsoft.CognitiveServices/accounts/projects/connect } } } + +output connectionId string = githubConnection.id +output connectionName string = githubConnection.name diff --git a/infra/main.bicep b/infra/main.bicep index 94a0f9a..60d78cb 100644 --- a/infra/main.bicep +++ b/infra/main.bicep @@ -75,6 +75,10 @@ param enableMonitoring bool = true @description('Log Analytics workspace name for Application Insights. Defaults to a deterministic name in the application resource group.') param logAnalyticsWorkspaceName string = '' +@secure() +@description('Optional GitHub MCP Authorization header value (for example Bearer ). When omitted, the postprovision hook injects a transient gh auth token without persisting it in azd env.') +param githubMcpAuthorization string = '' + @description('Application Insights component for Foundry hosted-agent tracing.') param agentAppInsightsName string = '' @@ -249,67 +253,266 @@ module foundryAgents './foundry-agents/main.bicep' = { } } -module aiGateway './ai-gateway/main.bicep' = { - name: 'ai-gateway-${resourceToken}' +module aiGatewayMonitoring './ai-gateway/monitoring.bicep' = { + name: 'ai-gateway-monitoring-${resourceToken}' scope: gatewayRg params: { location: location - gatewayLocation: aiGatewayLocation - gatewayName: effectiveAiGatewayName - foundryAgentsResourceGroupName: foundryAgentsRg.name - foundryAgentsAccountName: foundryAgents.outputs.aiServicesName - foundryAgentsProjectName: foundryAgents.outputs.aiProjectName tags: tags enableMonitoring: enableMonitoring - deployApimGatewayViaBicep: true appInsightsName: effectiveAppInsightsName logAnalyticsWorkspaceName: effectiveLogAnalyticsWorkspaceName - deployFoundryProvider: true - foundryProviderName: 'foundry' - foundryProviderDisplayName: 'Foundry' - foundryProviderDescription: 'Managed-identity Foundry provider for the deployments behind this sample.' - foundryEndpoint: foundryModels.outputs.aiServicesEndpoint - foundryResourceIds: [ - foundryModels.outputs.aiServicesId - ] - foundryModels: [for (deployment, i) in gatewayModelDeployments: { - armName: deployment.deploymentName - description: deployment.description - resourceId: foundryModels.outputs.modelDeploymentIds[i] - modelName: deployment.modelName - modelVersion: deployment.modelVersion - apiFormat: 'OpenAIChatCompletions' - tokenLimit: deployment.capacity * 1000 - costLimit: 10 - contentSafetySeverity: 'Medium' - supportedEndpoints: [ - '/openai/v1/chat/completions' - '/openai/v1/responses' - ] - }] - modelAliasesConfig: [ + } +} + +// Once the upstream AVM PR is approved and published, replace './avm/res/api-management/aigateway/main.bicep' +// with 'br/public:avm/res/api-management/aigateway:0.1.0'. +module aiGateway './avm/res/api-management/aigateway/main.bicep' = { + name: 'ai-gateway-${resourceToken}' + scope: gatewayRg + params: { + name: effectiveAiGatewayName + location: aiGatewayLocation + tags: tags + managedIdentities: { + systemAssigned: true + } + apiKeys: [ { - armName: 'primary-router' - aliasName: modelAliasName - description: 'Primary model with automatic failover to the secondary full model and mini deployment.' - backendModels: effectiveModelAliasBackends + name: 'default' + properties: { + displayName: 'Default hosted agent key' + } } + ] + secrets: !empty(githubMcpAuthorization) + ? { + githubMcpAuth: githubMcpAuthorization + } + : {} + workspaces: [ { - armName: 'mini-router' - aliasName: miniModelAliasName - description: 'Direct alias for the mini deployment.' - backendModels: [ + name: 'default' + modelProviders: [ + { + name: 'foundry' + properties: { + kind: 'Foundry' + displayName: 'Foundry' + description: 'Managed-identity Foundry provider for the deployments behind this sample.' + foundry: { + endpoint: foundryModels.outputs.aiServicesEndpoint + resourceIds: [ + foundryModels.outputs.aiServicesId + ] + assignUpstreamRole: true + authentication: { + kind: 'ManagedIdentity' + managedIdentity: { + resource: 'https://cognitiveservices.azure.com/' + } + } + } + } + models: [for (deployment, i) in gatewayModelDeployments: { + name: deployment.deploymentName + properties: { + displayName: deployment.modelName + description: deployment.description + apiFormat: 'OpenAIChatCompletions' + supportedEndpoints: [ + '/openai/v1/chat/completions' + '/openai/v1/responses' + ] + deployment: { + resourceId: foundryModels.outputs.modelDeploymentIds[i] + modelName: deployment.deploymentName + modelVersion: deployment.modelVersion + } + policies: [ + { + type: 'tokenLimit' + period: 'minute' + count: deployment.capacity * 1000 + counterKey: [ + 'identity' + ] + } + { + id: 'monthly-caller-budget' + type: 'costLimit' + period: 'month' + amount: 10 + counterKey: [ + 'identity' + ] + } + { + type: 'contentSafety' + hateSeverity: 'Medium' + selfHarmSeverity: 'Medium' + sexualSeverity: 'Medium' + violenceSeverity: 'Medium' + } + ] + } + }] + } + ] + aliases: [ + { + name: modelAliasName + properties: { + displayName: 'Primary Model Router' + description: 'Primary model with automatic failover to the secondary full model and mini deployment.' + routes: [for target in effectiveModelAliasBackends: { + providerName: 'foundry' + modelName: target.modelArmName + priority: target.priority + weight: target.weight + }] + } + } { - modelArmName: miniModelDeploymentName - priority: 0 - weight: 100 + name: miniModelAliasName + properties: { + displayName: 'Mini Model Router' + description: 'Direct alias for the mini deployment.' + routes: [ + { + providerName: 'foundry' + modelName: miniModelDeploymentName + priority: 0 + weight: 100 + } + ] + } } ] + toolServers: [ + { + name: 'github' + properties: { + displayName: 'GitHub repository digest' + description: 'Read-only GitHub tools for repository digests.' + type: 'mcp' + failureMode: 'failClosed' + policies: [ + { + type: 'tokenLimit' + period: 'minute' + count: 50000 + counterKey: [ + 'identity' + ] + } + { + id: 'monthly-caller-budget' + type: 'costLimit' + period: 'month' + amount: 5 + counterKey: [ + 'identity' + ] + } + { + type: 'contentSafety' + hateSeverity: 'Medium' + selfHarmSeverity: 'Medium' + sexualSeverity: 'Medium' + violenceSeverity: 'Medium' + } + ] + endpoints: [ + { + namespace: 'github' + kind: 'mcp' + mcp: { + url: 'https://api.githubcopilot.com/mcp/' + transport: 'streamableHttp' + } + credentials: { + type: 'header' + headers: concat( + !empty(githubMcpAuthorization) + ? [ + { + name: 'Authorization' + secretName: 'githubMcpAuth' + } + ] + : [], + [ + { + name: 'X-MCP-Readonly' + value: 'true' + } + { + name: 'X-MCP-Tools' + value: 'list_pull_requests,list_issues,actions_list' + } + ] + ) + } + } + ] + } + } + ] + telemetryExporters: enableMonitoring + ? [ + { + name: 'applicationInsights' + properties: { + kind: 'ApplicationInsights' + payloadCapture: false + applicationInsights: { + resourceId: aiGatewayMonitoring.outputs.appInsightsId + } + } + } + ] + : [] } ] } } +module foundryGithubConnection './ai-gateway/github-connection.bicep' = { + name: 'foundry-github-connection-${resourceToken}' + scope: gatewayRg + params: { + gatewayName: effectiveAiGatewayName + runtimeHostname: aiGateway.outputs.defaultHostname + foundryAgentsResourceGroupName: foundryAgentsRg.name + foundryAgentsAccountName: foundryAgents.outputs.aiServicesName + foundryAgentsProjectName: foundryAgents.outputs.aiProjectName + } +} + +var foundryUserRoleDefinitionId = subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '53ca6127-db72-4b80-b1b0-d745d6d5456d' +) +var modelAliasResourceIds = [ + subscriptionResourceId( + subscription().subscriptionId, + gatewayRg.name, + 'Microsoft.ApiManagement/aigateways/workspaces/aliases', + effectiveAiGatewayName, + 'default', + modelAliasName + ) + subscriptionResourceId( + subscription().subscriptionId, + gatewayRg.name, + 'Microsoft.ApiManagement/aigateways/workspaces/aliases', + effectiveAiGatewayName, + 'default', + miniModelAliasName + ) +] + output AZURE_LOCATION string = location output AZURE_TENANT_ID string = tenant().tenantId output RESOURCE_GROUP string = foundryAgentsRg.name @@ -338,19 +541,23 @@ output TOOLBOX_NAME string = 'repo-digest-tools' output ENABLE_AI_GATEWAY bool = true output AI_GATEWAY_NAME string = effectiveAiGatewayName output AI_GATEWAY_LOCATION string = aiGatewayLocation -output AI_GATEWAY_RESOURCE_ID string = aiGateway.outputs.apimGatewayId -output AI_GATEWAY_MODEL_ALIAS_IDS array = aiGateway.outputs.modelAliasIds -output AI_GATEWAY_DEFAULT_MODEL_ALIAS_NAME string = aiGateway.outputs.defaultModelAliasName -output AI_GATEWAY_FOUNDRY_ROLE_ASSIGNMENT_NAME string = aiGateway.outputs.foundryUserRoleAssignmentName -output AI_GATEWAY_FOUNDRY_ROLE_ASSIGNMENT_PRINCIPAL_ID string = aiGateway.outputs.gatewayPrincipalId -output AI_GATEWAY_APP_INSIGHTS_ID string = aiGateway.outputs.appInsightsId -output AI_GATEWAY_LOG_ANALYTICS_WORKSPACE_ID string = aiGateway.outputs.logAnalyticsWorkspaceId -output AI_GATEWAY_PRINCIPAL_ID string = aiGateway.outputs.gatewayPrincipalId -output APPLICATION_INSIGHTS_NAME string = aiGateway.outputs.appInsightsName -output LOG_ANALYTICS_WORKSPACE_ID string = aiGateway.outputs.logAnalyticsWorkspaceId -output LOG_ANALYTICS_WORKSPACE_NAME string = aiGateway.outputs.logAnalyticsWorkspaceName +output AI_GATEWAY_RESOURCE_ID string = aiGateway.outputs.resourceId +output AI_GATEWAY_MODEL_ALIAS_IDS array = modelAliasResourceIds +output AI_GATEWAY_DEFAULT_MODEL_ALIAS_NAME string = modelAliasName +output AI_GATEWAY_FOUNDRY_ROLE_ASSIGNMENT_NAME string = guid( + foundryModels.outputs.aiServicesId, + aiGateway.outputs.resourceId, + foundryUserRoleDefinitionId +) +output AI_GATEWAY_FOUNDRY_ROLE_ASSIGNMENT_PRINCIPAL_ID string = aiGateway.outputs.?systemAssignedMIPrincipalId ?? '' +output AI_GATEWAY_APP_INSIGHTS_ID string = aiGatewayMonitoring.outputs.appInsightsId +output AI_GATEWAY_LOG_ANALYTICS_WORKSPACE_ID string = aiGatewayMonitoring.outputs.logAnalyticsWorkspaceId +output AI_GATEWAY_PRINCIPAL_ID string = aiGateway.outputs.?systemAssignedMIPrincipalId ?? '' +output APPLICATION_INSIGHTS_NAME string = aiGatewayMonitoring.outputs.appInsightsName +output LOG_ANALYTICS_WORKSPACE_ID string = aiGatewayMonitoring.outputs.logAnalyticsWorkspaceId +output LOG_ANALYTICS_WORKSPACE_NAME string = aiGatewayMonitoring.outputs.logAnalyticsWorkspaceName output ENABLE_MONITORING bool = enableMonitoring -output AZURE_AI_GATEWAY_ENDPOINT string = 'https://${aiGateway.outputs.runtimeHostname}/' +output AZURE_AI_GATEWAY_ENDPOINT string = 'https://${aiGateway.outputs.defaultHostname}/' output AZURE_AI_GATEWAY_MODEL string = modelAliasName output AZURE_AI_GATEWAY_MINI_MODEL string = miniModelAliasName output AI_GATEWAY_INTERNAL_MODEL_DEPLOYMENT string = modelDeploymentName diff --git a/tests/test-ai-gateway-model-registration.sh b/tests/test-ai-gateway-model-registration.sh index 743cfe2..1754914 100755 --- a/tests/test-ai-gateway-model-registration.sh +++ b/tests/test-ai-gateway-model-registration.sh @@ -130,15 +130,15 @@ done root_alias_input="$(jq -r ' .. | objects - | select(has("modelAliasesConfig")) - | .modelAliasesConfig.value + | select(has("workspaces")) + | .workspaces.value | select(. != null) ' "$compiled_root_template")" if [[ "$root_alias_input" != *"modelArmName"* || "$root_alias_input" != *"priority"* || "$root_alias_input" != *"weight"* || - "$root_alias_input" != *"primary-router"* ]]; then + "$root_alias_input" != *"Primary Model Router"* ]]; then echo "Root deployment must create a multi-model alias with explicit priority and weight routes." >&2 echo "Actual: $root_alias_input" >&2 exit 1 @@ -174,21 +174,18 @@ for setting in \ fi done -root_model_input="$(jq -r ' - .. | objects - | select(has("foundryModels")) - | .foundryModels.copy[0].input - | select(. != null) -' "$compiled_root_template")" +root_model_input="$root_alias_input" for token in \ "OpenAIChatCompletions" \ "/openai/v1/chat/completions" \ "/openai/v1/responses" \ - "mul(variables('gatewayModelDeployments')[copyIndex('value')].capacity, 1000)" \ - "'costLimit', 10" \ - "'contentSafetySeverity', 'Medium'"; do + "mul(variables('gatewayModelDeployments')[copyIndex('models')].capacity, 1000)" \ + '"amount": 10' \ + '"hateSeverity": "Medium"' \ + "https://api.githubcopilot.com/mcp/" \ + "assignUpstreamRole"; do if ! grep -Fq "$token" <<< "$root_model_input"; then - echo "Root model registrations must use the live RP API, capacity-scaled token limits, and Medium content safety." >&2 + echo "Root model registrations must use the AVM module, capacity-scaled token limits, Medium content safety, and GitHub MCP." >&2 echo "Missing: $token" >&2 echo "Actual: $root_model_input" >&2 exit 1