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

quality: Add Pyright and fix first smells

Clémence Lesnéa6fd93c75824
diff --git a/Makefile b/Makefile
index 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/*.py
diff --git a/function_app.py b/function_app.py
index 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.py
index 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 recognize
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")
@@ -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.py
index 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[BaseMo
field_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.py
index 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: ignore
reminder.owner = owner
return 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: ignore
owner=owner,
title=title,
)
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 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 attempts
wait=wait_random_exponential(multiplier=0.8, max=8),
)
+ choice = None
async 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 None
def _limit_messages(
diff --git a/models/call.py b/models/call.py
index 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: ignore
from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
lang = CONFIG.conversation.initiate.lang
diff --git a/models/message.py b/models/message.py
index 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: ignore
if not isinstance(args, dict):
logger.warning(
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index 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 = 0
try:
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: ignore
except CosmosHttpResponseError:
logger.error("Error accessing CosmosDB", exc_info=True)
- return total if total else 0
+
+ return total
@asynccontextmanager
async def _use_client(self) -> AsyncGenerator[ContainerProxy, None]:
diff --git a/pyproject.toml b/pyproject.toml
index 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.txt
index 43908aa..6b857f3 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -4,6 +4,7 @@ deptry==0.16.1
isort==5.13.2
pur==7.3.2
pylint==3.2.5
+pyright==1.1.371
pytest-assume==2.4.3
pytest-asyncio==0.23.7 # Required for pytest
pytest-repeat==0.9.3 # Required for pytest
diff --git a/tests/cache.py b/tests/cache.py
index 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: ignore
from helpers.config import CONFIG
from helpers.config_models.cache import ModeEnum as CacheModeEnum
diff --git a/tests/conftest.py b/tests/conftest.py
index f3ef0ad..ae3d095 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -9,6 +9,7 @@ import pytest
import yaml
from _pytest.mark.structures import MarkDecorator
from azure.communication.callautomation import FileSource, SsmlSource, TextSource
+from azure.communication.callautomation._models import TransferCallResult
from 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: AzureChatOpenAI
def __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._model
def 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.py
index 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 GPTModel
from deepeval.test_case import LLMTestCase
from pydantic import TypeAdapter
-from pytest import assume # pylint: disable=no-name-in-module
+from pytest import assume # pylint: disable=no-name-in-module # pyright: ignore
from helpers.call_events import (
on_call_connected,
@@ -36,7 +36,6 @@ from tests.conftest import CallAutomationClientMock, with_conversations
class ClaimRelevancyMetric(BaseMetric):
call: CallStateModel
model: GPTModel
- threshold: float
def __init__(
self,
@@ -225,7 +224,7 @@ class ClaimRelevancyMetric(BaseMetric):
return self.success or False
@property
- def __name__(self):
+ def __name__(self): # pyright: ignore
return "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, ethnicity
ClaimRelevancyMetric(
call=call,
diff --git a/tests/local.py b/tests/local.py
index 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.py
index 230a09b..168b352 100644
--- a/tests/search.py
+++ b/tests/search.py
@@ -7,7 +7,7 @@ from deepeval.metrics import BaseMetric
from deepeval.models.gpt_model import GPTModel
from deepeval.test_case import LLMTestCase
from pydantic import TypeAdapter
-from pytest import assume # pylint: disable=no-name-in-module
+from pytest import assume # pylint: disable=no-name-in-module # pyright: ignore
from helpers.config import CONFIG
from helpers.logging import logger
@@ -19,7 +19,6 @@ from tests.conftest import with_conversations
class RagRelevancyMetric(BaseMetric):
model: GPTModel
- threshold: float
def __init__(
self,
@@ -114,7 +113,7 @@ class RagRelevancyMetric(BaseMetric):
return self.success or False
@property
- def __name__(self):
+ def __name__(self): # pyright: ignore
return "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 context
diff --git a/tests/store.py b/tests/store.py
index 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: ignore
from helpers.config import CONFIG
from helpers.config_models.database import ModeEnum as DatabaseModeEnum