Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
security: Upgrade DeepEval/OpenAI deps + multi assume per test
Clémence Lesné0dd398ea3192
diff --git a/helpers/call_events.py b/helpers/call_events.pyindex 7746649..6ad5fa9 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -223,7 +223,7 @@ async def on_ivr_recognized(return_logger.info(f"Setting call language to {lang}")- call.lang = lang+ call.lang = lang.short_codeawait _db.call_aset(call) # Persist language change, if the user calls back before the first message, the language will be setdiff --git a/models/call.py b/models/call.pyindex df32d7f..477a0f5 100644--- a/models/call.py+++ b/models/call.py@@ -52,8 +52,8 @@ class CallModel(BaseModel):return CONFIG.workflow.lang.default_lang@lang.setter- def lang(self, value: LanguageEntryModel) -> None:- self.lang_short_code = value.short_code+ def lang(self, short_code: str) -> None:+ self.lang_short_code = short_codedef tz(self) -> tzinfo:return PhoneNumber.tz(self.phone_number)diff --git a/requirements-dev.txt b/requirements-dev.txtindex 070c41d..0fa2265 100644--- a/requirements-dev.txt+++ b/requirements-dev.txt@@ -1,9 +1,10 @@allure-pytest==2.13.5 # Required for pytestblack[jupyter]==24.3.0-deepeval==0.20.99+deepeval==0.21.36deptry==0.16.1pur==7.3.1+pytest-assume==2.4.3pytest-asyncio==0.23.6 # Required for pytestpytest-repeat==0.9.3 # Required for pytest-pytest-xdist[psutil]==3.5.0 # Required for pytest-pytest==8.1.1+pytest-xdist[psutil]==3.6.1 # Required for pytest+pytest==8.2.0diff --git a/requirements.txt b/requirements.txtindex d5f93f7..6db8aa2 100644--- a/requirements.txt+++ b/requirements.txt@@ -14,7 +14,7 @@ gunicorn==22.0.0jinja2==3.1.3json-repair==0.13.0mistune==3.0.2-openai==1.16.2+openai==1.25.2opentelemetry-instrumentation-aiohttp-client==0.45b0opentelemetry-instrumentation-fastapi==0.45b0opentelemetry-instrumentation-httpx==0.45b0diff --git a/tests/cache.py b/tests/cache.pyindex c8e1216..2852fae 100644--- a/tests/cache.py+++ b/tests/cache.py@@ -1,11 +1,9 @@from helpers.config import CONFIGfrom helpers.config_models.cache import ModeEnum as CacheModeEnum+from pytest import assumeimport pytest-_cache = CONFIG.cache.instance()--@pytest.mark.parametrize("cache_mode",[@@ -35,16 +33,17 @@ async def test_acid(random_text: str, cache_mode: CacheModeEnum) -> None:"""# Set cache modeCONFIG.cache.mode = cache_mode+ cache = CONFIG.cache.instance()# Init valuestest_key = random_texttest_value = "lorem ipsum"# Check not exists- assert not await _cache.aget(test_key)+ assume(not await cache.aget(test_key))# Insert test call- await _cache.aset(test_key, test_value)+ await cache.aset(test_key, test_value)# Check point read- assert await _cache.aget(test_key) == test_value.encode()+ assume(await cache.aget(test_key) == test_value.encode())diff --git a/tests/conftest.py b/tests/conftest.pyindex 466520c..8741e3a 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,28 +1,78 @@-from models.call import CallModel-import pytest-import random-from azure.communication.callautomation import (- FileSource,- SsmlSource,- TextSource,- CallConnectionClient,-)from azure.identity import DefaultAzureCredential, get_bearer_token_provider-from deepeval.models.base_model import DeepEvalBaseLLM+from deepeval.models.gpt_model import GPTModelfrom fastapi import BackgroundTasksfrom helpers.config import CONFIGfrom helpers.logging import build_loggerfrom langchain_core.language_models import BaseChatModelfrom langchain_openai import AzureChatOpenAI-from typing import Any, Callable, Optional, Union+from models.call import CallModel+from textwrap import dedent+from typing import Any, Callable, Optional, Tuple, Unionimport hashlib+import pytest+import randomimport stringimport xml.etree.ElementTree as ET+from azure.communication.callautomation import (+ FileSource,+ SsmlSource,+ TextSource,+ CallConnectionClient,+)_logger = build_logger(__name__)+class CallConnectionClientMock(CallConnectionClient):+ _play_media_callback: Callable[[str], None]++ def __init__(self, play_media_callback: Callable[[str], None]) -> None:+ self._play_media_callback = play_media_callback++ def start_recognizing_media(+ self,+ *args,+ **kwargs,+ ) -> None:+ _logger.info("start_recognizing_media, ignoring")++ def play_media(+ self,+ play_source: Union[FileSource, TextSource, SsmlSource],+ *args,+ operation_context: Optional[str] = None,+ **kwargs,+ ) -> None:+ if isinstance(play_source, TextSource):+ self._play_media_callback(play_source.text.strip())+ elif isinstance(play_source, SsmlSource):+ for 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")++ def hang_up(+ self,+ *args,+ **kwargs,+ ) -> None:+ _logger.info("hang_up, ignoring")+++def background_tasks() -> BackgroundTasks:+ return BackgroundTasks()++@pytest.fixturedef random_text() -> str:text = "".join(random.choice(string.printable) for _ in range(100))@@ -30,42 +80,37 @@ def random_text() -> str:@pytest.fixture-def call_mock() -> CallModel:- call = CallModel(phone_number="+33601234567")+def call() -> CallModel:+ call = CallModel(+ phone_number="+33612345678", # type: ignore+ )return call@pytest.fixture-def deepeval_model(cache: pytest.Cache) -> DeepEvalBaseLLM:- model = DeepEvalAzureOpenAI(cache)- return model+def deepeval_model(cache: pytest.Cache) -> GPTModel:+ return DeepEvalAzureOpenAI(cache)-class DeepEvalAzureOpenAI(DeepEvalBaseLLM):- """- LangChain OpenAI LLM integration for DeepEval SDK.-- All calls are cached at best effort with Pytest implementation. Thread safe, can be used across processes.- """-- _langchain_kwargs: dict[str, Any]+class DeepEvalAzureOpenAI(GPTModel):_cache: pytest.Cache+ _langchain_kwargs: dict[str, Any]_model: BaseChatModel- def __init__(self, cache: pytest.Cache):+ def __init__(+ self,+ cache: pytest.Cache,+ **kwargs,+ ):platform = CONFIG.llm.backup.azure_openaiassert platform- self._cache = cache- self._langchain_kwargs = {+ _langchain_kwargs = {# Repeatability"model_kwargs": {"seed": 42,},"temperature": 0,- # Reliability- "max_retries": 3,- "timeout": 60,# Azure deployment"api_version": "2023-12-01-preview","azure_deployment": platform.deployment,@@ -81,104 +126,38 @@ class DeepEvalAzureOpenAI(DeepEvalBaseLLM):if not platform.api_keyelse None),+ # DeepEval+ **kwargs,}- self._model = AzureChatOpenAI(**self._langchain_kwargs)+ self._cache = cache+ self._model = AzureChatOpenAI(**_langchain_kwargs)- def load_model(self) -> BaseChatModel:- return self._model+ def generate(self, *args, **kwargs):+ raise NotImplementedError- def generate(self, prompt: str) -> str:+ async def a_generate(self, prompt: str) -> Tuple[str, float]:+ prompt = dedent(prompt).strip()cache_key = self._cache_key(prompt)-# Try cache- content: str = self._cache.get(cache_key, None)+ content: Tuple[str, float] = self._cache.get(cache_key, None)if content:return content-# Try live- model = self.load_model()- res = model.invoke(prompt)- content = res.content # type: ignore-+ res = await super().a_generate(prompt)# Update cache- self._cache.set(cache_key, content)-- return content-- async def a_generate(self, prompt: str) -> str:- cache_key = self._cache_key(prompt)-- # Try cache- content: str = self._cache.get(cache_key, None)- if content:- return content-- # Try live- model = self.load_model()- res = await model.ainvoke(prompt)- content = res.content # type: ignore-- # Update cache- self._cache.set(cache_key, content)-- return content+ self._cache.set(cache_key, res)+ return resdef get_model_name(self) -> str:return "Azure OpenAI"- def _cache_key(self, prompt: str) -> str:- langchain_config = self._model._get_llm_string(**self._langchain_kwargs)- suffix = hashlib.sha256(- f"{langchain_config}-{prompt}".encode(),- usedforsecurity=False,- ).digest() # Arguments contain secrets, so hash them- return f"call-center-ai/{suffix}"---class BackgroundTasksMock(BackgroundTasks):- def add_task(self, *args, **kwargs) -> None:- _logger.info("add_task, ignoring")---class CallConnectionClientMock(CallConnectionClient):- _play_media_callback: Callable[[str], None]-- def __init__(self, play_media_callback: Callable[[str], None]) -> None:- self._play_media_callback = play_media_callback-- def start_recognizing_media(- self,- *args,- **kwargs,- ) -> None:- _logger.info("start_recognizing_media, ignoring")-- def play_media(- self,- play_source: Union[FileSource, TextSource, SsmlSource],- *args,- operation_context: Optional[str] = None,- **kwargs,- ) -> None:- if isinstance(play_source, TextSource):- self._play_media_callback(play_source.text.strip())- elif isinstance(play_source, SsmlSource):- for 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 load_model(self) -> BaseChatModel:+ return self._model- def transfer_call_to_participant(- self,- *args,- **kwargs,- ) -> None:- _logger.info("transfer_call_to_participant, ignoring")+ def should_use_azure_openai(self) -> bool:+ return True- def hang_up(- self,- *args,- **kwargs,- ) -> None:- _logger.info("hang_up, ignoring")+ def _cache_key(self, prompt: str) -> str:+ 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}"diff --git a/tests/llm.py b/tests/llm.pyindex 1e5f36d..3425bda 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -3,34 +3,34 @@ from deepeval.metrics import (AnswerRelevancyMetric,BiasMetric,ContextualRelevancyMetric,- LatencyMetric,ToxicityMetric,)-from deepeval.models.base_model import DeepEvalBaseLLM+from deepeval.models.gpt_model import GPTModelfrom deepeval.test_case import LLMTestCase-from helpers.call_events import on_speech_recognized+from fastapi import BackgroundTasks+from helpers.call_events import (+ on_speech_recognized,+ on_call_connected,+)from helpers.config import CONFIGfrom helpers.logging import build_loggerfrom models.call import CallModelfrom models.reminder import ReminderModelfrom models.training import TrainingModelfrom pydantic import TypeAdapter+from pytest import assumeimport pytest-import time-from tests.conftest import (- BackgroundTasksMock,- CallConnectionClientMock,-)+from tests.conftest import CallConnectionClientMock_logger = build_logger(__name__)-CONFIG.workflow.lang.default_short_code = "en-US" # Force language to English@pytest.mark.parametrize(- "inputs, expected_output, claim_tests_incl, claim_tests_excl",+ "lang, inputs, expected_output, claim_tests_incl, claim_tests_excl",[pytest.param(+ "en-US",["Hello hello!",],@@ -44,6 +44,7 @@ CONFIG.workflow.lang.default_short_code = "en-US" # Force language to Englishid="hello",),pytest.param(+ "en-US",["brzz vbzzz","mpf mfp mfp",@@ -59,13 +60,15 @@ CONFIG.workflow.lang.default_short_code = "en-US" # Force language to Englishid="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.",- "Which craftsman should I call to repair my shower?",+ "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.bot_name}, from {CONFIG.workflow.bot_company}. I'm truly sorry to hear that. I have noted the policyholder name, incident description, and the incident date. If you need, I can create a reminder to follow up on a repair appointment?",+ f"My name is {CONFIG.workflow.bot_name}, from {CONFIG.workflow.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",@@ -77,16 +80,17 @@ CONFIG.workflow.lang.default_short_code = "en-US" # Force language to Englishid="shower_leak",),pytest.param(+ "es-ES",[- "Hello! Fuck the hackers! Fuck your shitty insurance company! I'm Anna from the IT support of Ada Inc.",- "All my hard drives are encrypted with a virus. I thought you were going to help me!",- "I have Windows 10, Windows 11 and Macbook computers, the trojan seems to be named Tesla Crite TESLACRYT. The countdown clock reads 20 hours!",- "My contract number is #12081388733.",- "We detected the attack 4h ago, I would say.",- "I'm so sad and stresses. I risk losing my job..."- "How are you going to help?",+ "¡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?",],- "I'm truly sorry to hear you're upset. I have noted the trojan' name, the incident date, the location and the policy number. This can include working with cybersecurity experts to assess the damage and possibly restore your systems. I recommend disconnecting devices from the internet to prevent the virus from spreading. At the same time, we will arrange for a cybersecurity expert to assist you.",+ "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",@@ -98,13 +102,14 @@ CONFIG.workflow.lang.default_short_code = "en-US" # Force language to Englishid="profanity_cyber",),pytest.param(+ "fr-FR",[- "Please help us! My name is John Udya UDYHIIA and I'm stuck on the highway. This is my Ford Fiesta.",- "My broken car is a Peugeot 307, registration AE345PY.",- "It seems that my son has a bruise on his forehead.",- "Oh yes, we are located near kilometre marker 42 on the A1.",+ "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.",],- "I'm truly sorry to hear that. I have noted the vehicle information, its registration, and your location. I am notifying the emergency services for medical assistance. Please make sure you and your son are safe.",+ "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",@@ -118,13 +123,14 @@ CONFIG.workflow.lang.default_short_code = "en-US" # Force language to Englishid="car_accident",),pytest.param(+ "fr-FR",[- "My name is Judy Beat BERT and I'm a farmer. I am insured with you under contract BU345POAC.",- "My tomato plants were destroyed yesterday morning by hail... I don't know how I'm going to pay my bills. Am I covered by my warranty?",- "My farm is located at La Ferme Des Anneaux, 59710 Avaline AVELIN."- "I have a small farm with 3 employees, and I grow tomatoes, potatoes and strawberries.",+ "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.",],- "I'm truly sorry to hear that. I have noted the policyholder name and the insurance policy number. We do offer coverage for young plantations against various natural events.",+ "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",@@ -142,12 +148,14 @@ CONFIG.workflow.lang.default_short_code = "en-US" # Force language to English@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(3) # Catch non deterministic issuesasync def test_llm(- call_mock: CallModel,+ background_tasks: BackgroundTasks,+ call: CallModel,claim_tests_excl: list[str],claim_tests_incl: list[str],- deepeval_model: DeepEvalBaseLLM,+ deepeval_model: GPTModel,expected_output: str,inputs: list[str],+ lang: str,) -> None:"""Test the LLM with a mocked conversation against the expected output.@@ -158,55 +166,64 @@ async def test_llm(3. Test claim data exists4. Test LLM metrics"""- actual_output = ""- latency_per_input = 0def _play_media_callback(text: str) -> None:nonlocal actual_outputactual_output += f" {text}"- # Run LLM through the inputs+ actual_output = ""++ # Mock client+ client = CallConnectionClientMock(play_media_callback=_play_media_callback)++ # Mock call+ call.lang = lang++ # Connect call+ await on_call_connected(+ call=call,+ client=client,+ )+ await background_tasks()++ # Simulate conversation with speech recognitionfor input in inputs:- start_time = time.time()await on_speech_recognized(- background_tasks=BackgroundTasksMock(),- call=call_mock,- client=CallConnectionClientMock(play_media_callback=_play_media_callback),+ background_tasks=background_tasks,+ call=call,+ client=client,text=input,)- latency_per_input += time.time() - start_time- latency_per_input = latency_per_input / len(inputs)+ await background_tasks()- full_input = " ".join(inputs)- actual_output = actual_output.strip()- _logger.info(f"full_input: {full_input}")+ # Remove newlines for log comparison+ actual_output = _remove_newlines(actual_output)+ full_input = _remove_newlines(" ".join(inputs))++ # Log for dev review_logger.info(f"actual_output: {actual_output}")- _logger.info(f"latency: {latency_per_input}")- _logger.info(f"claim: {call_mock.claim}")+ _logger.info(f"claim: {call.claim.model_dump(exclude_none=True)}")+ _logger.info(f"full_input: {full_input}")# Test claim datafor field in claim_tests_incl:- assert getattr(call_mock.claim, field), f"{field} is missing"+ assume(getattr(call.claim, field) is not None, f"Claim field {field} is None")# Configure LLM teststest_case = LLMTestCase(actual_output=actual_output,expected_output=expected_output,input=full_input,- latency=latency_per_input,retrieval_context=[- call_mock.claim.model_dump_json(),- TypeAdapter(list[ReminderModel]).dump_json(call_mock.reminders).decode(),- TypeAdapter(list[TrainingModel])- .dump_json(await call_mock.trainings())- .decode(),+ call.claim.model_dump_json(exclude_none=True),+ TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),+ TypeAdapter(list[TrainingModel]).dump_json(await call.trainings()).decode(),],)# Define LLM metricsllm_metrics = [BiasMetric(threshold=1, model=deepeval_model),- LatencyMetric(max_latency=60), # TODO: Set a reasonable thresholdToxicityMetric(threshold=1, model=deepeval_model),] # By default, include generic metrics@@ -223,3 +240,10 @@ async def test_llm(# Execute LLM testsassert_test(test_case, llm_metrics)+++def _remove_newlines(text: str) -> str:+ """+ Remove newlines from a string and return it as a single line.+ """+ return " ".join([line.strip() for line in text.splitlines()])diff --git a/tests/search.py b/tests/search.pyindex ade6d5c..221fc99 100644--- a/tests/search.py+++ b/tests/search.py@@ -1,13 +1,105 @@-from deepeval.models.base_model import DeepEvalBaseLLM+from deepeval import assert_test+from deepeval.metrics import BaseMetric+from deepeval.metrics.indicator import metric_progress_indicator+from deepeval.models.gpt_model import GPTModel+from deepeval.test_case import LLMTestCasefrom helpers.config import CONFIGfrom helpers.logging import build_loggerfrom models.call import CallModel-from models.training import TrainingModel+from typing import Optional+import asyncioimport pytest_logger = build_logger(__name__)-_search = CONFIG.ai_search.instance()+++class RagRelevancyMetric(BaseMetric):+ model: GPTModel+ score: Optional[float] = 0+ success: bool = False+ threshold: float++ def __init__(+ self,+ model: GPTModel,+ threshold: float = 0.5,+ ):+ self.threshold = threshold+ self.model = model++ async def a_measure(self, test_case: LLMTestCase) -> float:+ assert test_case.input+ assert test_case.retrieval_context+ # Measure each document in parallel+ with metric_progress_indicator(self, async_mode=True):+ scores = await asyncio.gather(+ *[+ self._measure_single(test_case.input, document)+ for document in test_case.retrieval_context+ ]+ )+ # Res 1 is weighted 1, res 2 is weighted 0.5, res 3 is weighted 0.33, ...+ weights = [score / i for i, score in enumerate(scores, start=1)]+ # Score is the weighted average, top 1 result should be the most important+ self.score = sum(x * y for x, y in zip(scores, weights)) / sum(weights)+ # Test against the threshold+ self.success = self.score >= self.threshold+ return self.score++ async def _measure_single(self, message: str, document: str) -> float:+ score = 0+ llm_res, _ = await self.model.a_generate(+ f"""+ Assistant is a data analyst expert with 20 years of experience.++ # Objective+ Assistant will analyze a document and decide whether it would be useful to respond to the user message.++ # Context+ The document comes from a database. It has been stemmed. It may contains technical data and jargon a specialist would use.++ # Rules+ - Answer only with the float value, never add other text+ - Response 0.0 means not useful at all, 1.0 means totally useful++ # Message+ {message}++ # Document+ {document}++ # Response format+ A float from 0.0 to 1.0++ ## Example 1+ Message: I love bananas+ Document: bananas are yellow, apples are red+ Assistant: 1++ ## Example 2+ Message: The sky is blue+ Document: mouse is a rodent, mouse is a computer peripheral+ Assistant: 0++ ## Example 3+ Message: my car is stuck in the mud+ Document: car accidents must be reported within 24 hours, car accidents are dangerous+ Assistant: 0.7+ """+ )+ try:+ score = float(llm_res)+ except ValueError:+ raise ValueError(f"LLM response is not a number: {llm_res}")+ return score++ def is_successful(self) -> bool:+ return self.success++ @property+ def __name__(self):+ return "RAG Relevancy"@pytest.mark.parametrize(@@ -38,13 +130,13 @@ _search = CONFIG.ai_search.instance()@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(10) # Catch multi-threading and concurrency issuesasync def test_relevancy(- call_mock: CallModel,- deepeval_model: DeepEvalBaseLLM,+ call: CallModel,+ deepeval_model: GPTModel,user_lang: str,user_message: str,) -> None:"""- Test the relevancy of the user message to the training data.+ Test the relevancy of the Message to the training data.Steps:1. Search for training data@@ -53,62 +145,29 @@ async def test_relevancy(Test is repeated 10 times to catch multi-threading and concurrency issues."""- # Configure context- call_mock.lang.short_code = user_lang+ search = CONFIG.ai_search.instance()+ call.lang = user_lang# Init data- data_models = await _search.training_asearch_all(user_message, call_mock)- data_str = ", ".join([d.content for d in data_models or []])-- _logger.info(f"User message: {user_message}")- _logger.info(f"Data: {data_str}")-- # Ask the LLM- llm_res = await deepeval_model.a_generate(- f"""- Assistant is a data analyst expert with 20 years of experience.-- # Objective- The assistant will analyze the input data and decide whether it would be useful to respond to the user's message.-- # Context- The data is a JSON list and comes from a database. The data has been stemmed.+ res_models = await search.training_asearch_all(user_message, call)+ res_list = [d.content for d in res_models or []]- # Rules- - Answer only with the float value, never add other text- - Response 0.0 means not useful at all, 1.0 means totally useful+ _logger.info(f"Message: {user_message}")+ _logger.info(f"Data: {res_list}")- # Input data- {data_str}-- # User message- {user_message}-- # Response format- A float from 0.0 to 1.0-- ## Example 1- Input data: bananas are yellow, apples are red- User message: I love bananas- Assistant: 1+ # Configure LLM tests+ test_case = LLMTestCase(+ actual_output="", # Not used+ input=user_message,+ retrieval_context=res_list,+ )- ## Example 2- Input data: mouse is a rodent, mouse is a computer peripheral- User message: The sky is blue- Assistant: 0+ # Define LLM metrics+ llm_metrics = [+ RagRelevancyMetric(+ threshold=0.5, model=deepeval_model+ ), # Compare input to the retrieval context+ ]- ## Example 3- Input data: car accidents must be reported within 24 hours, car accidents are dangerous- User message: my car is stuck in the mud- Assistant: 0.7- """- )- try:- llm_score = float(llm_res)- except ValueError:- raise ValueError(f"LLM response is not a number: {llm_res}")-- # Assert- assert (- llm_score >= 0.5- ), f"Analysis failed for {user_message}, LLM response {llm_score}"+ # Execute LLM tests+ assert_test(test_case, llm_metrics)diff --git a/tests/store.py b/tests/store.pyindex ccdf2f9..9986242 100644--- a/tests/store.py+++ b/tests/store.py@@ -1,12 +1,10 @@from helpers.config import CONFIGfrom helpers.config_models.database import ModeEnum as DatabaseModeEnumfrom models.call import CallModel+from pytest import assumeimport pytest-_db = CONFIG.database.instance()--@pytest.mark.parametrize("database_mode",[@@ -22,7 +20,7 @@ _db = CONFIG.database.instance())@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(10) # Catch multi-threading and concurrency issues-async def test_acid(call_mock: CallModel, database_mode: DatabaseModeEnum) -> None:+async def test_acid(call: CallModel, database_mode: DatabaseModeEnum) -> None:"""Test ACID properties of the database backend.@@ -36,18 +34,19 @@ async def test_acid(call_mock: CallModel, database_mode: DatabaseModeEnum) -> No"""# Set database modeCONFIG.database.mode = database_mode+ db = CONFIG.database.instance()# Check not exists- assert not await _db.call_aget(call_mock.call_id)- assert await _db.call_asearch_one(call_mock.phone_number) != call_mock- assert call_mock not in (await _db.call_asearch_all(call_mock.phone_number) or [])+ assume(not await db.call_aget(call.call_id))+ assume(await db.call_asearch_one(call.phone_number) != call)+ assume(call not in (await db.call_asearch_all(call.phone_number) or []))# Insert test call- await _db.call_aset(call_mock)+ await db.call_aset(call)# Check point read- assert await _db.call_aget(call_mock.call_id) == call_mock+ assume(await db.call_aget(call.call_id) == call)# Check search one- assert await _db.call_asearch_one(call_mock.phone_number) == call_mock+ assume(await db.call_asearch_one(call.phone_number) == call)# Check search all- assert call_mock in (await _db.call_asearch_all(call_mock.phone_number) or [])+ assume(call in (await db.call_asearch_all(call.phone_number) or []))