Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

perf: Init once the Twilio conn pool

Clémence Lesné648041406031
diff --git a/helpers/http.py b/helpers/http.py
index d52c903..17ad64c 100644
--- a/helpers/http.py
+++ b/helpers/http.py
@@ -1,11 +1,14 @@
from aiohttp import ClientSession, DummyCookieJar
+from aiohttp_retry import JitterRetry, RetryClient
from azure.core.pipeline.transport._aiohttp import AioHttpTransport
+from twilio.http.async_http_client import AsyncTwilioHttpClient
from typing import Optional
_cookie_jar: Optional[DummyCookieJar] = None
_session: Optional[ClientSession] = None
_transport: Optional[AioHttpTransport] = None
+_twilio_http: Optional[AsyncTwilioHttpClient] = None
async def _aiohttp_cookie_jar() -> DummyCookieJar:
@@ -34,3 +37,21 @@ async def azure_transport() -> AioHttpTransport:
session=await aiohttp_session(),
)
return _transport
+
+
+async def twilio_http() -> AsyncTwilioHttpClient:
+ global _twilio_http
+ 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,
+ ),
+ )
+ return _twilio_http
diff --git a/persistence/twilio.py b/persistence/twilio.py
index c418bbc..96a226e 100644
--- a/persistence/twilio.py
+++ b/persistence/twilio.py
@@ -1,12 +1,10 @@
-from aiohttp_retry import ExponentialRetry, RetryClient
-from helpers.http import aiohttp_session
from helpers.config_models.sms import TwilioModel
+from helpers.http import twilio_http
from helpers.logging import logger
from helpers.pydantic_types.phone_numbers import PhoneNumber
from models.readiness import ReadinessStatus
from persistence.isms import ISms
from twilio.base.exceptions import TwilioRestException
-from twilio.http.async_http_client import AsyncTwilioHttpClient
from twilio.rest import Client
from typing import Optional
@@ -63,14 +61,9 @@ class TwilioSms(ISms):
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,
+ http_client=await twilio_http(),
# Authentication
password=self._config.auth_token.get_secret_value(),
username=self._config.account_sid,