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: Comply with Ruff

Clémence Lesnébd191056cdf7
diff --git a/examples/blocklist.ipynb b/examples/blocklist.ipynb
index ee169d7..8549cea 100644
--- a/examples/blocklist.ipynb
+++ b/examples/blocklist.ipynb
@@ -63,14 +63,14 @@
"metadata": {},
"outputs": [],
"source": [
+ "import pandas as pd\n",
"from azure.ai.contentsafety import BlocklistClient\n",
"from azure.ai.contentsafety.models import (\n",
+ " AddOrUpdateTextBlocklistItemsOptions,\n",
" TextBlocklist,\n",
" TextBlocklistItem,\n",
- " AddOrUpdateTextBlocklistItemsOptions,\n",
")\n",
"from azure.core.credentials import AzureKeyCredential\n",
- "import pandas as pd\n",
"\n",
"key = AzureKeyCredential(\"xxx\")\n",
"client = BlocklistClient(\n",
@@ -102,10 +102,10 @@
"blocklists = client.list_text_blocklists()\n",
"\n",
"if not blocklists:\n",
- " print(\"There are no blocklists.\")\n",
+ " print(\"There are no blocklists.\") # noqa: T201\n",
"\n",
"for blocklist in blocklists:\n",
- " print(f\"{blocklist.blocklist_name}: {blocklist.description}\")"
+ " print(f\"{blocklist.blocklist_name}: {blocklist.description}\") # noqa: T201"
]
},
{
@@ -135,7 +135,7 @@
" block_items[row[\"blocklist\"]].append(text)\n",
"\n",
"for blocklist, words in block_items.items():\n",
- " print(f\"Creating blocklist {blocklist} with {len(words)} words\")\n",
+ " print(f\"Creating blocklist {blocklist} with {len(words)} words\") # noqa: T201\n",
" client.create_or_update_text_blocklist(\n",
" blocklist_name=blocklist,\n",
" options=TextBlocklist(blocklist_name=blocklist),\n",
diff --git a/function_app.py b/function_app.py
index 15d31b4..d793b9e 100644
--- a/function_app.py
+++ b/function_app.py
@@ -3,7 +3,6 @@ import json
from datetime import timedelta
from http import HTTPStatus
from os import getenv
-from typing import Any, Optional, Union
from urllib.parse import quote_plus, urljoin
from uuid import UUID
@@ -66,7 +65,7 @@ _jinja.filters["markdown"] = lambda x: (
) # pyright: ignore
# Azure Communication Services
-_automation_client: Optional[CallAutomationClient] = None
+_automation_client: CallAutomationClient | None = None
_source_caller = PhoneNumberIdentifier(CONFIG.communication_services.phone_number)
logger.info("Using phone number %s", CONFIG.communication_services.phone_number)
_communication_services_jwks_client = jwt.PyJWKClient(
@@ -97,7 +96,9 @@ logger.info("Using call event URL %s", _COMMUNICATIONSERVICES_CALLABACK_TPL)
methods=["GET"],
)
@tracer.start_as_current_span("openapi_get")
-async def openapi_get(req: func.HttpRequest) -> func.HttpResponse:
+async def openapi_get(
+ req: func.HttpRequest, # noqa: ARG001
+) -> func.HttpResponse:
"""
Generate the OpenAPI specification for the API.
@@ -105,10 +106,9 @@ async def openapi_get(req: func.HttpRequest) -> func.HttpResponse:
Returns a JSON object with the OpenAPI specification.
"""
- with open(
+ with open( # noqa: ASYNC230
encoding="utf-8",
file=resources_dir("openapi.json"),
- mode="r",
) as f:
openapi = json.load(f)
openapi["info"]["version"] = CONFIG.version
@@ -130,7 +130,9 @@ async def openapi_get(req: func.HttpRequest) -> func.HttpResponse:
methods=["GET"],
)
@tracer.start_as_current_span("health_liveness_get")
-async def health_liveness_get(req: func.HttpRequest) -> func.HttpResponse:
+async def health_liveness_get(
+ req: func.HttpRequest, # noqa: ARG001
+) -> func.HttpResponse:
"""
Check if the service is running.
@@ -146,7 +148,9 @@ async def health_liveness_get(req: func.HttpRequest) -> func.HttpResponse:
methods=["GET"],
)
@tracer.start_as_current_span("health_readiness_get")
-async def health_readiness_get(req: func.HttpRequest) -> func.HttpResponse:
+async def health_readiness_get(
+ req: func.HttpRequest, # noqa: ARG001
+) -> func.HttpResponse:
"""
Check if the service is ready to serve requests.
@@ -415,9 +419,7 @@ 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
- ), # pyright: ignore
+ target_participant=PhoneNumberIdentifier(initiate.phone_number), # pyright: ignore
)
logger.info(
"Created call with connection id: %s",
@@ -556,7 +558,7 @@ async def communicationservices_event_post(
Returns a 204 No Content if the events are properly fomatted. A 401 Unauthorized if the JWT token is invalid. Otherwise, returns a 400 Bad Request.
"""
# Validate JWT token
- service_jwt: Union[str, None] = req.headers.get("Authorization")
+ service_jwt: str | None = req.headers.get("Authorization")
if not service_jwt:
return _standard_error(
message="Authorization header missing",
@@ -614,7 +616,8 @@ async def communicationservices_event_post(
return func.HttpResponse(status_code=HTTPStatus.NO_CONTENT)
-async def _communicationservices_event_worker(
+# TODO: Refacto, too long (and remove PLR0912/PLR0915 ignore)
+async def _communicationservices_event_worker( # noqa: PLR0912, PLR0915
call_id: UUID,
event_dict: dict,
post: func.Out[str],
@@ -688,7 +691,7 @@ async def _communicationservices_event_worker(
recognition_result: str = event.data["recognitionType"]
if recognition_result == "speech": # Handle voice
- speech_text: Optional[str] = event.data["speechResult"]["speech"]
+ speech_text: str | None = event.data["speechResult"]["speech"]
if speech_text:
await on_speech_recognized(
call=call,
@@ -835,7 +838,7 @@ def _trigger_post_event(
async def _communicationservices_event_url(
- phone_number: PhoneNumber, initiate: Optional[CallInitiateModel] = None
+ phone_number: PhoneNumber, initiate: CallInitiateModel | None = None
) -> tuple[str, CallStateModel]:
"""
Generate the callback URL for a call.
@@ -933,7 +936,7 @@ async def twilio_sms_post(
)
-def _str_to_contexts(value: Optional[str]) -> Optional[set[CallContextEnum]]:
+def _str_to_contexts(value: str | None) -> set[CallContextEnum] | None:
"""
Convert a string to a set of contexts.
@@ -965,12 +968,7 @@ def _validation_error(
Response body is a JSON object with the following structure:
```
- {
- "error": {
- "message": "Validation error",
- "details": ["Error message"]
- }
- }
+ {"error": {"message": "Validation error", "details": ["Error message"]}}
```
Returns a 400 Bad Request with a JSON body.
@@ -991,7 +989,7 @@ def _validation_error(
def _standard_error(
message: str,
- details: Optional[list[str]] = None,
+ details: list[str] | None = None,
status_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
) -> func.HttpResponse:
"""
@@ -1000,12 +998,7 @@ def _standard_error(
Response body is a JSON object with the following structure:
```
- {
- "error": {
- "message": "Error message",
- "details": ["Error details"]
- }
- }
+ {"error": {"message": "Error message", "details": ["Error details"]}}
```
Returns a JOSN with a JSON body and the specified status code.
@@ -1031,7 +1024,7 @@ async def _use_automation_client() -> CallAutomationClient:
Returns a `CallAutomationClient` instance.
"""
- global _automation_client # pylint: disable=global-statement
+ global _automation_client # noqa: PLW0603
if not isinstance(_automation_client, CallAutomationClient):
_automation_client = CallAutomationClient(
# Deployment
diff --git a/helpers/__init__.py b/helpers/__init__.py
index ba2b052..cdf06e2 100644
--- a/helpers/__init__.py
+++ b/helpers/__init__.py
@@ -4,10 +4,10 @@ from dotenv import find_dotenv, load_dotenv
def init_env():
path = find_dotenv()
if not path:
- print("Env file not found")
+ print("Env file not found") # noqa: T201
return
load_dotenv(path)
- print(f'Env file loaded from "{path}"')
+ print(f'Env file loaded from "{path}"') # noqa: T201
init_env()
diff --git a/helpers/call_events.py b/helpers/call_events.py
index 099fb30..c19d87a 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -1,5 +1,5 @@
import asyncio
-from typing import Awaitable, Callable, Optional
+from collections.abc import Awaitable, Callable
from azure.communication.callautomation import DtmfTone, RecognitionChoice
from azure.communication.callautomation.aio import CallAutomationClient
@@ -154,7 +154,7 @@ async def on_speech_recognized(
async def on_recognize_timeout_error(
call: CallStateModel,
client: CallAutomationClient,
- contexts: Optional[set[CallContextEnum]],
+ contexts: set[CallContextEnum] | None,
) -> None:
if (
contexts and CallContextEnum.IVR_LANG_SELECT in contexts
@@ -224,7 +224,8 @@ async def on_recognize_unknown_error(
) -> None:
span_attribute(CallAttributes.CALL_CHANNEL, "voice")
- if error_code == 8511: # Failure while trying to play the prompt
+ if error_code == 8511: # noqa: PLR2004
+ # Failure while trying to play the prompt
logger.warning("Failed to play prompt")
else:
logger.warning(
@@ -245,7 +246,7 @@ async def on_recognize_unknown_error(
async def on_play_completed(
call: CallStateModel,
client: CallAutomationClient,
- contexts: Optional[set[CallContextEnum]],
+ contexts: set[CallContextEnum] | None,
post_callback: Callable[[CallStateModel], Awaitable[None]],
) -> None:
logger.debug("Play completed")
@@ -279,15 +280,19 @@ async def on_play_error(error_code: int) -> None:
logger.debug("Play failed")
span_attribute(CallAttributes.CALL_CHANNEL, "voice")
# See: https://github.com/MicrosoftDocs/azure-docs/blob/main/articles/communication-services/how-tos/call-automation/play-action.md
- if error_code == 8535: # Action failed, file format
+ if error_code == 8535: # noqa: PLR2004
+ # Action failed, file format
logger.warning("Error during media play, file format is invalid")
- elif error_code == 8536: # Action failed, file downloaded
+ elif error_code == 8536: # noqa: PLR2004
+ # Action failed, file downloaded
logger.warning("Error during media play, file could not be downloaded")
- elif error_code == 8565: # Action failed, AI services config
+ elif error_code == 8565: # noqa: PLR2004
+ # Action failed, AI services config
logger.error(
"Error during media play, impossible to connect with Azure AI services"
)
- elif error_code == 9999: # Unknown
+ elif error_code == 9999: # noqa: PLR2004
+ # Unknown error code
logger.warning("Error during media play, unknown internal server error")
else:
logger.warning("Error during media play, unknown error code %s", error_code)
@@ -429,7 +434,7 @@ async def on_end_call(
Shortcut to run all post-call intelligence tasks in background.
"""
if (
- len(call.messages) >= 3
+ len(call.messages) >= 3 # noqa: PLR2004
and call.messages[-3].action == MessageActionEnum.CALL
and call.messages[-2].persona == MessagePersonaEnum.ASSISTANT
and call.messages[-1].action == MessageActionEnum.HANGUP
@@ -451,11 +456,9 @@ async def _intelligence_sms(call: CallStateModel) -> None:
Send an SMS report to the customer.
"""
- def _validate(req: Optional[str]) -> tuple[bool, Optional[str], Optional[str]]:
+ def _validate(req: str | None) -> tuple[bool, str | None, str | None]:
if not req:
return False, "No SMS content", None
- if len(req) < 10:
- return False, "SMS content too short", None
return True, None, req
content = await completion_sync(
@@ -503,8 +506,8 @@ async def _intelligence_synthesis(call: CallStateModel) -> None:
logger.debug("Synthesizing call")
def _validate(
- req: Optional[str],
- ) -> tuple[bool, Optional[str], Optional[SynthesisModel]]:
+ req: str | None,
+ ) -> tuple[bool, str | None, SynthesisModel | None]:
if not req:
return False, "Empty response", None
try:
@@ -534,8 +537,8 @@ async def _intelligence_next(call: CallStateModel) -> None:
logger.debug("Generating next action")
def _validate(
- req: Optional[str],
- ) -> tuple[bool, Optional[str], Optional[NextModel]]:
+ req: str | None,
+ ) -> tuple[bool, str | None, NextModel | None]:
if not req:
return False, "Empty response", None
try:
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index f9f84ea..a142db4 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -1,6 +1,6 @@
import asyncio
import time
-from typing import Awaitable, Callable
+from collections.abc import Awaitable, Callable
from azure.communication.callautomation.aio import CallAutomationClient
from openai import APIError
@@ -35,8 +35,9 @@ _cache = CONFIG.cache.instance()
_db = CONFIG.database.instance()
+# TODO: Refacto, this function is too long (and remove PLR0912/PLR0915 ignore)
@tracer.start_as_current_span("call_load_llm_chat")
-async def load_llm_chat(
+async def load_llm_chat( # noqa: PLR0912, PLR0915
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
@@ -171,9 +172,7 @@ async def load_llm_chat(
text=await CONFIG.prompts.tts.timeout_loading(call),
)
- elif (
- loading_task.done()
- ): # Do not play timeout prompt plus loading, it can be frustrating for the user
+ elif loading_task.done(): # Do not play timeout prompt plus loading, it can be frustrating for the user
loading_task = _loading_task()
await handle_media(
call=call,
@@ -184,7 +183,7 @@ async def load_llm_chat(
# Wait to not block the event loop for other requests
await asyncio.sleep(1)
- except Exception: # pylint: disable=broad-exception-caught
+ except Exception:
logger.warning("Error loading intelligence", exc_info=True)
if is_error: # Error during chat
@@ -233,8 +232,9 @@ async def load_llm_chat(
return call
+# TODO: Refacto, this function is too long (and remove PLR0911/PLR0912/PLR0915 ignore)
@tracer.start_as_current_span("call_execute_llm_chat")
-async def _execute_llm_chat(
+async def _execute_llm_chat( # noqa: PLR0911, PLR0912, PLR0915
call: CallStateModel,
client: CallAutomationClient,
post_callback: Callable[[CallStateModel], Awaitable[None]],
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index f8bb02e..1132201 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -1,8 +1,8 @@
import json
import re
+from collections.abc import AsyncGenerator, Generator
from contextlib import asynccontextmanager
from enum import Enum
-from typing import AsyncGenerator, Generator, Optional
from azure.communication.callautomation import (
FileSource,
@@ -26,11 +26,12 @@ from models.message import (
StyleEnum as MessageStyleEnum,
)
+_MAX_CHARACTERS_PER_TTS = 400 # Azure Speech Service TTS limit is 400 characters
_SENTENCE_PUNCTUATION_R = (
r"([!?;]+|[\.\-:]+(?:$| ))" # Split by sentence by punctuation
)
_TTS_SANITIZER_R = re.compile(
- r"[^\w\sÀ-ÿ'«»“”\"\"‘’''(),.!?;:\-\+_@/&€$%=]"
+ r"[^\w\sÀ-ÿ'«»“”\"\"‘’''(),.!?;:\-\+_@/&€$%=]" # noqa: RUF001
) # Sanitize text for TTS
@@ -79,9 +80,9 @@ def tts_sentence_split(
async def _handle_recognize_media(
call: CallStateModel,
client: CallAutomationClient,
- context: Optional[ContextEnum],
+ context: ContextEnum | None,
style: MessageStyleEnum,
- text: Optional[str],
+ text: str | None,
) -> None:
"""
Play a media to a call participant and start recognizing the response.
@@ -107,9 +108,7 @@ 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
- ), # pyright: ignore
+ target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # pyright: ignore
)
except ResourceNotFoundError:
logger.debug("Call hung up before recognizing")
@@ -124,7 +123,7 @@ async def _handle_play_text(
call: CallStateModel,
client: CallAutomationClient,
text: str,
- context: Optional[ContextEnum] = None,
+ context: ContextEnum | None = None,
style: MessageStyleEnum = MessageStyleEnum.NONE,
) -> None:
"""
@@ -157,7 +156,7 @@ async def handle_media(
client: CallAutomationClient,
call: CallStateModel,
sound_url: str,
- context: Optional[ContextEnum] = None,
+ context: ContextEnum | None = None,
) -> None:
"""
Play a media to a call participant.
@@ -180,11 +179,11 @@ async def handle_media(
raise e
-async def handle_recognize_text(
+async def handle_recognize_text( # noqa: PLR0913
call: CallStateModel,
client: CallAutomationClient,
- text: Optional[str],
- context: Optional[ContextEnum] = None,
+ text: str | None,
+ context: ContextEnum | None = None,
no_response_error: bool = False,
store: bool = True,
style: MessageStyleEnum = MessageStyleEnum.NONE,
@@ -231,11 +230,11 @@ async def handle_recognize_text(
)
-async def handle_play_text(
+async def handle_play_text( # noqa: PLR0913
call: CallStateModel,
client: CallAutomationClient,
text: str,
- context: Optional[ContextEnum] = None,
+ context: ContextEnum | None = None,
store: bool = True,
style: MessageStyleEnum = MessageStyleEnum.NONE,
) -> None:
@@ -310,11 +309,11 @@ async def _chunk_before_tts(
)
)
- # Split text in chunks of max 400 characters, separated by sentence
+ # Split text in chunks, separated by sentence
chunks = []
chunk = ""
for to_add, _ in tts_sentence_split(text, True):
- if len(chunk) + len(to_add) >= 400:
+ if len(chunk) + len(to_add) >= _MAX_CHARACTERS_PER_TTS:
chunks.append(chunk.strip()) # Remove trailing space
chunk = ""
chunk += to_add
@@ -332,16 +331,13 @@ def _audio_from_text(
"""
Generate an audio source that can be read by Azure Communication Services SDK.
- Text requires to be SVG escaped, and SSML tags are used to control the voice. Plus, text is slowed down by 5% to make it more understandable for elderly people. Text is also truncated to 400 characters, as this is the limit of Azure Communication Services TTS, but a warning is logged.
+ Text requires to be SVG escaped, and SSML tags are used to control the voice. Plus, text is slowed down by 5% to make it more understandable for elderly people. Text is also truncated, as this is the limit of Azure Communication Services TTS, but a warning is logged.
See: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-synthesis-markup-structure
"""
- # Azure Speech Service TTS limit is 400 characters
- if len(text) > 400:
- logger.warning(
- "Text is too long to be processed by TTS, truncating to 400 characters, fix this!"
- )
- text = text[:400]
+ if len(text) > _MAX_CHARACTERS_PER_TTS:
+ logger.warning("Text is too long to be processed by TTS, truncating, fix this!")
+ text = text[:_MAX_CHARACTERS_PER_TTS]
# Escape text for SSML
text = text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
# Build SSML tree
@@ -368,7 +364,7 @@ async def handle_recognize_ivr(
choices: list[RecognitionChoice],
client: CallAutomationClient,
text: str,
- context: Optional[ContextEnum] = None,
+ context: ContextEnum | None = None,
) -> None:
"""
Recognize an IVR response after playing a text.
@@ -390,9 +386,7 @@ async def handle_recognize_ivr(
text=text,
),
speech_language=call.lang.short_code,
- target_participant=PhoneNumberIdentifier(
- call.initiate.phone_number
- ), # pyright: ignore
+ target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # pyright: ignore
)
except ResourceNotFoundError:
logger.debug("Call hung up before recognizing")
@@ -420,7 +414,7 @@ async def handle_transfer(
client: CallAutomationClient,
call: CallStateModel,
target: str,
- context: Optional[ContextEnum] = None,
+ context: ContextEnum | None = None,
) -> None:
logger.info("Transferring call: %s", target)
try:
@@ -439,7 +433,7 @@ async def handle_transfer(
raise e
-def _context_builder(contexts: Optional[set[Optional[ContextEnum]]]) -> Optional[str]:
+def _context_builder(contexts: set[ContextEnum | None] | None) -> str | None:
if not contexts:
return None
return json.dumps([context.value for context in contexts if context])
diff --git a/helpers/config.py b/helpers/config.py
index a6b9c27..c66b529 100644
--- a/helpers/config.py
+++ b/helpers/config.py
@@ -1,5 +1,4 @@
from os import environ
-from typing import Optional
import yaml
from dotenv import find_dotenv
@@ -17,16 +16,16 @@ class ConfigBadFormat(Exception):
def load_config() -> RootModel:
- config: Optional[RootModel] = None
+ config: RootModel | None = None
config_env = "CONFIG_JSON"
config_file = "config.yaml"
if config_env in environ:
config = RootModel.model_validate_json(environ[config_env])
- print(f'Config loaded from env "{config_env}"')
+ print(f'Config loaded from env "{config_env}"') # noqa: T201
return config
- print(f'Cannot find env "{config_env}", trying to load from file')
+ print(f'Cannot find env "{config_env}", trying to load from file') # noqa: T201
path = find_dotenv(filename=config_file)
if not path:
raise ConfigNotFound(f'Cannot find config file "{config_file}"')
@@ -34,10 +33,9 @@ def load_config() -> RootModel:
with open(
encoding="utf-8",
file=path,
- mode="r",
) as f:
config = RootModel.model_validate(yaml.safe_load(f))
- print(f'Config loaded from file "{path}"')
+ print(f'Config loaded from file "{path}"') # noqa: T201
return config
except ValidationError as e:
raise ConfigBadFormat("Config values are not valid") from e
diff --git a/helpers/config_models/ai_search.py b/helpers/config_models/ai_search.py
index 69ba28e..6825091 100644
--- a/helpers/config_models/ai_search.py
+++ b/helpers/config_models/ai_search.py
@@ -1,4 +1,4 @@
-from functools import lru_cache
+from functools import cache
from pydantic import BaseModel, Field, SecretStr
@@ -14,10 +14,10 @@ class AiSearchModel(BaseModel, frozen=True):
strictness: float = Field(default=2, ge=0, le=5)
top_n_documents: int = Field(default=5, ge=1)
- @lru_cache(maxsize=None) # pylint: disable=method-cache-max-size-none
+ @cache
def instance(self) -> ISearch:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
- from persistence.ai_search import ( # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
+ from persistence.ai_search import (
AiSearchSearch,
)
diff --git a/helpers/config_models/cache.py b/helpers/config_models/cache.py
index 2eccafa..4f61579 100644
--- a/helpers/config_models/cache.py
+++ b/helpers/config_models/cache.py
@@ -1,6 +1,5 @@
from enum import Enum
-from functools import lru_cache
-from typing import Optional
+from functools import cache
from pydantic import BaseModel, Field, SecretStr, ValidationInfo, field_validator
@@ -15,9 +14,9 @@ class ModeEnum(str, Enum):
class MemoryModel(BaseModel, frozen=True):
max_size: int = Field(default=100, ge=10)
- @lru_cache(maxsize=None) # pylint: disable=method-cache-max-size-none
+ @cache
def instance(self) -> ICache:
- from persistence.memory import ( # pylint: disable=import-outside-toplevel
+ from persistence.memory import (
MemoryCache,
)
@@ -31,9 +30,9 @@ class RedisModel(BaseModel, frozen=True):
port: int = 6379
ssl: bool = True
- @lru_cache(maxsize=None) # pylint: disable=method-cache-max-size-none
+ @cache
def instance(self) -> ICache:
- from persistence.redis import ( # pylint: disable=import-outside-toplevel
+ from persistence.redis import (
RedisCache,
)
@@ -41,17 +40,17 @@ class RedisModel(BaseModel, frozen=True):
class CacheModel(BaseModel):
- memory: Optional[MemoryModel] = MemoryModel() # Object is fully defined by default
+ memory: MemoryModel | None = MemoryModel() # Object is fully defined by default
mode: ModeEnum = ModeEnum.MEMORY
- redis: Optional[RedisModel] = None
+ redis: RedisModel | None = None
@field_validator("redis")
@classmethod
def _validate_sqlite(
cls,
- redis: Optional[RedisModel],
+ redis: RedisModel | None,
info: ValidationInfo,
- ) -> Optional[RedisModel]:
+ ) -> RedisModel | None:
if not redis and info.data.get("mode", None) == ModeEnum.REDIS:
raise ValueError("Redis config required")
return redis
@@ -60,9 +59,9 @@ class CacheModel(BaseModel):
@classmethod
def _validate_memory(
cls,
- memory: Optional[MemoryModel],
+ memory: MemoryModel | None,
info: ValidationInfo,
- ) -> Optional[MemoryModel]:
+ ) -> MemoryModel | None:
if not memory and info.data.get("mode", None) == ModeEnum.MEMORY:
raise ValueError("Memory config required")
return memory
diff --git a/helpers/config_models/conversation.py b/helpers/config_models/conversation.py
index da63d61..6a7eed5 100644
--- a/helpers/config_models/conversation.py
+++ b/helpers/config_models/conversation.py
@@ -1,5 +1,5 @@
from datetime import datetime
-from typing import Annotated, Any, Optional, Union
+from typing import Annotated, Any
from pydantic import BaseModel, ConfigDict, EmailStr, Field, create_model
from pydantic.fields import FieldInfo
@@ -15,7 +15,7 @@ class LanguageEntryModel(BaseModel):
See: https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts#supported-languages
"""
- custom_voice_endpoint_id: Optional[str] = None
+ custom_voice_endpoint_id: str | None = None
pronunciations_en: list[str]
short_code: str
voice: str
@@ -128,9 +128,7 @@ class WorkflowInitiateModel(BaseModel):
ge=0.75,
le=1.25,
)
- task: str = (
- "Helping the customer to file an insurance claim. The customer is probably calling because they have a problem with something covered by their policy, but it's not certain. The assistant needs information from the customer to complete the claim. The conversation is over when all the data relevant to the case has been collected. Filling in as much information as possible is important for further processing."
- )
+ task: str = "Helping the customer to file an insurance claim. The customer is probably calling because they have a problem with something covered by their policy, but it's not certain. The assistant needs information from the customer to complete the claim. The conversation is over when all the data relevant to the case has been collected. Filling in as much information as possible is important for further processing."
def claim_model(self) -> type[BaseModel]:
return _fields_to_pydantic(
@@ -197,10 +195,10 @@ def _fields_to_pydantic(name: str, fields: list[ClaimFieldModel]) -> type[BaseMo
def _field_to_pydantic(
field: ClaimFieldModel,
-) -> Union[Annotated[Any, ...], tuple[type, FieldInfo]]:
+) -> Annotated[Any, ...] | tuple[type, FieldInfo]:
field_type = _type_to_pydantic(field.type)
return (
- Optional[field_type],
+ field_type | None,
Field(
default=None,
description=field.description,
@@ -210,7 +208,7 @@ def _field_to_pydantic(
def _type_to_pydantic(
data: ClaimTypeEnum,
-) -> Union[type, Annotated[Any, ...]]:
+) -> type | Annotated[Any, ...]:
if data == ClaimTypeEnum.DATETIME:
return datetime
if data == ClaimTypeEnum.EMAIL:
diff --git a/helpers/config_models/database.py b/helpers/config_models/database.py
index 6f87632..0be2adf 100644
--- a/helpers/config_models/database.py
+++ b/helpers/config_models/database.py
@@ -1,6 +1,5 @@
from enum import Enum
-from functools import lru_cache
-from typing import Optional
+from functools import cache
from pydantic import BaseModel, SecretStr, ValidationInfo, field_validator
@@ -18,10 +17,10 @@ class CosmosDbModel(BaseModel, frozen=True):
database: str
endpoint: str
- @lru_cache(maxsize=None) # pylint: disable=method-cache-max-size-none
+ @cache
def instance(self) -> IStore:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
- from persistence.cosmos_db import ( # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
+ from persistence.cosmos_db import (
CosmosDbStore,
)
@@ -41,10 +40,10 @@ class SqliteModel(BaseModel, frozen=True):
"""
return f"{self.path}-v{self.schema_version}.sqlite"
- @lru_cache(maxsize=None) # pylint: disable=method-cache-max-size-none
+ @cache
def instance(self) -> IStore:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
- from persistence.sqlite import ( # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
+ from persistence.sqlite import (
SqliteStore,
)
@@ -52,17 +51,17 @@ class SqliteModel(BaseModel, frozen=True):
class DatabaseModel(BaseModel):
- cosmos_db: Optional[CosmosDbModel] = None
+ cosmos_db: CosmosDbModel | None = None
mode: ModeEnum = ModeEnum.SQLITE
- sqlite: Optional[SqliteModel] = SqliteModel() # Object is fully defined by default
+ sqlite: SqliteModel | None = SqliteModel() # Object is fully defined by default
@field_validator("cosmos_db")
@classmethod
def _validate_cosmos_db(
cls,
- cosmos_db: Optional[CosmosDbModel],
+ cosmos_db: CosmosDbModel | None,
info: ValidationInfo,
- ) -> Optional[CosmosDbModel]:
+ ) -> CosmosDbModel | None:
if not cosmos_db and info.data.get("mode", None) == ModeEnum.COSMOS_DB:
raise ValueError("Cosmos DB config required")
return cosmos_db
@@ -71,9 +70,9 @@ class DatabaseModel(BaseModel):
@classmethod
def _validate_sqlite(
cls,
- sqlite: Optional[SqliteModel],
+ sqlite: SqliteModel | None,
info: ValidationInfo,
- ) -> Optional[SqliteModel]:
+ ) -> SqliteModel | None:
if not sqlite and info.data.get("mode", None) == ModeEnum.SQLITE:
raise ValueError("SQLite config required")
return sqlite
diff --git a/helpers/config_models/llm.py b/helpers/config_models/llm.py
index f4cc1f5..d3b8a56 100644
--- a/helpers/config_models/llm.py
+++ b/helpers/config_models/llm.py
@@ -1,5 +1,5 @@
from enum import Enum
-from typing import Any, Optional, Union
+from typing import Any
from azure.identity import ManagedIdentityCredential, get_bearer_token_provider
from openai import AsyncAzureOpenAI, AsyncOpenAI
@@ -23,8 +23,8 @@ class AbstractPlatformModel(BaseModel):
class AzureOpenaiPlatformModel(AbstractPlatformModel):
- _client: Optional[AsyncAzureOpenAI] = None
- api_key: Optional[SecretStr] = None
+ _client: AsyncAzureOpenAI | None = None
+ api_key: SecretStr | None = None
deployment: str
endpoint: str
@@ -53,7 +53,7 @@ class AzureOpenaiPlatformModel(AbstractPlatformModel):
class OpenaiPlatformModel(AbstractPlatformModel):
- _client: Optional[AsyncOpenAI] = None
+ _client: AsyncOpenAI | None = None
api_key: SecretStr
endpoint: str
@@ -70,17 +70,17 @@ class OpenaiPlatformModel(AbstractPlatformModel):
class SelectedPlatformModel(BaseModel):
- azure_openai: Optional[AzureOpenaiPlatformModel] = None
+ azure_openai: AzureOpenaiPlatformModel | None = None
mode: ModeEnum
- openai: Optional[OpenaiPlatformModel] = None
+ openai: OpenaiPlatformModel | None = None
@field_validator("azure_openai")
@classmethod
def _validate_azure_openai(
cls,
- azure_openai: Optional[AzureOpenaiPlatformModel],
+ azure_openai: AzureOpenaiPlatformModel | None,
info: ValidationInfo,
- ) -> Optional[AzureOpenaiPlatformModel]:
+ ) -> AzureOpenaiPlatformModel | None:
if not azure_openai and info.data.get("mode", None) == ModeEnum.AZURE_OPENAI:
raise ValueError("Azure OpenAI config required")
return azure_openai
@@ -89,14 +89,14 @@ class SelectedPlatformModel(BaseModel):
@classmethod
def _validate_openai(
cls,
- openai: Optional[OpenaiPlatformModel],
+ openai: OpenaiPlatformModel | None,
info: ValidationInfo,
- ) -> Optional[OpenaiPlatformModel]:
+ ) -> OpenaiPlatformModel | None:
if not openai and info.data.get("mode", None) == ModeEnum.OPENAI:
raise ValueError("OpenAI config required")
return openai
- def selected(self) -> Union[AzureOpenaiPlatformModel, OpenaiPlatformModel]:
+ def selected(self) -> AzureOpenaiPlatformModel | OpenaiPlatformModel:
platform = (
self.azure_openai if self.mode == ModeEnum.AZURE_OPENAI else self.openai
)
@@ -112,8 +112,6 @@ class LlmModel(BaseModel):
serialization_alias="primary", # Backwards compatibility with v6
)
- def selected(
- self, is_fast: bool
- ) -> Union[AzureOpenaiPlatformModel, OpenaiPlatformModel]:
+ def selected(self, is_fast: bool) -> AzureOpenaiPlatformModel | OpenaiPlatformModel:
platform = self.fast if is_fast else self.slow
return platform.selected()
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index 413e3c5..d7f5934 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -4,7 +4,6 @@ from functools import cached_property
from html import escape
from logging import Logger
from textwrap import dedent
-from typing import Optional
from azure.core.exceptions import HttpResponseError
from openai.types.chat import ChatCompletionSystemMessageParam
@@ -23,14 +22,14 @@ class SoundModel(BaseModel):
ready_tpl: str = "{public_url}/ready.wav"
def loading(self) -> str:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
return self.loading_tpl.format(
public_url=CONFIG.resources.public_url,
)
def ready(self) -> str:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
return self.ready_tpl.format(
public_url=CONFIG.resources.public_url,
@@ -320,7 +319,7 @@ class LlmModel(BaseModel):
"""
def default_system(self, call: CallStateModel) -> str:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
return self._format(
self.default_system_tpl.format(
@@ -337,7 +336,7 @@ class LlmModel(BaseModel):
def chat_system(
self, call: CallStateModel, trainings: list[TrainingModel]
) -> list[ChatCompletionSystemMessageParam]:
- from models.message import ( # pylint: disable=import-outside-toplevel
+ from models.message import (
ActionEnum as MessageActionEnum,
StyleEnum as MessageStyleEnum,
)
@@ -441,7 +440,7 @@ class LlmModel(BaseModel):
def _format(
self,
prompt_tpl: str,
- trainings: Optional[list[TrainingModel]] = None,
+ trainings: list[TrainingModel] | None = None,
**kwargs: str,
) -> str:
# Remove possible indentation then render the template
@@ -486,34 +485,26 @@ class LlmModel(BaseModel):
@cached_property
def logger(self) -> Logger:
- from helpers.logging import logger # pylint: disable=import-outside-toplevel
+ from helpers.logging import logger
return logger
class TtsModel(BaseModel):
tts_lang: str = "en-US"
- calltransfer_failure_tpl: str = (
- "It seems I can't connect you with an agent at the moment, but the next available agent will call you back as soon as possible."
- )
- connect_agent_tpl: str = (
- "I'm sorry, I wasn't able to respond your request. Please allow me to transfer you to an agent who can assist you further. Please stay on the line and I will get back to you shortly."
- )
+ calltransfer_failure_tpl: str = "It seems I can't connect you with an agent at the moment, but the next available agent will call you back as soon as possible."
+ connect_agent_tpl: str = "I'm sorry, I wasn't able to respond your request. Please allow me to transfer you to an agent who can assist you further. Please stay on the line and I will get back to you shortly."
end_call_to_connect_agent_tpl: str = (
"Of course, stay on the line. I will transfer you to an agent."
)
error_tpl: str = (
"I'm sorry, I have encountered an error. Could you repeat your request?"
)
- goodbye_tpl: str = (
- "Thank you for calling, I hope I've been able to help. You can call back, I've got it all memorized. {bot_company} wishes you a wonderful day!"
- )
+ goodbye_tpl: str = "Thank you for calling, I hope I've been able to help. You can call back, I've got it all memorized. {bot_company} wishes you a wonderful day!"
hello_tpl: str = """
Hello, I'm {bot_name}, the virtual assistant {bot_company}! Here's how I work: while I'm processing your information, wou will hear a music. Feel free to speak to me in a natural way - I'm designed to understand your requests. During the conversation, you can also send me text messages.
"""
- timeout_silence_tpl: str = (
- "I'm sorry, I didn't hear anything. If you need help, let me know how I can help you."
- )
+ timeout_silence_tpl: str = "I'm sorry, I didn't hear anything. If you need help, let me know how I can help you."
welcome_back_tpl: str = "Hello, I'm {bot_name}, from {bot_company}!"
timeout_loading_tpl: str = (
"It's taking me longer than expected to reply. Thank you for your patience…"
@@ -551,7 +542,7 @@ class TtsModel(BaseModel):
return await self._translate(self.timeout_silence_tpl, call)
async def welcome_back(self, call: CallStateModel) -> str:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
return await self._translate(
self.welcome_back_tpl,
@@ -589,7 +580,7 @@ class TtsModel(BaseModel):
If the translation fails, the initial prompt is returned.
"""
- from helpers.translation import ( # pylint: disable=import-outside-toplevel
+ from helpers.translation import (
translate_text,
)
@@ -606,7 +597,7 @@ class TtsModel(BaseModel):
@cached_property
def logger(self) -> Logger:
- from helpers.logging import logger # pylint: disable=import-outside-toplevel
+ from helpers.logging import logger
return logger
diff --git a/helpers/config_models/root.py b/helpers/config_models/root.py
index ed9d161..853ffa6 100644
--- a/helpers/config_models/root.py
+++ b/helpers/config_models/root.py
@@ -53,7 +53,7 @@ class RootModel(BaseSettings):
@classmethod
def settings_customise_sources(
cls,
- settings_cls: type[BaseSettings],
+ settings_cls: type[BaseSettings], # noqa: ARG003
init_settings: PydanticBaseSettingsSource,
env_settings: PydanticBaseSettingsSource,
dotenv_settings: PydanticBaseSettingsSource,
diff --git a/helpers/config_models/sms.py b/helpers/config_models/sms.py
index bee0b54..f82baff 100644
--- a/helpers/config_models/sms.py
+++ b/helpers/config_models/sms.py
@@ -1,6 +1,5 @@
from enum import Enum
-from functools import lru_cache
-from typing import Optional
+from functools import cache
from pydantic import BaseModel, SecretStr, ValidationInfo, field_validator
@@ -20,10 +19,10 @@ class CommunicationServiceModel(BaseModel, frozen=True):
Model is purely empty to fit to the `ISms` interface and the "mode" enum code organization. As the Communication Services is also used as the only call interface, it is not necessary to duplicate the models.
"""
- @lru_cache(maxsize=None) # pylint: disable=method-cache-max-size-none
+ @cache
def instance(self) -> ISms:
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
- from persistence.communication_services import ( # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
+ from persistence.communication_services import (
CommunicationServicesSms,
)
@@ -35,9 +34,9 @@ class TwilioModel(BaseModel, frozen=True):
auth_token: SecretStr
phone_number: PhoneNumber
- @lru_cache(maxsize=None) # pylint: disable=method-cache-max-size-none
+ @cache
def instance(self) -> ISms:
- from persistence.twilio import ( # pylint: disable=import-outside-toplevel
+ from persistence.twilio import (
TwilioSms,
)
@@ -45,19 +44,19 @@ class TwilioModel(BaseModel, frozen=True):
class SmsModel(BaseModel):
- communication_services: Optional[CommunicationServiceModel] = (
+ communication_services: CommunicationServiceModel | None = (
CommunicationServiceModel()
) # Object is fully defined by default
mode: ModeEnum = ModeEnum.COMMUNICATION_SERVICES
- twilio: Optional[TwilioModel] = None
+ twilio: TwilioModel | None = None
@field_validator("communication_services")
@classmethod
def _validate_communication_services(
cls,
- communication_services: Optional[CommunicationServiceModel],
+ communication_services: CommunicationServiceModel | None,
info: ValidationInfo,
- ) -> Optional[CommunicationServiceModel]:
+ ) -> CommunicationServiceModel | None:
if (
not communication_services
and info.data.get("mode", None) == ModeEnum.COMMUNICATION_SERVICES
@@ -69,9 +68,9 @@ class SmsModel(BaseModel):
@classmethod
def _validate_twilio(
cls,
- twilio: Optional[TwilioModel],
+ twilio: TwilioModel | None,
info: ValidationInfo,
- ) -> Optional[TwilioModel]:
+ ) -> TwilioModel | None:
if not twilio and info.data.get("mode", None) == ModeEnum.TWILIO:
raise ValueError("Twilio config required")
return twilio
diff --git a/helpers/http.py b/helpers/http.py
index b993690..8bc2179 100644
--- a/helpers/http.py
+++ b/helpers/http.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from aiohttp import (
AsyncResolver,
ClientSession,
@@ -11,10 +9,10 @@ from aiohttp_retry import JitterRetry, RetryClient
from azure.core.pipeline.transport._aiohttp import AioHttpTransport
from twilio.http.async_http_client import AsyncTwilioHttpClient
-_cookie_jar: Optional[DummyCookieJar] = None
-_session: Optional[ClientSession] = None
-_transport: Optional[AioHttpTransport] = None
-_twilio_http: Optional[AsyncTwilioHttpClient] = None
+_cookie_jar: DummyCookieJar | None = None
+_session: ClientSession | None = None
+_transport: AioHttpTransport | None = None
+_twilio_http: AsyncTwilioHttpClient | None = None
async def _aiohttp_cookie_jar() -> DummyCookieJar:
@@ -25,7 +23,7 @@ async def _aiohttp_cookie_jar() -> DummyCookieJar:
Returns a `DummyCookieJar` instance.
"""
- global _cookie_jar # pylint: disable=global-statement
+ global _cookie_jar # noqa: PLW0603
if not _cookie_jar:
_cookie_jar = DummyCookieJar()
return _cookie_jar
@@ -39,7 +37,7 @@ async def aiohttp_session() -> ClientSession:
Returns a `ClientSession` instance.
"""
- global _session # pylint: disable=global-statement
+ global _session # noqa: PLW0603
if not _session:
_session = ClientSession(
# Same config as default in the SDK
@@ -65,7 +63,7 @@ async def azure_transport() -> AioHttpTransport:
Returns a `AioHttpTransport` instance.
"""
- global _transport # pylint: disable=global-statement
+ global _transport # noqa: PLW0603
if not _transport:
# Azure SDK implements its own retry logic (e.g. for Cosmos DB), so we don't add it here
_transport = AioHttpTransport(
@@ -83,7 +81,7 @@ async def twilio_http() -> AsyncTwilioHttpClient:
Returns a `AsyncTwilioHttpClient` instance.
"""
- global _twilio_http # pylint: disable=global-statement
+ global _twilio_http # noqa: PLW0603
if not _twilio_http:
_twilio_http = AsyncTwilioHttpClient(
timeout=10,
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index 202d653..3f8f238 100644
--- a/helpers/llm_tools.py
+++ b/helpers/llm_tools.py
@@ -1,7 +1,8 @@
import asyncio
+from collections.abc import Awaitable, Callable
from html import escape
from inspect import getmembers, isfunction
-from typing import Annotated, Awaitable, Callable, Literal
+from typing import Annotated, Literal
from azure.communication.callautomation.aio import CallAutomationClient
from openai.types.chat import ChatCompletionToolParam
@@ -586,8 +587,8 @@ class LlmPlugins:
async def to_openai(call: CallStateModel) -> list[ChatCompletionToolParam]:
return await asyncio.gather(
*[
- function_schema(type, call=call)
- for name, type in getmembers(LlmPlugins, isfunction)
+ function_schema(arg_type, call=call)
+ for name, arg_type in getmembers(LlmPlugins, isfunction)
if not name.startswith("_") and name != "to_openai"
]
)
diff --git a/helpers/llm_utils.py b/helpers/llm_utils.py
index 18276ba..542b9c3 100644
--- a/helpers/llm_utils.py
+++ b/helpers/llm_utils.py
@@ -4,8 +4,9 @@ See: https://github.com/microsoft/autogen/blob/2750391f847b7168d842dfcb815ac37bd
"""
import inspect
+from collections.abc import Callable
from textwrap import dedent
-from typing import Any, Callable, ForwardRef, Tuple, TypeVar, Union
+from typing import Annotated, Any, ForwardRef, TypeVar
from jinja2 import Environment
from openai.types.chat import ChatCompletionToolParam
@@ -13,7 +14,6 @@ from openai.types.shared_params.function_definition import FunctionDefinition
from pydantic import BaseModel, TypeAdapter
from pydantic._internal._typing_extra import eval_type_lenient
from pydantic.json_schema import JsonSchemaValue
-from typing_extensions import Annotated
from helpers.logging import logger
@@ -125,7 +125,7 @@ def _typed_signature(func: Callable[..., Any]) -> inspect.Signature:
def _param_annotations(
typed_signature: inspect.Signature,
-) -> dict[str, Union[Annotated[type[Any], str], type[Any]]]:
+) -> dict[str, Annotated[type[Any], str] | type[Any]]:
"""
Get the type annotations of the parameters of a function and return a dictionary of the annotated parameters.
"""
@@ -138,7 +138,7 @@ def _param_annotations(
async def _parameter_json_schema(
name: str,
- value: Union[Annotated[type[Any], str], type[Any]],
+ value: Annotated[type[Any], str] | type[Any],
default_values: dict[str, Any],
**kwargs: Any,
) -> JsonSchemaValue:
@@ -148,9 +148,7 @@ async def _parameter_json_schema(
Kwargs are passed to the Jinja template for rendering the parameter description.
"""
- def _description(
- name: str, value: Union[Annotated[type[Any], str], type[Any]]
- ) -> str:
+ def _description(name: str, value: Annotated[type[Any], str] | type[Any]) -> str:
# Handles Annotated
if hasattr(value, "__metadata__"):
retval = value.__metadata__[0]
@@ -199,7 +197,7 @@ def _default_values(typed_signature: inspect.Signature) -> dict[str, Any]:
async def _parameters(
required_params: set[str],
- param_annotations: dict[str, Union[Annotated[type[Any], str], type[Any]]],
+ param_annotations: dict[str, Annotated[type[Any], str] | type[Any]],
default_values: dict[str, Any],
**kwargs: Any,
) -> Parameters:
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index ee8ee73..21790bf 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -1,7 +1,8 @@
import json
+from collections.abc import AsyncGenerator, Callable
from functools import lru_cache
from os import environ
-from typing import AsyncGenerator, Callable, Optional, TypeVar, Union
+from typing import TypeVar
import tiktoken
from json_repair import repair_json
@@ -85,7 +86,7 @@ async def completion_stream(
max_tokens: int,
messages: list[MessageModel],
system: list[ChatCompletionSystemMessageParam],
- tools: Optional[list[ChatCompletionToolParam]] = None,
+ tools: list[ChatCompletionToolParam] | None = None,
) -> AsyncGenerator[ChoiceDelta, None]:
"""
Returns a stream of completions.
@@ -114,7 +115,7 @@ async def completion_stream(
):
yield chunck
return
- except Exception as e: # pylint: disable=broad-exception-caught
+ except Exception as e:
if not any(isinstance(e, exception) for exception in _retried_exceptions):
raise e
logger.warning(
@@ -135,12 +136,13 @@ async def completion_stream(
yield chunck
-async def _completion_stream_worker(
+# TODO: Refacto, too long (and remove PLR0912 ignore)
+async def _completion_stream_worker( # noqa: PLR0912
is_fast: bool,
max_tokens: int,
messages: list[MessageModel],
system: list[ChatCompletionSystemMessageParam],
- tools: Optional[list[ChatCompletionToolParam]] = None,
+ tools: list[ChatCompletionToolParam] | None = None,
) -> AsyncGenerator[ChoiceDelta, None]:
"""
Returns a stream of completions.
@@ -171,11 +173,11 @@ async def _completion_stream_worker(
try:
if platform.streaming: # Streaming
- stream: AsyncStream[ChatCompletionChunk] = (
- await client.chat.completions.create(
- **chat_kwargs,
- stream=True,
- )
+ stream: AsyncStream[
+ ChatCompletionChunk
+ ] = await client.chat.completions.create(
+ **chat_kwargs,
+ stream=True,
)
async for chunck in stream:
choices = chunck.choices
@@ -246,14 +248,12 @@ async def _completion_stream_worker(
async def completion_sync(
res_type: type[T],
system: list[ChatCompletionSystemMessageParam],
- validation_callback: Callable[
- [Optional[str]], tuple[bool, Optional[str], Optional[T]]
- ],
+ validation_callback: Callable[[str | None], tuple[bool, str | None, T | None]],
validate_json: bool = False,
- _previous_result: Optional[str] = None,
+ _previous_result: str | None = None,
_retries_remaining: int = 3,
- _validation_error: Optional[str] = None,
-) -> Optional[T]:
+ _validation_error: str | None = None,
+) -> T | None:
# Initialize prompts
messages = system
if _validation_error:
@@ -269,7 +269,7 @@ async def completion_sync(
]
# Generate
- res_content: Optional[str] = await _completion_sync_worker(
+ res_content: str | None = await _completion_sync_worker(
is_fast=False,
json_output=validate_json,
system=messages,
@@ -307,8 +307,8 @@ async def _completion_sync_worker(
is_fast: bool,
system: list[ChatCompletionSystemMessageParam],
json_output: bool = False,
- max_tokens: Optional[int] = None,
-) -> Optional[str]:
+ max_tokens: int | None = None,
+) -> str | None:
"""
Returns a completion.
"""
@@ -363,21 +363,19 @@ async def _completion_sync_worker(
return choice.message.content if choice else None
-def _limit_messages(
+def _limit_messages( # noqa: PLR0913
context_window: int,
- max_tokens: Optional[int],
+ max_tokens: int | None,
messages: list[MessageModel],
model: str,
system: list[ChatCompletionSystemMessageParam],
max_messages: int = 1000,
- tools: Optional[list[ChatCompletionToolParam]] = None,
+ tools: list[ChatCompletionToolParam] | None = None,
) -> list[
- Union[
- ChatCompletionAssistantMessageParam,
- ChatCompletionSystemMessageParam,
- ChatCompletionToolMessageParam,
- ChatCompletionUserMessageParam,
- ]
+ ChatCompletionAssistantMessageParam
+ | ChatCompletionSystemMessageParam
+ | ChatCompletionToolMessageParam
+ | ChatCompletionUserMessageParam
]:
"""
Returns a list of messages limited by the context size.
@@ -440,7 +438,7 @@ def _count_tokens(content: str, model: str) -> int:
def _use_llm(
is_fast: bool,
-) -> tuple[Union[AsyncAzureOpenAI, AsyncOpenAI], LlmAbstractPlatformModel]:
+) -> tuple[AsyncAzureOpenAI | AsyncOpenAI, LlmAbstractPlatformModel]:
"""
Returns an LLM client and platform model.
diff --git a/helpers/monitoring.py b/helpers/monitoring.py
index 32a0378..5687c02 100644
--- a/helpers/monitoring.py
+++ b/helpers/monitoring.py
@@ -14,7 +14,7 @@ try:
AioHttpClientInstrumentor().instrument() # Instrument aiohttp
HTTPXClientInstrumentor().instrument() # Instrument httpx
except ValueError as e:
- print(
+ print( # noqa: T201
"Azure Application Insights instrumentation failed, likely due to a missing APPLICATIONINSIGHTS_CONNECTION_STRING environment variable.",
e,
)
diff --git a/helpers/translation.py b/helpers/translation.py
index c7ba4d3..38be7d8 100644
--- a/helpers/translation.py
+++ b/helpers/translation.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from azure.ai.translation.text.aio import TextTranslationClient
from azure.ai.translation.text.models import TranslatedTextItem
from azure.core.credentials import AzureKeyCredential
@@ -18,7 +16,7 @@ from helpers.logging import logger
logger.info("Using Translation %s", CONFIG.ai_translation.endpoint)
_cache = CONFIG.cache.instance()
-_client = Optional[TextTranslationClient]
+_client: TextTranslationClient | None = None
@retry(
@@ -27,9 +25,7 @@ _client = Optional[TextTranslationClient]
stop=stop_after_attempt(3),
wait=wait_random_exponential(multiplier=0.8, max=8),
)
-async def translate_text(
- text: str, source_lang: str, target_lang: str
-) -> Optional[str]:
+async def translate_text(text: str, source_lang: str, target_lang: str) -> str | None:
"""
Translate text from source language to target language.
@@ -45,7 +41,7 @@ async def translate_text(
return cached.decode()
# Try live
- translation: Optional[str] = None
+ translation: str | None = None
client = await _use_client()
res: list[TranslatedTextItem] = await client.translate(
body=[text],
@@ -64,7 +60,7 @@ async def _use_client() -> TextTranslationClient:
"""
Generate the Translation client and close it after use.
"""
- global _client # pylint: disable=global-statement
+ global _client # noqa: PLW0603
if not isinstance(_client, TextTranslationClient):
_client = TextTranslationClient(
# Performance
diff --git a/models/call.py b/models/call.py
index c8f9764..040731e 100644
--- a/models/call.py
+++ b/models/call.py
@@ -2,7 +2,7 @@ import asyncio
import random
import string
from datetime import UTC, datetime, tzinfo
-from typing import Any, Optional
+from typing import Any
from uuid import UUID, uuid4
from pydantic import BaseModel, Field, ValidationInfo, computed_field, field_validator
@@ -27,13 +27,13 @@ class CallGetModel(BaseModel):
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC), frozen=True)
# Editable fields
initiate: CallInitiateModel = Field(frozen=True)
- claim: dict[str, Any] = (
- {}
- ) # Place after "initiate" as it depends on it for validation
+ claim: dict[
+ str, Any
+ ] = {} # Place after "initiate" as it depends on it for validation
messages: list[MessageModel] = []
- next: Optional[NextModel] = None
+ next: NextModel | None = None
reminders: list[ReminderModel] = []
- synthesis: Optional[SynthesisModel] = None
+ synthesis: SynthesisModel | None = None
@computed_field
@property
@@ -58,9 +58,9 @@ class CallGetModel(BaseModel):
@field_validator("claim")
@classmethod
def _validate_claim(
- cls, claim: Optional[dict[str, Any]], info: ValidationInfo
+ cls, claim: dict[str, Any] | None, info: ValidationInfo
) -> dict[str, Any]:
- initiate: Optional[CallInitiateModel] = info.data.get("initiate", None)
+ initiate: CallInitiateModel | None = info.data.get("initiate", None)
if not initiate:
return {}
return (
@@ -82,14 +82,14 @@ class CallStateModel(CallGetModel, extra="ignore"):
frozen=True,
)
# Editable fields
- lang_short_code: Optional[str] = None
+ lang_short_code: str | None = None
recognition_retry: int = 0
- voice_id: Optional[str] = None
+ voice_id: str | None = None
@computed_field
@property
def lang(self) -> LanguageEntryModel: # pyright: ignore
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
lang = CONFIG.conversation.initiate.lang
default = lang.default_lang
@@ -114,7 +114,7 @@ class CallStateModel(CallGetModel, extra="ignore"):
Is using query expansion from last messages. Then, data is sorted by score.
"""
- from helpers.config import CONFIG # pylint: disable=import-outside-toplevel
+ from helpers.config import CONFIG
with tracer.start_as_current_span("call_trainings"):
search = CONFIG.ai_search.instance()
diff --git a/models/claim.py b/models/claim.py
index 214f12b..d22ed15 100644
--- a/models/claim.py
+++ b/models/claim.py
@@ -12,6 +12,6 @@ class ClaimTypeEnum(str, Enum):
class ClaimFieldModel(BaseModel):
- description: Optional[str] = None
+ description: str | None = None
name: str
type: ClaimTypeEnum
diff --git a/models/message.py b/models/message.py
index 28e3068..5603983 100644
--- a/models/message.py
+++ b/models/message.py
@@ -3,7 +3,7 @@ import re
from datetime import UTC, datetime
from enum import Enum
from inspect import getmembers, isfunction
-from typing import Any, Optional, Union
+from typing import Any
from json_repair import repair_json
from openai.types.chat import (
@@ -82,7 +82,7 @@ class ToolModel(BaseModel):
return self
async def execute_function(self, plugins: object) -> None:
- from helpers.logging import logger # pylint: disable=import-outside-toplevel
+ from helpers.logging import logger
json_str = self.function_arguments
name = self.function_name
@@ -131,7 +131,7 @@ class ToolModel(BaseModel):
)
res = "Wrong arguments, please fix them and try again."
res_log = res
- except Exception as e: # pylint: disable=broad-exception-caught
+ except Exception as e:
logger.warning(
"Error executing function %s with args %s",
self.function_name,
@@ -145,7 +145,7 @@ class ToolModel(BaseModel):
@staticmethod
def _available_function_names() -> list[str]:
- from helpers.llm_tools import ( # pylint: disable=import-outside-toplevel
+ from helpers.llm_tools import (
LlmPlugins,
)
@@ -177,11 +177,9 @@ class MessageModel(BaseModel):
def to_openai(
self,
) -> list[
- Union[
- ChatCompletionAssistantMessageParam,
- ChatCompletionToolMessageParam,
- ChatCompletionUserMessageParam,
- ]
+ ChatCompletionAssistantMessageParam
+ | ChatCompletionToolMessageParam
+ | ChatCompletionUserMessageParam
]:
# Removing newlines from the content to avoid hallucinations issues with GPT-4 Turbo
content = " ".join([line.strip() for line in self.content.splitlines()])
@@ -211,14 +209,14 @@ class MessageModel(BaseModel):
tool_calls=[tool_call.to_openai() for tool_call in self.tool_calls],
)
)
- for tool_call in self.tool_calls:
- res.append(
- ChatCompletionToolMessageParam(
- content=tool_call.content,
- role="tool",
- tool_call_id=tool_call.tool_id,
- )
+ res.extend(
+ ChatCompletionToolMessageParam(
+ content=tool_call.content,
+ role="tool",
+ tool_call_id=tool_call.tool_id,
)
+ for tool_call in self.tool_calls
+ )
return res
@@ -236,7 +234,7 @@ def remove_message_action(text: str) -> str:
return text
-def extract_message_style(text: str) -> tuple[Optional[StyleEnum], str]:
+def extract_message_style(text: str) -> tuple[StyleEnum | None, str]:
"""
Detect the style of a message.
"""
diff --git a/models/readiness.py b/models/readiness.py
index 759783a..4e4c669 100644
--- a/models/readiness.py
+++ b/models/readiness.py
@@ -1,5 +1,4 @@
from enum import Enum
-from typing import List
from pydantic import BaseModel
@@ -15,5 +14,5 @@ class ReadinessCheckModel(BaseModel):
class ReadinessModel(BaseModel):
- checks: List[ReadinessCheckModel]
+ checks: list[ReadinessCheckModel]
status: ReadinessEnum
diff --git a/models/reminder.py b/models/reminder.py
index dee021a..bc714a6 100644
--- a/models/reminder.py
+++ b/models/reminder.py
@@ -10,5 +10,5 @@ class ReminderModel(BaseModel):
# Editable fields
description: str
due_date_time: datetime
- owner: Optional[str] = None # Optional for backwards compatibility
+ owner: str | None = None # Optional for backwards compatibility
title: str
diff --git a/persistence/ai_search.py b/persistence/ai_search.py
index 34f8d24..dcbb228 100644
--- a/persistence/ai_search.py
+++ b/persistence/ai_search.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import (
HttpResponseError,
@@ -35,7 +33,7 @@ from persistence.isearch import ISearch
class AiSearchSearch(ISearch):
- _client: Optional[SearchClient] = None
+ _client: SearchClient | None = None
_config: AiSearchModel
def __init__(self, cache: ICache, config: AiSearchModel):
@@ -59,7 +57,7 @@ class AiSearchSearch(ISearch):
logger.error("Error requesting AI Search", exc_info=True)
except ServiceRequestError:
logger.error("Error connecting to AI Search", exc_info=True)
- except Exception: # pylint: disable=broad-exception-caught
+ except Exception:
logger.error(
"Unknown error while checking AI Search readiness", exc_info=True
)
@@ -76,7 +74,7 @@ class AiSearchSearch(ISearch):
lang: str,
text: str,
cache_only: bool = False,
- ) -> Optional[list[TrainingModel]]:
+ ) -> list[TrainingModel] | None:
logger.debug('Searching training data for "%s"', text)
if not text:
return None
@@ -140,7 +138,7 @@ class AiSearchSearch(ISearch):
)
except ValidationError as e:
logger.debug("Parsing error: %s", e.errors())
- except ResourceNotFoundError as e:
+ except ResourceNotFoundError:
logger.warning('AI Search index "%s" not found', self._config.index)
except HttpResponseError as e:
logger.error("Error requesting AI Search: %s", e)
diff --git a/persistence/communication_services.py b/persistence/communication_services.py
index 0736a11..532b5ca 100644
--- a/persistence/communication_services.py
+++ b/persistence/communication_services.py
@@ -13,7 +13,7 @@ from persistence.isms import ISms
class CommunicationServicesSms(ISms):
- _client: Optional[SmsClient] = None
+ _client: SmsClient | None = None
_config: CommunicationServicesModel
def __init__(self, config: CommunicationServicesModel):
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index f445cf1..104f05c 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -1,7 +1,7 @@
import asyncio
-import logging
+from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
-from typing import AsyncGenerator, Optional
+from http import HTTPStatus
from uuid import UUID, uuid4
from azure.cosmos import ConsistencyLevel
@@ -20,7 +20,7 @@ from persistence.istore import IStore
class CosmosDbStore(IStore):
- _client: Optional[CosmosClient] = None
+ _client: CosmosClient | None = None
_config: CosmosDbModel
def __init__(self, cache: ICache, config: CosmosDbModel):
@@ -54,9 +54,9 @@ class CosmosDbStore(IStore):
read_item = await db.read_item(
item=test_id, partition_key=test_partition
)
- assert {
- k: v for k, v in read_item.items() if k in test_dict
- } == test_dict # Check only the relevant fields, Cosmos DB adds metadata
+ assert (
+ {k: v for k, v in read_item.items() if k in test_dict} == test_dict
+ ) # Check only the relevant fields, Cosmos DB adds metadata
# Delete the item
await db.delete_item(item=test_id, partition_key=test_partition)
# Test the item does not exist
@@ -67,7 +67,7 @@ class CosmosDbStore(IStore):
logger.error("Readiness test failed", exc_info=True)
except CosmosHttpResponseError:
logger.error("Error requesting CosmosDB", exc_info=True)
- except Exception: # pylint: disable=broad-exception-caught
+ except Exception:
logger.error(
"Unknown error while checking Cosmos DB readiness", exc_info=True
)
@@ -80,12 +80,12 @@ class CosmosDbStore(IStore):
await db.read_item(item=test_id, partition_key=partition_key)
exist = True
except CosmosHttpResponseError as e:
- if e.status_code != 404:
+ if e.status_code != HTTPStatus.NOT_FOUND:
logger.error("Error requesting CosmosDB: %s", e)
exist = True
return exist
- async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
+ async def call_aget(self, call_id: UUID) -> CallStateModel | None:
logger.debug("Loading call %s", call_id)
# Try cache
@@ -151,7 +151,7 @@ class CosmosDbStore(IStore):
return res
- async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
+ async def call_asearch_one(self, phone_number: str) -> CallStateModel | None:
logger.debug("Loading last call for %s", phone_number)
# Try cache
@@ -196,8 +196,8 @@ class CosmosDbStore(IStore):
async def call_asearch_all(
self,
count: int,
- phone_number: Optional[str] = None,
- ) -> tuple[Optional[list[CallStateModel]], int]:
+ phone_number: str | None = None,
+ ) -> tuple[list[CallStateModel] | None, int]:
logger.debug("Searching calls, for %s and count %s", phone_number, count)
# TODO: Cache results
calls, total = await asyncio.gather(
@@ -209,8 +209,8 @@ class CosmosDbStore(IStore):
async def _call_asearch_all_calls_worker(
self,
count: int,
- phone_number: Optional[str] = None,
- ) -> Optional[list[CallStateModel]]:
+ phone_number: str | None = None,
+ ) -> list[CallStateModel] | None:
calls: list[CallStateModel] = []
try:
async with self._use_client() as db:
@@ -245,7 +245,7 @@ class CosmosDbStore(IStore):
async def _call_asearch_all_total_worker(
self,
- phone_number: Optional[str] = None,
+ phone_number: str | None = None,
) -> int:
total = 0
try:
diff --git a/persistence/icache.py b/persistence/icache.py
index d86b245..880fc72 100644
--- a/persistence/icache.py
+++ b/persistence/icache.py
@@ -6,7 +6,6 @@ from models.readiness import ReadinessEnum
class ICache(ABC):
-
@abstractmethod
@tracer.start_as_current_span("cache_areadiness")
async def areadiness(self) -> ReadinessEnum:
@@ -14,12 +13,12 @@ class ICache(ABC):
@abstractmethod
@tracer.start_as_current_span("cache_aconnect")
- async def aget(self, key: str) -> Optional[bytes]:
+ async def aget(self, key: str) -> bytes | None:
pass
@abstractmethod
@tracer.start_as_current_span("cache_aset")
- async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:
+ async def aset(self, key: str, value: str | bytes | None) -> bool:
pass
@abstractmethod
diff --git a/persistence/isearch.py b/persistence/isearch.py
index aafe617..aa66559 100644
--- a/persistence/isearch.py
+++ b/persistence/isearch.py
@@ -25,5 +25,5 @@ class ISearch(ABC):
lang: str,
text: str,
cache_only: bool = False,
- ) -> Optional[list[TrainingModel]]:
+ ) -> list[TrainingModel] | None:
pass
diff --git a/persistence/isms.py b/persistence/isms.py
index 50ba369..460ffb0 100644
--- a/persistence/isms.py
+++ b/persistence/isms.py
@@ -6,7 +6,6 @@ from models.readiness import ReadinessEnum
class ISms(ABC):
-
@abstractmethod
@tracer.start_as_current_span("sms_areadiness")
async def areadiness(self) -> ReadinessEnum:
diff --git a/persistence/istore.py b/persistence/istore.py
index b0ee584..b0acd21 100644
--- a/persistence/istore.py
+++ b/persistence/istore.py
@@ -21,7 +21,7 @@ class IStore(ABC):
@abstractmethod
@tracer.start_as_current_span("store_call_aget")
- async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
+ async def call_aget(self, call_id: UUID) -> CallStateModel | None:
pass
@abstractmethod
@@ -31,7 +31,7 @@ class IStore(ABC):
@abstractmethod
@tracer.start_as_current_span("store_call_adel")
- async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
+ async def call_asearch_one(self, phone_number: str) -> CallStateModel | None:
pass
@abstractmethod
@@ -39,8 +39,8 @@ class IStore(ABC):
async def call_asearch_all(
self,
count: int,
- phone_number: Optional[str] = None,
- ) -> tuple[Optional[list[CallStateModel]], int]:
+ phone_number: str | None = None,
+ ) -> tuple[list[CallStateModel] | None, int]:
pass
def _cache_key_call_id(self, call_id: UUID) -> str:
diff --git a/persistence/memory.py b/persistence/memory.py
index 0a9ae76..1a9bf12 100644
--- a/persistence/memory.py
+++ b/persistence/memory.py
@@ -17,7 +17,7 @@ class MemoryCache(ICache):
See: https://en.wikipedia.org/wiki/Cache_replacement_policies#Least_recently_used_(LRU)
"""
- _cache: OrderedDict[str, Union[bytes, None]] = OrderedDict()
+ _cache: OrderedDict[str, bytes | None] = OrderedDict()
_config: MemoryModel
def __init__(self, config: MemoryModel):
@@ -33,7 +33,7 @@ class MemoryCache(ICache):
"""
return ReadinessEnum.OK # Always ready, it's memory :)
- async def aget(self, key: str) -> Optional[bytes]:
+ async def aget(self, key: str) -> bytes | None:
"""
Get a value from the cache.
@@ -46,7 +46,7 @@ class MemoryCache(ICache):
self._cache.move_to_end(sha_key, last=False) # Move to first
return res
- async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:
+ async def aset(self, key: str, value: str | bytes | None) -> bool:
"""
Set a value in the cache.
"""
diff --git a/persistence/redis.py b/persistence/redis.py
index ccf8c90..e300f66 100644
--- a/persistence/redis.py
+++ b/persistence/redis.py
@@ -1,5 +1,4 @@
import hashlib
-from typing import Optional, Union
from uuid import uuid4
from opentelemetry.instrumentation.redis import RedisInstrumentor
@@ -68,11 +67,11 @@ class RedisCache(ICache):
logger.error("Readiness test failed", exc_info=True)
except RedisError:
logger.error("Error requesting Redis", exc_info=True)
- except Exception: # pylint: disable=broad-exception-caught
+ except Exception:
logger.error("Unknown error while checking Redis readiness", exc_info=True)
return ReadinessEnum.FAIL
- async def aget(self, key: str) -> Optional[bytes]:
+ async def aget(self, key: str) -> bytes | None:
"""
Get a value from the cache.
@@ -88,7 +87,7 @@ class RedisCache(ICache):
logger.error("Error getting value", exc_info=True)
return res
- async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:
+ async def aset(self, key: str, value: str | bytes | None) -> bool:
"""
Set a value in the cache.
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index d76b84c..319d4de 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -1,7 +1,7 @@
import asyncio
import os
+from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager
-from typing import AsyncGenerator, Optional
from uuid import UUID
from aiosqlite import Connection, connect as sqlite_connect
@@ -52,11 +52,11 @@ class SqliteStore(IStore):
async with self._use_db() as db:
await db.execute("SELECT 1")
return ReadinessEnum.OK
- except Exception: # pylint: disable=broad-exception-caught
+ except Exception:
logger.error("Unknown error while checking SQLite readiness", exc_info=True)
return ReadinessEnum.FAIL
- async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
+ async def call_aget(self, call_id: UUID) -> CallStateModel | None:
logger.debug("Loading call %s", call_id)
# Try cache
@@ -116,7 +116,7 @@ class SqliteStore(IStore):
return True
- async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
+ async def call_asearch_one(self, phone_number: str) -> CallStateModel | None:
logger.debug("Loading last call for %s", phone_number)
# Try cache
@@ -154,8 +154,8 @@ class SqliteStore(IStore):
async def call_asearch_all(
self,
count: int,
- phone_number: Optional[str] = None,
- ) -> tuple[Optional[list[CallStateModel]], int]:
+ phone_number: str | None = None,
+ ) -> tuple[list[CallStateModel] | None, int]:
logger.debug("Searching calls, for %s and count %s", phone_number, count)
# TODO: Cache results
calls, total = await asyncio.gather(
@@ -167,8 +167,8 @@ class SqliteStore(IStore):
async def _call_asearch_all_calls_worker(
self,
count: int,
- phone_number: Optional[str] = None,
- ) -> Optional[list[CallStateModel]]:
+ phone_number: str | None = None,
+ ) -> list[CallStateModel] | None:
calls: list[CallStateModel] = []
async with self._use_db() as db:
where_clause = (
@@ -200,7 +200,7 @@ class SqliteStore(IStore):
async def _call_asearch_all_total_worker(
self,
- phone_number: Optional[str] = None,
+ phone_number: str | None = None,
) -> int:
async with self._use_db() as db:
where_clause = (
diff --git a/persistence/twilio.py b/persistence/twilio.py
index 464b12a..cb2b2ac 100644
--- a/persistence/twilio.py
+++ b/persistence/twilio.py
@@ -1,5 +1,3 @@
-from typing import Optional
-
from twilio.base.exceptions import TwilioRestException
from twilio.rest import Client
@@ -12,7 +10,7 @@ from persistence.isms import ISms
class TwilioSms(ISms):
- _client: Optional[Client] = None
+ _client: Client | None = None
_config: TwilioModel
def __init__(self, config: TwilioModel):
@@ -34,7 +32,7 @@ class TwilioSms(ISms):
return ReadinessEnum.OK
except AssertionError:
logger.error("Readiness test failed", exc_info=True)
- except Exception: # pylint: disable=broad-exception-caught
+ except Exception:
logger.error("Unknown error while checking Twilio readiness", exc_info=True)
return ReadinessEnum.FAIL
diff --git a/tests/cache.py b/tests/cache.py
index 5999101..e07db75 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 # pyright: ignore
+from pytest import assume
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 055d23d..d6e9dca 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -2,8 +2,9 @@ import hashlib
import random
import string
import xml.etree.ElementTree as ET
+from collections.abc import Callable
from textwrap import dedent
-from typing import Any, Callable, Optional, Union
+from typing import Any
import pytest
import yaml
@@ -45,10 +46,10 @@ class CallConnectionClientMock(CallConnectionClient):
async def start_recognizing_media(
self,
- play_prompt: Union[FileSource, TextSource, SsmlSource],
- *args,
- operation_context: Optional[str] = None,
- **kwargs,
+ play_prompt: FileSource | TextSource | SsmlSource,
+ *args, # noqa: ARG002
+ operation_context: str | None = None,
+ **kwargs, # noqa: ARG002
) -> None:
contexts = _str_to_contexts(operation_context)
for context in contexts or []:
@@ -57,10 +58,10 @@ class CallConnectionClientMock(CallConnectionClient):
async def play_media(
self,
- play_source: Union[FileSource, TextSource, SsmlSource],
- *args,
- operation_context: Optional[str] = None,
- **kwargs,
+ play_source: FileSource | TextSource | SsmlSource,
+ *args, # noqa: ARG002
+ operation_context: str | None = None,
+ **kwargs, # noqa: ARG002
) -> None:
contexts = _str_to_contexts(operation_context)
for context in contexts or []:
@@ -69,16 +70,16 @@ class CallConnectionClientMock(CallConnectionClient):
async def transfer_call_to_participant(
self,
- *args,
- **kwargs,
+ *args, # noqa: ARG002
+ **kwargs, # noqa: ARG002
) -> TransferCallResult:
self._transfer_callback()
return TransferCallResult()
async def hang_up(
self,
- *args,
- **kwargs,
+ *args, # noqa: ARG002
+ **kwargs, # noqa: ARG002
) -> None:
self._hang_up_callback()
@@ -89,9 +90,7 @@ class CallConnectionClientMock(CallConnectionClient):
) -> None:
pass
- def _log_media(
- self, play_source: Union[FileSource, TextSource, SsmlSource]
- ) -> None:
+ def _log_media(self, play_source: FileSource | TextSource | SsmlSource) -> None:
if isinstance(play_source, TextSource):
self._play_media_callback(play_source.text.strip())
elif isinstance(play_source, SsmlSource):
@@ -118,8 +117,8 @@ class CallAutomationClientMock(CallAutomationClient):
def get_call_connection(
self,
- *args,
- **kwargs,
+ *args, # noqa: ARG002
+ **kwargs, # noqa: ARG002
) -> CallConnectionClientMock:
return self._call_client
@@ -202,9 +201,7 @@ class DeepEvalAzureOpenAI(GPTModel):
return True
def _cache_key(self, prompt: str) -> str:
- llm_string = self._model._get_llm_string(
- input=prompt
- ) # pylint: disable=protected-access
+ llm_string = self._model._get_llm_string(input=prompt)
llm_hash = hashlib.sha256(llm_string.encode(), usedforsecurity=False).digest()
return f"call-center-ai/{llm_hash}"
@@ -221,7 +218,6 @@ def with_conversations(fn=None) -> MarkDecorator:
with open(
encoding="utf-8",
file="tests/conversations.yaml",
- mode="r",
) as f:
file: dict = yaml.safe_load(f)
conversations: list[Conversation] = []
@@ -230,7 +226,7 @@ def with_conversations(fn=None) -> MarkDecorator:
conversations.append(Conversation.model_validate(conv))
except ValidationError:
logger.error("Failed to parse conversation", exc_info=True)
- print(f"Loaded {len(conversations)} conversations")
+ print(f"Loaded {len(conversations)} conversations") # noqa: T201
keys = sorted(Conversation.model_fields.keys() - {"id"})
values = [
pytest.param(
diff --git a/tests/llm.py b/tests/llm.py
index ff9a303..8d044e3 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -2,7 +2,6 @@ import asyncio
import json
import re
from datetime import datetime
-from typing import Optional
import pytest
from deepeval import assert_test
@@ -16,7 +15,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 # pyright: ignore
+from pytest import assume
from helpers.call_events import (
on_call_connected,
@@ -58,8 +57,8 @@ class ClaimRelevancyMetric(BaseMetric):
async def a_measure(
self,
test_case: LLMTestCase,
- *args,
- **kwargs,
+ *args, # noqa: ARG002
+ **kwargs, # noqa: ARG002
) -> float:
assert test_case.input
# Extract claim data
@@ -83,7 +82,7 @@ class ClaimRelevancyMetric(BaseMetric):
self.success = self.score >= self.threshold
return self.score
- async def _score_data(self, key: str, throry: str, real: Optional[str]) -> float:
+ async def _score_data(self, key: str, throry: str, real: str | None) -> float:
res, _ = await self.model.a_generate(
f"""
Assistant is a data analyst expert with 20 years of experience.
@@ -230,7 +229,7 @@ class ClaimRelevancyMetric(BaseMetric):
@with_conversations
@pytest.mark.asyncio(scope="session")
-async def test_llm(
+async def test_llm( # noqa: PLR0913
call: CallStateModel,
claim_tests_excl: list[str],
deepeval_model: GPTModel,
diff --git a/tests/search.py b/tests/search.py
index 84c7691..9d01836 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 # pyright: ignore
+from pytest import assume
from helpers.config import CONFIG
from helpers.logging import logger
@@ -38,8 +38,8 @@ class RagRelevancyMetric(BaseMetric):
async def a_measure(
self,
test_case: LLMTestCase,
- *args,
- **kwargs,
+ *args, # noqa: ARG002
+ **kwargs, # noqa: ARG002
) -> float:
assert test_case.input
assert test_case.retrieval_context
@@ -120,11 +120,11 @@ class RagRelevancyMetric(BaseMetric):
@with_conversations
@pytest.mark.asyncio(scope="session")
@pytest.mark.repeat(10) # Catch multi-threading and concurrency issues
-async def test_relevancy(
+async def test_relevancy( # noqa: PLR0913
call: CallStateModel,
- claim_tests_excl: list[str],
+ claim_tests_excl: list[str], # noqa: ARG001
deepeval_model: GPTModel,
- expected_output: str,
+ expected_output: str, # noqa: ARG001
speeches: list[str],
lang: str,
) -> None:
diff --git a/tests/store.py b/tests/store.py
index ab2e665..dd17113 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 # pyright: ignore
+from pytest import assume
from helpers.config import CONFIG
from helpers.config_models.database import ModeEnum as DatabaseModeEnum