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: Automatically test claim field accuracy in testsa

Clémence Lesné7b3aeed94847
diff --git a/tests/conftest.py b/tests/conftest.py
index 77f32a3..4fbe98e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -168,7 +168,6 @@ class DeepEvalAzureOpenAI(GPTModel):
class Conversation(BaseModel):
claim_tests_excl: list[str] = []
- claim_tests_incl: list[str] = []
expected_output: str
id: str
inputs: list[str]
diff --git a/tests/conversations.yaml b/tests/conversations.yaml
index 9be6510..5a3a4e1 100644
--- a/tests/conversations.yaml
+++ b/tests/conversations.yaml
@@ -3,7 +3,6 @@ conversations:
inputs:
- "Hello hello!"
expected_output: "Hello, how can I help you?"
- claim_tests_incl: []
claim_tests_excl:
- "contextual_relevancy"
id: "hello"
@@ -13,7 +12,6 @@ conversations:
- "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"
@@ -27,10 +25,6 @@ conversations:
- "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"
@@ -45,9 +39,6 @@ conversations:
- "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"
@@ -58,11 +49,6 @@ conversations:
- "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"
@@ -74,11 +60,5 @@ conversations:
- "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.py
index 291d8d8..3ca2db7 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -11,6 +11,9 @@ from helpers.call_events import (
on_speech_recognized,
on_call_connected,
)
+from datetime import UTC, datetime
+from deepeval.metrics import BaseMetric
+from helpers.config_models.workflow import ClaimFieldModel
from helpers.logging import logger
from models.call import CallStateModel
from models.reminder import ReminderModel
@@ -18,8 +21,200 @@ from models.training import TrainingModel
from pydantic import TypeAdapter
from pytest import assume
from tests.conftest import CallAutomationClientMock, with_conversations
+from typing import Any, Optional
+import asyncio
import json
import pytest
+import re
+
+
+class ClaimRelevancyMetric(BaseMetric):
+ claim_fields: list[ClaimFieldModel]
+ claim: dict[str, Any]
+ model: GPTModel
+ threshold: float
+
+ def __init__(
+ self,
+ claim_keys: list[ClaimFieldModel],
+ claim: dict[str, Any],
+ model: GPTModel,
+ threshold: float = 0.5,
+ ):
+ self.claim = claim
+ self.claim_fields = claim_keys
+ self.model = model
+ self.threshold = threshold
+
+ async def a_measure(
+ self,
+ test_case: LLMTestCase,
+ *args,
+ **kwargs,
+ ) -> float:
+ assert test_case.input
+ # Extract claim data
+ extracts = await self._extract_claim_theory(test_case.input)
+ logger.info(f"Extracted claim data: {extracts}")
+ # Measure each claim in parallel
+ scores = await asyncio.gather(
+ *[
+ self._score_data(
+ key=key,
+ throry=value,
+ real=str(self.claim.get(key, None)),
+ )
+ for key, value in extracts.items()
+ ]
+ )
+ logger.info(f"Claim scores: {scores}")
+ # Score is the average
+ self.score = sum(scores) / len(scores) if len(extracts) > 0 else 1
+ # Test against the threshold
+ self.success = self.score >= self.threshold
+ return self.score
+
+ async def _score_data(self, key: str, throry: str, real: Optional[str]) -> float:
+ res, _ = await self.model.a_generate(
+ f"""
+ Assistant is a data analyst expert with 20 years of experience.
+
+ # Context
+ Connversation come from a call center.
+
+ # Objective
+ Score the relevancy of a theoritical data against the real one.
+
+ # Rules
+ - A high score means the real data is correct
+ - A low score means the real data is not relevant and lacks details against the theoritical data
+ - Answer only with the score, nothing else
+ - The score should be between 0 and 1
+
+ # Data
+ Name: {key}
+ Throry: {throry or "N/A"}
+ Real: {real or "N/A"}
+
+ # Response format
+ [score, a float between 0.0 and 1.0]
+
+ ## Example 1
+ Name: age
+ Throry: 25 years old, born in 1996
+ Real: 25
+ Assistant: 1
+
+ ## Example 2
+ Name: street_address
+ Throry: 123 Main St, New York, NY 10001
+ Real: United States
+ Assistant: 0.2
+
+ ## Example 3
+ Name: phone
+ Throry: 123-456-7890
+ Real: +11234567890
+ Assistant: 1.0
+
+ ## Example 4
+ Name: email
+ Assistant: 0.0
+
+ ## Example 5
+ Name: incident_location
+ Throry: Near the Eiffel Tower, Paris, France
+ Real: Eiffel Tower
+ Assistant: 0.6
+
+ ## Example 6
+ Name: incident_date
+ Throry: 2021-01-01
+ Real: N/A
+ Assistant: 0.0
+ """
+ )
+ try:
+ score = float(res)
+ except ValueError:
+ group = re.search(r"\d+\.\d+", res)
+ if group:
+ return float(group.group())
+ raise ValueError(f"LLM response is not a number: {res}")
+ return score
+
+ async def _extract_claim_theory(self, conversation: str) -> dict[str, str]:
+ res, _ = await self.model.a_generate(
+ f"""
+ Assistant is a data analyst expert with 20 years of experience.
+
+ # Context
+ Conversation is coming from a call centre. Today is {datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M")}.
+
+ # Objective
+ Extract fields from a conversation. The answer will be a JSON object with the key-value pairs.
+
+ # Rules
+ - All data should be extracted
+ - Answer only with the JSON object, nothing else
+ - If there is no data to populate a field, do not include it
+ - Limit fields to the ones listed
+ - Values should be detailed, if data exists
+
+ # Fields
+ {", ".join([f"{field.name} ({field.type.value})" for field in self.claim_fields])}
+
+ # Conversation
+ {conversation}
+
+ # Response format in JSON
+ [
+ {{
+ "key": "[key]",
+ "value": "[value]"
+ }}
+ ]
+
+ ## Example 1
+ Conversation: I am 25 years old and I was born in 1996.
+ Fields: age (text), birth_date (datetime), car_model (text)
+ Assistant: [{{"key": "age", "value": "25 years old"}}, {{"key": "birth_date", "value": "1996-05-07"}}]
+
+ ## Example 2
+ Conversation: I live at 123 Main St, New York, NY 10001. My car is a Ford F-150 2021.
+ Fields: street_address (text), car_model (text), phone (phone_number)
+ Assistant: [{{"key": "street_address", "value": "123 Main St, New York, NY 10001"}}, {{"key": "car_model", "value": "Ford F-150 2021"}}]
+
+ ## Example 3
+ Conversation: zsssk zsssk
+ Fields: incident_location (text), incident_date (datetime)
+ Assistant: []
+
+ ## Example 4
+ Conversation: My name is John Doe.
+ Fields: car_model (text)
+ Assistant: []
+ """
+ )
+ res = res.strip().strip("```json\n").strip("\n```").strip()
+ extracts: list[dict[str, str]] = json.loads(res)
+ return {
+ extract["key"]: extract["value"]
+ for extract in extracts
+ if extract["value"]
+ and any(
+ claim_field.name == extract["key"] for claim_field in self.claim_fields
+ )
+ }
+
+ def is_successful(self) -> bool:
+ return self.success
+
+ @property
+ def __name__(self):
+ return "Claim Relevancy"
@with_conversations
@@ -28,7 +223,6 @@ import pytest
async def test_llm(
call: CallStateModel,
claim_tests_excl: list[str],
- claim_tests_incl: list[str],
deepeval_model: GPTModel,
expected_output: str,
inputs: list[str],
@@ -81,10 +275,6 @@ async def test_llm(
logger.info(f"claim: {call.claim}")
logger.info(f"full_input: {full_input}")
- # Test claim data
- for field in claim_tests_incl:
- assume(call.claim.get(field, None), f"Claim field {field} is missing")
-
# Configure LLM tests
test_case = LLMTestCase(
actual_output=actual_output,
@@ -99,9 +289,15 @@ async def test_llm(
# Define LLM metrics
llm_metrics = [
- BiasMetric(threshold=1, model=deepeval_model),
- ToxicityMetric(threshold=1, model=deepeval_model),
- ] # By default, include generic metrics
+ BiasMetric(threshold=1, model=deepeval_model), # Gender, age, ethnicity
+ ClaimRelevancyMetric(
+ claim_keys=call.initiate.claim,
+ claim=call.claim,
+ model=deepeval_model,
+ threshold=0.5,
+ ), # Claim data
+ ToxicityMetric(threshold=1, model=deepeval_model), # Hate speech, insults
+ ] # Include those by default
if not any(
field == "answer_relevancy" for field in claim_tests_excl