Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
ops: Add OTEL attributes to follow user flow in App Insights
Clémence Lesné257dca989b28
diff --git a/function_app.py b/function_app.pyindex 5aad47d..93f2302 100644--- a/function_app.py+++ b/function_app.py@@ -15,7 +15,6 @@ from azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNamesfrom htmlmin.minify import html_minifyfrom jinja2 import Environment, FileSystemLoader-from opentelemetry.semconv.trace import SpanAttributesfrom pydantic import TypeAdapter, ValidationErrorfrom twilio.twiml.messaging_response import MessagingResponse@@ -38,7 +37,7 @@ from helpers.call_utils import ContextEnum as CallContextEnumfrom helpers.config import CONFIGfrom helpers.http import azure_transportfrom helpers.logging import logger-from helpers.monitoring import trace+from helpers.monitoring import CallAttributes, span_attribute, tracerfrom helpers.pydantic_types.phone_numbers import PhoneNumberfrom models.call import CallGetModel, CallInitiateModel, CallStateModelfrom models.next import ActionEnum as NextActionEnum@@ -90,6 +89,7 @@ logger.info("Using call event URL %s", _COMMUNICATIONSERVICES_CALLABACK_TPL)"health/liveness",methods=["GET"],)[email protected]_as_current_span("health_liveness_get")async def health_liveness_get(req: func.HttpRequest) -> func.HttpResponse:"""Check if the service is running.@@ -105,6 +105,7 @@ async def health_liveness_get(req: func.HttpRequest) -> func.HttpResponse:"health/readiness",methods=["GET"],)[email protected]_as_current_span("health_readiness_get")async def health_readiness_get(req: func.HttpRequest) -> func.HttpResponse:"""Check if the service is ready to serve requests.@@ -154,6 +155,7 @@ async def health_readiness_get(req: func.HttpRequest) -> func.HttpResponse:methods=["GET"],trigger_arg_name="req",)[email protected]_as_current_span("report_get")async def report_get(req: func.HttpRequest) -> func.HttpResponse:"""List all calls with a web interface.@@ -204,6 +206,7 @@ async def report_get(req: func.HttpRequest) -> func.HttpResponse:methods=["GET"],trigger_arg_name="req",)[email protected]_as_current_span("report_single_get")async def report_single_get(req: func.HttpRequest) -> func.HttpResponse:"""Show a single call with a web interface.@@ -249,6 +252,7 @@ async def report_single_get(req: func.HttpRequest) -> func.HttpResponse:methods=["GET"],trigger_arg_name="req",)[email protected]_as_current_span("call_search_get")async def call_search_get(req: func.HttpRequest) -> func.HttpResponse:"""REST API to search for calls by phone number.@@ -275,6 +279,7 @@ async def call_search_get(req: func.HttpRequest) -> func.HttpResponse:methods=["GET"],trigger_arg_name="req",)[email protected]_as_current_span("call_get")async def call_get(req: func.HttpRequest) -> func.HttpResponse:""" "REST API to get a single call by call ID.@@ -306,6 +311,7 @@ async def call_get(req: func.HttpRequest) -> func.HttpResponse:methods=["POST"],trigger_arg_name="req",)[email protected]_as_current_span("call_post")async def call_post(req: func.HttpRequest) -> func.HttpResponse:"""REST API to initiate a call.@@ -319,9 +325,8 @@ async def call_post(req: func.HttpRequest) -> func.HttpResponse:except ValidationError as e:return _validation_error(e)url, call = await _communicationservices_event_url(initiate.phone_number, initiate)- trace.get_current_span().set_attribute(- SpanAttributes.ENDUSER_ID, call.initiate.phone_number- )+ span_attribute(CallAttributes.CALL_ID, str(call.call_id))+ span_attribute(CallAttributes.CALL_PHONE_NUMBER, call.initiate.phone_number)automation_client = await _use_automation_client()call_connection_properties = await automation_client.create_call(callback_url=url,@@ -348,6 +353,7 @@ async def call_post(req: func.HttpRequest) -> func.HttpResponse:connection="Storage",queue_name=CONFIG.communication_services.call_queue_name,)[email protected]_as_current_span("call_event")async def call_event(call: func.QueueMessage,) -> None:@@ -369,9 +375,8 @@ async def call_event(call_context: str = event.data["incomingCallContext"]phone_number = PhoneNumber(event.data["from"]["phoneNumber"]["value"])url, _call = await _communicationservices_event_url(phone_number)- trace.get_current_span().set_attribute(- SpanAttributes.ENDUSER_ID, _call.initiate.phone_number- )+ span_attribute(CallAttributes.CALL_ID, str(_call.call_id))+ span_attribute(CallAttributes.CALL_PHONE_NUMBER, _call.initiate.phone_number)await on_new_call(callback_url=url,client=await _use_automation_client(),@@ -395,6 +400,7 @@ async def call_event(connection="Storage",queue_name=CONFIG.communication_services.post_queue_name,)[email protected]_as_current_span("sms_event")async def sms_event(post: func.Out[str],sms: func.QueueMessage,@@ -417,13 +423,12 @@ async def sms_event(message: str = event.data["message"]phone_number: str = event.data["from"]+ span_attribute(CallAttributes.CALL_PHONE_NUMBER, phone_number)call = await _db.call_asearch_one(phone_number)if not call:logger.warning("Call for phone number %s not found", phone_number)return- trace.get_current_span().set_attribute(- SpanAttributes.ENDUSER_ID, call.initiate.phone_number- )+ span_attribute(CallAttributes.CALL_ID, str(call.call_id))async def _post_callback(_call: CallStateModel) -> None:_trigger_post_event(call=_call, post=post)@@ -455,6 +460,7 @@ async def sms_event(connection="Storage",queue_name=CONFIG.communication_services.post_queue_name,)[email protected]_as_current_span("communicationservices_event_post")async def communicationservices_event_post(post: func.Out[str],req: func.HttpRequest,@@ -515,6 +521,7 @@ async def _communicationservices_event_worker(Returns None. Can trigger additional events to `trainings` and `post` queues."""+ span_attribute(CallAttributes.CALL_ID, str(call_id))call = await _db.call_aget(call_id)if not call:logger.warning("Call %s not found", call_id)@@ -523,10 +530,7 @@ async def _communicationservices_event_worker(logger.warning("Secret for call %s does not match", call_id)return- # OpenTelemetry- trace.get_current_span().set_attribute(- SpanAttributes.ENDUSER_ID, call.initiate.phone_number- )+ span_attribute(CallAttributes.CALL_PHONE_NUMBER, call.initiate.phone_number)# Event parsingevent = CloudEvent.from_dict(event_dict)assert isinstance(event.data, dict)@@ -656,6 +660,7 @@ async def _communicationservices_event_worker(connection="Storage",queue_name=CONFIG.communication_services.trainings_queue_name,)[email protected]_as_current_span("trainings_event")async def trainings_event(trainings: func.QueueMessage,) -> None:@@ -668,9 +673,8 @@ async def trainings_event("""call = CallStateModel.model_validate_json(trainings.get_body())logger.debug("Trainings event received for call %s", call)- trace.get_current_span().set_attribute(- SpanAttributes.ENDUSER_ID, call.initiate.phone_number- )+ span_attribute(CallAttributes.CALL_ID, str(call.call_id))+ span_attribute(CallAttributes.CALL_PHONE_NUMBER, call.initiate.phone_number)await call.trainings(cache_only=False) # Get trainings by advance to populate cache@@ -679,6 +683,7 @@ async def trainings_event(connection="Storage",queue_name=CONFIG.communication_services.post_queue_name,)[email protected]_as_current_span("post_event")async def post_event(post: func.QueueMessage,) -> None:@@ -689,9 +694,8 @@ async def post_event("""call = CallStateModel.model_validate_json(post.get_body())logger.debug("Post event received for call %s", call)- trace.get_current_span().set_attribute(- SpanAttributes.ENDUSER_ID, call.initiate.phone_number- )+ span_attribute(CallAttributes.CALL_ID, str(call.call_id))+ span_attribute(CallAttributes.CALL_PHONE_NUMBER, call.initiate.phone_number)await on_end_call(call)@@ -758,6 +762,7 @@ async def _communicationservices_event_url(connection="Storage",queue_name=CONFIG.communication_services.post_queue_name,)[email protected]_as_current_span("twilio_sms_post")async def twilio_sms_post(post: func.Out[str],req: func.HttpRequest,@@ -777,15 +782,15 @@ async def twilio_sms_post(message: str = req.form["Body"]except ValueError as e:return _validation_error(e)++ span_attribute(CallAttributes.CALL_PHONE_NUMBER, phone_number)call = await _db.call_asearch_one(phone_number)if not call:logger.warning("Call for phone number %s not found", phone_number)else:- trace.get_current_span().set_attribute(- SpanAttributes.ENDUSER_ID, call.initiate.phone_number- )+ span_attribute(CallAttributes.CALL_ID, str(call.call_id))async def _post_callback(_call: CallStateModel) -> None:_trigger_post_event(call=_call, post=post)diff --git a/helpers/call_events.py b/helpers/call_events.pyindex 580dac6..c278a80 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -19,7 +19,7 @@ from helpers.call_utils import (from helpers.config import CONFIGfrom helpers.llm_worker import completion_syncfrom helpers.logging import logger-from helpers.monitoring import tracer+from helpers.monitoring import CallAttributes, span_attribute, tracerfrom models.call import CallStateModelfrom models.message import (ActionEnum as MessageActionEnum,@@ -124,6 +124,8 @@ async def on_speech_recognized(trainings_callback: Callable[[CallStateModel], Awaitable[None]],) -> None:logger.info("Voice recognition: %s", text)+ span_attribute(CallAttributes.CALL_CHANNEL, "voice")+ span_attribute(CallAttributes.CALL_MESSAGE, text)call.messages.append(MessageModel(content=text,@@ -157,6 +159,7 @@ async def on_recognize_timeout_error(if (contexts and CallContextEnum.IVR_LANG_SELECT in contexts): # Retry IVR recognition+ span_attribute(CallAttributes.CALL_CHANNEL, "ivr")if call.recognition_retry < CONFIG.conversation.voice_recognition_retry_max:call.recognition_retry += 1logger.info(@@ -184,6 +187,7 @@ async def on_recognize_timeout_error(return# Retry voice recognition+ span_attribute(CallAttributes.CALL_CHANNEL, "voice")call.recognition_retry += 1logger.info("Timeout, retrying voice recognition (%s/%s)",@@ -218,6 +222,8 @@ async def on_recognize_unknown_error(client: CallAutomationClient,error_code: int,) -> None:+ span_attribute(CallAttributes.CALL_CHANNEL, "voice")+if error_code == 8511: # Failure while trying to play the promptlogger.warning("Failed to play prompt")else:@@ -225,6 +231,7 @@ async def on_recognize_unknown_error("Recognition failed with unknown error code %s, answering with default error",error_code,)+await handle_recognize_text(call=call,client=client,@@ -242,6 +249,7 @@ async def on_play_completed(post_callback: Callable[[CallStateModel], Awaitable[None]],) -> None:logger.debug("Play completed")+ span_attribute(CallAttributes.CALL_CHANNEL, "voice")if not contexts:return@@ -269,6 +277,7 @@ async def on_play_completed(@tracer.start_as_current_span("on_play_error")async def on_play_error(error_code: int) -> None:logger.debug("Play failed")+ span_attribute(CallAttributes.CALL_CHANNEL, "voice")# See: https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/communication-services/how-tos/call-automation/play-action.mdif error_code == 8535: # Action failed, file formatlogger.warning("Error during media play, file format is invalid")@@ -292,6 +301,9 @@ async def on_ivr_recognized(post_callback: Callable[[CallStateModel], Awaitable[None]],trainings_callback: Callable[[CallStateModel], Awaitable[None]],) -> None:+ logger.info("IVR recognized: %s", label)+ span_attribute(CallAttributes.CALL_CHANNEL, "ivr")+ span_attribute(CallAttributes.CALL_MESSAGE, label)call.recognition_retry = 0 # Reset recognition retry countertry:lang = next(@@ -371,6 +383,8 @@ async def on_sms_received(trainings_callback: Callable[[CallStateModel], Awaitable[None]],) -> bool:logger.info("SMS received from %s: %s", call.initiate.phone_number, message)+ span_attribute(CallAttributes.CALL_CHANNEL, "sms")+ span_attribute(CallAttributes.CALL_MESSAGE, message)call.messages.append(MessageModel(action=MessageActionEnum.SMS,diff --git a/helpers/monitoring.py b/helpers/monitoring.pyindex 8aaeb8d..1d63e73 100644--- a/helpers/monitoring.py+++ b/helpers/monitoring.py@@ -4,6 +4,8 @@ from azure.monitor.opentelemetry import configure_azure_monitorfrom opentelemetry import tracefrom opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentorfrom opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor+from opentelemetry.trace.span import INVALID_SPAN+from opentelemetry.util.types import AttributeValueVERSION = environ.get("VERSION", "0.0.0-unknown")@@ -14,3 +16,30 @@ tracer = trace.get_tracer(instrumenting_library_version=VERSION,instrumenting_module_name="com.github.clemlesne.call-center-ai",) # Create a tracer that will be used in the app+++def span_attribute(key: str, value: AttributeValue) -> None:+ """+ Set an attribute on the current span.++ Prefer using attributes from `opentelemetry.semconv.attributes` when possible.++ Returns None.+ """+ span = trace.get_current_span()+ if span == INVALID_SPAN:+ return+ span.set_attribute(key, value)+++class CallAttributes:+ """+ OpenTelemetry attributes for a call.++ These attributes are used to track a call in the logs and metrics.+ """++ CALL_CHANNEL = "call.channel"+ CALL_ID = "call.id"+ CALL_MESSAGE = "call.message"+ CALL_PHONE_NUMBER = "call.phone_number"