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.mdindex 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.bicepindex 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: prefixlocation: locationdiff --git a/helpers/call_events.py b/helpers/call_events.pyindex 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, TRACERfrom 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.pyindex 4c2df7d..c981f0b 100644--- a/helpers/config.py+++ b/helpers/config.py@@ -11,8 +11,8 @@ import osimport 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.pyindex 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: SecretStrclass LoggingLevelEnum(str, Enum):@@ -12,12 +17,11 @@ class LoggingLevelEnum(str, Enum):WARNING = "WARNING"-class LoggingMonitoringModel(BaseModel):+class LoggingModel(BaseModel):app_level: LoggingLevelEnum = LoggingLevelEnum.INFOsys_level: LoggingLevelEnum = LoggingLevelEnum.WARNINGclass MonitoringModel(BaseModel):- logging: LoggingMonitoringModel = (- LoggingMonitoringModel()- ) # Object is fully defined by default+ logging: LoggingModel = LoggingModel() # Object is fully defined by default+ application_insights: ApplicationInsightsModeldiff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex 3db5d98..33ec121 100644--- a/helpers/config_models/root.py+++ b/helpers/config_models/root.py@@ -34,9 +34,7 @@ class RootModel(BaseSettings):communication_service: CommunicationServiceModelcontent_safety: ContentSafetyModeldatabase: DatabaseModel = DatabaseModel() # Object is fully defined by default- monitoring: MonitoringModel = (- MonitoringModel()- ) # Object is fully defined by default+ monitoring: MonitoringModelopenai: OpenAiModelprompts: PromptsModel = PromptsModel() # Object is fully defined by defaultresources: ResourcesModeldiff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex 9ba95b2..368396d 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -10,7 +10,7 @@ from azure.core.exceptions import HttpResponseErrorfrom azure.identity import DefaultAzureCredential, get_bearer_token_providerfrom helpers.config import CONFIGfrom contextlib import asynccontextmanager-from helpers.logging import build_logger+from helpers.logging import build_logger, TRACERfrom openai import AsyncAzureOpenAI, AsyncStream, RateLimitError, APIErrorfrom 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.pyindex 71fdf66..91fb34b 100644--- a/helpers/logging.py+++ b/helpers/logging.py@@ -1,14 +1,30 @@+from azure.monitor.opentelemetry import configure_azure_monitorfrom helpers.config import CONFIGfrom 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 loggerdiff --git a/main.py b/main.pyindex 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.pyindex abdadc6..3b592f1 100644--- a/models/message.py+++ b/models/message.py@@ -12,6 +12,7 @@ from inspect import getmembers, isfunctionfrom json_repair import repair_jsonfrom openai.types.chat.chat_completion_chunk import ChoiceDeltaToolCallimport re+import json_FUNC_NAME_SANITIZER_R = r"[^a-zA-Z0-9_-]"@@ -87,7 +88,7 @@ class ToolModel(BaseModel):return selfasync def execute_function(self, plugins: object) -> None:- from helpers.logging import build_logger+ from helpers.logging import build_logger, TRACERlogger = 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@staticmethoddef _available_function_names() -> list[str]:diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex d0b7018..654e662 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -2,7 +2,6 @@ from azure.core.exceptions import ServiceResponseErrorfrom azure.cosmos.aio import CosmosClient, ContainerProxyfrom azure.cosmos.exceptions import CosmosHttpResponseErrorfrom contextlib import asynccontextmanager-from datetime import datetime, timedeltafrom fastapi.encoders import jsonable_encoderfrom helpers.config import CONFIGfrom helpers.config_models.database import CosmosDbModeldiff --git a/persistence/redis.py b/persistence/redis.pyindex ef21223..385360f 100644--- a/persistence/redis.py+++ b/persistence/redis.py@@ -1,6 +1,7 @@from contextlib import asynccontextmanagerfrom helpers.config_models.cache import RedisModelfrom helpers.logging import build_logger+from opentelemetry.instrumentation.redis import RedisInstrumentorfrom persistence.icache import ICachefrom redis.asyncio import Redisfrom redis.asyncio.retry import Retry@@ -10,6 +11,9 @@ from typing import AsyncGenerator, Optional, Unionimport hashlib+# Instrument redis+RedisInstrumentor().instrument()+_logger = build_logger(__name__)_retry = Retry(ExponentialBackoff(), 3)diff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex 2c169ef..e8b24ca 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -5,6 +5,7 @@ from helpers.config import CONFIGfrom helpers.config_models.database import SqliteModelfrom helpers.logging import build_loggerfrom models.call import CallModel+from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentorfrom persistence.istore import IStorefrom pydantic import ValidationErrorfrom typing import AsyncGenerator, Optional@@ -13,6 +14,9 @@ import jsonimport os+# Instrument sqlite+SQLite3Instrumentor().instrument()+_logger = build_logger(__name__)diff --git a/requirements.txt b/requirements.txtindex 1a89cbb..e9fff12 100644--- a/requirements.txt+++ b/requirements.txt@@ -7,12 +7,18 @@ azure-communication-sms==1.0.1azure-cosmos==4.6.0azure-eventgrid==4.18.0azure-identity==1.15.0 # Required for all Azure SDKs+azure-monitor-opentelemetry==1.3.0azure-search-documents==11.6.0b2fastapi==0.110.0jinja2==3.1.3json-repair==0.10.1mistune==3.0.2openai==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.44b0phonenumbers==8.13.32 # Required for pydantic-extra-typespydantic-extra-types==2.6.0 # Required for pydanticpydantic-settings==2.2.1