Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!
Python
quality: Add Pyright and fix first smells
Clémence Lesnéa6fd93c75824
diff --git a/Makefile b/Makefileindex 58e0d8b..bebb35c 100644--- a/Makefile+++ b/Makefile@@ -71,6 +71,10 @@ test:.@echo "➡️ Running Pytest..."++ @echo "➡️ Test types (Pyright)..."+ python3 -m pyright .+PUBLIC_DOMAIN=dummy pytest \--junit-xml=test-reports/$$(date +%Y%m%d%H%M%S).xml \tests/*.pydiff --git a/function_app.py b/function_app.pyindex 70d75c2..c62b663 100644--- a/function_app.py+++ b/function_app.py@@ -54,7 +54,9 @@ _jinja = Environment()# Jinja custom functions_jinja.filters["quote_plus"] = lambda x: quote_plus(str(x)) if x else ""-_jinja.filters["markdown"] = lambda x: mistune.create_markdown(plugins=["abbr", "speedup", "url"])(x) if x else "" # type: ignore+_jinja.filters["markdown"] = lambda x: (+ mistune.create_markdown(plugins=["abbr", "speedup", "url"])(x) if x else ""+) # pyright: ignore# Azure Communication Services_automation_client: Optional[CallAutomationClient] = None@@ -271,7 +273,9 @@ async def call_post(req: func.HttpRequest) -> func.HttpResponse:cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,source_caller_id_number=_source_caller,# deepcode ignore AttributeLoadOnNone: Phone number is validated with Pydantic- target_participant=PhoneNumberIdentifier(initiate.phone_number), # type: ignore+ target_participant=PhoneNumberIdentifier(+ initiate.phone_number+ ), # pyright: ignore)logger.info("Created call with connection id: %s",diff --git a/helpers/call_utils.py b/helpers/call_utils.pyindex 7fff245..474a573 100644--- a/helpers/call_utils.py+++ b/helpers/call_utils.py@@ -98,7 +98,9 @@ async def _handle_recognize_media(else None), # If no text is provided, only recognizespeech_language=call.lang.short_code,- target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore+ target_participant=PhoneNumberIdentifier(+ call.initiate.phone_number+ ), # pyright: ignore)except ResourceNotFoundError:logger.debug("Call hung up before recognizing")@@ -376,7 +378,9 @@ async def handle_recognize_ivr(text=text,),speech_language=call.lang.short_code,- target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore+ target_participant=PhoneNumberIdentifier(+ call.initiate.phone_number+ ), # pyright: ignore)except ResourceNotFoundError:logger.debug("Call hung up before recognizing")diff --git a/helpers/config_models/conversation.py b/helpers/config_models/conversation.pyindex 40f7234..9f38c4c 100644--- a/helpers/config_models/conversation.py+++ b/helpers/config_models/conversation.py@@ -187,7 +187,7 @@ def _fields_to_pydantic(name: str, fields: list[ClaimFieldModel]) -> type[BaseMofield_definitions = {field.name: _field_to_pydantic(field) for field in fields}return create_model(name,- **field_definitions, # type: ignore+ **field_definitions, # pyright: ignore__config__=ConfigDict(extra="ignore", # Avoid validation errors, just ignore data),diff --git a/helpers/llm_tools.py b/helpers/llm_tools.pyindex ada7f34..3eec404 100644--- a/helpers/llm_tools.py+++ b/helpers/llm_tools.py@@ -185,7 +185,7 @@ class LlmPlugins:if reminder.title == title:try:reminder.description = description- reminder.due_date_time = due_date_time # type: ignore+ reminder.due_date_time = due_date_time # pyright: ignorereminder.owner = ownerreturn f'Reminder "{title}" updated.'except ValidationError as e:@@ -195,7 +195,7 @@ class LlmPlugins:try:reminder = ReminderModel(description=description,- due_date_time=due_date_time, # type: ignore+ due_date_time=due_date_time, # pyright: ignoreowner=owner,title=title,)diff --git a/helpers/llm_worker.py b/helpers/llm_worker.pyindex 4e5c075..0a5ea47 100644--- a/helpers/llm_worker.py+++ b/helpers/llm_worker.py@@ -335,6 +335,7 @@ async def _completion_sync_worker(), # Usage is async and long-lived, so stop after 10 attemptswait=wait_random_exponential(multiplier=0.8, max=8),)+ choice = Noneasync for attempt in retryed:with attempt:try:@@ -358,8 +359,7 @@ async def _completion_sync_worker(if choice.finish_reason == "length":raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")- content = choice.message.content- return content or None+ return choice.message.content if choice else Nonedef _limit_messages(diff --git a/models/call.py b/models/call.pyindex 8ecf63a..497fb5b 100644--- a/models/call.py+++ b/models/call.py@@ -87,7 +87,7 @@ class CallStateModel(CallGetModel, extra="ignore"):@computed_field@property- def lang(self) -> LanguageEntryModel: # type: ignore+ def lang(self) -> LanguageEntryModel: # pyright: ignorefrom helpers.config import CONFIG # pylint: disable=import-outside-toplevellang = CONFIG.conversation.initiate.langdiff --git a/models/message.py b/models/message.pyindex 26223b8..32e9d03 100644--- a/models/message.py+++ b/models/message.py@@ -100,7 +100,7 @@ class ToolModel(BaseModel):args: dict[str, Any] = repair_json(json_str=json_str,return_objects=True,- ) # type: ignore+ ) # pyright: ignoreif not isinstance(args, dict):logger.warning(diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.pyindex 9dac723..f445cf1 100644--- a/persistence/cosmos_db.py+++ b/persistence/cosmos_db.py@@ -247,6 +247,7 @@ class CosmosDbStore(IStore):self,phone_number: Optional[str] = None,) -> int:+ total = 0try:async with self._use_client() as db:where_clause = (@@ -263,10 +264,11 @@ class CosmosDbStore(IStore):},],)- total: int = await anext(items) # type: ignore+ total: int = await anext(items) # pyright: ignoreexcept CosmosHttpResponseError:logger.error("Error accessing CosmosDB", exc_info=True)- return total if total else 0++ return total@asynccontextmanagerasync def _use_client(self) -> AsyncGenerator[ContainerProxy, None]:diff --git a/pyproject.toml b/pyproject.tomlindex d33aa42..7f86516 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -11,3 +11,6 @@ py-version = "3.11"[tool.pylint.format]max-line-length = "88"++[tool.pyright]+pythonVersion = "3.11"diff --git a/requirements-dev.txt b/requirements-dev.txtindex 43908aa..6b857f3 100644--- a/requirements-dev.txt+++ b/requirements-dev.txt@@ -4,6 +4,7 @@ deptry==0.16.1isort==5.13.2pur==7.3.2pylint==3.2.5+pyright==1.1.371pytest-assume==2.4.3pytest-asyncio==0.23.7 # Required for pytestpytest-repeat==0.9.3 # Required for pytestdiff --git a/tests/cache.py b/tests/cache.pyindex b9f99ac..5999101 100644--- a/tests/cache.py+++ b/tests/cache.py@@ -1,5 +1,5 @@import pytest-from pytest import assume # pylint: disable=no-name-in-module+from pytest import assume # pylint: disable=no-name-in-module # pyright: ignorefrom helpers.config import CONFIGfrom helpers.config_models.cache import ModeEnum as CacheModeEnumdiff --git a/tests/conftest.py b/tests/conftest.pyindex f3ef0ad..ae3d095 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -9,6 +9,7 @@ import pytestimport yamlfrom _pytest.mark.structures import MarkDecoratorfrom azure.communication.callautomation import FileSource, SsmlSource, TextSource+from azure.communication.callautomation._models import TransferCallResultfrom azure.communication.callautomation.aio import (CallAutomationClient,CallConnectionClient,@@ -71,8 +72,9 @@ class CallConnectionClientMock(CallConnectionClient):self,*args,**kwargs,- ) -> None:+ ) -> TransferCallResult:self._transfer_callback()+ return TransferCallResult()async def hang_up(self,@@ -126,7 +128,7 @@ class CallAutomationClientMock(CallAutomationClient):class DeepEvalAzureOpenAI(GPTModel):_cache: pytest.Cache_langchain_kwargs: dict[str, Any]- _model: BaseChatModel+ _model: AzureChatOpenAIdef __init__(self,@@ -148,7 +150,9 @@ class DeepEvalAzureOpenAI(GPTModel):"azure_endpoint": platform.endpoint,"model": platform.model,# Authentication, either RBAC or API- "api_key": platform.api_key.get_secret_value() if platform.api_key else None, # type: ignore+ "api_key": (+ platform.api_key.get_secret_value() if platform.api_key else None+ ), # pyright: ignore"azure_ad_token_provider": (get_bearer_token_provider(ManagedIdentityCredential(),@@ -192,7 +196,7 @@ class DeepEvalAzureOpenAI(GPTModel):def get_model_name(self) -> str:return "Azure OpenAI"- def load_model(self) -> BaseChatModel:+ def load_model(self) -> AzureChatOpenAI:return self._modeldef should_use_azure_openai(self) -> bool:@@ -249,7 +253,7 @@ def call() -> CallStateModel:call = CallStateModel(initiate=CallInitiateModel(**CONFIG.conversation.initiate.model_dump(),- phone_number="+33612345678", # type: ignore+ phone_number="+33612345678", # pyright: ignore),voice_id="dummy",)diff --git a/tests/llm.py b/tests/llm.pyindex 61bf19a..7ece69b 100644--- a/tests/llm.py+++ b/tests/llm.py@@ -16,7 +16,7 @@ from deepeval.metrics import (from deepeval.models.gpt_model import GPTModelfrom deepeval.test_case import LLMTestCasefrom pydantic import TypeAdapter-from pytest import assume # pylint: disable=no-name-in-module+from pytest import assume # pylint: disable=no-name-in-module # pyright: ignorefrom helpers.call_events import (on_call_connected,@@ -36,7 +36,6 @@ from tests.conftest import CallAutomationClientMock, with_conversationsclass ClaimRelevancyMetric(BaseMetric):call: CallStateModelmodel: GPTModel- threshold: floatdef __init__(self,@@ -225,7 +224,7 @@ class ClaimRelevancyMetric(BaseMetric):return self.success or False@property- def __name__(self):+ def __name__(self): # pyright: ignorereturn "Claim Relevancy"@@ -339,7 +338,7 @@ async def test_llm(assume(call.synthesis, "No synthesis found")# Define LLM metrics- llm_metrics = [+ llm_metrics: list[BaseMetric] = [BiasMetric(threshold=1, model=deepeval_model), # Gender, age, ethnicityClaimRelevancyMetric(call=call,diff --git a/tests/local.py b/tests/local.pyindex e1c37ee..7109cca 100644--- a/tests/local.py+++ b/tests/local.py@@ -34,9 +34,9 @@ async def main() -> None:call = CallStateModel(initiate=CallInitiateModel(**CONFIG.conversation.initiate.model_dump(),- phone_number="+33612345678", # type: ignore+ phone_number="+33612345678", # pyright: ignore),- lang_shmediumort_code="fr-FR",+ lang_short_code="fr-FR",voice_id="dummy",)automation_client = CallAutomationClientMock(diff --git a/tests/search.py b/tests/search.pyindex 230a09b..168b352 100644--- a/tests/search.py+++ b/tests/search.py@@ -7,7 +7,7 @@ from deepeval.metrics import BaseMetricfrom deepeval.models.gpt_model import GPTModelfrom deepeval.test_case import LLMTestCasefrom pydantic import TypeAdapter-from pytest import assume # pylint: disable=no-name-in-module+from pytest import assume # pylint: disable=no-name-in-module # pyright: ignorefrom helpers.config import CONFIGfrom helpers.logging import logger@@ -19,7 +19,6 @@ from tests.conftest import with_conversationsclass RagRelevancyMetric(BaseMetric):model: GPTModel- threshold: floatdef __init__(self,@@ -114,7 +113,7 @@ class RagRelevancyMetric(BaseMetric):return self.success or False@property- def __name__(self):+ def __name__(self): # pyright: ignorereturn "RAG Relevancy"@@ -195,7 +194,7 @@ async def test_relevancy()# Define LLM metrics- llm_metrics = [+ llm_metrics: list[BaseMetric] = [RagRelevancyMetric(threshold=0.5, model=deepeval_model), # Compare speech to the retrieval contextdiff --git a/tests/store.py b/tests/store.pyindex 409c7be..ab2e665 100644--- a/tests/store.py+++ b/tests/store.py@@ -1,5 +1,5 @@import pytest-from pytest import assume # pylint: disable=no-name-in-module+from pytest import assume # pylint: disable=no-name-in-module # pyright: ignorefrom helpers.config import CONFIGfrom helpers.config_models.database import ModeEnum as DatabaseModeEnum