Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
perf: Enhance memory usage by fixing SDK clients caching
Clémence Lesné3f72173d507c
diff --git a/app/helpers/cache.py b/app/helpers/cache.pyindex fb6a782..1bace6b 100644--- a/app/helpers/cache.py+++ b/app/helpers/cache.py@@ -1,8 +1,8 @@import asyncio-import functoolsfrom collections import OrderedDictfrom collections.abc import AsyncGenerator, Awaitablefrom contextlib import asynccontextmanager+from functools import wrapsfrom aiojobs import Scheduler@@ -20,9 +20,9 @@ async def get_scheduler() -> AsyncGenerator[Scheduler, None]:yield scheduler-def async_lru_cache(maxsize: int = 128):+def lru_acache(maxsize: int = 128):"""- Caches a function's return value each time it is called.+ Caches an async function's return value each time it is called.If the maxsize is reached, the least recently used value is removed."""@@ -30,7 +30,7 @@ def async_lru_cache(maxsize: int = 128):def decorator(func):cache: OrderedDict[tuple, Awaitable] = OrderedDict()- @functools.wraps(func)+ @wraps(func)async def wrapper(*args, **kwargs) -> Awaitable:# Create a cache key from event loop, args and kwargs, using frozenset for kwargs to ensure hashabilitykey = (@@ -49,6 +49,46 @@ def async_lru_cache(maxsize: int = 128):cache[key] = valuecache.move_to_end(key)+ # Remove the least recently used key if the cache is full+ if len(cache) > maxsize:+ cache.popitem(last=False)++ return value++ return wrapper++ return decorator+++def lru_cache(maxsize: int = 128):+ """+ Caches a sync 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()++ @wraps(func)+ 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 = func(*args, **kwargs)+ cache[key] = value+ cache.move_to_end(key)++ # Remove the least recently used key if the cache is fullif len(cache) > maxsize:cache.popitem(last=False)diff --git a/app/helpers/call_events.py b/app/helpers/call_events.pyindex 6076dbf..7349bcc 100644--- a/app/helpers/call_events.py+++ b/app/helpers/call_events.py@@ -46,8 +46,8 @@ from app.models.message import (from app.models.next import NextModelfrom app.models.synthesis import SynthesisModel-_sms = CONFIG.sms.instance()-_db = CONFIG.database.instance()+_sms = CONFIG.sms.instance+_db = CONFIG.database.instance@tracer.start_as_current_span("on_new_call")diff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.pyindex fa1487b..cc62213 100644--- a/app/helpers/call_llm.py+++ b/app/helpers/call_llm.py@@ -49,7 +49,7 @@ from app.models.message import (extract_message_style,)-_db = CONFIG.database.instance()+_db = CONFIG.database.instance# TODO: Refacto, this function is too longdiff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.pyindex 7293a40..77a8fac 100644--- a/app/helpers/call_utils.py+++ b/app/helpers/call_utils.py@@ -40,7 +40,7 @@ from azure.communication.callautomation.aio import (from azure.core.exceptions import HttpResponseError, ResourceNotFoundErrorfrom noisereduce import reduce_noise-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.config import CONFIGfrom app.helpers.features import (recognition_stt_complete_timeout_ms,@@ -71,7 +71,7 @@ _TTS_SANITIZER_R = re.compile(r"[^\w\sÀ-ÿ'«»“”\"\"‘’''(),.!?;:\-\+_@/&€$%=]" # noqa: RUF001) # Sanitize text for TTS-_db = CONFIG.database.instance()+_db = CONFIG.database.instanceclass CallHangupException(Exception):@@ -526,7 +526,7 @@ def _detect_hangup() -> Generator[None, None, None]:raise e-@async_lru_cache()+@lru_acache()async def _use_call_client(client: CallAutomationClient, voice_id: str) -> CallConnectionClient:diff --git a/app/helpers/config_models/ai_search.py b/app/helpers/config_models/ai_search.pyindex 4b72b59..4300883 100644--- a/app/helpers/config_models/ai_search.py+++ b/app/helpers/config_models/ai_search.py@@ -1,4 +1,4 @@-from functools import lru_cache+from functools import cached_propertyfrom pydantic import BaseModel, Field@@ -17,7 +17,7 @@ class AiSearchModel(BaseModel, frozen=True):strictness: float = Field(default=2, ge=0, le=5)top_n_documents: int = Field(default=5, ge=1)- @lru_cache+ @cached_propertydef instance(self) -> ISearch:from app.helpers.config import CONFIGfrom app.persistence.ai_search import (@@ -25,6 +25,6 @@ class AiSearchModel(BaseModel, frozen=True):)return AiSearchSearch(- cache=CONFIG.cache.instance(),+ cache=CONFIG.cache.instance,config=self,)diff --git a/app/helpers/config_models/cache.py b/app/helpers/config_models/cache.pyindex fdc3097..3c5229d 100644--- a/app/helpers/config_models/cache.py+++ b/app/helpers/config_models/cache.py@@ -1,5 +1,5 @@from enum import Enum-from functools import lru_cache+from functools import cached_propertyfrom pydantic import BaseModel, Field, SecretStr, ValidationInfo, field_validator@@ -16,7 +16,7 @@ class ModeEnum(str, Enum):class MemoryModel(BaseModel, frozen=True):max_size: int = Field(default=128, ge=10)- @lru_cache+ @cached_propertydef instance(self) -> ICache:from app.persistence.memory import (MemoryCache,@@ -32,7 +32,7 @@ class RedisModel(BaseModel, frozen=True):port: int = 6379ssl: bool = True- @lru_cache+ @cached_propertydef instance(self) -> ICache:from app.persistence.redis import (RedisCache,@@ -68,10 +68,11 @@ class CacheModel(BaseModel):raise ValueError("Memory config required")return memory+ @cached_propertydef instance(self) -> ICache:if self.mode == ModeEnum.MEMORY:assert self.memory- return self.memory.instance()+ return self.memory.instanceassert self.redis- return self.redis.instance()+ return self.redis.instancediff --git a/app/helpers/config_models/database.py b/app/helpers/config_models/database.pyindex 8b7bbf3..9dea232 100644--- a/app/helpers/config_models/database.py+++ b/app/helpers/config_models/database.py@@ -1,4 +1,4 @@-from functools import lru_cache+from functools import cached_propertyfrom pydantic import BaseModel@@ -10,7 +10,7 @@ class CosmosDbModel(BaseModel, frozen=True):database: strendpoint: str- @lru_cache+ @cached_propertydef instance(self) -> IStore:from app.helpers.config import CONFIGfrom app.persistence.cosmos_db import (@@ -18,7 +18,7 @@ class CosmosDbModel(BaseModel, frozen=True):)return CosmosDbStore(- cache=CONFIG.cache.instance(),+ cache=CONFIG.cache.instance,config=self,)@@ -26,5 +26,6 @@ class CosmosDbModel(BaseModel, frozen=True):class DatabaseModel(BaseModel):cosmos_db: CosmosDbModel+ @cached_propertydef instance(self) -> IStore:- return self.cosmos_db.instance()+ return self.cosmos_db.instancediff --git a/app/helpers/config_models/llm.py b/app/helpers/config_models/llm.pyindex 7538fa7..8883d40 100644--- a/app/helpers/config_models/llm.py+++ b/app/helpers/config_models/llm.py@@ -1,7 +1,7 @@from azure.ai.inference.aio import ChatCompletionsClientfrom pydantic import BaseModel-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.http import azure_transportfrom app.helpers.identity import credential@@ -14,8 +14,8 @@ class DeploymentModel(BaseModel, frozen=True):seed: int = 42 # Reproducible resultstemperature: float = 0.0 # Most focused and deterministic- @async_lru_cache()- async def instance(self) -> tuple[ChatCompletionsClient, "DeploymentModel"]:+ @lru_acache()+ async def client(self) -> tuple[ChatCompletionsClient, "DeploymentModel"]:return ChatCompletionsClient(# Reliabilityseed=self.seed,diff --git a/app/helpers/config_models/queue.py b/app/helpers/config_models/queue.pyindex 48e9f4c..2106641 100644--- a/app/helpers/config_models/queue.py+++ b/app/helpers/config_models/queue.py@@ -1,4 +1,4 @@-from functools import lru_cache+from functools import cached_propertyfrom pydantic import BaseModel@@ -10,7 +10,7 @@ class QueueModel(BaseModel, frozen=True):sms_name: strtraining_name: str- @lru_cache+ @cached_propertydef call(self):from app.persistence.azure_queue_storage import AzureQueueStorage@@ -19,7 +19,7 @@ class QueueModel(BaseModel, frozen=True):name=self.call_name,)- @lru_cache+ @cached_propertydef post(self):from app.persistence.azure_queue_storage import AzureQueueStorage@@ -28,7 +28,7 @@ class QueueModel(BaseModel, frozen=True):name=self.post_name,)- @lru_cache+ @cached_propertydef sms(self):from app.persistence.azure_queue_storage import AzureQueueStorage@@ -37,7 +37,7 @@ class QueueModel(BaseModel, frozen=True):name=self.sms_name,)- @lru_cache+ @cached_propertydef training(self):from app.persistence.azure_queue_storage import AzureQueueStoragediff --git a/app/helpers/config_models/sms.py b/app/helpers/config_models/sms.pyindex 013dde5..929f7d8 100644--- a/app/helpers/config_models/sms.py+++ b/app/helpers/config_models/sms.py@@ -1,5 +1,5 @@from enum import Enum-from functools import lru_cache+from functools import cached_propertyfrom pydantic import BaseModel, SecretStr, ValidationInfo, field_validator@@ -21,7 +21,7 @@ class CommunicationServiceModel(BaseModel, frozen=True):Model is purely empty to fit to the `ISms` interface and the "mode" enum code organization. As the Communication Services is also used as the only call interface, it is not necessary to duplicate the models."""- @lru_cache+ @cached_propertydef instance(self) -> ISms:from app.helpers.config import CONFIGfrom app.persistence.communication_services import (@@ -36,7 +36,7 @@ class TwilioModel(BaseModel, frozen=True):auth_token: SecretStrphone_number: PhoneNumber- @lru_cache+ @cached_propertydef instance(self) -> ISms:from app.persistence.twilio import (TwilioSms,@@ -77,10 +77,11 @@ class SmsModel(BaseModel):raise ValueError("Twilio config required")return twilio+ @cached_propertydef instance(self) -> ISms:if self.mode == ModeEnum.COMMUNICATION_SERVICES:assert self.communication_services- return self.communication_services.instance()+ return self.communication_services.instanceassert self.twilio- return self.twilio.instance()+ return self.twilio.instancediff --git a/app/helpers/features.py b/app/helpers/features.pyindex 1233964..00fbc14 100644--- a/app/helpers/features.py+++ b/app/helpers/features.py@@ -3,7 +3,7 @@ from typing import TypeVar, castfrom azure.appconfiguration.aio import AzureAppConfigurationClientfrom azure.core.exceptions import ResourceNotFoundError-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.config import CONFIGfrom app.helpers.config_models.cache import MemoryModelfrom app.helpers.http import azure_transport@@ -233,7 +233,7 @@ async def _get(key: str, type_res: type[T]) -> T | None:)-@async_lru_cache()+@lru_acache()async def _use_client() -> AzureAppConfigurationClient:"""Generate the App Configuration client and close it after use.diff --git a/app/helpers/http.py b/app/helpers/http.pyindex 96469e2..aae6aeb 100644--- a/app/helpers/http.py+++ b/app/helpers/http.py@@ -9,10 +9,10 @@ from aiohttp_retry import JitterRetry, RetryClientfrom azure.core.pipeline.transport._aiohttp import AioHttpTransportfrom twilio.http.async_http_client import AsyncTwilioHttpClient-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acache-@async_lru_cache()+@lru_acache()async def _aiohttp_cookie_jar() -> DummyCookieJar:"""Create a cookie jar mock for AIOHTTP.@@ -24,7 +24,7 @@ async def _aiohttp_cookie_jar() -> DummyCookieJar:return DummyCookieJar()-@async_lru_cache()+@lru_acache()async def aiohttp_session() -> ClientSession:"""Create an AIOHTTP session.@@ -48,7 +48,7 @@ async def aiohttp_session() -> ClientSession:)-@async_lru_cache()+@lru_acache()async def azure_transport() -> AioHttpTransport:"""Create an AIOHTTP transport, for Azure SDK.@@ -64,7 +64,7 @@ async def azure_transport() -> AioHttpTransport:)-@async_lru_cache()+@lru_acache()async def twilio_http() -> AsyncTwilioHttpClient:"""Create a Twilio HTTP client.diff --git a/app/helpers/identity.py b/app/helpers/identity.pyindex e0f6796..eed3d37 100644--- a/app/helpers/identity.py+++ b/app/helpers/identity.py@@ -2,11 +2,11 @@ from collections.abc import Awaitable, Callablefrom azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.http import azure_transport-@async_lru_cache()+@lru_acache()async def credential() -> DefaultAzureCredential:return DefaultAzureCredential(# Performance@@ -14,6 +14,6 @@ async def credential() -> DefaultAzureCredential:)-@async_lru_cache()+@lru_acache()async def token(service: str) -> Callable[[], Awaitable[str]]:return get_bearer_token_provider(await credential(), service)diff --git a/app/helpers/llm_tools.py b/app/helpers/llm_tools.pyindex 08bbf61..c1eb127 100644--- a/app/helpers/llm_tools.py+++ b/app/helpers/llm_tools.py@@ -20,9 +20,9 @@ from app.models.message import (from app.models.reminder import ReminderModelfrom app.models.training import TrainingModel-_db = CONFIG.database.instance()-_search = CONFIG.ai_search.instance()-_sms = CONFIG.sms.instance()+_db = CONFIG.database.instance+_search = CONFIG.ai_search.instance+_sms = CONFIG.sms.instanceclass UpdateClaimDict(TypedDict):diff --git a/app/helpers/llm_utils.py b/app/helpers/llm_utils.pyindex 7ef7bf2..0a61056 100644--- a/app/helpers/llm_utils.py+++ b/app/helpers/llm_utils.py@@ -7,7 +7,7 @@ import asyncioimport inspectimport jsonfrom collections.abc import Awaitable, Callable-from functools import lru_cache, wraps+from functools import wrapsfrom inspect import getmembers, isfunctionfrom textwrap import dedentfrom types import FunctionType@@ -25,7 +25,7 @@ from pydantic import BaseModel, TypeAdapterfrom pydantic._internal._typing_extra import eval_type_lenientfrom pydantic.json_schema import JsonSchemaValue-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acache, lru_cachefrom app.helpers.logging import loggerfrom app.helpers.monitoring import SpanAttributeEnum, tracerfrom app.models.call import CallStateModel@@ -72,7 +72,7 @@ class AbstractPlugin:self.tts_callback = tts_callbackself.tts_client = tts_client- @async_lru_cache()+ @lru_acache()async def to_openai(self,blacklist: frozenset[str],@@ -161,7 +161,7 @@ class AbstractPlugin:# Enrich spanSpanAttributeEnum.TOOL_RESULT.attribute(tool.content)- @lru_cache+ @lru_cache()def _available_functions(self,blacklist: frozenset[str],diff --git a/app/helpers/llm_worker.py b/app/helpers/llm_worker.pyindex dec184f..adb532e 100644--- a/app/helpers/llm_worker.py+++ b/app/helpers/llm_worker.py@@ -1,6 +1,5 @@import jsonfrom collections.abc import AsyncGenerator, Callable-from functools import lru_cachefrom os import environfrom typing import TypeVar@@ -30,6 +29,7 @@ from tenacity import (wait_random_exponential,)+from app.helpers.cache import lru_cachefrom app.helpers.config import CONFIGfrom app.helpers.config_models.llm import DeploymentModel as LlmDeploymentModelfrom app.helpers.features import slow_llm_for_chat@@ -345,7 +345,7 @@ def _limit_messages( # noqa: PLR0913]-@lru_cache # Cache results in memory as token count is done many times on the same content+@lru_cache() # Cache results in memory as token count is done many times on the same contentdef _count_tokens(content: str, model: str) -> int:"""Returns the number of tokens in the content, using the model's encoding.@@ -379,4 +379,4 @@ async def _use_llm(The client is either an Azure OpenAI or an OpenAI client, depending on the configuration."""- return await CONFIG.llm.selected(is_fast).instance()+ return await CONFIG.llm.selected(is_fast).client()diff --git a/app/helpers/pydantic_types/phone_numbers.py b/app/helpers/pydantic_types/phone_numbers.pyindex 670b3ff..a96a0f2 100644--- a/app/helpers/pydantic_types/phone_numbers.py+++ b/app/helpers/pydantic_types/phone_numbers.py@@ -1,15 +1,16 @@from datetime import tzinfo-from functools import lru_cacheimport phonenumbersfrom pydantic_extra_types.phone_numbers import PhoneNumber as PydanticPhoneNumberfrom pytz import country_timezones, timezone, utc+from app.helpers.cache import lru_cache+class PhoneNumber(PydanticPhoneNumber):phone_format = "E164" # E164 is standard accross all Microsoft services- @lru_cache # Cache results in memory as func is executed many times on the same content+ @lru_cache() # Cache results in memory as func is executed many times on the same contentdef tz(self: PydanticPhoneNumber) -> tzinfo:"""Return timezone of a phone number.diff --git a/app/helpers/resources.py b/app/helpers/resources.pyindex 58bc0dc..4cbbc5d 100644--- a/app/helpers/resources.py+++ b/app/helpers/resources.py@@ -1,10 +1,11 @@-from functools import lru_cachefrom os import getcwdfrom os.path import abspath, joinfrom pathlib import Path+from app.helpers.cache import lru_cache-@lru_cache # Cache results in memory as resources are not expected to change++@lru_cache() # Cache results in memory as resources are not expected to changedef resources_dir(folder: str) -> str:"""Get the absolute path to the resources folder.diff --git a/app/helpers/translation.py b/app/helpers/translation.pyindex 9a3f33b..d2a139f 100644--- a/app/helpers/translation.py+++ b/app/helpers/translation.py@@ -9,14 +9,14 @@ from tenacity import (wait_random_exponential,)-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.config import CONFIGfrom app.helpers.http import azure_transportfrom app.helpers.logging import loggerlogger.info("Using Translation %s", CONFIG.ai_translation.endpoint)-_cache = CONFIG.cache.instance()+_cache = CONFIG.cache.instance@retry(@@ -61,7 +61,7 @@ async def translate_text(text: str, source_lang: str, target_lang: str) -> str |return translation-@async_lru_cache()+@lru_acache()async def _use_client() -> TextTranslationClient:"""Generate the Translation client and close it after use.diff --git a/app/main.py b/app/main.pyindex 513fb50..4a934bf 100644--- a/app/main.py+++ b/app/main.py@@ -41,7 +41,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_cache, get_scheduler+from app.helpers.cache import get_scheduler, lru_acachefrom app.helpers.call_events import (on_audio_connected,on_automation_play_completed,@@ -106,14 +106,14 @@ _communication_services_jwks_client = jwt.PyJWKClient()# Persistences-_cache = CONFIG.cache.instance()-_call_queue = CONFIG.queue.call()-_db = CONFIG.database.instance()-_post_queue = CONFIG.queue.post()-_search = CONFIG.ai_search.instance()-_sms = CONFIG.sms.instance()-_sms_queue = CONFIG.queue.sms()-_training_queue = CONFIG.queue.training()+_cache = CONFIG.cache.instance+_call_queue = CONFIG.queue.call+_db = CONFIG.database.instance+_post_queue = CONFIG.queue.post+_search = CONFIG.ai_search.instance+_sms = CONFIG.sms.instance+_sms_queue = CONFIG.queue.sms+_training_queue = CONFIG.queue.training# Communication Services callbackassert CONFIG.public_domain, "public_domain config is not set"@@ -1127,7 +1127,7 @@ def _standard_error()-@async_lru_cache()+@lru_acache()async def _use_automation_client() -> CallAutomationClient:"""Get the call automation client for Azure Communication Services.diff --git a/app/models/call.py b/app/models/call.pyindex c34c994..9c3bc76 100644--- a/app/models/call.py+++ b/app/models/call.py@@ -130,7 +130,7 @@ class CallStateModel(CallGetModel, extra="ignore"):from app.helpers.monitoring import tracerwith tracer.start_as_current_span("call_trainings"):- search = CONFIG.ai_search.instance()+ search = CONFIG.ai_search.instancetasks = await asyncio.gather(*[search.training_search_all(diff --git a/app/persistence/ai_search.py b/app/persistence/ai_search.pyindex 5719c3c..24ae49a 100644--- a/app/persistence/ai_search.py+++ b/app/persistence/ai_search.py@@ -45,7 +45,7 @@ from tenacity import (wait_random_exponential,)-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.config_models.ai_search import AiSearchModelfrom app.helpers.http import azure_transportfrom app.helpers.identity import credential@@ -182,7 +182,7 @@ class AiSearchSearch(ISearch):return trainings or None- @async_lru_cache()+ @lru_acache()async def _use_client(self) -> SearchClient:"""Get the search client.diff --git a/app/persistence/azure_queue_storage.py b/app/persistence/azure_queue_storage.pyindex df9f7f8..acac18e 100644--- a/app/persistence/azure_queue_storage.py+++ b/app/persistence/azure_queue_storage.py@@ -14,7 +14,7 @@ from tenacity import (wait_random_exponential,)-from app.helpers.cache import async_lru_cache, get_scheduler+from app.helpers.cache import get_scheduler, lru_acachefrom app.helpers.http import azure_transportfrom app.helpers.identity import credentialfrom app.helpers.logging import logger@@ -158,7 +158,7 @@ class AzureQueueStorage:# Then, delete messageawait self.delete_message(message)- @async_lru_cache()+ @lru_acache()async def _use_service_client(self) -> QueueServiceClient:"""Generate a new service client.diff --git a/app/persistence/communication_services.py b/app/persistence/communication_services.pyindex 4a3e6d4..520c705 100644--- a/app/persistence/communication_services.py+++ b/app/persistence/communication_services.py@@ -3,7 +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_cache+from app.helpers.cache import lru_acachefrom app.helpers.config_models.communication_services import CommunicationServicesModelfrom app.helpers.http import azure_transportfrom app.helpers.logging import logger@@ -55,7 +55,7 @@ class CommunicationServicesSms(ISms):logger.exception("Error sending SMS to %s", phone_number)return success- @async_lru_cache()+ @lru_acache()async def _use_client(self) -> SmsClient:logger.debug("Using SMS client for %s", self._config.endpoint)diff --git a/app/persistence/cosmos_db.py b/app/persistence/cosmos_db.pyindex 7b1de22..191854a 100644--- a/app/persistence/cosmos_db.py+++ b/app/persistence/cosmos_db.py@@ -10,7 +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_cache+from app.helpers.cache import lru_acachefrom app.helpers.config_models.database import CosmosDbModelfrom app.helpers.features import callback_timeout_hourfrom app.helpers.http import azure_transport@@ -373,7 +373,7 @@ class CosmosDbStore(IStore):return total- @async_lru_cache()+ @lru_acache()async def _use_service_client(self) -> CosmosClient:"""Generate the Cosmos DB client.diff --git a/app/persistence/redis.py b/app/persistence/redis.pyindex feb35b7..776ea95 100644--- a/app/persistence/redis.py+++ b/app/persistence/redis.py@@ -13,7 +13,7 @@ from redis.exceptions import (RedisError,)-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.config_models.cache import RedisModelfrom app.helpers.logging import loggerfrom app.models.readiness import ReadinessEnum@@ -116,7 +116,7 @@ class RedisCache(ICache):return Falsereturn True- @async_lru_cache()+ @lru_acache()async def _use_connection_pool(self) -> ConnectionPool:"""Generate the Redis connection pool.diff --git a/app/persistence/twilio.py b/app/persistence/twilio.pyindex b405d9c..941392d 100644--- a/app/persistence/twilio.py+++ b/app/persistence/twilio.py@@ -1,7 +1,7 @@from twilio.base.exceptions import TwilioRestExceptionfrom twilio.rest import Client-from app.helpers.cache import async_lru_cache+from app.helpers.cache import lru_acachefrom app.helpers.config_models.sms import TwilioModelfrom app.helpers.http import twilio_httpfrom app.helpers.logging import logger@@ -63,7 +63,7 @@ class TwilioSms(ISms):logger.exception("Error sending SMS to %s", phone_number)return success- @async_lru_cache()+ @lru_acache()async def _use_client(self) -> Client:logger.debug("Using Twilio client for %s", self._config.account_sid)diff --git a/tests/cache.py b/tests/cache.pyindex d98dca7..5568f5e 100644--- a/tests/cache.py+++ b/tests/cache.py@@ -37,7 +37,7 @@ async def test_acid("""# Set cache modeCONFIG.cache.mode = cache_mode- cache = CONFIG.cache.instance()+ cache = CONFIG.cache.instance# Init valuestest_key = random_textdiff --git a/tests/conftest.py b/tests/conftest.pyindex 8b23f98..ed645d2 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -308,7 +308,7 @@ def random_text() -> str:@pytest_asyncio.fixtureasync def call() -> CallStateModel:- db = CONFIG.database.instance()+ db = CONFIG.database.instancecall = await db.call_create(CallStateModel(initiate=CallInitiateModel(diff --git a/tests/llm.py b/tests/llm.pyindex 89644a2..39a41e3 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -254,7 +254,7 @@ async def test_llm( # noqa: PLR09133. Test claim data exists4. Test LLM metrics"""- db = CONFIG.database.instance()+ db = CONFIG.database.instancedef _play_media_callback(text: str) -> None:nonlocal actual_outputdiff --git a/tests/local.py b/tests/local.pyindex fac8a18..869efd4 100644--- a/tests/local.py+++ b/tests/local.py@@ -15,7 +15,7 @@ from app.models.call import CallInitiateModel, CallStateModelfrom app.models.message import MessageModel, PersonaEnum as MessagePersonaEnumfrom tests.conftest import CallAutomationClientMock, SpeechSynthesizerMock-_db = CONFIG.database.instance()+_db = CONFIG.database.instanceasync def main() -> None:diff --git a/tests/store.py b/tests/store.pyindex c74d844..284e746 100644--- a/tests/store.py+++ b/tests/store.py@@ -20,7 +20,7 @@ async def test_acid(call: CallStateModel) -> None:Test is repeated 10 times to catch multi-threading and concurrency issues."""- db = CONFIG.database.instance()+ db = CONFIG.database.instance# Check not existsassume(not await db.call_get(call.call_id))@@ -67,7 +67,7 @@ async def test_transaction("""Test transactional properties of the database backend."""- db = CONFIG.database.instance()+ db = CONFIG.database.instanceasync with Scheduler() as scheduler:# Check not exists