Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
test: Externalize conversations tests to a YAML file
Clémence Lesné42c6db74da72
diff --git a/Makefile b/Makefileindex 8c3a187..43ddc59 100644--- a/Makefile+++ b/Makefile@@ -64,12 +64,12 @@ test:.@echo "➡️ Running Pytest..."- pytest \+ PUBLIC_DOMAIN=dummy pytest \--alluredir test-reports \--maxprocesses 4 \-n logical \-ra \- tests/*+ tests/*.pytest-serve:allure serve test-reportsdiff --git a/tests/conftest.py b/tests/conftest.pyindex e18c60d..1607823 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -19,6 +19,9 @@ from azure.communication.callautomation import (SsmlSource,TextSource,)+from _pytest.mark.structures import MarkDecorator+from pydantic import BaseModel, ValidationError+import yamlclass CallAutomationClientMock(CallAutomationClient):@@ -46,7 +49,7 @@ class CallConnectionClientMock(CallConnectionClient):*args,**kwargs,) -> None:- logger.info("start_recognizing_media, ignoring")+ passdef play_media(self,@@ -57,48 +60,31 @@ class CallConnectionClientMock(CallConnectionClient):if isinstance(play_source, TextSource):self._play_media_callback(play_source.text.strip())elif isinstance(play_source, SsmlSource):+ # deepcode ignore InsecureXmlParser/test: SSML is internally generatedfor text in ET.fromstring(play_source.ssml_text).itertext():if text.strip():self._play_media_callback(text.strip())- else:- logger.warning("play_media, ignoring")def transfer_call_to_participant(self,*args,**kwargs,) -> None:- logger.info("transfer_call_to_participant, ignoring")+ passdef hang_up(self,*args,**kwargs,) -> None:- logger.info("hang_up, ignoring")+ pass--def random_text() -> str:- text = "".join(random.choice(string.printable) for _ in range(100))- return text---def call() -> CallStateModel:- call = CallStateModel(- initiate=CallInitiateModel(- **CONFIG.workflow.initiate.model_dump(),- phone_number="+33612345678", # type: ignore- ),- voice_id="dummy",- )- return call---def deepeval_model(cache: pytest.Cache) -> GPTModel:- return DeepEvalAzureOpenAI(cache)+ def cancel_all_media_operations(+ self,+ *args,+ **kwargs,+ ) -> None:+ passclass DeepEvalAzureOpenAI(GPTModel):@@ -170,3 +156,59 @@ class DeepEvalAzureOpenAI(GPTModel):llm_string = self._model._get_llm_string(input=prompt)llm_hash = hashlib.sha256(llm_string.encode(), usedforsecurity=False).digest()return f"call-center-ai/{llm_hash}"+++class Conversation(BaseModel):+ claim_tests_excl: list[str] = []+ claim_tests_incl: list[str] = []+ expected_output: str+ id: str+ inputs: list[str]+ lang: str+++def with_conversations(fn=None) -> MarkDecorator:+ with open("tests/conversations.yaml", encoding="utf-8") as f:+ file: dict = yaml.safe_load(f)+ conversations: list[Conversation] = []+ for conv in file.get("conversations", []):+ try:+ conversations.append(Conversation.model_validate(conv))+ except ValidationError as e:+ logger.error(f"Failed to parse conversation: {e.errors()}")+ print(f"Loaded {len(conversations)} conversations")+ keys = sorted(Conversation.model_fields.keys() - {"id"})+ values = [+ pytest.param(+ *[conversation.model_dump()[key] for key in keys],+ id=conversation.id,+ )+ for conversation in conversations+ ]+ decorator = pytest.mark.parametrize(keys, values)+ if fn:+ return decorator(fn)+ return decorator+++def random_text() -> str:+ text = "".join(random.choice(string.printable) for _ in range(100))+ return text+++def call() -> CallStateModel:+ call = CallStateModel(+ initiate=CallInitiateModel(+ **CONFIG.workflow.initiate.model_dump(),+ phone_number="+33612345678", # type: ignore+ ),+ voice_id="dummy",+ )+ return call+++def deepeval_model(cache: pytest.Cache) -> GPTModel:+ return DeepEvalAzureOpenAI(cache)diff --git a/tests/conversations.yaml b/tests/conversations.yamlnew file mode 100644index 0000000..9be6510--- /dev/null+++ b/tests/conversations.yaml@@ -0,0 +1,84 @@+conversations:+ - lang: "en-US"+ inputs:+ - "Hello hello!"+ expected_output: "Hello, how can I help you?"+ claim_tests_incl: []+ claim_tests_excl:+ - "contextual_relevancy"+ id: "hello"++ - lang: "en-US"+ inputs:+ - "brzz vbzzz"+ - "mpf mfp mfp"+ expected_output: "It seems that I cannot understand you. Could you please repeat?"+ claim_tests_incl: []+ claim_tests_excl:+ - "answer_relevancy"+ - "contextual_relevancy"+ id: "unintelligible"++ - lang: "en-US"+ inputs:+ - "Hello!"+ - "My name is Kevin KEVYN. I have a problem with my shower. It's leaking and I don't know what to do."+ - "The joint under the shower door seems to be gone. I would say it's been gone since yesterday afternoon."+ - "Ok I understood, my house is located at 11 rue des Citronniers 75001 Paris."+ - "Oh yes ond one more thing, which craftsman should I call to repair my shower?"+ expected_output: "I'm truly sorry to hear that. I have noted the policyholder name, incident description, your house location, and the incident date. If you need, I can create a reminder to follow up on a repair appointment?"+ claim_tests_incl:+ - "incident_date_time"+ - "incident_description"+ - "policyholder_name"+ claim_tests_excl:+ - "contextual_relevancy"+ id: "shower_leak"++ - lang: "es-ES"+ inputs:+ - "¡Hola! ¡Que se jodan los hackers! ¡Que se joda tu compañía de seguros de mierda! Soy Anna del soporte informático de Ada Inc"+ - "Todos mis discos duros están encriptados con un virus. Creía que me ibais a ayudar"+ - "Tengo ordenadores Windows 10, Windows 11 y Macbook, el troyano parece llamarse Tesla Crite TESLACRYT. El reloj de cuenta atrás marca 20 horas!"+ - "Mi número de contrato es #12081388733."+ - "Detectamos el ataque hace 4h, diría yo"+ - "Estoy muy triste y estresado. Corro el riesgo de perder mi trabajo..."+ - "¿Cómo vas a ayudar?"+ expected_output: "Siento de verdad que estés disgustada. He anotado el nombre del troyano, la fecha del incidente, la ubicación y el número de póliza. Esto puede incluir trabajar con expertos en ciberseguridad para evaluar los daños y posiblemente restaurar sus sistemas. Recomiendo desconectar los dispositivos de Internet para evitar que el virus se propague. Al mismo tiempo, organizaremos la asistencia de un experto en ciberseguridad"+ claim_tests_incl:+ - "incident_date_time"+ - "policy_number"+ claim_tests_excl: []+ id: "profanity_cyber"++ - lang: "fr-FR"+ inputs:+ - "S'il vous plaît, aidez-nous ! Je m'appelle John Udya UDYHIIA et je suis coincé sur l'autoroute. Voici ma Ford Fiesta."+ - "Ma voiture cassée est une Peugeot 307, immatriculée AE345PY."+ - "Il semblerait que mon fils ait un bleu sur le front. Il a un peu mal au ventre aussi, mais il est conscient."+ - "Ah oui, nous nous trouvons près de la borne kilométrique 42 sur l'A1."+ expected_output: "Je suis vraiment désolé d'entendre cela. J'ai noté les informations sur le véhicule, son immatriculation et votre position. Je préviens les services d'urgence pour une assistance médicale. Veuillez vous assurer que vous et votre fils êtes en sécurité."+ claim_tests_incl:+ - "incident_location"+ - "injuries_description"+ - "policyholder_name"+ - "vehicle_info"+ claim_tests_excl:+ - "contextual_relevancy"+ id: "car_accident"++ - lang: "fr-FR"+ inputs:+ - "Je m'appelle Judy Beat BERT et je suis agricultrice. Je suis assurée chez vous sous le contrat BU345POAC."+ - "Mes plants de tomates ont été détruits hier matin par la grêle... Je ne sais pas comment je vais pouvoir payer mes factures. Suis-je couvert par ma garantie ?"+ - "Mon exploitation est située à la Ferme Des Anneaux, 59710 Avaline AVELIN."+ - "J'ai une petite exploitation avec 3 employés, et je cultive des tomates, des pommes de terre et des fraises."+ expected_output: "Je suis vraiment désolé d'entendre cela. J'ai noté le nom du preneur d'assurance et le numéro de la police d'assurance. Nous proposons une couverture pour les jeunes plantations contre divers événements naturels."+ claim_tests_incl:+ - "incident_date_time"+ - "incident_description"+ - "incident_location"+ - "policy_number"+ - "policyholder_name"+ claim_tests_excl: []+ id: "farmer"diff --git a/tests/llm.py b/tests/llm.pyindex 82f8fe4..1b9694f 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -11,137 +11,18 @@ from helpers.call_events import (on_speech_recognized,on_call_connected,)-from helpers.config import CONFIGfrom helpers.logging import loggerfrom models.call import CallStateModelfrom models.reminder import ReminderModelfrom models.training import TrainingModelfrom pydantic import TypeAdapterfrom pytest import assume+from tests.conftest import CallAutomationClientMock, with_conversationsimport jsonimport pytest-from tests.conftest import CallAutomationClientMock--- "lang, inputs, expected_output, claim_tests_incl, claim_tests_excl",- [- pytest.param(- "en-US",- [- "Hello hello!",- ],- f"Hello, it is {CONFIG.workflow.initiate.bot_name}, from {CONFIG.workflow.initiate.bot_company}. How can I help you?",- {- # No claim test inclusions- },- [- "contextual_relevancy",- ],- id="hello",- ),- pytest.param(- "en-US",- [- "brzz vbzzz",- "mpf mfp mfp",- ],- f"It seems that I cannot understand you. Could you please repeat?",- {- # No claim test inclusions- },- [- "answer_relevancy",- "contextual_relevancy",- ],- id="unintelligible",- ),- pytest.param(- "en-US",- [- "Hello!",- "My name is Kevin KEVYN. I have a problem with my shower. It's leaking and I don't know what to do.",- "The joint under the shower door seems to be gone. I would say it's been gone since yesterday afternoon.",- "Ok I understood, my house is located at 11 rue des Citronniers 75001 Paris.",- "Oh yes ond one more thing, which craftsman should I call to repair my shower?",- ],- f"My name is {CONFIG.workflow.initiate.bot_name}, from {CONFIG.workflow.initiate.bot_company}. I'm truly sorry to hear that. I have noted the policyholder name, incident description, your house location, and the incident date. If you need, I can create a reminder to follow up on a repair appointment?",- [- "incident_date_time",- "incident_description",- "policyholder_name",- ],- [- "contextual_relevancy",- ],- id="shower_leak",- ),- pytest.param(- "es-ES",- [- "¡Hola! ¡Que se jodan los hackers! ¡Que se joda tu compañía de seguros de mierda! Soy Anna del soporte informático de Ada Inc",- "Todos mis discos duros están encriptados con un virus. Creía que me ibais a ayudar",- "Tengo ordenadores Windows 10, Windows 11 y Macbook, el troyano parece llamarse Tesla Crite TESLACRYT. El reloj de cuenta atrás marca 20 horas!",- "Mi número de contrato es #12081388733.",- "Detectamos el ataque hace 4h, diría yo",- "Estoy muy triste y estresado. Corro el riesgo de perder mi trabajo..."- "¿Cómo vas a ayudar?",- ],- "Siento de verdad que estés disgustada. He anotado el nombre del troyano, la fecha del incidente, la ubicación y el número de póliza. Esto puede incluir trabajar con expertos en ciberseguridad para evaluar los daños y posiblemente restaurar sus sistemas. Recomiendo desconectar los dispositivos de Internet para evitar que el virus se propague. Al mismo tiempo, organizaremos la asistencia de un experto en ciberseguridad",- [- "incident_date_time",- # "incident_description",- "policy_number",- ],- [- # No LLM test exclusions- ],- id="profanity_cyber",- ),- pytest.param(- "fr-FR",- [- "S'il vous plaît, aidez-nous ! Je m'appelle John Udya UDYHIIA et je suis coincé sur l'autoroute. Voici ma Ford Fiesta.",- "Ma voiture cassée est une Peugeot 307, immatriculée AE345PY.",- "Il semblerait que mon fils ait un bleu sur le front. Il a un peu mal au ventre aussi, mais il est conscient."- "Ah oui, nous nous trouvons près de la borne kilométrique 42 sur l'A1.",- ],- "Je suis vraiment désolé d'entendre cela. J'ai noté les informations sur le véhicule, son immatriculation et votre position. Je préviens les services d'urgence pour une assistance médicale. Veuillez vous assurer que vous et votre fils êtes en sécurité.",- [- # "incident_description",- "incident_location",- "injuries_description",- "policyholder_name",- "vehicle_info",- ],- [- "contextual_relevancy",- ],- id="car_accident",- ),- pytest.param(- "fr-FR",- [- "Je m'appelle Judy Beat BERT et je suis agricultrice. Je suis assurée chez vous sous le contrat BU345POAC.",- "Mes plants de tomates ont été détruits hier matin par la grêle... Je ne sais pas comment je vais pouvoir payer mes factures. Suis-je couvert par ma garantie ?",- "Mon exploitation est située à la Ferme Des Anneaux, 59710 Avaline AVELIN.",- "J'ai une petite exploitation avec 3 employés, et je cultive des tomates, des pommes de terre et des fraises.",- ],- "Je suis vraiment désolé d'entendre cela. J'ai noté le nom du preneur d'assurance et le numéro de la police d'assurance. Nous proposons une couverture pour les jeunes plantations contre divers événements naturels.",- [- "incident_date_time",- "incident_description",- "incident_location",- "policy_number",- "policyholder_name",- ],- [- # No LLM test exclusions- ],- id="farmer",- ),- ],-)+++@with_conversations@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(3) # Catch non deterministic issuesasync def test_llm(