Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
perf: Cache stores
Clémence Lesné5118b6d6fe8a
diff --git a/helpers/config_models/database.py b/helpers/config_models/database.pyindex c93a4e6..355fc1f 100644--- a/helpers/config_models/database.py+++ b/helpers/config_models/database.py@@ -18,9 +18,10 @@ class CosmosDbModel(BaseModel, frozen=True):@cachedef instance(self) -> IStore:+ from helpers.config import CONFIGfrom persistence.cosmos_db import CosmosDbStore- return CosmosDbStore(self)+ return CosmosDbStore(CONFIG.cache.instance(), self)class SqliteModel(BaseModel, frozen=True):@@ -38,9 +39,10 @@ class SqliteModel(BaseModel, frozen=True):@cachedef instance(self) -> IStore:+ from helpers.config import CONFIGfrom persistence.sqlite import SqliteStore- return SqliteStore(self)+ return SqliteStore(CONFIG.cache.instance(), self)class DatabaseModel(BaseModel):diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex e1ff7f6..16dddfa 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -2,12 +2,13 @@ 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 CosmosDbModel+from helpers.http import azure_transportfrom helpers.logging import loggerfrom models.call import CallStateModelfrom models.readiness import ReadinessStatus+from persistence.icache import ICachefrom persistence.istore import IStorefrom pydantic import ValidationErrorfrom typing import AsyncGenerator, Optional@@ -19,7 +20,8 @@ class CosmosDbStore(IStore):_client: Optional[CosmosClient] = None_config: CosmosDbModel- def __init__(self, config: CosmosDbModel):+ def __init__(self, cache: ICache, config: CosmosDbModel):+ super().__init__(cache)logger.info(f"Using Cosmos DB {config.database}/{config.container}")self._config = config@@ -78,6 +80,17 @@ class CosmosDbStore(IStore):async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:logger.debug(f"Loading call {call_id}")++ # Try cache+ cache_key = self._cache_key_call_id(call_id)+ cached = await self._cache.aget(cache_key)+ if cached:+ try:+ return CallStateModel.model_validate_json(cached)+ except ValidationError as e:+ logger.debug(f"Parsing error: {e.errors()}")++ # Try livecall = Nonetry:async with self._use_client() as db:@@ -94,22 +107,48 @@ class CosmosDbStore(IStore):passexcept CosmosHttpResponseError as e:logger.error(f"Error accessing CosmosDB, {e}")++ # Update cache+ if call:+ await self._cache.aset(cache_key, call.model_dump_json())+return callasync def call_aset(self, call: CallStateModel) -> bool:+ logger.debug(f"Saving call {call.call_id}")++ # Update livedata = call.model_dump(mode="json", exclude_none=True)data["id"] = str(call.call_id) # CosmosDB requires an id fieldlogger.debug(f"Saving call {call.call_id}: {data}")+ res = Falsetry:async with self._use_client() as db:await db.upsert_item(body=data)- return True+ res = Trueexcept CosmosHttpResponseError as e:logger.error(f"Error accessing CosmosDB: {e}")- return False++ # Update cache+ if res:+ cache_key = self._cache_key_call_id(call.call_id)+ await self._cache.aset(cache_key, call.model_dump_json())++ return resasync def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:logger.debug(f"Loading last call for {phone_number}")++ # Try cache+ cache_key = self._cache_key_phone_number(phone_number)+ cached = await self._cache.aget(cache_key)+ if cached:+ try:+ return CallStateModel.model_validate_json(cached)+ except ValidationError as e:+ logger.debug(f"Parsing error: {e.errors()}")++ # Try livecall = Nonetry:async with self._use_client() as db:@@ -132,6 +171,11 @@ class CosmosDbStore(IStore):passexcept CosmosHttpResponseError as e:logger.error(f"Error accessing CosmosDB: {e}")++ # Update cache+ if call:+ await self._cache.aset(cache_key, call.model_dump_json())+return callasync def call_asearch_all(@@ -140,6 +184,7 @@ class CosmosDbStore(IStore):phone_number: Optional[str] = None,) -> tuple[Optional[list[CallStateModel]], int]:logger.debug(f"Searching calls, for {phone_number} and count {count}")+ # TODO: Cache resultscalls, total = await asyncio.gather(self._call_asearch_all_calls_worker(count, phone_number),self._call_asearch_all_total_worker(phone_number),diff --git a/persistence/icache.py b/persistence/icache.pyindex 12acd11..97872f2 100644--- a/persistence/icache.py+++ b/persistence/icache.py@@ -16,3 +16,7 @@ class ICache(ABC):@abstractmethodasync def aset(self, key: str, value: Union[str, bytes, None]) -> bool:pass++ @abstractmethod+ async def adel(self, key: str) -> bool:+ passdiff --git a/persistence/istore.py b/persistence/istore.pyindex a0ffda6..090f70b 100644--- a/persistence/istore.py+++ b/persistence/istore.py@@ -1,11 +1,16 @@from abc import ABC, abstractmethodfrom models.call import CallStateModelfrom models.readiness import ReadinessStatus+from persistence.icache import ICachefrom typing import Optionalfrom uuid import UUIDclass IStore(ABC):+ _cache: ICache++ def __init__(self, cache: ICache):+ self._cache = cache@abstractmethodasync def areadiness(self) -> ReadinessStatus:@@ -30,3 +35,9 @@ class IStore(ABC):phone_number: Optional[str] = None,) -> tuple[Optional[list[CallStateModel]], int]:pass++ def _cache_key_call_id(self, call_id: UUID) -> str:+ return f"{self.__class__.__name__}-call_id-{call_id}"++ def _cache_key_phone_number(self, phone_number: str) -> str:+ return f"{self.__class__.__name__}-phone_number-{phone_number}"diff --git a/persistence/memory.py b/persistence/memory.pyindex ab1e7ff..8a37af2 100644--- a/persistence/memory.py+++ b/persistence/memory.py@@ -56,6 +56,15 @@ class MemoryCache(ICache):self._cache.move_to_end(sha_key, last=False)return True+ async def adel(self, key: str) -> bool:+ """+ Delete a value from the cache.+ """+ sha_key = self._key_to_hash(key)+ if sha_key in self._cache:+ self._cache.pop(sha_key)+ return True+@staticmethoddef _key_to_hash(key: str) -> str:"""diff --git a/persistence/redis.py b/persistence/redis.pyindex c5005f7..cd6f3d3 100644--- a/persistence/redis.py+++ b/persistence/redis.py@@ -100,6 +100,20 @@ class RedisCache(ICache):return Falsereturn True+ async def adel(self, key: str) -> bool:+ """+ Delete a value from the cache.++ Catch errors for a maximum of 3 times, then raise the error.+ """+ sha_key = self._key_to_hash(key)+ try:+ await self._client.delete(sha_key)+ except RedisError as e:+ logger.error(f"Error deleting value, {e}")+ return False+ return True+@staticmethoddef _key_to_hash(key: str) -> bytes:"""diff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex f0ea2fd..de7c6b6 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -6,6 +6,7 @@ from helpers.logging import loggerfrom models.call import CallStateModelfrom models.readiness import ReadinessStatusfrom opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor+from persistence.icache import ICachefrom persistence.istore import IStorefrom pydantic import ValidationErrorfrom typing import AsyncGenerator, Optional@@ -23,7 +24,8 @@ class SqliteStore(IStore):_config: SqliteModel_first_run_done: bool = False- def __init__(self, config: SqliteModel):+ def __init__(self, cache: ICache, config: SqliteModel):+ super().__init__(cache)logger.info(f"Using SQLite database at {config.path} with table {config.table}")self._config = config@@ -53,6 +55,17 @@ class SqliteStore(IStore):async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:logger.debug(f"Loading call {call_id}")++ # Try cache+ cache_key = self._cache_key_call_id(call_id)+ call = await self._cache.aget(cache_key)+ if call:+ try:+ return CallStateModel.model_validate_json(call)+ except ValidationError as e:+ logger.debug(f"Parsing error: {e.errors()}")++ # Try livecall = Noneasync with self._use_db() as db:cursor = await db.execute(@@ -65,10 +78,17 @@ class SqliteStore(IStore):call = CallStateModel.model_validate_json(row[0])except ValidationError as e:logger.debug(f"Parsing error: {e.errors()}")++ # Update cache+ if call:+ await self._cache.aset(cache_key, call.model_dump_json())+return callasync def call_aset(self, call: CallStateModel) -> bool:# TODO: Catch exceptions and return False if something goes wrong++ # Update livedata = call.model_dump_json(exclude_none=True)logger.debug(f"Saving call {call.call_id}: {data}")async with self._use_db() as db:@@ -80,10 +100,26 @@ class SqliteStore(IStore):),)await db.commit()++ # Update cache+ cache_key = self._cache_key_call_id(call.call_id)+ await self._cache.aset(cache_key, data)+return Trueasync def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:logger.debug(f"Loading last call for {phone_number}")++ # Try cache+ cache_key = self._cache_key_phone_number(phone_number)+ call = await self._cache.aget(cache_key)+ if call:+ try:+ return CallStateModel.model_validate_json(call)+ except ValidationError as e:+ logger.debug(f"Parsing error: {e.errors()}")++ # Try livecall = Noneasync with self._use_db() as db:cursor = await db.execute(@@ -99,6 +135,11 @@ class SqliteStore(IStore):call = CallStateModel.model_validate_json(row[0])except ValidationError as e:logger.debug(f"Parsing error: {e.errors()}")++ # Update cache+ if call:+ await self._cache.aset(cache_key, call.model_dump_json())+return callasync def call_asearch_all(@@ -107,6 +148,7 @@ class SqliteStore(IStore):phone_number: Optional[str] = None,) -> tuple[Optional[list[CallStateModel]], int]:logger.debug(f"Searching calls, for {phone_number} and count {count}")+ # TODO: Cache resultscalls, total = await asyncio.gather(self._call_asearch_all_calls_worker(count, phone_number),self._call_asearch_all_total_worker(phone_number),