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

ux: Allow user to speak whenever he/she wants

Clémence Lesnéaa7deb5072b7
diff --git a/function_app.py b/function_app.py
index e354880..ec6cbad 100644
--- a/function_app.py
+++ b/function_app.py
@@ -54,9 +54,11 @@ from helpers.call_events import (
on_transfer_completed,
on_transfer_error,
)
+from helpers.call_utils import ContextEnum as CallContextEnum
from models.readiness import ReadinessModel, ReadinessCheckModel, ReadinessStatus
from htmlmin.minify import html_minify
import azure.functions as func
+import json
# Jinja configuration
@@ -71,13 +73,13 @@ _jinja.filters["quote_plus"] = lambda x: quote_plus(str(x)) if x else ""
_jinja.filters["markdown"] = lambda x: mistune.create_markdown(plugins=["abbr", "speedup", "url"])(x) if x else "" # type: ignore
# Azure Communication Services
-_source_caller = PhoneNumberIdentifier(CONFIG.communication_service.phone_number)
-_logger.info(f"Using phone number {str(CONFIG.communication_service.phone_number)}")
+_source_caller = PhoneNumberIdentifier(CONFIG.communication_services.phone_number)
+_logger.info(f"Using phone number {str(CONFIG.communication_services.phone_number)}")
# Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)
_automation_client = CallAutomationClient(
- endpoint=CONFIG.communication_service.endpoint,
+ endpoint=CONFIG.communication_services.endpoint,
credential=AzureKeyCredential(
- CONFIG.communication_service.access_key.get_secret_value()
+ CONFIG.communication_services.access_key.get_secret_value()
),
)
@@ -284,7 +286,7 @@ async def eventgrid_event_post(msg: func.QueueMessage) -> None:
await on_new_call(
callback_url=url,
client=_automation_client,
- context=call_context,
+ incoming_context=call_context,
phone_number=phone_number,
)
@@ -347,10 +349,15 @@ async def _communicationservices_event_worker(
# Store connection ID
connection_id = event.data["callConnectionId"]
call.voice_id = connection_id
-
+ # Extract context
+ event_type = event.type
# Extract event context
operation_context = event.data.get("operationContext", None)
- event_type = event.type
+ operation_contexts: Optional[list[CallContextEnum]] = (
+ [CallContextEnum(context) for context in json.loads(operation_context)]
+ if operation_context
+ else None
+ )
_logger.debug(f"Call event received {event_type} for call {call}")
_logger.debug(event.data)
@@ -374,13 +381,14 @@ async def _communicationservices_event_worker(
recognition_result: str = event.data["recognitionType"]
if recognition_result == "speech": # Handle voice
- speech_text: str = event.data["speechResult"]["speech"]
- await on_speech_recognized(
- background_tasks=background_tasks,
- call=call,
- client=_automation_client,
- text=speech_text,
- )
+ speech_text: Optional[str] = event.data["speechResult"]["speech"]
+ if speech_text:
+ await on_speech_recognized(
+ background_tasks=background_tasks,
+ call=call,
+ client=_automation_client,
+ text=speech_text,
+ )
elif recognition_result == "choices": # Handle IVR
label_detected: str = event.data["choiceResult"]["label"]
@@ -405,6 +413,7 @@ async def _communicationservices_event_worker(
await on_speech_timeout_error(
call=call,
client=_automation_client,
+ contexts=operation_contexts,
)
else: # Unknown error
await on_speech_unknown_error(
@@ -418,7 +427,7 @@ async def _communicationservices_event_worker(
background_tasks=background_tasks,
call=call,
client=_automation_client,
- context=operation_context,
+ contexts=operation_contexts,
)
elif event_type == "Microsoft.Communication.PlayFailed": # Media play failed
diff --git a/helpers/call_events.py b/helpers/call_events.py
index d71bba5..ae249fe 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -1,3 +1,4 @@
+from typing import Optional
from azure.communication.callautomation import (
CallAutomationClient,
DtmfTone,
@@ -21,8 +22,8 @@ from models.message import (
)
from helpers.call_utils import (
ContextEnum as CallContextEnum,
+ handle_clear_queue,
handle_hangup,
- handle_play,
handle_recognize_ivr,
handle_recognize_text,
handle_transfer,
@@ -42,7 +43,7 @@ _db = CONFIG.database.instance()
async def on_new_call(
callback_url: str,
client: CallAutomationClient,
- context: str,
+ incoming_context: str,
phone_number: str,
) -> bool:
_logger.debug(f"Incoming call handler caller ID: {phone_number}")
@@ -51,7 +52,7 @@ async def on_new_call(
answer_call_result = client.answer_call(
callback_url=callback_url,
cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,
- incoming_call_context=context,
+ incoming_call_context=incoming_context,
)
_logger.info(
f"Answered call with {phone_number} ({answer_call_result.call_connection_id})"
@@ -119,6 +120,9 @@ async def on_speech_recognized(
await _db.call_aset(
call
) # Save ASAP in DB allowing SMS answers to be more "in-sync"
+ await handle_clear_queue(
+ call=call, client=client
+ ) # When the user speak, the conversation should continue based on its last message
call = await load_llm_chat(
background_tasks=background_tasks,
call=call,
@@ -131,23 +135,30 @@ async def on_speech_recognized(
async def on_speech_timeout_error(
call: CallStateModel,
client: CallAutomationClient,
+ contexts: Optional[list[CallContextEnum]],
) -> None:
+ if not (contexts and CallContextEnum.LAST_CHUNK in contexts):
+ _logger.debug("Ignoring timeout if bot is still speaking")
+ return
+
+ res_context = None
if call.voice_recognition_retry < 10:
- await handle_recognize_text(
- call=call,
- client=client,
- store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
- text=await CONFIG.prompts.tts.timeout_silence(call),
- )
call.voice_recognition_retry += 1
+ trigger_timeout = True # Should re-trigger an error or the LLM
+ text = await CONFIG.prompts.tts.timeout_silence(call)
else:
- await handle_play(
- call=call,
- client=client,
- context=CallContextEnum.GOODBYE,
- text=await CONFIG.prompts.tts.goodbye(call),
- store=False, # Do not store goodbye prompt as it perturbs the LLM and makes it hallucinate
- )
+ trigger_timeout = False # Shouldn't trigger anything, as call is ending
+ res_context = CallContextEnum.GOODBYE
+ text = await CONFIG.prompts.tts.goodbye(call)
+
+ await handle_recognize_text(
+ call=call,
+ client=client,
+ context=res_context,
+ store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
+ text=text,
+ trigger_timeout=trigger_timeout,
+ )
@TRACER.start_as_current_span("on_speech_unknown_error")
@@ -175,17 +186,21 @@ async def on_play_completed(
background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
- context: str,
+ contexts: Optional[list[CallContextEnum]],
) -> None:
_logger.debug("Play completed")
+ if not contexts:
+ return
+
if (
- context == CallContextEnum.TRANSFER_FAILED or context == CallContextEnum.GOODBYE
+ CallContextEnum.TRANSFER_FAILED in contexts
+ or CallContextEnum.GOODBYE in contexts
): # Call ended
_logger.info("Ending call")
await _handle_hangup(background_tasks, client, call)
- elif context == CallContextEnum.CONNECT_AGENT: # Call transfer
+ elif CallContextEnum.CONNECT_AGENT in contexts: # Call transfer
_logger.info("Initiating transfer call initiated")
await handle_transfer(
call=call,
@@ -195,9 +210,7 @@ async def on_play_completed(
@TRACER.start_as_current_span("on_play_error")
-async def on_play_error(
- error_code: int,
-) -> None:
+async def on_play_error(error_code: int) -> None:
_logger.debug("Play failed")
# See: https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/communication-services/how-tos/call-automation/play-action.md
if error_code == 8535: # Action failed, file format
@@ -244,11 +257,12 @@ async def on_ivr_recognized(
)
else: # Returning call
- await handle_play(
+ await handle_recognize_text(
call=call,
client=client,
style=MessageStyleEnum.CHEERFUL,
text=await CONFIG.prompts.tts.welcome_back(call),
+ trigger_timeout=False, # Do not trigger timeout, as the chat will continue
)
call = await load_llm_chat(
background_tasks=background_tasks,
@@ -271,7 +285,7 @@ async def on_transfer_error(
error_code: int,
) -> None:
_logger.info(f"Error during call transfer, subCode {error_code}")
- await handle_play(
+ await handle_recognize_text(
call=call,
client=client,
context=CallContextEnum.TRANSFER_FAILED,
@@ -306,7 +320,6 @@ async def on_sms_received(
call=call,
client=client,
post_call_intelligence=_post_call_intelligence,
- then_recognize=False,
)
return True
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 2a79028..6cd0fda 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -12,8 +12,8 @@ from models.message import (
ToolModel as MessageToolModel,
)
from helpers.call_utils import (
+ handle_clear_queue,
handle_media,
- handle_play,
handle_recognize_text,
tts_sentence_split,
)
@@ -30,9 +30,11 @@ from helpers.llm_worker import (
)
from openai import APIError
from openai.types.chat import ChatCompletionSystemMessageParam
+import time
_logger = build_logger(__name__)
+_cache = CONFIG.cache.instance()
_db = CONFIG.database.instance()
@@ -113,7 +115,6 @@ async def load_llm_chat(
call: CallStateModel,
client: CallAutomationClient,
post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],
- then_recognize: bool = True,
_iterations_remaining: int = 3,
) -> CallStateModel:
"""
@@ -140,14 +141,29 @@ async def load_llm_chat(
return
should_play_sound = False
- await handle_play(
+ await handle_recognize_text(
call=call,
client=client,
- store=False,
style=style,
text=text,
+ trigger_timeout=False, # Voice will continue, don't trigger
)
+ 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
+
+ # Pointer
+ def _pointer_task() -> asyncio.Task:
+ return asyncio.create_task(asyncio.sleep(pointer_timer))
+
+ pointer_timer = 1 # Fetch pointer every seconds
+ 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))
+ pointer_task = _pointer_task()
+
+ # Chat
chat_task = asyncio.create_task(
_execute_llm_chat(
background_tasks=background_tasks,
@@ -159,6 +175,14 @@ async def load_llm_chat(
)
)
+ # Loading
+ def _loading_task() -> asyncio.Task:
+ return asyncio.create_task(asyncio.sleep(loading_timer))
+
+ loading_timer = 5 # Play loading sound every 5 seconds
+ loading_task = _loading_task()
+
+ # Timeouts
soft_timeout_triggered = False
soft_timeout_task = asyncio.create_task(
asyncio.sleep(CONFIG.workflow.intelligence_soft_timeout_sec)
@@ -167,22 +191,47 @@ async def load_llm_chat(
asyncio.sleep(CONFIG.workflow.intelligence_hard_timeout_sec)
)
+ await handle_media(
+ call=call,
+ client=client,
+ sound_url=CONFIG.prompts.sounds.loading(),
+ ) # Play loading sound a first time
+
+ def _clear_tasks() -> None:
+ chat_task.cancel()
+ hard_timeout_task.cancel()
+ loading_task.cancel()
+ soft_timeout_task.cancel()
+
is_error = True
continue_chat = True
- should_user_answer = True
try:
while True:
_logger.debug(f"Chat task status: {chat_task.done()}")
+
+ if pointer_task.done(): # Test if another chat is running
+ if pointer_current == float(
+ (await _cache.aget(pointer_cache_key) or b"0").decode()
+ ): # Pointer not updated
+ pointer_task = _pointer_task()
+ else: # Pointer updated by another instance
+ _logger.warning("Another chat is running, stopping this one")
+ # Clean up Communication Services queue
+ await handle_clear_queue(call=call, client=client)
+ # Clean up tasks
+ _clear_tasks()
+ break
+
if chat_task.done(): # Break when chat coroutine is done
# Clean up
- soft_timeout_task.cancel()
- hard_timeout_task.cancel()
- is_error, continue_chat, should_user_answer, call = (
+ _clear_tasks()
+ # Get result
+ is_error, continue_chat, call = (
chat_task.result()
) # Store updated chat model
await _db.call_aset(
call
- ) # Save ASAP in DB allowing SMS answers to be more "in-sync"
+ ) # 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
@@ -190,8 +239,7 @@ async def load_llm_chat(
f"Hard timeout of {CONFIG.workflow.intelligence_hard_timeout_sec}s reached"
)
# Clean up
- chat_task.cancel()
- soft_timeout_task.cancel()
+ _clear_tasks()
break
if should_play_sound: # Catch timeout if async loading is not started
@@ -202,22 +250,26 @@ async def load_llm_chat(
f"Soft timeout of {CONFIG.workflow.intelligence_soft_timeout_sec}s reached"
)
soft_timeout_triggered = True
- await handle_play(
+ await handle_recognize_text(
call=call,
client=client,
- text=await CONFIG.prompts.tts.timeout_loading(call),
+ trigger_timeout=False, # Voice will continue, don't trigger
store=False, # Do not store timeout prompt as it perturbs the LLM and makes it hallucinate
+ text=await CONFIG.prompts.tts.timeout_loading(call),
)
- else: # Do not play timeout prompt plus loading, it can be frustrating for the user
+ elif (
+ loading_task.done()
+ ): # Do not play timeout prompt plus loading, it can be frustrating for the user
+ loading_task = _loading_task()
await handle_media(
call=call,
client=client,
sound_url=CONFIG.prompts.sounds.loading(),
) # Play loading sound
- # Wait to not block the event loop and play too many sounds
- await asyncio.sleep(5)
+ # Wait to not block the event loop for other requests
+ await asyncio.sleep(0.5)
except Exception:
_logger.warning("Error loading intelligence", exc_info=True)
@@ -225,7 +277,6 @@ async def load_llm_chat(
if is_error: # Error during chat
if not continue_chat or _iterations_remaining < 1: # Maximum retries reached
_logger.warning("Maximum retries reached, stopping chat")
- should_user_answer = True
content = await CONFIG.prompts.tts.error(call)
style = MessageStyleEnum.NONE
await _user_callback(content, style)
@@ -257,12 +308,6 @@ async def load_llm_chat(
_iterations_remaining=_iterations_remaining - 1,
)
- if then_recognize and should_user_answer:
- await handle_recognize_text(
- call=call,
- client=client,
- )
-
return call
@@ -273,7 +318,7 @@ async def _execute_llm_chat(
post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],
use_tools: bool,
user_callback: Callable[[str, MessageStyleEnum], Awaitable],
-) -> Tuple[bool, bool, bool, CallStateModel]:
+) -> Tuple[bool, bool, CallStateModel]:
"""
Perform the chat with the LLM model.
@@ -286,12 +331,10 @@ async def _execute_llm_chat(
1. `bool`, notify error
2. `bool`, should retry chat
- 3. `bool`, if the chat should continue
4. `CallStateModel`, the updated model
"""
_logger.debug("Running LLM chat")
content_full = ""
- should_user_answer = True
async def _tools_callback(text: str, style: MessageStyleEnum) -> None:
nonlocal content_full
@@ -310,11 +353,6 @@ async def _execute_llm_chat(
await user_callback(local_content, new_style)
return new_style
- async def _tools_cancellation_callback() -> None:
- nonlocal should_user_answer
- _logger.info("Chat stopped by tool")
- should_user_answer = False
-
# Build RAG
trainings = await call.trainings()
_logger.info(f"Enhancing LLM chat with {len(trainings)} trainings")
@@ -338,7 +376,6 @@ async def _execute_llm_chat(
# Build plugins
plugins = LlmPlugins(
call=call,
- cancellation_callback=_tools_cancellation_callback,
client=client,
post_call_intelligence=lambda call: post_call_intelligence(
call, background_tasks
@@ -379,7 +416,7 @@ async def _execute_llm_chat(
plugins.style = await _content_callback(sentence, plugins.style)
except APIError as e:
_logger.warning(f"OpenAI API call error: {e}")
- return True, True, should_user_answer, call
+ return True, True, call
# Flush the remaining buffer
if content_buffer_pointer < len(content_full):
@@ -403,12 +440,12 @@ async def _execute_llm_chat(
tool_call.function_name == "multi_tool_use.parallel" for tool_call in tool_calls
):
_logger.warning(f'LLM send back invalid tool schema "multi_tool_use.parallel"')
- return True, True, should_user_answer, call
+ return True, True, call
# OpenAI GPT-4 Turbo tends to return empty content, in that case, retry within limits
if not content_full and not tool_calls:
_logger.warning("Empty content, retrying")
- return True, True, should_user_answer, call
+ return True, True, call
# Execute tools
tool_tasks = [tool_call.execute_function(plugins) for tool_call in tool_calls]
@@ -416,17 +453,22 @@ async def _execute_llm_chat(
call = plugins.call # Update call model if object reference changed
# Store message
- call.messages.append(
- MessageModel(
+ 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:
+ message = MessageModel(
content=content_full.strip(),
persona=MessagePersonaEnum.ASSISTANT,
style=plugins.style,
tool_calls=tool_calls,
)
- )
+ call.messages.append(message)
# Recusive call if needed
- if tool_calls and should_user_answer:
- return False, True, should_user_answer, call
+ if tool_calls:
+ return False, True, call
- return False, False, should_user_answer, call
+ return False, False, call
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index c5220ec..ac7d2aa 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -21,6 +21,7 @@ from models.message import (
StyleEnum as MessageStyleEnum,
)
import re
+import json
_logger = build_logger(__name__)
@@ -39,6 +40,7 @@ class ContextEnum(str, Enum):
CONNECT_AGENT = "connect_agent" # Transfer to agent
GOODBYE = "goodbye" # Hang up
+ LAST_CHUNK = "last_chunk" # Last chunk of text
TRANSFER_FAILED = "transfer_failed" # Transfer failed
@@ -62,9 +64,12 @@ def tts_sentence_split(text: str, include_last: bool) -> Generator[str, None, No
# TODO: Disable or lower profanity filter. The filter seems enabled by default, it replaces words like "holes in my roof" by "*** in my roof". This is not acceptable for a call center.
async def _handle_recognize_media(
- client: CallAutomationClient,
call: CallStateModel,
- sound_url: str,
+ client: CallAutomationClient,
+ contexts: Optional[list[ContextEnum]],
+ end_silence: Optional[int],
+ style: MessageStyleEnum,
+ text: str,
) -> None:
"""
Play a media to a call participant and start recognizing the response.
@@ -74,9 +79,15 @@ 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:
call_client.start_recognizing_media(
- end_silence_timeout=3, # Sometimes user includes breaks in their speech
+ end_silence_timeout=end_silence,
input_type=RecognizeInputType.SPEECH,
- play_prompt=FileSource(url=sound_url),
+ interrupt_prompt=True,
+ operation_context=json.dumps(contexts) if contexts else None,
+ play_prompt=_audio_from_text(
+ call=call,
+ style=style,
+ text=text,
+ ),
speech_language=call.lang.short_code,
target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore
)
@@ -104,7 +115,7 @@ async def handle_media(
assert call.voice_id, "Voice ID is required for recognizing media"
async with _use_call_client(client, call.voice_id) as call_client:
call_client.play_media(
- operation_context=context,
+ operation_context=json.dumps([context]) if context else None,
play_source=FileSource(url=sound_url),
)
except ResourceNotFoundError:
@@ -119,8 +130,10 @@ async def handle_media(
async def handle_recognize_text(
client: CallAutomationClient,
call: CallStateModel,
+ text: str,
+ trigger_timeout: bool = True,
+ context: Optional[ContextEnum] = None,
style: MessageStyleEnum = MessageStyleEnum.NONE,
- text: Optional[str] = None,
store: bool = True,
) -> None:
"""
@@ -128,49 +141,79 @@ async def handle_recognize_text(
If `store` is `True`, the text will be stored in the call messages. Starts by playing text, then the "ready" sound, and finally starts recognizing the response.
"""
- if text:
- await handle_play(
+ contexts = [context] if context else []
+ chunks = await _chunk_before_tts(
+ call=call,
+ store=store,
+ style=style,
+ text=text,
+ )
+
+ for i, chunk in enumerate(chunks):
+ context = None
+ end_silence = None
+ if i == len(chunks) - 1: # Last chunk
+ end_silence = (
+ 5 # Wait 5 seconds for the user to speak and end the recognition
+ )
+ if trigger_timeout:
+ contexts.append(ContextEnum.LAST_CHUNK)
+ await _handle_recognize_media(
call=call,
client=client,
- store=store,
+ contexts=contexts,
+ end_silence=end_silence,
style=style,
- text=text,
+ text=chunk,
)
- await _handle_recognize_media(
- call=call,
- client=client,
- sound_url=CONFIG.prompts.sounds.ready(),
- )
-
-async def handle_play(
+async def handle_clear_queue(
client: CallAutomationClient,
call: CallStateModel,
- text: str,
- style: MessageStyleEnum = MessageStyleEnum.NONE,
- context: Optional[str] = None,
- store: bool = True,
) -> None:
"""
- Play a text to a call participant.
+ Clear the media queue of a call.
+ """
+ try:
+ assert call.voice_id, "Voice ID is required for recognizing media"
+ async with _use_call_client(client, call.voice_id) as call_client:
+ call_client.cancel_all_media_operations()
+ except ResourceNotFoundError:
+ _logger.debug(f"Call hung up before playing")
+ except HttpResponseError as e:
+ if "call already terminated" in e.message.lower():
+ _logger.debug(f"Call hung up before playing")
+ else:
+ raise e
- If store is True, the text will be stored in the call messages. Compatible with text larger than 400 characters, in that case the text will be split in chunks and played sequentially.
- See: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts
+async def _chunk_before_tts(
+ call: CallStateModel,
+ style: MessageStyleEnum,
+ text: str,
+ store: bool = True,
+) -> list[str]:
+ """
+ Split a text in chunks and store them in the call messages.
"""
# Sanitize text for TTS
text = re.sub(_TTS_SANITIZER_R, "", text)
# Store text in call messages
if store:
- call.messages.append(
- MessageModel(
- content=text,
- persona=MessagePersonaEnum.ASSISTANT,
- style=style,
+ if (
+ call.messages and call.messages[-1].persona == MessagePersonaEnum.ASSISTANT
+ ): # Append to last message if possible
+ call.messages[-1].content += f" {text}"
+ else:
+ call.messages.append(
+ MessageModel(
+ content=text,
+ persona=MessagePersonaEnum.ASSISTANT,
+ style=style,
+ )
)
- )
# Split text in chunks of max 400 characters, separated by sentence
chunks = []
@@ -183,27 +226,13 @@ async def handle_play(
if chunk:
chunks.append(chunk)
- # Play each chunk
- try:
- assert call.voice_id, "Voice ID is required for recognizing media"
- async with _use_call_client(client, call.voice_id) as call_client:
- for chunk in chunks:
- _logger.info(f"Playing text: {text} ({style})")
- call_client.play_media(
- operation_context=context,
- play_source=_audio_from_text(chunk, style, call),
- )
- except ResourceNotFoundError:
- _logger.debug(f"Call hung up before playing")
- except HttpResponseError as e:
- if "call already terminated" in e.message.lower():
- _logger.debug(f"Call hung up before playing")
- else:
- raise e
+ return chunks
def _audio_from_text(
- text: str, style: MessageStyleEnum, call: CallStateModel
+ call: CallStateModel,
+ style: MessageStyleEnum,
+ text: str,
) -> SsmlSource:
"""
Generate an audio source that can be read by Azure Communication Services SDK.
@@ -252,7 +281,11 @@ async def handle_recognize_ivr(
end_silence_timeout=20,
input_type=RecognizeInputType.CHOICES,
interrupt_prompt=True,
- play_prompt=_audio_from_text(text, MessageStyleEnum.NONE, call),
+ play_prompt=_audio_from_text(
+ call=call,
+ style=MessageStyleEnum.NONE,
+ text=text,
+ ),
speech_language=call.lang.short_code,
target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore
)
@@ -289,7 +322,7 @@ async def handle_transfer(
assert call.voice_id, "Voice ID is required for recognizing media"
async with _use_call_client(client, call.voice_id) as call_client:
call_client.transfer_call_to_participant(
- operation_context=context,
+ operation_context=json.dumps([context]) if context else None,
target_participant=PhoneNumberIdentifier(target),
)
except ResourceNotFoundError:
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index fd6aced..4cc71fc 100644
--- a/helpers/llm_tools.py
+++ b/helpers/llm_tools.py
@@ -1,5 +1,5 @@
from azure.communication.callautomation import CallAutomationClient
-from helpers.call_utils import ContextEnum as CallContextEnum, handle_play
+from helpers.call_utils import ContextEnum as CallContextEnum, handle_recognize_text
from helpers.config import CONFIG
from helpers.llm_utils import function_schema
from helpers.logging import build_logger
@@ -31,7 +31,6 @@ class UpdateClaimDict(TypedDict):
class LlmPlugins:
call: CallStateModel
- cancellation_callback: Callable[[], Awaitable]
client: CallAutomationClient
post_call_intelligence: Callable[[CallStateModel], None]
style: MessageStyleEnum = MessageStyleEnum.NONE
@@ -40,13 +39,11 @@ class LlmPlugins:
def __init__(
self,
call: CallStateModel,
- cancellation_callback: Callable[[], Awaitable],
client: CallAutomationClient,
post_call_intelligence: Callable[[CallStateModel], None],
user_callback: Callable[[str, MessageStyleEnum], Awaitable],
):
self.call = call
- self.cancellation_callback = cancellation_callback
self.client = client
self.post_call_intelligence = post_call_intelligence
self.user_callback = user_callback
@@ -67,12 +64,12 @@ class LlmPlugins:
- 'Goodbye, see you tomorrow'
- 'I want to hangup'
"""
- await self.cancellation_callback()
- await handle_play(
+ await handle_recognize_text(
call=self.call,
client=self.client,
context=CallContextEnum.GOODBYE,
text=await CONFIG.prompts.tts.goodbye(self.call),
+ trigger_timeout=False, # Shouldn't trigger anything, as call is ending
)
return "Call ended"
@@ -254,11 +251,11 @@ class LlmPlugins:
- 'I want to talk to a human'
- 'I want to talk to a real person'
"""
- await self.cancellation_callback()
- await handle_play(
+ await handle_recognize_text(
call=self.call,
client=self.client,
context=CallContextEnum.CONNECT_AGENT,
+ trigger_timeout=False, # Shouldn't trigger anything, as conversation with Assistant is ending
text=await CONFIG.prompts.tts.end_call_to_connect_agent(self.call),
)
return "Transferring to human agent"
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 95d43e0..9a58534 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -163,7 +163,7 @@ async def _completion_stream_worker(
extra["tools"] = tools # Add tools if any
prompt = _limit_messages(
- context=platform.context,
+ context_window=platform.context,
max_messages=20, # Quick response
max_tokens=max_tokens,
messages=messages,
@@ -293,7 +293,7 @@ async def _completion_sync_worker(
extra["response_format"] = {"type": "json_object"}
prompt = _limit_messages(
- context=platform.context,
+ context_window=platform.context,
max_tokens=max_tokens,
messages=[],
model=platform.model,
@@ -349,7 +349,7 @@ async def completion_model_sync(
def _limit_messages(
- context: int,
+ context_window: int,
max_tokens: int,
messages: list[MessageModel],
model: str,
@@ -370,7 +370,7 @@ def _limit_messages(
The context size is the maximum number of tokens allowed by the model. The messages are selected from the newest to the oldest, until the context or the maximum number of messages is reached.
"""
counter = 0
- max_context = context - max_tokens
+ max_context = context_window - max_tokens
selected_messages = []
tokens = 0
total = min(len(system) + len(messages), max_messages)