Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
perf: Externalize Event Grid subscription
Clémence Lesné2f60c08bf610
diff --git a/Makefile b/Makefileindex f9ca731..3c3f5ea 100644--- a/Makefile+++ b/Makefile@@ -61,16 +61,43 @@ build:.run:+ @echo "🛠️ Deploying to localhost..."$(docker) run \+ --detach \--env 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 claim-ai-phone-bot \+ --name claim-ai \--publish 8080:8080 \--rm \$(container_name):$(version_small)+ $(MAKE) eventgrid-register \+ endpoint=$(tunnel_url) \+ name=$(tunnel_name) \+ phone_number=$(shell cat config.yaml | yq '.communication_service.phone_number') \+ source="/subscriptions/2e41c463-3dfb-4760-8161-60e8cefa6d28/resourceGroups/claim-ai/providers/Microsoft.Communication/communicationServices/claim-ai"++ @echo "🚀 Claim AI is running on $(tunnel_url)"+ $(docker) attach --name claim-ai+stop:@echo "Stopping container..."- $(docker) stop claim-ai-phone-bot+ $(docker) stop claim-ai++eventgrid-register:+ @echo "⚙️ Deleting previous event grid subscription..."+ az eventgrid event-subscription delete --name $(name) || true++ @echo "⚙️ Creating event grid subscription..."+ az eventgrid event-subscription create \+ --advanced-filter data.to.PhoneNumber.Value StringBeginsWith $(phone_number) \+ --enable-advanced-filtering-on-arrays true \+ --endpoint $(endpoint)/call/inbound \+ --event-delivery-schema eventgridschema \+ --event-ttl 3 \+ --included-event-types Microsoft.Communication.IncomingCall \+ --max-delivery-attempts 8 \+ --name $(name) \+ --source-resource-id $(source)diff --git a/main.py b/main.pyindex 9aa1b7c..aabbafe 100644--- a/main.py+++ b/main.py@@ -13,8 +13,6 @@ from azure.core.exceptions import ResourceNotFoundErrorfrom azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNamesfrom azure.identity import DefaultAzureCredential, get_bearer_token_provider-from azure.mgmt.core.polling.arm_polling import ARMPolling-from azure.mgmt.eventgrid import EventGridManagementClientfrom contextlib import asynccontextmanagerfrom datetime import datetimefrom enum import Enum@@ -38,7 +36,6 @@ from models.claim import ClaimModelfrom openai import AsyncAzureOpenAIfrom os import environfrom uuid import UUID, uuid4-import asyncioimport jsonimport sqlite3@@ -59,10 +56,6 @@ oai_gpt = AsyncAzureOpenAI(azure_deployment=CONFIG.openai.gpt_deployment,)eventgrid_subscription_name = f"tmp-{uuid4()}"-eventgrid_mgmt_client = EventGridManagementClient(- credential=DefaultAzureCredential(),- subscription_id=CONFIG.eventgrid.subscription_id,-)source_caller = PhoneNumberIdentifier(CONFIG.communication_service.phone_number)# Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)call_automation_client = CallAutomationClient(@@ -89,10 +82,7 @@ class Context(str, Enum):@asynccontextmanagerasync def lifespan(_: FastAPI):init_db()- task = asyncio.create_task(eventgrid_register()) # Background taskyield- task.cancel()- eventgrid_unregister() # Foreground taskapi = FastAPI(@@ -118,56 +108,6 @@ api.add_middleware()-async def eventgrid_register() -> None:- def callback(future: ARMPolling):- _logger.info(f"Event Grid subscription created (status {future.status()})")-- _logger.info(f"Creating Event Grid subscription {eventgrid_subscription_name}")- eventgrid_mgmt_client.system_topic_event_subscriptions.begin_create_or_update(- resource_group_name=CONFIG.eventgrid.resource_group,- system_topic_name=CONFIG.eventgrid.system_topic,- event_subscription_name=eventgrid_subscription_name,- event_subscription_info={- "properties": {- "eventDeliverySchema": "EventGridSchema",- "retryPolicy": {- "maxDeliveryAttempts": 8,- "eventTimeToLiveInMinutes": 3, # Call are real time, no need to wait- },- "destination": {- "endpointType": "WebHook",- "properties": {- "endpointUrl": CALL_INBOUND_URL,- "maxEventsPerBatch": 1,- },- },- "filter": {- "enableAdvancedFilteringOnArrays": True,- "includedEventTypes": ["Microsoft.Communication.IncomingCall"],- "advancedFilters": [- {- "key": "data.to.PhoneNumber.Value",- "operatorType": "StringBeginsWith",- "values": [CONFIG.communication_service.phone_number],- }- ],- },- },- },- ).add_done_callback(callback)---def eventgrid_unregister() -> None:- _logger.info(- f"Deleting Event Grid subscription {eventgrid_subscription_name} (do not wait for completion)"- )- eventgrid_mgmt_client.system_topic_event_subscriptions.begin_delete(- event_subscription_name=eventgrid_subscription_name,- resource_group_name=CONFIG.eventgrid.resource_group,- system_topic_name=CONFIG.eventgrid.system_topic,- )--@api.get("/health/liveness",status_code=status.HTTP_204_NO_CONTENT,diff --git a/requirements.txt b/requirements.txtindex 73365bb..def3e55 100644--- a/requirements.txt+++ b/requirements.txt@@ -2,7 +2,6 @@ azure-communication-callautomation==1.1.0azure-communication-sms==1.0.1azure-eventgrid==4.16.0azure-identity==1.15.0-azure-mgmt-eventgrid==10.2.0fastapi==0.108.0openai==1.7.1phonenumbers==8.13.27