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

quality: Simplify exception management

Clémence Lesnéc9e20f6a5e64
diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.py
index b453263..5ab9dbd 100644
--- a/app/helpers/call_utils.py
+++ b/app/helpers/call_utils.py
@@ -1,7 +1,7 @@
import json
import re
from collections.abc import AsyncGenerator, Generator
-from contextlib import asynccontextmanager
+from contextlib import asynccontextmanager, contextmanager, suppress
from enum import Enum
from azure.communication.callautomation import (
@@ -40,6 +40,15 @@ _TTS_SANITIZER_R = re.compile(
_db = CONFIG.database.instance()
+class CallHangupException(Exception):
+ """
+ Exception raised when a call is hung up.
+ """
+
+ pass
+
+
+
class ContextEnum(str, Enum):
"""
Enum for call context.
@@ -106,7 +115,7 @@ async def _handle_play_text(
assert call.voice_id, "Voice ID is required to control the call"
async with _use_call_client(client, call.voice_id) as call_client:
await call_client.play_media(
- operation_context=_context_builder({context}),
+ operation_context=_context_serializer({context}),
play_source=_audio_from_text(
call=call,
style=style,
@@ -135,20 +144,13 @@ async def handle_media(
If `context` is provided, it will be used to track the operation.
"""
- try:
+ with _detect_hangup():
assert call.voice_id, "Voice ID is required to control the call"
async with _use_call_client(client, call.voice_id) as call_client:
await call_client.play_media(
- operation_context=_context_builder({context}),
+ operation_context=_context_serializer({context}),
play_source=FileSource(url=sound_url),
)
- except ResourceNotFoundError:
- logger.debug("Call hung up before playing")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- logger.debug("Call hung up before playing")
- else:
- raise e
async def handle_play_text( # noqa: PLR0913
@@ -309,7 +311,7 @@ async def handle_recognize_ivr(
choices=choices,
input_type=RecognizeInputType.CHOICES,
interrupt_prompt=True,
- operation_context=_context_builder({context}),
+ operation_context=_context_serializer({context}),
play_prompt=_audio_from_text(
call=call,
style=MessageStyleEnum.NONE,
@@ -327,17 +329,15 @@ async def handle_hangup(
call: CallStateModel,
) -> None:
logger.info("Hanging up: %s", call.initiate.phone_number)
- try:
+ with (
+ # Suppress hangup exception
+ suppress(CallHangupException),
+ # Detect hangup exception
+ _detect_hangup(),
+ ):
assert call.voice_id, "Voice ID is required to control the call"
async with _use_call_client(client, call.voice_id) as call_client:
await call_client.hang_up(is_for_everyone=True)
- except ResourceNotFoundError:
- logger.debug("Call already hung up")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- logger.debug("Call hung up before playing")
- else:
- raise e
async def handle_transfer(
@@ -347,20 +347,13 @@ async def handle_transfer(
context: ContextEnum | None = None,
) -> None:
logger.info("Transferring call: %s", target)
- try:
+ with _detect_hangup():
assert call.voice_id, "Voice ID is required to control the call"
async with _use_call_client(client, call.voice_id) as call_client:
await call_client.transfer_call_to_participant(
- operation_context=_context_builder({context}),
+ operation_context=_context_serializer({context}),
target_participant=PhoneNumberIdentifier(target),
)
- except ResourceNotFoundError:
- logger.debug("Call hung up before transferring")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- logger.debug("Call hung up before transferring")
- else:
- raise e
async def start_audio_streaming(
@@ -368,7 +361,7 @@ async def start_audio_streaming(
call: CallStateModel,
) -> None:
logger.info("Starting audio streaming")
- try:
+ with _detect_hangup():
assert call.voice_id, "Voice ID is required to control the call"
async with _use_call_client(client, call.voice_id) as call_client:
# TODO: Use the public API once the "await" have been fixed
@@ -377,13 +370,6 @@ async def start_audio_streaming(
call_connection_id=call_client._call_connection_id,
start_media_streaming_request=StartMediaStreamingRequest(),
)
- except ResourceNotFoundError:
- logger.debug("Call hung up before starting streaming")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- logger.debug("Call hung up before starting streaming")
- else:
- raise e
async def stop_audio_streaming(
@@ -391,25 +377,41 @@ async def stop_audio_streaming(
call: CallStateModel,
) -> None:
logger.info("Stopping audio streaming")
- try:
+ with _detect_hangup():
assert call.voice_id, "Voice ID is required to control the call"
async with _use_call_client(client, call.voice_id) as call_client:
await call_client.stop_media_streaming()
- except ResourceNotFoundError:
- logger.debug("Call hung up before stopping streaming")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- logger.debug("Call hung up before stopping streaming")
- else:
- raise e
-def _context_builder(contexts: set[ContextEnum | None] | None) -> str | None:
+def _context_serializer(contexts: set[ContextEnum | None] | None) -> str | None:
+ """
+ Serialize a set of contexts to a JSON string.
+
+ Returns `None` if no context is provided.
+ """
if not contexts:
return None
return json.dumps([context.value for context in contexts if context])
+@contextmanager
+def _detect_hangup() -> Generator[None, None, None]:
+ """
+ Catch a call hangup and raise a `CallHangupException` instead of the Call Automation SDK exceptions.
+ """
+ try:
+ yield
+ except ResourceNotFoundError:
+ logger.debug("Call hung up")
+ raise CallHangupException
+ except HttpResponseError as e:
+ if "call already terminated" in e.message.lower():
+ logger.debug("Call hung up")
+ raise CallHangupException
+ else:
+ raise e
+
+
@asynccontextmanager
async def _use_call_client(
client: CallAutomationClient, voice_id: str
diff --git a/app/helpers/features.py b/app/helpers/features.py
index 20a63ec..11be914 100644
--- a/app/helpers/features.py
+++ b/app/helpers/features.py
@@ -1,3 +1,4 @@
+from contextlib import suppress
from typing import TypeVar, cast
from azure.appconfiguration.aio import AzureAppConfigurationClient
@@ -100,7 +101,7 @@ def _cache_key(key: str) -> str:
def _parse(value: str, type_res: type[T]) -> T | None:
- try:
+ with suppress(ValueError):
if type_res is bool:
return cast(T, value.lower() == "true")
if type_res is int:
@@ -110,5 +111,3 @@ def _parse(value: str, type_res: type[T]) -> T | None:
if type_res is str:
return cast(T, str(value))
raise ValueError(f"Unsupported type: {type_res}")
- except ValueError:
- pass
diff --git a/app/main.py b/app/main.py
index 416237d..0ea20a3 100644
--- a/app/main.py
+++ b/app/main.py
@@ -1,7 +1,7 @@
import asyncio
import json
from base64 import b64decode
-from contextlib import asynccontextmanager
+from contextlib import asynccontextmanager, suppress
from datetime import timedelta
from http import HTTPStatus
from os import getenv
@@ -343,13 +343,11 @@ async def call_get(call_id_or_phone_number: str) -> CallGetModel:
Returns a single call object `CallGetModel`, in JSON format.
"""
# First, try to get by call ID
- try:
+ with suppress(ValueError):
call_id = UUID(call_id_or_phone_number)
call = await _db.call_get(call_id)
if call:
return TypeAdapter(CallGetModel).dump_python(call)
- except ValueError:
- pass
# Second, try to get by phone number
phone_number = PhoneNumber(call_id_or_phone_number)
diff --git a/app/persistence/ai_search.py b/app/persistence/ai_search.py
index 85ba049..00a8089 100644
--- a/app/persistence/ai_search.py
+++ b/app/persistence/ai_search.py
@@ -1,3 +1,5 @@
+from contextlib import suppress
+
from azure.core.exceptions import (
HttpResponseError,
ResourceExistsError,
@@ -279,17 +281,16 @@ class AiSearchSearch(ISearch):
credential=await credential(),
) as client:
try:
- await client.create_index(
- SearchIndex(
- fields=fields,
- name=self._config.index,
- semantic_search=semantic_search,
- vector_search=vector_search,
+ with suppress(ResourceExistsError):
+ await client.create_index(
+ SearchIndex(
+ fields=fields,
+ name=self._config.index,
+ semantic_search=semantic_search,
+ vector_search=vector_search,
+ )
)
- )
- logger.info('Created Search "%s"', self._config.index)
- except ResourceExistsError:
- pass
+ logger.info('Created Search "%s"', self._config.index)
except HttpResponseError as e:
if not e.error or not e.error.code == "ResourceNameAlreadyInUse":
raise e
diff --git a/app/persistence/cosmos_db.py b/app/persistence/cosmos_db.py
index 4c43911..2aa3afa 100644
--- a/app/persistence/cosmos_db.py
+++ b/app/persistence/cosmos_db.py
@@ -1,6 +1,6 @@
import asyncio
from collections.abc import AsyncGenerator
-from contextlib import asynccontextmanager
+from contextlib import asynccontextmanager, suppress
from typing import Any
from uuid import UUID, uuid4
@@ -75,11 +75,9 @@ class CosmosDbStore(IStore):
async def _item_exists(self, test_id: str, partition_key: str) -> bool:
exist = False
async with self._use_client() as db:
- try:
+ with suppress(CosmosResourceNotFoundError):
await db.read_item(item=test_id, partition_key=partition_key)
exist = True
- except CosmosResourceNotFoundError:
- pass
return exist
async def call_get(self, call_id: UUID) -> CallStateModel | None:
@@ -97,18 +95,17 @@ class CosmosDbStore(IStore):
# Try live
call = None
try:
- 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)}],
- )
- raw = await anext(items)
- try:
- call = CallStateModel.model_validate(raw)
- except ValidationError as e:
- logger.debug("Parsing error: %s", e.errors())
- except StopAsyncIteration:
- pass
+ with suppress(StopAsyncIteration):
+ 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)}],
+ )
+ raw = await anext(items)
+ try:
+ call = CallStateModel.model_validate(raw)
+ except ValidationError as e:
+ logger.debug("Parsing error: %s", e.errors())
except CosmosHttpResponseError as e:
logger.error("Error accessing CosmosDB: %s", e)
@@ -258,24 +255,23 @@ class CosmosDbStore(IStore):
# Try live
call = None
try:
- 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', -{await callback_timeout_hour()}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",
- parameters=[
- {
- "name": "@phone_number",
- "value": phone_number,
- }
- ],
- )
- raw = await anext(items)
- try:
- call = CallStateModel.model_validate(raw)
- except ValidationError:
- logger.debug("Parsing error", exc_info=True)
- except StopAsyncIteration:
- pass
+ with suppress(StopAsyncIteration):
+ 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', -{await callback_timeout_hour()}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",
+ parameters=[
+ {
+ "name": "@phone_number",
+ "value": phone_number,
+ }
+ ],
+ )
+ raw = await anext(items)
+ try:
+ call = CallStateModel.model_validate(raw)
+ except ValidationError:
+ logger.debug("Parsing error", exc_info=True)
except CosmosHttpResponseError:
logger.exception("Error accessing CosmosDB")