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

refacto: Application Insights integration and client ID attribute

Clémence Lesné799437045d3f
diff --git a/README.md b/README.md
index f1b6829..a0eb866 100644
--- a/README.md
+++ b/README.md
@@ -297,10 +297,6 @@ Place a file called `config.yaml` in the root of the project with the following
```yaml
# config.yaml
-monitoring:
- application_insights:
- connection_string: xxx
-
resources:
public_url: "https://xxx.blob.core.windows.net/public"
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 6da5f6b..b6b6f8a 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -27,11 +27,6 @@ var localConfig = loadYamlContent('../config.yaml')
var phonenumberSanitized = replace(localConfig.communication_services.phone_number, '+', '')
var config = {
public_domain: appUrl
- monitoring: {
- application_insights: {
- connection_string: applicationInsights.properties.ConnectionString
- }
- }
database: {
mode: 'cosmos_db'
cosmos_db: {
@@ -174,16 +169,15 @@ resource functionApp 'Microsoft.Web/sites@2023-12-01' = {
name: 'AzureWebJobsStorage__accountName'
value: storageAccount.name
}
- // See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#appinsights_instrumentationkey
+ // See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#applicationinsights_connection_string
{
- name: 'APPINSIGHTS_INSTRUMENTATIONKEY'
- value: applicationInsights.properties.InstrumentationKey
+ name: 'APPLICATIONINSIGHTS_CONNECTION_STRING'
+ value: applicationInsights.properties.ConnectionString
}
- // Threadpool for async tasks
- // See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-app-settings#python_threadpool_thread_count
+ // See: https://learn.microsoft.com/en-us/azure/azure-monitor/app/opentelemetry-configuration?tabs=python#enable-sampling
{
- name: 'PYTHON_THREADPOOL_THREAD_COUNT'
- value: '4'
+ name: 'OTEL_TRACES_SAMPLER_ARG'
+ value: '0.5'
}
{
name: 'CONFIG_JSON'
diff --git a/function_app.py b/function_app.py
index b4ed3ef..98bc4ff 100644
--- a/function_app.py
+++ b/function_app.py
@@ -1,5 +1,5 @@
# First imports, to make sure the following logs are first
-from helpers.logging import logger, APP_NAME
+from helpers.logging import logger, APP_NAME, trace
from helpers.config import CONFIG
@@ -46,6 +46,8 @@ from models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatu
from pydantic import TypeAdapter, ValidationError
import azure.functions as func
import json
+from os import getenv
+from opentelemetry.semconv.trace import SpanAttributes
# Jinja configuration
@@ -153,7 +155,9 @@ async def report_get(req: func.HttpRequest) -> func.HttpResponse:
)
template = _jinja.get_template("list.html.jinja")
render = await template.render_async(
- application_insights_connection_string=CONFIG.monitoring.application_insights.connection_string.get_secret_value(),
+ applicationinsights_connection_string=getenv(
+ "APPLICATIONINSIGHTS_CONNECTION_STRING"
+ ),
calls=calls or [],
count=count,
phone_number=phone_number,
@@ -187,7 +191,9 @@ async def report_single_get(req: func.HttpRequest) -> func.HttpResponse:
)
template = _jinja.get_template("single.html.jinja")
render = await template.render_async(
- application_insights_connection_string=CONFIG.monitoring.application_insights.connection_string.get_secret_value(),
+ applicationinsights_connection_string=getenv(
+ "APPLICATIONINSIGHTS_CONNECTION_STRING"
+ ),
bot_company=call.initiate.bot_company,
bot_name=call.initiate.bot_name,
call=call,
@@ -257,6 +263,9 @@ async def call_post(req: func.HttpRequest) -> func.HttpResponse:
except Exception 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
+ )
call_connection_properties = _automation_client.create_call(
callback_url=url,
cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,
@@ -291,7 +300,10 @@ async def call_event(
call_context: str = event.data["incomingCallContext"]
phone_number = PhoneNumber(event.data["from"]["phoneNumber"]["value"])
- url, _ = await _communicationservices_event_url(phone_number)
+ url, _call = await _communicationservices_event_url(phone_number)
+ trace.get_current_span().set_attribute(
+ SpanAttributes.ENDUSER_ID, _call.initiate.phone_number
+ )
await on_new_call(
callback_url=url,
client=_automation_client,
@@ -334,6 +346,9 @@ async def sms_event(
if not call:
logger.warning(f"Call for phone number {phone_number} not found")
return
+ trace.get_current_span().set_attribute(
+ SpanAttributes.ENDUSER_ID, call.initiate.phone_number
+ )
await on_sms_received(
call=call,
client=_automation_client,
@@ -400,6 +415,9 @@ async def _communicationservices_event_worker(
logger.warning(f"Secret for call {call_id} does not match")
return
+ trace.get_current_span().set_attribute(
+ SpanAttributes.ENDUSER_ID, call.initiate.phone_number
+ )
event = CloudEvent.from_dict(event_dict)
assert isinstance(event.data, dict)
@@ -531,6 +549,9 @@ async def trainings_event(
) -> None:
call = CallStateModel.model_validate_json(trainings.get_body())
logger.debug(f"Trainings event received for call {call}")
+ trace.get_current_span().set_attribute(
+ SpanAttributes.ENDUSER_ID, call.initiate.phone_number
+ )
await call.trainings() # Get trainings by advance to populate cache
@@ -544,6 +565,9 @@ async def post_event(
) -> None:
call = CallStateModel.model_validate_json(post.get_body())
logger.debug(f"Post event received for call {call}")
+ trace.get_current_span().set_attribute(
+ SpanAttributes.ENDUSER_ID, call.initiate.phone_number
+ )
await on_end_call(call)
@@ -629,6 +653,9 @@ async def twilio_sms_post(
if not call:
logger.warning(f"Call for phone number {phone_number} not found")
else:
+ trace.get_current_span().set_attribute(
+ SpanAttributes.ENDUSER_ID, call.initiate.phone_number
+ )
event_status = await on_sms_received(
call=call,
message=message,
diff --git a/helpers/config_models/monitoring.py b/helpers/config_models/monitoring.py
index 1bf7855..5933d3b 100644
--- a/helpers/config_models/monitoring.py
+++ b/helpers/config_models/monitoring.py
@@ -1,9 +1,5 @@
from enum import Enum
-from pydantic import BaseModel, SecretStr
-
-
-class ApplicationInsightsModel(BaseModel):
- connection_string: SecretStr
+from pydantic import BaseModel
class LoggingLevelEnum(str, Enum):
@@ -23,4 +19,3 @@ class LoggingModel(BaseModel):
class MonitoringModel(BaseModel):
logging: LoggingModel = LoggingModel() # Object is fully defined by default
- application_insights: ApplicationInsightsModel
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index 8287ec5..41a9f7c 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -37,7 +37,9 @@ class RootModel(BaseSettings):
content_safety: ContentSafetyModel
database: DatabaseModel = DatabaseModel() # Object is fully defined by default
llm: LlmModel
- monitoring: MonitoringModel
+ monitoring: MonitoringModel = (
+ MonitoringModel()
+ ) # Object is fully defined by default
prompts: PromptsModel = PromptsModel() # Object is fully defined by default
resources: ResourcesModel
sms: SmsModel = SmsModel() # Object is fully defined by default
diff --git a/helpers/logging.py b/helpers/logging.py
index d8184f8..497f249 100644
--- a/helpers/logging.py
+++ b/helpers/logging.py
@@ -1,10 +1,10 @@
from azure.monitor.opentelemetry import configure_azure_monitor
from helpers.config import CONFIG
-from logging import Logger, getLogger, basicConfig
+from logging import getLogger, basicConfig
from opentelemetry import trace
from opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentor
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
-from os import environ
+from os import getenv
APP_NAME = "call-center-ai"
@@ -15,10 +15,9 @@ logger = getLogger(APP_NAME)
logger.setLevel(CONFIG.monitoring.logging.app_level.value)
# OpenTelemetry
-environ["OTEL_TRACES_SAMPLER_ARG"] = str(0.5) # Sample 50% of traces
configure_azure_monitor(
- connection_string=CONFIG.monitoring.application_insights.connection_string.get_secret_value(),
-) # Configure Azure monitor collection
+ connection_string=getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"),
+) # Configure Azure Application Insights exporter
AioHttpClientInstrumentor().instrument() # Instrument aiohttp
HTTPXClientInstrumentor().instrument() # Instrument httpx
tracer = trace.get_tracer(
diff --git a/host.json b/host.json
index 03d5449..2c2391f 100644
--- a/host.json
+++ b/host.json
@@ -9,7 +9,7 @@
"logLevel": {
"default": "Warning",
"Function": "Information",
- "Host.Results": "Information"
+ "Host.Results": "Warning"
}
},
"extensions": {
diff --git a/public_website/templates/base.html.jinja b/public_website/templates/base.html.jinja
index 690b848..61ad257 100644
--- a/public_website/templates/base.html.jinja
+++ b/public_website/templates/base.html.jinja
@@ -10,7 +10,7 @@
crossOrigin: "anonymous",
cr: true,
cfg: { // Application Insights Configuration
- connectionString: "{{ application_insights_connection_string }}",
+ connectionString: "{{ applicationinsights_connection_string }}",
}
});
</script>
diff --git a/requirements.txt b/requirements.txt
index d4526cb..674e17f 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -21,6 +21,7 @@ opentelemetry-instrumentation-httpx==0.45b0
opentelemetry-instrumentation-openai==0.21.0
opentelemetry-instrumentation-redis==0.45b0
opentelemetry-instrumentation-sqlite3==0.45b0
+opentelemetry-semantic-conventions==0.45b0
phonenumbers==8.13.37 # Required for pydantic-extra-types
pydantic-extra-types==2.7.0 # Required for pydantic
pydantic-settings==2.2.1