Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
fix: OTEL spans in async context
Clémence Lesnéba468e7c5f9f
diff --git a/app/helpers/call_events.py b/app/helpers/call_events.pyindex 7349bcc..3367b8d 100644--- a/app/helpers/call_events.py+++ b/app/helpers/call_events.py@@ -35,7 +35,7 @@ from app.helpers.config import CONFIGfrom app.helpers.features import recognition_retry_max, recording_enabledfrom app.helpers.llm_worker import completion_syncfrom app.helpers.logging import logger-from app.helpers.monitoring import SpanAttributeEnum, tracer+from app.helpers.monitoring import SpanAttributeEnum, start_as_current_spanfrom app.models.call import CallStateModelfrom app.models.message import (ActionEnum as MessageActionEnum,@@ -50,7 +50,7 @@ _sms = CONFIG.sms.instance_db = CONFIG.database.instance[email protected]_as_current_span("on_new_call")+@start_as_current_span("on_new_call")async def on_new_call(callback_url: str,client: CallAutomationClient,@@ -101,7 +101,7 @@ async def on_new_call(return False[email protected]_as_current_span("on_call_connected")+@start_as_current_span("on_call_connected")async def on_call_connected(call: CallStateModel,client: CallAutomationClient,@@ -145,7 +145,7 @@ async def on_call_connected()[email protected]_as_current_span("on_call_disconnected")+@start_as_current_span("on_call_disconnected")async def on_call_disconnected(call: CallStateModel,client: CallAutomationClient,@@ -166,7 +166,7 @@ async def on_call_disconnected()[email protected]_as_current_span("on_audio_connected")+@start_as_current_span("on_audio_connected")async def on_audio_connected( # noqa: PLR0913audio_in: asyncio.Queue[bytes],audio_out: asyncio.Queue[bytes | bool],@@ -194,7 +194,7 @@ async def on_audio_connected( # noqa: PLR0913)[email protected]_as_current_span("on_automation_recognize_error")+@start_as_current_span("on_automation_recognize_error")async def on_automation_recognize_error(call: CallStateModel,client: CallAutomationClient,@@ -243,7 +243,7 @@ async def on_automation_recognize_error()[email protected]_as_current_span("on_realtime_recognize_error")+@start_as_current_span("on_realtime_recognize_error")async def on_realtime_recognize_error(call: CallStateModel,client: CallAutomationClient,@@ -334,7 +334,7 @@ async def _pre_recognize_error(return True[email protected]_as_current_span("on_play_started")+@start_as_current_span("on_play_started")async def on_play_started(call: CallStateModel,scheduler: Scheduler,@@ -357,7 +357,7 @@ async def on_play_started(call.last_interaction_at = datetime.now(UTC)[email protected]_as_current_span("on_play_completed")+@start_as_current_span("on_play_completed")async def on_automation_play_completed(call: CallStateModel,client: CallAutomationClient,@@ -403,7 +403,7 @@ async def on_automation_play_completed(logger.warning("Unknown context %s", contexts)[email protected]_as_current_span("on_play_error")+@start_as_current_span("on_play_error")async def on_play_error(error_code: int) -> None:"""Callback for when a media play action fails.@@ -436,7 +436,7 @@ async def on_play_error(error_code: int) -> None:logger.warning("Error during media play, unknown error code %s", error_code)[email protected]_as_current_span("on_ivr_recognized")+@start_as_current_span("on_ivr_recognized")async def on_ivr_recognized(call: CallStateModel,client: CallAutomationClient,@@ -478,7 +478,7 @@ async def on_ivr_recognized()[email protected]_as_current_span("on_transfer_error")+@start_as_current_span("on_transfer_error")async def on_transfer_error(call: CallStateModel,client: CallAutomationClient,@@ -502,7 +502,7 @@ async def on_transfer_error()[email protected]_as_current_span("on_sms_received")+@start_as_current_span("on_sms_received")async def on_sms_received(call: CallStateModel,message: str,diff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.pyindex 06564d7..a3dd315 100644--- a/app/helpers/call_llm.py+++ b/app/helpers/call_llm.py@@ -37,7 +37,7 @@ from app.helpers.monitoring import (SpanAttributeEnum,call_cutoff_latency,gauge_set,- tracer,+ start_as_current_span,)from app.models.call import CallStateModelfrom app.models.message import (@@ -53,7 +53,7 @@ _db = CONFIG.database.instance# TODO: Refacto, this function is too long[email protected]_as_current_span("call_load_llm_chat")+@start_as_current_span("call_load_llm_chat")async def load_llm_chat( # noqa: PLR0913audio_in: asyncio.Queue[bytes],audio_out: asyncio.Queue[bytes | bool],@@ -233,7 +233,7 @@ async def load_llm_chat( # noqa: PLR0913# TODO: Refacto, this function is too long (and remove PLR0912/PLR0915 ignore)[email protected]_as_current_span("call_continue_chat")+@start_as_current_span("call_continue_chat")async def _continue_chat( # noqa: PLR0915, PLR0913call: CallStateModel,client: CallAutomationClient,@@ -426,7 +426,7 @@ async def _continue_chat( # noqa: PLR0915, PLR0913# TODO: Refacto, this function is too long[email protected]_as_current_span("call_generate_chat_completion")+@start_as_current_span("call_generate_chat_completion")async def _generate_chat_completion( # noqa: PLR0913, PLR0912, PLR0915call: CallStateModel,client: CallAutomationClient,diff --git a/app/helpers/llm_utils.py b/app/helpers/llm_utils.pyindex 0a61056..22ad427 100644--- a/app/helpers/llm_utils.py+++ b/app/helpers/llm_utils.py@@ -27,7 +27,7 @@ from pydantic.json_schema import JsonSchemaValuefrom app.helpers.cache import lru_acache, lru_cachefrom app.helpers.logging import logger-from app.helpers.monitoring import SpanAttributeEnum, tracer+from app.helpers.monitoring import SpanAttributeEnum, start_as_current_spanfrom app.models.call import CallStateModelfrom app.models.message import ToolModel@@ -85,7 +85,7 @@ class AbstractPlugin:*[_function_schema(func, call=self.call) for func in functions])- @tracer.start_as_current_span("plugin_execute")+ @start_as_current_span("plugin_execute")async def execute(self,tool: ToolModel,diff --git a/app/helpers/llm_worker.py b/app/helpers/llm_worker.pyindex 86a8a57..33a3f9e 100644--- a/app/helpers/llm_worker.py+++ b/app/helpers/llm_worker.py@@ -33,7 +33,7 @@ from app.helpers.config import CONFIGfrom app.helpers.config_models.llm import DeploymentModel as LlmDeploymentModelfrom app.helpers.features import slow_llm_for_chatfrom app.helpers.logging import logger-from app.helpers.monitoring import tracer+from app.helpers.monitoring import start_as_current_spanfrom app.helpers.resources import resources_dirfrom app.models.message import MessageModel@@ -62,7 +62,7 @@ _retried_exceptions = [][email protected]_as_current_span("llm_completion_stream")+@start_as_current_span("llm_completion_stream")async def completion_stream(max_tokens: int,messages: list[MessageModel],@@ -176,7 +176,7 @@ async def _completion_stream_worker(stop=stop_after_attempt(3),wait=wait_random_exponential(multiplier=0.8, max=8),)[email protected]_as_current_span("llm_completion_sync")+@start_as_current_span("llm_completion_sync")async def completion_sync(res_type: type[T],system: list[SystemMessage],diff --git a/app/helpers/monitoring.py b/app/helpers/monitoring.pyindex d2d8e21..d1425ad 100644--- a/app/helpers/monitoring.py+++ b/app/helpers/monitoring.py@@ -1,5 +1,7 @@+from asyncio import iscoroutinefunctionfrom contextlib import contextmanagerfrom enum import Enum+from functools import wrapsfrom os import environfrom azure.monitor.opentelemetry import configure_azure_monitor@@ -9,7 +11,7 @@ from opentelemetry.metrics._internal.instrument import Counter, Gaugefrom opentelemetry.semconv.attributes import service_attributesfrom opentelemetry.trace import Status, StatusCodefrom opentelemetry.trace.span import INVALID_SPAN-from opentelemetry.util.types import AttributeValue+from opentelemetry.util.types import Attributes, AttributeValuefrom structlog.contextvars import bind_contextvars, get_contextvarsMODULE_NAME = "com.github.clemlesne.call-center-ai"@@ -173,6 +175,40 @@ def counter_add()+def start_as_current_span(+ name: str,+ attributes: Attributes = None,+):+ """+ Decorator to start an OTEL span for the function and set it as the current.+ """++ def _wrapper(func):+ @wraps(func)+ def _inner(*args, **kwargs):+ # Start a span+ with tracer.start_as_current_span(+ attributes=attributes,+ name=name,+ ):+ # Call the function+ return func(*args, **kwargs)++ @wraps(func)+ async def _async_inner(*args, **kwargs):+ # Start a span+ with tracer.start_as_current_span(+ attributes=attributes,+ name=name,+ ):+ # Call the function+ return await func(*args, **kwargs)++ return _async_inner if iscoroutinefunction(func) else _inner++ return _wrapper++@contextmanagerdef suppress(*exceptions):"""diff --git a/app/main.py b/app/main.pyindex cfccdbb..05472ce 100644--- a/app/main.py+++ b/app/main.py@@ -65,8 +65,8 @@ from app.helpers.monitoring import (call_frames_in_latency,call_frames_out_latency,gauge_set,+ start_as_current_span,suppress,- tracer,)from app.helpers.pydantic_types.phone_numbers import PhoneNumberfrom app.helpers.resources import resources_dir@@ -181,7 +181,7 @@ api = FastAPI(@api.get("/health/liveness")[email protected]_as_current_span("health_liveness_get")+@start_as_current_span("health_liveness_get")async def health_liveness_get() -> None:"""Check if the service is running.@@ -197,7 +197,7 @@ async def health_liveness_get() -> None:"/health/readiness",status_code=HTTPStatus.OK,)[email protected]_as_current_span("health_readiness_get")+@start_as_current_span("health_readiness_get")async def health_readiness_get() -> JSONResponse:"""Check if the service is ready to serve requests.@@ -245,7 +245,7 @@ async def health_readiness_get() -> JSONResponse:"/report",response_class=HTMLResponse,)[email protected]_as_current_span("report_get")+@start_as_current_span("report_get")async def report_get(phone_number: str | None = None) -> HTMLResponse:"""List all calls with a web interface.@@ -284,7 +284,7 @@ async def report_get(phone_number: str | None = None) -> HTMLResponse:"/report/{call_id}",response_class=HTMLResponse,)[email protected]_as_current_span("report_single_get")+@start_as_current_span("report_single_get")async def report_single_get(call_id: UUID) -> HTMLResponse:"""Show a single call with a web interface.@@ -317,7 +317,7 @@ async def report_single_get(call_id: UUID) -> HTMLResponse:@api.get("/call")[email protected]_as_current_span("call_list_get")+@start_as_current_span("call_list_get")async def call_list_get(phone_number: str | None = None,) -> list[CallGetModel]:@@ -343,7 +343,7 @@ async def call_list_get(@api.get("/call/{call_id_or_phone_number}")[email protected]_as_current_span("call_get")+@start_as_current_span("call_get")async def call_get(call_id_or_phone_number: str) -> CallGetModel:"""REST API to search for calls by call ID or phone number.@@ -379,7 +379,7 @@ async def call_get(call_id_or_phone_number: str) -> CallGetModel:"/call",status_code=HTTPStatus.CREATED,)[email protected]_as_current_span("call_post")+@start_as_current_span("call_post")async def call_post(request: Request) -> CallGetModel:"""REST API to initiate a call.@@ -428,7 +428,7 @@ async def call_post(request: Request) -> CallGetModel:return TypeAdapter(CallGetModel).dump_python(call)[email protected]_as_current_span("call_event")+@start_as_current_span("call_event")async def call_event(call: AzureQueueStorageMessage,) -> None:@@ -468,7 +468,7 @@ async def call_event()[email protected]_as_current_span("sms_event")+@start_as_current_span("sms_event")async def sms_event(sms: AzureQueueStorageMessage,) -> None:@@ -578,7 +578,7 @@ async def _communicationservices_validate_call_id(@api.websocket("/communicationservices/wss/{call_id}/{secret}")[email protected]_as_current_span("communicationservices_event_post")+@start_as_current_span("communicationservices_event_post")async def communicationservices_wss_post(call_id: UUID,secret: Annotated[str, Field(min_length=16, max_length=16)],@@ -702,7 +702,7 @@ async def communicationservices_wss_post(@api.post("/communicationservices/callback/{call_id}/{secret}")[email protected]_as_current_span("communicationservices_callback_post")+@start_as_current_span("communicationservices_callback_post")async def communicationservices_callback_post(call_id: UUID,request: Request,@@ -879,7 +879,7 @@ async def _communicationservices_event_worker(# logger.debug("Event data %s", event.data)[email protected]_as_current_span("training_event")+@start_as_current_span("training_event")async def training_event(training: AzureQueueStorageMessage,) -> None:@@ -903,7 +903,7 @@ async def training_event(await call.trainings(cache_only=False) # Get trainings by advance to populate cache[email protected]_as_current_span("post_event")+@start_as_current_span("post_event")async def post_event(post: AzureQueueStorageMessage,) -> None:@@ -988,7 +988,7 @@ async def _communicationservices_urls("/twilio/sms",status_code=HTTPStatus.OK,)[email protected]_as_current_span("twilio_sms_post")+@start_as_current_span("twilio_sms_post")async def twilio_sms_post(Body: Annotated[str, Form()],From: Annotated[PhoneNumber, Form()],diff --git a/app/models/call.py b/app/models/call.pyindex 9c3bc76..6f07382 100644--- a/app/models/call.py+++ b/app/models/call.py@@ -11,6 +11,7 @@ from app.helpers.config_models.conversation import (LanguageEntryModel,WorkflowInitiateModel,)+from app.helpers.monitoring import tracerfrom app.helpers.pydantic_types.phone_numbers import PhoneNumberfrom app.models.message import (ActionEnum as MessageActionEnum,@@ -127,7 +128,6 @@ class CallStateModel(CallGetModel, extra="ignore"):Is using query expansion from last messages. Then, data is sorted by score."""from app.helpers.config import CONFIG- from app.helpers.monitoring import tracerwith tracer.start_as_current_span("call_trainings"):search = CONFIG.ai_search.instancediff --git a/app/persistence/icache.py b/app/persistence/icache.pyindex 6f681cf..4d12538 100644--- a/app/persistence/icache.py+++ b/app/persistence/icache.py@@ -1,22 +1,22 @@from abc import ABC, abstractmethod-from app.helpers.monitoring import tracer+from app.helpers.monitoring import start_as_current_spanfrom app.models.readiness import ReadinessEnumclass ICache(ABC):@abstractmethod- @tracer.start_as_current_span("cache_readiness")+ @start_as_current_span("cache_readiness")async def readiness(self) -> ReadinessEnum:pass@abstractmethod- @tracer.start_as_current_span("cache_get")+ @start_as_current_span("cache_get")async def get(self, key: str) -> bytes | None:pass@abstractmethod- @tracer.start_as_current_span("cache_set")+ @start_as_current_span("cache_set")async def set(self,key: str,@@ -26,6 +26,6 @@ class ICache(ABC):pass@abstractmethod- @tracer.start_as_current_span("cache_delete")+ @start_as_current_span("cache_delete")async def delete(self, key: str) -> bool:passdiff --git a/app/persistence/isearch.py b/app/persistence/isearch.pyindex 41c18aa..219ed7c 100644--- a/app/persistence/isearch.py+++ b/app/persistence/isearch.py@@ -1,6 +1,6 @@from abc import ABC, abstractmethod-from app.helpers.monitoring import tracer+from app.helpers.monitoring import start_as_current_spanfrom app.models.readiness import ReadinessEnumfrom app.models.training import TrainingModelfrom app.persistence.icache import ICache@@ -13,12 +13,12 @@ class ISearch(ABC):self._cache = cache@abstractmethod- @tracer.start_as_current_span("search_readiness")+ @start_as_current_span("search_readiness")async def readiness(self) -> ReadinessEnum:pass@abstractmethod- @tracer.start_as_current_span("search_training_search_all")+ @start_as_current_span("search_training_search_all")async def training_search_all(self,lang: str,diff --git a/app/persistence/isms.py b/app/persistence/isms.pyindex d560a93..873330d 100644--- a/app/persistence/isms.py+++ b/app/persistence/isms.py@@ -1,17 +1,17 @@from abc import ABC, abstractmethod-from app.helpers.monitoring import tracer+from app.helpers.monitoring import start_as_current_spanfrom app.helpers.pydantic_types.phone_numbers import PhoneNumberfrom app.models.readiness import ReadinessEnumclass ISms(ABC):@abstractmethod- @tracer.start_as_current_span("sms_readiness")+ @start_as_current_span("sms_readiness")async def readiness(self) -> ReadinessEnum:pass@abstractmethod- @tracer.start_as_current_span("sms_send")+ @start_as_current_span("sms_send")async def send(self, content: str, phone_number: PhoneNumber) -> bool:passdiff --git a/app/persistence/istore.py b/app/persistence/istore.pyindex becd3fa..1fae4e8 100644--- a/app/persistence/istore.py+++ b/app/persistence/istore.py@@ -4,7 +4,7 @@ from uuid import UUIDfrom aiojobs import Scheduler-from app.helpers.monitoring import tracer+from app.helpers.monitoring import start_as_current_spanfrom app.models.call import CallStateModelfrom app.models.readiness import ReadinessEnumfrom app.persistence.icache import ICache@@ -17,12 +17,12 @@ class IStore(ABC):self._cache = cache@abstractmethod- @tracer.start_as_current_span("store_readiness")+ @start_as_current_span("store_readiness")async def readiness(self) -> ReadinessEnum:pass@abstractmethod- @tracer.start_as_current_span("store_call_get")+ @start_as_current_span("store_call_get")async def call_get(self,call_id: UUID,@@ -30,7 +30,7 @@ class IStore(ABC):pass@abstractmethod- @tracer.start_as_current_span("store_call_transac")+ @start_as_current_span("store_call_transac")def call_transac(self,call: CallStateModel,@@ -39,7 +39,7 @@ class IStore(ABC):pass@abstractmethod- @tracer.start_as_current_span("store_call_create")+ @start_as_current_span("store_call_create")async def call_create(self,call: CallStateModel,@@ -47,7 +47,7 @@ class IStore(ABC):pass@abstractmethod- @tracer.start_as_current_span("store_call_search_one")+ @start_as_current_span("store_call_search_one")async def call_search_one(self,phone_number: str,@@ -56,7 +56,7 @@ class IStore(ABC):pass@abstractmethod- @tracer.start_as_current_span("store_call_search_all")+ @start_as_current_span("store_call_search_all")async def call_search_all(self,count: int,