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

feat: Add tracing with App Insights

Clémence Lesné089631b59e82
diff --git a/README.md b/README.md
index 8fa66d1..856105f 100644
--- a/README.md
+++ b/README.md
@@ -60,6 +60,7 @@ Extract of the data stored during the call:
- [x] Has access to a documentation database (few-shot training / RAG)
- [x] Help the user to find the information needed to complete the claim
- [x] Lower AI Search cost by usign a Redis cache
+- [x] Monitoring and tracing with Application Insights
- [x] Responses are streamed from the LLM to the user, to avoid long pauses
- [x] Send a SMS report after the call
- [x] Take back a conversation after a disengagement
@@ -247,6 +248,10 @@ 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 9a16826..6a9d6a7 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -26,6 +26,11 @@ var config = {
api: {
events_domain: appUrl
}
+ monitoring: {
+ application_insights: {
+ connection_string: applicationInsights.properties.ConnectionString
+ }
+ }
database: {
mode: 'cosmos_db'
cosmos_db: {
@@ -107,6 +112,17 @@ resource logAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2022-10
}
}
+resource applicationInsights 'Microsoft.Insights/components@2020-02-02' = {
+ name: prefix
+ location: location
+ tags: tags
+ kind: 'web'
+ properties: {
+ Application_Type: 'web'
+ WorkspaceResourceId: logAnalyticsWorkspace.id
+ }
+}
+
resource acaEnv 'Microsoft.App/managedEnvironments@2023-05-01' = {
name: prefix
location: location
diff --git a/helpers/call_events.py b/helpers/call_events.py
index 41910e8..5ffe0cf 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -6,7 +6,7 @@ from azure.communication.callautomation import (
PhoneNumberIdentifier,
)
from helpers.config import CONFIG
-from helpers.logging import build_logger
+from helpers.logging import build_logger, TRACER
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
@@ -40,6 +40,7 @@ _sms_client = SmsClient(
_db = CONFIG.database.instance()
[email protected]_as_current_span("on_new_call")
async def on_new_call(
client: CallAutomationClient, context: str, phone_number: str, callback_url: str
) -> bool:
@@ -73,6 +74,7 @@ async def on_new_call(
return False
[email protected]_as_current_span("on_call_connected")
async def on_call_connected(
call: CallModel,
client: CallConnectionClient,
@@ -93,6 +95,7 @@ async def on_call_connected(
) # Every time a call is answered, confirm the language
[email protected]_as_current_span("on_call_disconnected")
async def on_call_disconnected(
background_tasks: BackgroundTasks,
call: CallModel,
@@ -102,6 +105,7 @@ async def on_call_disconnected(
await _handle_hangup(background_tasks, client, call)
[email protected]_as_current_span("on_speech_recognized")
async def on_speech_recognized(
background_tasks: BackgroundTasks,
call: CallModel,
@@ -118,6 +122,7 @@ async def on_speech_recognized(
)
[email protected]_as_current_span("on_speech_timeout_error")
async def on_speech_timeout_error(
call: CallModel,
client: CallConnectionClient,
@@ -140,6 +145,7 @@ async def on_speech_timeout_error(
)
[email protected]_as_current_span("on_speech_unknown_error")
async def on_speech_unknown_error(
call: CallModel,
client: CallConnectionClient,
@@ -159,6 +165,7 @@ async def on_speech_unknown_error(
)
[email protected]_as_current_span("on_play_completed")
async def on_play_completed(
background_tasks: BackgroundTasks,
call: CallModel,
@@ -181,6 +188,7 @@ async def on_play_completed(
)
[email protected]_as_current_span("on_play_error")
async def on_play_error(
error_code: int,
) -> None:
@@ -200,6 +208,7 @@ async def on_play_error(
_logger.warning(f"Error during media play, unknown error code {error_code}")
[email protected]_as_current_span("on_ivr_recognized")
async def on_ivr_recognized(
client: CallConnectionClient,
call: CallModel,
@@ -242,11 +251,13 @@ async def on_ivr_recognized(
)
[email protected]_as_current_span("on_transfer_completed")
async def on_transfer_completed() -> None:
_logger.info("Call transfer accepted event")
# TODO: Is there anything to do here?
[email protected]_as_current_span("on_transfer_error")
async def on_transfer_error(
call: CallModel,
client: CallConnectionClient,
diff --git a/helpers/config.py b/helpers/config.py
index 4c2df7d..c981f0b 100644
--- a/helpers/config.py
+++ b/helpers/config.py
@@ -11,8 +11,8 @@ import os
import yaml
-CONFIG_ENV = "CONFIG_JSON"
-CONFIG_FILE = "config.yaml"
+_CONFIG_ENV = "CONFIG_JSON"
+_CONFIG_FILE = "config.yaml"
class ConfigNotFound(Exception):
@@ -23,15 +23,15 @@ class ConfigBadFormat(Exception):
pass
-if CONFIG_ENV in os.environ:
- CONFIG = RootModel.model_validate_json(os.environ[CONFIG_ENV])
- print(f'Config from env "{CONFIG_ENV}" loaded')
+if _CONFIG_ENV in os.environ:
+ CONFIG = RootModel.model_validate_json(os.environ[_CONFIG_ENV])
+ print(f'Config from env "{_CONFIG_ENV}" loaded')
else:
- print(f'Config from env "{CONFIG_ENV}" not found')
- path = find_dotenv(filename=CONFIG_FILE)
+ print(f'Config from env "{_CONFIG_ENV}" not found')
+ path = find_dotenv(filename=_CONFIG_FILE)
if not path:
- raise ConfigNotFound(f'Cannot find config file "{CONFIG_FILE}"')
+ raise ConfigNotFound(f'Cannot find config file "{_CONFIG_FILE}"')
try:
with open(path, "r", encoding="utf-8") as f:
CONFIG = RootModel.model_validate(yaml.safe_load(f))
diff --git a/helpers/config_models/monitoring.py b/helpers/config_models/monitoring.py
index fee328c..c1416f6 100644
--- a/helpers/config_models/monitoring.py
+++ b/helpers/config_models/monitoring.py
@@ -1,5 +1,10 @@
from enum import Enum
-from pydantic import BaseModel
+from typing import Optional
+from pydantic import BaseModel, SecretStr
+
+
+class ApplicationInsightsModel(BaseModel):
+ connection_string: SecretStr
class LoggingLevelEnum(str, Enum):
@@ -12,12 +17,11 @@ class LoggingLevelEnum(str, Enum):
WARNING = "WARNING"
-class LoggingMonitoringModel(BaseModel):
+class LoggingModel(BaseModel):
app_level: LoggingLevelEnum = LoggingLevelEnum.INFO
sys_level: LoggingLevelEnum = LoggingLevelEnum.WARNING
class MonitoringModel(BaseModel):
- logging: LoggingMonitoringModel = (
- LoggingMonitoringModel()
- ) # Object is fully defined by default
+ 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 3db5d98..33ec121 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -34,9 +34,7 @@ class RootModel(BaseSettings):
communication_service: CommunicationServiceModel
content_safety: ContentSafetyModel
database: DatabaseModel = DatabaseModel() # Object is fully defined by default
- monitoring: MonitoringModel = (
- MonitoringModel()
- ) # Object is fully defined by default
+ monitoring: MonitoringModel
openai: OpenAiModel
prompts: PromptsModel = PromptsModel() # Object is fully defined by default
resources: ResourcesModel
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 9ba95b2..368396d 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -10,7 +10,7 @@ from azure.core.exceptions import HttpResponseError
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from helpers.config import CONFIG
from contextlib import asynccontextmanager
-from helpers.logging import build_logger
+from helpers.logging import build_logger, TRACER
from openai import AsyncAzureOpenAI, AsyncStream, RateLimitError, APIError
from openai.types.chat import (
ChatCompletionAssistantMessageParam,
@@ -59,6 +59,7 @@ class SafetyCheckError(Exception):
stop=stop_after_attempt(3),
wait=wait_random_exponential(multiplier=0.5, max=30),
)
[email protected]_as_current_span("completion_stream")
async def completion_stream(
is_backup: bool,
max_tokens: int,
@@ -125,6 +126,7 @@ async def completion_stream(
stop=stop_after_attempt(3),
wait=wait_random_exponential(multiplier=0.5, max=30),
)
[email protected]_as_current_span("completion_sync")
async def completion_sync(
max_tokens: int,
messages: list[MessageModel],
@@ -183,6 +185,7 @@ async def completion_sync(
stop=stop_after_attempt(3),
wait=wait_random_exponential(multiplier=0.5, max=30),
)
[email protected]_as_current_span("completion_model_sync")
async def completion_model_sync(
max_tokens: int,
messages: list[MessageModel],
@@ -255,6 +258,7 @@ def _prepare_messages(
]
[email protected]_as_current_span("safety_check")
async def safety_check(text: str) -> None:
"""
Raise `SafetyCheckError` if the text is safe, nothing otherwise.
diff --git a/helpers/logging.py b/helpers/logging.py
index 71fdf66..91fb34b 100644
--- a/helpers/logging.py
+++ b/helpers/logging.py
@@ -1,14 +1,30 @@
+from azure.monitor.opentelemetry import configure_azure_monitor
from helpers.config import CONFIG
from logging import Logger, getLogger, basicConfig
+from opentelemetry import trace
+from opentelemetry.instrumentation.aiohttp_client import AioHttpClientInstrumentor
+from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
-LOGGING_APP_LEVEL = CONFIG.monitoring.logging.app_level.value
-LOGGING_SYS_LEVEL = CONFIG.monitoring.logging.sys_level.value
+configure_azure_monitor(
+ connection_string=CONFIG.monitoring.application_insights.connection_string.get_secret_value(),
+) # Configure Azure monitor collection
+AioHttpClientInstrumentor().instrument() # Instrument aiohttp
+HTTPXClientInstrumentor().instrument() # Instrument httpx
-basicConfig(level=LOGGING_SYS_LEVEL)
+_LOGGING_APP_LEVEL = CONFIG.monitoring.logging.app_level.value
+_LOGGING_SYS_LEVEL = CONFIG.monitoring.logging.sys_level.value
+
+basicConfig(level=_LOGGING_SYS_LEVEL)
+
+# Creates a tracer from the global tracer provider
+TRACER = trace.get_tracer(
+ instrumenting_library_version=CONFIG.version,
+ instrumenting_module_name="com.github.clemlesne.claim-ai",
+)
def build_logger(name: str) -> Logger:
logger = getLogger(name)
- logger.setLevel(LOGGING_APP_LEVEL)
+ logger.setLevel(_LOGGING_APP_LEVEL)
return logger
diff --git a/main.py b/main.py
index 2f3746b..445ef08 100644
--- a/main.py
+++ b/main.py
@@ -44,6 +44,7 @@ from helpers.call_events import (
on_transfer_error,
)
import html
+from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
# Jinja configuration
@@ -86,6 +87,9 @@ api = FastAPI(
version=CONFIG.version,
)
+# OpenTelemetry
+FastAPIInstrumentor.instrument_app(api)
+
assert CONFIG.api.events_domain, "api.events_domain config is not set"
_CALL_EVENT_URL = urljoin(
diff --git a/models/message.py b/models/message.py
index abdadc6..3b592f1 100644
--- a/models/message.py
+++ b/models/message.py
@@ -12,6 +12,7 @@ from inspect import getmembers, isfunction
from json_repair import repair_json
from openai.types.chat.chat_completion_chunk import ChoiceDeltaToolCall
import re
+import json
_FUNC_NAME_SANITIZER_R = r"[^a-zA-Z0-9_-]"
@@ -87,7 +88,7 @@ class ToolModel(BaseModel):
return self
async def execute_function(self, plugins: object) -> None:
- from helpers.logging import build_logger
+ from helpers.logging import build_logger, TRACER
logger = build_logger(__name__)
json_str = self.function_arguments
@@ -107,15 +108,20 @@ class ToolModel(BaseModel):
self.content = f"Bad arguments, available are {ToolModel._available_function_names()}. Please try again."
return
- try:
- res = await getattr(plugins, name)(**args)
- logger.info(f"Executing function {name} ({args}): {res[:20]}...{res[-20:]}")
- except Exception as e:
- logger.warn(
- f"Error executing function {self.function_name} with args {args}: {e}"
- )
- res = f"Error: {e}. Please try again."
- self.content = res
+ with TRACER.start_as_current_span("execute_function") as span:
+ span.set_attribute("name", name)
+ span.set_attribute("args", json.dumps(args))
+ try:
+ res = await getattr(plugins, name)(**args)
+ logger.info(
+ f"Executing function {name} ({args}): {res[:20]}...{res[-20:]}"
+ )
+ except Exception as e:
+ logger.warn(
+ f"Error executing function {self.function_name} with args {args}: {e}"
+ )
+ res = f"Error: {e}. Please try again."
+ self.content = res
@staticmethod
def _available_function_names() -> list[str]:
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index d0b7018..654e662 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -2,7 +2,6 @@ from azure.core.exceptions import ServiceResponseError
from azure.cosmos.aio import CosmosClient, ContainerProxy
from azure.cosmos.exceptions import CosmosHttpResponseError
from contextlib import asynccontextmanager
-from datetime import datetime, timedelta
from fastapi.encoders import jsonable_encoder
from helpers.config import CONFIG
from helpers.config_models.database import CosmosDbModel
diff --git a/persistence/redis.py b/persistence/redis.py
index ef21223..385360f 100644
--- a/persistence/redis.py
+++ b/persistence/redis.py
@@ -1,6 +1,7 @@
from contextlib import asynccontextmanager
from helpers.config_models.cache import RedisModel
from helpers.logging import build_logger
+from opentelemetry.instrumentation.redis import RedisInstrumentor
from persistence.icache import ICache
from redis.asyncio import Redis
from redis.asyncio.retry import Retry
@@ -10,6 +11,9 @@ from typing import AsyncGenerator, Optional, Union
import hashlib
+# Instrument redis
+RedisInstrumentor().instrument()
+
_logger = build_logger(__name__)
_retry = Retry(ExponentialBackoff(), 3)
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index 2c169ef..e8b24ca 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -5,6 +5,7 @@ from helpers.config import CONFIG
from helpers.config_models.database import SqliteModel
from helpers.logging import build_logger
from models.call import CallModel
+from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor
from persistence.istore import IStore
from pydantic import ValidationError
from typing import AsyncGenerator, Optional
@@ -13,6 +14,9 @@ import json
import os
+# Instrument sqlite
+SQLite3Instrumentor().instrument()
+
_logger = build_logger(__name__)
diff --git a/requirements.txt b/requirements.txt
index 1a89cbb..e9fff12 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -7,12 +7,18 @@ azure-communication-sms==1.0.1
azure-cosmos==4.6.0
azure-eventgrid==4.18.0
azure-identity==1.15.0 # Required for all Azure SDKs
+azure-monitor-opentelemetry==1.3.0
azure-search-documents==11.6.0b2
fastapi==0.110.0
jinja2==3.1.3
json-repair==0.10.1
mistune==3.0.2
openai==1.14.0
+opentelemetry-instrumentation-aiohttp-client==0.44b0
+opentelemetry-instrumentation-fastapi==0.44b0
+opentelemetry-instrumentation-httpx==0.44b0
+opentelemetry-instrumentation-redis==0.44b0
+opentelemetry-instrumentation-sqlite3==0.44b0
phonenumbers==8.13.32 # Required for pydantic-extra-types
pydantic-extra-types==2.6.0 # Required for pydantic
pydantic-settings==2.2.1