Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
reliability: Add a readiness health check
Clémence Lesné5ce83610b43d
diff --git a/bicep/app.bicep b/bicep/app.bicepindex 1d64401..c782f3d 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -191,6 +191,12 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {memory: '2Gi'}probes: [+ {+ type: 'Startup'+ tcpSocket: {+ port: 8080+ }+ }{type: 'Liveness'httpGet: {@@ -198,6 +204,13 @@ resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {port: 8080}}+ {+ type: 'Readiness'+ httpGet: {+ path: '/health/readiness'+ port: 8080+ }+ }]}]diff --git a/main.py b/main.pyindex a3afec2..62b81e0 100644--- a/main.py+++ b/main.py@@ -21,6 +21,7 @@ from azure.core.credentials import AzureKeyCredentialfrom azure.core.messaging import CloudEventfrom azure.eventgrid import EventGridEvent, SystemEventNamesfrom fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks, Response+from fastapi.encoders import jsonable_encoderfrom fastapi.responses import JSONResponse, HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom jinja2 import Environment, FileSystemLoader, select_autoescape@@ -44,6 +45,7 @@ from helpers.call_events import (on_transfer_error,)from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor+from models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatus# Jinja configuration@@ -67,8 +69,11 @@ _call_client = CallAutomationClient(),)-# Persistence+# Persistences+_cache = CONFIG.cache.instance()_db = CONFIG.database.instance()+_search = CONFIG.ai_search.instance()+_sms = CONFIG.sms.instance()# FastAPI_logger.info(f'Using root path "{CONFIG.api.root_path}"')@@ -106,6 +111,38 @@ async def health_liveness_get() -> None:pass+ "/health/readiness",+ description="Readiness healthckeck, returns the status of all components, and fails if one of them is not ready. If all components are ready, returns 200, otherwise 503.",+)+async def health_readiness_get() -> JSONResponse:+ # Check all components in parallel+ cache_check, db_check, search_check, sms_check = await asyncio.gather(+ _cache.areadiness(), _db.areadiness(), _search.areadiness(), _sms.areadiness()+ )+ readiness = ReadinessModel(+ status=ReadinessStatus.OK,+ checks=[+ ReadinessCheckModel(id="cache", status=cache_check),+ ReadinessCheckModel(id="index", status=db_check),+ ReadinessCheckModel(id="startup", status=ReadinessStatus.OK),+ ReadinessCheckModel(id="store", status=search_check),+ ReadinessCheckModel(id="stream", status=sms_check),+ ],+ )+ # If one of the checks fails, the whole readiness fails+ status_code = status.HTTP_200_OK+ for check in readiness.checks:+ if check.status != ReadinessStatus.OK:+ readiness.status = ReadinessStatus.FAIL+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ break+ return JSONResponse(+ content=jsonable_encoder(readiness),+ status_code=status_code,+ )++# Serve static filesapi.mount("/static", StaticFiles(directory="public_website/static"))diff --git a/models/readiness.py b/models/readiness.pynew file mode 100644index 0000000..282c53a--- /dev/null+++ b/models/readiness.py@@ -0,0 +1,21 @@+from enum import Enum+from pydantic import BaseModel+from typing import List+++class ReadinessStatus(str, Enum):+ FAIL = "fail"+ OK = "ok"+++class ReadinessCheckModel(BaseModel):+ id: str+ status: ReadinessStatus++ class Config:+ use_enum_values = True+++class ReadinessModel(BaseModel):+ checks: List[ReadinessCheckModel]+ status: strdiff --git a/persistence/ai_search.py b/persistence/ai_search.pyindex 142137c..68bda73 100644--- a/persistence/ai_search.py+++ b/persistence/ai_search.py@@ -10,6 +10,7 @@ from contextlib import asynccontextmanagerfrom helpers.config_models.ai_search import AiSearchModelfrom helpers.logging import build_loggerfrom models.call import CallModel+from models.readiness import ReadinessStatusfrom models.training import TrainingModelfrom persistence.icache import ICachefrom persistence.isearch import ISearch@@ -38,6 +39,20 @@ class AiSearchSearch(ISearch):self._config = configsuper().__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()+ return ReadinessStatus.OK+ except HttpResponseError as e:+ _logger.error(f"Error requesting AI Search, {e}")+ except ServiceRequestError as e:+ _logger.error(f"Error connecting to AI Search, {e}")+ return ReadinessStatus.FAIL+@retry(reraise=True,retry=retry_if_exception_type(ServiceResponseError),diff --git a/persistence/communication_services.py b/persistence/communication_services.pyindex 8f853e7..1cd584f 100644--- a/persistence/communication_services.py+++ b/persistence/communication_services.py@@ -5,6 +5,7 @@ from contextlib import asynccontextmanagerfrom helpers.config_models.communication_service import CommunicationServiceModelfrom helpers.logging import build_loggerfrom helpers.pydantic_types.phone_numbers import PhoneNumber+from models.readiness import ReadinessStatusfrom persistence.isms import ISmsfrom typing import AsyncGenerator@@ -19,6 +20,13 @@ class CommunicationServicesSms(ISms):_logger.info(f"Using Communication Services from number {config.phone_number}")self._config = config+ async def areadiness(self) -> ReadinessStatus:+ """+ Check the readiness of the Communication Services SMS service.+ """+ # TODO: How to check the readiness of the SMS service? We could send a SMS for each test, but that would be damm expensive.+ return ReadinessStatus.OK+async def asend(self, content: str, phone_number: PhoneNumber) -> bool:_logger.info(f"Sending SMS to {phone_number}")success = Falsediff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex 654e662..884b82f 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -7,10 +7,11 @@ from helpers.config import CONFIGfrom helpers.config_models.database import CosmosDbModelfrom helpers.logging import build_loggerfrom models.call import CallModel+from models.readiness import ReadinessStatusfrom persistence.istore import IStorefrom pydantic import ValidationErrorfrom typing import AsyncGenerator, Optional-from uuid import UUID+from uuid import UUID, uuid4from tenacity import (retry,stop_after_attempt,@@ -29,6 +30,55 @@ class CosmosDbStore(IStore):_logger.info(f"Using Cosmos DB {config.database}/{config.container}")self._config = config+ async def areadiness(self) -> ReadinessStatus:+ """+ Check the readiness of the Cosmos DB service.++ This will validate the ACID properties of the database: Create, Read, Update, Delete.+ """+ test_id = str(uuid4())+ test_partition = "+33612345678"+ test_dict = {+ "id": test_id, # unique id+ "phone_number": test_partition, # partition key+ "test": "test",+ }+ try:+ async with self._use_db() as db:+ # Test the item does not exist+ try:+ await db.read_item(item=test_id, partition_key=test_partition)+ return ReadinessStatus.FAIL+ except CosmosHttpResponseError as e:+ if e.status_code != 404:+ _logger.error(f"Error requesting CosmosDB, {e}")+ return ReadinessStatus.FAIL+ # Create a new item+ await db.upsert_item(body=test_dict)+ # Test the item is the same+ read_item = await db.read_item(+ item=test_id, partition_key=test_partition+ )+ assert {+ k: v for k, v in read_item.items() if k in test_dict+ } == test_dict # Check only the relevant fields, Cosmos DB adds metadata+ # Delete the item+ await db.delete_item(item=test_id, partition_key=test_partition)+ # Test the item does not exist+ try:+ await db.read_item(item=test_id, partition_key=test_partition)+ return ReadinessStatus.FAIL+ except CosmosHttpResponseError as e:+ if e.status_code != 404:+ _logger.error(f"Error requesting CosmosDB, {e}")+ return ReadinessStatus.FAIL+ return ReadinessStatus.OK+ except AssertionError:+ _logger.error("Readiness test failed", exc_info=True)+ except CosmosHttpResponseError as e:+ _logger.error(f"Error requesting CosmosDB, {e}")+ return ReadinessStatus.FAIL+@retry(reraise=True,retry=retry_if_exception_type(ServiceResponseError),diff --git a/persistence/icache.py b/persistence/icache.pyindex 07d3118..12acd11 100644--- a/persistence/icache.py+++ b/persistence/icache.py@@ -1,8 +1,14 @@from abc import ABC, abstractmethod+from models.readiness import ReadinessStatusfrom typing import Optional, Unionclass ICache(ABC):++ @abstractmethod+ async def areadiness(self) -> ReadinessStatus:+ pass+@abstractmethodasync def aget(self, key: str) -> Optional[bytes]:passdiff --git a/persistence/isearch.py b/persistence/isearch.pyindex 451a220..61d9fb0 100644--- a/persistence/isearch.py+++ b/persistence/isearch.py@@ -1,5 +1,6 @@from abc import ABC, abstractmethodfrom models.call import CallModel+from models.readiness import ReadinessStatusfrom models.training import TrainingModelfrom persistence.icache import ICachefrom typing import Optional@@ -11,6 +12,10 @@ class ISearch(ABC):def __init__(self, cache: ICache):self._cache = cache+ @abstractmethod+ async def areadiness(self) -> ReadinessStatus:+ pass+@abstractmethodasync def training_asearch_all(self, text: str, call: CallModeldiff --git a/persistence/isms.py b/persistence/isms.pyindex c9d26ca..1cb1310 100644--- a/persistence/isms.py+++ b/persistence/isms.py@@ -1,8 +1,14 @@from abc import ABC, abstractmethodfrom helpers.pydantic_types.phone_numbers import PhoneNumber+from models.readiness import ReadinessStatusclass ISms(ABC):++ @abstractmethod+ async def areadiness(self) -> ReadinessStatus:+ pass+@abstractmethodasync def asend(self, content: str, phone_number: PhoneNumber) -> bool:passdiff --git a/persistence/istore.py b/persistence/istore.pyindex 08a337e..e969394 100644--- a/persistence/istore.py+++ b/persistence/istore.py@@ -1,10 +1,16 @@from abc import ABC, abstractmethodfrom models.call import CallModel+from models.readiness import ReadinessStatusfrom typing import Optionalfrom uuid import UUIDclass IStore(ABC):++ @abstractmethod+ async def areadiness(self) -> ReadinessStatus:+ pass+@abstractmethodasync def call_aget(self, call_id: UUID) -> Optional[CallModel]:passdiff --git a/persistence/memory.py b/persistence/memory.pyindex 5845296..8859a3f 100644--- a/persistence/memory.py+++ b/persistence/memory.py@@ -1,6 +1,7 @@from collections import OrderedDictfrom helpers.config_models.cache import MemoryModelfrom helpers.logging import build_logger+from models.readiness import ReadinessStatusfrom persistence.icache import ICachefrom typing import Optional, Unionimport hashlib@@ -25,6 +26,12 @@ class MemoryCache(ICache):_logger.info(f"Using memory cache with {config.max_size} size limit")self._config = config+ async def areadiness(self) -> ReadinessStatus:+ """+ Check the readiness of the memory cache.+ """+ return ReadinessStatus.OK # Always ready, it's memory :)+async def aget(self, key: str) -> Optional[bytes]:"""Get a value from the cache.diff --git a/persistence/redis.py b/persistence/redis.pyindex a5a2455..969280e 100644--- a/persistence/redis.py+++ b/persistence/redis.py@@ -1,6 +1,7 @@from contextlib import asynccontextmanagerfrom helpers.config_models.cache import RedisModelfrom helpers.logging import build_logger+from models.readiness import ReadinessStatusfrom opentelemetry.instrumentation.redis import RedisInstrumentorfrom persistence.icache import ICachefrom redis.asyncio import Redis@@ -8,6 +9,7 @@ from redis.asyncio.retry import Retryfrom redis.backoff import ExponentialBackofffrom redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError, RedisErrorfrom typing import AsyncGenerator, Optional, Union+from uuid import uuid4import hashlib@@ -25,6 +27,33 @@ class RedisCache(ICache):_logger.info(f"Using Redis cache {config.host}:{config.port}")self._config = config+ async def areadiness(self) -> ReadinessStatus:+ """+ Check the readiness of the Redis cache.++ This will validate the ACID properties of the database: Create, Read, Update, Delete.+ """+ 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+ return ReadinessStatus.OK+ except AssertionError as e:+ _logger.error(f"Readiness test failed, {e}")+ except RedisError as e:+ _logger.error(f"Error requesting Redis, {e}")+ return ReadinessStatus.FAIL+async def aget(self, key: str) -> Optional[bytes]:"""Get a value from the cache.diff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex e8b24ca..0171a4a 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -5,6 +5,7 @@ from helpers.config import CONFIGfrom helpers.config_models.database import SqliteModelfrom helpers.logging import build_loggerfrom models.call import CallModel+from models.readiness import ReadinessStatusfrom opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentorfrom persistence.istore import IStorefrom pydantic import ValidationError@@ -29,6 +30,20 @@ class SqliteStore(IStore):)self._config = config+ async def areadiness(self) -> ReadinessStatus:+ """+ Check the readiness of the SQLite database.++ This checks if the database is reachable and can be queried.+ """+ try:+ async with self._use_db() as db:+ await db.execute("SELECT 1")+ return ReadinessStatus.OK+ except Exception as e:+ _logger.error(f"Error requesting SQLite, {e}")+ return ReadinessStatus.FAIL+async def call_aget(self, call_id: UUID) -> Optional[CallModel]:_logger.debug(f"Loading call {call_id}")call = Nonediff --git a/persistence/twilio.py b/persistence/twilio.pyindex 20e31f8..100932f 100644--- a/persistence/twilio.py+++ b/persistence/twilio.py@@ -1,6 +1,7 @@from helpers.config_models.sms import TwilioModelfrom helpers.logging import build_loggerfrom helpers.pydantic_types.phone_numbers import PhoneNumber+from models.readiness import ReadinessStatusfrom persistence.isms import ISmsfrom twilio.base.exceptions import TwilioRestExceptionfrom twilio.http.async_http_client import AsyncTwilioHttpClient@@ -23,6 +24,22 @@ class TwilioSms(ISms):username=config.account_sid,)+ async def areadiness(self) -> ReadinessStatus:+ """+ Check the readiness of the Twilio SMS service.++ This only check if the Twilio API is reachable and the account has remaining balance.+ """+ account_sid = self._config.account_sid+ try:+ account = await self._client.api.accounts(account_sid).fetch_async()+ balance = await account.balance.fetch_async()+ assert balance.balance and float(balance.balance) > 0+ return ReadinessStatus.OK+ except AssertionError:+ _logger.error("Readiness test failed", exc_info=True)+ return ReadinessStatus.FAIL+async def asend(self, content: str, phone_number: PhoneNumber) -> bool:_logger.info(f"Sending SMS to {phone_number}")success = False