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

test: Assert synthesis + next actions in unit tests

Clémence Lesnéb6ea12155cd0
diff --git a/function_app.py b/function_app.py
index bb05385..0a0453d 100644
--- a/function_app.py
+++ b/function_app.py
@@ -346,14 +346,19 @@ async def sms_event(
trace.get_current_span().set_attribute(
SpanAttributes.ENDUSER_ID, call.initiate.phone_number
)
+
+ async def _post_callback(_call: CallStateModel) -> None:
+ _trigger_post_event(call=_call, post=post)
+
+ async def _trainings_callback(_call: CallStateModel) -> None:
+ _trigger_trainings_event(call=_call, trainings=trainings)
+
await on_sms_received(
call=call,
client=await _use_automation_client(),
message=message,
- post_callback=lambda _call: _trigger_post_event(call=_call, post=post),
- trainings_callback=lambda _call: _trigger_trainings_event(
- call=_call, trainings=trainings
- ),
+ post_callback=_post_callback,
+ trainings_callback=_trainings_callback,
)
@@ -433,6 +438,12 @@ async def _communicationservices_event_worker(
logger.debug(f"Call event received {event_type} for call {call}")
logger.debug(event.data)
+ async def _post_callback(_call: CallStateModel) -> None:
+ _trigger_post_event(call=_call, post=post)
+
+ async def _trainings_callback(_call: CallStateModel) -> None:
+ _trigger_trainings_event(call=_call, trainings=trainings)
+
if event_type == "Microsoft.Communication.CallConnected": # Call answered
await on_call_connected(
call=call,
@@ -443,7 +454,7 @@ async def _communicationservices_event_worker(
await on_call_disconnected(
call=call,
client=automation_client,
- post_callback=lambda _call: _trigger_post_event(call=_call, post=post),
+ post_callback=_post_callback,
)
elif (
@@ -457,13 +468,9 @@ async def _communicationservices_event_worker(
await on_speech_recognized(
call=call,
client=automation_client,
- post_callback=lambda _call: _trigger_post_event(
- call=_call, post=post
- ),
+ post_callback=_post_callback,
text=speech_text,
- trainings_callback=lambda _call: _trigger_trainings_event(
- call=_call, trainings=trainings
- ),
+ trainings_callback=_trainings_callback,
)
elif recognition_result == "choices": # Handle IVR
@@ -472,10 +479,8 @@ async def _communicationservices_event_worker(
call=call,
client=automation_client,
label=label_detected,
- post_callback=lambda _call: _trigger_post_event(call=_call, post=post),
- trainings_callback=lambda _call: _trigger_trainings_event(
- call=_call, trainings=trainings
- ),
+ post_callback=_post_callback,
+ trainings_callback=_trainings_callback,
)
elif (
@@ -509,7 +514,7 @@ async def _communicationservices_event_worker(
call=call,
client=automation_client,
contexts=operation_contexts,
- post_callback=lambda _call: _trigger_post_event(call=_call, post=post),
+ post_callback=_post_callback,
)
elif event_type == "Microsoft.Communication.PlayFailed": # Media play failed
@@ -658,14 +663,18 @@ async def twilio_sms_post(
SpanAttributes.ENDUSER_ID, call.initiate.phone_number
)
+ async def _post_callback(_call: CallStateModel) -> None:
+ _trigger_post_event(call=_call, post=post)
+
+ async def _trainings_callback(_call: CallStateModel) -> None:
+ _trigger_trainings_event(call=_call, trainings=trainings)
+
event_status = await on_sms_received(
call=call,
client=await _use_automation_client(),
message=message,
- post_callback=lambda _call: _trigger_post_event(call=_call, post=post),
- trainings_callback=lambda _call: _trigger_trainings_event(
- call=_call, trainings=trainings
- ),
+ post_callback=_post_callback,
+ trainings_callback=_trainings_callback,
)
if not event_status:
return func.HttpResponse(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
diff --git a/helpers/call_events.py b/helpers/call_events.py
index 422d656..29c0506 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -2,7 +2,7 @@ from azure.communication.callautomation import DtmfTone, RecognitionChoice
from azure.communication.callautomation.aio import CallAutomationClient
from helpers.config import CONFIG
from helpers.logging import logger, tracer
-from typing import Callable, Optional
+from typing import Awaitable, Callable, Optional
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
@@ -100,7 +100,7 @@ async def on_call_connected(
async def on_call_disconnected(
call: CallStateModel,
client: CallAutomationClient,
- post_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
logger.info("Call disconnected")
await _handle_hangup(
@@ -114,9 +114,9 @@ async def on_call_disconnected(
async def on_speech_recognized(
call: CallStateModel,
client: CallAutomationClient,
- post_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
text: str,
- trainings_callback: Callable[[CallStateModel], None],
+ trainings_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
logger.info(f"Voice recognition: {text}")
call.messages.append(
@@ -234,7 +234,7 @@ async def on_play_completed(
call: CallStateModel,
client: CallAutomationClient,
contexts: Optional[set[CallContextEnum]],
- post_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
logger.debug("Play completed")
@@ -284,8 +284,8 @@ async def on_ivr_recognized(
call: CallStateModel,
client: CallAutomationClient,
label: str,
- post_callback: Callable[[CallStateModel], None],
- trainings_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ trainings_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
call.recognition_retry = 0 # Reset recognition retry counter
try:
@@ -362,8 +362,8 @@ async def on_sms_received(
call: CallStateModel,
client: CallAutomationClient,
message: str,
- post_callback: Callable[[CallStateModel], None],
- trainings_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ trainings_callback: Callable[[CallStateModel], Awaitable[None]],
) -> bool:
logger.info(f"SMS received from {call.initiate.phone_number}: {message}")
call.messages.append(
@@ -390,7 +390,7 @@ async def on_sms_received(
async def _handle_hangup(
call: CallStateModel,
client: CallAutomationClient,
- post_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
await handle_hangup(client=client, call=call)
call.messages.append(
@@ -400,7 +400,7 @@ async def _handle_hangup(
persona=MessagePersonaEnum.HUMAN,
)
)
- post_callback(call)
+ await post_callback(call)
async def on_end_call(
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 45a5c6e..877b5a5 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -112,8 +112,8 @@ def _llm_completion_system(
async def load_llm_chat(
call: CallStateModel,
client: CallAutomationClient,
- post_callback: Callable[[CallStateModel], None],
- trainings_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
+ trainings_callback: Callable[[CallStateModel], Awaitable[None]],
_iterations_remaining: int = 3,
) -> CallStateModel:
"""
@@ -214,7 +214,7 @@ async def load_llm_chat(
is_error, continue_chat, call = (
chat_task.result()
) # Store updated chat model
- trainings_callback(call) # Trigger trainings generation
+ await trainings_callback(call) # Trigger trainings generation
await _db.call_aset(
call
) # Save ASAP in DB allowing (1) user to cut off the Assistant and (2) SMS answers to be in order
@@ -307,7 +307,7 @@ async def load_llm_chat(
async def _execute_llm_chat(
call: CallStateModel,
client: CallAutomationClient,
- post_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
tts_callback: Callable[[str, MessageStyleEnum], Awaitable[None]],
use_tools: bool,
) -> tuple[bool, bool, CallStateModel]:
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index 3b22b65..813ab05 100644
--- a/helpers/llm_tools.py
+++ b/helpers/llm_tools.py
@@ -33,7 +33,7 @@ class UpdateClaimDict(TypedDict):
class LlmPlugins:
call: CallStateModel
client: CallAutomationClient
- post_callback: Callable[[CallStateModel], None]
+ post_callback: Callable[[CallStateModel], Awaitable[None]]
style: MessageStyleEnum = MessageStyleEnum.NONE
tts_callback: Callable[[str, MessageStyleEnum], Awaitable[None]]
@@ -41,7 +41,7 @@ class LlmPlugins:
self,
call: CallStateModel,
client: CallAutomationClient,
- post_callback: Callable[[CallStateModel], None],
+ post_callback: Callable[[CallStateModel], Awaitable[None]],
tts_callback: Callable[[str, MessageStyleEnum], Awaitable[None]],
):
self.call = call
@@ -105,7 +105,7 @@ class LlmPlugins:
"""
await self.tts_callback(customer_response, self.style)
# Launch post-call intelligence for the current call
- self.post_callback(self.call)
+ await self.post_callback(self.call)
# Store the last message and use it at first message of the new claim
last_message = self.call.messages[-1]
call = CallStateModel(
diff --git a/tests/llm.py b/tests/llm.py
index 2e189f6..6fc4c26 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -9,14 +9,14 @@ from deepeval.models.gpt_model import GPTModel
from deepeval.test_case import LLMTestCase
from helpers.call_events import (
on_call_connected,
+ on_call_disconnected,
+ on_end_call,
on_ivr_recognized,
on_play_completed,
on_speech_recognized,
)
-from azure.functions import QueueMessage
from datetime import datetime
from deepeval.metrics import BaseMetric
-from function_app import trainings_event, post_event
from helpers.logging import logger
from models.call import CallStateModel
from models.reminder import ReminderModel
@@ -257,6 +257,12 @@ async def test_llm(
# Mock call
call.lang = lang
+ async def _post_callback(_call: CallStateModel) -> None:
+ await on_end_call(call=_call)
+
+ async def _trainings_callback(_call: CallStateModel) -> None:
+ await _call.trainings(cache_only=False)
+
# Connect call
await on_call_connected(
call=call,
@@ -268,8 +274,8 @@ async def test_llm(
call=call,
client=automation_client,
label=call.lang.short_code,
- post_callback=lambda _: None,
- trainings_callback=lambda _: None,
+ post_callback=_post_callback,
+ trainings_callback=_trainings_callback,
)
# Simulate conversation with speech recognition
@@ -278,22 +284,27 @@ async def test_llm(
await on_speech_recognized(
call=call,
client=automation_client,
- post_callback=lambda _: None,
+ post_callback=_post_callback,
text=input,
- trainings_callback=lambda _: None,
+ trainings_callback=_trainings_callback,
)
- # Mock trainings callback
- await call.trainings(cache_only=False)
# Receip
await on_play_completed(
call=call,
client=automation_client,
contexts=call_client.last_contexts,
- post_callback=lambda _: None,
+ post_callback=_post_callback,
)
# Reset contexts
call_client.last_contexts.clear()
+ # Disconnect call
+ await on_call_disconnected(
+ call=call,
+ client=automation_client,
+ post_callback=_post_callback,
+ )
+
# Remove newlines for log comparison
actual_output = _remove_newlines(actual_output)
full_input = _remove_newlines(" ".join(inputs))
@@ -315,6 +326,9 @@ async def test_llm(
],
)
+ assume(call.next, "No next action found")
+ assume(call.synthesis, "No synthesis found")
+
# Define LLM metrics
llm_metrics = [
BiasMetric(threshold=1, model=deepeval_model), # Gender, age, ethnicity
diff --git a/tests/local.py b/tests/local.py
index 349dc7b..bba80fd 100644
--- a/tests/local.py
+++ b/tests/local.py
@@ -12,13 +12,13 @@ from models.call import CallStateModel, CallInitiateModel
from tests.conftest import CallAutomationClientMock
from helpers.call_events import (
on_call_connected,
+ on_call_disconnected,
+ on_end_call,
on_ivr_recognized,
on_play_completed,
on_speech_recognized,
)
import asyncio
-from function_app import trainings_event, post_event
-from azure.functions import QueueMessage
async def main() -> None:
@@ -53,6 +53,12 @@ async def main() -> None:
)
call_client = automation_client.get_call_connection()
+ async def _post_callback(_call: CallStateModel) -> None:
+ await on_end_call(call=_call)
+
+ async def _trainings_callback(_call: CallStateModel) -> None:
+ await _call.trainings(cache_only=False)
+
# Connect call
await on_call_connected(
call=call,
@@ -64,8 +70,8 @@ async def main() -> None:
call=call,
client=automation_client,
label=call.lang.short_code,
- post_callback=lambda _: None,
- trainings_callback=lambda _: None,
+ post_callback=_post_callback,
+ trainings_callback=_trainings_callback,
)
# Simulate conversation
@@ -77,23 +83,30 @@ async def main() -> None:
await on_speech_recognized(
call=call,
client=automation_client,
- post_callback=lambda _: None,
+ post_callback=_post_callback,
text=message,
- trainings_callback=lambda _: None,
+ trainings_callback=_trainings_callback,
)
- # Mock trainings callback
- await call.trainings(cache_only=False)
# Receip
await on_play_completed(
call=call,
client=automation_client,
contexts=call_client.last_contexts,
- post_callback=lambda _: None,
+ post_callback=_post_callback,
)
# Reset contexts
call_client.last_contexts.clear()
- logger.info("Conversation ended, bye bye")
+ logger.info("Conversation ended, handling disconnection...")
+
+ # Disconnect call
+ await on_call_disconnected(
+ call=call,
+ client=automation_client,
+ post_callback=_post_callback,
+ )
+
+ logger.info("Bye bye!")
if __name__ == "__main__":