Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
breaking: Rename "workflow" model to "conversation"
Clémence Lesné5fc8c47b04bf
diff --git a/README.md b/README.mdindex 61e9358..f3b3e4b 100644--- a/README.md+++ b/README.md@@ -260,7 +260,7 @@ Create a local `config.yaml` file (most of the fields are filled automatically b```yaml# config.yaml-workflow:+conversation:initiate:agent_phone_number: "+33612345678"bot_company: Contoso@@ -300,7 +300,7 @@ Place a file called `config.yaml` in the root of the project with the followingresources:public_url: "https://xxx.blob.core.windows.net/public"-workflow:+conversation:initiate:agent_phone_number: "+33612345678"bot_company: Contoso@@ -333,9 +333,9 @@ llm:azure_openai:api_key: xxxcontext: 128000- deployment: gpt-4-0125-preview+ deployment: gpt-4o-2024-05-13endpoint: https://xxx.openai.azure.com- model: gpt-4+ model: gpt-4ostreaming: trueai_search:@@ -420,7 +420,7 @@ See the [list of supported languages](https://learn.microsoft.com/en-us/azure/ai# config.yaml[...]-workflow:+conversation:initiate:lang:default_short_code: "fr-FR"@@ -475,7 +475,7 @@ Default schema, for inbound calls, is defined in the configuration:# config.yaml[...]-workflow:+conversation:default_initiate:claim:- name: additional_notes@@ -503,7 +503,7 @@ Default task, for inbound calls, is defined in the configuration:# config.yaml[...]-workflow:+conversation:initiate:task: "Help the customer with their insurance claim. Assistant requires data from the customer to fill the claim. The latest claim data will be given. Assistant role is not over until all the relevant data is gathered."```diff --git a/bicep/app.bicep b/bicep/app.bicepindex 858a47e..f928284 100644--- a/bicep/app.bicep+++ b/bicep/app.bicep@@ -45,12 +45,12 @@ var config = {resources: {public_url: storageAccount.properties.primaryEndpoints.web}- workflow: {+ conversation: {initiate: {- agent_phone_number: localConfig.workflow.initiate.agent_phone_number- bot_company: localConfig.workflow.initiate.bot_company- bot_name: localConfig.workflow.initiate.bot_name- lang: localConfig.workflow.initiate.lang+ agent_phone_number: localConfig.conversation.initiate.agent_phone_number+ bot_company: localConfig.conversation.initiate.bot_company+ bot_name: localConfig.conversation.initiate.bot_name+ lang: localConfig.conversation.initiate.lang}}communication_services: {diff --git a/function_app.py b/function_app.pyindex 02392ec..ea40ceb 100644--- a/function_app.py+++ b/function_app.py@@ -609,7 +609,7 @@ async def _communicationservices_event_url(call = CallStateModel(initiate=initiateor CallInitiateModel(- **CONFIG.workflow.initiate.model_dump(),+ **CONFIG.conversation.initiate.model_dump(),phone_number=phone_number,))diff --git a/helpers/call_events.py b/helpers/call_events.pyindex 7129802..84c9160 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -147,10 +147,10 @@ async def on_recognize_timeout_error(if (contexts and CallContextEnum.IVR_LANG_SELECT in contexts): # Retry IVR recognition- if call.recognition_retry < CONFIG.workflow.max_voice_recognition_retry:+ if call.recognition_retry < CONFIG.conversation.voice_recognition_retry_max:call.recognition_retry += 1logger.info(- f"Timeout, retrying language selection ({call.recognition_retry}/{CONFIG.workflow.max_voice_recognition_retry})"+ f"Timeout, retrying language selection ({call.recognition_retry}/{CONFIG.conversation.voice_recognition_retry_max})")await _handle_ivr_language(call=call, client=client)else: # IVR retries are exhausted, end call@@ -162,7 +162,7 @@ async def on_recognize_timeout_error(returnif (- call.recognition_retry >= CONFIG.workflow.max_voice_recognition_retry+ call.recognition_retry >= CONFIG.conversation.voice_recognition_retry_max): # Voice retries are exhausted, end calllogger.info("Timeout, ending call")await _handle_goodbye(@@ -180,7 +180,7 @@ async def on_recognize_timeout_error(# Retry voice recognitioncall.recognition_retry += 1logger.info(- f"Timeout, retrying voice recognition ({call.recognition_retry}/{CONFIG.workflow.max_voice_recognition_retry})"+ f"Timeout, retrying voice recognition ({call.recognition_retry}/{CONFIG.conversation.voice_recognition_retry_max})")await handle_recognize_text(call=call,@@ -539,7 +539,7 @@ async def _handle_ivr_language(DtmfTone.NINE,]choices = []- for i, lang in enumerate(CONFIG.workflow.initiate.lang.availables):+ for i, lang in enumerate(CONFIG.conversation.initiate.lang.availables):choices.append(RecognitionChoice(label=lang.short_code,diff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex 7e60779..dc46316 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -179,10 +179,10 @@ async def load_llm_chat(# Timeoutssoft_timeout_triggered = Falsesoft_timeout_task = asyncio.create_task(- asyncio.sleep(CONFIG.workflow.intelligence_soft_timeout_sec)+ asyncio.sleep(CONFIG.conversation.answer_soft_timeout_sec))hard_timeout_task = asyncio.create_task(- asyncio.sleep(CONFIG.workflow.intelligence_hard_timeout_sec)+ asyncio.sleep(CONFIG.conversation.answer_hard_timeout_sec))await handle_media(@@ -228,7 +228,7 @@ async def load_llm_chat(if hard_timeout_task.done(): # Break when hard timeout is reachedlogger.warning(- f"Hard timeout of {CONFIG.workflow.intelligence_hard_timeout_sec}s reached"+ f"Hard timeout of {CONFIG.conversation.answer_hard_timeout_sec}s reached")# Clean up_clear_tasks()@@ -239,7 +239,7 @@ async def load_llm_chat(soft_timeout_task.done() and not soft_timeout_triggered): # Speak when soft timeout is reachedlogger.warning(- f"Soft timeout of {CONFIG.workflow.intelligence_soft_timeout_sec}s reached"+ f"Soft timeout of {CONFIG.conversation.answer_soft_timeout_sec}s reached")soft_timeout_triggered = Trueawait handle_recognize_text(diff --git a/helpers/call_utils.py b/helpers/call_utils.pyindex 679ad39..6260061 100644--- a/helpers/call_utils.py+++ b/helpers/call_utils.py@@ -189,7 +189,7 @@ async def handle_recognize_text(call=call,client=client,contexts=contexts,- end_silence=CONFIG.workflow.voice_timeout_after_silence_sec,+ end_silence=CONFIG.conversation.phone_silence_timeout_sec,style=style,text=None,)@@ -204,7 +204,7 @@ async def handle_recognize_text(for i, chunk in enumerate(chunks):end_silence = Noneif i == len(chunks) - 1: # Last chunk- end_silence = CONFIG.workflow.voice_timeout_after_silence_sec+ end_silence = CONFIG.conversation.phone_silence_timeout_secif timeout_error:contexts.append(ContextEnum.LAST_CHUNK)await _handle_recognize_media(diff --git a/helpers/config_models/workflow.py b/helpers/config_models/conversation.pysimilarity index 87%rename from helpers/config_models/workflow.pyrename to helpers/config_models/conversation.pyindex a678536..a8c239d 100644--- a/helpers/config_models/workflow.py+++ b/helpers/config_models/conversation.py@@ -156,14 +156,32 @@ class WorkflowInitiateModel(BaseModel):)-class WorkflowModel(BaseModel):- conversation_timeout_hour: int = 72 # 3 days+class ConversationModel(BaseModel):initiate: WorkflowInitiateModel- intelligence_hard_timeout_sec: int = 180 # 3 minutes- intelligence_soft_timeout_sec: int = 30 # 30 seconds- max_voice_recognition_retry: int = 3- use_slow_llm_for_chat_as_default: bool = True- voice_timeout_after_silence_sec: int = 2 # 2 seconds+ answer_hard_timeout_sec: int = Field(+ default=180, # 3 minutes+ serialization_alias="intelligence_hard_timeout_sec", # Compatibility with v7+ )+ answer_soft_timeout_sec: int = Field(+ default=30, # 30 seconds+ 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=2, # 2 seconds+ serialization_alias="voice_timeout_after_silence_sec", # Compatibility with v7+ )+ slow_llm_for_chat: bool = Field(+ default=True,+ 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.pyindex fe89db8..37fd0cc 100644--- a/helpers/config_models/prompts.py+++ b/helpers/config_models/prompts.py@@ -554,7 +554,7 @@ class TtsModel(BaseModel):call,bot_company=call.initiate.bot_company,bot_name=call.initiate.bot_name,- conversation_timeout_hour=CONFIG.workflow.conversation_timeout_hour,+ conversation_timeout_hour=CONFIG.conversation.callback_timeout_hour,)async def timeout_loading(self, call: CallStateModel) -> str:diff --git a/helpers/config_models/root.py b/helpers/config_models/root.pyindex 41a9f7c..0336ad2 100644--- a/helpers/config_models/root.py+++ b/helpers/config_models/root.py@@ -10,7 +10,7 @@ from helpers.config_models.monitoring import MonitoringModelfrom helpers.config_models.prompts import PromptsModelfrom helpers.config_models.resources import ResourcesModelfrom helpers.config_models.sms import SmsModel-from helpers.config_models.workflow import WorkflowModel+from helpers.config_models.conversation import ConversationModelfrom pydantic import Fieldfrom pydantic_settings import BaseSettings, SettingsConfigDict@@ -43,4 +43,6 @@ class RootModel(BaseSettings):prompts: PromptsModel = PromptsModel() # Object is fully defined by defaultresources: ResourcesModelsms: SmsModel = SmsModel() # Object is fully defined by default- workflow: WorkflowModel+ conversation: ConversationModel = Field(+ serialization_alias="workflow"+ ) # Compatibility with v7diff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex 19ea096..e9c14aa 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -103,7 +103,7 @@ async def completion_stream(# Try a first time with primary LLMtry:async for chunck in _completion_stream_worker(- is_fast=not CONFIG.workflow.use_slow_llm_for_chat_as_default, # Let configuration decide+ is_fast=not CONFIG.conversation.slow_llm_for_chat, # Let configuration decidemax_tokens=max_tokens,messages=messages,system=system,@@ -115,7 +115,7 @@ async def completion_stream(if not any(isinstance(e, exception) for exception in _retried_exceptions):raise elogger.warning(- f"{e.__class__.__name__} error, trying with {'fast' if CONFIG.workflow.use_slow_llm_for_chat_as_default else 'slow'} LLM"+ f"{e.__class__.__name__} error, trying with {'fast' if CONFIG.conversation.slow_llm_for_chat else 'slow'} LLM")# Try more times with backup LLM, if it fails again, raise the error@@ -130,7 +130,7 @@ async def completion_stream(async for attempt in retryed:with attempt:async for chunck in _completion_stream_worker(- is_fast=CONFIG.workflow.use_slow_llm_for_chat_as_default, # Let configuration decide+ is_fast=CONFIG.conversation.slow_llm_for_chat, # Let configuration decidemax_tokens=max_tokens,messages=messages,system=system,@@ -528,7 +528,7 @@ def _count_tokens(content: str, model: str) -> int:encoding_name = tiktoken.encoding_name_for_model(model)except KeyError:encoding_name = tiktoken.encoding_name_for_model("gpt-3.5")- logger.warning(f"Unknown model {model}, using {encoding_name} encoding")+ logger.debug(f"Unknown model {model}, using {encoding_name} encoding")return len(tiktoken.get_encoding(encoding_name).encode(content))diff --git a/models/call.py b/models/call.pyindex a755135..2fa8d5d 100644--- a/models/call.py+++ b/models/call.py@@ -1,6 +1,6 @@from datetime import datetime, UTC, tzinfo-from helpers.config_models.workflow import LanguageEntryModel-from helpers.config_models.workflow import WorkflowInitiateModel+from helpers.config_models.conversation import LanguageEntryModel+from helpers.config_models.conversation import WorkflowInitiateModelfrom helpers.pydantic_types.phone_numbers import PhoneNumberfrom models.message import MessageModel, ActionEnum as MessageActionEnumfrom models.next import NextModel@@ -85,7 +85,7 @@ class CallStateModel(CallGetModel, extra="ignore"):def lang(self) -> LanguageEntryModel: # type: ignorefrom helpers.config import CONFIG- lang = CONFIG.workflow.initiate.lang+ lang = CONFIG.conversation.initiate.langdefault = lang.default_langif self.lang_short_code:return next(diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex 9ed9b35..b58e034 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -162,7 +162,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.workflow.conversation_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', -{CONFIG.conversation.callback_timeout_hour}, GETCURRENTDATETIME()) ORDER BY c.created_at DESC",parameters=[{"name": "@phone_number",diff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex 322ac0f..4a2e5b6 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -132,7 +132,7 @@ class SqliteStore(IStore):call = Noneasync 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.workflow.conversation_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', '-{CONFIG.conversation.callback_timeout_hour} hours') ORDER BY DATETIME(JSON_EXTRACT(data, '$.created_at')) DESC LIMIT 1",(phone_number, # data.initiate.phone_numberphone_number, # data.claim.policyholder_phonediff --git a/tests/conftest.py b/tests/conftest.pyindex 4fbe98e..cd114d5 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -208,7 +208,7 @@ def random_text() -> str:def call() -> CallStateModel:call = CallStateModel(initiate=CallInitiateModel(- **CONFIG.workflow.initiate.model_dump(),+ **CONFIG.conversation.initiate.model_dump(),phone_number="+33612345678", # type: ignore),voice_id="dummy",diff --git a/tests/llm.py b/tests/llm.pyindex 3ca2db7..4883a94 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -13,7 +13,7 @@ from helpers.call_events import ()from datetime import UTC, datetimefrom deepeval.metrics import BaseMetric-from helpers.config_models.workflow import ClaimFieldModel+from helpers.config_models.conversation import ClaimFieldModelfrom helpers.logging import loggerfrom models.call import CallStateModelfrom models.reminder import ReminderModel