Skip to content

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/.funcignore
new file mode 100644
index 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__/
+*.pyc
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index bd7cf87..8eeac22 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -10,8 +10,3 @@ updates:
target-branch: develop
schedule:
interval: daily
- - package-ecosystem: docker
- directory: ""
- target-branch: develop
- schedule:
- interval: daily
diff --git a/.github/workflows/pipeline.yaml b/.github/workflows/pipeline.yaml
index 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-verified
head: 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 - Semgrep
runs-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 Security
continue-on-error: true
env:
- SEMGREP_RULES: p/cwe-top-25 p/owasp-top-ten p/dockerfile
+ SEMGREP_RULES: p/cwe-top-25 p/owasp-top-ten
run: semgrep ci --sarif --output=semgrep.sarif
- name: Upload results to GitHub Security
@@ -158,7 +82,6 @@ jobs:
create-release:
name: Create release
needs:
- - build-image
- init
permissions:
# Allow to create releases
diff --git a/.gitignore b/.gitignore
index 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 file
config*.yaml
@@ -10,8 +11,12 @@ config*.yaml
# Test reports
test-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,azurefunctions
diff --git a/.python-version b/.python-version
index 9a941ac..ff7de60 100644
--- a/.python-version
+++ b/.python-version
@@ -1 +1 @@
-callcenterai312
+callcenterai311
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
index 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/Dockerfile
deleted file mode 100644
index 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/Makefile
index 3d1c0d7..8f703ad 100644
--- a/Makefile
+++ b/Makefile
@@ -1,6 +1,3 @@
-# Container configuration
-container_name := ghcr.io/clemlesne/call-center-ai
-docker := docker
# Versioning
version_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 := westeurope
cognitive_communication_location := westeurope
+default_location := westeurope
+functionapp_location := swedencentral
openai_location := southcentralus
search_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 -m
install:
- @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 8080
deploy:
@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) \
+ --browser
twilio-register:
@echo "⚙️ Registering Twilio webhook..."
diff --git a/README.md b/README.md
index 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 server
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 69ee049..49630f4 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -1,30 +1,31 @@
param adaModel string
param adaVersion string
param cognitiveCommunicationLocation string
+param functionappLocation string
param gptBackupContext int
param gptBackupModel string
param gptBackupVersion string
param gptContext int
param gptModel string
param gptVersion string
-param imageVersion string
param location string
param moderationBlocklists array
param openaiLocation string
param searchLocation string
param 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 version
var localConfig = loadYamlContent('../config.yaml')
var config = {
- api: {
- events_domain: appUrl
- }
+ public_domain: appUrl
monitoring: {
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.hostName
phone_number: localConfig.communication_service.phone_number
+ queue_name: communicationServicesQueue.name
}
sms: localConfig.sms
cognitive_service: {
@@ -112,10 +114,11 @@ var config = {
output appUrl string = appUrl
output 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: prefix
location: location
tags: 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: functionappLocation
tags: 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: functionappLocation
tags: 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: blobService
name: '$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: communicationServices
properties: {
- principalId: containerApp.identity.principalId
+ principalId: functionApp.identity.principalId
principalType: '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: prefix
location: 'global'
tags: tags
+ identity: {
+ type: 'SystemAssigned'
+ }
properties: {
- source: communication.id
+ source: communicationServices.id
topicType: '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 User
resource 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: cognitiveCommunication
properties: {
- principalId: communication.identity.principalId
+ principalId: communicationServices.identity.principalId
principalType: 'ServicePrincipal'
roleDefinitionId: roleCognitiveUser.id
}
@@ -328,15 +482,16 @@ resource cognitiveContentsafety 'Microsoft.CognitiveServices/accounts@2023-10-01
}
}
+// Cognitive Services OpenAI Contributor
resource 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: cognitiveOpenai
properties: {
- principalId: containerApp.identity.principalId
+ principalId: functionApp.identity.principalId
principalType: 'ServicePrincipal'
roleDefinitionId: roleOpenaiContributor.id
}
@@ -358,6 +513,7 @@ resource cognitiveOpenai 'Microsoft.CognitiveServices/accounts@2023-10-01-previe
resource gpt 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
parent: cognitiveOpenai
name: gptModelFullName
+ tags: tags
sku: {
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-previe
resource gptBackup 'Microsoft.CognitiveServices/accounts/deployments@2023-10-01-preview' = {
parent: cognitiveOpenai
name: gptBackupModelFullName
+ tags: tags
sku: {
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: cognitiveOpenai
name: adaModelFullName
+ tags: tags
sku: {
capacity: 150
name: '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: appName
properties: {
resource: {
- id: 'call-center-ai'
+ id: appName
}
}
}
diff --git a/bicep/main.bicep b/bicep/main.bicep
index 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 string
param gptBackupContext int = 16385
param gptBackupModel string = 'gpt-35-turbo'
param gptBackupVersion string = '0125'
param gptContext int = 128000
param gptModel string = 'gpt-4o'
param gptVersion string = '2024-05-13'
-param imageVersion string = 'main'
param instance string = deployment().name
param location string = deployment().location
param openaiLocation string
param searchLocation string
+param version string
targetScope = 'subscription'
output appUrl string = app.outputs.appUrl
output blobStoragePublicName string = app.outputs.blobStoragePublicName
output communicationId string = app.outputs.communicationId
-output logAnalyticsWorkspaceCustomerId string = app.outputs.logAnalyticsWorkspaceCustomerId
+output functionAppName string = app.outputs.functionAppName
+output logAnalyticsCustomerId string = app.outputs.logAnalyticsCustomerId
var tags = {
application: 'call-center-ai'
instance: instance
managed_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: adaModel
adaVersion: adaVersion
cognitiveCommunicationLocation: cognitiveCommunicationLocation
+ functionappLocation: functionappLocation
gptBackupContext: gptBackupContext
gptBackupModel: gptBackupModel
gptBackupVersion: gptBackupVersion
gptContext: gptContext
gptModel: gptModel
gptVersion: gptVersion
- imageVersion: imageVersion
location: location
moderationBlocklists: []
openaiLocation: openaiLocation
searchLocation: searchLocation
tags: tags
+ version: version
}
}
diff --git a/main.py b/function_app.py
similarity index 87%
rename from main.py
rename to function_app.py
index 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, ReadinessStatus
from 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",
+ 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.py
index 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.py
deleted file mode 100644
index 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.py
index 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: SecretStr
endpoint: str
phone_number: PhoneNumber
+ queue_name: str
diff --git a/helpers/config_models/llm.py b/helpers/config_models/llm.py
index 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_provider
from contextlib import asynccontextmanager
from enum import Enum
from 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 None
token_func = (
get_bearer_token_provider(
- DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
+ ManagedIdentityCredential(),
+ "https://cognitiveservices.azure.com/.default",
)
if not self.api_key
else None
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index 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 AiSearchModel
from helpers.config_models.ai_translation import AiTranslationModel
-from helpers.config_models.api import ApiModel
from helpers.config_models.cache import CacheModel
from helpers.config_models.cognitive_service import CognitiveServiceModel
from 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 fields
ai_search: AiSearchModel
ai_translation: AiTranslationModel
- api: ApiModel = ApiModel() # Object is fully defined by default
cache: CacheModel = CacheModel() # Object is fully defined by default
cognitive_service: CognitiveServiceModel
communication_service: CommunicationServiceModel
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index 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 ReminderModel
from openai.types.chat import ChatCompletionToolParam
from pydantic import ValidationError
-from typing import Awaitable, Callable, Annotated, Literal, TypedDict
+from typing import Awaitable, Callable, Annotated, Literal
+from typing_extensions import TypedDict
import asyncio
diff --git a/host.json b/host.json
new file mode 100644
index 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.py
index 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.py
index 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_number
diff --git a/requirements.txt b/requirements.txt
index a0539c2..d512cac 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -6,12 +6,13 @@ azure-communication-callautomation==1.2.0
azure-communication-sms==1.0.1
azure-cosmos==4.7.0
azure-eventgrid==4.19.0
+azure-functions==1.19.0
azure-identity==1.16.0 # Required for all Azure SDKs
azure-monitor-opentelemetry==1.4.2
azure-search-documents==11.6.0b3
+azure-storage-queue==12.10.0
django-htmlmin==0.11.0
fastapi==0.111.0
-gunicorn==22.0.0
jinja2==3.1.4
json-repair==0.20.1
mistune==3.0.2
@@ -34,4 +35,3 @@ tenacity==8.3.0
tiktoken==0.7.0
twilio==9.1.0
typing-extensions==4.12.0
-uvicorn[standard]==0.30.0 # Required for Gunicorn
diff --git a/tests/conftest.py b/tests/conftest.py
index 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_provider
from deepeval.models.gpt_model import GPTModel
from fastapi import BackgroundTasks
from 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