Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
breaking: Add strict and threshold parameters for AI Search
Clémence Lesné6a37d66a7684
diff --git a/helpers/config_models/ai_search.py b/helpers/config_models/ai_search.pyindex 00a132f..54f7791 100644--- a/helpers/config_models/ai_search.py+++ b/helpers/config_models/ai_search.py@@ -6,10 +6,11 @@ from pydantic import SecretStr, BaseModel, Fieldclass AiSearchModel(BaseModel, frozen=True):access_key: SecretStrendpoint: str- expansion_k: int = Field(default=5, ge=1)+ expansion_n_messages: int = Field(default=10, ge=1)index: strsemantic_configuration: str = "default"- top_k: int = Field(default=15, ge=1)+ strictness: float = Field(default=2, ge=0, le=5)+ top_n_documents: int = Field(default=5, ge=1)@cachedef instance(self) -> ISearch:diff --git a/models/call.py b/models/call.pyindex 60752cb..d3db0c7 100644--- a/models/call.py+++ b/models/call.py@@ -123,12 +123,19 @@ class CallStateModel(CallGetModel):lang=self.lang.short_code,text=message.content,)- for message in self.messages[-CONFIG.ai_search.expansion_k :]+ for message in self.messages[+ -CONFIG.ai_search.expansion_n_messages :+ ]],) # Get trainings from last messagestrainings = sorted(- set(training for trainings in tasks for training in trainings or [])- ) # Flatten, remove duplicates, and sort by score+ set(+ training+ for trainings in tasks+ for training in trainings or []+ if training.score >= CONFIG.ai_search.strictness+ )+ ) # Flatten, remove duplicates, sort by score, filter by strictnessreturn trainingsdef tz(self) -> tzinfo:diff --git a/persistence/ai_search.py b/persistence/ai_search.pyindex 89aea52..c11d7ae 100644--- a/persistence/ai_search.py+++ b/persistence/ai_search.py@@ -5,11 +5,16 @@ from azure.core.exceptions import (ServiceResponseError,)from azure.search.documents.aio import SearchClient-from azure.search.documents.models import VectorizableTextQuery+from azure.search.documents.models import (+ QueryLanguage,+ QueryType,+ ScoringStatistics,+ SearchMode,+ VectorizableTextQuery,+)from contextlib import asynccontextmanagerfrom helpers.config_models.ai_search import AiSearchModelfrom helpers.logging import logger-from models.call import CallStateModelfrom models.readiness import ReadinessStatusfrom models.training import TrainingModelfrom persistence.icache import ICache@@ -31,7 +36,7 @@ class AiSearchSearch(ISearch):def __init__(self, cache: ICache, config: AiSearchModel):logger.info(f"Using AI Search {config.endpoint} with index {config.index}")logger.info(- f"Note: At ~300 chars /doc, each LLM call will use approx {300 * config.top_k * config.expansion_k / 4} tokens (without tools)"+ f"Note: At ~300 chars /doc, each LLM call will use approx {300 * config.top_n_documents * config.expansion_n_messages / 4} tokens (without tools)")self._config = configsuper().__init__(cache)@@ -67,7 +72,7 @@ class AiSearchSearch(ISearch):return None# Try cache- cache_key = f"{self.__class__.__name__}-training_asearch_all-{text}"+ cache_key = f"{self.__class__.__name__}-training_asearch_all-v2-{text}" # Cache sort method has been updated in v6, thus the v2cached = await self._cache.aget(cache_key)if cached:try:@@ -85,16 +90,15 @@ class AiSearchSearch(ISearch):async with self._use_db() as db:results = await db.search(# Full text search- query_type="semantic",+ query_language=QueryLanguage(lang.lower()),+ query_type=QueryType.SEMANTIC,semantic_configuration_name=self._config.semantic_configuration,search_fields=["content","title",],+ search_mode=SearchMode.ANY, # Any of the terms will matchsearch_text=text,- # Spell correction- query_language=lang,- query_speller="lexicon",# Vector searchvector_queries=[VectorizableTextQuery(@@ -102,14 +106,13 @@ class AiSearchSearch(ISearch):text=text,)],+ # Relability+ semantic_max_wait_in_milliseconds=750, # Timeout in ms# Return fields- select=[- "id",- "content",- "source_uri",- "title",- ],- top=self._config.top_k,+ include_total_count=False, # Total count is not used+ query_caption_highlight_enabled=False, # Highlighting is not used+ scoring_statistics=ScoringStatistics.GLOBAL, # Evaluate scores in the backend for more accurate values+ top=self._config.top_n_documents,)async for result in results:try:@@ -117,9 +120,11 @@ class AiSearchSearch(ISearch):TrainingModel.model_validate({**result,- "score": result[- "@search.score"- ], # TODO: Use score from semantic ranking with "@search.rerankerScore"+ "score": (+ (result["@search.reranker_score"] / 4 * 5)+ if "@search.reranker_score" in result+ else (result["@search.score"] * 5)+ ), # Normalize score to 0-5, failback to search score if reranker is not available}))diff --git a/tests/search.py b/tests/search.pyindex 5ddce50..f6f0dc3 100644--- a/tests/search.py+++ b/tests/search.py@@ -1,11 +1,15 @@from deepeval import assert_testfrom deepeval.metrics import BaseMetric-from deepeval.metrics.indicator import metric_progress_indicatorfrom deepeval.models.gpt_model import GPTModelfrom deepeval.test_case import LLMTestCasefrom helpers.config import CONFIGfrom helpers.logging import loggerfrom models.call import CallStateModel+from models.message import MessageModel, PersonaEnum as MessagePersonaEnum+from models.training import TrainingModel+from pydantic import TypeAdapter+from pytest import assume+from tests.conftest import with_conversationsfrom typing import Optionalimport asyncioimport pytest@@ -25,26 +29,30 @@ class RagRelevancyMetric(BaseMetric):self.threshold = thresholdself.model = model- async def a_measure(self, test_case: LLMTestCase) -> float:+ async def a_measure(+ self,+ test_case: LLMTestCase,+ *args,+ **kwargs,+ ) -> float:assert test_case.inputassert 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)+ scores = await asyncio.gather(+ *[+ self._measure_single(message=test_case.input, document=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 thresholdself.success = self.score >= self.thresholdreturn self.score- async def _measure_single(self, message: str, document: str) -> float:+ async def _measure_single(self, document: str, message: str) -> float:score = 0llm_res, _ = await self.model.a_generate(f"""@@ -99,37 +107,17 @@ class RagRelevancyMetric(BaseMetric):return "RAG Relevancy"- "user_message, user_lang",- [- pytest.param(- "accident de voiture sur autoroute",- "fr-FR",- id="car_fr",- ),- pytest.param(- "cyber-attaque par DDOS sur mon entreprise",- "fr-FR",- id="cyberattack_fr",- ),- pytest.param(- "refus passage expert souhaite contre-expertise",- "fr-FR",- id="expertise_fr",- ),- pytest.param(- "grêlons champ réculte tomates perdue indemnisation",- "fr-FR",- id="hail_fr",- ),- ],-)+@with_conversations@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(10) # Catch multi-threading and concurrency issuesasync def test_relevancy(+ call: CallStateModel,+ claim_tests_excl: list[str],+ claim_tests_incl: list[str],deepeval_model: GPTModel,- user_lang: str,- user_message: str,+ expected_output: str,+ inputs: list[str],+ lang: str,) -> None:"""Test the relevancy of the Message to the training data.@@ -141,20 +129,53 @@ async def test_relevancy(Test is repeated 10 times to catch multi-threading and concurrency issues."""- search = CONFIG.ai_search.instance()+ # Set call language+ call.lang = lang++ # Fill call with messages+ for input in inputs:+ call.messages.append(+ MessageModel(content=input, persona=MessagePersonaEnum.HUMAN)+ )++ # Get trainings+ trainings = await call.trainings()- # Init data- res_models = await search.training_asearch_all(text=user_message, lang=user_lang)- res_list = [d.content for d in res_models or []]+ logger.info(f"Messages: {call.messages}")+ logger.info(f"Trainings: {trainings}")- logger.info(f"Message: {user_message}")- logger.info(f"Data: {res_list}")+ if not trainings:+ logger.warning("No training data found, please add objects in AI Search")+ return++ # Confirm top N config is respected+ len_trainings = len(trainings)+ max_documents = (+ CONFIG.ai_search.top_n_documents * CONFIG.ai_search.expansion_n_messages+ )+ assume(+ len_trainings <= max_documents,+ f"Data is too large, should be max {max_documents}, actual is {len_trainings}",+ )++ # Confirm strictness config is respected+ min_score = CONFIG.ai_search.strictness+ for training in trainings or []:+ actual_score = training.score+ assume(+ actual_score >= min_score,+ f"Model score is too low, should be min {min_score}, actual is {actual_score}",+ )# Configure LLM tests+ full_input = " ".join([message.content for message in call.messages])test_case = LLMTestCase(actual_output="", # Not used- input=user_message,- retrieval_context=res_list,+ input=full_input,+ retrieval_context=[+ TypeAdapter(TrainingModel).dump_json(training).decode()+ for training in trainings+ ],)# Define LLM metrics