Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
refacto: Use native list type instead typing implementation
Clémence Lesnéb5e303a74e89
diff --git a/helpers/call_llm.py b/helpers/call_llm.pyindex 21cc367..26877f0 100644--- a/helpers/call_llm.py+++ b/helpers/call_llm.py@@ -1,4 +1,4 @@-from typing import Awaitable, Callable, List, Optional, Tuple, Type+from typing import Awaitable, Callable, Optional, Tuple, Typefrom azure.communication.callautomation import (CallConnectionClient,)@@ -103,7 +103,7 @@ async def llm_model(def _llm_completion_system(system: str, call: CallModel-) -> List[ChatCompletionSystemMessageParam]:+) -> list[ChatCompletionSystemMessageParam]:messages = [ChatCompletionSystemMessageParam(content=CONFIG.prompts.llm.default_system(diff --git a/helpers/call_utils.py b/helpers/call_utils.pyindex bf05825..f858b18 100644--- a/helpers/call_utils.py+++ b/helpers/call_utils.py@@ -3,7 +3,7 @@ from helpers.config import CONFIGfrom helpers.logging import build_loggerfrom models.call import CallModelfrom models.message import StyleEnum as MessageStyleEnum-from typing import Generator, List, Optional+from typing import Generator, Optionalfrom azure.communication.callautomation import (FileSource,PhoneNumberIdentifier,@@ -209,7 +209,7 @@ async def handle_recognize_ivr(client: CallConnectionClient,call: CallModel,text: str,- choices: List[RecognitionChoice],+ choices: list[RecognitionChoice],) -> None:_logger.info(f"Playing text before IVR: {text}")_logger.debug(f"Recognizing IVR")diff --git a/helpers/config_models/content_safety.py b/helpers/config_models/content_safety.pyindex 9272fea..01102d4 100644--- a/helpers/config_models/content_safety.py+++ b/helpers/config_models/content_safety.py@@ -1,10 +1,9 @@-from typing import Listfrom pydantic import SecretStr, Field, BaseModelclass ContentSafetyModel(BaseModel):access_key: SecretStr- blocklists: List[str] = []+ blocklists: list[str] = []category_hate_score: int = Field(default=0, ge=0, le=7)category_self_harm_score: int = Field(default=1, ge=0, le=7)category_sexual_score: int = Field(default=2, ge=0, le=7)diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.pyindex 75ae115..93ab052 100644--- a/helpers/config_models/prompts.py+++ b/helpers/config_models/prompts.py@@ -9,7 +9,7 @@ from models.reminder import ReminderModelfrom models.training import TrainingModelfrom pydantic import TypeAdapter, BaseModelfrom textwrap import dedent-from typing import List, Optional+from typing import Optionalclass SoundModel(BaseModel):@@ -303,7 +303,7 @@ class LlmModel(BaseModel):))- def chat_system(self, call: CallModel, trainings: List[TrainingModel]) -> str:+ def chat_system(self, call: CallModel, trainings: list[TrainingModel]) -> str:from helpers.config import CONFIGfrom models.message import (ActionEnum as MessageActionEnum,@@ -316,7 +316,7 @@ class LlmModel(BaseModel):bot_company=CONFIG.workflow.bot_company,claim=call.claim.model_dump_json(),default_lang=call.lang.human_name,- reminders=TypeAdapter(List[ReminderModel])+ reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),styles=", ".join([style.value for style in MessageStyleEnum]),@@ -328,8 +328,8 @@ class LlmModel(BaseModel):self.sms_summary_system_tpl,claim=call.claim.model_dump_json(),default_lang=call.lang.human_name,- messages=TypeAdapter(List[MessageModel]).dump_json(call.messages).decode(),- reminders=TypeAdapter(List[ReminderModel])+ messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),+ reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),)@@ -339,8 +339,8 @@ class LlmModel(BaseModel):self.synthesis_short_system_tpl,claim=call.claim.model_dump_json(),default_lang=call.lang.human_name,- messages=TypeAdapter(List[MessageModel]).dump_json(call.messages).decode(),- reminders=TypeAdapter(List[ReminderModel])+ messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),+ reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),)@@ -350,8 +350,8 @@ class LlmModel(BaseModel):self.synthesis_long_system_tpl,claim=call.claim.model_dump_json(),default_lang=call.lang.human_name,- messages=TypeAdapter(List[MessageModel]).dump_json(call.messages).decode(),- reminders=TypeAdapter(List[ReminderModel])+ messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),+ reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),)@@ -370,17 +370,17 @@ class LlmModel(BaseModel):return self._return(self.citations_system_tpl,claim=call.claim.model_dump_json(),- messages=TypeAdapter(List[MessageModel])+ messages=TypeAdapter(list[MessageModel]).dump_json([messagefor message in call.messages- if message.persona is not MessagePersonaEnum.TOOL+ if message.persona != MessagePersonaEnum.TOOL],exclude={"tool_calls"},).decode(), # Filter out tool messages, to avoid LLM to cite itself- reminders=TypeAdapter(List[ReminderModel])+ reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),text=text,@@ -391,8 +391,8 @@ class LlmModel(BaseModel):self.next_system_tpl,actions=", ".join([action.value for action in NextActionEnum]),claim=call.claim.model_dump_json(),- messages=TypeAdapter(List[MessageModel]).dump_json(call.messages).decode(),- reminders=TypeAdapter(List[ReminderModel])+ messages=TypeAdapter(list[MessageModel]).dump_json(call.messages).decode(),+ reminders=TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),)@@ -400,7 +400,7 @@ class LlmModel(BaseModel):def _return(self,prompt_tpl: str,- trainings: Optional[List[TrainingModel]] = None,+ trainings: Optional[list[TrainingModel]] = None,**kwargs: str,) -> str:# Build templatediff --git a/helpers/config_models/workflow.py b/helpers/config_models/workflow.pyindex cdd81dc..8b1851f 100644--- a/helpers/config_models/workflow.py+++ b/helpers/config_models/workflow.py@@ -1,7 +1,6 @@from functools import cached_propertyfrom pydantic import BaseModelfrom pydantic_extra_types.phone_numbers import PhoneNumber-from typing import List# E164 is standard accross all Microsoft services@@ -15,7 +14,7 @@ class LanguageEntryModel(BaseModel):See: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts#supported-languages"""- pronunciations_en: List[str]+ pronunciations_en: list[str]short_code: strvoice: str@@ -33,7 +32,7 @@ class LanguageModel(BaseModel):"""default_short_code: str = "fr-FR"- availables: List[LanguageEntryModel] = [+ availables: list[LanguageEntryModel] = [LanguageEntryModel(pronunciations_en=["French", "FR", "France"],short_code="fr-FR",diff --git a/helpers/llm_tools.py b/helpers/llm_tools.pyindex def9fbd..8dc01a9 100644--- a/helpers/llm_tools.py+++ b/helpers/llm_tools.py@@ -10,7 +10,7 @@ from models.message import StyleEnum as MessageStyleEnumfrom models.reminder import ReminderModelfrom openai.types.chat import ChatCompletionToolParamfrom pydantic import ValidationError-from typing import Awaitable, Callable, Annotated, List, Literal+from typing import Awaitable, Callable, Annotated, Literalimport asyncio@@ -231,7 +231,7 @@ class LlmPlugins:return f"Notifying {service} for {reason}."@staticmethod- def to_openai() -> List[ChatCompletionToolParam]:+ def to_openai() -> list[ChatCompletionToolParam]:return [function_schema(func[1])for func in getmembers(LlmPlugins, isfunction)diff --git a/helpers/llm_utils.py b/helpers/llm_utils.pyindex 480cd77..1706fc2 100644--- a/helpers/llm_utils.py+++ b/helpers/llm_utils.py@@ -10,7 +10,6 @@ from typing import (Callable,Dict,ForwardRef,- List,Set,Tuple,Type,@@ -35,7 +34,7 @@ class Parameters(BaseModel):"""properties: Dict[str, JsonSchemaValue]- required: List[str]+ required: list[str]type: str = "object"@@ -149,7 +148,7 @@ def _param_annotations(return {k: v.annotationfor k, v in typed_signature.parameters.items()- if v.annotation is not inspect.Signature.empty and k != "self"+ if v.annotation != inspect.Signature.empty and k != "self"}@@ -193,7 +192,7 @@ def _parameter_json_schema(return schema-def _required_params(typed_signature: inspect.Signature) -> List[str]:+def _required_params(typed_signature: inspect.Signature) -> list[str]:"""Get the required parameters of a function.@@ -228,7 +227,7 @@ def _default_values(typed_signature: inspect.Signature) -> Dict[str, Any]:def _parameters(- required: List[str],+ required: list[str],param_annotations: Dict[str, Union[Annotated[Type[Any], str], Type[Any]]],default_values: Dict[str, Any],) -> Parameters:@@ -246,14 +245,14 @@ def _parameters(properties={k: _parameter_json_schema(k, v, default_values)for k, v in param_annotations.items()- if v is not inspect.Signature.empty and k != "self"+ if v != inspect.Signature.empty and k != "self"},required=required,)def _missing_annotations(- typed_signature: inspect.Signature, required: List[str]+ typed_signature: inspect.Signature, required: list[str]) -> Tuple[Set[str], Set[str]]:"""Get the missing annotations of a function.@@ -270,7 +269,7 @@ def _missing_annotations(all_missing = {kfor k, v in typed_signature.parameters.items()- if v.annotation is inspect.Signature.empty and k != "self"+ if v.annotation == inspect.Signature.empty and k != "self"}missing = all_missing.intersection(set(required))unannotated_with_default = all_missing.difference(missing)diff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex e32cae3..abd9b18 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -28,7 +28,7 @@ from tenacity import (wait_random_exponential,retry_if_exception_type,)-from typing import AsyncGenerator, List, Optional, Tuple, Type, TypeVar, Union+from typing import AsyncGenerator, Optional, Tuple, Type, TypeVar, Unionfrom httpx import ReadErrorfrom models.message import MessageModelimport tiktoken@@ -62,9 +62,9 @@ class SafetyCheckError(Exception):async def completion_stream(is_backup: bool,max_tokens: int,- messages: List[MessageModel],- system: List[ChatCompletionSystemMessageParam],- tools: Optional[List[ChatCompletionToolParam]] = None,+ messages: list[MessageModel],+ system: list[ChatCompletionSystemMessageParam],+ tools: Optional[list[ChatCompletionToolParam]] = None,) -> AsyncGenerator[ChoiceDelta, None]:"""Returns a stream of completion results.@@ -113,8 +113,8 @@ async def completion_stream()async def completion_sync(max_tokens: int,- messages: List[MessageModel],- system: List[ChatCompletionSystemMessageParam],+ messages: list[MessageModel],+ system: list[ChatCompletionSystemMessageParam],json_output: bool = False,) -> Optional[str]:"""@@ -162,9 +162,9 @@ async def completion_sync()async def completion_model_sync(max_tokens: int,- messages: List[MessageModel],+ messages: list[MessageModel],model: Type[ModelType],- system: List[ChatCompletionSystemMessageParam],+ system: list[ChatCompletionSystemMessageParam],) -> Optional[ModelType]:"""Returns an object validated against a given model, from a completion result.@@ -184,12 +184,12 @@ async def completion_model_sync(def _prepare_messages(context: int,- messages: List[MessageModel],+ messages: list[MessageModel],model: str,- system: List[ChatCompletionSystemMessageParam],+ system: list[ChatCompletionSystemMessageParam],max_messages: int = 1000,- tools: Optional[List[ChatCompletionToolParam]] = None,-) -> List[+ tools: Optional[list[ChatCompletionToolParam]] = None,+) -> list[Union[ChatCompletionAssistantMessageParam,ChatCompletionSystemMessageParam,@@ -305,7 +305,7 @@ async def _contentsafety_analysis(text: str) -> AnalyzeTextResult:def _contentsafety_category_test(- res: List[TextCategoriesAnalysis],+ res: list[TextCategoriesAnalysis],category: TextCategory,score: int,) -> bool:diff --git a/helpers/translation.py b/helpers/translation.pyindex daa96f9..788cd27 100644--- a/helpers/translation.py+++ b/helpers/translation.py@@ -4,7 +4,7 @@ from azure.core.credentials import AzureKeyCredentialfrom contextlib import asynccontextmanagerfrom helpers.config import CONFIGfrom helpers.logging import build_logger-from typing import AsyncGenerator, List, Optional+from typing import AsyncGenerator, Optionalfrom azure.core.exceptions import HttpResponseErrorfrom tenacity import (retry,@@ -45,7 +45,7 @@ async def translate_text(# Try livetranslation: Optional[str] = Noneasync with _use_client() as client: # Perform translation- res: List[TranslatedTextItem] = await client.translate(+ res: list[TranslatedTextItem] = await client.translate(content=[InputTextItem(text=text)], # type: ignorefrom_parameter=source_lang,to=[target_lang],diff --git a/main.py b/main.pyindex 9f91e4d..daf0db2 100644--- a/main.py+++ b/main.py@@ -10,7 +10,6 @@ _logger.info(f"claim-ai v{CONFIG.version}")# General importsfrom typing import (Any,- List,Optional,Union,)@@ -148,7 +147,7 @@ async def report_call_get(phone_number: str, call_id: UUID) -> HTMLResponse:"/call",description="Get all calls by phone number.",)-async def call_get(phone_number: str) -> List[CallModel]:+async def call_get(phone_number: str) -> list[CallModel]:return await _db.call_asearch_all(phone_number) or []@@ -288,7 +287,7 @@ async def _communication_event_worker(if recognition_result == "speech": # Handle voicespeech_text = event.data["speechResult"]["speech"]if (- speech_text is not None and len(speech_text) > 0+ speech_text != None and len(speech_text) > 0): # TODO: Is this check necessary?await on_speech_recognized(background_tasks=background_tasks,diff --git a/models/call.py b/models/call.pyindex 1294b2a..e22d88d 100644--- a/models/call.py+++ b/models/call.py@@ -7,7 +7,7 @@ from models.reminder import ReminderModelfrom models.synthesis import SynthesisModelfrom models.training import TrainingModelfrom pydantic import BaseModel, Field, computed_field-from typing import List, Optional+from typing import Optionalfrom uuid import UUID, uuid4import asyncioimport random@@ -28,11 +28,11 @@ class CallModel(BaseModel):lang_short_code: Optional[str] = None# Editable fieldsclaim: ClaimModel = Field(default_factory=ClaimModel)- messages: List[MessageModel] = []+ messages: list[MessageModel] = []next: Optional[NextModel] = Nonephone_number: strrecognition_retry: int = Field(default=0)- reminders: List[ReminderModel] = []+ reminders: list[ReminderModel] = []synthesis: Optional[SynthesisModel] = None@computed_field@@ -54,7 +54,7 @@ class CallModel(BaseModel):def lang(self, value: LanguageEntryModel) -> None:self.lang_short_code = value.short_code- async def trainings(self) -> List[TrainingModel]:+ async def trainings(self) -> list[TrainingModel]:"""Get the trainings from the last messages.diff --git a/models/message.py b/models/message.pyindex 6068278..e52c42e 100644--- a/models/message.py+++ b/models/message.py@@ -1,7 +1,7 @@from datetime import datetime, UTCfrom enum import Enumfrom pydantic import BaseModel, Field, field_validator-from typing import Any, List, Optional, Tuple, Union+from typing import Any, Optional, Tuple, Unionfrom openai.types.chat import (ChatCompletionAssistantMessageParam,ChatCompletionMessageToolCallParam,@@ -100,7 +100,7 @@ class ToolModel(BaseModel):return_objects=True,) # type: ignore- if args is None:+ if args == None:logger.warn(f"Error decoding JSON args for function {name}: {self.function_arguments[:20]}...{self.function_arguments[-20:]}")@@ -118,7 +118,7 @@ class ToolModel(BaseModel):self.content = res@staticmethod- def _available_function_names() -> List[str]:+ def _available_function_names() -> list[str]:from helpers.llm_tools import LlmPluginsreturn [name for name, _ in getmembers(LlmPlugins, isfunction)]@@ -132,11 +132,11 @@ class MessageModel(BaseModel):content: strpersona: PersonaEnumstyle: StyleEnum = StyleEnum.NONE- tool_calls: List[ToolModel] = []+ tool_calls: list[ToolModel] = []def to_openai(self,- ) -> List[+ ) -> list[Union[ChatCompletionAssistantMessageParam,ChatCompletionToolMessageParam,diff --git a/persistence/ai_search.py b/persistence/ai_search.pyindex f8950e6..02bb525 100644--- a/persistence/ai_search.py+++ b/persistence/ai_search.py@@ -15,7 +15,7 @@ from persistence.icache import ICachefrom persistence.isearch import ISearchfrom pydantic import TypeAdapterfrom pydantic import ValidationError-from typing import AsyncGenerator, List, Optional+from typing import AsyncGenerator, Optionalfrom tenacity import (retry,stop_after_attempt,@@ -46,7 +46,7 @@ class AiSearchSearch(ISearch):)async def training_asearch_all(self, text: str, call: CallModel- ) -> Optional[List[TrainingModel]]:+ ) -> Optional[list[TrainingModel]]:_logger.debug(f'Searching training data for "{text}"')if not text:return None@@ -56,13 +56,13 @@ class AiSearchSearch(ISearch):cached = await self._cache.aget(cache_key)if cached:try:- return TypeAdapter(List[TrainingModel]).validate_json(cached)+ return TypeAdapter(list[TrainingModel]).validate_json(cached)except ValidationError:_logger.warning(f"Error parsing cached training: {cached}")pass# Try live- trainings: List[TrainingModel] = []+ trainings: list[TrainingModel] = []try:async with self._use_db() as db:results = await db.search(@@ -118,7 +118,7 @@ class AiSearchSearch(ISearch):await self._cache.aset(cache_key,(- TypeAdapter(List[TrainingModel]).dump_json(trainings)+ TypeAdapter(list[TrainingModel]).dump_json(trainings)if trainingselse None),diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex b5cd07d..d0b7018 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -10,7 +10,7 @@ from helpers.logging import build_loggerfrom models.call import CallModelfrom persistence.istore import IStorefrom pydantic import ValidationError-from typing import AsyncGenerator, List, Optional+from typing import AsyncGenerator, Optionalfrom uuid import UUIDfrom tenacity import (retry,@@ -112,7 +112,7 @@ class CosmosDbStore(IStore):stop=stop_after_attempt(3),wait=wait_random_exponential(multiplier=0.5, max=30),)- async def call_asearch_all(self, phone_number: str) -> Optional[List[CallModel]]:+ async def call_asearch_all(self, phone_number: str) -> Optional[list[CallModel]]:_logger.debug(f"Loading all calls for {phone_number}")calls = []try:diff --git a/persistence/isearch.py b/persistence/isearch.pyindex 9590b22..451a220 100644--- a/persistence/isearch.py+++ b/persistence/isearch.py@@ -2,7 +2,7 @@ from abc import ABC, abstractmethodfrom models.call import CallModelfrom models.training import TrainingModelfrom persistence.icache import ICache-from typing import List, Optional+from typing import Optionalclass ISearch(ABC):@@ -14,5 +14,5 @@ class ISearch(ABC):@abstractmethodasync def training_asearch_all(self, text: str, call: CallModel- ) -> Optional[List[TrainingModel]]:+ ) -> Optional[list[TrainingModel]]:passdiff --git a/persistence/istore.py b/persistence/istore.pyindex 84bb7ef..08a337e 100644--- a/persistence/istore.py+++ b/persistence/istore.py@@ -1,6 +1,6 @@from abc import ABC, abstractmethodfrom models.call import CallModel-from typing import List, Optional+from typing import Optionalfrom uuid import UUID@@ -18,5 +18,5 @@ class IStore(ABC):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[CallModel]]:passdiff --git a/persistence/sqlite.py b/persistence/sqlite.pyindex ed8c1d3..2c169ef 100644--- a/persistence/sqlite.py+++ b/persistence/sqlite.py@@ -7,7 +7,7 @@ from helpers.logging import build_loggerfrom models.call import CallModelfrom persistence.istore import IStorefrom pydantic import ValidationError-from typing import AsyncGenerator, List, Optional+from typing import AsyncGenerator, Optionalfrom uuid import UUIDimport jsonimport os@@ -75,7 +75,7 @@ class SqliteStore(IStore):_logger.warning(f"Error parsing call: {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[CallModel]]:_logger.debug(f"Loading all {self._config.table} for {phone_number}")calls = []async with self._use_db() as db:diff --git a/test.py b/test.pyindex a865ecd..a0ec387 100644--- a/test.py+++ b/test.py@@ -25,7 +25,7 @@ from models.call import CallModelfrom models.reminder import ReminderModelfrom models.training import TrainingModelfrom pydantic import TypeAdapter-from typing import Callable, List, Optional, Union+from typing import Callable, Optional, Unionimport pytestimport timeimport xml.etree.ElementTree as ET@@ -288,8 +288,8 @@ async def test_llm(latency=latency_per_input,retrieval_context=[call.claim.model_dump_json(),- TypeAdapter(List[ReminderModel]).dump_json(call.reminders).decode(),- TypeAdapter(List[TrainingModel]).dump_json(await call.trainings()).decode(),+ TypeAdapter(list[ReminderModel]).dump_json(call.reminders).decode(),+ TypeAdapter(list[TrainingModel]).dump_json(await call.trainings()).decode(),],)