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: Defer feature loading

Clémence Lesnéae4e841606cc
diff --git a/app/helpers/call_events.py b/app/helpers/call_events.py
index 4964d77..6c2ae68 100644
--- a/app/helpers/call_events.py
+++ b/app/helpers/call_events.py
@@ -125,6 +125,7 @@ async def on_call_connected(
_handle_recording(
call=call,
client=client,
+ scheduler=scheduler,
server_call_id=server_call_id,
), # Second, start recording the call
)
@@ -234,7 +235,7 @@ async def on_automation_recognize_error(
logger.info(
"Timeout, retrying language selection (%s/%s)",
call.recognition_retry,
- await recognition_retry_max(),
+ await recognition_retry_max(scheduler),
)
await _handle_ivr_language(
call=call,
@@ -320,7 +321,7 @@ async def _pre_recognize_error(
Returns True if the call should continue, False if it should end.
"""
# Voice retries are exhausted, end call
- if call.recognition_retry >= await recognition_retry_max():
+ if call.recognition_retry >= await recognition_retry_max(scheduler):
logger.info("Timeout, ending call")
return False
@@ -792,6 +793,7 @@ async def _handle_ivr_language(
async def _handle_recording(
call: CallStateModel,
client: CallAutomationClient,
+ scheduler: Scheduler,
server_call_id: str,
) -> None:
"""
@@ -799,7 +801,7 @@ async def _handle_recording(
Feature activation is checked before starting the recording.
"""
- if not await recording_enabled():
+ if not await recording_enabled(scheduler):
return
assert CONFIG.communication_services.recording_container_url
diff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.py
index 00ae850..7308768 100644
--- a/app/helpers/call_llm.py
+++ b/app/helpers/call_llm.py
@@ -65,6 +65,7 @@ async def load_llm_chat( # noqa: PLR0913, PLR0915
stt_complete_gate = asyncio.Event() # Gate to wait for the recognition
aec = EchoCancellationStream(
sample_rate=audio_sample_rate,
+ scheduler=scheduler,
)
audio_reference: asyncio.Queue[bytes] = asyncio.Queue()
@@ -271,10 +272,11 @@ async def load_llm_chat( # noqa: PLR0913, PLR0915
# Detect VAD
_process_audio_for_vad(
call=call,
- stop_callback=_stop_callback,
echo_cancellation=aec,
out_stream=stt_stream,
response_callback=_response_callback,
+ scheduler=scheduler,
+ stop_callback=_stop_callback,
timeout_callback=_timeout_callback,
),
)
@@ -354,10 +356,10 @@ async def _continue_chat( # noqa: PLR0915, PLR0913
# Timeouts
soft_timeout_triggered = False
soft_timeout_task = asyncio.create_task(
- asyncio.sleep(await answer_soft_timeout_sec())
+ asyncio.sleep(await answer_soft_timeout_sec(scheduler))
)
hard_timeout_task = asyncio.create_task(
- asyncio.sleep(await answer_hard_timeout_sec())
+ asyncio.sleep(await answer_hard_timeout_sec(scheduler))
)
def _clear_tasks() -> None:
@@ -387,7 +389,7 @@ async def _continue_chat( # noqa: PLR0915, PLR0913
if hard_timeout_task.done():
logger.warning(
"Hard timeout of %ss reached",
- await answer_hard_timeout_sec(),
+ await answer_hard_timeout_sec(scheduler),
)
# Clean up
_clear_tasks()
@@ -399,7 +401,7 @@ async def _continue_chat( # noqa: PLR0915, PLR0913
if soft_timeout_task.done() and not soft_timeout_triggered:
logger.warning(
"Soft timeout of %ss reached",
- await answer_soft_timeout_sec(),
+ await answer_soft_timeout_sec(scheduler),
)
soft_timeout_triggered = True
# Never store the error message in the call history, it has caused hallucinations in the LLM
@@ -548,6 +550,7 @@ async def _generate_chat_completion( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
async for delta in completion_stream(
max_tokens=160, # Lowest possible value for 90% of the cases, if not sufficient, retry will be triggered, 100 tokens ~= 75 words, 20 words ~= 1 sentence, 6 sentences ~= 160 tokens
messages=call.messages,
+ scheduler=scheduler,
system=system,
tools=tools,
):
@@ -659,6 +662,7 @@ async def _process_audio_for_vad( # noqa: PLR0913
echo_cancellation: EchoCancellationStream,
out_stream: PushAudioInputStream,
response_callback: Callable[[], Awaitable[None]],
+ scheduler: Scheduler,
stop_callback: Callable[[], Awaitable[None]],
timeout_callback: Callable[[], Awaitable[None]],
) -> None:
@@ -682,7 +686,7 @@ async def _process_audio_for_vad( # noqa: PLR0913
"""
# Wait before flushing
nonlocal stop_task
- timeout_ms = await vad_silence_timeout_ms()
+ timeout_ms = await vad_silence_timeout_ms(scheduler)
await asyncio.sleep(timeout_ms / 1000)
# Cancel the clear TTS task
@@ -695,7 +699,7 @@ async def _process_audio_for_vad( # noqa: PLR0913
await response_callback()
# Wait for silence and trigger timeout
- timeout_sec = await phone_silence_timeout_sec()
+ timeout_sec = await phone_silence_timeout_sec(scheduler)
while True:
# Stop this time if the call played a message
timeout_start = datetime.now(UTC)
@@ -724,7 +728,7 @@ async def _process_audio_for_vad( # noqa: PLR0913
"""
Stop the TTS if user speaks for too long.
"""
- timeout_ms = await vad_cutoff_timeout_ms()
+ timeout_ms = await vad_cutoff_timeout_ms(scheduler)
# Wait before clearing the TTS queue
await asyncio.sleep(timeout_ms / 1000)
diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.py
index 1076706..3fc162b 100644
--- a/app/helpers/call_utils.py
+++ b/app/helpers/call_utils.py
@@ -644,15 +644,18 @@ class EchoCancellationStream:
_packet_size: int
_reference_queue: asyncio.Queue[bytes] = asyncio.Queue()
_sample_rate: int
+ _scheduler: Scheduler
def __init__(
self,
sample_rate: int,
+ scheduler: Scheduler,
max_delay_ms: int = 200,
packet_duration_ms: int = 20,
):
self._packet_duration_ms = packet_duration_ms
self._sample_rate = sample_rate
+ self._scheduler = scheduler
max_delay_samples = int(max_delay_ms / 1000 * self._sample_rate)
self._bot_voice_buffer = np.zeros(max_delay_samples, dtype=np.float32)
@@ -703,7 +706,7 @@ class EchoCancellationStream:
# Calculate Root Mean Square (RMS)
rms = np.sqrt(np.mean(voice**2))
# Get VAD threshold, divide by 10 to more usability from user side, as RMS is in range 0-1 and a detection of 0.1 is a good maximum threshold
- threshold = await vad_threshold() / 10
+ threshold = await vad_threshold(self._scheduler) / 10
return rms >= threshold
async def _process_one(self, input_pcm: bytes) -> None:
diff --git a/app/helpers/features.py b/app/helpers/features.py
index 86af770..d9b4f8e 100644
--- a/app/helpers/features.py
+++ b/app/helpers/features.py
@@ -1,5 +1,6 @@
from typing import TypeVar, cast
+from aiojobs import Scheduler
from azure.appconfiguration.aio import AzureAppConfigurationClient
from azure.core.exceptions import ResourceNotFoundError
@@ -15,82 +16,92 @@ _cache = MemoryCache(MemoryModel())
T = TypeVar("T", bool, int, float, str)
-async def answer_hard_timeout_sec() -> int:
+async def answer_hard_timeout_sec(scheduler: Scheduler) -> int:
return await _default(
default=180,
key="answer_hard_timeout_sec",
+ scheduler=scheduler,
type_res=int,
)
-async def answer_soft_timeout_sec() -> int:
+async def answer_soft_timeout_sec(scheduler: Scheduler) -> int:
return await _default(
default=120,
key="answer_soft_timeout_sec",
+ scheduler=scheduler,
type_res=int,
)
-async def callback_timeout_hour() -> int:
+async def callback_timeout_hour(scheduler: Scheduler) -> int:
return await _default(
default=24,
key="callback_timeout_hour",
+ scheduler=scheduler,
type_res=int,
)
-async def phone_silence_timeout_sec() -> int:
+async def phone_silence_timeout_sec(scheduler: Scheduler) -> int:
return await _default(
default=20,
key="phone_silence_timeout_sec",
+ scheduler=scheduler,
type_res=int,
)
-async def vad_threshold() -> float:
+async def vad_threshold(scheduler: Scheduler) -> float:
return await _default(
default=0.5,
key="vad_threshold",
+ scheduler=scheduler,
type_res=float,
)
-async def vad_silence_timeout_ms() -> int:
+async def vad_silence_timeout_ms(scheduler: Scheduler) -> int:
return await _default(
default=500,
key="vad_silence_timeout_ms",
+ scheduler=scheduler,
type_res=int,
)
-async def vad_cutoff_timeout_ms() -> int:
+async def vad_cutoff_timeout_ms(scheduler: Scheduler) -> int:
return await _default(
default=150,
key="vad_cutoff_timeout_ms",
+ scheduler=scheduler,
type_res=int,
)
-async def recording_enabled() -> bool:
+async def recording_enabled(scheduler: Scheduler) -> bool:
return await _default(
default=False,
key="recording_enabled",
+ scheduler=scheduler,
type_res=bool,
)
-async def slow_llm_for_chat() -> bool:
+async def slow_llm_for_chat(scheduler: Scheduler) -> bool:
return await _default(
default=True,
key="slow_llm_for_chat",
+ scheduler=scheduler,
type_res=bool,
)
-async def recognition_retry_max() -> int:
+async def recognition_retry_max(scheduler: Scheduler) -> int:
return await _default(
default=3,
key="recognition_retry_max",
+ scheduler=scheduler,
type_res=int,
)
@@ -98,20 +109,29 @@ async def recognition_retry_max() -> int:
async def _default(
default: T,
key: str,
+ scheduler: Scheduler,
type_res: type[T],
) -> T:
"""
Get a setting from the App Configuration service with a default value.
"""
- res = await _get(key=key, type_res=type_res)
+ # Get the setting
+ res = await _get(
+ key=key,
+ scheduler=scheduler,
+ type_res=type_res,
+ )
if res:
return res
- logger.warning("Setting %s not found, using default: %s", key, default)
+
+ # Return default
+ logger.info("Feature %s not found, using default: %s", key, default)
return default
async def _get(
key: str,
+ scheduler: Scheduler,
type_res: type[T],
) -> T | None:
"""
@@ -126,6 +146,15 @@ async def _get(
value=cached.decode(),
)
+ # Defer the update
+ await scheduler.spawn(_refresh(cache_key, key))
+ return
+
+
+async def _refresh(
+ cache_key: str,
+ key: str,
+) -> T | None:
# Try live
try:
async with await _use_client() as client:
@@ -146,12 +175,6 @@ async def _get(
value=res,
)
- # Return the type
- return _parse(
- type_res=type_res,
- value=res,
- )
-
@async_lru_cache()
async def _use_client() -> AzureAppConfigurationClient:
diff --git a/app/helpers/llm_tools.py b/app/helpers/llm_tools.py
index 037dc80..8a45275 100644
--- a/app/helpers/llm_tools.py
+++ b/app/helpers/llm_tools.py
@@ -98,7 +98,7 @@ class DefaultPlugin(AbstractPlugin):
# Store the last message and use it at first message of the new claim
self.call = await _db.call_create(
- CallStateModel(
+ call=CallStateModel(
initiate=self.call.initiate.model_copy(),
voice_id=self.call.voice_id,
messages=[
@@ -111,7 +111,8 @@ class DefaultPlugin(AbstractPlugin):
# Reinsert the last message, using more will add the user message asking to create the new claim and the assistant can loop on it sometimes
self.call.messages[-1],
],
- )
+ ),
+ scheduler=self.scheduler,
)
return "Claim, reminders and messages reset"
diff --git a/app/helpers/llm_worker.py b/app/helpers/llm_worker.py
index 3bfe22e..4433981 100644
--- a/app/helpers/llm_worker.py
+++ b/app/helpers/llm_worker.py
@@ -5,6 +5,7 @@ from os import environ
from typing import TypeVar
import tiktoken
+from aiojobs import Scheduler
from json_repair import repair_json
from openai import (
APIConnectionError,
@@ -88,6 +89,7 @@ _retried_exceptions = [
async def completion_stream(
max_tokens: int,
messages: list[MessageModel],
+ scheduler: Scheduler,
system: list[ChatCompletionSystemMessageParam],
tools: list[ChatCompletionToolParam] | None = None,
) -> AsyncGenerator[ChoiceDelta, None]:
@@ -110,7 +112,9 @@ async def completion_stream(
async for attempt in retryed:
with attempt:
async for chunck in _completion_stream_worker(
- is_fast=not await slow_llm_for_chat(), # Let configuration decide
+ is_fast=not await slow_llm_for_chat(
+ scheduler
+ ), # Let configuration decide
max_tokens=max_tokens,
messages=messages,
system=system,
@@ -130,7 +134,7 @@ async def completion_stream(
async for attempt in retryed:
with attempt:
async for chunck in _completion_stream_worker(
- is_fast=await slow_llm_for_chat(), # Let configuration decide
+ is_fast=await slow_llm_for_chat(scheduler), # Let configuration decide
max_tokens=max_tokens,
messages=messages,
system=system,
diff --git a/app/main.py b/app/main.py
index 18d7e94..df4fb3d 100644
--- a/app/main.py
+++ b/app/main.py
@@ -285,7 +285,11 @@ async def report_single_get(call_id: UUID) -> HTMLResponse:
Returns a single call with a web interface.
"""
- call = await _db.call_get(call_id)
+ async with get_scheduler() as scheduler:
+ call = await _db.call_get(
+ call_id=call_id,
+ scheduler=scheduler,
+ )
if not call:
return HTMLResponse(
content=f"Call {call_id} not found",
@@ -345,21 +349,29 @@ 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
- 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)
-
- # Second, try to get by phone number
- phone_number = PhoneNumber(call_id_or_phone_number)
- call = await _db.call_search_one(phone_number=phone_number)
- if not call:
- raise HTTPException(
- detail=f"Call {call_id_or_phone_number} not found",
- status_code=HTTPStatus.NOT_FOUND,
+ async with get_scheduler() as scheduler:
+ # First, try to get by call ID
+ with suppress(ValueError):
+ call_id = UUID(call_id_or_phone_number)
+ call = await _db.call_get(
+ call_id=call_id,
+ scheduler=scheduler,
+ )
+ if call:
+ return TypeAdapter(CallGetModel).dump_python(call)
+
+ # Second, try to get by phone number
+ phone_number = PhoneNumber(call_id_or_phone_number)
+ call = await _db.call_search_one(
+ phone_number=phone_number,
+ scheduler=scheduler,
)
+ if not call:
+ raise HTTPException(
+ detail=f"Call {call_id_or_phone_number} not found",
+ status_code=HTTPStatus.NOT_FOUND,
+ )
+
return TypeAdapter(CallGetModel).dump_python(call)
@@ -483,11 +495,15 @@ async def sms_event(
# Enrich span
span_attribute(SpanAttributes.CALL_PHONE_NUMBER, phone_number)
- # Get call
- call = await _db.call_search_one(phone_number)
- if not call:
- logger.warning("Call for phone number %s not found", phone_number)
- return
+ async with get_scheduler() as scheduler:
+ # Get call
+ call = await _db.call_search_one(
+ phone_number=phone_number,
+ scheduler=scheduler,
+ )
+ if not call:
+ logger.warning("Call for phone number %s not found", phone_number)
+ return
# Enrich span
span_attribute(SpanAttributes.CALL_ID, str(call.call_id))
@@ -540,13 +556,17 @@ async def _communicationservices_validate_call_id(
# Enrich span
span_attribute(SpanAttributes.CALL_ID, str(call_id))
- # Validate call
- call = await _db.call_get(call_id)
- if not call:
- raise HTTPException(
- detail=f"Call {call_id} not found",
- status_code=HTTPStatus.NOT_FOUND,
+ async with get_scheduler() as scheduler:
+ # Validate call
+ call = await _db.call_get(
+ call_id=call_id,
+ scheduler=scheduler,
)
+ if not call:
+ raise HTTPException(
+ detail=f"Call {call_id} not found",
+ status_code=HTTPStatus.NOT_FOUND,
+ )
# Validate secret
if call.callback_secret != secret:
@@ -865,20 +885,22 @@ async def post_event(
Queue message is the UUID of a call. The event will load asynchroniously the `on_end_call` workflow.
"""
- # Validate call
- call = await _db.call_get(UUID(post.content))
- if not call:
- logger.warning("Call %s not found", post.content)
- return
-
- # Enrich span
- span_attribute(SpanAttributes.CALL_ID, str(call.call_id))
- span_attribute(SpanAttributes.CALL_PHONE_NUMBER, call.initiate.phone_number)
+ async with get_scheduler() as scheduler:
+ # Validate call
+ call = await _db.call_get(
+ call_id=UUID(post.content),
+ scheduler=scheduler,
+ )
+ if not call:
+ logger.warning("Call %s not found", post.content)
+ return
- logger.debug("Post event received")
+ # Enrich span
+ span_attribute(SpanAttributes.CALL_ID, str(call.call_id))
+ span_attribute(SpanAttributes.CALL_PHONE_NUMBER, call.initiate.phone_number)
- async with get_scheduler() as scheduler:
# Execute business logic
+ logger.debug("Post event received")
await on_end_call(
call=call,
scheduler=scheduler,
@@ -909,21 +931,26 @@ async def _communicationservices_urls(
Returnes a tuple of the callback URL, the WebSocket URL, and the call object.
"""
- # Get call
- call = await _db.call_search_one(phone_number)
-
- # Create new call if initiate is different
- if not call or (initiate and call.initiate != initiate):
- call = await _db.call_create(
- CallStateModel(
- initiate=initiate
- or CallInitiateModel(
- **CONFIG.conversation.initiate.model_dump(),
- phone_number=phone_number,
- )
- )
+ async with get_scheduler() as scheduler:
+ # Get call
+ call = await _db.call_search_one(
+ phone_number=phone_number,
+ scheduler=scheduler,
)
+ # Create new call if initiate is different
+ if not call or (initiate and call.initiate != initiate):
+ call = await _db.call_create(
+ call=CallStateModel(
+ initiate=initiate
+ or CallInitiateModel(
+ **CONFIG.conversation.initiate.model_dump(),
+ phone_number=phone_number,
+ )
+ ),
+ scheduler=scheduler,
+ )
+
# Format URLs
wss_url = _COMMUNICATIONSERVICES_WSS_TPL.format(
callback_secret=call.callback_secret,
@@ -957,16 +984,22 @@ async def twilio_sms_post(
# Enrich span
span_attribute(SpanAttributes.CALL_PHONE_NUMBER, From)
- # Get call
- call = await _db.call_search_one(From)
+ async with get_scheduler() as scheduler:
+ # Get call
+ call = await _db.call_search_one(
+ phone_number=From,
+ scheduler=scheduler,
+ )
+
+ # Call not found
+ if not call:
+ logger.warning("Call for phone number %s not found", From)
- if not call:
- logger.warning("Call for phone number %s not found", From)
- else:
- # Enrich span
- span_attribute(SpanAttributes.CALL_ID, str(call.call_id))
+ # Call found
+ else:
+ # Enrich span
+ span_attribute(SpanAttributes.CALL_ID, str(call.call_id))
- async with get_scheduler() as scheduler:
# Execute business logic
event_status = await on_sms_received(
call=call,
@@ -974,12 +1007,12 @@ async def twilio_sms_post(
scheduler=scheduler,
)
- # Return error for unsuccessful event
- if not event_status:
- raise HTTPException(
- detail="SMS event failed",
- status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
- )
+ # Return error for unsuccessful event
+ if not event_status:
+ raise HTTPException(
+ detail="SMS event failed",
+ status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
+ )
# Default response
return Response(
diff --git a/app/persistence/cosmos_db.py b/app/persistence/cosmos_db.py
index cd4f548..e16c05c 100644
--- a/app/persistence/cosmos_db.py
+++ b/app/persistence/cosmos_db.py
@@ -81,7 +81,11 @@ class CosmosDbStore(IStore):
exist = True
return exist
- async def call_get(self, call_id: UUID) -> CallStateModel | None:
+ async def call_get(
+ self,
+ call_id: UUID,
+ scheduler: Scheduler,
+ ) -> CallStateModel | None:
logger.debug("Loading call %s", call_id)
# Try cache
@@ -114,7 +118,7 @@ class CosmosDbStore(IStore):
if call:
await self._cache.set(
key=cache_key,
- ttl_sec=await callback_timeout_hour(),
+ ttl_sec=await callback_timeout_hour(scheduler),
value=call.model_dump_json(),
)
@@ -185,7 +189,7 @@ class CosmosDbStore(IStore):
cache_key_id = self._cache_key_call_id(call.call_id)
await self._cache.set(
key=cache_key_id,
- ttl_sec=await callback_timeout_hour(),
+ ttl_sec=await callback_timeout_hour(scheduler),
value=call.model_dump_json(),
)
@@ -193,7 +197,11 @@ class CosmosDbStore(IStore):
await scheduler.spawn(_exec())
# TODO: Catch errors
- async def call_create(self, call: CallStateModel) -> CallStateModel:
+ async def call_create(
+ self,
+ call: CallStateModel,
+ scheduler: Scheduler,
+ ) -> CallStateModel:
logger.debug("Creating new call %s", call.call_id)
# Serialize
@@ -213,7 +221,7 @@ class CosmosDbStore(IStore):
cache_key = self._cache_key_call_id(call.call_id)
await self._cache.set(
key=cache_key,
- ttl_sec=await callback_timeout_hour(),
+ ttl_sec=await callback_timeout_hour(scheduler),
value=call.model_dump_json(),
)
@@ -225,7 +233,11 @@ class CosmosDbStore(IStore):
return call
- async def call_search_one(self, phone_number: str) -> CallStateModel | None:
+ async def call_search_one(
+ self,
+ phone_number: str,
+ scheduler: Scheduler,
+ ) -> CallStateModel | None:
logger.debug("Loading last call for %s", phone_number)
# Try cache
@@ -244,7 +256,7 @@ class CosmosDbStore(IStore):
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",
+ 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(scheduler)}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",
parameters=[
{
"name": "@phone_number",
@@ -264,7 +276,7 @@ class CosmosDbStore(IStore):
if call:
await self._cache.set(
key=cache_key,
- ttl_sec=await callback_timeout_hour(),
+ ttl_sec=await callback_timeout_hour(scheduler),
value=call.model_dump_json(),
)
diff --git a/app/persistence/istore.py b/app/persistence/istore.py
index e144309..960f4ae 100644
--- a/app/persistence/istore.py
+++ b/app/persistence/istore.py
@@ -23,7 +23,11 @@ class IStore(ABC):
@abstractmethod
@tracer.start_as_current_span("store_call_get")
- async def call_get(self, call_id: UUID) -> CallStateModel | None:
+ async def call_get(
+ self,
+ call_id: UUID,
+ scheduler: Scheduler,
+ ) -> CallStateModel | None:
pass
@abstractmethod
@@ -37,12 +41,20 @@ class IStore(ABC):
@abstractmethod
@tracer.start_as_current_span("store_call_create")
- async def call_create(self, call: CallStateModel) -> CallStateModel:
+ async def call_create(
+ self,
+ call: CallStateModel,
+ scheduler: Scheduler,
+ ) -> CallStateModel:
pass
@abstractmethod
@tracer.start_as_current_span("store_call_search_one")
- async def call_search_one(self, phone_number: str) -> CallStateModel | None:
+ async def call_search_one(
+ self,
+ phone_number: str,
+ scheduler: Scheduler,
+ ) -> CallStateModel | None:
pass
@abstractmethod
diff --git a/tests/conftest.py b/tests/conftest.py
index c3820af..839f4b5 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -211,7 +211,10 @@ class DeepEvalAzureOpenAI(GPTModel):
# Try live
res = super().generate(prompt)
# Update cache
- self._cache.set(cache_key, res)
+ self._cache.set(
+ key=cache_key,
+ value=res,
+ )
# Return
return res
@@ -225,7 +228,10 @@ class DeepEvalAzureOpenAI(GPTModel):
# Try live
res = await super().a_generate(prompt)
# Update cache
- self._cache.set(cache_key, res)
+ self._cache.set(
+ key=cache_key,
+ value=res,
+ )
# Return
return res
diff --git a/tests/store.py b/tests/store.py
index db99191..6146cef 100644
--- a/tests/store.py
+++ b/tests/store.py
@@ -22,40 +22,67 @@ async def test_acid(call: CallStateModel) -> None:
"""
db = CONFIG.database.instance()
- # Check not exists
- assume(not await db.call_get(call.call_id))
- assume(await db.call_search_one(call.initiate.phone_number) != call)
- assume(
- call
- not in (
- (
- await db.call_search_all(
- phone_number=call.initiate.phone_number, count=1
- )
- )[0]
- or []
+ async with Scheduler() as scheduler:
+ # Check not exists
+ assume(
+ not await db.call_get(
+ call_id=call.call_id,
+ scheduler=scheduler,
+ )
+ )
+ assume(
+ await db.call_search_one(
+ phone_number=call.initiate.phone_number,
+ scheduler=scheduler,
+ )
+ != call
+ )
+ assume(
+ call
+ not in (
+ (
+ await db.call_search_all(
+ phone_number=call.initiate.phone_number, count=1
+ )
+ )[0]
+ or []
+ )
+ )
+
+ # Insert test call
+ await db.call_create(
+ call=call,
+ scheduler=scheduler,
+ )
+
+ # Check point read
+ assume(
+ await db.call_get(
+ call_id=call.call_id,
+ scheduler=scheduler,
+ )
+ == call
)
- )
-
- # Insert test call
- await db.call_create(call)
-
- # Check point read
- assume(await db.call_get(call.call_id) == call)
- # Check search one
- assume(await db.call_search_one(call.initiate.phone_number) == call)
- # Check search all
- assume(
- call
- in (
- (
- await db.call_search_all(
- phone_number=call.initiate.phone_number, count=1
- )
- )[0]
- or []
+ # Check search one
+ assume(
+ await db.call_search_one(
+ phone_number=call.initiate.phone_number,
+ scheduler=scheduler,
+ )
+ == call
+ )
+ # Check search all
+ assume(
+ call
+ in (
+ (
+ await db.call_search_all(
+ phone_number=call.initiate.phone_number, count=1
+ )
+ )[0]
+ or []
+ )
)
- )
@pytest.mark.asyncio(loop_scope="session")
@@ -69,13 +96,21 @@ async def test_transaction(
"""
db = CONFIG.database.instance()
- # Check not exists
- assume(not await db.call_get(call.call_id))
+ async with Scheduler() as scheduler:
+ # Check not exists
+ assume(
+ not await db.call_get(
+ call_id=call.call_id,
+ scheduler=scheduler,
+ )
+ )
- # Insert call
- await db.call_create(call)
+ # Insert call
+ await db.call_create(
+ call=call,
+ scheduler=scheduler,
+ )
- async with Scheduler() as scheduler:
# Check first change
async with db.call_transac(
call=call,
@@ -101,6 +136,9 @@ async def test_transaction(
# Check first string change
assume(call.voice_id == random_text)
- # Check point read
- new_call = await db.call_get(call.call_id)
- assume(new_call and new_call.voice_id == random_text and new_call.in_progress)
+ # Check point read
+ new_call = await db.call_get(
+ call_id=call.call_id,
+ scheduler=scheduler,
+ )
+ assume(new_call and new_call.voice_id == random_text and new_call.in_progress)