Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
feat: Endpoint get a call by ID
Clémence Lesnéa9710734b709
diff --git a/helpers/call_events.py b/helpers/call_events.pyindex 6ad5fa9..a24d467 100644--- a/helpers/call_events.py+++ b/helpers/call_events.py@@ -13,7 +13,7 @@ from azure.core.exceptions import (ResourceNotFoundError,)from models.synthesis import SynthesisModel-from models.call import CallModel+from models.call import CallStateModelfrom models.message import (ActionEnum as MessageActionEnum,extract_message_style,@@ -74,7 +74,7 @@ async def on_new_call(@TRACER.start_as_current_span("on_call_connected")async def on_call_connected(- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,) -> None:_logger.info("Call connected")@@ -96,7 +96,7 @@ async def on_call_connected(@TRACER.start_as_current_span("on_call_disconnected")async def on_call_disconnected(background_tasks: BackgroundTasks,- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,) -> None:_logger.info("Call disconnected")@@ -106,7 +106,7 @@ async def on_call_disconnected(@TRACER.start_as_current_span("on_speech_recognized")async def on_speech_recognized(background_tasks: BackgroundTasks,- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,text: str,) -> None:@@ -122,7 +122,7 @@ async def on_speech_recognized(@TRACER.start_as_current_span("on_speech_timeout_error")async def on_speech_timeout_error(- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,) -> None:if call.recognition_retry < 10:@@ -145,7 +145,7 @@ async def on_speech_timeout_error(@TRACER.start_as_current_span("on_speech_unknown_error")async def on_speech_unknown_error(- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,error_code: int,) -> None:@@ -166,7 +166,7 @@ async def on_speech_unknown_error(@TRACER.start_as_current_span("on_play_completed")async def on_play_completed(background_tasks: BackgroundTasks,- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,context: str,) -> None:@@ -209,7 +209,7 @@ async def on_play_error(@TRACER.start_as_current_span("on_ivr_recognized")async def on_ivr_recognized(client: CallConnectionClient,- call: CallModel,+ call: CallStateModel,label: str,background_tasks: BackgroundTasks,) -> None:@@ -257,7 +257,7 @@ async def on_transfer_completed() -> None:@TRACER.start_as_current_span("on_transfer_error")async def on_transfer_error(- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,error_code: int,) -> None:@@ -271,7 +271,9 @@ async def on_transfer_error(async def _handle_hangup(- background_tasks: BackgroundTasks, client: CallConnectionClient, call: CallModel+ background_tasks: BackgroundTasks,+ client: CallConnectionClient,+ call: CallStateModel,) -> None:_logger.debug("Hanging up call")try:@@ -295,7 +297,9 @@ async def _handle_hangup(_post_call_intelligence(call, background_tasks)-def _post_call_intelligence(call: CallModel, background_tasks: BackgroundTasks) -> None:+def _post_call_intelligence(+ call: CallStateModel, background_tasks: BackgroundTasks+) -> None:"""Shortcut to run all post-call intelligence tasks in background."""@@ -304,7 +308,7 @@ def _post_call_intelligence(call: CallModel, background_tasks: BackgroundTasks)background_tasks.add_task(_post_call_synthesis, call)-async def _post_call_sms(call: CallModel) -> None:+async def _post_call_sms(call: CallStateModel) -> None:"""Send an SMS report to the customer."""@@ -344,7 +348,7 @@ async def _post_call_sms(call: CallModel) -> None:await _db.call_aset(call)-async def _post_call_synthesis(call: CallModel) -> None:+async def _post_call_synthesis(call: CallStateModel) -> None:"""Synthesize the call and store it to the model."""@@ -381,7 +385,7 @@ async def _post_call_synthesis(call: CallModel) -> None:await _db.call_aset(call)-async def _post_call_next(call: CallModel) -> None:+async def _post_call_next(call: CallStateModel) -> None:"""Generate next action for the call."""@@ -402,7 +406,7 @@ async def _post_call_next(call: CallModel) -> None:async def _handle_ivr_language(client: CallConnectionClient,- call: CallModel,+ call: CallStateModel,) -> None:tones = [DtmfTone.ONE,diff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex e04553b..4268f5d 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -4,7 +4,7 @@ from azure.communication.callautomation import ()from helpers.config import CONFIGfrom helpers.logging import build_logger-from models.call import CallModel+from models.call import CallStateModelfrom models.message import (extract_message_style,MessageModel,@@ -38,7 +38,7 @@ _logger = build_logger(__name__)_db = CONFIG.database.instance()-async def llm_completion(text: Optional[str], call: CallModel) -> Optional[str]:+async def llm_completion(text: Optional[str], call: CallStateModel) -> Optional[str]:"""Run LLM completion from a system prompt and a Call model.@@ -67,7 +67,7 @@ async def llm_completion(text: Optional[str], call: CallModel) -> Optional[str]:async def llm_model(- text: Optional[str], call: CallModel, model: Type[ModelType]+ text: Optional[str], call: CallStateModel, model: Type[ModelType]) -> Optional[ModelType]:"""Run LLM completion from a system prompt, a Call model, and an expected model type as a return.@@ -96,7 +96,7 @@ async def llm_model(def _llm_completion_system(- system: str, call: CallModel+ system: str, call: CallStateModel) -> list[ChatCompletionSystemMessageParam]:messages = [ChatCompletionSystemMessageParam(@@ -116,11 +116,11 @@ def _llm_completion_system(async def load_llm_chat(background_tasks: BackgroundTasks,- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,- post_call_intelligence: Callable[[CallModel, BackgroundTasks], None],+ post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],_iterations_remaining: int = 3,-) -> CallModel:+) -> CallStateModel:"""Handle the intelligence of the call, including: LLM chat, TTS, and media play.@@ -271,12 +271,12 @@ async def load_llm_chat(async def _execute_llm_chat(background_tasks: BackgroundTasks,- call: CallModel,+ call: CallStateModel,client: CallConnectionClient,- post_call_intelligence: Callable[[CallModel, BackgroundTasks], None],+ post_call_intelligence: Callable[[CallStateModel, BackgroundTasks], None],use_tools: bool,user_callback: Callable[[str, MessageStyleEnum], Awaitable],-) -> Tuple[bool, bool, bool, CallModel]:+) -> Tuple[bool, bool, bool, CallStateModel]:"""Perform the chat with the LLM model.@@ -290,7 +290,7 @@ async def _execute_llm_chat(1. `bool`, notify error2. `bool`, should retry chat3. `bool`, if the chat should continue- 4. `CallModel`, the updated model+ 4. `CallStateModel`, the updated model"""_logger.debug("Running LLM chat")content_full = ""diff --git a/helpers/call_utils.py b/helpers/call_utils.pyindex ec03dfa..28da7c0 100644--- a/helpers/call_utils.py+++ b/helpers/call_utils.py@@ -1,7 +1,7 @@from enum import Enumfrom helpers.config import CONFIGfrom helpers.logging import build_logger-from models.call import CallModel+from models.call import CallStateModelfrom models.message import StyleEnum as MessageStyleEnumfrom typing import Generator, Optionalfrom azure.communication.callautomation import (@@ -61,7 +61,7 @@ def tts_sentence_split(text: str, include_last: bool) -> Generator[str, None, No# TODO: Disable or lower profanity filter. The filter seems enabled by default, it replaces words like "holes in my roof" by "*** in my roof". This is not acceptable for a call center.async def _handle_recognize_media(client: CallConnectionClient,- call: CallModel,+ call: CallStateModel,sound_url: str,) -> None:"""@@ -87,7 +87,7 @@ async def _handle_recognize_media(async def handle_media(client: CallConnectionClient,- call: CallModel,+ call: CallStateModel,sound_url: str,context: Optional[str] = None,) -> None:@@ -112,7 +112,7 @@ async def handle_media(async def handle_recognize_text(client: CallConnectionClient,- call: CallModel,+ call: CallStateModel,style: MessageStyleEnum = MessageStyleEnum.NONE,text: Optional[str] = None,store: bool = True,@@ -140,7 +140,7 @@ async def handle_recognize_text(async def handle_play(client: CallConnectionClient,- call: CallModel,+ call: CallStateModel,text: str,style: MessageStyleEnum = MessageStyleEnum.NONE,context: Optional[str] = None,@@ -199,7 +199,9 @@ async def handle_play(raise e-def _audio_from_text(text: str, style: MessageStyleEnum, call: CallModel) -> SsmlSource:+def _audio_from_text(+ text: str, style: MessageStyleEnum, call: CallStateModel+) -> SsmlSource:"""Generate an audio source that can be read by Azure Communication Services SDK.@@ -226,7 +228,7 @@ def _audio_from_text(text: str, style: MessageStyleEnum, call: CallModel) -> Ssmasync def handle_recognize_ivr(client: CallConnectionClient,- call: CallModel,+ call: CallStateModel,text: str,choices: list[RecognitionChoice],) -> None:diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.pyindex dc9a4f6..296e4b1 100644--- a/helpers/config_models/prompts.py+++ b/helpers/config_models/prompts.py@@ -2,7 +2,7 @@ from azure.core.exceptions import HttpResponseErrorfrom datetime import datetime, UTCfrom functools import cached_propertyfrom logging import Logger-from models.call import CallModel+from models.call import CallStateModelfrom models.message import MessageModelfrom models.next import ActionEnum as NextActionEnumfrom models.reminder import ReminderModel@@ -336,7 +336,7 @@ class LlmModel(BaseModel):))- def chat_system(self, call: CallModel, trainings: list[TrainingModel]) -> str:+ def chat_system(self, call: CallStateModel, trainings: list[TrainingModel]) -> str:from helpers.config import CONFIGfrom models.message import (ActionEnum as MessageActionEnum,@@ -356,7 +356,7 @@ class LlmModel(BaseModel):trainings=trainings,)- def sms_summary_system(self, call: CallModel) -> str:+ def sms_summary_system(self, call: CallStateModel) -> str:from helpers.config import CONFIGreturn self._return(@@ -371,7 +371,7 @@ class LlmModel(BaseModel):.decode(),)- def synthesis_short_system(self, call: CallModel) -> str:+ def synthesis_short_system(self, call: CallStateModel) -> str:return self._return(self.synthesis_short_system_tpl,claim=call.claim.model_dump_json(),@@ -382,7 +382,7 @@ class LlmModel(BaseModel):.decode(),)- def synthesis_long_system(self, call: CallModel) -> str:+ def synthesis_long_system(self, call: CallStateModel) -> str:return self._return(self.synthesis_long_system_tpl,claim=call.claim.model_dump_json(),@@ -393,7 +393,9 @@ class LlmModel(BaseModel):.decode(),)- def citations_system(self, call: CallModel, text: Optional[str]) -> Optional[str]:+ def citations_system(+ self, call: CallStateModel, text: Optional[str]+ ) -> Optional[str]:"""Return the formatted prompt. Prompt is used to add citations to the text, without cluttering the content itself.@@ -423,7 +425,7 @@ class LlmModel(BaseModel):text=text,)- def next_system(self, call: CallModel) -> str:+ def next_system(self, call: CallStateModel) -> str:return self._return(self.next_system_tpl,actions=", ".join([action.value for action in NextActionEnum]),@@ -501,19 +503,19 @@ class TtsModel(BaseModel):)ivr_language_tpl: str = "To continue in {label}, press {index}."- async def calltransfer_failure(self, call: CallModel) -> str:+ async def calltransfer_failure(self, call: CallStateModel) -> str:return await self._translate(self.calltransfer_failure_tpl, call)- async def connect_agent(self, call: CallModel) -> str:+ async def connect_agent(self, call: CallStateModel) -> str:return await self._translate(self.connect_agent_tpl, call)- async def end_call_to_connect_agent(self, call: CallModel) -> str:+ async def end_call_to_connect_agent(self, call: CallStateModel) -> str:return await self._translate(self.end_call_to_connect_agent_tpl, call)- async def error(self, call: CallModel) -> str:+ async def error(self, call: CallStateModel) -> str:return await self._translate(self.error_tpl, call)- async def goodbye(self, call: CallModel) -> str:+ async def goodbye(self, call: CallStateModel) -> str:from helpers.config import CONFIGreturn await self._translate(@@ -522,7 +524,7 @@ class TtsModel(BaseModel):bot_company=CONFIG.workflow.bot_company,)- async def hello(self, call: CallModel) -> str:+ async def hello(self, call: CallStateModel) -> str:from helpers.config import CONFIGreturn await self._translate(@@ -532,10 +534,10 @@ class TtsModel(BaseModel):bot_name=CONFIG.workflow.bot_name,)- async def timeout_silence(self, call: CallModel) -> str:+ async def timeout_silence(self, call: CallStateModel) -> str:return await self._translate(self.timeout_silence_tpl, call)- async def welcome_back(self, call: CallModel) -> str:+ async def welcome_back(self, call: CallStateModel) -> str:from helpers.config import CONFIGreturn await self._translate(@@ -546,10 +548,10 @@ class TtsModel(BaseModel):conversation_timeout_hour=CONFIG.workflow.conversation_timeout_hour,)- async def timeout_loading(self, call: CallModel) -> str:+ async def timeout_loading(self, call: CallStateModel) -> str:return await self._translate(self.timeout_loading_tpl, call)- async def ivr_language(self, call: CallModel) -> str:+ async def ivr_language(self, call: CallStateModel) -> str:from helpers.config import CONFIGres = ""@@ -567,7 +569,7 @@ class TtsModel(BaseModel):def _return(self, prompt_tpl: str, **kwargs) -> str:return dedent(prompt_tpl.format(**kwargs)).strip()- async def _translate(self, prompt_tpl: str, call: CallModel, **kwargs) -> str:+ async def _translate(self, prompt_tpl: str, call: CallStateModel, **kwargs) -> str:"""Format the prompt and translate it to the TTS language.diff --git a/helpers/llm_tools.py b/helpers/llm_tools.pyindex 4793318..cd556b2 100644--- a/helpers/llm_tools.py+++ b/helpers/llm_tools.py@@ -4,7 +4,7 @@ from helpers.config import CONFIGfrom helpers.llm_utils import function_schemafrom helpers.logging import build_loggerfrom inspect import getmembers, isfunction-from models.call import CallModel+from models.call import CallStateModelfrom models.claim import ClaimModelfrom models.message import StyleEnum as MessageStyleEnumfrom models.reminder import ReminderModel@@ -24,19 +24,19 @@ class UpdateClaimDict(TypedDict):class LlmPlugins:- call: CallModel+ call: CallStateModelcancellation_callback: Callable[[], Awaitable]client: CallConnectionClient- post_call_intelligence: Callable[[CallModel], None]+ post_call_intelligence: Callable[[CallStateModel], None]style: MessageStyleEnum = MessageStyleEnum.NONEuser_callback: Callable[[str, MessageStyleEnum], Awaitable]def __init__(self,- call: CallModel,+ call: CallStateModel,cancellation_callback: Callable[[], Awaitable],client: CallConnectionClient,- post_call_intelligence: Callable[[CallModel], None],+ post_call_intelligence: Callable[[CallStateModel], None],user_callback: Callable[[str, MessageStyleEnum], Awaitable],):self.call = call@@ -81,7 +81,7 @@ class LlmPlugins:self.post_call_intelligence(self.call)# Store the last message and use it at first message of the new claimlast_message = self.call.messages[-1]- call = CallModel(phone_number=self.call.phone_number)+ call = CallStateModel(phone_number=self.call.phone_number)call.messages.append(last_message)return "Claim, reminders and messages reset"@@ -311,7 +311,7 @@ class LlmPlugins:return f"Notifying {service} for {reason}."@staticmethod- async def to_openai(call: CallModel) -> list[ChatCompletionToolParam]:+ async def to_openai(call: CallStateModel) -> list[ChatCompletionToolParam]:return await asyncio.gather(*[function_schema(type, call=call)diff --git a/main.py b/main.pyindex d480935..2adf1b6 100644--- a/main.py+++ b/main.py@@ -24,7 +24,7 @@ from fastapi import FastAPI, status, Request, HTTPException, BackgroundTasks, Refrom fastapi.responses import JSONResponse, HTMLResponsefrom fastapi.staticfiles import StaticFilesfrom jinja2 import Environment, FileSystemLoader-from models.call import CallModel+from models.call import CallStateModel, CallGetModelfrom models.next import ActionEnum as NextActionEnumfrom urllib.parse import quote_plus, urljoinimport asyncio@@ -191,8 +191,25 @@ async def report_call_get(phone_number: PhoneNumber, call_id: UUID) -> HTMLRespodescription="Search all calls by phone number.",name="Search calls",)-async def call_search_get(phone_number: PhoneNumber) -> list[CallModel]:- return await _db.call_asearch_all(phone_number) or []+async def call_search_get(phone_number: PhoneNumber) -> list[CallGetModel]:+ calls = await _db.call_asearch_all(phone_number) or []+ output = [CallGetModel.model_validate(call) for call in calls]+ return output+++ "/call/{call_id}",+ description="Get a call by its ID.",+ name="Get call",+)+async def call_get(call_id: UUID) -> CallGetModel:+ call = await _db.call_aget(call_id)+ if not call:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail=f"Call {call_id} not found",+ )+ return CallGetModel.model_validate(call)@api.get(@@ -409,7 +426,7 @@ async def _callback_url(phone_number: PhoneNumber) -> str:"""call = await _db.call_asearch_one(phone_number)if not call:- call = CallModel(phone_number=phone_number)+ call = CallStateModel(phone_number=phone_number)await _db.call_aset(call) # Create for the first timereturn _CALL_EVENT_URL.format(callback_secret=call.callback_secret,diff --git a/models/call.py b/models/call.pyindex 477a0f5..ecfe520 100644--- a/models/call.py+++ b/models/call.py@@ -15,18 +15,10 @@ import randomimport string-class CallModel(BaseModel):+class CallGetModel(BaseModel):# Immutable fieldscall_id: UUID = Field(default_factory=uuid4, frozen=True)created_at: datetime = Field(default_factory=lambda: datetime.now(UTC), frozen=True)- callback_secret: str = Field(- default="".join(- random.choice(string.ascii_letters + string.digits) for _ in range(16)- ),- frozen=True,- )- # Private fields- lang_short_code: Optional[str] = None# Editable fieldsclaim: ClaimModel = Field(default_factory=ClaimModel)messages: list[MessageModel] = []@@ -36,6 +28,25 @@ class CallModel(BaseModel):reminders: list[ReminderModel] = []synthesis: Optional[SynthesisModel] = None+ def tz(self) -> tzinfo:+ return PhoneNumber.tz(self.phone_number)+++class CallStateModel(CallGetModel):+ # Immutable fields+ callback_secret: str = Field(+ default="".join(+ random.choice(string.ascii_letters + string.digits) for _ in range(16)+ ),+ frozen=True,+ )+ # Editable fields+ lang_short_code: Optional[str] = Field(default=None)+ voice_recognition_retry: int = Field(+ default=0,+ validation_alias="recognition_retry", # Compatibility with v1+ )+@computed_fielddef lang(self) -> LanguageEntryModel: # type: ignorefrom helpers.config import CONFIG@@ -55,9 +66,6 @@ class CallModel(BaseModel):def lang(self, short_code: str) -> None:self.lang_short_code = short_code- def tz(self) -> tzinfo:- return PhoneNumber.tz(self.phone_number)-async def trainings(self) -> list[TrainingModel]:"""Get the trainings from the last messages.diff --git a/persistence/ai_search.py b/persistence/ai_search.pyindex 94a08f1..1b5a9ae 100644--- a/persistence/ai_search.py+++ b/persistence/ai_search.py@@ -9,7 +9,7 @@ from azure.search.documents.models import VectorizableTextQueryfrom contextlib import asynccontextmanagerfrom helpers.config_models.ai_search import AiSearchModelfrom helpers.logging import build_logger-from models.call import CallModel+from models.call import CallStateModelfrom models.readiness import ReadinessStatusfrom models.training import TrainingModelfrom persistence.icache import ICache@@ -60,7 +60,7 @@ class AiSearchSearch(ISearch):wait=wait_random_exponential(multiplier=0.5, max=30),)async def training_asearch_all(- self, text: str, call: CallModel+ self, text: str, call: CallStateModel) -> Optional[list[TrainingModel]]:_logger.debug(f'Searching training data for "{text}"')if not text:diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex 0b81944..d6aac39 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -5,7 +5,7 @@ from contextlib import asynccontextmanagerfrom helpers.config import CONFIGfrom helpers.config_models.database import CosmosDbModelfrom helpers.logging import build_logger-from models.call import CallModel+from models.call import CallStateModelfrom models.readiness import ReadinessStatusfrom persistence.istore import IStorefrom pydantic import ValidationError@@ -74,7 +74,7 @@ class CosmosDbStore(IStore):exist = Truereturn exist- async def call_aget(self, call_id: UUID) -> Optional[CallModel]:+ async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:_logger.debug(f"Loading call {call_id}")call = Nonetry:@@ -85,7 +85,7 @@ class CosmosDbStore(IStore):)raw = await anext(items)try:- call = CallModel.model_validate(raw)+ call = CallStateModel.model_validate(raw)except ValidationError as e:_logger.debug(f"Parsing error: {e.errors()}")except StopAsyncIteration:@@ -94,7 +94,7 @@ class CosmosDbStore(IStore):_logger.error(f"Error accessing CosmosDB, {e}")return call- async def call_aset(self, call: CallModel) -> bool:+ async def call_aset(self, call: CallStateModel) -> bool:data = call.model_dump(mode="json", exclude_none=True)data["id"] = str(call.call_id) # CosmosDB requires an id field_logger.debug(f"Saving call {call.call_id}: {data}")@@ -106,7 +106,7 @@ class CosmosDbStore(IStore):_logger.error(f"Error accessing CosmosDB: {e}")return False- async def call_asearch_one(self, phone_number: str) -> Optional[CallModel]:+ async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:_logger.debug(f"Loading last call for {phone_number}")call = Nonetry:@@ -123,7 +123,7 @@ class CosmosDbStore(IStore):)raw = await anext(items)try:- call = CallModel.model_validate(raw)+ call = CallStateModel.model_validate(raw)except ValidationError as e:_logger.debug(f"Parsing error: {e.errors()}")except StopAsyncIteration:@@ -132,7 +132,9 @@ class CosmosDbStore(IStore):_logger.error(f"Error accessing CosmosDB: {e}")return call- async def call_asearch_all(self, phone_number: str) -> Optional[list[CallModel]]:+ async def call_asearch_all(+ self, phone_number: str+ ) -> Optional[list[CallStateModel]]:_logger.debug(f"Loading all calls for {phone_number}")calls = []try:@@ -150,7 +152,7 @@ class CosmosDbStore(IStore):if not raw:continuetry:- calls.append(CallModel.model_validate(raw))+ calls.append(CallStateModel.model_validate(raw))except ValidationError as e:_logger.debug(f"Parsing error: {e.errors()}")except CosmosHttpResponseError as e:diff --git a/persistence/isearch.py b/persistence/isearch.pyindex 61d9fb0..777432c 100644--- a/persistence/isearch.py+++ b/persistence/isearch.py@@ -1,5 +1,5 @@from abc import ABC, abstractmethod-from models.call import CallModel+from models.call import CallStateModelfrom models.readiness import ReadinessStatusfrom models.training import TrainingModelfrom persistence.icache import ICache@@ -18,6 +18,6 @@ class ISearch(ABC):@abstractmethodasync def training_asearch_all(- self, text: str, call: CallModel+ self, text: str, call: CallStateModel) -> Optional[list[TrainingModel]]:passdiff --git a/persistence/istore.py b/persistence/istore.pyindex e969394..3ef5d43 100644--- a/persistence/istore.py+++ b/persistence/istore.py@@ -1,5 +1,5 @@from abc import ABC, abstractmethod-from models.call import CallModel+from models.call import CallStateModelfrom models.readiness import ReadinessStatusfrom typing import Optionalfrom uuid import UUID@@ -12,17 +12,19 @@ class IStore(ABC):pass@abstractmethod- async def call_aget(self, call_id: UUID) -> Optional[CallModel]:+ async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:pass@abstractmethod- async def call_aset(self, call: CallModel) -> bool:+ async def call_aset(self, call: CallStateModel) -> bool:pass@abstractmethod- async def call_asearch_one(self, phone_number: str) -> Optional[CallModel]:+ async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:pass@abstractmethod- async def call_asearch_all(self, phone_number: str) -> Optional[list[CallModel]]:+ async def call_asearch_all(+ self, phone_number: str+ ) -> Optional[list[CallStateModel]]:passdiff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex 3b6088d..d96c107 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -3,7 +3,7 @@ from contextlib import asynccontextmanagerfrom helpers.config import CONFIGfrom helpers.config_models.database import SqliteModelfrom helpers.logging import build_logger-from models.call import CallModel+from models.call import CallStateModelfrom models.readiness import ReadinessStatusfrom opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentorfrom persistence.istore import IStore@@ -42,7 +42,7 @@ class SqliteStore(IStore):_logger.error(f"Error requesting SQLite, {e}")return ReadinessStatus.FAIL- async def call_aget(self, call_id: UUID) -> Optional[CallModel]:+ async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:_logger.debug(f"Loading call {call_id}")call = Noneasync with self._use_db() as db:@@ -53,12 +53,12 @@ class SqliteStore(IStore):row = await cursor.fetchone()if row:try:- call = CallModel.model_validate_json(row[0])+ call = CallStateModel.model_validate_json(row[0])except ValidationError as e:_logger.debug(f"Parsing error: {e.errors()}")return call- async def call_aset(self, call: CallModel) -> bool:+ async def call_aset(self, call: CallStateModel) -> bool:# TODO: Catch exceptions and return False if something goes wrongdata = call.model_dump_json(exclude_none=True)_logger.debug(f"Saving call {call.call_id}: {data}")@@ -73,7 +73,7 @@ class SqliteStore(IStore):await db.commit()return True- async def call_asearch_one(self, phone_number: str) -> Optional[CallModel]:+ async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:_logger.debug(f"Loading last call for {phone_number}")call = Noneasync with self._use_db() as db:@@ -87,12 +87,14 @@ class SqliteStore(IStore):row = await cursor.fetchone()if row:try:- call = CallModel.model_validate_json(row[0])+ call = CallStateModel.model_validate_json(row[0])except ValidationError as e:_logger.debug(f"Parsing error: {e.errors()}")return call- async def call_asearch_all(self, phone_number: str) -> Optional[list[CallModel]]:+ async def call_asearch_all(+ self, phone_number: str+ ) -> Optional[list[CallStateModel]]:_logger.debug(f"Loading all {self._config.table} for {phone_number}")calls = []async with self._use_db() as db:@@ -108,7 +110,7 @@ class SqliteStore(IStore):if not row:continuetry:- calls.append(CallModel.model_validate_json(row[0]))+ calls.append(CallStateModel.model_validate_json(row[0]))except ValidationError as e:_logger.debug(f"Parsing error: {e.errors()}")return calls or Nonediff --git a/tests/conftest.py b/tests/conftest.pyindex 8741e3a..3495857 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -5,7 +5,7 @@ from helpers.config import CONFIGfrom helpers.logging import build_loggerfrom langchain_core.language_models import BaseChatModelfrom langchain_openai import AzureChatOpenAI-from models.call import CallModel+from models.call import CallStateModelfrom textwrap import dedentfrom typing import Any, Callable, Optional, Tuple, Unionimport hashlib@@ -80,8 +80,8 @@ def random_text() -> str:@pytest.fixture-def call() -> CallModel:- call = CallModel(+def call() -> CallStateModel:+ call = CallStateModel(phone_number="+33612345678", # type: ignore)return calldiff --git a/tests/llm.py b/tests/llm.pyindex 3425bda..8b79743 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -14,7 +14,7 @@ from helpers.call_events import ()from helpers.config import CONFIGfrom helpers.logging import build_logger-from models.call import CallModel+from models.call import CallStateModelfrom models.reminder import ReminderModelfrom models.training import TrainingModelfrom pydantic import TypeAdapter@@ -149,7 +149,7 @@ _logger = build_logger(__name__)@pytest.mark.repeat(3) # Catch non deterministic issuesasync def test_llm(background_tasks: BackgroundTasks,- call: CallModel,+ call: CallStateModel,claim_tests_excl: list[str],claim_tests_incl: list[str],deepeval_model: GPTModel,diff --git a/tests/search.py b/tests/search.pyindex 221fc99..cd1f929 100644--- a/tests/search.py+++ b/tests/search.py@@ -5,7 +5,7 @@ from deepeval.models.gpt_model import GPTModelfrom deepeval.test_case import LLMTestCasefrom helpers.config import CONFIGfrom helpers.logging import build_logger-from models.call import CallModel+from models.call import CallStateModelfrom typing import Optionalimport asyncioimport pytest@@ -130,7 +130,7 @@ class RagRelevancyMetric(BaseMetric):@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(10) # Catch multi-threading and concurrency issuesasync def test_relevancy(- call: CallModel,+ call: CallStateModel,deepeval_model: GPTModel,user_lang: str,user_message: str,diff --git a/tests/store.py b/tests/store.pyindex 9986242..c85c69c 100644--- a/tests/store.py+++ b/tests/store.py@@ -1,6 +1,6 @@from helpers.config import CONFIGfrom helpers.config_models.database import ModeEnum as DatabaseModeEnum-from models.call import CallModel+from models.call import CallStateModelfrom pytest import assumeimport pytest@@ -20,7 +20,7 @@ import pytest)@pytest.mark.asyncio # Allow async functions@pytest.mark.repeat(10) # Catch multi-threading and concurrency issues-async def test_acid(call: CallModel, database_mode: DatabaseModeEnum) -> None:+async def test_acid(call: CallStateModel, database_mode: DatabaseModeEnum) -> None:"""Test ACID properties of the database backend.