Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
refacto: Use LRU cache for frequently accesses SDK clients
Clémence Lesnébfb206fd84ac
diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.pyindex 131322e..f678b87 100644--- a/app/helpers/call_utils.py+++ b/app/helpers/call_utils.py@@ -35,6 +35,7 @@ from azure.communication.callautomation.aio import ()from azure.core.exceptions import HttpResponseError, ResourceNotFoundError+from app.helpers.cache import async_lru_cachefrom app.helpers.config import CONFIGfrom app.helpers.identity import tokenfrom app.helpers.logging import logger@@ -141,11 +142,11 @@ async def handle_media("""with _detect_hangup():assert call.voice_id, "Voice ID is required to control the call"- async with _use_call_client(client, call.voice_id) as call_client:- await call_client.play_media(- operation_context=_context_serializer({context}),- play_source=FileSource(url=sound_url),- )+ call_client = await _use_call_client(client, call.voice_id)+ await call_client.play_media(+ operation_context=_context_serializer({context}),+ play_source=FileSource(url=sound_url),+ )async def handle_automation_tts( # noqa: PLR0913@@ -170,19 +171,19 @@ async def handle_automation_tts( # noqa: PLR0913# Play each chunkjobs: list[Job] = []chunks = _chunk_for_tts(text)- async with _use_call_client(client, call.voice_id) as call_client:- jobs += [- await scheduler.spawn(- _automation_play_text(- call_client=call_client,- call=call,- context=context,- style=style,- text=chunk,- )+ call_client = await _use_call_client(client, call.voice_id)+ jobs += [+ await scheduler.spawn(+ _automation_play_text(+ call_client=call_client,+ call=call,+ context=context,+ style=style,+ text=chunk,)- for chunk in chunks- ]+ )+ for chunk in chunks+ ]# Wait for all jobs to finish and catch hangupfor job in jobs:@@ -379,20 +380,20 @@ async def handle_recognize_ivr(logger.info("Recognizing IVR: %s", text)try:assert call.voice_id, "Voice ID is required to control the call"- async with _use_call_client(client, call.voice_id) as call_client:- await call_client.start_recognizing_media(- choices=choices,- input_type=RecognizeInputType.CHOICES,- interrupt_prompt=True,- operation_context=_context_serializer({context}),- play_prompt=_ssml_from_text(- call=call,- style=MessageStyleEnum.NONE,- text=text,- ),- speech_language=call.lang.short_code,- target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # pyright: ignore- )+ call_client = await _use_call_client(client, call.voice_id)+ await call_client.start_recognizing_media(+ choices=choices,+ input_type=RecognizeInputType.CHOICES,+ interrupt_prompt=True,+ operation_context=_context_serializer({context}),+ play_prompt=_ssml_from_text(+ call=call,+ style=MessageStyleEnum.NONE,+ text=text,+ ),+ speech_language=call.lang.short_code,+ target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # pyright: ignore+ )except ResourceNotFoundError:logger.debug("Call hung up before recognizing")@@ -414,8 +415,8 @@ async def handle_hangup(_detect_hangup(),):assert call.voice_id, "Voice ID is required to control the call"- async with _use_call_client(client, call.voice_id) as call_client:- await call_client.hang_up(is_for_everyone=True)+ call_client = await _use_call_client(client, call.voice_id)+ await call_client.hang_up(is_for_everyone=True)async def handle_transfer(@@ -432,11 +433,11 @@ async def handle_transfer(logger.info("Transferring call: %s", target)with _detect_hangup():assert call.voice_id, "Voice ID is required to control the call"- async with _use_call_client(client, call.voice_id) as call_client:- await call_client.transfer_call_to_participant(- operation_context=_context_serializer({context}),- target_participant=PhoneNumberIdentifier(target),- )+ call_client = await _use_call_client(client, call.voice_id)+ await call_client.transfer_call_to_participant(+ operation_context=_context_serializer({context}),+ target_participant=PhoneNumberIdentifier(target),+ )async def start_audio_streaming(@@ -451,13 +452,13 @@ async def start_audio_streaming(logger.info("Starting audio streaming")with _detect_hangup():assert call.voice_id, "Voice ID is required to control the call"- async with _use_call_client(client, call.voice_id) as call_client:- # TODO: Use the public API once the "await" have been fixed- # await call_client.start_media_streaming()- await call_client._call_media_client.start_media_streaming(- call_connection_id=call_client._call_connection_id,- start_media_streaming_request=StartMediaStreamingRequest(),- )+ call_client = await _use_call_client(client, call.voice_id)+ # TODO: Use the public API once the "await" have been fixed+ # await call_client.start_media_streaming()+ await call_client._call_media_client.start_media_streaming(+ call_connection_id=call_client._call_connection_id,+ start_media_streaming_request=StartMediaStreamingRequest(),+ )async def stop_audio_streaming(@@ -472,8 +473,8 @@ async def stop_audio_streaming(logger.info("Stopping audio streaming")with _detect_hangup():assert call.voice_id, "Voice ID is required to control the call"- async with _use_call_client(client, call.voice_id) as call_client:- await call_client.stop_media_streaming()+ call_client = await _use_call_client(client, call.voice_id)+ await call_client.stop_media_streaming()def _context_serializer(contexts: set[ContextEnum | None] | None) -> str | None:@@ -505,15 +506,14 @@ def _detect_hangup() -> Generator[None, None, None]:raise e-@asynccontextmanager+@async_lru_cache()async def _use_call_client(client: CallAutomationClient, voice_id: str-) -> AsyncGenerator[CallConnectionClient, None]:+) -> CallConnectionClient:"""Return the call client for a given call."""- # Client already been created in the call client, never close it from here- yield client.get_call_connection(call_connection_id=voice_id)+ return client.get_call_connection(call_connection_id=voice_id)@asynccontextmanagerdiff --git a/app/helpers/config_models/llm.py b/app/helpers/config_models/llm.pyindex 3df7fde..a5c6e35 100644--- a/app/helpers/config_models/llm.py+++ b/app/helpers/config_models/llm.py@@ -5,6 +5,7 @@ from typing import Anyfrom openai import AsyncAzureOpenAI, AsyncOpenAIfrom pydantic import BaseModel, Field, SecretStr, ValidationInfo, field_validator+from app.helpers.cache import async_lru_cachefrom app.helpers.identity import token@@ -13,7 +14,7 @@ class ModeEnum(str, Enum):OPENAI = "openai"-class AbstractPlatformModel(BaseModel):+class AbstractPlatformModel(BaseModel, frozen=True):_client_kwargs: dict[str, Any] = {# Reliability"max_retries": 0, # Retries are managed manually@@ -33,41 +34,37 @@ class AbstractPlatformModel(BaseModel):pass-class AzureOpenaiPlatformModel(AbstractPlatformModel):- _client: AsyncAzureOpenAI | None = None+class AzureOpenaiPlatformModel(AbstractPlatformModel, frozen=True):api_version: str = "2024-06-01"deployment: str+ @async_lru_cache()async def instance(self) -> tuple[AsyncAzureOpenAI, AbstractPlatformModel]:- if not self._client:- self._client = AsyncAzureOpenAI(- **self._client_kwargs,- # Deployment- api_version=self.api_version,- azure_deployment=self.deployment,- azure_endpoint=self.endpoint,- # Authentication- azure_ad_token_provider=await token(- "https://cognitiveservices.azure.com/.default"- ),- )- return self._client, self---class OpenaiPlatformModel(AbstractPlatformModel):- _client: AsyncOpenAI | None = None+ return AsyncAzureOpenAI(+ **self._client_kwargs,+ # Deployment+ api_version=self.api_version,+ azure_deployment=self.deployment,+ azure_endpoint=self.endpoint,+ # Authentication+ azure_ad_token_provider=await token(+ "https://cognitiveservices.azure.com/.default"+ ),+ ), self+++class OpenaiPlatformModel(AbstractPlatformModel, frozen=True):api_key: SecretStr+ @async_lru_cache()async def instance(self) -> tuple[AsyncOpenAI, AbstractPlatformModel]:- if not self._client:- self._client = AsyncOpenAI(- **self._client_kwargs,- # API root URL- base_url=self.endpoint,- # Authentication- api_key=self.api_key.get_secret_value(),- )- return self._client, self+ return AsyncOpenAI(+ **self._client_kwargs,+ # API root URL+ base_url=self.endpoint,+ # Authentication+ api_key=self.api_key.get_secret_value(),+ ), selfclass SelectedPlatformModel(BaseModel):diff --git a/app/persistence/azure_queue_storage.py b/app/persistence/azure_queue_storage.pyindex bcddd99..a060f63 100644--- a/app/persistence/azure_queue_storage.py+++ b/app/persistence/azure_queue_storage.py@@ -15,6 +15,7 @@ from tenacity import (wait_random_exponential,)+from app.helpers.cache import async_lru_cachefrom app.helpers.http import azure_transportfrom app.helpers.identity import credentialfrom app.helpers.logging import logger@@ -105,17 +106,27 @@ class AzureQueueStorage:except (UnicodeDecodeError, BinasciiError):return value- @asynccontextmanager- async def _use_client(self) -> AsyncGenerator[QueueClient, None]:- async with QueueServiceClient(+ @async_lru_cache()+ async def _use_service_client(self) -> QueueServiceClient:+ """+ Generate a new service client.+ """+ return QueueServiceClient(# Performancetransport=await azure_transport(),# Deploymentaccount_url=self._account_url,# Authenticationcredential=await credential(),- ) as service:- yield service.get_queue_client(+ )++ @asynccontextmanager+ async def _use_client(self) -> AsyncGenerator[QueueClient, None]:+ """+ Generate a queue client.+ """+ async with await self._use_service_client() as client:+ yield client.get_queue_client(# Performancetransport=await azure_transport(),# Deploymentdiff --git a/app/persistence/communication_services.py b/app/persistence/communication_services.pyindex 2c3bcec..828d2f1 100644--- a/app/persistence/communication_services.py+++ b/app/persistence/communication_services.py@@ -3,6 +3,7 @@ from azure.communication.sms.aio import SmsClientfrom azure.core.credentials import AzureKeyCredentialfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError+from app.helpers.cache import async_lru_cachefrom app.helpers.config_models.communication_services import CommunicationServicesModelfrom app.helpers.http import azure_transportfrom app.helpers.logging import logger@@ -54,16 +55,13 @@ class CommunicationServicesSms(ISms):logger.exception("Error sending SMS to %s", phone_number)return success+ @async_lru_cache()async def _use_client(self) -> SmsClient:- if not self._client:- self._client = SmsClient(- # Deployment- endpoint=self._config.endpoint,- # Performance- transport=await azure_transport(),- # Authentication- credential=AzureKeyCredential(- self._config.access_key.get_secret_value()- ),- )- return self._client+ return SmsClient(+ # Deployment+ endpoint=self._config.endpoint,+ # Performance+ transport=await azure_transport(),+ # Authentication+ credential=AzureKeyCredential(self._config.access_key.get_secret_value()),+ )diff --git a/app/persistence/cosmos_db.py b/app/persistence/cosmos_db.pyindex c57f009..5275410 100644--- a/app/persistence/cosmos_db.py+++ b/app/persistence/cosmos_db.py@@ -10,6 +10,7 @@ from azure.cosmos.aio import ContainerProxy, CosmosClientfrom azure.cosmos.exceptions import CosmosHttpResponseError, CosmosResourceNotFoundErrorfrom pydantic import ValidationError+from app.helpers.cache import async_lru_cachefrom app.helpers.config_models.database import CosmosDbModelfrom app.helpers.features import callback_timeout_hourfrom app.helpers.http import azure_transport@@ -22,7 +23,6 @@ from app.persistence.istore import IStoreclass CosmosDbStore(IStore):- _client: CosmosClient | None = None_config: CosmosDbModeldef __init__(self, cache: ICache, config: CosmosDbModel):@@ -372,27 +372,32 @@ class CosmosDbStore(IStore):return total+ @async_lru_cache()+ async def _use_service_client(self) -> CosmosClient:+ """+ Generate the Cosmos DB client.+ """+ return CosmosClient(+ # Usage+ consistency_level=ConsistencyLevel.Eventual,+ # Reliability+ connection_timeout=10, # 10 secs+ retry_backoff_factor=0.8,+ retry_backoff_max=8,+ retry_total=3,+ # Performance+ transport=await azure_transport(),+ # Deployment+ url=self._config.endpoint,+ # Authentication+ credential=await credential(),+ )+@asynccontextmanagerasync def _use_client(self) -> AsyncGenerator[ContainerProxy, None]:"""- Generate the Cosmos DB client and close it after use.+ Generate the container client."""- if not self._client:- self._client = CosmosClient(- # Usage- consistency_level=ConsistencyLevel.Eventual,- # Reliability- connection_timeout=10, # 10 secs- retry_backoff_factor=0.8,- retry_backoff_max=8,- retry_total=3,- # Performance- transport=await azure_transport(),- # Deployment- url=self._config.endpoint,- # Authentication- credential=await credential(),- )- async with self._client as client:+ async with await self._use_service_client() as client:database = client.get_database_client(self._config.database)yield database.get_container_client(self._config.container)diff --git a/app/persistence/twilio.py b/app/persistence/twilio.pyindex e52feb8..c26b9fe 100644--- a/app/persistence/twilio.py+++ b/app/persistence/twilio.py@@ -1,6 +1,7 @@from twilio.base.exceptions import TwilioRestExceptionfrom twilio.rest import Client+from app.helpers.cache import async_lru_cachefrom app.helpers.config_models.sms import TwilioModelfrom app.helpers.http import twilio_httpfrom app.helpers.logging import logger@@ -62,13 +63,12 @@ class TwilioSms(ISms):logger.exception("Error sending SMS to %s", phone_number)return success+ @async_lru_cache()async def _use_client(self) -> Client:- if not self._client:- self._client = Client(- # Performance- http_client=await twilio_http(),- # Authentication- password=self._config.auth_token.get_secret_value(),- username=self._config.account_sid,- )- return self._client+ return Client(+ # Performance+ http_client=await twilio_http(),+ # Authentication+ password=self._config.auth_token.get_secret_value(),+ username=self._config.account_sid,+ )