Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
quality: Simplify SDK client caching
Clémence Lesnéd56181dea4c6
diff --git a/app/helpers/cache.py b/app/helpers/cache.pynew file mode 100644index 0000000..94bb1ed--- /dev/null+++ b/app/helpers/cache.py@@ -0,0 +1,38 @@+import functools+from collections import OrderedDict+from collections.abc import Awaitable+++def async_lru_cache(maxsize: int = 128):+ """+ Caches a function's return value each time it is called.++ If the maxsize is reached, the least recently used value is removed.+ """++ def decorator(func):+ cache: OrderedDict[tuple, Awaitable] = OrderedDict()++ @functools.wraps(func)+ async def wrapper(*args, **kwargs) -> Awaitable:+ # Create a cache key from args and kwargs, using frozenset for kwargs to ensure hashability+ key = (args, frozenset(kwargs.items()))++ if key in cache:+ # Move the recently accessed key to the end (most recently used)+ cache.move_to_end(key)+ return cache[key]++ # Compute the value since it's not cached+ value = await func(*args, **kwargs)+ cache[key] = value+ cache.move_to_end(key)++ if len(cache) > maxsize:+ cache.popitem(last=False)++ return value++ return wrapper++ return decoratordiff --git a/app/helpers/features.py b/app/helpers/features.pyindex 11be914..3d8c66f 100644--- a/app/helpers/features.py+++ b/app/helpers/features.py@@ -4,6 +4,7 @@ from typing import TypeVar, castfrom azure.appconfiguration.aio import AzureAppConfigurationClientfrom azure.core.exceptions import ResourceNotFoundError+from app.helpers.cache import async_lru_cachefrom app.helpers.config import CONFIGfrom app.helpers.config_models.cache import MemoryModelfrom app.helpers.http import azure_transport@@ -13,7 +14,6 @@ from app.persistence.icache import ICachefrom app.persistence.memory import MemoryCache_cache: ICache = MemoryCache(MemoryModel(max_size=100))-_client: AzureAppConfigurationClient | None = NoneT = TypeVar("T", bool, int, float, str)@@ -79,21 +79,19 @@ async def _get(key: str, type_res: type[T]) -> T | None:return _parse(value=setting.value, type_res=type_res)+@async_lru_cache()async def _use_client() -> AzureAppConfigurationClient:"""Generate the App Configuration client and close it after use."""- global _client # noqa: PLW0603- if not _client:- _client = AzureAppConfigurationClient(- # Performance- transport=await azure_transport(),- # Deployment- base_url=CONFIG.app_configuration.endpoint,- # Authentication- credential=await credential(),- )- return _client+ return AzureAppConfigurationClient(+ # Performance+ transport=await azure_transport(),+ # Deployment+ base_url=CONFIG.app_configuration.endpoint,+ # Authentication+ credential=await credential(),+ )def _cache_key(key: str) -> str:diff --git a/app/helpers/http.py b/app/helpers/http.pyindex 8bc2179..96469e2 100644--- a/app/helpers/http.py+++ b/app/helpers/http.py@@ -9,12 +9,10 @@ from aiohttp_retry import JitterRetry, RetryClientfrom azure.core.pipeline.transport._aiohttp import AioHttpTransportfrom twilio.http.async_http_client import AsyncTwilioHttpClient-_cookie_jar: DummyCookieJar | None = None-_session: ClientSession | None = None-_transport: AioHttpTransport | None = None-_twilio_http: AsyncTwilioHttpClient | None = None+from app.helpers.cache import async_lru_cache+@async_lru_cache()async def _aiohttp_cookie_jar() -> DummyCookieJar:"""Create a cookie jar mock for AIOHTTP.@@ -23,12 +21,10 @@ async def _aiohttp_cookie_jar() -> DummyCookieJar:Returns a `DummyCookieJar` instance."""- global _cookie_jar # noqa: PLW0603- if not _cookie_jar:- _cookie_jar = DummyCookieJar()- return _cookie_jar+ return DummyCookieJar()+@async_lru_cache()async def aiohttp_session() -> ClientSession:"""Create an AIOHTTP session.@@ -37,24 +33,22 @@ async def aiohttp_session() -> ClientSession:Returns a `ClientSession` instance."""- global _session # noqa: PLW0603- if not _session:- _session = ClientSession(- # Same config as default in the SDK- auto_decompress=False,- cookie_jar=await _aiohttp_cookie_jar(),- trust_env=True,- # Performance- connector=TCPConnector(resolver=AsyncResolver()),- # Reliability- timeout=ClientTimeout(- connect=5,- total=60,- ),- )- return _session--+ return ClientSession(+ # Same config as default in the SDK+ auto_decompress=False,+ cookie_jar=await _aiohttp_cookie_jar(),+ trust_env=True,+ # Performance+ connector=TCPConnector(resolver=AsyncResolver()),+ # Reliability+ timeout=ClientTimeout(+ connect=5,+ total=60,+ ),+ )+++@async_lru_cache()async def azure_transport() -> AioHttpTransport:"""Create an AIOHTTP transport, for Azure SDK.@@ -63,16 +57,14 @@ async def azure_transport() -> AioHttpTransport:Returns a `AioHttpTransport` instance."""- global _transport # noqa: PLW0603- if not _transport:- # Azure SDK implements its own retry logic (e.g. for Cosmos DB), so we don't add it here- _transport = AioHttpTransport(- session_owner=False, # Restrict the SDK to close the client after usage- session=await aiohttp_session(),- )- return _transport+ # Azure SDK implements its own retry logic (e.g. for Cosmos DB), so we don't add it here+ return AioHttpTransport(+ session_owner=False, # Restrict the SDK to close the client after usage+ session=await aiohttp_session(),+ )+@async_lru_cache()async def twilio_http() -> AsyncTwilioHttpClient:"""Create a Twilio HTTP client.@@ -81,18 +73,16 @@ async def twilio_http() -> AsyncTwilioHttpClient:Returns a `AsyncTwilioHttpClient` instance."""- global _twilio_http # noqa: PLW0603- if not _twilio_http:- _twilio_http = AsyncTwilioHttpClient(- timeout=10,- )- _twilio_http.session = RetryClient(- client_session=await aiohttp_session(),- # Reliability- retry_options=JitterRetry(- attempts=3,- max_timeout=8,- start_timeout=0.8,- ), # Twilio SDK outsources its retry logic to AIOHTTP- )+ _twilio_http = AsyncTwilioHttpClient(+ timeout=10,+ )+ _twilio_http.session = RetryClient(+ client_session=await aiohttp_session(),+ # Reliability+ retry_options=JitterRetry(+ attempts=3,+ max_timeout=8,+ start_timeout=0.8,+ ), # Twilio SDK outsources its retry logic to AIOHTTP+ )return _twilio_httpdiff --git a/app/helpers/identity.py b/app/helpers/identity.pyindex eabf777..e0f6796 100644--- a/app/helpers/identity.py+++ b/app/helpers/identity.py@@ -2,20 +2,18 @@ from collections.abc import Awaitable, Callablefrom azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider+from app.helpers.cache import async_lru_cachefrom app.helpers.http import azure_transport-_client: DefaultAzureCredential | None = None-+@async_lru_cache()async def credential() -> DefaultAzureCredential:- global _client # noqa: PLW0603- if not _client:- _client = DefaultAzureCredential(- # Performance- transport=await azure_transport(),- )- return _client+ return DefaultAzureCredential(+ # Performance+ transport=await azure_transport(),+ )+@async_lru_cache()async def token(service: str) -> Callable[[], Awaitable[str]]:return get_bearer_token_provider(await credential(), service)diff --git a/app/helpers/translation.py b/app/helpers/translation.pyindex 84655b5..fe6fc89 100644--- a/app/helpers/translation.py+++ b/app/helpers/translation.py@@ -9,6 +9,7 @@ from tenacity import (wait_random_exponential,)+from app.helpers.cache import async_lru_cachefrom app.helpers.config import CONFIGfrom app.helpers.http import azure_transportfrom app.helpers.logging import logger@@ -16,7 +17,6 @@ from app.helpers.logging import loggerlogger.info("Using Translation %s", CONFIG.ai_translation.endpoint)_cache = CONFIG.cache.instance()-_client: TextTranslationClient | None = None@retry(@@ -60,20 +60,18 @@ async def translate_text(text: str, source_lang: str, target_lang: str) -> str |return translation+@async_lru_cache()async def _use_client() -> TextTranslationClient:"""Generate the Translation client and close it after use."""- global _client # noqa: PLW0603- if not isinstance(_client, TextTranslationClient):- _client = TextTranslationClient(- # Performance- transport=await azure_transport(),- # Deployment- endpoint=CONFIG.ai_translation.endpoint,- # Authentication- credential=AzureKeyCredential(- CONFIG.ai_translation.access_key.get_secret_value()- ),- )- return _client+ return TextTranslationClient(+ # Performance+ transport=await azure_transport(),+ # Deployment+ endpoint=CONFIG.ai_translation.endpoint,+ # Authentication+ credential=AzureKeyCredential(+ CONFIG.ai_translation.access_key.get_secret_value()+ ),+ )diff --git a/app/main.py b/app/main.pyindex 0ea20a3..9f3e9ec 100644--- a/app/main.py+++ b/app/main.py@@ -39,6 +39,7 @@ from starlette.datastructures import Headersfrom starlette.exceptions import HTTPException as StarletteHTTPExceptionfrom twilio.twiml.messaging_response import MessagingResponse+from app.helpers.cache import async_lru_cachefrom app.helpers.call_events import (on_audio_connected,on_call_connected,@@ -1014,6 +1015,7 @@ def _standard_error()+@async_lru_cache()async def _use_automation_client() -> CallAutomationClient:"""Get the call automation client for Azure Communication Services.@@ -1022,16 +1024,13 @@ async def _use_automation_client() -> CallAutomationClient:Returns a `CallAutomationClient` instance."""- global _automation_client # noqa: PLW0603- if not isinstance(_automation_client, CallAutomationClient):- _automation_client = CallAutomationClient(- # Deployment- endpoint=CONFIG.communication_services.endpoint,- # Performance- transport=await azure_transport(),- # Authentication- credential=AzureKeyCredential(- CONFIG.communication_services.access_key.get_secret_value()- ), # Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)- )- return _automation_client+ return CallAutomationClient(+ # Deployment+ endpoint=CONFIG.communication_services.endpoint,+ # Performance+ transport=await azure_transport(),+ # Authentication+ credential=AzureKeyCredential(+ CONFIG.communication_services.access_key.get_secret_value()+ ), # Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)+ )