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

feat: Externalize feature flags to App Configuration

Clémence Lesné90d9ba9a5d3a
diff --git a/README.md b/README.md
index 0b4b4d0..aa861cd 100644
--- a/README.md
+++ b/README.md
@@ -69,6 +69,7 @@ curl \
- [x] Jailbreak detection
- [x] Lower AI Search cost by usign a Redis cache
- [x] Monitoring and tracing with Application Insights
+- [x] Perform user tests with feature flags
- [x] Receive SMS during a conversation for explicit wordings
- [x] Record the calls for audit and quality assurance
- [x] Responses are streamed from the LLM to the user, to avoid long pauses
@@ -299,7 +300,6 @@ conversation:
communication_services:
# Phone number purshased from Communication Services
phone_number: "+33612345678"
- recording_enabled: false
sms: {}
@@ -368,7 +368,7 @@ communication_services:
endpoint: https://xxx.france.communication.azure.com
phone_number: "+33612345678"
post_queue_name: post-33612345678
- recording_enabled: false
+ recording_container_url: https://xxx.blob.core.windows.net/recordings
resource_id: xxx
sms_queue_name: sms-33612345678
@@ -465,16 +465,7 @@ make dev
Call recording is disabled by default. To enable it:
1. Create a new container in the Azure Storage account (i.e. `recordings`), it is already done if you deployed the solution on Azure
-2. Update the configuration
-
-Configuration is the following:
-
-```yaml
-# config.yaml
-communication_services:
- recording_container_url: https://xxx.blob.core.windows.net/recordings # Only needed for local deployment
- recording_enabled: true
-```
+2. Update the feature flag `recording_enabled` in App Configuration to `true`
### Add my custom training data with AI Search
@@ -594,18 +585,17 @@ Task can be customized for each call, by adding the `task` field in the `POST /c
### Customize the conversation
-Conversation options are documented in [conversation.py](helpers/config_models/conversation.py). The options can all be overridden in `config.yaml` file:
-
-```yaml
-# config.yaml
-conversation:
- answer_hard_timeout_sec: 180
- answer_soft_timeout_sec: 30
- callback_timeout_hour: 72
- phone_silence_timeout_sec: 1
- slow_llm_for_chat: true
- voice_recognition_retry_max: 2
-```
+Conversation options are represented as features. They can be configured from App Configuration, without the need to redeploy or restart the application. Once a feature is updated, a delay of 60 seconds is needed to make the change effective.
+
+| Name | Description | Type | Default |
+|-|-|-|
+| `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` | 72 |
+| `phone_silence_timeout_sec` | The timeout for phone silence in seconds. | `int` | 1 |
+| `recording_enabled` | Whether call recording is enabled. | `bool` | false |
+| `slow_llm_for_chat` | Whether to use the slower LLM for chat. | `bool` | true |
+| `voice_recognition_retry_max` | The maximum number of retries for voice recognition. | `int` | 2 |
### Use an OpenAI compatible model for the LLM
diff --git a/bicep/app.bicep b/bicep/app.bicep
index 647f235..87e1e32 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -60,7 +60,6 @@ var config = {
phone_number: localConfig.communication_services.phone_number
post_queue_name: postQueue.name
recording_container_url: '${storageAccount.properties.primaryEndpoints.blob}${recordingsBlob.name}'
- recording_enabled: localConfig.communication_services.recording_enabled
resource_id: communicationServices.properties.immutableResourceId
sms_queue_name: smsQueue.name
trainings_queue_name: trainingsQueue.name
@@ -114,6 +113,9 @@ var config = {
port: redis.properties.sslPort
}
}
+ app_configuration: {
+ connection_string: configStore.listKeys().value[0].connectionString
+ }
}
output appUrl string = appUrl
@@ -732,3 +734,29 @@ resource redis 'Microsoft.Cache/redis@2024-03-01' = {
redisVersion: '6' // v6.x
}
}
+
+resource configStore 'Microsoft.AppConfiguration/configurationStores@2023-03-01' = {
+ name: prefix
+ location: location
+ sku: {
+ name: 'Standard'
+ }
+}
+
+resource configValues 'Microsoft.AppConfiguration/configurationStores/keyValues@2023-03-01' = [
+ for item in items({
+ answer_hard_timeout_sec: 180
+ answer_soft_timeout_sec: 30
+ callback_timeout_hour: 72
+ phone_silence_timeout_sec: 1
+ recording_enabled: false
+ slow_llm_for_chat: true
+ voice_recognition_retry_max: 2
+ }): {
+ parent: configStore
+ name: item.key
+ properties: {
+ value: string(item.value)
+ }
+ }
+]
diff --git a/helpers/call_events.py b/helpers/call_events.py
index a7ac124..f516a46 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -24,6 +24,7 @@ from helpers.call_utils import (
handle_transfer,
)
from helpers.config import CONFIG
+from helpers.features import recording_enabled, voice_recognition_retry_max
from helpers.llm_worker import completion_sync
from helpers.logging import logger
from helpers.monitoring import CallAttributes, span_attribute, tracer
@@ -173,12 +174,12 @@ async def on_recognize_timeout_error(
contexts and CallContextEnum.IVR_LANG_SELECT in contexts
): # Retry IVR recognition
span_attribute(CallAttributes.CALL_CHANNEL, "ivr")
- if call.recognition_retry < CONFIG.conversation.voice_recognition_retry_max:
+ if call.recognition_retry < await voice_recognition_retry_max():
call.recognition_retry += 1
logger.info(
"Timeout, retrying language selection (%s/%s)",
call.recognition_retry,
- CONFIG.conversation.voice_recognition_retry_max,
+ await voice_recognition_retry_max(),
)
await _handle_ivr_language(call=call, client=client)
else: # IVR retries are exhausted, end call
@@ -190,7 +191,7 @@ async def on_recognize_timeout_error(
return
if (
- call.recognition_retry >= CONFIG.conversation.voice_recognition_retry_max
+ call.recognition_retry >= await voice_recognition_retry_max()
): # Voice retries are exhausted, end call
logger.info("Timeout, ending call")
await _handle_goodbye(
@@ -205,7 +206,7 @@ async def on_recognize_timeout_error(
logger.info(
"Timeout, retrying voice recognition (%s/%s)",
call.recognition_retry,
- CONFIG.conversation.voice_recognition_retry_max,
+ await voice_recognition_retry_max(),
)
# Never store the warning message in the call history, it has caused hallucinations in the LLM
await handle_recognize_text(
@@ -614,7 +615,7 @@ async def _handle_recording(
client: CallAutomationClient,
server_call_id: str,
) -> None:
- if not CONFIG.communication_services.recording_enabled:
+ if not await recording_enabled():
return
assert CONFIG.communication_services.recording_container_url
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 875da25..4efd01b 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -12,6 +12,7 @@ from helpers.call_utils import (
tts_sentence_split,
)
from helpers.config import CONFIG
+from helpers.features import answer_hard_timeout_sec, answer_soft_timeout_sec
from helpers.llm_tools import LlmPlugins
from helpers.llm_worker import (
MaximumTokensReachedError,
@@ -77,7 +78,11 @@ async def load_llm_chat( # noqa: PLR0912, PLR0915
# Pointer
pointer_cache_key = f"{__name__}-load_llm_chat-pointer-{call.call_id}"
pointer_current = time.time() # Get system current time
- await _cache.aset(pointer_cache_key, str(pointer_current))
+ await _cache.aset(
+ key=pointer_cache_key,
+ ttl_sec=await answer_hard_timeout_sec(),
+ value=str(pointer_current),
+ )
# Chat
chat_task = asyncio.create_task(
@@ -100,10 +105,10 @@ async def load_llm_chat( # noqa: PLR0912, PLR0915
# Timeouts
soft_timeout_triggered = False
soft_timeout_task = asyncio.create_task(
- asyncio.sleep(CONFIG.conversation.answer_soft_timeout_sec)
+ asyncio.sleep(await answer_soft_timeout_sec())
)
hard_timeout_task = asyncio.create_task(
- asyncio.sleep(CONFIG.conversation.answer_hard_timeout_sec)
+ asyncio.sleep(await answer_hard_timeout_sec())
)
await handle_media(
@@ -150,7 +155,7 @@ async def load_llm_chat( # noqa: PLR0912, PLR0915
if hard_timeout_task.done(): # Break when hard timeout is reached
logger.warning(
"Hard timeout of %ss reached",
- CONFIG.conversation.answer_hard_timeout_sec,
+ await answer_hard_timeout_sec(),
)
# Clean up
_clear_tasks()
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index 0ec4bbe..d1e5c49 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -18,6 +18,7 @@ from azure.communication.callautomation.aio import (
from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
from helpers.config import CONFIG
+from helpers.features import phone_silence_timeout_sec
from helpers.logging import logger
from models.call import CallStateModel
from models.message import (
@@ -100,7 +101,7 @@ async def _handle_recognize_media(
assert call.voice_id, "Voice ID is required for recognizing media"
async with _use_call_client(client, call.voice_id) as call_client:
await call_client.start_recognizing_media(
- end_silence_timeout=CONFIG.conversation.phone_silence_timeout_sec,
+ end_silence_timeout=await phone_silence_timeout_sec(),
input_type=RecognizeInputType.SPEECH,
interrupt_prompt=True,
operation_context=_context_builder({context}),
diff --git a/helpers/config_models/app_configuration.py b/helpers/config_models/app_configuration.py
new file mode 100644
index 0000000..75b9ae3
--- /dev/null
+++ b/helpers/config_models/app_configuration.py
@@ -0,0 +1,6 @@
+from pydantic import BaseModel, SecretStr
+
+
+class AppConfigurationModel(BaseModel):
+ connection_string: SecretStr
+ ttl_sec: int = 60 # 1 min
diff --git a/helpers/config_models/communication_services.py b/helpers/config_models/communication_services.py
index ee0b0b2..dab4579 100644
--- a/helpers/config_models/communication_services.py
+++ b/helpers/config_models/communication_services.py
@@ -1,4 +1,4 @@
-from pydantic import BaseModel, SecretStr, ValidationInfo, field_validator
+from pydantic import BaseModel, SecretStr
from helpers.pydantic_types.phone_numbers import PhoneNumber
@@ -9,19 +9,7 @@ class CommunicationServicesModel(BaseModel):
endpoint: str
phone_number: PhoneNumber
post_queue_name: str
- recording_container_url: str | None = None
- recording_enabled: bool
+ recording_container_url: str
resource_id: str
sms_queue_name: str
trainings_queue_name: str
-
- @field_validator("recording_container_url")
- @classmethod
- def _validate_recording_container_url(
- cls,
- recording_container_url: str | None,
- info: ValidationInfo,
- ) -> str | None:
- if not recording_container_url and info.data.get("recording_enabled", False):
- raise ValueError("Recording container URL required")
- return recording_container_url
diff --git a/helpers/config_models/conversation.py b/helpers/config_models/conversation.py
index 9de704c..6dbc2b7 100644
--- a/helpers/config_models/conversation.py
+++ b/helpers/config_models/conversation.py
@@ -155,31 +155,8 @@ class WorkflowInitiateModel(BaseModel):
class ConversationModel(BaseModel):
+ # TODO: This could be simplified by removing the parent class but would cause a breaking change
initiate: WorkflowInitiateModel
- answer_hard_timeout_sec: int = Field(
- default=180, # 3 mins
- serialization_alias="intelligence_hard_timeout_sec", # Compatibility with v7
- )
- answer_soft_timeout_sec: int = Field(
- default=30, # 30 secs
- serialization_alias="intelligence_soft_timeout_sec", # Compatibility with v7
- )
- callback_timeout_hour: int = Field(
- default=72, # 3 days
- serialization_alias="conversation_timeout_hour", # Compatibility with v7
- )
- phone_silence_timeout_sec: int = Field(
- default=1, # 1 second
- serialization_alias="voice_timeout_after_silence_sec", # Compatibility with v7
- )
- slow_llm_for_chat: bool = Field(
- default=False,
- serialization_alias="use_slow_llm_for_chat_as_default", # Compatibility with v7
- )
- voice_recognition_retry_max: int = Field(
- default=2, # 2 retries
- serialization_alias="max_voice_recognition_retry", # Compatibility with v7
- )
def _fields_to_pydantic(name: str, fields: list[ClaimFieldModel]) -> type[BaseModel]:
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index d7f5934..9b4910c 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -542,14 +542,14 @@ class TtsModel(BaseModel):
return await self._translate(self.timeout_silence_tpl, call)
async def welcome_back(self, call: CallStateModel) -> str:
- from helpers.config import CONFIG
+ from helpers.features import callback_timeout_hour
return await self._translate(
self.welcome_back_tpl,
call,
bot_company=call.initiate.bot_company,
bot_name=call.initiate.bot_name,
- conversation_timeout_hour=CONFIG.conversation.callback_timeout_hour,
+ conversation_timeout_hour=await callback_timeout_hour(),
)
async def timeout_loading(self, call: CallStateModel) -> str:
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index 853ffa6..9be326a 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -7,6 +7,7 @@ from pydantic_settings import (
from helpers.config_models.ai_search import AiSearchModel
from helpers.config_models.ai_translation import AiTranslationModel
+from helpers.config_models.app_configuration import AppConfigurationModel
from helpers.config_models.cache import CacheModel
from helpers.config_models.cognitive_service import CognitiveServiceModel
from helpers.config_models.communication_services import CommunicationServicesModel
@@ -49,6 +50,7 @@ class RootModel(BaseSettings):
conversation: ConversationModel = Field(
serialization_alias="workflow"
) # Compatibility with v7
+ app_configuration: AppConfigurationModel
@classmethod
def settings_customise_sources(
diff --git a/helpers/features.py b/helpers/features.py
new file mode 100644
index 0000000..95b702b
--- /dev/null
+++ b/helpers/features.py
@@ -0,0 +1,92 @@
+from typing import TypeVar, cast
+
+from azure.appconfiguration.aio import AzureAppConfigurationClient
+
+from helpers.config import CONFIG
+from helpers.config_models.cache import MemoryModel
+from helpers.http import azure_transport
+from persistence.icache import ICache
+from persistence.memory import MemoryCache
+
+_cache: ICache = MemoryCache(MemoryModel(max_size=100))
+_client: AzureAppConfigurationClient | None = None
+T = TypeVar("T", bool, int, str)
+
+
+async def answer_hard_timeout_sec() -> int:
+ return await _get(key="answer_hard_timeout_sec", type=int) or 180
+
+
+async def answer_soft_timeout_sec() -> int:
+ return await _get(key="answer_soft_timeout_sec", type=int) or 120
+
+
+async def callback_timeout_hour() -> int:
+ return await _get(key="callback_timeout_hour", type=int) or 24
+
+
+async def phone_silence_timeout_sec() -> int:
+ return await _get(key="phone_silence_timeout_sec", type=int) or 10
+
+
+async def recording_enabled() -> bool:
+ return await _get(key="recording_enabled", type=bool) or False
+
+
+async def slow_llm_for_chat() -> bool:
+ return await _get(key="slow_llm_for_chat", type=bool) or True
+
+
+async def voice_recognition_retry_max() -> int:
+ return await _get(key="voice_recognition_retry_max", type=int) or 3
+
+
+async def _get(key: str, type: type[T]) -> T | None:
+ # Try cache
+ cache_key = _cache_key(key)
+ cached = await _cache.aget(cache_key)
+ if cached:
+ return _parse(value=cached.decode(), type=type)
+ # Try live
+ async with await _use_client() as client:
+ setting = await client.get_configuration_setting(key)
+ # Return default if not found
+ if not setting:
+ return
+ # Update cache
+ await _cache.aset(
+ key=cache_key,
+ ttl_sec=CONFIG.app_configuration.ttl_sec,
+ value=setting.value,
+ )
+ # Return
+ return _parse(value=setting.value, type=type)
+
+
+async def _use_client() -> AzureAppConfigurationClient:
+ """
+ Generate the App Configuration client and close it after use.
+ """
+ global _client # noqa: PLW0603
+ if not _client:
+ _client = AzureAppConfigurationClient.from_connection_string(
+ # Performance
+ transport=await azure_transport(),
+ # Authentication
+ connection_string=CONFIG.app_configuration.connection_string.get_secret_value(),
+ )
+ return _client
+
+
+def _cache_key(key: str) -> str:
+ return f"{__name__}-{key}"
+
+
+def _parse(value: str, type: type[T]) -> T:
+ if type is bool:
+ return cast(T, value.lower() == "true")
+ if type is int:
+ return cast(T, int(value))
+ if type is str:
+ return cast(T, str(value))
+ raise ValueError(f"Unsupported type: {type}")
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 21790bf..5b8269f 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -43,6 +43,7 @@ from tenacity import (
from helpers.config import CONFIG
from helpers.config_models.llm import AbstractPlatformModel as LlmAbstractPlatformModel
+from helpers.features import slow_llm_for_chat
from helpers.logging import logger
from helpers.monitoring import tracer
from helpers.resources import resources_dir
@@ -107,7 +108,7 @@ async def completion_stream(
async for attempt in retryed:
with attempt:
async for chunck in _completion_stream_worker(
- is_fast=not CONFIG.conversation.slow_llm_for_chat, # Let configuration decide
+ is_fast=not await slow_llm_for_chat(), # Let configuration decide
max_tokens=max_tokens,
messages=messages,
system=system,
@@ -127,7 +128,7 @@ async def completion_stream(
async for attempt in retryed:
with attempt:
async for chunck in _completion_stream_worker(
- is_fast=CONFIG.conversation.slow_llm_for_chat, # Let configuration decide
+ is_fast=await slow_llm_for_chat(), # Let configuration decide
max_tokens=max_tokens,
messages=messages,
system=system,
diff --git a/helpers/translation.py b/helpers/translation.py
index 38be7d8..10b11d8 100644
--- a/helpers/translation.py
+++ b/helpers/translation.py
@@ -42,16 +42,20 @@ async def translate_text(text: str, source_lang: str, target_lang: str) -> str |
# Try live
translation: str | None = None
- client = await _use_client()
- res: list[TranslatedTextItem] = await client.translate(
- body=[text],
- from_language=source_lang,
- to_language=[target_lang],
- )
+ async with await _use_client() as client:
+ res: list[TranslatedTextItem] = await client.translate(
+ body=[text],
+ from_language=source_lang,
+ to_language=[target_lang],
+ )
translation = res[0].translations[0].text if res and res[0].translations else None
# Update cache
- await _cache.aset(cache_key, translation)
+ await _cache.aset(
+ key=cache_key,
+ ttl_sec=60 * 60 * 24, # 1 day
+ value=translation,
+ )
return translation
diff --git a/persistence/ai_search.py b/persistence/ai_search.py
index dcbb228..f4f7bfa 100644
--- a/persistence/ai_search.py
+++ b/persistence/ai_search.py
@@ -148,7 +148,9 @@ class AiSearchSearch(ISearch):
# Update cache
if trainings:
await self._cache.aset(
- cache_key, TypeAdapter(list[TrainingModel]).dump_json(trainings)
+ key=cache_key,
+ ttl_sec=60 * 60 * 24, # 1 day
+ value=TypeAdapter(list[TrainingModel]).dump_json(trainings),
)
return trainings or None
diff --git a/persistence/communication_services.py b/persistence/communication_services.py
index 532b5ca..37f6b9f 100644
--- a/persistence/communication_services.py
+++ b/persistence/communication_services.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from azure.communication.sms import SmsSendResult
from azure.communication.sms.aio import SmsClient
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index 104f05c..e0b8484 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -9,8 +9,8 @@ from azure.cosmos.aio import ContainerProxy, CosmosClient
from azure.cosmos.exceptions import CosmosHttpResponseError
from pydantic import ValidationError
-from helpers.config import CONFIG
from helpers.config_models.database import CosmosDbModel
+from helpers.features import callback_timeout_hour
from helpers.http import azure_transport
from helpers.logging import logger
from models.call import CallStateModel
@@ -117,7 +117,11 @@ class CosmosDbStore(IStore):
# Update cache
if call:
- await self._cache.aset(cache_key, call.model_dump_json())
+ await self._cache.aset(
+ key=cache_key,
+ ttl_sec=await callback_timeout_hour(),
+ value=call.model_dump_json(),
+ )
return call
@@ -140,7 +144,9 @@ class CosmosDbStore(IStore):
if res:
cache_key_id = self._cache_key_call_id(call.call_id)
await self._cache.aset(
- cache_key_id, call.model_dump_json()
+ 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
@@ -169,7 +175,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', -{CONFIG.conversation.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()}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",
parameters=[
{
"name": "@phone_number",
@@ -189,7 +195,11 @@ class CosmosDbStore(IStore):
# Update cache
if call:
- await self._cache.aset(cache_key, call.model_dump_json())
+ await self._cache.aset(
+ key=cache_key,
+ ttl_sec=await callback_timeout_hour(),
+ value=call.model_dump_json(),
+ )
return call
diff --git a/persistence/icache.py b/persistence/icache.py
index 880fc72..af28473 100644
--- a/persistence/icache.py
+++ b/persistence/icache.py
@@ -18,7 +18,7 @@ class ICache(ABC):
@abstractmethod
@tracer.start_as_current_span("cache_aset")
- async def aset(self, key: str, value: str | bytes | None) -> bool:
+ async def aset(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
pass
@abstractmethod
diff --git a/persistence/memory.py b/persistence/memory.py
index 1a9bf12..19d32c4 100644
--- a/persistence/memory.py
+++ b/persistence/memory.py
@@ -1,6 +1,6 @@
import hashlib
from collections import OrderedDict
-from typing import Optional, Union
+from datetime import UTC, datetime, timedelta
from helpers.config_models.cache import MemoryModel
from helpers.logging import logger
@@ -19,6 +19,7 @@ class MemoryCache(ICache):
_cache: OrderedDict[str, bytes | None] = OrderedDict()
_config: MemoryModel
+ _ttl: dict[str, datetime] = {}
def __init__(self, config: MemoryModel):
logger.warning(
@@ -40,13 +41,18 @@ class MemoryCache(ICache):
If the key does not exist, return `None`.
"""
sha_key = self._key_to_hash(key)
+ # Check TTL
+ if sha_key in self._ttl:
+ if self._ttl[sha_key] < datetime.now(UTC):
+ return None
+ # Get from cache
res = self._cache.get(sha_key, None)
if not res:
return None
self._cache.move_to_end(sha_key, last=False) # Move to first
return res
- async def aset(self, key: str, value: str | bytes | None) -> bool:
+ async def aset(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
"""
Set a value in the cache.
"""
@@ -56,6 +62,8 @@ class MemoryCache(ICache):
# Add to first
self._cache[sha_key] = value.encode() if isinstance(value, str) else value
self._cache.move_to_end(sha_key, last=False)
+ # Set the TTL
+ self._ttl[sha_key] = datetime.now(UTC) + timedelta(seconds=ttl_sec)
return True
async def adel(self, key: str) -> bool:
@@ -63,8 +71,12 @@ class MemoryCache(ICache):
Delete a value from the cache.
"""
sha_key = self._key_to_hash(key)
+ # Delete from cache
if sha_key in self._cache:
self._cache.pop(sha_key)
+ # Delete from TTL
+ if sha_key in self._ttl:
+ self._ttl.pop(sha_key)
return True
@staticmethod
diff --git a/persistence/redis.py b/persistence/redis.py
index e300f66..62acf3b 100644
--- a/persistence/redis.py
+++ b/persistence/redis.py
@@ -1,4 +1,5 @@
import hashlib
+from datetime import timedelta
from uuid import uuid4
from opentelemetry.instrumentation.redis import RedisInstrumentor
@@ -87,7 +88,7 @@ class RedisCache(ICache):
logger.error("Error getting value", exc_info=True)
return res
- async def aset(self, key: str, value: str | bytes | None) -> bool:
+ async def aset(self, key: str, value: str | bytes | None, ttl_sec: int) -> bool:
"""
Set a value in the cache.
@@ -97,7 +98,11 @@ class RedisCache(ICache):
"""
sha_key = self._key_to_hash(key)
try:
- await self._client.set(sha_key, value if value else "")
+ await self._client.set(
+ ex=timedelta(seconds=ttl_sec),
+ name=sha_key,
+ value=value if value else "",
+ )
except RedisError:
logger.error("Error setting value", exc_info=True)
return False
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index 319d4de..be3f32d 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -8,8 +8,8 @@ from aiosqlite import Connection, connect as sqlite_connect
from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor
from pydantic import ValidationError
-from helpers.config import CONFIG
from helpers.config_models.database import SqliteModel
+from helpers.features import callback_timeout_hour
from helpers.logging import logger
from models.call import CallStateModel
from models.readiness import ReadinessEnum
@@ -84,7 +84,11 @@ class SqliteStore(IStore):
# Update cache
if call:
- await self._cache.aset(cache_key, call.model_dump_json())
+ await self._cache.aset(
+ key=cache_key,
+ ttl_sec=60 * 60 * 24, # 1 day
+ value=call.model_dump_json(),
+ )
return call
@@ -106,7 +110,11 @@ class SqliteStore(IStore):
# Update cache
cache_key_id = self._cache_key_call_id(call.call_id)
- await self._cache.aset(cache_key_id, data) # Update for 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
)
@@ -132,7 +140,7 @@ class SqliteStore(IStore):
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', '-{CONFIG.conversation.callback_timeout_hour} hours') ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT 1",
+ 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
@@ -147,7 +155,11 @@ class SqliteStore(IStore):
# Update cache
if call:
- await self._cache.aset(cache_key, call.model_dump_json())
+ await self._cache.aset(
+ key=cache_key,
+ ttl_sec=60 * 60 * 24, # 1 day
+ value=call.model_dump_json(),
+ )
return call
diff --git a/pyproject.toml b/pyproject.toml
index dff93b6..234b218 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,6 +10,7 @@ dependencies = [
"aiohttp[speedups]~=3.9", # Async HTTP client for Azure and Twilio SDKs, plus async DNS resolver and async Brotli compression
"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-communication-callautomation~=1.2", # Azure Communication Services Call Automation
"azure-communication-sms~=1.0", # Azure Communication Services SMS
"azure-cosmos~=4.7", # Azure Cosmos DB
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 9d8c18c..6707f5c 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -133,6 +133,10 @@ azure-ai-translation-text==1.0.0 \
--hash=sha256:268f1bc486e57ebf65b4f1368b9aa939be90064262ba5e3b821ce5000bf84eb3 \
--hash=sha256:46e25cd5ea87b7dfbc46ba31777af16fa985219cd0dea820b0bcc1e0f2b7a41e
# via call-center-ai (pyproject.toml)
+azure-appconfiguration==1.7.1 \
+ --hash=sha256:3ebe41e9be3f4ae6ca61e5dbc42c4b7cc007a01054a8506501a26dfc199fd3ec \
+ --hash=sha256:6e62b040a0210071be4423aafbdca3b053884c0d412855e3f8eff8e8d0b1a02b
+ # via call-center-ai (pyproject.toml)
azure-common==1.1.28 \
--hash=sha256:4ac0cd3214e36b6a1b6a442686722a5d8cc449603aa833f3f0f40bda836704a3 \
--hash=sha256:5c12d3dcf4ec20599ca6b0d3e09e86e146353d443e7fcc050c9a19c1f9df20ad
@@ -150,6 +154,7 @@ azure-core==1.30.2 \
--hash=sha256:cf019c1ca832e96274ae85abd3d9f752397194d9fea3b41487290562ac8abe4a
# via
# azure-ai-translation-text
+ # azure-appconfiguration
# azure-communication-callautomation
# azure-communication-sms
# azure-core-tracing-opentelemetry
@@ -652,6 +657,81 @@ googleapis-common-protos==1.63.2 \
--hash=sha256:27a2499c7e8aff199665b22741997e485eccc8645aa9176c7c988e6fae507945 \
--hash=sha256:27c5abdffc4911f28101e635de1533fb4cfd2c37fbaa9174587c799fac90aa87
# via opentelemetry-exporter-otlp-proto-grpc
+greenlet==3.1.1 \
+ --hash=sha256:0153404a4bb921f0ff1abeb5ce8a5131da56b953eda6e14b88dc6bbc04d2049e \
+ --hash=sha256:03a088b9de532cbfe2ba2034b2b85e82df37874681e8c470d6fb2f8c04d7e4b7 \
+ --hash=sha256:04b013dc07c96f83134b1e99888e7a79979f1a247e2a9f59697fa14b5862ed01 \
+ --hash=sha256:05175c27cb459dcfc05d026c4232f9de8913ed006d42713cb8a5137bd49375f1 \
+ --hash=sha256:09fc016b73c94e98e29af67ab7b9a879c307c6731a2c9da0db5a7d9b7edd1159 \
+ --hash=sha256:0bbae94a29c9e5c7e4a2b7f0aae5c17e8e90acbfd3bf6270eeba60c39fce3563 \
+ --hash=sha256:0fde093fb93f35ca72a556cf72c92ea3ebfda3d79fc35bb19fbe685853869a83 \
+ --hash=sha256:1443279c19fca463fc33e65ef2a935a5b09bb90f978beab37729e1c3c6c25fe9 \
+ --hash=sha256:1776fd7f989fc6b8d8c8cb8da1f6b82c5814957264d1f6cf818d475ec2bf6395 \
+ --hash=sha256:1d3755bcb2e02de341c55b4fca7a745a24a9e7212ac953f6b3a48d117d7257aa \
+ --hash=sha256:23f20bb60ae298d7d8656c6ec6db134bca379ecefadb0b19ce6f19d1f232a942 \
+ --hash=sha256:275f72decf9932639c1c6dd1013a1bc266438eb32710016a1c742df5da6e60a1 \
+ --hash=sha256:2846930c65b47d70b9d178e89c7e1a69c95c1f68ea5aa0a58646b7a96df12441 \
+ --hash=sha256:3319aa75e0e0639bc15ff54ca327e8dc7a6fe404003496e3c6925cd3142e0e22 \
+ --hash=sha256:346bed03fe47414091be4ad44786d1bd8bef0c3fcad6ed3dee074a032ab408a9 \
+ --hash=sha256:36b89d13c49216cadb828db8dfa6ce86bbbc476a82d3a6c397f0efae0525bdd0 \
+ --hash=sha256:37b9de5a96111fc15418819ab4c4432e4f3c2ede61e660b1e33971eba26ef9ba \
+ --hash=sha256:396979749bd95f018296af156201d6211240e7a23090f50a8d5d18c370084dc3 \
+ --hash=sha256:3b2813dc3de8c1ee3f924e4d4227999285fd335d1bcc0d2be6dc3f1f6a318ec1 \
+ --hash=sha256:411f015496fec93c1c8cd4e5238da364e1da7a124bcb293f085bf2860c32c6f6 \
+ --hash=sha256:47da355d8687fd65240c364c90a31569a133b7b60de111c255ef5b606f2ae291 \
+ --hash=sha256:48ca08c771c268a768087b408658e216133aecd835c0ded47ce955381105ba39 \
+ --hash=sha256:4afe7ea89de619adc868e087b4d2359282058479d7cfb94970adf4b55284574d \
+ --hash=sha256:4ce3ac6cdb6adf7946475d7ef31777c26d94bccc377e070a7986bd2d5c515467 \
+ --hash=sha256:4ead44c85f8ab905852d3de8d86f6f8baf77109f9da589cb4fa142bd3b57b475 \
+ --hash=sha256:54558ea205654b50c438029505def3834e80f0869a70fb15b871c29b4575ddef \
+ --hash=sha256:5e06afd14cbaf9e00899fae69b24a32f2196c19de08fcb9f4779dd4f004e5e7c \
+ --hash=sha256:62ee94988d6b4722ce0028644418d93a52429e977d742ca2ccbe1c4f4a792511 \
+ --hash=sha256:63e4844797b975b9af3a3fb8f7866ff08775f5426925e1e0bbcfe7932059a12c \
+ --hash=sha256:6510bf84a6b643dabba74d3049ead221257603a253d0a9873f55f6a59a65f822 \
+ --hash=sha256:667a9706c970cb552ede35aee17339a18e8f2a87a51fba2ed39ceeeb1004798a \
+ --hash=sha256:6ef9ea3f137e5711f0dbe5f9263e8c009b7069d8a1acea822bd5e9dae0ae49c8 \
+ --hash=sha256:7017b2be767b9d43cc31416aba48aab0d2309ee31b4dbf10a1d38fb7972bdf9d \
+ --hash=sha256:7124e16b4c55d417577c2077be379514321916d5790fa287c9ed6f23bd2ffd01 \
+ --hash=sha256:73aaad12ac0ff500f62cebed98d8789198ea0e6f233421059fa68a5aa7220145 \
+ --hash=sha256:77c386de38a60d1dfb8e55b8c1101d68c79dfdd25c7095d51fec2dd800892b80 \
+ --hash=sha256:7876452af029456b3f3549b696bb36a06db7c90747740c5302f74a9e9fa14b13 \
+ --hash=sha256:7939aa3ca7d2a1593596e7ac6d59391ff30281ef280d8632fa03d81f7c5f955e \
+ --hash=sha256:8320f64b777d00dd7ccdade271eaf0cad6636343293a25074cc5566160e4de7b \
+ --hash=sha256:85f3ff71e2e60bd4b4932a043fbbe0f499e263c628390b285cb599154a3b03b1 \
+ --hash=sha256:8b8b36671f10ba80e159378df9c4f15c14098c4fd73a36b9ad715f057272fbef \
+ --hash=sha256:93147c513fac16385d1036b7e5b102c7fbbdb163d556b791f0f11eada7ba65dc \
+ --hash=sha256:935e943ec47c4afab8965954bf49bfa639c05d4ccf9ef6e924188f762145c0ff \
+ --hash=sha256:94b6150a85e1b33b40b1464a3f9988dcc5251d6ed06842abff82e42632fac120 \
+ --hash=sha256:94ebba31df2aa506d7b14866fed00ac141a867e63143fe5bca82a8e503b36437 \
+ --hash=sha256:95ffcf719966dd7c453f908e208e14cde192e09fde6c7186c8f1896ef778d8cd \
+ --hash=sha256:98884ecf2ffb7d7fe6bd517e8eb99d31ff7855a840fa6d0d63cd07c037f6a981 \
+ --hash=sha256:99cfaa2110534e2cf3ba31a7abcac9d328d1d9f1b95beede58294a60348fba36 \
+ --hash=sha256:9e8f8c9cb53cdac7ba9793c276acd90168f416b9ce36799b9b885790f8ad6c0a \
+ --hash=sha256:a0dfc6c143b519113354e780a50381508139b07d2177cb6ad6a08278ec655798 \
+ --hash=sha256:b2795058c23988728eec1f36a4e5e4ebad22f8320c85f3587b539b9ac84128d7 \
+ --hash=sha256:b42703b1cf69f2aa1df7d1030b9d77d3e584a70755674d60e710f0af570f3761 \
+ --hash=sha256:b7cede291382a78f7bb5f04a529cb18e068dd29e0fb27376074b6d0317bf4dd0 \
+ --hash=sha256:b8a678974d1f3aa55f6cc34dc480169d58f2e6d8958895d68845fa4ab566509e \
+ --hash=sha256:b8da394b34370874b4572676f36acabac172602abf054cbc4ac910219f3340af \
+ --hash=sha256:c3a701fe5a9695b238503ce5bbe8218e03c3bcccf7e204e455e7462d770268aa \
+ --hash=sha256:c4aab7f6381f38a4b42f269057aee279ab0fc7bf2e929e3d4abfae97b682a12c \
+ --hash=sha256:ca9d0ff5ad43e785350894d97e13633a66e2b50000e8a183a50a88d834752d42 \
+ --hash=sha256:d0028e725ee18175c6e422797c407874da24381ce0690d6b9396c204c7f7276e \
+ --hash=sha256:d21e10da6ec19b457b82636209cbe2331ff4306b54d06fa04b7c138ba18c8a81 \
+ --hash=sha256:d5e975ca70269d66d17dd995dafc06f1b06e8cb1ec1e9ed54c1d1e4a7c4cf26e \
+ --hash=sha256:da7a9bff22ce038e19bf62c4dd1ec8391062878710ded0a845bcf47cc0200617 \
+ --hash=sha256:db32b5348615a04b82240cc67983cb315309e88d444a288934ee6ceaebcad6cc \
+ --hash=sha256:dcc62f31eae24de7f8dce72134c8651c58000d3b1868e01392baea7c32c247de \
+ --hash=sha256:dfc59d69fc48664bc693842bd57acfdd490acafda1ab52c7836e3fc75c90a111 \
+ --hash=sha256:e347b3bfcf985a05e8c0b7d462ba6f15b1ee1c909e2dcad795e49e91b152c383 \
+ --hash=sha256:e4d333e558953648ca09d64f13e6d8f0523fa705f51cae3f03b5983489958c70 \
+ --hash=sha256:ed10eac5830befbdd0c32f83e8aa6288361597550ba669b04c48f0f9a2c843c6 \
+ --hash=sha256:efc0f674aa41b92da8c49e0346318c6075d734994c3c4e4430b1c3f853e498e4 \
+ --hash=sha256:f1695e76146579f8c06c1509c7ce4dfe0706f49c6831a817ac04eebb2fd02011 \
+ --hash=sha256:f1d4aeb8891338e60d1ab6127af1fe45def5259def8094b9c7e34690c8858803 \
+ --hash=sha256:f406b22b7c9a9b4f8aa9d2ab13d6ae0ac3e85c9a809bd590ad53fed2bf70dc79 \
+ --hash=sha256:f6ff3b14f2df4c41660a7dec01045a045653998784bf8cfcb5a525bdffffbc8f
+ # via sqlalchemy
grpcio==1.64.1 \
--hash=sha256:03b43d0ccf99c557ec671c7dede64f023c7da9bb632ac65dbc57f166e4970040 \
--hash=sha256:0a12ddb1678ebc6a84ec6b0487feac020ee2b1659cbe69b80f06dbffdb249122 \
@@ -745,6 +825,7 @@ isodate==0.6.1 \
--hash=sha256:48c5881de7e8b0a0d648cb024c8062dc84e7b840ed81e864c7614fd3c127bde9
# via
# azure-ai-translation-text
+ # azure-appconfiguration
# azure-communication-callautomation
# azure-eventgrid
# azure-search-documents
diff --git a/requirements.txt b/requirements.txt
index 6945013..6bdce6d 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -125,6 +125,10 @@ azure-ai-translation-text==1.0.0 \
--hash=sha256:268f1bc486e57ebf65b4f1368b9aa939be90064262ba5e3b821ce5000bf84eb3 \
--hash=sha256:46e25cd5ea87b7dfbc46ba31777af16fa985219cd0dea820b0bcc1e0f2b7a41e
# via call-center-ai (pyproject.toml)
+azure-appconfiguration==1.7.1 \
+ --hash=sha256:3ebe41e9be3f4ae6ca61e5dbc42c4b7cc007a01054a8506501a26dfc199fd3ec \
+ --hash=sha256:6e62b040a0210071be4423aafbdca3b053884c0d412855e3f8eff8e8d0b1a02b
+ # via call-center-ai (pyproject.toml)
azure-common==1.1.28 \
--hash=sha256:4ac0cd3214e36b6a1b6a442686722a5d8cc449603aa833f3f0f40bda836704a3 \
--hash=sha256:5c12d3dcf4ec20599ca6b0d3e09e86e146353d443e7fcc050c9a19c1f9df20ad
@@ -142,6 +146,7 @@ azure-core==1.30.2 \
--hash=sha256:cf019c1ca832e96274ae85abd3d9f752397194d9fea3b41487290562ac8abe4a
# via
# azure-ai-translation-text
+ # azure-appconfiguration
# azure-communication-callautomation
# azure-communication-sms
# azure-core-tracing-opentelemetry
@@ -613,6 +618,7 @@ isodate==0.6.1 \
--hash=sha256:48c5881de7e8b0a0d648cb024c8062dc84e7b840ed81e864c7614fd3c127bde9
# via
# azure-ai-translation-text
+ # azure-appconfiguration
# azure-communication-callautomation
# azure-eventgrid
# azure-search-documents
diff --git a/tests/cache.py b/tests/cache.py
index e07db75..86c86dd 100644
--- a/tests/cache.py
+++ b/tests/cache.py
@@ -44,7 +44,11 @@ async def test_acid(random_text: str, cache_mode: CacheModeEnum) -> None:
assume(not await cache.aget(test_key))
# Insert test call
- await cache.aset(test_key, test_value)
+ await cache.aset(
+ key=test_key,
+ ttl_sec=60,
+ value=test_value,
+ )
# Check point read
assume(await cache.aget(test_key) == test_value.encode())