Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Allow to cut the voice for the first message
Clémence Lesné222f63bf62d3
diff --git a/app/helpers/call_events.py b/app/helpers/call_events.pyindex d3efe9e..8f2f2f8 100644--- a/app/helpers/call_events.py+++ b/app/helpers/call_events.py@@ -41,7 +41,6 @@ from app.models.message import (ActionEnum as MessageActionEnum,MessageModel,PersonaEnum as MessagePersonaEnum,- StyleEnum as MessageStyleEnum,extract_message_style,remove_message_action,)@@ -107,7 +106,6 @@ async def on_new_call(async def on_call_connected(call: CallStateModel,client: CallAutomationClient,- post_callback: Callable[[CallStateModel], Awaitable[None]],scheduler: Scheduler,server_call_id: str,) -> None:@@ -123,7 +121,6 @@ async def on_call_connected(_handle_ivr_language(call=call,client=client,- post_callback=post_callback,scheduler=scheduler,), # First, every time a call is answered, confirm the language_handle_recording(@@ -247,7 +244,6 @@ async def on_automation_recognize_error(await _handle_ivr_language(call=call,client=client,- post_callback=post_callback,scheduler=scheduler,)@@ -409,15 +405,6 @@ async def on_automation_play_completed()return- # Start real-time- if CallContextEnum.START_REALTIME in contexts:- logger.info("Starting real-time")- await start_audio_streaming(- call=call,- client=client,- )- return-logger.warning("Unknown context %s", contexts)@@ -459,7 +446,6 @@ async def on_ivr_recognized(call: CallStateModel,client: CallAutomationClient,label: str,- post_callback: Callable[[CallStateModel], Awaitable[None]],scheduler: Scheduler,) -> None:"""@@ -491,28 +477,9 @@ async def on_ivr_recognized(call.lang = lang.short_codecall.recognition_retry = 0- # First call- if len(call.messages) <= 1:- # Greet the userwith the next message- await handle_automation_tts(- call=call,- client=client,- context=CallContextEnum.START_REALTIME,- post_callback=post_callback,- scheduler=scheduler,- text=await CONFIG.prompts.tts.hello(call),- )- return-- # Welcome back the user- await handle_automation_tts(+ await start_audio_streaming(call=call,client=client,- context=CallContextEnum.START_REALTIME,- post_callback=post_callback,- scheduler=scheduler,- style=MessageStyleEnum.CHEERFUL,- text=await CONFIG.prompts.tts.welcome_back(call),)@@ -779,7 +746,6 @@ async def _intelligence_next(async def _handle_ivr_language(call: CallStateModel,client: CallAutomationClient,- post_callback: Callable[[CallStateModel], Awaitable[None]],scheduler: Scheduler,) -> None:"""@@ -795,7 +761,6 @@ async def _handle_ivr_language(call=call,client=client,label=short_code,- post_callback=post_callback,scheduler=scheduler,)returndiff --git a/app/helpers/call_llm.py b/app/helpers/call_llm.pyindex 2598cc6..c248c72 100644--- a/app/helpers/call_llm.py+++ b/app/helpers/call_llm.py@@ -69,8 +69,8 @@ async def load_llm_chat( # noqa: PLR0913training_callback: Callable[[CallStateModel], Awaitable[None]],) -> None:# Init language recognition- stt_buffer: list[str] = []- stt_complete_gate = asyncio.Event()+ stt_buffer: list[str] = [] # Temporary buffer for recognition+ stt_complete_gate = asyncio.Event() # Gate to wait for the recognitiondef _stt_callback(text: str) -> None:# Skip if no text@@ -133,6 +133,27 @@ async def load_llm_chat( # noqa: PLR0913# Clear the recognition bufferstt_buffer.clear()+ async def _commit_answer(tool_blacklist: set[str] | None = None) -> None:+ """+ Process the response.+ """+ # Store recognition task+ nonlocal last_response+ last_response = await scheduler.spawn(+ _continue_chat(+ call=call,+ client=automation_client,+ post_callback=post_callback,+ scheduler=scheduler,+ tool_blacklist=tool_blacklist,+ training_callback=training_callback,+ tts_client=tts_client,+ )+ )++ # Wait for the response to be processed+ await last_response.wait()+async def _response_callback() -> None:# Wait for the complete recognitionawait stt_complete_gate.wait()@@ -160,23 +181,26 @@ async def load_llm_chat( # noqa: PLR0913# Clear the recognition bufferstt_buffer.clear()- # Store recognitio task- nonlocal last_response- last_response = await scheduler.spawn(- _out_answer(- call=call,- client=automation_client,- post_callback=post_callback,- scheduler=scheduler,- training_callback=training_callback,- tts_client=tts_client,- )- )+ # Process the response+ await _commit_answer()- # Wait for the response to be processed- await last_response.wait()+ # First call+ if len(call.messages) <= 1:+ # Welcome with a pre-recorded message+ await handle_realtime_tts(+ call=call,+ tts_client=tts_client,+ scheduler=scheduler,+ text=await CONFIG.prompts.tts.hello(call),+ )+ # User is back+ else:+ # Welcome with the LLM, do not use the end call tool for the first message, LLM hallucinates it and this is extremely frustrating for the user+ await _commit_answer(+ {"end_call"},+ )- await _in_audio(+ await _process_chat_audio(bits_per_sample=audio_bits_per_sample,call=call,channels=audio_channels,@@ -190,12 +214,13 @@ async def load_llm_chat( # noqa: PLR0913# TODO: Refacto, this function is too long (and remove PLR0912/PLR0915 ignore)[email protected]_as_current_span("call_load_out_answer")-async def _out_answer( # noqa: PLR0915, PLR0913[email protected]_as_current_span("call_continue_chat")+async def _continue_chat( # noqa: PLR0915, PLR0913call: CallStateModel,client: CallAutomationClient,post_callback: Callable[[CallStateModel], Awaitable[None]],scheduler: Scheduler,+ tool_blacklist: set[str] | None,training_callback: Callable[[CallStateModel], Awaitable[None]],tts_client: SpeechSynthesizer,_iterations_remaining: int = 3,@@ -353,11 +378,12 @@ async def _out_answer( # noqa: PLR0915, PLR0913# Retry chat after an errorelse:logger.info("Retrying chat, %s remaining", _iterations_remaining - 1)- return await _out_answer(+ return await _continue_chat(call=call,client=client,post_callback=post_callback,scheduler=scheduler,+ tool_blacklist=tool_blacklist,training_callback=training_callback,tts_client=tts_client,_iterations_remaining=_iterations_remaining - 1,@@ -366,11 +392,12 @@ async def _out_answer( # noqa: PLR0915, PLR0913# Contiue chatelif continue_chat and _iterations_remaining > 0:logger.info("Continuing chat, %s remaining", _iterations_remaining - 1)- return await _out_answer(+ return await _continue_chat(call=call,client=client,post_callback=post_callback,scheduler=scheduler,+ tool_blacklist=tool_blacklist,training_callback=training_callback,tts_client=tts_client,_iterations_remaining=_iterations_remaining - 1,@@ -383,12 +410,13 @@ async def _out_answer( # noqa: PLR0915, PLR0913# TODO: Refacto, this function is too long[email protected]_as_current_span("call_execute_llm_chat")-async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915[email protected]_as_current_span("call_generate_chat_completion")+async def _generate_chat_completion( # noqa: PLR0913, PLR0911, PLR0912, PLR0915call: CallStateModel,client: CallAutomationClient,post_callback: Callable[[CallStateModel], Awaitable[None]],scheduler: Scheduler,+ tool_blacklist: set[str] | None,tts_callback: Callable[[str, MessageStyleEnum], Awaitable[None]],tts_client: SpeechSynthesizer,use_tools: bool,@@ -445,7 +473,7 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915if not use_tools:logger.warning("Tools disabled for this chat")else:- tools = await plugins.to_openai()+ tools = await plugins.to_openai(tool_blacklist)# logger.debug("Tools: %s", tools)# Execute LLM inference@@ -564,7 +592,7 @@ async def _execute_llm_chat( # noqa: PLR0913, PLR0911, PLR0912, PLR0915# TODO: Refacto and simplify-async def _in_audio( # noqa: PLR0913+async def _process_chat_audio( # noqa: PLR0913bits_per_sample: int,call: CallStateModel,channels: int,diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.pyindex 1bb8511..766b5ce 100644--- a/app/helpers/call_utils.py+++ b/app/helpers/call_utils.py@@ -89,8 +89,6 @@ class ContextEnum(str, Enum):"""Hang up"""IVR_LANG_SELECT = "ivr_lang_select""""IVR language selection"""- START_REALTIME = "start_realtime"- """Start realtime call"""TRANSFER_FAILED = "transfer_failed""""Transfer failed"""diff --git a/app/helpers/config_models/prompts.py b/app/helpers/config_models/prompts.pyindex 242f125..56b1e61 100644--- a/app/helpers/config_models/prompts.py+++ b/app/helpers/config_models/prompts.py@@ -520,11 +520,6 @@ class TtsModel(BaseModel):"It seems quiet on your end. How can I assist you?","I didn't catch that. How can I help?",]- welcome_back_tpl: list[str] = [- "Hello, I'm {bot_name}, from {bot_company}!",- "Hi there, {bot_name} from {bot_company} here!",- "Hey, it's {bot_name} from {bot_company}!",- ]timeout_loading_tpl: list[str] = ["It's taking me longer than expected to reply. Thank you for your patience…","I'm working on your request. Thanks for waiting!",@@ -566,17 +561,6 @@ class TtsModel(BaseModel):async def timeout_silence(self, call: CallStateModel) -> str:return await self._translate(self.timeout_silence_tpl, call)- async def welcome_back(self, call: CallStateModel) -> str:- from app.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=await callback_timeout_hour(),- )-async def timeout_loading(self, call: CallStateModel) -> str:return await self._translate(self.timeout_loading_tpl, call)diff --git a/app/helpers/llm_utils.py b/app/helpers/llm_utils.pyindex e37451b..128ff64 100644--- a/app/helpers/llm_utils.py+++ b/app/helpers/llm_utils.py@@ -71,12 +71,20 @@ class AbstractPlugin:self.tts_callback = tts_callbackself.tts_client = tts_client- async def to_openai(self) -> list[ChatCompletionToolParam]:+ async def to_openai(+ self,+ blacklist: set[str] | None,+ ) -> list[ChatCompletionToolParam]:+ """+ Get the OpenAI SDK schema for all functions of the plugin, excluding the ones in the blacklist.+ """return await asyncio.gather(*[_function_schema(arg_type, call=self.call)for name, arg_type in getmembers(self.__class__, isfunction)- if not name.startswith("_") and name != "to_openai"+ if not name.startswith("_")+ and name != "to_openai"+ and name not in (blacklist or set())])diff --git a/app/main.py b/app/main.pyindex 57c4438..fd3b2b8 100644--- a/app/main.py+++ b/app/main.py@@ -749,7 +749,6 @@ async def _communicationservices_event_worker(await on_call_connected(call=call,client=automation_client,- post_callback=_trigger_post_event,scheduler=scheduler,server_call_id=server_call_id,)@@ -773,7 +772,6 @@ async def _communicationservices_event_worker(call=call,client=automation_client,label=label_detected,- post_callback=_trigger_post_event,scheduler=scheduler,)diff --git a/tests/llm.py b/tests/llm.pyindex ef538a4..695b929 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -26,7 +26,7 @@ from app.helpers.call_events import (on_ivr_recognized,on_play_started,)-from app.helpers.call_llm import _out_answer+from app.helpers.call_llm import _continue_chatfrom app.helpers.config import CONFIGfrom app.helpers.logging import loggerfrom app.models.call import CallStateModel@@ -291,7 +291,6 @@ async def test_llm( # noqa: PLR0913await on_call_connected(call=call,client=automation_client,- post_callback=_post_callback,scheduler=scheduler,server_call_id="dummy",)@@ -301,7 +300,6 @@ async def test_llm( # noqa: PLR0913call=call,client=automation_client,label=call.lang.short_code,- post_callback=_post_callback,scheduler=scheduler,)@@ -319,11 +317,12 @@ async def test_llm( # noqa: PLR0913)# Respond- await _out_answer(+ await _continue_chat(call=call,client=automation_client,post_callback=_post_callback,scheduler=scheduler,+ tool_blacklist=None,training_callback=_training_callback,tts_client=tts_client,)diff --git a/tests/local.py b/tests/local.pyindex f903230..6a0ad05 100644--- a/tests/local.py+++ b/tests/local.py@@ -8,7 +8,7 @@ from app.helpers.call_events import (on_end_call,on_ivr_recognized,)-from app.helpers.call_llm import _out_answer+from app.helpers.call_llm import _continue_chatfrom app.helpers.config import CONFIGfrom app.helpers.logging import loggerfrom app.models.call import CallInitiateModel, CallStateModel@@ -68,7 +68,6 @@ async def main() -> None:await on_call_connected(call=call,client=automation_client,- post_callback=_post_callback,scheduler=scheduler,server_call_id="dummy",)@@ -78,7 +77,6 @@ async def main() -> None:call=call,client=automation_client,label=call.lang.short_code,- post_callback=_post_callback,scheduler=scheduler,)@@ -102,11 +100,12 @@ async def main() -> None:)# Respond- await _out_answer(+ await _continue_chat(call=call,client=automation_client,post_callback=_post_callback,scheduler=scheduler,+ tool_blacklist=None,training_callback=_training_callback,tts_client=tts_client,)