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+fix+breaking+refacto: Interaction timeout, db perfs, remove SQLite

Clémence Lesnéce57ca6c286d
diff --git a/README.md b/README.md
index 4b13cd5..9fc52f6 100644
--- a/README.md
+++ b/README.md
@@ -179,7 +179,7 @@ graph LR
ada["Embedding<br>(ADA)"]
app["App<br>(Container App)"]
communication_services["Call & SMS gateway<br>(Communication Services)"]
- db[("Conversations and claims<br>(Cosmos DB / SQLite)")]
+ db[("Conversations and claims<br>(Cosmos DB)")]
eventgrid["Broker<br>(Event Grid)"]
gpt["LLM<br>(GPT-4o)"]
queues[("Queues<br>(Azure Storage)")]
@@ -627,7 +627,7 @@ Conversation options are represented as features. They can be configured from Ap
| `answer_hard_timeout_sec` | The hard timeout for the bot answer in seconds. | `int` | 180 |
| `answer_soft_timeout_sec` | The soft timeout for the bot answer in seconds. | `int` | 30 |
| `callback_timeout_hour` | The timeout for a callback in hours. | `int` | 3 |
-| `phone_silence_timeout_sec` | The timeout for phone silence in seconds. | `int` | 10 |
+| `phone_silence_timeout_sec` | The timeout for phone silence in seconds. | `int` | 20 |
| `recognition_retry_max` | The maximum number of retries for voice recognition. | `int` | 2 |
| `recording_enabled` | Whether call recording is enabled. | `bool` | false |
| `slow_llm_for_chat` | Whether to use the slow LLM for chat. | `bool` | false |
diff --git a/app/helpers/call_events.py b/app/helpers/call_events.py
index 505efac..fde93bd 100644
--- a/app/helpers/call_events.py
+++ b/app/helpers/call_events.py
@@ -1,5 +1,6 @@
import asyncio
from collections.abc import Awaitable, Callable
+from datetime import UTC, datetime
from azure.communication.callautomation import (
AzureBlobContainerRecordingStorage,
@@ -76,19 +77,17 @@ async def on_new_call(
return True
except ClientAuthenticationError:
- logger.error(
- "Authentication error with Communication Services, check the credentials",
- exc_info=True,
+ logger.exception(
+ "Authentication error with Communication Services, check the credentials"
)
except HttpResponseError as e:
if "lifetime validation of the signed http request failed" in e.message.lower():
logger.debug("Old call event received, ignoring")
else:
- logger.error(
+ logger.exception(
"Unknown error answering call with %s",
phone_number,
- exc_info=True,
)
return False
@@ -101,23 +100,25 @@ async def on_call_connected(
server_call_id: str,
) -> None:
logger.info("Call connected, asking for language")
- call.recognition_retry = 0 # Reset recognition retry counter
- call.in_progress = True
- call.messages.append(
- MessageModel(
- action=MessageActionEnum.CALL,
- content="",
- persona=MessagePersonaEnum.HUMAN,
+
+ # Add define the call as in progress
+ async with _db.call_transac(call):
+ call.in_progress = True
+ call.recognition_retry = 0
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.CALL,
+ content="",
+ persona=MessagePersonaEnum.HUMAN,
+ )
)
- )
+
+ # Execute business logic
await asyncio.gather(
_handle_ivr_language(
call=call,
client=client,
), # First, every time a call is answered, confirm the language
- _db.call_aset(
- call
- ), # Second, save in DB allowing SMS answers to be more "in-sync", should be quick enough to be in sync with the next message
_handle_recording(
call=call,
client=client,
@@ -172,7 +173,10 @@ async def on_recognize_error(
) -> None:
# Retry IVR recognition
if contexts and CallContextEnum.IVR_LANG_SELECT in contexts:
+ # Enrich span
span_attribute(CallAttributes.CALL_CHANNEL, "ivr")
+
+ # Retry IVR recognition
if call.recognition_retry < await recognition_retry_max():
logger.info(
"Timeout, retrying language selection (%s/%s)",
@@ -183,13 +187,16 @@ async def on_recognize_error(
call=call,
client=client,
)
- else: # IVR retries are exhausted, end call
+
+ # IVR retries are exhausted, end call
+ else:
logger.info("Timeout, ending call")
await _handle_goodbye(
call=call,
client=client,
post_callback=post_callback,
)
+
return
# Voice retries are exhausted, end call
@@ -203,7 +210,8 @@ async def on_recognize_error(
return
# Increment the recognition retry counter
- call.recognition_retry += 1
+ async with _db.call_transac(call):
+ call.recognition_retry += 1
# Play a timeout prompt
await handle_play_text(
@@ -236,6 +244,20 @@ async def _handle_goodbye(
)
[email protected]_as_current_span("on_play_started")
+async def on_play_started(
+ call: CallStateModel,
+) -> None:
+ logger.debug("Play started")
+
+ # Enrich span
+ span_attribute(CallAttributes.CALL_CHANNEL, "voice")
+
+ # Update last interaction
+ async with _db.call_transac(call):
+ call.last_interaction_at = datetime.now(UTC)
+
+
@tracer.start_as_current_span("on_play_completed")
async def on_play_completed(
call: CallStateModel,
@@ -244,35 +266,52 @@ async def on_play_completed(
post_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
logger.debug("Play completed")
+
+ # Enrich span
span_attribute(CallAttributes.CALL_CHANNEL, "voice")
+ # Update last interaction
+ async with _db.call_transac(call):
+ call.last_interaction_at = datetime.now(UTC)
+
+ # Skip if no context data
if not contexts:
return
+ # Call ended context
if (
CallContextEnum.TRANSFER_FAILED in contexts
or CallContextEnum.GOODBYE in contexts
- ): # Call ended
+ ):
logger.info("Ending call")
await _handle_hangup(
call=call,
client=client,
post_callback=post_callback,
)
+ return
- elif CallContextEnum.CONNECT_AGENT in contexts: # Call transfer
+ # Call transfer context
+ if CallContextEnum.CONNECT_AGENT in contexts:
logger.info("Initiating transfer call initiated")
await handle_transfer(
call=call,
client=client,
target=call.initiate.agent_phone_number,
)
+ return
+
+ logger.warning("Unknown context %s", contexts)
@tracer.start_as_current_span("on_play_error")
async def on_play_error(error_code: int) -> None:
logger.debug("Play failed")
+
+ # Enrich span
span_attribute(CallAttributes.CALL_CHANNEL, "voice")
+
+ # Suppress known errors
# See: https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/communication-services/how-tos/call-automation/play-action.md
match error_code:
case 8535:
@@ -300,9 +339,12 @@ async def on_ivr_recognized(
label: str,
) -> None:
logger.info("IVR recognized: %s", label)
+
+ # Enrich span
span_attribute(CallAttributes.CALL_CHANNEL, "ivr")
span_attribute(CallAttributes.CALL_MESSAGE, label)
- call.recognition_retry = 0 # Reset recognition retry counter
+
+ # Parse language from label
try:
lang = next(
(x for x in call.initiate.lang.availables if x.short_code == label),
@@ -313,8 +355,9 @@ async def on_ivr_recognized(
return
logger.info("Setting call language to %s", lang)
- call.lang = lang.short_code
- persist_coro = _db.call_aset(call)
+ async with _db.call_transac(call):
+ call.lang = lang.short_code
+ call.recognition_retry = 0
if len(call.messages) <= 1: # First call, or only the call action
await asyncio.gather(
@@ -322,12 +365,11 @@ async def on_ivr_recognized(
call=call,
client=client,
text=await CONFIG.prompts.tts.hello(call),
- ), # First, greet the user
- persist_coro, # Second, persist language change for next messages, should be quick enough to be in sync with the next message
+ ), # First, greet the userwith the next message
start_audio_streaming(
call=call,
client=client,
- ), # Third, the conversation with the LLM should start
+ ), # Second, the conversation with the LLM should start
) # All in parallel to lower the response latency
else: # Returning call
@@ -338,11 +380,10 @@ async def on_ivr_recognized(
style=MessageStyleEnum.CHEERFUL,
text=await CONFIG.prompts.tts.welcome_back(call),
), # First, welcome back the user
- persist_coro, # Second, persist language change for next messages, should be quick enough to be in sync with the next message
start_audio_streaming(
call=call,
client=client,
- ), # Third, the conversation with the LLM should start
+ ), # Second, the conversation with the LLM should start
)
@@ -373,18 +414,26 @@ async def on_sms_received(
message: str,
) -> bool:
logger.info("SMS received from %s: %s", call.initiate.phone_number, message)
+
+ # Enrich span
span_attribute(CallAttributes.CALL_CHANNEL, "sms")
span_attribute(CallAttributes.CALL_MESSAGE, message)
- call.messages.append(
- MessageModel(
- action=MessageActionEnum.SMS,
- content=message,
- persona=MessagePersonaEnum.HUMAN,
+
+ # Add the SMS to the call history
+ async with _db.call_transac(call):
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.SMS,
+ content=message,
+ persona=MessagePersonaEnum.HUMAN,
+ )
)
- )
- await _db.call_aset(call) # save in DB allowing SMS answers to be more "in-sync"
+
+ # If the call is not in progress, answer with SMS
if not call.in_progress:
logger.info("Call not in progress, answering with SMS")
+
+ # If the call is in progress, answer with voice
else:
logger.info("Call in progress, answering with voice")
# TODO: Reimplement SMS answers in voice
@@ -393,6 +442,7 @@ async def on_sms_received(
# client=client,
# post_callback=post_callback,
# )
+
return True
@@ -402,14 +452,17 @@ async def _handle_hangup(
post_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
await handle_hangup(client=client, call=call)
- call.in_progress = False
- call.messages.append(
- MessageModel(
- action=MessageActionEnum.HANGUP,
- content="",
- persona=MessagePersonaEnum.HUMAN,
+
+ async with _db.call_transac(call):
+ call.in_progress = False
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.HANGUP,
+ content="",
+ persona=MessagePersonaEnum.HUMAN,
+ )
)
- )
+
await post_callback(call)
@@ -467,21 +520,21 @@ async def _intelligence_sms(call: CallStateModel) -> None:
):
if not number:
continue
- res = await _sms.asend(content, number)
+ res = await _sms.send(content, number)
if not res:
logger.warning("Failed sending SMS report to %s", number)
continue
success = True
if success:
- call.messages.append(
- MessageModel(
- action=MessageActionEnum.SMS,
- content=content,
- persona=MessagePersonaEnum.ASSISTANT,
+ async with _db.call_transac(call):
+ call.messages.append(
+ MessageModel(
+ action=MessageActionEnum.SMS,
+ content=content,
+ persona=MessagePersonaEnum.ASSISTANT,
+ )
)
- )
- await _db.call_aset(call)
async def _intelligence_synthesis(call: CallStateModel) -> None:
@@ -511,8 +564,8 @@ async def _intelligence_synthesis(call: CallStateModel) -> None:
return
logger.info("Synthesis: %s", model)
- call.synthesis = model
- await _db.call_aset(call)
+ async with _db.call_transac(call):
+ call.synthesis = model
async def _intelligence_next(call: CallStateModel) -> None:
@@ -542,8 +595,8 @@ async def _intelligence_next(call: CallStateModel) -> None:
return
logger.info("Next action: %s", model)
- call.next = model
- await _db.call_aset(call)
+ async with _db.call_transac(call):
+ call.next = model
async def _handle_ivr_language(
diff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.py
index 6b8647e..fef9c4d 100644
--- a/app/helpers/call_llm.py
+++ b/app/helpers/call_llm.py
@@ -164,14 +164,16 @@ async def load_llm_chat( # noqa: PLR0913
if not recognizer_text:
return
- # Add it to the call history
+ # Add it to the call history and update last interaction
logger.info("Voice stored: %s", recognizer_buffer)
- call.messages.append(
- MessageModel(
- content=recognizer_text,
- persona=MessagePersonaEnum.HUMAN,
+ async with _db.call_transac(call):
+ call.last_interaction_at = datetime.now(UTC)
+ call.messages.append(
+ MessageModel(
+ content=recognizer_text,
+ persona=MessagePersonaEnum.HUMAN,
+ )
)
- )
# Clear the recognition buffer
recognizer_buffer.clear()
@@ -226,7 +228,8 @@ async def _out_answer( # noqa: PLR0915
span_attribute(CallAttributes.CALL_MESSAGE, call.messages[-1].content)
# Reset recognition retry counter
- call.recognition_retry = 0
+ async with _db.call_transac(call):
+ call.recognition_retry = 0
# By default, play the loading sound
play_loading_sound = True
@@ -287,9 +290,10 @@ async def _out_answer( # noqa: PLR0915
continue_chat = True
try:
while True:
- logger.debug("Chat task status: %s", chat_task.done())
+ # logger.debug("Chat task status: %s", chat_task.done())
- if chat_task.done(): # Break when chat coroutine is done
+ # Break when chat coroutine is done
+ if chat_task.done():
# Clean up
_clear_tasks()
# Get result
@@ -297,12 +301,10 @@ async def _out_answer( # noqa: PLR0915
chat_task.result()
) # Store updated chat model
await training_callback(call) # Trigger trainings generation
- await _db.call_aset(
- call
- ) # Save ASAP in DB allowing (1) user to cut off the Assistant and (2) SMS answers to be in order
break
- if hard_timeout_task.done(): # Break when hard timeout is reached
+ # Break when hard timeout is reached
+ if hard_timeout_task.done():
logger.warning(
"Hard timeout of %ss reached",
await answer_hard_timeout_sec(),
@@ -311,10 +313,10 @@ async def _out_answer( # noqa: PLR0915
_clear_tasks()
break
- if play_loading_sound: # Catch timeout if async loading is not started
- if (
- soft_timeout_task.done() and not soft_timeout_triggered
- ): # Speak when soft timeout is reached
+ # Catch timeout if async loading is not started
+ if play_loading_sound:
+ # Speak when soft timeout is reached
+ if soft_timeout_task.done() and not soft_timeout_triggered:
logger.warning(
"Soft timeout of %ss reached",
await answer_soft_timeout_sec(),
@@ -330,7 +332,8 @@ async def _out_answer( # noqa: PLR0915
)
)
- elif loading_task.done(): # Do not play timeout prompt plus loading, it can be frustrating for the user
+ # Do not play timeout prompt plus loading, it can be frustrating for the user
+ elif loading_task.done():
loading_task = _loading_task()
await scheduler.spawn(
handle_media(
@@ -344,7 +347,8 @@ async def _out_answer( # noqa: PLR0915
await asyncio.sleep(1)
except Exception:
- logger.warning("Error loading intelligence", exc_info=True)
+ # TODO: Remove last message
+ logger.exception("Error loading intelligence")
if is_error: # Error during chat
if not continue_chat or _iterations_remaining < 1: # Maximum retries reached
@@ -408,27 +412,20 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
logger.debug("Running LLM chat")
content_full = ""
- async def _buffer_callback(text: str, style: MessageStyleEnum) -> None:
+ async def _plugin_tts_callback(text: str) -> None:
nonlocal content_full
content_full += f" {text}"
- await tts_callback(text, style)
+ await tts_callback(text, MessageStyleEnum.NONE)
- async def _content_callback(
- buffer: str, style: MessageStyleEnum
- ) -> MessageStyleEnum:
+ async def _content_callback(buffer: str) -> None:
# Remove tool calls from buffer content and detect style
- local_style, local_content = extract_message_style(
- remove_message_action(buffer)
- )
- new_style = local_style or style
- if local_content:
- await tts_callback(local_content, new_style)
- return new_style
+ style, local_content = extract_message_style(remove_message_action(buffer))
+ await tts_callback(local_content, style)
# Build RAG
trainings = await call.trainings()
logger.info("Enhancing LLM chat with %s trainings", len(trainings))
- logger.debug("Trainings: %s", trainings)
+ # logger.debug("Trainings: %s", trainings)
# System prompts
system = CONFIG.prompts.llm.chat_system(
@@ -448,7 +445,7 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
call=call,
client=client,
post_callback=post_callback,
- tts_callback=_buffer_callback,
+ tts_callback=_plugin_tts_callback,
)
tools = []
@@ -456,7 +453,7 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
logger.warning("Tools disabled for this chat")
else:
tools = await plugins.to_openai()
- logger.debug("Tools: %s", tools)
+ # logger.debug("Tools: %s", tools)
# Execute LLM inference
maximum_tokens_reached = False
@@ -482,7 +479,7 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
content_full[content_buffer_pointer:], False
):
content_buffer_pointer += length
- plugins.style = await _content_callback(sentence, plugins.style)
+ await _content_callback(sentence)
except MaximumTokensReachedError: # Retry on maximum tokens reached
logger.warning("Maximum tokens reached for this completion, retry asked")
maximum_tokens_reached = True
@@ -505,15 +502,15 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
# Flush the remaining buffer
if content_buffer_pointer < len(content_full):
- plugins.style = await _content_callback(
- content_full[content_buffer_pointer:], plugins.style
- )
+ await _content_callback(content_full[content_buffer_pointer:])
# Convert tool calls buffer
tool_calls = [tool_call for _, tool_call in tool_calls_buffer.items()]
# Delete action and style from the message as they are in the history and LLM hallucinates them
- _, content_full = extract_message_style(remove_message_action(content_full))
+ last_style, content_full = extract_message_style(
+ remove_message_action(content_full)
+ )
logger.debug("Chat response: %s", content_full)
logger.debug("Tool calls: %s", tool_calls)
@@ -538,17 +535,12 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915
call = plugins.call # Update call model if object reference changed
# Store message
- if call.messages[-1].persona == MessagePersonaEnum.ASSISTANT:
- message = call.messages[-1]
- message.content = content_full.strip()
- message.style = plugins.style
- message.tool_calls = tool_calls
- else:
+ async with _db.call_transac(call):
call.messages.append(
MessageModel(
- content=content_full.strip(),
+ content="", # Content has already been stored within the TTS callback
persona=MessagePersonaEnum.ASSISTANT,
- style=plugins.style,
+ style=last_style,
tool_calls=tool_calls,
)
)
@@ -586,29 +578,43 @@ async def _in_audio( # noqa: PLR0913
"""
Flush the audio buffer if no audio is detected for a while and trigger the timeout if required.
"""
- # Wait and flush the audio buffer
+ # Wait before flushing
nonlocal clear_tts_task
timeout_ms = await vad_silence_timeout_ms()
await asyncio.sleep(timeout_ms / 1000)
+
+ # Cancel the clear TTS task if any
if clear_tts_task:
clear_tts_task.cancel()
clear_tts_task = None
+
+ # Flush the audio buffer
logger.debug("Flushing audio buffer after %i ms", timeout_ms)
await response_callback()
# Wait for silence and trigger timeout
timeout_sec = await phone_silence_timeout_sec()
- while call.in_progress:
+ while True:
+ # Stop this time if the call played a message
timeout_start = datetime.now(UTC)
await asyncio.sleep(timeout_sec)
+
+ # Stop if the call ended
+ if not call.in_progress:
+ break
+
+ # Cancel if an interaction happened in the meantime
if (
- call.messages[-1].created_at + timedelta(seconds=timeout_sec)
+ call.last_interaction_at
+ and call.last_interaction_at + timedelta(seconds=timeout_sec)
> timeout_start
):
logger.debug(
"Message sent in the meantime, canceling this silence timeout"
)
continue
+
+ # Trigger the timeout
logger.info("Silence triggered after %i sec", timeout_sec)
await timeout_callback()
@@ -691,7 +697,11 @@ def _tts_callback(
text: str,
style: MessageStyleEnum,
) -> None:
- # First, play the TTS to the user
+ # Skip if no text
+ if not text:
+ return
+
+ # Play the TTS
await scheduler.spawn(
handle_play_text(
call=call,
@@ -700,7 +710,5 @@ def _tts_callback(
text=text,
)
)
- # Second, save in DB allowing (1) user to cut off the Assistant and (2) SMS answers to be in order
- await _db.call_aset(call)
return wrapper
diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.py
index 5f605dc..b453263 100644
--- a/app/helpers/call_utils.py
+++ b/app/helpers/call_utils.py
@@ -37,6 +37,8 @@ _TTS_SANITIZER_R = re.compile(
r"[^\w\sÀ-ÿ'«»“”\"\"‘’''(),.!?;:\-\+_@/&€$%=]" # noqa: RUF001
) # Sanitize text for TTS
+_db = CONFIG.database.instance()
+
class ContextEnum(str, Enum):
"""
@@ -221,13 +223,7 @@ async def _chunk_before_tts(
# Store text in call messages
if store:
- if (
- call.messages
- and call.messages[-1].persona == MessagePersonaEnum.ASSISTANT
- and call.messages[-1].style == style
- ): # Append to last message if possible
- call.messages[-1].content += f" {text}"
- else:
+ async with _db.call_transac(call):
call.messages.append(
MessageModel(
content=text,
diff --git a/app/helpers/config_models/cache.py b/app/helpers/config_models/cache.py
index 1928d09..454349b 100644
--- a/app/helpers/config_models/cache.py
+++ b/app/helpers/config_models/cache.py
@@ -46,7 +46,7 @@ class CacheModel(BaseModel):
@field_validator("redis")
@classmethod
- def _validate_sqlite(
+ def _validate_redis(
cls,
redis: RedisModel | None,
info: ValidationInfo,
diff --git a/app/helpers/config_models/database.py b/app/helpers/config_models/database.py
index 0e5a84b..347e1f4 100644
--- a/app/helpers/config_models/database.py
+++ b/app/helpers/config_models/database.py
@@ -1,16 +1,10 @@
-from enum import Enum
from functools import cache
-from pydantic import BaseModel, ValidationInfo, field_validator
+from pydantic import BaseModel
from app.persistence.istore import IStore
-class ModeEnum(str, Enum):
- COSMOS_DB = "cosmos_db"
- SQLITE = "sqlite"
-
-
class CosmosDbModel(BaseModel, frozen=True):
container: str
database: str
@@ -26,60 +20,9 @@ class CosmosDbModel(BaseModel, frozen=True):
return CosmosDbStore(CONFIG.cache.instance(), self)
-class SqliteModel(BaseModel, frozen=True):
- path: str = ".local"
- schema_version: int = 3
- table: str = "calls"
-
- def full_path(self) -> str:
- """
- Returns the full path to the sqlite database file.
-
- Formatted as: `{path}-v{schema_version}.sqlite`.
- """
- return f"{self.path}-v{self.schema_version}.sqlite"
-
- @cache
- def instance(self) -> IStore:
- from app.helpers.config import CONFIG
- from app.persistence.sqlite import (
- SqliteStore,
- )
-
- return SqliteStore(CONFIG.cache.instance(), self)
-
-
class DatabaseModel(BaseModel):
- cosmos_db: CosmosDbModel | None = None
- mode: ModeEnum = ModeEnum.SQLITE
- sqlite: SqliteModel | None = SqliteModel() # Object is fully defined by default
-
- @field_validator("cosmos_db")
- @classmethod
- def _validate_cosmos_db(
- cls,
- cosmos_db: CosmosDbModel | None,
- info: ValidationInfo,
- ) -> CosmosDbModel | None:
- if not cosmos_db and info.data.get("mode", None) == ModeEnum.COSMOS_DB:
- raise ValueError("Cosmos DB config required")
- return cosmos_db
-
- @field_validator("sqlite")
- @classmethod
- def _validate_sqlite(
- cls,
- sqlite: SqliteModel | None,
- info: ValidationInfo,
- ) -> SqliteModel | None:
- if not sqlite and info.data.get("mode", None) == ModeEnum.SQLITE:
- raise ValueError("SQLite config required")
- return sqlite
+ cosmos_db: CosmosDbModel
def instance(self) -> IStore:
- if self.mode == ModeEnum.SQLITE:
- assert self.sqlite
- return self.sqlite.instance()
-
assert self.cosmos_db
return self.cosmos_db.instance()
diff --git a/app/helpers/config_models/root.py b/app/helpers/config_models/root.py
index 585017a..66d9e8d 100644
--- a/app/helpers/config_models/root.py
+++ b/app/helpers/config_models/root.py
@@ -40,7 +40,7 @@ class RootModel(BaseSettings):
communication_services: CommunicationServicesModel = Field(
serialization_alias="communication_service", # Compatibility with v5
)
- database: DatabaseModel = DatabaseModel() # Object is fully defined by default
+ database: DatabaseModel
llm: LlmModel
monitoring: MonitoringModel = (
MonitoringModel()
diff --git a/app/helpers/features.py b/app/helpers/features.py
index 6342f5d..20a63ec 100644
--- a/app/helpers/features.py
+++ b/app/helpers/features.py
@@ -29,7 +29,7 @@ async def callback_timeout_hour() -> int:
async def phone_silence_timeout_sec() -> int:
- return await _get(key="phone_silence_timeout_sec", type_res=int) or 10
+ return await _get(key="phone_silence_timeout_sec", type_res=int) or 20
async def vad_silence_timeout_ms() -> int:
@@ -55,7 +55,7 @@ async def recognition_retry_max() -> int:
async def _get(key: str, type_res: type[T]) -> T | None:
# Try cache
cache_key = _cache_key(key)
- cached = await _cache.aget(cache_key)
+ cached = await _cache.get(cache_key)
if cached:
return _parse(value=cached.decode(), type_res=type_res)
# Try live
@@ -69,7 +69,7 @@ async def _get(key: str, type_res: type[T]) -> T | None:
logger.warning("Setting %s not found", key)
return
# Update cache
- await _cache.aset(
+ await _cache.set(
key=cache_key,
ttl_sec=CONFIG.app_configuration.ttl_sec,
value=setting.value,
diff --git a/app/helpers/llm_tools.py b/app/helpers/llm_tools.py
index 139363e..97bd544 100644
--- a/app/helpers/llm_tools.py
+++ b/app/helpers/llm_tools.py
@@ -15,7 +15,6 @@ from app.models.message import (
ActionEnum as MessageActionEnum,
MessageModel,
PersonaEnum as MessagePersonaEnum,
- StyleEnum as MessageStyleEnum,
)
from app.models.reminder import ReminderModel
from app.models.training import TrainingModel
@@ -32,15 +31,14 @@ class UpdateClaimDict(TypedDict):
class DefaultPlugin(AbstractPlugin):
client: CallAutomationClient
post_callback: Callable[[CallStateModel], Awaitable[None]]
- style: MessageStyleEnum = MessageStyleEnum.NONE
- tts_callback: Callable[[str, MessageStyleEnum], Awaitable[None]]
+ tts_callback: Callable[[str], Awaitable[None]]
def __init__(
self,
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
- tts_callback: Callable[[str, MessageStyleEnum], Awaitable[None]],
+ tts_callback: Callable[[str], Awaitable[None]],
):
super().__init__(call)
self.client = client
@@ -103,7 +101,7 @@ class DefaultPlugin(AbstractPlugin):
- Customer wants explicitely to create a new claim
- Talking about a totally different subject
"""
- await self.tts_callback(customer_response, self.style)
+ await self.tts_callback(customer_response)
# Launch post-call intelligence for the current call
await self.post_callback(self.call)
# Store the last message and use it at first message of the new claim
@@ -174,7 +172,7 @@ class DefaultPlugin(AbstractPlugin):
- Call back for a follow-up
- Wait for customer to send a document
"""
- await self.tts_callback(customer_response, self.style)
+ await self.tts_callback(customer_response)
# Check if reminder already exists, if so update it
for reminder in self.call.reminders:
@@ -261,7 +259,7 @@ class DefaultPlugin(AbstractPlugin):
- Store details about the conversation
- Update the claim with a new phone number
"""
- await self.tts_callback(customer_response, self.style)
+ await self.tts_callback(customer_response)
# Update all claim fields
res = "# Updated fields"
for field in updates:
@@ -343,11 +341,11 @@ class DefaultPlugin(AbstractPlugin):
- Know the procedure to declare a stolen luxury watch
- Understand the requirements to ask for a cyber attack insurance
"""
- await self.tts_callback(customer_response, self.style)
+ await self.tts_callback(customer_response)
# Execute in parallel
tasks = await asyncio.gather(
*[
- _search.training_asearch_all(text=query, lang="en-US")
+ _search.training_search_all(text=query, lang="en-US")
for query in queries
]
)
@@ -415,7 +413,7 @@ class DefaultPlugin(AbstractPlugin):
- A neighbor is having a heart attack
- Someons is stuck in a car accident
"""
- await self.tts_callback(customer_response, self.style)
+ await self.tts_callback(customer_response)
# TODO: Implement notification to emergency services for production usage
logger.info(
"Notifying %s, location %s, contact %s, reason %s",
@@ -457,8 +455,8 @@ class DefaultPlugin(AbstractPlugin):
- Confirm a detail like a reference number, if there is a misunderstanding
- Send a confirmation, if the customer wants to have a written proof
"""
- await self.tts_callback(customer_response, self.style)
- success = await _sms.asend(
+ await self.tts_callback(customer_response)
+ success = await _sms.send(
content=message,
phone_number=self.call.initiate.phone_number,
)
@@ -512,7 +510,7 @@ class DefaultPlugin(AbstractPlugin):
initial_speed = self.call.initiate.prosody_rate
self.call.initiate.prosody_rate = speed
# Customer confirmation (with new speed)
- await self.tts_callback(customer_response, self.style)
+ await self.tts_callback(customer_response)
# LLM confirmation
return f"Voice speed set to {speed} (was {initial_speed})"
@@ -575,6 +573,6 @@ class DefaultPlugin(AbstractPlugin):
initial_lang = self.call.lang.short_code
self.call.lang = lang
# Customer confirmation (with new language)
- await self.tts_callback(customer_response, self.style)
+ await self.tts_callback(customer_response)
# LLM confirmation
return f"Voice language set to {lang} (was {initial_lang})"
diff --git a/app/helpers/translation.py b/app/helpers/translation.py
index d502113..84655b5 100644
--- a/app/helpers/translation.py
+++ b/app/helpers/translation.py
@@ -36,7 +36,7 @@ async def translate_text(text: str, source_lang: str, target_lang: str) -> str |
# Try cache
cache_key = f"{__name__}-translate_text-{text}-{source_lang}-{target_lang}"
- cached = await _cache.aget(cache_key)
+ cached = await _cache.get(cache_key)
if cached:
return cached.decode()
@@ -51,7 +51,7 @@ async def translate_text(text: str, source_lang: str, target_lang: str) -> str |
translation = res[0].translations[0].text if res and res[0].translations else None
# Update cache
- await _cache.aset(
+ await _cache.set(
key=cache_key,
ttl_sec=60 * 60 * 24, # 1 day
value=translation,
diff --git a/app/main.py b/app/main.py
index ba55c27..416237d 100644
--- a/app/main.py
+++ b/app/main.py
@@ -48,6 +48,7 @@ from app.helpers.call_events import (
on_new_call,
on_play_completed,
on_play_error,
+ on_play_started,
on_recognize_error,
on_sms_received,
on_transfer_completed,
@@ -201,10 +202,10 @@ async def health_readiness_get() -> JSONResponse:
search_check,
sms_check,
) = await asyncio.gather(
- _cache.areadiness(),
- _db.areadiness(),
- _search.areadiness(),
- _sms.areadiness(),
+ _cache.readiness(),
+ _db.readiness(),
+ _search.readiness(),
+ _sms.readiness(),
)
readiness = ReadinessModel(
status=ReadinessEnum.OK,
@@ -246,7 +247,7 @@ async def report_get(phone_number: str | None = None) -> HTMLResponse:
phone_number = PhoneNumber(phone_number) if phone_number else None
count = 100
calls, total = (
- await _db.call_asearch_all(count=count, phone_number=phone_number) or []
+ await _db.call_search_all(count=count, phone_number=phone_number) or []
)
template = _jinja.get_template("list.html.jinja")
@@ -281,7 +282,7 @@ async def report_single_get(call_id: UUID) -> HTMLResponse:
Returns a single call with a web interface.
"""
- call = await _db.call_aget(call_id)
+ call = await _db.call_get(call_id)
if not call:
return HTMLResponse(
content=f"Call {call_id} not found",
@@ -319,7 +320,7 @@ async def call_list_get(
"""
phone_number = PhoneNumber(phone_number) if phone_number else None
count = 100
- calls, _ = await _db.call_asearch_all(phone_number=phone_number, count=count)
+ calls, _ = await _db.call_search_all(phone_number=phone_number, count=count)
if not calls:
raise HTTPException(
detail=f"Call {phone_number} not found",
@@ -344,7 +345,7 @@ async def call_get(call_id_or_phone_number: str) -> CallGetModel:
# First, try to get by call ID
try:
call_id = UUID(call_id_or_phone_number)
- call = await _db.call_aget(call_id)
+ call = await _db.call_get(call_id)
if call:
return TypeAdapter(CallGetModel).dump_python(call)
except ValueError:
@@ -352,7 +353,7 @@ async def call_get(call_id_or_phone_number: str) -> CallGetModel:
# Second, try to get by phone number
phone_number = PhoneNumber(call_id_or_phone_number)
- call = await _db.call_asearch_one(phone_number=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",
@@ -482,7 +483,7 @@ async def sms_event(
span_attribute(CallAttributes.CALL_PHONE_NUMBER, phone_number)
# Get call
- call = await _db.call_asearch_one(phone_number)
+ call = await _db.call_search_one(phone_number)
if not call:
logger.warning("Call for phone number %s not found", phone_number)
return
@@ -537,7 +538,7 @@ async def _communicationservices_validate_call_id(
span_attribute(CallAttributes.CALL_ID, str(call_id))
# Validate call
- call = await _db.call_aget(call_id)
+ call = await _db.call_get(call_id)
if not call:
raise HTTPException(
detail=f"Call {call_id} not found",
@@ -682,14 +683,19 @@ async def _communicationservices_event_worker(
# Event parsing
event = CloudEvent.from_dict(event_dict)
assert isinstance(event.data, dict)
+
# Store connection ID
connection_id = event.data["callConnectionId"]
- call.voice_id = connection_id
+ async with _db.call_transac(call):
+ call.voice_id = connection_id
+
# Extract context
event_type = event.type
+
# Extract event context
operation_context = event.data.get("operationContext", None)
operation_contexts = _str_to_contexts(operation_context)
+
# Client SDK
automation_client = await _use_automation_client()
@@ -738,6 +744,11 @@ async def _communicationservices_event_worker(
post_callback=_trigger_post_event,
)
+ case "Microsoft.Communication.PlayStarted": # Media started
+ await on_play_started(
+ call=call,
+ )
+
case "Microsoft.Communication.PlayCompleted": # Media played
await on_play_completed(
call=call,
@@ -767,10 +778,6 @@ async def _communicationservices_event_worker(
logger.warning("Event %s not supported", event_type)
logger.debug("Event data %s", event.data)
- await _db.call_aset(
- call
- ) # TODO: Do not persist on every event, this is simpler but not efficient
-
@tracer.start_as_current_span("training_event")
async def training_event(
@@ -806,7 +813,7 @@ 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_aget(UUID(post.content))
+ call = await _db.call_get(UUID(post.content))
if not call:
logger.warning("Call %s not found", post.content)
return
@@ -845,18 +852,22 @@ async def _communicationservices_urls(
Returnes a tuple of the callback URL, the WebSocket URL, and the call object.
"""
- call = await _db.call_asearch_one(phone_number)
- if not call or (
- initiate and call.initiate != initiate
- ): # Create new call if initiate is different
- call = CallStateModel(
- initiate=initiate
- or CallInitiateModel(
- **CONFIG.conversation.initiate.model_dump(),
- phone_number=phone_number,
+ # 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,
+ )
)
)
- await _db.call_aset(call) # Create for the first time
+
+ # Format URLs
wss_url = _COMMUNICATIONSERVICES_WSS_TPL.format(
callback_secret=call.callback_secret,
call_id=str(call.call_id),
@@ -865,6 +876,7 @@ async def _communicationservices_urls(
callback_secret=call.callback_secret,
call_id=str(call.call_id),
)
+
return callaback_url, wss_url, call
@@ -888,7 +900,7 @@ async def twilio_sms_post(
span_attribute(CallAttributes.CALL_PHONE_NUMBER, From)
# Get call
- call = await _db.call_asearch_one(From)
+ call = await _db.call_search_one(From)
if not call:
logger.warning("Call for phone number %s not found", From)
diff --git a/app/models/call.py b/app/models/call.py
index b8df7df..aa4250b 100644
--- a/app/models/call.py
+++ b/app/models/call.py
@@ -48,6 +48,9 @@ class CallGetModel(BaseModel):
def _validate_claim(
cls, claim: dict[str, Any] | None, info: ValidationInfo
) -> dict[str, Any]:
+ """
+ Validate the claim field against the initiate data model.
+ """
initiate: CallInitiateModel | None = info.data.get("initiate", None)
if not initiate:
return {}
@@ -60,6 +63,26 @@ class CallGetModel(BaseModel):
)
)
+ @field_validator("messages")
+ @classmethod
+ def _validate_messages(cls, messages: list[MessageModel]) -> list[MessageModel]:
+ """
+ Merge messages with the same persona.
+ """
+ merged: list[MessageModel] = []
+ for new_message in messages:
+ if not (
+ merged
+ and (last := merged[-1]).persona == new_message.persona
+ and last.action == new_message.action
+ ):
+ merged.append(new_message)
+ continue
+ last.content = (last.content + " " + new_message.content).strip()
+ last.style = new_message.style
+ last.tool_calls += new_message.tool_calls
+ return merged
+
class CallStateModel(CallGetModel, extra="ignore"):
# Immutable fields
@@ -71,6 +94,7 @@ class CallStateModel(CallGetModel, extra="ignore"):
)
# Editable fields
lang_short_code: str | None = None
+ last_interaction_at: datetime | None = None
recognition_retry: int = 0
voice_id: str | None = None
@@ -108,7 +132,7 @@ class CallStateModel(CallGetModel, extra="ignore"):
search = CONFIG.ai_search.instance()
tasks = await asyncio.gather(
*[
- search.training_asearch_all(
+ search.training_search_all(
cache_only=cache_only,
lang=self.lang.short_code,
text=message.content,
diff --git a/app/models/message.py b/app/models/message.py
index bb4fdcd..c5d79c8 100644
--- a/app/models/message.py
+++ b/app/models/message.py
@@ -132,11 +132,10 @@ class ToolModel(BaseModel):
res = "Wrong arguments, please fix them and try again."
res_log = res
except Exception as e:
- logger.warning(
+ logger.exception(
"Error executing function %s with args %s",
self.function_name,
args,
- exc_info=True,
)
res = f"Error: {e}."
res_log = res
@@ -224,6 +223,10 @@ class MessageModel(BaseModel):
def remove_message_action(text: str) -> str:
"""
Remove action from content. AI often adds it by mistake event if explicitly asked not to.
+
+ Example:
+ - Input: "action=talk Hello!"
+ - Output: "Hello!"
"""
# TODO: Use JSON as LLM response instead of using a regex to parse the text
res = re.match(_MESSAGE_ACTION_R, text)
@@ -235,18 +238,22 @@ def remove_message_action(text: str) -> str:
return text
-def extract_message_style(text: str) -> tuple[StyleEnum | None, str]:
+def extract_message_style(text: str) -> tuple[StyleEnum, str]:
"""
- Detect the style of a message.
+ Detect the style of a message and extract it from the text.
+
+ Example:
+ - Input: "style=cheerful Hello!"
+ - Output: (StyleEnum.CHEERFUL, "Hello!")
"""
- # TODO: Use JSON as LLM response instead of using a regex to parse the text
+ default_style = StyleEnum.NONE
res = re.match(_MESSAGE_STYLE_R, text)
if not res:
- return None, text
+ return default_style, text
try:
return (
StyleEnum(res.group(1)), # style
(res.group(2) or ""), # content
)
except ValueError: # Regex failed, return original text
- return None, text
+ return default_style, text
diff --git a/app/persistence/ai_search.py b/app/persistence/ai_search.py
index 3bbacdd..63f2912 100644
--- a/app/persistence/ai_search.py
+++ b/app/persistence/ai_search.py
@@ -64,7 +64,7 @@ class AiSearchSearch(ISearch):
)
self._config = config
- async def areadiness(self) -> ReadinessEnum:
+ async def readiness(self) -> ReadinessEnum:
"""
Check the readiness of the AI Search service.
"""
@@ -77,9 +77,7 @@ class AiSearchSearch(ISearch):
except ServiceRequestError:
logger.exception("Error connecting to AI Search")
except Exception:
- logger.error(
- "Unknown error while checking AI Search readiness", exc_info=True
- )
+ logger.exception("Unknown error while checking AI Search readiness")
return ReadinessEnum.FAIL
@retry(
@@ -88,7 +86,7 @@ class AiSearchSearch(ISearch):
stop=stop_after_attempt(3),
wait=wait_random_exponential(multiplier=0.8, max=8),
)
- async def training_asearch_all(
+ async def training_search_all(
self,
lang: str,
text: str,
@@ -100,7 +98,7 @@ class AiSearchSearch(ISearch):
# Try cache
cache_key = f"{self.__class__.__name__}-training_asearch_all-v2-{text}" # Cache sort method has been updated in v6, thus the v2
- cached = await self._cache.aget(cache_key)
+ cached = await self._cache.get(cache_key)
if cached:
try:
return TypeAdapter(list[TrainingModel]).validate_json(cached)
@@ -166,7 +164,7 @@ class AiSearchSearch(ISearch):
# Update cache
if trainings:
- await self._cache.aset(
+ await self._cache.set(
key=cache_key,
ttl_sec=60 * 60 * 24, # 1 day
value=TypeAdapter(list[TrainingModel]).dump_json(trainings),
diff --git a/app/persistence/communication_services.py b/app/persistence/communication_services.py
index 4694000..2c3bcec 100644
--- a/app/persistence/communication_services.py
+++ b/app/persistence/communication_services.py
@@ -19,14 +19,14 @@ class CommunicationServicesSms(ISms):
logger.info("Using Communication Services from number %s", config.phone_number)
self._config = config
- async def areadiness(self) -> ReadinessEnum:
+ async def readiness(self) -> ReadinessEnum:
"""
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 ReadinessEnum.OK
- async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
+ async def send(self, content: str, phone_number: PhoneNumber) -> bool:
logger.info("Sending SMS to %s", phone_number)
success = False
logger.info("SMS content: %s", content)
@@ -49,11 +49,9 @@ class CommunicationServicesSms(ISms):
response.error_message,
)
except ClientAuthenticationError:
- logger.error(
- "Authentication error for SMS, check the credentials", exc_info=True
- )
+ logger.exception("Authentication error for SMS, check the credentials")
except HttpResponseError:
- logger.error("Error sending SMS to %s", phone_number, exc_info=True)
+ logger.exception("Error sending SMS to %s", phone_number)
return success
async def _use_client(self) -> SmsClient:
diff --git a/app/persistence/cosmos_db.py b/app/persistence/cosmos_db.py
index e8c12b3..4c43911 100644
--- a/app/persistence/cosmos_db.py
+++ b/app/persistence/cosmos_db.py
@@ -1,6 +1,7 @@
import asyncio
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
+from typing import Any
from uuid import UUID, uuid4
from azure.cosmos import ConsistencyLevel
@@ -28,7 +29,7 @@ class CosmosDbStore(IStore):
logger.info("Using Cosmos DB %s/%s", config.database, config.container)
self._config = config
- async def areadiness(self) -> ReadinessEnum:
+ async def readiness(self) -> ReadinessEnum:
"""
Check the readiness of the Cosmos DB service.
@@ -68,9 +69,7 @@ class CosmosDbStore(IStore):
except CosmosHttpResponseError:
logger.exception("Error requesting CosmosDB")
except Exception:
- logger.error(
- "Unknown error while checking Cosmos DB readiness", exc_info=True
- )
+ logger.exception("Unknown error while checking Cosmos DB readiness")
return ReadinessEnum.FAIL
async def _item_exists(self, test_id: str, partition_key: str) -> bool:
@@ -83,12 +82,12 @@ class CosmosDbStore(IStore):
pass
return exist
- async def call_aget(self, call_id: UUID) -> CallStateModel | None:
+ async def call_get(self, call_id: UUID) -> CallStateModel | None:
logger.debug("Loading call %s", call_id)
# Try cache
cache_key = self._cache_key_call_id(call_id)
- cached = await self._cache.aget(cache_key)
+ cached = await self._cache.get(cache_key)
if cached:
try:
return CallStateModel.model_validate_json(cached)
@@ -115,7 +114,7 @@ class CosmosDbStore(IStore):
# Update cache
if call:
- await self._cache.aset(
+ await self._cache.set(
key=cache_key,
ttl_sec=await callback_timeout_hour(),
value=call.model_dump_json(),
@@ -123,43 +122,133 @@ class CosmosDbStore(IStore):
return call
- async def call_aset(self, call: CallStateModel) -> bool:
- logger.debug("Saving call %s", call.call_id)
+ @asynccontextmanager
+ async def call_transac(self, call: CallStateModel) -> AsyncGenerator[None, None]:
+ # Copy and yield the updated object
+ init_data = call.model_copy().model_dump(mode="json", exclude_none=True)
+ yield
+
+ # Compute the diff
+ call_data = call.model_dump(mode="json", exclude_none=True)
+ update_data: dict[str, Any | list[Any]] = {}
+ for field, new_value in call_data.items():
+ init_value = init_data.get(field)
+ if init_value != new_value:
+ if isinstance(new_value, list) and isinstance(init_value, list):
+ update_data[field] = [
+ item for item in new_value if item not in init_value
+ ]
+ else:
+ update_data[field] = new_value
- # Update live
- data = call.model_dump(mode="json", exclude_none=True)
- data["id"] = str(call.call_id) # CosmosDB requires an id field
- res = False
+ # Skip if no diff
+ if not update_data:
+ logger.debug("No update needed for call %s", call.call_id)
+ return
+
+ # Update
+ logger.debug(
+ "Updating call %s with %s",
+ call.call_id,
+ update_data,
+ )
+ refreshed_call_raw = None
try:
async with self._use_client() as db:
- await db.upsert_item(body=data)
- res = True
+ # See: https://learn.microsoft.com/en-us/azure/cosmos-db/partial-document-update#supported-operations
+ refreshed_call_raw = await db.patch_item(
+ item=str(call.call_id),
+ partition_key=call.initiate.phone_number,
+ patch_operations=[
+ # Replace fields
+ *[
+ {
+ "op": "set",
+ "path": f"/{field}",
+ "value": value,
+ }
+ for field, value in update_data.items()
+ if not isinstance(value, list)
+ ],
+ # Add to arrays
+ *[
+ {
+ "op": "add",
+ "path": f"/{field}/-",
+ "value": value,
+ }
+ for field, values in update_data.items()
+ if isinstance(values, list)
+ for value in values
+ ],
+ ],
+ )
except CosmosHttpResponseError as e:
logger.error("Error accessing CosmosDB: %s", e)
- # Update cache
- if res:
- cache_key_id = self._cache_key_call_id(call.call_id)
- await self._cache.aset(
- key=cache_key_id,
- ttl_sec=await callback_timeout_hour(),
- value=call.model_dump_json(),
- ) # Update for ID
- cache_key_phone_number = self._cache_key_phone_number(
- call.initiate.phone_number
+ # Skip if no refresh
+ if not refreshed_call_raw:
+ return
+
+ # Parse refreshed object
+ try:
+ refreshed_call = CallStateModel.model_validate(refreshed_call_raw)
+ except ValidationError:
+ logger.debug("Parsing error", exc_info=True)
+ return
+
+ # Refresh live object
+ for field in call.model_fields_set:
+ new_value = getattr(refreshed_call, field)
+ if getattr(call, field) == new_value:
+ continue
+ logger.debug(
+ "Updating local field %s with %s from remote",
+ field,
+ new_value,
)
- await self._cache.adel(
- cache_key_phone_number
- ) # Invalidate for phone number because we don't know if it's the same call
+ setattr(call, field, new_value)
+
+ # Update cache
+ cache_key_id = self._cache_key_call_id(refreshed_call.call_id)
+ await self._cache.set(
+ key=cache_key_id,
+ ttl_sec=await callback_timeout_hour(),
+ value=refreshed_call.model_dump_json(),
+ ) # Update for ID
+ cache_key_phone_number = self._cache_key_phone_number(
+ refreshed_call.initiate.phone_number
+ )
+ await self._cache.delete(
+ cache_key_phone_number
+ ) # Invalidate for phone number because we don't know if it's the same call
+
+ # TODO: Catch errors
+ async def call_create(self, call: CallStateModel) -> CallStateModel:
+ logger.debug("Creating new call %s", call.call_id)
+
+ # Serialize
+ data = call.model_dump(mode="json", exclude_none=True)
+ data["id"] = str(call.call_id)
- return res
+ # Persist
+ try:
+ async with self._use_client() as db:
+ raw = await db.create_item(body=data)
+ return CallStateModel.model_validate(raw)
+ except CosmosHttpResponseError:
+ logger.exception("Error accessing CosmosDB")
+ except ValidationError:
+ logger.debug("Parsing error", exc_info=True)
+
+ return call
- async def call_asearch_one(self, phone_number: str) -> CallStateModel | None:
+ async def call_search_one(self, phone_number: str) -> CallStateModel | None:
logger.debug("Loading last call for %s", phone_number)
# Try cache
cache_key = self._cache_key_phone_number(phone_number)
- cached = await self._cache.aget(cache_key)
+ cached = await self._cache.get(cache_key)
if cached:
try:
return CallStateModel.model_validate_json(cached)
@@ -192,7 +281,7 @@ class CosmosDbStore(IStore):
# Update cache
if call:
- await self._cache.aset(
+ await self._cache.set(
key=cache_key,
ttl_sec=await callback_timeout_hour(),
value=call.model_dump_json(),
@@ -200,7 +289,7 @@ class CosmosDbStore(IStore):
return call
- async def call_asearch_all(
+ async def call_search_all(
self,
count: int,
phone_number: str | None = None,
diff --git a/app/persistence/icache.py b/app/persistence/icache.py
index fd975ea..d347864 100644
--- a/app/persistence/icache.py
+++ b/app/persistence/icache.py
@@ -6,21 +6,21 @@ from app.models.readiness import ReadinessEnum
class ICache(ABC):
@abstractmethod
- @tracer.start_as_current_span("cache_areadiness")
- async def areadiness(self) -> ReadinessEnum:
+ @tracer.start_as_current_span("cache_readiness")
+ async def readiness(self) -> ReadinessEnum:
pass
@abstractmethod
- @tracer.start_as_current_span("cache_aget")
- async def aget(self, key: str) -> bytes | None:
+ @tracer.start_as_current_span("cache_get")
+ async def get(self, key: str) -> bytes | None:
pass
@abstractmethod
- @tracer.start_as_current_span("cache_aset")
- async def aset(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
+ @tracer.start_as_current_span("cache_set")
+ async def set(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
pass
@abstractmethod
- @tracer.start_as_current_span("cache_adel")
- async def adel(self, key: str) -> bool:
+ @tracer.start_as_current_span("cache_delete")
+ async def delete(self, key: str) -> bool:
pass
diff --git a/app/persistence/isearch.py b/app/persistence/isearch.py
index f354c2d..41c18aa 100644
--- a/app/persistence/isearch.py
+++ b/app/persistence/isearch.py
@@ -13,13 +13,13 @@ class ISearch(ABC):
self._cache = cache
@abstractmethod
- @tracer.start_as_current_span("search_areadiness")
- async def areadiness(self) -> ReadinessEnum:
+ @tracer.start_as_current_span("search_readiness")
+ async def readiness(self) -> ReadinessEnum:
pass
@abstractmethod
- @tracer.start_as_current_span("search_training_asearch_all")
- async def training_asearch_all(
+ @tracer.start_as_current_span("search_training_search_all")
+ async def training_search_all(
self,
lang: str,
text: str,
diff --git a/app/persistence/isms.py b/app/persistence/isms.py
index deeae09..d560a93 100644
--- a/app/persistence/isms.py
+++ b/app/persistence/isms.py
@@ -7,11 +7,11 @@ from app.models.readiness import ReadinessEnum
class ISms(ABC):
@abstractmethod
- @tracer.start_as_current_span("sms_areadiness")
- async def areadiness(self) -> ReadinessEnum:
+ @tracer.start_as_current_span("sms_readiness")
+ async def readiness(self) -> ReadinessEnum:
pass
@abstractmethod
- @tracer.start_as_current_span("sms_asend")
- async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
+ @tracer.start_as_current_span("sms_send")
+ async def send(self, content: str, phone_number: PhoneNumber) -> bool:
pass
diff --git a/app/persistence/istore.py b/app/persistence/istore.py
index 1a42a85..5920cfd 100644
--- a/app/persistence/istore.py
+++ b/app/persistence/istore.py
@@ -1,4 +1,5 @@
from abc import ABC, abstractmethod
+from contextlib import AbstractAsyncContextManager
from uuid import UUID
from app.helpers.monitoring import tracer
@@ -14,28 +15,33 @@ class IStore(ABC):
self._cache = cache
@abstractmethod
- @tracer.start_as_current_span("store_areadiness")
- async def areadiness(self) -> ReadinessEnum:
+ @tracer.start_as_current_span("store_readiness")
+ async def readiness(self) -> ReadinessEnum:
pass
@abstractmethod
- @tracer.start_as_current_span("store_call_aget")
- async def call_aget(self, call_id: UUID) -> CallStateModel | None:
+ @tracer.start_as_current_span("store_call_get")
+ async def call_get(self, call_id: UUID) -> CallStateModel | None:
pass
@abstractmethod
- @tracer.start_as_current_span("store_call_aset")
- async def call_aset(self, call: CallStateModel) -> bool:
+ @tracer.start_as_current_span("store_call_transac")
+ def call_transac(self, call: CallStateModel) -> AbstractAsyncContextManager[None]:
pass
@abstractmethod
- @tracer.start_as_current_span("store_call_asearch_one")
- async def call_asearch_one(self, phone_number: str) -> CallStateModel | None:
+ @tracer.start_as_current_span("store_call_create")
+ async def call_create(self, call: CallStateModel) -> CallStateModel:
pass
@abstractmethod
- @tracer.start_as_current_span("store_call_asearch_all")
- async def call_asearch_all(
+ @tracer.start_as_current_span("store_call_search_one")
+ async def call_search_one(self, phone_number: str) -> CallStateModel | None:
+ pass
+
+ @abstractmethod
+ @tracer.start_as_current_span("store_call_search_all")
+ async def call_search_all(
self,
count: int,
phone_number: str | None = None,
diff --git a/app/persistence/memory.py b/app/persistence/memory.py
index 636347a..95ccc43 100644
--- a/app/persistence/memory.py
+++ b/app/persistence/memory.py
@@ -28,13 +28,13 @@ class MemoryCache(ICache):
)
self._config = config
- async def areadiness(self) -> ReadinessEnum:
+ async def readiness(self) -> ReadinessEnum:
"""
Check the readiness of the memory cache.
"""
return ReadinessEnum.OK # Always ready, it's memory :)
- async def aget(self, key: str) -> bytes | None:
+ async def get(self, key: str) -> bytes | None:
"""
Get a value from the cache.
@@ -53,7 +53,7 @@ class MemoryCache(ICache):
self._cache.move_to_end(sha_key, last=False)
return res
- async def aset(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
+ async def set(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
"""
Set a value in the cache.
"""
@@ -68,7 +68,7 @@ class MemoryCache(ICache):
self._ttl[sha_key] = datetime.now(UTC) + timedelta(seconds=ttl_sec)
return True
- async def adel(self, key: str) -> bool:
+ async def delete(self, key: str) -> bool:
"""
Delete a value from the cache.
"""
diff --git a/app/persistence/redis.py b/app/persistence/redis.py
index a64a922..5e2ad29 100644
--- a/app/persistence/redis.py
+++ b/app/persistence/redis.py
@@ -48,7 +48,7 @@ class RedisCache(ICache):
password=config.password.get_secret_value(),
) # Redis manage by itself a low level connection pool with asyncio, but be warning to not use a generator while consuming the connection, it will close it
- async def areadiness(self) -> ReadinessEnum:
+ async def readiness(self) -> ReadinessEnum:
"""
Check the readiness of the Redis cache.
@@ -76,7 +76,7 @@ class RedisCache(ICache):
logger.exception("Unknown error while checking Redis readiness")
return ReadinessEnum.FAIL
- async def aget(self, key: str) -> bytes | None:
+ async def get(self, key: str) -> bytes | None:
"""
Get a value from the cache.
@@ -92,7 +92,7 @@ class RedisCache(ICache):
logger.exception("Error getting value")
return res
- async def aset(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
+ async def set(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
"""
Set a value in the cache.
@@ -112,7 +112,7 @@ class RedisCache(ICache):
return False
return True
- async def adel(self, key: str) -> bool:
+ async def delete(self, key: str) -> bool:
"""
Delete a value from the cache.
diff --git a/app/persistence/sqlite.py b/app/persistence/sqlite.py
deleted file mode 100644
index c76943e..0000000
--- a/app/persistence/sqlite.py
+++ /dev/null
@@ -1,274 +0,0 @@
-import asyncio
-import os
-from collections.abc import AsyncGenerator
-from contextlib import asynccontextmanager
-from uuid import UUID
-
-from aiosqlite import Connection, connect as sqlite_connect
-from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor
-from pydantic import ValidationError
-
-from app.helpers.config_models.database import SqliteModel
-from app.helpers.features import callback_timeout_hour
-from app.helpers.logging import logger
-from app.models.call import CallStateModel
-from app.models.readiness import ReadinessEnum
-from app.persistence.icache import ICache
-from app.persistence.istore import IStore
-
-# Instrument sqlite
-SQLite3Instrumentor().instrument()
-
-
-class SqliteStore(IStore):
- _config: SqliteModel
- _db_path: str
- _first_run_done: bool
-
- def __init__(self, cache: ICache, config: SqliteModel):
- super().__init__(cache)
- logger.info(
- "Using SQLite database at %s with table %s", config.path, config.table
- )
- self._config = config
-
- # Create folder if does not exist
- self._db_path = self._config.full_path()
-
- # Check if first run
- self._first_run_done = False
- if not os.path.isfile(self._db_path):
- db_folder = self._db_path[: self._db_path.rfind("/")]
- os.makedirs(name=db_folder, exist_ok=True)
- self._first_run_done = True
-
- async def areadiness(self) -> ReadinessEnum:
- """
- 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 ReadinessEnum.OK
- except Exception:
- logger.exception("Unknown error while checking SQLite readiness")
- return ReadinessEnum.FAIL
-
- async def call_aget(self, call_id: UUID) -> CallStateModel | None:
- logger.debug("Loading call %s", 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:
- logger.debug("Parsing error", exc_info=True)
-
- # Try live
- call = None
- async with self._use_db() as db:
- cursor = await db.execute(
- f"SELECT data FROM {self._config.table} WHERE id = ?",
- (str(call_id),),
- )
- row = await cursor.fetchone()
- if row:
- try:
- call = CallStateModel.model_validate_json(row[0])
- except ValidationError:
- logger.debug("Parsing error", exc_info=True)
-
- # Update cache
- if call:
- await self._cache.aset(
- key=cache_key,
- ttl_sec=60 * 60 * 24, # 1 day
- value=call.model_dump_json(),
- )
-
- return call
-
- # TODO: Catch exceptions and return False if something goes wrong
- async def call_aset(self, call: CallStateModel) -> bool:
- logger.debug("Saving call %s", call.call_id)
-
- # Update live
- data = call.model_dump_json(exclude_none=True)
- async with self._use_db() as db:
- await db.execute(
- f"INSERT OR REPLACE INTO {self._config.table} VALUES (?, ?)",
- (
- str(call.call_id), # id
- data, # data
- ),
- )
- await db.commit()
-
- # Update cache
- cache_key_id = self._cache_key_call_id(call.call_id)
- await self._cache.aset(
- key=cache_key_id,
- ttl_sec=60 * 60 * 24, # 1 day
- value=data,
- ) # Update for ID
- cache_key_phone_number = self._cache_key_phone_number(
- call.initiate.phone_number
- )
- await self._cache.adel(
- cache_key_phone_number
- ) # Invalidate for phone number because we don't know if it's the same call
-
- return True
-
- async def call_asearch_one(self, phone_number: str) -> CallStateModel | None:
- logger.debug("Loading last call for %s", 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:
- logger.debug("Parsing error", exc_info=True)
-
- # Try live
- call = None
- async with self._use_db() as db:
- cursor = await db.execute(
- f"SELECT data FROM {self._config.table} WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?) AND DATETIME(JSON_EXTRACT(data, '$.created_at')) >= DATETIME('now', '-{await callback_timeout_hour()} hours') ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT 1",
- (
- phone_number, # data.initiate.phone_number
- phone_number, # data.claim.policyholder_phone
- ),
- )
- row = await cursor.fetchone()
- if row:
- try:
- call = CallStateModel.model_validate_json(row[0])
- except ValidationError:
- logger.debug("Parsing error", exc_info=True)
-
- # Update cache
- if call:
- await self._cache.aset(
- key=cache_key,
- ttl_sec=60 * 60 * 24, # 1 day
- value=call.model_dump_json(),
- )
-
- return call
-
- async def call_asearch_all(
- self,
- count: int,
- phone_number: str | None = None,
- ) -> tuple[list[CallStateModel] | None, int]:
- logger.debug("Searching calls, for %s and count %s", phone_number, count)
- # TODO: Cache results
- calls, total = await asyncio.gather(
- self._call_asearch_all_calls_worker(count, phone_number),
- self._call_asearch_all_total_worker(phone_number),
- )
- return calls, total
-
- async def _call_asearch_all_calls_worker(
- self,
- count: int,
- phone_number: str | None = None,
- ) -> list[CallStateModel] | None:
- calls: list[CallStateModel] = []
- async with self._use_db() as db:
- where_clause = (
- "WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)"
- if phone_number
- else ""
- )
- cursor = await db.execute(
- f"SELECT data FROM {self._config.table} {where_clause} ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT ?",
- (
- (
- phone_number, # data.initiate.phone_number
- phone_number, # data.claim.policyholder_phone
- count, # limit
- )
- if phone_number
- else (count,) # limit
- ),
- )
- rows = await cursor.fetchall()
- for row in rows:
- if not row:
- continue
- try:
- calls.append(CallStateModel.model_validate_json(row[0]))
- except ValidationError:
- logger.debug("Parsing error", exc_info=True)
- return calls
-
- async def _call_asearch_all_total_worker(
- self,
- phone_number: str | None = None,
- ) -> int:
- async with self._use_db() as db:
- where_clause = (
- "WHERE (JSON_EXTRACT(data, '$.initiate.phone_number') LIKE ? OR JSON_EXTRACT(data, '$.claim.policyholder_phone') LIKE ?)"
- if phone_number
- else ""
- )
- cursor = await db.execute(
- f"SELECT COUNT(*) FROM {self._config.table} {where_clause}",
- (
- (
- phone_number, # data.initiate.phone_number
- phone_number, # data.claim.policyholder_phone
- )
- if phone_number
- else ()
- ),
- )
- row = await cursor.fetchone()
- return int(row[0]) if row else 0
-
- async def _init_db(self, db: Connection):
- """
- Initialize the database.
-
- See: https://sqlite.org/cgi/src/doc/wal2/doc/wal2.md
- """
- logger.info("First run, init database")
- # Optimize performance for concurrent writes
- await db.execute("PRAGMA journal_mode=WAL")
- # Create table
- await db.execute(
- f"CREATE TABLE IF NOT EXISTS {self._config.table} (id VARCHAR(36) PRIMARY KEY, data TEXT)"
- )
- # Create indexes
- await db.execute(
- f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_initiate_phone_number ON {self._config.table} (JSON_EXTRACT(data, '$.initiate.phone_number'))"
- )
- await db.execute(
- f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_created_at ON {self._config.table} (DATETIME(JSON_EXTRACT(data, '$.created_at')))"
- )
- await db.execute(
- f"CREATE INDEX IF NOT EXISTS {self._config.table}_data_claim_policyholder_phone ON {self._config.table} (JSON_EXTRACT(data, '$.claim.policyholder_phone'))"
- )
-
- # Write changes to disk
- await db.commit()
-
- @asynccontextmanager
- async def _use_db(self) -> AsyncGenerator[Connection, None]:
- """
- Generate the SQLite client and close it after use.
- """
- async with sqlite_connect(
- database=self._db_path,
- ) as client:
- if self._first_run_done:
- await self._init_db(client)
- yield client
diff --git a/app/persistence/twilio.py b/app/persistence/twilio.py
index 13d8817..e52feb8 100644
--- a/app/persistence/twilio.py
+++ b/app/persistence/twilio.py
@@ -17,7 +17,7 @@ class TwilioSms(ISms):
logger.info("Using Twilio from number %s", config.phone_number)
self._config = config
- async def areadiness(self) -> ReadinessEnum:
+ async def readiness(self) -> ReadinessEnum:
"""
Check the readiness of the Twilio SMS service.
@@ -36,7 +36,7 @@ class TwilioSms(ISms):
logger.exception("Unknown error while checking Twilio readiness")
return ReadinessEnum.FAIL
- async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
+ async def send(self, content: str, phone_number: PhoneNumber) -> bool:
logger.info("Sending SMS to %s", phone_number)
success = False
logger.info("SMS content: %s", content)
@@ -59,7 +59,7 @@ class TwilioSms(ISms):
logger.debug("SMS sent to %s", phone_number)
success = True
except TwilioRestException:
- logger.error("Error sending SMS to %s", phone_number, exc_info=True)
+ logger.exception("Error sending SMS to %s", phone_number)
return success
async def _use_client(self) -> Client:
diff --git a/cicd/bicep/app.bicep b/cicd/bicep/app.bicep
index f7b666f..0d11904 100644
--- a/cicd/bicep/app.bicep
+++ b/cicd/bicep/app.bicep
@@ -33,7 +33,6 @@ var phonenumberSanitized = replace(localConfig.communication_services.phone_numb
var config = {
public_domain: appUrl
database: {
- mode: 'cosmos_db'
cosmos_db: {
container: container.name
database: database.name
@@ -902,7 +901,7 @@ resource configValues 'Microsoft.AppConfiguration/configurationStores/keyValues@
answer_hard_timeout_sec: 180
answer_soft_timeout_sec: 30
callback_timeout_hour: 3
- phone_silence_timeout_sec: 10
+ phone_silence_timeout_sec: 20
recognition_retry_max: 2
recording_enabled: false
slow_llm_for_chat: false
diff --git a/pyproject.toml b/pyproject.toml
index 199f01c..bd1d2a5 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -9,7 +9,6 @@ dependencies = [
"aiohttp-retry~=2.9", # Retry middleware for aiohttp, used with Twilio SDK
"aiohttp[speedups]~=3.10", # Async HTTP client for Azure and Twilio SDKs, plus async DNS resolver and async Brotli compression
"aiojobs~=1.3", # Async job scheduler
- "aiosqlite~=0.20", # Async SQLite3 driver
"azure-ai-translation-text~=1.0", # Azure Cognitive Services Text Translation
"azure-appconfiguration~=1.7", # Outsourced configuration for live updates
"azure-cognitiveservices-speech~=1.41", # Azure AI Speech
@@ -32,7 +31,6 @@ dependencies = [
"opentelemetry-instrumentation-httpx~=0.0a0", # OpenTelemetry instrumentation for HTTPX
"opentelemetry-instrumentation-openai~=0.0a0", # OpenTelemetry instrumentation for OpenAI
"opentelemetry-instrumentation-redis~=0.0a0", # OpenTelemetry instrumentation for Redis
- "opentelemetry-instrumentation-sqlite3~=0.0a0", # OpenTelemetry instrumentation for SQLite3
"opentelemetry-semantic-conventions~=0.0a0", # OpenTelemetry conventions, to standardize telemetry data
"phonenumbers~=8.13", # Phone number parsing and formatting, used with Pydantic
"pydantic-extra-types~=2.9", # Extra types for Pydantic
diff --git a/tests/cache.py b/tests/cache.py
index a1acc68..41e82ec 100644
--- a/tests/cache.py
+++ b/tests/cache.py
@@ -41,14 +41,14 @@ async def test_acid(random_text: str, cache_mode: CacheModeEnum) -> None:
test_value = "lorem ipsum"
# Check not exists
- assume(not await cache.aget(test_key))
+ assume(not await cache.get(test_key))
# Insert test call
- await cache.aset(
+ await cache.set(
key=test_key,
ttl_sec=60,
value=test_value,
)
# Check point read
- assume(await cache.aget(test_key) == test_value.encode())
+ assume(await cache.get(test_key) == test_value.encode())
diff --git a/tests/llm.py b/tests/llm.py
index 337bcf0..544cf1f 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -24,6 +24,7 @@ from app.helpers.call_events import (
on_end_call,
on_ivr_recognized,
on_play_completed,
+ on_play_started,
)
from app.helpers.call_llm import _out_answer
from app.helpers.logging import logger
@@ -305,6 +306,10 @@ async def test_llm( # noqa: PLR0913
scheduler=scheduler,
training_callback=_training_callback,
)
+ # Play
+ await on_play_started(
+ call=call,
+ )
# Receip
await on_play_completed(
call=call,
diff --git a/tests/store.py b/tests/store.py
index c76f04d..9714d8d 100644
--- a/tests/store.py
+++ b/tests/store.py
@@ -2,26 +2,12 @@ import pytest
from pytest_assume.plugin import assume
from app.helpers.config import CONFIG
-from app.helpers.config_models.database import ModeEnum as DatabaseModeEnum
from app.models.call import CallStateModel
- "database_mode",
- [
- pytest.param(
- DatabaseModeEnum.SQLITE,
- id="sqlite",
- ),
- pytest.param(
- DatabaseModeEnum.COSMOS_DB,
- id="cosmos_db",
- ),
- ],
-)
@pytest.mark.asyncio(scope="session")
@pytest.mark.repeat(10) # Catch multi-threading and concurrency issues
-async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> None:
+async def test_acid(call: CallStateModel) -> None:
"""
Test ACID properties of the database backend.
@@ -33,18 +19,16 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> No
Test is repeated 10 times to catch multi-threading and concurrency issues.
"""
- # Set database mode
- CONFIG.database.mode = database_mode
db = CONFIG.database.instance()
# Check not exists
- assume(not await db.call_aget(call.call_id))
- assume(await db.call_asearch_one(call.initiate.phone_number) != call)
+ 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_asearch_all(
+ await db.call_search_all(
phone_number=call.initiate.phone_number, count=1
)
)[0]
@@ -53,18 +37,18 @@ async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> No
)
# Insert test call
- await db.call_aset(call)
+ await db.call_create(call)
# Check point read
- assume(await db.call_aget(call.call_id) == call)
+ assume(await db.call_get(call.call_id) == call)
# Check search one
- assume(await db.call_asearch_one(call.initiate.phone_number) == call)
+ assume(await db.call_search_one(call.initiate.phone_number) == call)
# Check search all
assume(
call
in (
(
- await db.call_asearch_all(
+ await db.call_search_all(
phone_number=call.initiate.phone_number, count=1
)
)[0]
diff --git a/uv.lock b/uv.lock
index e1e0c4c..f26868e 100644
--- a/uv.lock
+++ b/uv.lock
@@ -113,18 +113,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/76/ac/a7305707cb852b7e16ff80eaf5692309bde30e2b1100a1fcacdc8f731d97/aiosignal-1.3.1-py3-none-any.whl", hash = "sha256:f8376fb07dd1e86a584e4fcdec80b36b7f81aac666ebc724e2c090300dd83b17", size = 7617 },
]
-[[package]]
-name = "aiosqlite"
-version = "0.20.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "typing-extensions" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/0d/3a/22ff5415bf4d296c1e92b07fd746ad42c96781f13295a074d58e77747848/aiosqlite-0.20.0.tar.gz", hash = "sha256:6d35c8c256637f4672f843c31021464090805bf925385ac39473fb16eaaca3d7", size = 21691 }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/00/c4/c93eb22025a2de6b83263dfe3d7df2e19138e345bca6f18dba7394120930/aiosqlite-0.20.0-py3-none-any.whl", hash = "sha256:36a1deaca0cac40ebe32aac9977a6e2bbc7f5189f23f4a54d5908986729e5bd6", size = 15564 },
-]
-
[[package]]
name = "annotated-types"
version = "0.7.0"
@@ -466,7 +454,6 @@ dependencies = [
{ name = "aiohttp", extra = ["speedups"] },
{ name = "aiohttp-retry" },
{ name = "aiojobs" },
- { name = "aiosqlite" },
{ name = "azure-ai-translation-text" },
{ name = "azure-appconfiguration" },
{ name = "azure-cognitiveservices-speech" },
@@ -489,7 +476,6 @@ dependencies = [
{ name = "opentelemetry-instrumentation-httpx" },
{ name = "opentelemetry-instrumentation-openai" },
{ name = "opentelemetry-instrumentation-redis" },
- { name = "opentelemetry-instrumentation-sqlite3" },
{ name = "opentelemetry-semantic-conventions" },
{ name = "phonenumbers" },
{ name = "pydantic", extra = ["email"] },
@@ -529,7 +515,6 @@ requires-dist = [
{ name = "aiohttp", extras = ["speedups"], specifier = "~=3.10" },
{ name = "aiohttp-retry", specifier = "~=2.9" },
{ name = "aiojobs", specifier = "~=1.3" },
- { name = "aiosqlite", specifier = "~=0.20" },
{ name = "azure-ai-translation-text", specifier = "~=1.0" },
{ name = "azure-appconfiguration", specifier = "~=1.7" },
{ name = "azure-cognitiveservices-speech", specifier = "~=1.41" },
@@ -554,7 +539,6 @@ requires-dist = [
{ name = "opentelemetry-instrumentation-httpx", specifier = "~=0.0a0" },
{ name = "opentelemetry-instrumentation-openai", specifier = "~=0.0a0" },
{ name = "opentelemetry-instrumentation-redis", specifier = "~=0.0a0" },
- { name = "opentelemetry-instrumentation-sqlite3", specifier = "~=0.0a0" },
{ name = "opentelemetry-semantic-conventions", specifier = "~=0.0a0" },
{ name = "phonenumbers", specifier = "~=8.13" },
{ name = "pydantic", extras = ["email"], specifier = "~=2.9" },
@@ -1872,20 +1856,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/43/df/0df9226d1b14f29d23c07e6194b9fd5ad50e7d987b7fd13df7dcf718aeb1/opentelemetry_instrumentation_requests-0.48b0-py3-none-any.whl", hash = "sha256:d4f01852121d0bd4c22f14f429654a735611d4f7bf3cf93f244bdf1489b2233d", size = 12366 },
]
-[[package]]
-name = "opentelemetry-instrumentation-sqlite3"
-version = "0.48b0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "opentelemetry-api" },
- { name = "opentelemetry-instrumentation" },
- { name = "opentelemetry-instrumentation-dbapi" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/36/fa/ef80b55f8b2a5814fc4a868159f2b5b3c8316d20d449ba2f9f314faed9f1/opentelemetry_instrumentation_sqlite3-0.48b0.tar.gz", hash = "sha256:483b973a197890d69a25d17956d6fa66c540fc0f9f73190c93c98d2dabb3188b", size = 7530 }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/9c/04/6d1b1789e1c1da35d839a0075a7cfb1ca14de4f06e75a390f8ce4402e101/opentelemetry_instrumentation_sqlite3-0.48b0-py3-none-any.whl", hash = "sha256:558ff8e7b78d0647cdffb1496c5e92f72d1f459e9ae9c6d3ae9eab3517d481e5", size = 8716 },
-]
-
[[package]]
name = "opentelemetry-instrumentation-urllib"
version = "0.48b0"
@@ -2532,7 +2502,7 @@ wheels = [
[[package]]
name = "ragas"
-version = "0.2.6"
+version = "0.2.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "appdirs" },