Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
infra: Use Functions Apps instead of Container Apps
Clémence Lesnéd3aea46a7874
diff --git a/.funcignore b/.funcignorenew file mode 100644index 0000000..9c0595f--- /dev/null+++ b/.funcignore@@ -0,0 +1,17 @@+# Temporary files+*.sqlite*+.pytest_cache/++# Local app config file+config*.yaml++# Test reports+test-reports/++# Documentation and examples+docs/+examples/++# Python Tools for Visual Studio (PTVS)+__pycache__/+*.pycdiff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex bd7cf87..8eeac22 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -10,8 +10,3 @@ updates:target-branch: developschedule:interval: daily- - package-ecosystem: docker- directory: ""- target-branch: develop- schedule:- interval: dailydiff --git a/.github/workflows/pipeline.yaml b/.github/workflows/pipeline.yamlindex 30bf149..cb0cf5e 100644--- a/.github/workflows/pipeline.yaml+++ b/.github/workflows/pipeline.yaml@@ -14,13 +14,6 @@ on:- hotfix/*- main-env:- CONTAINER_NAME: ${{ github.repository }}- CONTAINER_REGISTRY_GHCR: ghcr.io- CONTAINER_PLATFORMS: linux/amd64,linux/arm64/v8- # https://github.com/docker/buildx/releases- BUILDX_VERSION: 0.11.2-jobs:init:name: Init@@ -62,75 +55,6 @@ jobs:extra_args: --only-verifiedhead: HEAD~1- build-image:- name: Build & publish image- needs:- - init- - sast-creds- - sast-semgrep- runs-on: ubuntu-22.04- permissions:- # Allow to write to GitHub Packages- packages: write- steps:- - name: Checkout- uses: actions/[email protected]-- - name: Configure Git- run: |- git config user.name "${{ github.actor }}"- git config user.email "${{ github.actor }}@users.noreply.github.com"-- - name: Setup QEMU- id: setup-qemu- uses: docker/[email protected]- with:- platforms: ${{ env.CONTAINER_PLATFORMS }}-- - name: Setup Docker Buildx- uses: docker/[email protected]- with:- version: v${{ env.BUILDX_VERSION }}-- - name: Login to registry - GitHub- uses: docker/[email protected]- with:- registry: ${{ env.CONTAINER_REGISTRY_GHCR }}- username: ${{ github.actor }}- password: ${{ secrets.GITHUB_TOKEN }}-- - name: Container meta- id: meta- uses: docker/[email protected]- with:- images: ${{ env.CONTAINER_REGISTRY_GHCR }}/${{ env.CONTAINER_NAME }}- tags: |- type=raw,value=latest,enable={{is_default_branch}}- type=ref,event=branch- type=ref,event=pr- type=schedule- type=schedule,pattern={{date 'YYYYMMDD'}}- type=semver,pattern={{version}},value=${{ needs.init.outputs.VERSION_FULL }}- type=sha- labels: |- org.opencontainers.image.documentation=https://github.com/${{ env.CONTAINER_NAME }}- org.opencontainers.image.vendor=${{ github.actor }}-- - name: Build/push container- uses: docker/[email protected]- with:- build-args: |- VERSION=${{ needs.init.outputs.VERSION_FULL }}- cache-from: type=gha- cache-to: type=gha- context: .- labels: ${{ steps.meta.outputs.labels }}- platforms: ${{ env.CONTAINER_PLATFORMS }}- provenance: true- push: true- sbom: true- tags: ${{ steps.meta.outputs.tags }}-sast-semgrep:name: SAST - Semgrepruns-on: ubuntu-22.04@@ -147,7 +71,7 @@ jobs:# Semgrep can be used to break the build when it detects security issues. In this case we want to upload the issues to GitHub Securitycontinue-on-error: trueenv:- SEMGREP_RULES: p/cwe-top-25 p/owasp-top-ten p/dockerfile+ SEMGREP_RULES: p/cwe-top-25 p/owasp-top-tenrun: semgrep ci --sarif --output=semgrep.sarif- name: Upload results to GitHub Security@@ -158,7 +82,6 @@ jobs:create-release:name: Create releaseneeds:- - build-image- initpermissions:# Allow to create releasesdiff --git a/.gitignore b/.gitignoreindex f25a9e4..230927d 100644--- a/.gitignore+++ b/.gitignore@@ -1,8 +1,9 @@# See: https://github.com/clemlesne/gitops-version.version.cache-# Temporary database+# Temporary files*.sqlite*+.pytest_cache/# Local app config fileconfig*.yaml@@ -10,8 +11,12 @@ config*.yaml# Test reportstest-reports/-# Created by https://www.toptal.com/developers/gitignore/api/osx,linux,dotenv,eclipse,windows,visualstudio,visualstudiocode,jupyternotebooks-# Edit at https://www.toptal.com/developers/gitignore?templates=osx,linux,dotenv,eclipse,windows,visualstudio,visualstudiocode,jupyternotebooks+# Created by https://www.toptal.com/developers/gitignore/api/osx,linux,dotenv,eclipse,windows,visualstudio,jupyternotebooks,visualstudiocode,azurefunctions+# Edit at https://www.toptal.com/developers/gitignore?templates=osx,linux,dotenv,eclipse,windows,visualstudio,jupyternotebooks,visualstudiocode,azurefunctions++### AzureFunctions ###+# Azure Functions localsettings file+local.settings.json### dotenv ###.env@@ -573,4 +578,4 @@ FodyWeavers.xsd### VisualStudio Patch #### Additional files built by Visual Studio-# End of https://www.toptal.com/developers/gitignore/api/osx,linux,dotenv,eclipse,windows,visualstudio,visualstudiocode,jupyternotebooks+# End of https://www.toptal.com/developers/gitignore/api/osx,linux,dotenv,eclipse,windows,visualstudio,jupyternotebooks,visualstudiocode,azurefunctionsdiff --git a/.python-version b/.python-versionindex 9a941ac..ff7de60 100644--- a/.python-version+++ b/.python-version@@ -1 +1 @@-callcenterai312+callcenterai311diff --git a/.vscode/extensions.json b/.vscode/extensions.jsonindex 00a9804..8eb48b6 100644--- a/.vscode/extensions.json+++ b/.vscode/extensions.json@@ -1,19 +1,18 @@{"recommendations": ["EditorConfig.EditorConfig",- "ms-python.python",- "ms-toolsai.jupyter",+ "mechatroner.rainbow-csv","mikestead.dotenv",+ "ms-azuretools.vscode-bicep","ms-python.black-formatter",- "redhat.vscode-yaml",+ "ms-python.python","ms-python.vscode-pylance",- "qwtel.sqlite-viewer",- "mechatroner.rainbow-csv",- "ms-azuretools.vscode-docker",+ "ms-toolsai.jupyter","ms-vscode.makefile-tools",- "wholroyd.jinja",+ "qwtel.sqlite-viewer",+ "redhat.vscode-yaml",+ "tomoki1207.pdf","visualstudioexptteam.vscodeintellicode",- "ms-azuretools.vscode-bicep",- "tomoki1207.pdf"+ "wholroyd.jinja"]}diff --git a/Dockerfile b/Dockerfiledeleted file mode 100644index 7ca8f22..0000000--- a/Dockerfile+++ /dev/null@@ -1,45 +0,0 @@-# Base container-FROM docker.io/library/python:3.12-slim-bookworm@sha256:541d45d3d675fb8197f534525a671e2f8d66c882b89491f9dda271f4f94dcd06 AS base--# Build container-FROM base AS build--RUN rm -f /etc/apt/apt.conf.d/docker-clean \- && echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache-RUN --mount=target=/var/lib/apt/lists,type=cache,sharing=locked --mount=target=/root/.cache/pip,type=cache,sharing=locked \- apt-get update -q \- && apt-get install -y -q --no-install-recommends \- gcc \- python3-dev \- && python3 -m pip install --upgrade \- pip \- setuptools \- wheel--RUN python -m venv /venv-ENV PATH=/venv/bin:$PATH--COPY requirements.txt .-RUN --mount=target=/root/.cache/pip,type=cache,sharing=locked \- python3 -m pip install --requirement requirements.txt--# Output container-FROM base--ARG VERSION-ENV VERSION=${VERSION}--RUN useradd -m appuser \- && mkdir /app \- && chown -R appuser:appuser /app--USER appuser--COPY --from=build /venv /venv-ENV PATH=/venv/bin:$PATH--COPY --chown=appuser:appuser . /app--WORKDIR /app--CMD ["bash", "-c", "gunicorn main:api --bind 0.0.0.0:8080 --proxy-protocol --workers 4 --worker-class uvicorn.workers.UvicornWorker"]diff --git a/Makefile b/Makefileindex 3d1c0d7..8f703ad 100644--- a/Makefile+++ b/Makefile@@ -1,6 +1,3 @@-# Container configuration-container_name := ghcr.io/clemlesne/call-center-ai-docker := docker# Versioningversion_full ?= $(shell $(MAKE) --silent version-full)version_small ?= $(shell $(MAKE) --silent version)@@ -8,8 +5,9 @@ version_small ?= $(shell $(MAKE) --silent version)tunnel_name := call-center-ai-$(shell hostname | sed 's/[^a-zA-Z0-9]//g' | tr '[:upper:]' '[:lower:]')tunnel_url ?= $(shell res=$$(devtunnel show $(tunnel_name) | grep -o 'http[s]*://[^"]*' | xargs) && echo $${res%/})# App location-app_location := westeuropecognitive_communication_location := westeurope+default_location := westeurope+functionapp_location := swedencentralopenai_location := southcentralussearch_location := northeurope# App configuration@@ -20,6 +18,7 @@ twilio_phone_number ?= $(shell cat config.yaml | yq '.sms.twilio.phone_number')app_url ?= $(shell az deployment sub show --name $(name) | yq '.properties.outputs["appUrl"].value')blob_storage_public_name ?= $(shell az deployment sub show --name $(name) | yq '.properties.outputs["blobStoragePublicName"].value')communication_id ?= $(shell az deployment sub show --name $(name) | yq '.properties.outputs["communicationId"].value')+function_app_name ?= $(shell az deployment sub show --name $(name) | yq '.properties.outputs["functionAppName"].value')log_analytics_workspace_customer_id ?= $(shell az deployment sub show --name $(name) | yq '.properties.outputs["logAnalyticsWorkspaceName"].value')version:@@ -29,9 +28,6 @@ version-full:@bash ./cicd/version/version.sh -g . -c -minstall:- @echo "➡️ Installing Dev Tunnels CLI..."- devtunnel --version || brew install --cask devtunnel-@echo "➡️ Installing Allure..."allure --version || brew install allure@@ -44,9 +40,6 @@ install:@echo "➡️ Installing Python dev dependencies..."python3 -m pip install -r requirements-dev.txt- @echo "➡️ Testing Docker installation..."- $(docker) --version || echo "🚨 Docker is not installed."-upgrade:@echo "➡️ Upgrading pip..."python3 -m pip install --upgrade pip@@ -96,63 +89,34 @@ tunnel:devtunnel host $(tunnel_name)dev:- VERSION=$(version_full) API__EVENTS_DOMAIN=$(tunnel_url) python3 -m gunicorn main:api \- --access-logfile - \- --bind 0.0.0.0:8080 \- --proxy-protocol \- --reload \- --reload-extra-file .env \- --reload-extra-file config.yaml \- --workers 2 \- --worker-class uvicorn.workers.UvicornWorker--build:- $(docker) build \- --build-arg VERSION=$(version_full) \- --tag $(container_name):$(version_small) \- --tag $(container_name):latest \- .--start:- @echo "🛠️ Deploying to localhost..."- $(docker) run \- --env API__EVENTS_DOMAIN=$(tunnel_url) \- --env VERSION=$(version_full) \- --mount type=bind,source="$(CURDIR)/.env",target="/app/.env" \- --mount type=bind,source="$(CURDIR)/config.yaml",target="/app/config.yaml" \- --name call-center-ai \- --publish 8080:8080 \- --rm \- $(container_name):$(version_small)--stop:- @echo "Stopping container..."- $(docker) stop call-center-ai+ VERSION=$(version_full) PUBLIC_DOMAIN=$(tunnel_url) func start \+ --port 8080deploy:@echo "👀 Current subscription:"@az account show --query "{subscriptionId:id, subscriptionName:name, tenantId:tenantId}" --output table- @echo "🛠️ Deploying to Azure..."+ @echo "🛠️ Deploying resources..."az deployment sub create \- --location $(app_location) \+ --location $(default_location) \--parameters \'cognitiveCommunicationLocation=$(cognitive_communication_location)' \+ 'functionappLocation=$(functionapp_location)' \'openaiLocation=$(openai_location)' \'searchLocation=$(search_location)' \+ 'version=$(version_full)' \--template-file bicep/main.bicep \--name $(name)+ @echo "🛠️ Deploying Function App..."+ func azure functionapp publish $(function_app_name)+@$(MAKE) post-deploy name=$(name)post-deploy:@$(MAKE) copy-resources \name=$(blob_storage_public_name)- @$(MAKE) eventgrid-register \- endpoint=$(app_url) \- source=$(communication_id)-@$(MAKE) twilio-register \endpoint=$(app_url)@@ -170,61 +134,8 @@ destroy:az deployment sub delete --name $(name)logs:- az containerapp logs show \- --follow \- --format text \- --name call-center-ai \- --resource-group $(name) \- --tail 100--logs-history:- az monitor log-analytics query \- --analytics-query "ContainerAppConsoleLogs_CL | project TimeGenerated, Log_s | sort by TimeGenerated desc" \- --output jsonc \- --timespan P1D \- --workspace $(log_analytics_workspace_customer_id)--eventgrid-register:- @$(MAKE) eventgrid-subscription-delete \- event_source=$(source) \- event_subscription_name=$(event_subscription_name)-- @$(MAKE) eventgrid-subscription-create \- event_filter="data.to.PhoneNumber.Value" \- event_phone_number=$(bot_phone_number) \- event_source=$(source) \- event_subscription_name=$(event_subscription_name) \- event_types="Microsoft.Communication.IncomingCall"-- @$(MAKE) eventgrid-subscription-delete \- event_source=$(source) \- event_subscription_name=$(event_subscription_name)-sms-- @$(MAKE) eventgrid-subscription-create \- event_filter="data.to" \- event_phone_number=$(bot_phone_number) \- event_source=$(source) \- event_subscription_name=$(event_subscription_name)-sms \- event_types="Microsoft.Communication.SMSReceived"--eventgrid-subscription-create:- @echo "⚙️ Registering Event Grid webhook $(event_subscription_name)..."- az eventgrid event-subscription create \- --advanced-filter $(event_filter) StringBeginsWith $(event_phone_number) \- --enable-advanced-filtering-on-arrays true \- --endpoint $(endpoint)/eventgrid/event \- --event-delivery-schema eventgridschema \- --event-ttl 3 \- --included-event-types "$(event_types)" \- --max-delivery-attempts 8 \- --name $(event_subscription_name) \- --source-resource-id $(event_source)--eventgrid-subscription-delete:- @echo "⚙️ Deleting Event Grid webhook $(event_subscription_name)..."- az eventgrid event-subscription delete \- --name $(event_subscription_name) \- --source-resource-id $(event_source)+ func azure functionapp logstream $(function_app_name) \+ --browsertwilio-register:@echo "⚙️ Registering Twilio webhook..."diff --git a/README.md b/README.mdindex 0fda5df..f7ef4c3 100644--- a/README.md+++ b/README.md@@ -244,10 +244,7 @@ sequenceDiagram## Remote deployment-Container is available on GitHub Actions, at:--- Latest version from a branch: `ghcr.io/clemlesne/call-center-ai:main`-- Specific tag: `ghcr.io/clemlesne/call-center-ai:0.1.0` (recommended)+Application is hosted by Azure Functions. Code will be pushed automatically `make deploy`, with after the deployment.Create a local `config.yaml` file (most of the fields are filled automatically by the deployment script):@@ -373,12 +370,7 @@ For your knowledge, this `resources` folder contains:### Run-Finally, in two different terminals, run:--```bash-# Expose the local server to the internet-make tunnel-```+Finally, run:```bash# Start the local API serverdiff --git a/bicep/app.bicep b/bicep/app.bicepindex 69ee049..49630f4 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -1,30 +1,31 @@param adaModel stringparam adaVersion stringparam cognitiveCommunicationLocation string+param functionappLocation stringparam gptBackupContext intparam gptBackupModel stringparam gptBackupVersion stringparam gptContext intparam gptModel stringparam gptVersion string-param imageVersion stringparam location stringparam moderationBlocklists arrayparam openaiLocation stringparam searchLocation stringparam tags object+param version string+var appName = 'call-center-ai'var prefix = deployment().name-var appUrl = 'https://call-center-ai.${acaEnv.properties.defaultDomain}'+var functionAppName = '${prefix}-${appName}'+var appUrl = 'https://${functionAppName}.azurewebsites.net'var gptBackupModelFullName = toLower('${gptBackupModel}-${gptBackupVersion}')var gptModelFullName = toLower('${gptModel}-${gptVersion}')var adaModelFullName = toLower('${adaModel}-${adaVersion}')var cosmosContainerName = 'calls-v3' // Third schema versionvar localConfig = loadYamlContent('../config.yaml')var config = {- api: {- events_domain: appUrl- }+ public_domain: appUrlmonitoring: {application_insights: {connection_string: applicationInsights.properties.ConnectionString@@ -51,9 +52,10 @@ var config = {}}communication_service: {- access_key: communication.listKeys().primaryKey- endpoint: communication.properties.hostName+ access_key: communicationServices.listKeys().primaryKey+ endpoint: communicationServices.properties.hostNamephone_number: localConfig.communication_service.phone_number+ queue_name: communicationServicesQueue.name}sms: localConfig.smscognitive_service: {@@ -112,10 +114,11 @@ var config = {output appUrl string = appUrloutput blobStoragePublicName string = storageAccount.name-output communicationId string = communication.id-output logAnalyticsWorkspaceCustomerId string = logAnalyticsWorkspace.properties.customerId+output communicationId string = communicationServices.id+output functionAppName string = functionAppName+output logAnalyticsCustomerId string = logAnalytics.properties.customerId-resource logAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {+resource logAnalytics 'Microsoft.OperationalInsights/workspaces@2022-10-01' = {name: prefixlocation: locationtags: tags@@ -134,92 +137,135 @@ resource applicationInsights 'Microsoft.Insights/components@2020-02-02' = {kind: 'web'properties: {Application_Type: 'web'- WorkspaceResourceId: logAnalyticsWorkspace.id+ WorkspaceResourceId: logAnalytics.id}}-resource acaEnv 'Microsoft.App/managedEnvironments@2023-05-01' = {+resource flexFuncPlan 'Microsoft.Web/serverfarms@2023-12-01' = {name: prefix- location: location+ location: functionappLocationtags: tags+ sku: {+ tier: 'FlexConsumption'+ name: 'FC1'+ }properties: {- appLogsConfiguration: {- destination: 'log-analytics'- logAnalyticsConfiguration: {- customerId: logAnalyticsWorkspace.properties.customerId- sharedKey: logAnalyticsWorkspace.listKeys().primarySharedKey- }- }- workloadProfiles: [- {- // Consumption workload profile name must be 'Consumption'- name: 'Consumption'- workloadProfileType: 'Consumption'- }- ]+ reserved: true}}-resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {- name: 'call-center-ai'- location: location+resource functionApp 'Microsoft.Web/sites@2023-12-01' = {+ name: functionAppName+ location: functionappLocationtags: tags+ kind: 'functionapp,linux'identity: {type: 'SystemAssigned'}properties: {- configuration: {- activeRevisionsMode: 'Single'- ingress: {- external: true- targetPort: 8080- }- }- environmentId: acaEnv.id- template: {- containers: [+ serverFarmId: flexFuncPlan.id+ siteConfig: {+ appSettings: [+ // See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#azurewebjobsstorage__accountname{- image: 'ghcr.io/clemlesne/call-center-ai:${imageVersion}'- name: 'call-center-ai'- env: [- {- name: 'CONFIG_JSON'- value: string(config)- }- ]- resources: {- cpu: 1- memory: '2Gi'- }- probes: [- {- type: 'Startup'- tcpSocket: {- port: 8080- }- }- {- type: 'Liveness'- httpGet: {- path: '/health/liveness'- port: 8080- }- periodSeconds: 10 // 2x the timeout- timeoutSeconds: 5 // Fast to check if the app is running- }- {- type: 'Readiness'- httpGet: {- path: '/health/readiness'- port: 8080- }- periodSeconds: 20 // 2x the timeout- timeoutSeconds: 10 // Database can take a while to be ready, query is necessary but expensive to run- }- ]+ name: 'AzureWebJobsStorage__accountName'+ value: storageAccount.name+ }+ // See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#appinsights_instrumentationkey+ {+ name: 'APPINSIGHTS_INSTRUMENTATIONKEY'+ value: applicationInsights.properties.InstrumentationKey+ }+ // Threadpool for async tasks+ // See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#python_threadpool_thread_count+ {+ name: 'PYTHON_THREADPOOL_THREAD_COUNT'+ value: '4'+ }+ {+ name: 'CONFIG_JSON'+ value: string(config)+ }+ {+ name: 'VERSION'+ value: version}]}+ functionAppConfig: {+ deployment: {+ storage: {+ type: 'blobContainer'+ value: '${storageAccount.properties.primaryEndpoints.blob}${functionAppBlob.name}'+ authentication: {+ type: 'SystemAssignedIdentity'+ }+ }+ }+ scaleAndConcurrency: {+ instanceMemoryMB: 2048 // Default and recommended+ maximumInstanceCount: 100 // TODO: Avoid billing surprises, delete when sure+ alwaysReady: [+ {+ instanceCount: 1+ name: 'function:eventgrid_event_post'+ }+ {+ instanceCount: 1+ name: 'function:http_app_func'+ }+ ]+ }+ runtime: {+ name: 'python'+ version: '3.11'+ }+ }+ }+}++// Storage Account Contributor+resource roleStorageAccountContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {+ name: '17d1049b-9a84-46fb-8f53-869881c3d3ab'+}++resource assignmentFunctionAppStorageAccountContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, prefix, storageAccount.name, 'assignmentFunctionAppStorageAccountContributor')+ scope: storageAccount+ properties: {+ principalId: functionApp.identity.principalId+ principalType: 'ServicePrincipal'+ roleDefinitionId: roleStorageAccountContributor.id+ }+}++// Storage Blob Data Owner+resource roleBlobDataOwner 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {+ name: 'b7e6dc6d-f1e8-4753-8033-0f276bb0955b'+}++resource assignmentFunctionAppBlobDataOwner 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, prefix, storageAccount.name, 'assignmentFunctionAppBlobDataOwner')+ scope: storageAccount+ properties: {+ principalId: functionApp.identity.principalId+ principalType: 'ServicePrincipal'+ roleDefinitionId: roleBlobDataOwner.id+ }+}++// Storage Queue Data Contributor+resource roleQueueDataContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {+ name: '974c5e8b-45b9-4653-ba55-5f855dd0fb88'+}++resource assignmentFunctionAppQueueDataContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, prefix, storageAccount.name, 'assignmentFunctionAppQueueDataContributor')+ scope: storageAccount+ properties: {+ principalId: functionApp.identity.principalId+ principalType: 'ServicePrincipal'+ roleDefinitionId: roleQueueDataContributor.id}}@@ -231,6 +277,19 @@ resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {name: 'Standard_ZRS'}kind: 'StorageV2'+ properties: {+ supportsHttpsTrafficOnly: true+ }+}++resource queueService 'Microsoft.Storage/storageAccounts/queueServices@2023-01-01' = {+ parent: storageAccount+ name: 'default'+}++resource communicationServicesQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-01-01' = {+ parent: queueService+ name: 'communication-services'}resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01' = {@@ -238,26 +297,32 @@ resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01'name: 'default'}-resource blobContainer 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = {+resource publicBlob 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = {parent: blobServicename: '$web'}-resource roleCommunicationContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {+resource functionAppBlob 'Microsoft.Storage/storageAccounts/blobServices/containers@2023-01-01' = {+ parent: blobService+ name: functionAppName+}++// Contributor+resource roleContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {name: 'b24988ac-6180-42a0-ab88-20f7382dd24c'}-resource appContribCommunication 'Microsoft.Authorization/roleAssignments@2022-04-01' = {- name: guid(subscription().id, deployment().name, communication.name, 'appContribCommunication')- scope: communication+resource assignmentFunctionAppContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, prefix, communicationServices.name, 'assignmentFunctionAppContributor')+ scope: communicationServicesproperties: {- principalId: containerApp.identity.principalId+ principalId: functionApp.identity.principalIdprincipalType: 'ServicePrincipal'- roleDefinitionId: roleCommunicationContributor.id+ roleDefinitionId: roleContributor.id}}-resource communication 'Microsoft.Communication/CommunicationServices@2023-06-01-preview' existing = {+resource communicationServices 'Microsoft.Communication/CommunicationServices@2023-06-01-preview' existing = {name: prefix}@@ -265,21 +330,110 @@ resource eventgridTopic 'Microsoft.EventGrid/systemTopics@2023-12-15-preview' =name: prefixlocation: 'global'tags: tags+ identity: {+ type: 'SystemAssigned'+ }properties: {- source: communication.id+ source: communicationServices.idtopicType: 'Microsoft.Communication.CommunicationServices'}}+// Storage Queue Data Message Sender+resource roleQueueSender 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {+ name: 'c6a89b2d-59bc-44d0-9896-0f6e12d7b80a'+}++resource assignmentEventgridTopicQueueSender 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, prefix, eventgridTopic.name, 'assignmentEventgridTopicQueueSender')+ scope: storageAccount+ properties: {+ principalId: eventgridTopic.identity.principalId+ principalType: 'ServicePrincipal'+ roleDefinitionId: roleQueueSender.id+ }+}++resource eventgridSubscriptionCall 'Microsoft.EventGrid/systemTopics/eventSubscriptions@2024-06-01-preview' = {+ parent: eventgridTopic+ name: '${prefix}-${replace(localConfig.communication_service.phone_number, '+', '')}'+ properties: {+ eventDeliverySchema: 'EventGridSchema'+ deliveryWithResourceIdentity: {+ identity: {+ type: 'SystemAssigned'+ }+ destination: {+ endpointType: 'StorageQueue'+ properties: {+ queueMessageTimeToLiveInSeconds: 60 // Short lived messages, only new call events+ queueName: communicationServicesQueue.name+ resourceId: storageAccount.id+ }+ }+ }+ filter: {+ enableAdvancedFilteringOnArrays: true+ advancedFilters: [+ {+ operatorType: 'StringBeginsWith'+ key: 'data.to.PhoneNumber.Value'+ values: [+ localConfig.communication_service.phone_number+ ]+ }+ ]+ includedEventTypes: ['Microsoft.Communication.IncomingCall']+ }+ }+ dependsOn: [assignmentEventgridTopicQueueSender]+}++resource eventgridSubscriptionSms 'Microsoft.EventGrid/systemTopics/eventSubscriptions@2024-06-01-preview' = {+ parent: eventgridTopic+ name: '${prefix}-${replace(localConfig.communication_service.phone_number, '+', '')}-sms'+ properties: {+ eventDeliverySchema: 'EventGridSchema'+ deliveryWithResourceIdentity: {+ identity: {+ type: 'SystemAssigned'+ }+ destination: {+ endpointType: 'StorageQueue'+ properties: {+ queueMessageTimeToLiveInSeconds: -1 // Infinite persistence, SMS is async+ queueName: communicationServicesQueue.name+ resourceId: storageAccount.id+ }+ }+ }+ filter: {+ enableAdvancedFilteringOnArrays: true+ advancedFilters: [+ {+ operatorType: 'StringBeginsWith'+ key: 'data.to'+ values: [+ localConfig.communication_service.phone_number+ ]+ }+ ]+ includedEventTypes: ['Microsoft.Communication.SMSReceived']+ }+ }+ dependsOn: [assignmentEventgridTopicQueueSender]+}++// Cognitive Services Userresource roleCognitiveUser 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {name: 'a97b65f3-24c7-4388-baec-2e87135dc908'}-resource appUserCommunication 'Microsoft.Authorization/roleAssignments@2022-04-01' = {- name: guid(subscription().id, deployment().name, cognitiveCommunication.name, 'appUserCommunication')+resource assignmentsCommunicationServicesCognitiveUser 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, prefix, cognitiveCommunication.name, 'assignmentsCommunicationServicesCognitiveUser')scope: cognitiveCommunicationproperties: {- principalId: communication.identity.principalId+ principalId: communicationServices.identity.principalIdprincipalType: 'ServicePrincipal'roleDefinitionId: roleCognitiveUser.id}@@ -328,15 +482,16 @@ resource cognitiveContentsafety 'Microsoft.CognitiveServices/accounts@2023-10-01}}+// Cognitive Services OpenAI Contributorresource roleOpenaiContributor 'Microsoft.Authorization/roleDefinitions@2022-04-01' existing = {name: 'a001fd3d-188f-4b5d-821b-7da978bf7442'}-resource appContribOpenai 'Microsoft.Authorization/roleAssignments@2022-04-01' = {- name: guid(subscription().id, deployment().name, cognitiveOpenai.name, 'appContribOpenai')+resource assignmentsFunctionAppOpenaiContributor 'Microsoft.Authorization/roleAssignments@2022-04-01' = {+ name: guid(subscription().id, prefix, cognitiveOpenai.name, 'assignmentsFunctionAppOpenaiContributor')scope: cognitiveOpenaiproperties: {- principalId: containerApp.identity.principalId+ principalId: functionApp.identity.principalIdprincipalType: 'ServicePrincipal'roleDefinitionId: roleOpenaiContributor.id}@@ -358,6 +513,7 @@ resource cognitiveOpenai 'Microsoft.CognitiveServices/accounts@2023-10-01-previeresource gpt 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {parent: cognitiveOpenainame: gptModelFullName+ tags: tagssku: {capacity: 20 // Keep it small, will be scaled up if needed with "dynamicThrottlingEnabled"name: 'Standard' // Pay-as-you-go@@ -377,6 +533,7 @@ resource gpt 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-previeresource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {parent: cognitiveOpenainame: gptBackupModelFullName+ tags: tagssku: {capacity: 20 // Keep it small, will be scaled up if needed with "dynamicThrottlingEnabled"name: 'Standard' // Pay-as-you-go@@ -396,6 +553,7 @@ resource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-// resource contentfilter 'Microsoft.CognitiveServices/accounts/raiPolicies@2023-06-01-preview' = {// parent: cognitiveOpenai// name: 'disabled'+// tags: tags// properties: {// basePolicyName: 'Microsoft.Default'// mode: 'Default'@@ -455,6 +613,7 @@ resource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-resource ada 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {parent: cognitiveOpenainame: adaModelFullName+ tags: tagssku: {capacity: 150name: 'Standard' // Pay-as-you-go@@ -498,10 +657,10 @@ resource cosmos 'Microsoft.DocumentDB/databaseAccounts@2023-11-15' = {resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2023-11-15' = {parent: cosmos- name: 'call-center-ai'+ name: appNameproperties: {resource: {- id: 'call-center-ai'+ id: appName}}}diff --git a/bicep/main.bicep b/bicep/main.bicepindex 1a025bc..bf52431 100644--- a/bicep/main.bicep+++ b/bicep/main.bicep@@ -1,31 +1,33 @@param adaModel string = 'text-embedding-ada-002'param adaVersion string = '2'param cognitiveCommunicationLocation string+param functionappLocation stringparam gptBackupContext int = 16385param gptBackupModel string = 'gpt-35-turbo'param gptBackupVersion string = '0125'param gptContext int = 128000param gptModel string = 'gpt-4o'param gptVersion string = '2024-05-13'-param imageVersion string = 'main'param instance string = deployment().nameparam location string = deployment().locationparam openaiLocation stringparam searchLocation string+param version stringtargetScope = 'subscription'output appUrl string = app.outputs.appUrloutput blobStoragePublicName string = app.outputs.blobStoragePublicNameoutput communicationId string = app.outputs.communicationId-output logAnalyticsWorkspaceCustomerId string = app.outputs.logAnalyticsWorkspaceCustomerId+output functionAppName string = app.outputs.functionAppName+output logAnalyticsCustomerId string = app.outputs.logAnalyticsCustomerIdvar tags = {application: 'call-center-ai'instance: instancemanaged_by: 'Bicep'sources: 'https://github.com/clemlesne/call-center-ai'- version: imageVersion+ version: version}resource sub 'Microsoft.Resources/resourceGroups@2021-04-01' = {@@ -41,17 +43,18 @@ module app 'app.bicep' = {adaModel: adaModeladaVersion: adaVersioncognitiveCommunicationLocation: cognitiveCommunicationLocation+ functionappLocation: functionappLocationgptBackupContext: gptBackupContextgptBackupModel: gptBackupModelgptBackupVersion: gptBackupVersiongptContext: gptContextgptModel: gptModelgptVersion: gptVersion- imageVersion: imageVersionlocation: locationmoderationBlocklists: []openaiLocation: openaiLocationsearchLocation: searchLocationtags: tags+ version: version}}diff --git a/main.py b/function_app.pysimilarity index 87%rename from main.pyrename to function_app.pyindex 0ecc111..e354880 100644--- a/main.py+++ b/function_app.py@@ -56,6 +56,7 @@ from helpers.call_events import ()from models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatusfrom htmlmin.minify import html_minify+import azure.functions as func# Jinja configuration@@ -87,7 +88,6 @@ _search = CONFIG.ai_search.instance()_sms = CONFIG.sms.instance()# FastAPI-_logger.info(f'Using root path "{CONFIG.api.root_path}"')api = FastAPI(contact={"url": "https://github.com/clemlesne/call-center-ai",@@ -97,18 +97,29 @@ api = FastAPI("name": "Apache-2.0","url": "https://github.com/clemlesne/call-center-ai/blob/master/LICENCE",},- root_path=CONFIG.api.root_path,title="call-center-ai",version=CONFIG.version,+ servers=[+ {+ "url": CONFIG.public_domain,+ "description": "Current environment",+ },+ ],)+# Azure Functions+app = func.AsgiFunctionApp(+ app=api,+ http_auth_level=func.AuthLevel.ANONYMOUS,+)-assert CONFIG.api.events_domain, "api.events_domain config is not set"-_COMMUNICATIONSERVICES_EVENT_TPL = urljoin(- str(CONFIG.api.events_domain),+#+assert CONFIG.public_domain, "public_domain config is not set"+_COMMUNICATIONSERVICES_CALLABACK_TPL = urljoin(+ str(CONFIG.public_domain),"/communicationservices/event/{call_id}/{callback_secret}",)-_logger.info(f"Using call event URL {_COMMUNICATIONSERVICES_EVENT_TPL}")+_logger.info(f"Using call event URL {_COMMUNICATIONSERVICES_CALLABACK_TPL}")@api.get(@@ -253,63 +264,29 @@ async def call_post(initiate: CallInitiateModel) -> CallGetModel:return CallGetModel.model_validate(call)-# TODO: Secure this endpoint with a secret, either in the Authorization header or in the URL- "/eventgrid/event",- description="Handle incoming call from a Azure Event Grid event originating from Azure Communication Services.",- name="Receive Event Grid event",[email protected]_trigger(+ arg_name="msg",+ connection="Storage",+ queue_name=CONFIG.communication_service.queue_name,)-async def eventgrid_event_post(- background_tasks: BackgroundTasks,- request: Request,-) -> Response:- responses = await asyncio.gather(- *[- _eventgrid_event_worker(- background_tasks=background_tasks,- event_dict=event_dict,- )- for event_dict in await request.json()- ]- )- for response in responses:- if response:- return response- return Response(status_code=status.HTTP_204_NO_CONTENT)---async def _eventgrid_event_worker(- background_tasks: BackgroundTasks,- event_dict: dict[str, Any],-) -> Optional[Union[JSONResponse, Response]]:- event = EventGridEvent.from_dict(event_dict)+async def eventgrid_event_post(msg: func.QueueMessage) -> None:+ background_tasks = BackgroundTasks()+ event = EventGridEvent.from_json(msg.get_body())event_type = event.event_type_logger.debug(f"Call inbound event {event_type} with data {event.data}")- if event_type == SystemEventNames.EventGridSubscriptionValidationEventName:- validation_code: str = event.data["validationCode"]- _logger.info(f"Validating Event Grid subscription ({validation_code})")- return JSONResponse(- content={"validationResponse": event.data["validationCode"]},- status_code=status.HTTP_200_OK,- )-- elif event_type == SystemEventNames.AcsIncomingCallEventName:+ if event_type == SystemEventNames.AcsIncomingCallEventName:call_context: str = event.data["incomingCallContext"]phone_number = event.data["from"]["phoneNumber"]["value"]phone_number = PhoneNumber(phone_number)url, _ = await _communicationservices_event_url(phone_number)- event_status = await on_new_call(+ await on_new_call(callback_url=url,client=_automation_client,context=call_context,phone_number=phone_number,)- if not event_status:- return Response(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- )elif event_type == SystemEventNames.AcsSmsReceivedEventName:message: str = event.data["message"]@@ -317,19 +294,15 @@ async def _eventgrid_event_worker(call = await _db.call_asearch_one(phone_number)if not call:_logger.warning(f"Call for phone number {phone_number} not found")- return Response(- status_code=status.HTTP_404_NOT_FOUND,- )- event_status = await on_sms_received(+ return+ await on_sms_received(background_tasks=background_tasks,call=call,client=_automation_client,message=message,)- if not event_status:- return Response(- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,- )++ await background_tasks()@api.post(@@ -494,7 +467,7 @@ async def _communicationservices_event_url())await _db.call_aset(call) # Create for the first time- url = _COMMUNICATIONSERVICES_EVENT_TPL.format(+ url = _COMMUNICATIONSERVICES_CALLABACK_TPL.format(callback_secret=call.callback_secret,call_id=str(call.call_id),)diff --git a/helpers/call_utils.py b/helpers/call_utils.pyindex 3c77fda..c5220ec 100644--- a/helpers/call_utils.py+++ b/helpers/call_utils.py@@ -220,9 +220,11 @@ def _audio_from_text(<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xmlns:mstts="https://www.w3.org/2001/mstts" xml:lang="{call.lang.short_code}"><voice name="{call.lang.voice}" effect="eq_telecomhp8k"><lexicon uri="{CONFIG.resources.public_url}/lexicon.xml" />- <mstts:express-as style="{style.value}" styledegree="0.5">- <prosody rate="0.95">{text}</prosody>- </mstts:express-as>+ <lang xml:lang="{call.lang.short_code}">+ <mstts:express-as style="{style.value}" styledegree="0.5">+ <prosody rate="0.95">{text}</prosody>+ </mstts:express-as>+ </lang></voice></speak>"""diff --git a/helpers/config_models/api.py b/helpers/config_models/api.pydeleted file mode 100644index f4efb05..0000000--- a/helpers/config_models/api.py+++ /dev/null@@ -1,7 +0,0 @@-from pydantic import BaseModel-from typing import Optional---class ApiModel(BaseModel):- events_domain: Optional[str] = None- root_path: str = ""diff --git a/helpers/config_models/communication_service.py b/helpers/config_models/communication_service.pyindex 60f333e..64225f2 100644--- a/helpers/config_models/communication_service.py+++ b/helpers/config_models/communication_service.py@@ -6,3 +6,4 @@ class CommunicationServiceModel(BaseModel):access_key: SecretStrendpoint: strphone_number: PhoneNumber+ queue_name: strdiff --git a/helpers/config_models/llm.py b/helpers/config_models/llm.pyindex 58a269f..e90414e 100644--- a/helpers/config_models/llm.py+++ b/helpers/config_models/llm.py@@ -1,4 +1,4 @@-from azure.identity import DefaultAzureCredential, get_bearer_token_provider+from azure.identity import ManagedIdentityCredential, get_bearer_token_providerfrom contextlib import asynccontextmanagerfrom enum import Enumfrom openai import AsyncAzureOpenAI, AsyncOpenAI@@ -34,7 +34,8 @@ class AzureOpenaiPlatformModel(AbstractPlatformModel, frozen=True):api_key = self.api_key.get_secret_value() if self.api_key else Nonetoken_func = (get_bearer_token_provider(- DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"+ ManagedIdentityCredential(),+ "https://cognitiveservices.azure.com/.default",)if not self.api_keyelse Nonediff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex 24bbc76..9ae849c 100644--- a/helpers/config_models/root.py+++ b/helpers/config_models/root.py@@ -1,6 +1,5 @@from helpers.config_models.ai_search import AiSearchModelfrom helpers.config_models.ai_translation import AiTranslationModel-from helpers.config_models.api import ApiModelfrom helpers.config_models.cache import CacheModelfrom helpers.config_models.cognitive_service import CognitiveServiceModelfrom helpers.config_models.communication_service import CommunicationServiceModel@@ -25,11 +24,11 @@ class RootModel(BaseSettings):)# Immutable fields+ public_domain: str = Field(frozen=True)version: str = Field(default="0.0.0-unknown", frozen=True)# Editable fieldsai_search: AiSearchModelai_translation: AiTranslationModel- api: ApiModel = ApiModel() # Object is fully defined by defaultcache: CacheModel = CacheModel() # Object is fully defined by defaultcognitive_service: CognitiveServiceModelcommunication_service: CommunicationServiceModeldiff --git a/helpers/llm_tools.py b/helpers/llm_tools.pyindex 7b0cc63..fd6aced 100644--- a/helpers/llm_tools.py+++ b/helpers/llm_tools.py@@ -14,7 +14,8 @@ from models.message import (from models.reminder import ReminderModelfrom openai.types.chat import ChatCompletionToolParamfrom pydantic import ValidationError-from typing import Awaitable, Callable, Annotated, Literal, TypedDict+from typing import Awaitable, Callable, Annotated, Literal+from typing_extensions import TypedDictimport asynciodiff --git a/host.json b/host.jsonnew file mode 100644index 0000000..836fbfd--- /dev/null+++ b/host.json@@ -0,0 +1,19 @@+{+ "version": "2.0",+ "extensionBundle": {+ "id": "Microsoft.Azure.Functions.ExtensionBundle",+ "version": "[4.0.0, 5.0.0)"+ },+ "extensions": {+ "http": {+ "maxConcurrentRequests": 8,+ "maxOutstandingRequests": 4,+ "routePrefix": ""+ },+ "queues": {+ "batchSize": 16,+ "maxDequeueCount": 3,+ "maxPollingInterval": "00:00:02"+ }+ }+}diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex abb6fa4..a965ca2 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -155,8 +155,13 @@ class CosmosDbStore(IStore):calls: list[CallStateModel] = []try:async with self._use_db() as db:+ where_clause = (+ "WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)"+ if phone_number+ else ""+ )items = db.query_items(- query=f"SELECT * FROM c {"WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""} ORDER BY c.created_at DESC OFFSET 0 LIMIT @count",+ query=f"SELECT * FROM c {where_clause} ORDER BY c.created_at DESC OFFSET 0 LIMIT @count",parameters=[{"name": "@phone_number",@@ -185,8 +190,13 @@ class CosmosDbStore(IStore):) -> int:try:async with self._use_db() as db:+ where_clause = (+ "WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)"+ if phone_number+ else ""+ )items = db.query_items(- query=f"SELECT VALUE COUNT(1) FROM c {"WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)" if phone_number else ""}",+ query=f"SELECT VALUE COUNT(1) FROM c {where_clause}",parameters=[{"name": "@phone_number",diff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex a1f2129..947c501 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -112,8 +112,13 @@ class SqliteStore(IStore):) -> Optional[list[CallStateModel]]:calls: list[CallStateModel] = []async with self._use_db() as db:+ where_clause = (+ "WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)"+ if phone_number+ else ""+ )cursor = await db.execute(- f"SELECT data FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""} ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT ?",+ f"SELECT data FROM {self._config.table} {where_clause} ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT ?",((phone_number, # data.initiate.phone_number@@ -139,8 +144,13 @@ class SqliteStore(IStore):phone_number: Optional[str] = None,) -> int:async with self._use_db() as db:+ where_clause = (+ "WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)"+ if phone_number+ else ""+ )cursor = await db.execute(- f"SELECT COUNT(*) FROM {self._config.table} {"WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)" if phone_number else ""}",+ f"SELECT COUNT(*) FROM {self._config.table} {where_clause}",((phone_number, # data.initiate.phone_numberdiff --git a/requirements.txt b/requirements.txtindex a0539c2..d512cac 100644--- a/requirements.txt+++ b/requirements.txt@@ -6,12 +6,13 @@ azure-communication-callautomation==1.2.0azure-communication-sms==1.0.1azure-cosmos==4.7.0azure-eventgrid==4.19.0+azure-functions==1.19.0azure-identity==1.16.0 # Required for all Azure SDKsazure-monitor-opentelemetry==1.4.2azure-search-documents==11.6.0b3+azure-storage-queue==12.10.0django-htmlmin==0.11.0fastapi==0.111.0-gunicorn==22.0.0jinja2==3.1.4json-repair==0.20.1mistune==3.0.2@@ -34,4 +35,3 @@ tenacity==8.3.0tiktoken==0.7.0twilio==9.1.0typing-extensions==4.12.0-uvicorn[standard]==0.30.0 # Required for Gunicorndiff --git a/tests/conftest.py b/tests/conftest.pyindex 780c714..68710b9 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,4 +1,4 @@-from azure.identity import DefaultAzureCredential, get_bearer_token_provider+from azure.identity import ManagedIdentityCredential, get_bearer_token_providerfrom deepeval.models.gpt_model import GPTModelfrom fastapi import BackgroundTasksfrom helpers.config import CONFIG@@ -138,7 +138,7 @@ class DeepEvalAzureOpenAI(GPTModel):"api_key": platform.api_key.get_secret_value() if platform.api_key else None, # type: ignore"azure_ad_token_provider": (get_bearer_token_provider(- DefaultAzureCredential(),+ ManagedIdentityCredential(),"https://cognitiveservices.azure.com/.default",)if not platform.api_key