Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
perf: Use the same aiohttp session for the hole application
Clémence Lesné1bc347588826
diff --git a/Makefile b/Makefileindex cce7a69..a8bf716 100644--- a/Makefile+++ b/Makefile@@ -61,13 +61,12 @@ test:python3 -m deptry \--ignore-notebooks \--per-rule-ignores "DEP002=aiohttp" \+ --per-rule-ignores "DEP003=aiohttp_retry" \.@echo "➡️ Running Pytest..."PUBLIC_DOMAIN=dummy pytest \--alluredir test-reports \- --maxprocesses 4 \- -n logical \-ra \tests/*.pydiff --git a/function_app.py b/function_app.pyindex b61dde3..8a3e329 100644--- a/function_app.py+++ b/function_app.py@@ -7,11 +7,8 @@ logger.info(f"{APP_NAME} v{CONFIG.version}")# General imports-from typing import Any, Optional-from azure.communication.callautomation import (- CallAutomationClient,- PhoneNumberIdentifier,-)+from azure.communication.callautomation import PhoneNumberIdentifier+from azure.communication.callautomation.aio import CallAutomationClientfrom azure.core.credentials import AzureKeyCredentialfrom azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNames@@ -20,6 +17,7 @@ from jinja2 import Environment, FileSystemLoaderfrom models.call import CallStateModel, CallGetModel, CallInitiateModelfrom models.next import ActionEnum as NextActionEnumfrom twilio.twiml.messaging_response import MessagingResponse+from typing import Any, Optionalfrom urllib.parse import quote_plus, urljoinfrom uuid import UUIDimport asyncio@@ -39,15 +37,16 @@ from helpers.call_events import (on_transfer_completed,on_transfer_error,)+from helpers.http import azure_transportfrom helpers.call_utils import ContextEnum as CallContextEnumfrom htmlmin.minify import html_minifyfrom http import HTTPStatusfrom models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatus+from opentelemetry.semconv.trace import SpanAttributes+from os import getenvfrom pydantic import TypeAdapter, ValidationErrorimport azure.functions as funcimport json-from os import getenv-from opentelemetry.semconv.trace import SpanAttributes# Jinja configuration@@ -62,15 +61,9 @@ _jinja.filters["quote_plus"] = lambda x: quote_plus(str(x)) if x else ""_jinja.filters["markdown"] = lambda x: mistune.create_markdown(plugins=["abbr", "speedup", "url"])(x) if x else "" # type: ignore# Azure Communication Services+_automation_client: Optional[CallAutomationClient] = None_source_caller = PhoneNumberIdentifier(CONFIG.communication_services.phone_number)logger.info(f"Using phone number {str(CONFIG.communication_services.phone_number)}")-# Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)-_automation_client = CallAutomationClient(- endpoint=CONFIG.communication_services.endpoint,- credential=AzureKeyCredential(- CONFIG.communication_services.access_key.get_secret_value()- ),-)# Persistences_cache = CONFIG.cache.instance()@@ -266,7 +259,8 @@ async def call_post(req: func.HttpRequest) -> func.HttpResponse:trace.get_current_span().set_attribute(SpanAttributes.ENDUSER_ID, call.initiate.phone_number)- call_connection_properties = _automation_client.create_call(+ automation_client = await _use_automation_client()+ call_connection_properties = await automation_client.create_call(callback_url=url,cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,source_caller_id_number=_source_caller,@@ -307,7 +301,7 @@ async def call_event()await on_new_call(callback_url=url,- client=_automation_client,+ client=await _use_automation_client(),incoming_context=call_context,phone_number=phone_number,)@@ -352,7 +346,7 @@ async def sms_event()await on_sms_received(call=call,- client=_automation_client,+ client=await _use_automation_client(),message=message,post_callback=lambda _call: _trigger_post_event(call=_call, post=post),trainings_callback=lambda _call: _trigger_trainings_event(@@ -416,12 +410,13 @@ async def _communicationservices_event_worker(logger.warning(f"Secret for call {call_id} does not match")return+ # OpenTelemetrytrace.get_current_span().set_attribute(SpanAttributes.ENDUSER_ID, call.initiate.phone_number)+ # Event parsingevent = CloudEvent.from_dict(event_dict)assert isinstance(event.data, dict)-# Store connection IDconnection_id = event.data["callConnectionId"]call.voice_id = connection_id@@ -434,6 +429,8 @@ async def _communicationservices_event_worker(if operation_contextelse None)+ # Client SDK+ automation_client = await _use_automation_client()logger.debug(f"Call event received {event_type} for call {call}")logger.debug(event.data)@@ -441,13 +438,13 @@ async def _communicationservices_event_worker(if event_type == "Microsoft.Communication.CallConnected": # Call answeredawait on_call_connected(call=call,- client=_automation_client,+ client=automation_client,)elif event_type == "Microsoft.Communication.CallDisconnected": # Call hung upawait on_call_disconnected(call=call,- client=_automation_client,+ client=automation_client,post_callback=lambda _call: _trigger_post_event(call=_call, post=post),)@@ -461,7 +458,7 @@ async def _communicationservices_event_worker(if speech_text:await on_speech_recognized(call=call,- client=_automation_client,+ client=automation_client,text=speech_text,post_callback=lambda _call: _trigger_post_event(call=_call, post=post@@ -475,7 +472,7 @@ async def _communicationservices_event_worker(label_detected: str = event.data["choiceResult"]["label"]await on_ivr_recognized(call=call,- client=_automation_client,+ client=automation_client,label=label_detected,post_callback=lambda _call: _trigger_post_event(call=_call, post=post),trainings_callback=lambda _call: _trigger_trainings_event(@@ -496,20 +493,20 @@ async def _communicationservices_event_worker(if error_code in (8510, 8532): # Timeout retryawait on_speech_timeout_error(call=call,- client=_automation_client,+ client=automation_client,contexts=operation_contexts,)else: # Unknown errorawait on_speech_unknown_error(call=call,- client=_automation_client,+ client=automation_client,error_code=error_code,)elif event_type == "Microsoft.Communication.PlayCompleted": # Media playedawait on_play_completed(call=call,- client=_automation_client,+ client=automation_client,contexts=operation_contexts,post_callback=lambda _call: _trigger_post_event(call=_call, post=post),)@@ -531,7 +528,7 @@ async def _communicationservices_event_worker(sub_code: int = result_information["subCode"]await on_transfer_error(call=call,- client=_automation_client,+ client=automation_client,error_code=sub_code,)@@ -660,7 +657,7 @@ async def twilio_sms_post(event_status = await on_sms_received(call=call,message=message,- client=_automation_client,+ client=await _use_automation_client(),post_callback=lambda _call: _trigger_post_event(call=_call, post=post),trainings_callback=lambda _call: _trigger_trainings_event(call=_call, trainings=trainings@@ -697,3 +694,19 @@ def _validation_error(mimetype="application/json",status_code=HTTPStatus.BAD_REQUEST,)+++async def _use_automation_client() -> CallAutomationClient:+ global _automation_client+ if not isinstance(_automation_client, CallAutomationClient):+ _automation_client = CallAutomationClient(+ # Azure 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_clientdiff --git a/helpers/call_events.py b/helpers/call_events.pyindex c42e81d..e39ce82 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -1,11 +1,8 @@-from typing import Callable, Optional-from azure.communication.callautomation import (- CallAutomationClient,- DtmfTone,- RecognitionChoice,-)+from azure.communication.callautomation import DtmfTone, RecognitionChoice+from azure.communication.callautomation.aio import CallAutomationClientfrom helpers.config import CONFIGfrom helpers.logging import logger, tracer+from typing import Callable, Optionalfrom azure.core.exceptions import (ClientAuthenticationError,HttpResponseError,@@ -47,7 +44,7 @@ async def on_new_call(logger.debug(f"Incoming call handler caller ID: {phone_number}")try:- answer_call_result = client.answer_call(+ answer_call_result = await client.answer_call(callback_url=callback_url,cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,incoming_call_context=incoming_context,diff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex 9f590a6..d6821aa 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -1,5 +1,5 @@from typing import Awaitable, Callable, Optional, Tuple, Type-from azure.communication.callautomation import CallAutomationClient+from azure.communication.callautomation.aio import CallAutomationClientfrom helpers.config import CONFIGfrom helpers.logging import loggerfrom models.call import CallStateModel@@ -359,7 +359,7 @@ async def _execute_llm_chat(return new_style# Build RAG- trainings = await call.trainings(cache_only=True)+ trainings = await call.trainings()logger.info(f"Enhancing LLM chat with {len(trainings)} trainings")logger.debug(f"Trainings: {trainings}")diff --git a/helpers/call_utils.py b/helpers/call_utils.pyindex c389d63..dd00b43 100644--- a/helpers/call_utils.py+++ b/helpers/call_utils.py@@ -6,14 +6,16 @@ from models.call import CallStateModelfrom models.message import StyleEnum as MessageStyleEnumfrom typing import AsyncGenerator, Generator, Optionalfrom azure.communication.callautomation import (- CallAutomationClient,- CallConnectionClient,FileSource,PhoneNumberIdentifier,RecognitionChoice,RecognizeInputType,SsmlSource,)+from azure.communication.callautomation.aio import (+ CallAutomationClient,+ CallConnectionClient,+)from azure.core.exceptions import ResourceNotFoundError, HttpResponseErrorfrom models.message import (MessageModel,@@ -77,7 +79,7 @@ async def _handle_recognize_media(try:assert call.voice_id, "Voice ID is required for recognizing media"async with _use_call_client(client, call.voice_id) as call_client:- call_client.start_recognizing_media(+ await call_client.start_recognizing_media(end_silence_timeout=end_silence,input_type=RecognizeInputType.SPEECH,interrupt_prompt=True,@@ -117,7 +119,7 @@ async def handle_media(try:assert call.voice_id, "Voice ID is required for recognizing media"async with _use_call_client(client, call.voice_id) as call_client:- call_client.play_media(+ await call_client.play_media(operation_context=json.dumps([context]) if context else None,play_source=FileSource(url=sound_url),)@@ -192,7 +194,7 @@ async def handle_clear_queue(try:assert call.voice_id, "Voice ID is required for recognizing media"async with _use_call_client(client, call.voice_id) as call_client:- call_client.cancel_all_media_operations()+ await call_client.cancel_all_media_operations()except ResourceNotFoundError:logger.debug(f"Call hung up before playing")except HttpResponseError as e:@@ -290,7 +292,7 @@ async def handle_recognize_ivr(try:assert call.voice_id, "Voice ID is required for recognizing media"async with _use_call_client(client, call.voice_id) as call_client:- call_client.start_recognizing_media(+ await call_client.start_recognizing_media(choices=choices,end_silence_timeout=20,input_type=RecognizeInputType.CHOICES,@@ -315,7 +317,7 @@ async def handle_hangup(try:assert call.voice_id, "Voice ID is required for recognizing media"async with _use_call_client(client, call.voice_id) as call_client:- call_client.hang_up(is_for_everyone=True)+ await call_client.hang_up(is_for_everyone=True)except ResourceNotFoundError:logger.debug("Call already hung up")except HttpResponseError as e:@@ -335,7 +337,7 @@ async def handle_transfer(try:assert call.voice_id, "Voice ID is required for recognizing media"async with _use_call_client(client, call.voice_id) as call_client:- call_client.transfer_call_to_participant(+ await call_client.transfer_call_to_participant(operation_context=json.dumps([context]) if context else None,target_participant=PhoneNumberIdentifier(target),)diff --git a/helpers/config_models/llm.py b/helpers/config_models/llm.pyindex e90414e..b703db8 100644--- a/helpers/config_models/llm.py+++ b/helpers/config_models/llm.py@@ -1,9 +1,8 @@from azure.identity import ManagedIdentityCredential, get_bearer_token_provider-from contextlib import asynccontextmanagerfrom enum import Enumfrom openai import AsyncAzureOpenAI, AsyncOpenAIfrom pydantic import field_validator, SecretStr, BaseModel, ValidationInfo-from typing import Any, AsyncGenerator, Optional, Tuple, Union+from typing import Any, Optional, Tuple, Unionclass ModeEnum(str, Enum):@@ -11,7 +10,7 @@ class ModeEnum(str, Enum):OPENAI = "openai"-class AbstractPlatformModel(BaseModel, frozen=True):+class AbstractPlatformModel(BaseModel):_client_kwargs: dict[str, Any] = {# Reliability"max_retries": 0, # Retries are managed manually@@ -22,59 +21,51 @@ class AbstractPlatformModel(BaseModel, frozen=True):streaming: bool-class AzureOpenaiPlatformModel(AbstractPlatformModel, frozen=True):+class AzureOpenaiPlatformModel(AbstractPlatformModel):+ _client: Optional[AsyncAzureOpenAI] = Noneapi_key: Optional[SecretStr] = Nonedeployment: strendpoint: str- @asynccontextmanager- async def instance(- self,- ) -> AsyncGenerator[Tuple[AsyncAzureOpenAI, AbstractPlatformModel], None]:- api_key = self.api_key.get_secret_value() if self.api_key else None- token_func = (- get_bearer_token_provider(- ManagedIdentityCredential(),- "https://cognitiveservices.azure.com/.default",+ def instance(self) -> Tuple[AsyncAzureOpenAI, AbstractPlatformModel]:+ if not self._client:+ api_key = self.api_key.get_secret_value() if self.api_key else None+ token_func = (+ get_bearer_token_provider(+ ManagedIdentityCredential(),+ "https://cognitiveservices.azure.com/.default",+ )+ if not self.api_key+ else None)- if not self.api_key- else None- )- client = AsyncAzureOpenAI(- **self._client_kwargs,- # Azure deployment- api_version="2023-12-01-preview",- azure_deployment=self.deployment,- azure_endpoint=self.endpoint,- # Authentication, either RBAC or API key- api_key=api_key,- azure_ad_token_provider=token_func,- )- try:- yield client, self- finally:- await client.close()+ self._client = AsyncAzureOpenAI(+ **self._client_kwargs,+ # Azure deployment+ api_version="2023-12-01-preview",+ azure_deployment=self.deployment,+ azure_endpoint=self.endpoint,+ # Authentication+ api_key=api_key,+ azure_ad_token_provider=token_func,+ )+ return self._client, self-class OpenaiPlatformModel(AbstractPlatformModel, frozen=True):+class OpenaiPlatformModel(AbstractPlatformModel):+ _client: Optional[AsyncOpenAI] = Noneapi_key: SecretStrendpoint: str- @asynccontextmanager- async def instance(- self,- ) -> AsyncGenerator[Tuple[AsyncOpenAI, AbstractPlatformModel], None]:- client = AsyncOpenAI(- **self._client_kwargs,- # OpenAI deployment- base_url=self.endpoint,- # Authentication, either API key or no auth- api_key=self.api_key.get_secret_value(),- )- try:- yield client, self- finally:- await client.close()+ 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, selfclass SelectedPlatformModel(BaseModel):diff --git a/helpers/http.py b/helpers/http.pynew file mode 100644index 0000000..d52c903--- /dev/null+++ b/helpers/http.py@@ -0,0 +1,36 @@+from aiohttp import ClientSession, DummyCookieJar+from azure.core.pipeline.transport._aiohttp import AioHttpTransport+from typing import Optional+++_cookie_jar: Optional[DummyCookieJar] = None+_session: Optional[ClientSession] = None+_transport: Optional[AioHttpTransport] = None+++async def _aiohttp_cookie_jar() -> DummyCookieJar:+ global _cookie_jar+ if not _cookie_jar:+ _cookie_jar = DummyCookieJar()+ return _cookie_jar+++async def aiohttp_session() -> ClientSession:+ global _session+ if not _session:+ _session = ClientSession(+ auto_decompress=False,+ cookie_jar=await _aiohttp_cookie_jar(),+ trust_env=True,+ )+ return _session+++async def azure_transport() -> AioHttpTransport:+ global _transport+ if not _transport:+ _transport = AioHttpTransport(+ session_owner=False,+ session=await aiohttp_session(),+ )+ return _transportdiff --git a/helpers/llm_tools.py b/helpers/llm_tools.pyindex 1e0867c..adc05ff 100644--- a/helpers/llm_tools.py+++ b/helpers/llm_tools.py@@ -1,4 +1,4 @@-from azure.communication.callautomation import CallAutomationClient+from azure.communication.callautomation.aio import CallAutomationClientfrom helpers.call_utils import ContextEnum as CallContextEnum, handle_recognize_textfrom helpers.config import CONFIGfrom helpers.llm_utils import function_schemadiff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex c48e69c..f053f8c 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -8,7 +8,6 @@ from azure.ai.contentsafety.models import (from azure.core.credentials import AzureKeyCredentialfrom azure.core.exceptions import HttpResponseError, ServiceRequestErrorfrom helpers.config import CONFIG-from contextlib import asynccontextmanagerfrom helpers.logging import logger, tracerfrom openai import (APIConnectionError,@@ -50,6 +49,7 @@ from os import environfrom typing import AsyncGenerator, Optional, Tuple, Type, TypeVar, Unionimport jsonimport tiktoken+from helpers.http import azure_transport# Instrument OpenAI@@ -71,6 +71,7 @@ _retried_exceptions = [InternalServerError,RateLimitError,]+_contentsafety_client: Optional[ContentSafetyClient] = Noneclass SafetyCheckError(Exception):@@ -156,70 +157,64 @@ async def _completion_stream_worker(# Try liveto_cache: list[ChoiceDelta] = []- async with _use_llm(is_backup) as (client, platform):- extra = {}- if tools:- extra["tools"] = tools # Add tools if any-- prompt = _limit_messages(- context_window=platform.context,- max_messages=20, # Quick response- max_tokens=max_tokens,- messages=messages,- model=platform.model,- system=system,- tools=tools,- ) # Limit to 20 messages for quick response and avoid hallucinations- chat_kwargs = {- "max_tokens": max_tokens,- "messages": prompt,- "model": platform.model,- "seed": 42, # Reproducible results- "temperature": 0, # Most focused and deterministic- **extra,- } # Shared kwargs for both streaming and non-streaming-- if platform.streaming: # Streaming- stream: AsyncStream[ChatCompletionChunk] = (- await client.chat.completions.create(- **chat_kwargs,- stream=True,- )- )- async for chunck in stream:- choices = chunck.choices- if (- not choices- ): # Skip empty choices, happens sometimes with GPT-4 Turbo- continue- delta = choices[0].delta- yield delta- to_cache.append(delta)-- else: # Non-streaming, emulate streaming with a single completion- completion: ChatCompletion = await client.chat.completions.create(- **chat_kwargs- )- message = completion.choices[0].message- delta = ChoiceDelta(- content=message.content,- role=message.role,- tool_calls=[- ChoiceDeltaToolCall(- id=tool.id,- index=0,- type=tool.type,- function=ChoiceDeltaToolCallFunction(- arguments=tool.function.arguments,- name=tool.function.name,- ),- )- for tool in message.tool_calls or []- ],- )+ client, platform = _use_llm(is_backup)+ extra = {}+ if tools:+ extra["tools"] = tools # Add tools if any++ prompt = _limit_messages(+ context_window=platform.context,+ max_messages=20, # Quick response+ max_tokens=max_tokens,+ messages=messages,+ model=platform.model,+ system=system,+ tools=tools,+ ) # Limit to 20 messages for quick response and avoid hallucinations+ chat_kwargs = {+ "max_tokens": max_tokens,+ "messages": prompt,+ "model": platform.model,+ "seed": 42, # Reproducible results+ "temperature": 0, # Most focused and deterministic+ **extra,+ } # Shared kwargs for both streaming and non-streaming++ if platform.streaming: # Streaming+ stream: AsyncStream[ChatCompletionChunk] = await client.chat.completions.create(+ **chat_kwargs,+ stream=True,+ )+ async for chunck in stream:+ choices = chunck.choices+ if not choices: # Skip empty choices, happens sometimes with GPT-4 Turbo+ continue+ delta = choices[0].deltayield deltato_cache.append(delta)+ else: # Non-streaming, emulate streaming with a single completion+ completion: ChatCompletion = await client.chat.completions.create(**chat_kwargs)+ message = completion.choices[0].message+ delta = ChoiceDelta(+ content=message.content,+ role=message.role,+ tool_calls=[+ ChoiceDeltaToolCall(+ id=tool.id,+ index=0,+ type=tool.type,+ function=ChoiceDeltaToolCallFunction(+ arguments=tool.function.arguments,+ name=tool.function.name,+ ),+ )+ for tool in message.tool_calls or []+ ],+ )+ yield delta+ to_cache.append(delta)+# Update cacheawait _cache.aset(cache_key, TypeAdapter(list[ChoiceDelta]).dump_json(to_cache))@@ -286,28 +281,28 @@ async def _completion_sync_worker(# Try livecontent = None- async with _use_llm(is_backup) as (client, platform):- extra = {}- if json_output:- extra["response_format"] = {"type": "json_object"}+ client, platform = _use_llm(is_backup)+ extra = {}+ if json_output:+ extra["response_format"] = {"type": "json_object"}- prompt = _limit_messages(- context_window=platform.context,- max_tokens=max_tokens,- messages=[],- model=platform.model,- system=system,- )+ prompt = _limit_messages(+ context_window=platform.context,+ max_tokens=max_tokens,+ messages=[],+ model=platform.model,+ system=system,+ )- res = await client.chat.completions.create(- max_tokens=max_tokens,- messages=prompt,- model=platform.model,- seed=42, # Reproducible results- temperature=0, # Most focused and deterministic- **extra,- )- content = res.choices[0].message.content+ res = await client.chat.completions.create(+ max_tokens=max_tokens,+ messages=prompt,+ model=platform.model,+ seed=42, # Reproducible results+ temperature=0, # Most focused and deterministic+ **extra,+ )+ content = res.choices[0].message.content# Update cacheif content:@@ -488,15 +483,15 @@ async def _contentsafety_analysis(text: str) -> AnalyzeTextResult:Catch errors for a maximum of 3 times (internal + `HttpResponseError`), then raise the error."""- async with _use_contentsafety() as client:- res = await client.analyze_text(- AnalyzeTextOptions(- blocklist_names=CONFIG.content_safety.blocklists,- halt_on_blocklist_hit=False,- output_type="EightSeverityLevels",- text=text,- )+ client = await _use_contentsafety()+ res = await client.analyze_text(+ AnalyzeTextOptions(+ blocklist_names=CONFIG.content_safety.blocklists,+ halt_on_blocklist_hit=False,+ output_type="EightSeverityLevels",+ text=text,)+ )return res@@ -539,36 +534,31 @@ def _llm_key(is_backup: bool) -> str:return f"{platform.model}-{platform.context}"-@asynccontextmanager-async def _use_llm(+def _use_llm(is_backup: bool,-) -> AsyncGenerator[- Tuple[Union[AsyncAzureOpenAI, AsyncOpenAI], LlmAbstractPlatformModel], None-]:+) -> Tuple[Union[AsyncAzureOpenAI, AsyncOpenAI], LlmAbstractPlatformModel]:"""Returns an LLM client and platform model.The client is either an Azure OpenAI or an OpenAI client, depending on the configuration."""- async with CONFIG.llm.selected(is_backup).instance() as (client, platform):- yield client, platform+ return CONFIG.llm.selected(is_backup).instance()-@asynccontextmanager-async def _use_contentsafety() -> AsyncGenerator[ContentSafetyClient, None]:+async def _use_contentsafety() -> ContentSafetyClient:"""Returns a Content Safety client."""- client = ContentSafetyClient(- # Azure deployment- endpoint=CONFIG.content_safety.endpoint,- # Authentication with API key- credential=AzureKeyCredential(- CONFIG.content_safety.access_key.get_secret_value()- ),- )-- try:- yield client- finally:- await client.close()+ global _contentsafety_client+ if not isinstance(_contentsafety_client, ContentSafetyClient):+ _contentsafety_client = ContentSafetyClient(+ # Azure deployment+ endpoint=CONFIG.content_safety.endpoint,+ # Performance+ transport=await azure_transport(),+ # Authentication+ credential=AzureKeyCredential(+ CONFIG.content_safety.access_key.get_secret_value()+ ),+ )+ return _contentsafety_clientdiff --git a/helpers/translation.py b/helpers/translation.pyindex aa11e2f..34f2c5a 100644--- a/helpers/translation.py+++ b/helpers/translation.py@@ -2,10 +2,10 @@ from azure.ai.translation.text.aio import TextTranslationClientfrom azure.ai.translation.text.models import TranslatedTextItemfrom azure.core.credentials import AzureKeyCredentialfrom azure.core.exceptions import HttpResponseError-from contextlib import asynccontextmanager+from helpers.http import azure_transportfrom helpers.config import CONFIGfrom helpers.logging import logger-from typing import AsyncGenerator, Optional+from typing import Optionalfrom tenacity import (retry_if_exception_type,retry,@@ -17,6 +17,7 @@ from tenacity import (logger.info(f"Using Translation {CONFIG.ai_translation.endpoint}")_cache = CONFIG.cache.instance()+_client = Optional[TextTranslationClient]@retry(@@ -44,15 +45,13 @@ async def translate_text(# Try livetranslation: Optional[str] = None- async with _use_client() as client: # Perform translation- res: list[TranslatedTextItem] = await client.translate(- body=[text],- from_language=source_lang,- to_language=[target_lang],- )- translation = (- res[0].translations[0].text if res and res[0].translations else None- )+ client = await _use_client()+ res: list[TranslatedTextItem] = await client.translate(+ body=[text],+ from_language=source_lang,+ to_language=[target_lang],+ )+ translation = res[0].translations[0].text if res and res[0].translations else None# Update cacheawait _cache.aset(cache_key, translation)@@ -60,15 +59,20 @@ async def translate_text(return translation-@asynccontextmanager-async def _use_client() -> AsyncGenerator[TextTranslationClient, None]:- client = TextTranslationClient(- credential=AzureKeyCredential(- CONFIG.ai_translation.access_key.get_secret_value()- ),- endpoint=CONFIG.ai_translation.endpoint,- )- try:- yield client- finally:- await client.close()+async def _use_client() -> TextTranslationClient:+ """+ Generate the Translation client and close it after use.+ """+ global _client+ if not isinstance(_client, TextTranslationClient):+ _client = TextTranslationClient(+ # Performance+ transport=await azure_transport(),+ # Azure deployment+ endpoint=CONFIG.ai_translation.endpoint,+ # Authentication+ credential=AzureKeyCredential(+ CONFIG.ai_translation.access_key.get_secret_value()+ ),+ )+ return _clientdiff --git a/persistence/ai_search.py b/persistence/ai_search.pyindex c11d7ae..35a55f3 100644--- a/persistence/ai_search.py+++ b/persistence/ai_search.py@@ -12,7 +12,7 @@ from azure.search.documents.models import (SearchMode,VectorizableTextQuery,)-from contextlib import asynccontextmanager+from helpers.http import azure_transportfrom helpers.config_models.ai_search import AiSearchModelfrom helpers.logging import loggerfrom models.readiness import ReadinessStatus@@ -21,7 +21,7 @@ from persistence.icache import ICachefrom persistence.isearch import ISearchfrom pydantic import TypeAdapterfrom pydantic import ValidationError-from typing import AsyncGenerator, Optional+from typing import Optionalfrom tenacity import (retry,stop_after_attempt,@@ -31,23 +31,24 @@ from tenacity import (class AiSearchSearch(ISearch):+ _client: Optional[SearchClient] = None_config: AiSearchModeldef __init__(self, cache: ICache, config: AiSearchModel):+ super().__init__(cache)logger.info(f"Using AI Search {config.endpoint} with index {config.index}")logger.info(f"Note: At ~300 chars /doc, each LLM call will use approx {300 * config.top_n_documents * config.expansion_n_messages / 4} tokens (without tools)")self._config = config- super().__init__(cache)async def areadiness(self) -> ReadinessStatus:"""Check the readiness of the AI Search service."""try:- async with self._use_db() as db:- await db.get_document_count()+ async with await self._use_client() as client:+ await client.get_document_count()return ReadinessStatus.OKexcept HttpResponseError as e:logger.error(f"Error requesting AI Search, {e}")@@ -87,8 +88,8 @@ class AiSearchSearch(ISearch):# Try livetrainings: list[TrainingModel] = []try:- async with self._use_db() as db:- results = await db.search(+ async with await self._use_client() as client:+ results = await client.search(# Full text searchquery_language=QueryLanguage(lang.lower()),query_type=QueryType.SEMANTIC,@@ -147,17 +148,17 @@ class AiSearchSearch(ISearch):return trainings or None- @asynccontextmanager- async def _use_db(self) -> AsyncGenerator[SearchClient, None]:- """- Generate the AI Search client and close it after use.- """- db = SearchClient(- credential=AzureKeyCredential(self._config.access_key.get_secret_value()),- endpoint=self._config.endpoint,- index_name=self._config.index,- )- try:- yield db- finally:- await db.close()+ async def _use_client(self) -> SearchClient:+ if not self._client:+ self._client = SearchClient(+ # Azure deployment+ endpoint=self._config.endpoint,+ index_name=self._config.index,+ # Performance+ transport=await azure_transport(),+ # Authentication+ credential=AzureKeyCredential(+ self._config.access_key.get_secret_value()+ ),+ )+ return self._clientdiff --git a/persistence/communication_services.py b/persistence/communication_services.pyindex f1eff24..e834236 100644--- a/persistence/communication_services.py+++ b/persistence/communication_services.py@@ -1,16 +1,17 @@from azure.communication.sms import SmsSendResultfrom azure.communication.sms.aio import SmsClientfrom azure.core.exceptions import ClientAuthenticationError, HttpResponseError-from contextlib import asynccontextmanager+from helpers.http import azure_transportfrom helpers.config_models.communication_services import CommunicationServicesModelfrom helpers.logging import loggerfrom helpers.pydantic_types.phone_numbers import PhoneNumberfrom models.readiness import ReadinessStatusfrom persistence.isms import ISms-from typing import AsyncGenerator+from typing import Optionalclass CommunicationServicesSms(ISms):+ _client: Optional[SmsClient] = None_config: CommunicationServicesModeldef __init__(self, config: CommunicationServicesModel):@@ -29,7 +30,7 @@ class CommunicationServicesSms(ISms):success = Falselogger.info(f"SMS content: {content}")try:- async with self._use_client() as client:+ async with await self._use_client() as client:responses: list[SmsSendResult] = await client.send(from_=str(self._config.phone_number),message=content,@@ -53,13 +54,14 @@ class CommunicationServicesSms(ISms):logger.warning(f"Failed SMS to {phone_number}", exc_info=True)return success- @asynccontextmanager- async def _use_client(self) -> AsyncGenerator[SmsClient, None]:- client = SmsClient(- credential=self._config.access_key.get_secret_value(),- endpoint=self._config.endpoint,- )- try:- yield client- finally:- await client.close()+ async def _use_client(self) -> SmsClient:+ if not self._client:+ self._client = SmsClient(+ # Azure deployment+ endpoint=self._config.endpoint,+ # Performance+ transport=await azure_transport(),+ # Authentication+ credential=self._config.access_key.get_secret_value(),+ )+ return self._clientdiff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex 8978f30..e1ff7f6 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -1,8 +1,8 @@-import asyncio-from azure.core.exceptions import ServiceResponseError+from azure.cosmos import ConsistencyLevelfrom azure.cosmos.aio import CosmosClient, ContainerProxyfrom azure.cosmos.exceptions import CosmosHttpResponseErrorfrom contextlib import asynccontextmanager+from helpers.http import azure_transportfrom helpers.config import CONFIGfrom helpers.config_models.database import CosmosDbModelfrom helpers.logging import logger@@ -12,9 +12,11 @@ from persistence.istore import IStorefrom pydantic import ValidationErrorfrom typing import AsyncGenerator, Optionalfrom uuid import UUID, uuid4+import asyncioclass CosmosDbStore(IStore):+ _client: Optional[CosmosClient] = None_config: CosmosDbModeldef __init__(self, config: CosmosDbModel):@@ -40,7 +42,7 @@ class CosmosDbStore(IStore):# Test the item does not existif await self._item_exists(test_id, test_partition):return ReadinessStatus.FAIL- async with self._use_db() as db:+ async with self._use_client() as db:# Create a new itemawait db.upsert_item(body=test_dict)# Test the item is the same@@ -64,7 +66,7 @@ class CosmosDbStore(IStore):async def _item_exists(self, test_id: str, partition_key: str) -> bool:exist = False- async with self._use_db() as db:+ async with self._use_client() as db:try:await db.read_item(item=test_id, partition_key=partition_key)exist = True@@ -78,7 +80,7 @@ class CosmosDbStore(IStore):logger.debug(f"Loading call {call_id}")call = Nonetry:- async with self._use_db() as db:+ async with self._use_client() as db:items = db.query_items(query="SELECT * FROM c WHERE STRINGEQUALS(c.id, @id)",parameters=[{"name": "@id", "value": str(call_id)}],@@ -99,7 +101,7 @@ class CosmosDbStore(IStore):data["id"] = str(call.call_id) # CosmosDB requires an id fieldlogger.debug(f"Saving call {call.call_id}: {data}")try:- async with self._use_db() as db:+ async with self._use_client() as db:await db.upsert_item(body=data)return Trueexcept CosmosHttpResponseError as e:@@ -110,7 +112,7 @@ class CosmosDbStore(IStore):logger.debug(f"Loading last call for {phone_number}")call = Nonetry:- async with self._use_db() as db:+ async with self._use_client() as db:items = db.query_items(max_item_count=1,query=f"SELECT * FROM c WHERE (STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)) AND c.created_at >= DATETIMEADD('hh', -{CONFIG.workflow.conversation_timeout_hour}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",@@ -151,7 +153,7 @@ class CosmosDbStore(IStore):) -> Optional[list[CallStateModel]]:calls: list[CallStateModel] = []try:- async with self._use_db() as db:+ async with self._use_client() as db:where_clause = ("WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)"if phone_number@@ -186,7 +188,7 @@ class CosmosDbStore(IStore):phone_number: Optional[str] = None,) -> int:try:- async with self._use_db() as db:+ async with self._use_client() as db:where_clause = ("WHERE STRINGEQUALS(c.initiate.phone_number, @phone_number, true) OR STRINGEQUALS(c.claim.policyholder_phone, @phone_number, true)"if phone_number@@ -207,23 +209,26 @@ class CosmosDbStore(IStore):return total if total else 0@asynccontextmanager- async def _use_db(self) -> AsyncGenerator[ContainerProxy, None]:+ async def _use_client(self) -> AsyncGenerator[ContainerProxy, None]:"""Generate the Cosmos DB client and close it after use."""- client = CosmosClient(- # Reliability- connection_timeout=10,- retry_backoff_factor=0.5,- retry_backoff_max=30,- retry_total=3,- # Azure deployment- url=self._config.endpoint,- # Authentication with API key- credential=self._config.access_key.get_secret_value(),- )- try:+ if not self._client:+ self._client = CosmosClient(+ # Usage+ consistency_level=ConsistencyLevel.Eventual,+ # Reliability+ connection_timeout=10,+ retry_backoff_factor=0.5,+ retry_backoff_max=30,+ retry_total=3,+ # Performance+ transport=await azure_transport(),+ # Azure deployment+ url=self._config.endpoint,+ # Authentication+ credential=self._config.access_key.get_secret_value(),+ )+ async with self._client as client:database = client.get_database_client(self._config.database)yield database.get_container_client(self._config.container)- finally:- await client.close()diff --git a/persistence/redis.py b/persistence/redis.pyindex fa92c99..c5005f7 100644--- a/persistence/redis.py+++ b/persistence/redis.py@@ -1,4 +1,3 @@-from contextlib import asynccontextmanagerfrom helpers.config_models.cache import RedisModelfrom helpers.logging import loggerfrom models.readiness import ReadinessStatus@@ -8,7 +7,7 @@ from redis.asyncio import Redisfrom redis.asyncio.retry import Retryfrom redis.backoff import ExponentialBackofffrom redis.exceptions import BusyLoadingError, ConnectionError, RedisError-from typing import AsyncGenerator, Optional, Union+from typing import Optional, Unionfrom uuid import uuid4import hashlib@@ -20,11 +19,28 @@ _retry = Retry(backoff=ExponentialBackoff(), retries=3)class RedisCache(ICache):+ _client: Redis_config: RedisModeldef __init__(self, config: RedisModel):logger.info(f"Using Redis cache {config.host}:{config.port}")self._config = config+ self._client = Redis(+ # Database location+ db=config.database,+ # Reliability+ retry_on_error=[BusyLoadingError, ConnectionError],+ retry_on_timeout=True,+ retry=_retry,+ socket_connect_timeout=1, # Timeout for connection, we want it to fail fast, that's cache+ socket_timeout=10, # Timeout for queries+ # Azure deployment+ host=config.host,+ port=config.port,+ ssl=config.ssl,+ # Authentication+ password=config.password.get_secret_value(),+ ) # Redis manage by itself a low level connection pool with asyncio, but be warning to not use a generator while consuming the connection, it will close itasync def areadiness(self) -> ReadinessStatus:"""@@ -35,17 +51,16 @@ class RedisCache(ICache):test_name = str(uuid4())test_value = "test"try:- async with self._use_db() as db:- # Test the item does not exist- assert await db.get(test_name) is None- # Create a new item- await db.set(test_name, test_value)- # Test the item is the same- assert (await db.get(test_name)).decode() == test_value- # Delete the item- await db.delete(test_name)- # Test the item does not exist- assert await db.get(test_name) is None+ # Test the item does not exist+ assert await self._client.get(test_name) is None+ # Create a new item+ await self._client.set(test_name, test_value)+ # Test the item is the same+ assert (await self._client.get(test_name)).decode() == test_value+ # Delete the item+ await self._client.delete(test_name)+ # Test the item does not exist+ assert await self._client.get(test_name) is Nonereturn ReadinessStatus.OKexcept AssertionError as e:logger.error(f"Readiness test failed, {e}")@@ -64,8 +79,7 @@ class RedisCache(ICache):sha_key = self._key_to_hash(key)res = Nonetry:- async with self._use_db() as db:- res = await db.get(sha_key)+ res = await self._client.get(sha_key)except RedisError as e:logger.error(f"Error getting value, {e}")return res@@ -80,39 +94,12 @@ class RedisCache(ICache):"""sha_key = self._key_to_hash(key)try:- async with self._use_db() as db:- await db.set(sha_key, value if value else "")+ await self._client.set(sha_key, value if value else "")except RedisError as e:logger.error(f"Error setting value, {e}")return Falsereturn True- @asynccontextmanager- async def _use_db(self) -> AsyncGenerator[Redis, None]:- """- Generate the Redis client and close it after use.- """- client = Redis(- # Database location- db=self._config.database,- # Reliability- retry_on_error=[BusyLoadingError, ConnectionError],- retry_on_timeout=True,- retry=_retry,- socket_connect_timeout=1, # Timeout for connection, we want it to fail fast, that's cache- socket_timeout=10, # Timeout for queries- # Azure deployment- host=self._config.host,- port=self._config.port,- ssl=self._config.ssl,- # Authentication with password- password=self._config.password.get_secret_value(),- )- try:- yield client- finally:- await client.aclose()-@staticmethoddef _key_to_hash(key: str) -> bytes:"""diff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex 31c81aa..f0ea2fd 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -1,4 +1,4 @@-from aiosqlite import connect as sqlite_connect, Connection as SQLiteConnection+from aiosqlite import connect as sqlite_connect, Connectionfrom contextlib import asynccontextmanagerfrom helpers.config import CONFIGfrom helpers.config_models.database import SqliteModel@@ -19,12 +19,24 @@ SQLite3Instrumentor().instrument()class SqliteStore(IStore):+ _client: Connection_config: SqliteModel+ _first_run_done: bool = Falsedef __init__(self, config: SqliteModel):logger.info(f"Using SQLite database at {config.path} with table {config.table}")self._config = config+ # Create folder if does not exist+ db_path = self._config.full_path()+ if not os.path.isfile(db_path):+ db_folder = db_path[: db_path.rfind("/")]+ os.makedirs(name=db_folder, exist_ok=True)+ self._first_run_done = True++ # Init client+ self._client = sqlite_connect(database=db_path)+async def areadiness(self) -> ReadinessStatus:"""Check the readiness of the SQLite database.@@ -159,7 +171,7 @@ class SqliteStore(IStore):row = await cursor.fetchone()return int(row[0]) if row else 0- async def _init_db(self, db: SQLiteConnection):+ async def _init_db(self, db: Connection):"""Initialize the database.@@ -187,20 +199,11 @@ class SqliteStore(IStore):await db.commit()@asynccontextmanager- async def _use_db(self) -> AsyncGenerator[SQLiteConnection, None]:+ async def _use_db(self) -> AsyncGenerator[Connection, None]:"""Generate the SQLite client and close it after use."""- # Create folder- db_path = self._config.full_path()- first_run = False- if not os.path.isfile(db_path):- db_folder = db_path[: db_path.rfind("/")]- os.makedirs(name=db_folder, exist_ok=True)- first_run = True-- # Connect to DB- async with sqlite_connect(database=db_path) as db:- if first_run:- await self._init_db(db)- yield db+ async with self._client as client:+ if self._first_run_done:+ await self._init_db(client)+ yield clientdiff --git a/persistence/twilio.py b/persistence/twilio.pyindex 8264fcb..c418bbc 100644--- a/persistence/twilio.py+++ b/persistence/twilio.py@@ -1,23 +1,23 @@+from aiohttp_retry import ExponentialRetry, RetryClient+from helpers.http import aiohttp_sessionfrom helpers.config_models.sms import TwilioModelfrom helpers.logging import loggerfrom helpers.pydantic_types.phone_numbers import PhoneNumberfrom models.readiness import ReadinessStatusfrom persistence.isms import ISmsfrom twilio.base.exceptions import TwilioRestException+from twilio.http.async_http_client import AsyncTwilioHttpClientfrom twilio.rest import Client+from typing import Optionalclass TwilioSms(ISms):- _client: Client+ _client: Optional[Client] = None_config: TwilioModeldef __init__(self, config: TwilioModel):logger.info(f"Using Twilio from number {config.phone_number}")self._config = config- self._client = Client(- password=config.auth_token.get_secret_value(),- username=config.account_sid,- ) # TODO: Use async client, but get multiple "attached to a different loop" errors with AsyncTwilioHttpClientasync def areadiness(self) -> ReadinessStatus:"""@@ -26,8 +26,9 @@ class TwilioSms(ISms):This only check if the Twilio API is reachable and the account has remaining balance."""account_sid = self._config.account_sid+ client = await self._use_client()try:- account = self._client.api.accounts(account_sid).fetch()+ account = await client.api.accounts(account_sid).fetch_async()balance = account.balance.fetch()assert balance.balance and float(balance.balance) > 0return ReadinessStatus.OK@@ -39,8 +40,9 @@ class TwilioSms(ISms):logger.info(f"Sending SMS to {phone_number}")success = Falselogger.info(f"SMS content: {content}")+ client = await self._use_client()try:- res = self._client.messages.create(+ res = await client.messages.create_async(body=content,from_=str(self._config.phone_number),to=phone_number,@@ -58,3 +60,19 @@ class TwilioSms(ISms):except Exception:logger.warning(f"Failed SMS to {phone_number}", exc_info=True)return success++ async def _use_client(self) -> Client:+ if not self._client:+ http = AsyncTwilioHttpClient()+ http.session = RetryClient(+ client_session=await aiohttp_session(),+ retry_options=ExponentialRetry(attempts=3),+ ) # Use the same session as the rest of the application, and retry 3 times with exponential backoff with the same lib as Twilio+ self._client = Client(+ # Performance+ http_client=http,+ # Authentication+ password=self._config.auth_token.get_secret_value(),+ username=self._config.account_sid,+ )+ return self._clientdiff --git a/tests/cache.py b/tests/cache.pyindex 2852fae..6017f9a 100644--- a/tests/cache.py+++ b/tests/cache.py@@ -17,7 +17,7 @@ import pytest),],)[email protected] # Allow async functions[email protected](scope="session")@pytest.mark.repeat(10) # Catch multi-threading and concurrency issuesasync def test_acid(random_text: str, cache_mode: CacheModeEnum) -> None:"""diff --git a/tests/conftest.py b/tests/conftest.pyindex 1607823..b6cca29 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -13,12 +13,14 @@ import randomimport stringimport xml.etree.ElementTree as ETfrom azure.communication.callautomation import (- CallAutomationClient,- CallConnectionClient,FileSource,SsmlSource,TextSource,)+from azure.communication.callautomation.aio import (+ CallAutomationClient,+ CallConnectionClient,+)from _pytest.mark.structures import MarkDecoratorfrom pydantic import BaseModel, ValidationErrorimport yaml@@ -44,14 +46,14 @@ class CallConnectionClientMock(CallConnectionClient):def __init__(self, play_media_callback: Callable[[str], None]) -> None:self._play_media_callback = play_media_callback- def start_recognizing_media(+ async def start_recognizing_media(self,*args,**kwargs,) -> None:pass- def play_media(+ async def play_media(self,play_source: Union[FileSource, TextSource, SsmlSource],*args,@@ -65,21 +67,21 @@ class CallConnectionClientMock(CallConnectionClient):if text.strip():self._play_media_callback(text.strip())- def transfer_call_to_participant(+ async def transfer_call_to_participant(self,*args,**kwargs,) -> None:pass- def hang_up(+ async def hang_up(self,*args,**kwargs,) -> None:pass- def cancel_all_media_operations(+ async def cancel_all_media_operations(self,*args,**kwargs,diff --git a/tests/llm.py b/tests/llm.pyindex 1b9694f..291d8d8 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -23,7 +23,7 @@ import pytest@with_conversations[email protected] # Allow async functions[email protected](scope="session")@pytest.mark.repeat(3) # Catch non deterministic issuesasync def test_llm(call: CallStateModel,diff --git a/tests/search.py b/tests/search.pyindex 3ad7bc1..8780d9d 100644--- a/tests/search.py+++ b/tests/search.py@@ -108,7 +108,7 @@ class RagRelevancyMetric(BaseMetric):@with_conversations[email protected] # Allow async functions[email protected](scope="session")@pytest.mark.repeat(10) # Catch multi-threading and concurrency issuesasync def test_relevancy(call: CallStateModel,diff --git a/tests/store.py b/tests/store.pyindex 792228d..a72518b 100644--- a/tests/store.py+++ b/tests/store.py@@ -18,7 +18,7 @@ import pytest),],)[email protected] # Allow async functions[email protected](scope="session")@pytest.mark.repeat(10) # Catch multi-threading and concurrency issuesasync def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> None:"""