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: Code comment formatting

Clémence Lesné4613a8335eee
diff --git a/app/helpers/call_utils.py b/app/helpers/call_utils.py
index 5ab9dbd..1243c8e 100644
--- a/app/helpers/call_utils.py
+++ b/app/helpers/call_utils.py
@@ -48,7 +48,6 @@ class CallHangupException(Exception):
pass
-
class ContextEnum(str, Enum):
"""
Enum for call context.
@@ -79,17 +78,21 @@ def tts_sentence_split(
# Split by sentence by punctuation
splits = re.split(_SENTENCE_PUNCTUATION_R, text)
for i, split in enumerate(splits):
- if i % 2 == 1: # Skip punctuation
+ # Skip punctuation
+ if i % 2 == 1:
continue
- if not split.strip(): # Skip empty lines
+ # Skip empty lines
+ if not split.strip():
continue
- if i == len(splits) - 1: # Skip last line in case of missing punctuation
+ # Skip last line in case of missing punctuation
+ if i == len(splits) - 1:
if include_last:
yield (
split.strip(),
len(split),
)
- else: # Add punctuation back
+ # Add punctuation back
+ else:
yield (
split.strip() + splits[i + 1].strip(),
len(split) + len(splits[i + 1]),
@@ -238,9 +241,8 @@ async def _chunk_before_tts(
chunks = []
chunk = ""
for to_add, _ in tts_sentence_split(text, True):
- if (
- len(chunk) + len(to_add) >= _MAX_CHARACTERS_PER_TTS
- ): # If chunck overflows TTS capacity, start a new record
+ # If chunck overflows TTS capacity, start a new record
+ if len(chunk) + len(to_add) >= _MAX_CHARACTERS_PER_TTS:
# Remove trailing space as sentences are separated by spaces
chunks.append(chunk.strip())
# Reset chunk
@@ -248,7 +250,8 @@ async def _chunk_before_tts(
# Add space to separate sentences
chunk += to_add + " "
- if chunk: # If there is a remaining chunk, add it
+ # If there is a remaining chunk, add it
+ if chunk:
# Remove trailing space as sentences are separated by spaces
chunks.append(chunk.strip())
diff --git a/app/helpers/config_models/conversation.py b/app/helpers/config_models/conversation.py
index 97608e0..45f90af 100644
--- a/app/helpers/config_models/conversation.py
+++ b/app/helpers/config_models/conversation.py
@@ -24,7 +24,10 @@ class LanguageEntryModel(BaseModel):
def human_name(self) -> str:
return self.pronunciations_en[0]
- def __str__(self): # Pretty print for logs
+ def __str__(self):
+ """
+ Return the short code as string.
+ """
return self.short_code
diff --git a/app/helpers/llm_tools.py b/app/helpers/llm_tools.py
index 97bd544..9d6c007 100644
--- a/app/helpers/llm_tools.py
+++ b/app/helpers/llm_tools.py
@@ -274,7 +274,8 @@ class DefaultPlugin(AbstractPlugin):
self.call.claim[field] = new_value
CallStateModel.model_validate(self.call) # Force a re-validation
return f'Updated claim field "{field}" with value "{new_value}".'
- except ValidationError as e: # Catch error to inform LLM and rollback changes
+ # Catch error to inform LLM and rollback changes
+ except ValidationError as e:
self.call.claim[field] = old_value
return f'Failed to edit field "{field}": {e.json()}'
diff --git a/app/helpers/llm_worker.py b/app/helpers/llm_worker.py
index 03ba698..3bfe22e 100644
--- a/app/helpers/llm_worker.py
+++ b/app/helpers/llm_worker.py
@@ -175,7 +175,8 @@ async def _completion_stream_worker( # noqa: PLR0912
maximum_tokens_reached = False
try:
- if platform.streaming: # Streaming
+ # Streaming
+ if platform.streaming:
stream: AsyncStream[
ChatCompletionChunk
] = await client.chat.completions.create(
@@ -184,15 +185,13 @@ async def _completion_stream_worker( # noqa: PLR0912
)
async for chunck in stream:
choices = chunck.choices
- if (
- not choices
- ): # Skip empty choices, happens sometimes with GPT-4 Turbo
+ # Skip empty choices, happens sometimes with GPT-4 Turbo
+ if not choices:
continue
choice = choices[0]
delta = choice.delta
- if (
- choice.finish_reason == "content_filter"
- ): # Azure OpenAI content filter
+ # Azure OpenAI content filter
+ if choice.finish_reason == "content_filter":
raise SafetyCheckError(f"Issue detected in text: {delta.content}")
if choice.finish_reason == "length":
logger.warning(
@@ -202,12 +201,14 @@ async def _completion_stream_worker( # noqa: PLR0912
if delta:
yield delta
- else: # Non-streaming, emulate streaming with a single completion
+ # Non-streaming, emulate streaming with a single completion
+ else:
completion: ChatCompletion = await client.chat.completions.create(
**chat_kwargs
)
choice = completion.choices[0]
- if choice.finish_reason == "content_filter": # Azure OpenAI content filter
+ # Azure OpenAI content filter
+ if choice.finish_reason == "content_filter":
raise SafetyCheckError(
f"Issue detected in generation: {choice.message.content}"
)
@@ -284,7 +285,8 @@ async def completion_sync(
# Validate
is_valid, validation_error, res_object = validation_callback(res_content)
- if not is_valid: # Retry if validation failed
+ # Retry if validation failed
+ if not is_valid:
if _retries_remaining == 0:
logger.error("LLM validation error: %s", validation_error)
return None
@@ -356,7 +358,8 @@ async def _completion_sync_worker(
raise SafetyCheckError("Issue detected in prompt") from e
raise e
choice = res.choices[0]
- if choice.finish_reason == "content_filter": # Azure OpenAI content filter
+ # Azure OpenAI content filter
+ if choice.finish_reason == "content_filter":
raise SafetyCheckError(
f"Issue detected in generation: {choice.message.content}"
)
diff --git a/app/helpers/translation.py b/app/helpers/translation.py
index fe6fc89..58d2334 100644
--- a/app/helpers/translation.py
+++ b/app/helpers/translation.py
@@ -31,7 +31,8 @@ async def translate_text(text: str, source_lang: str, target_lang: str) -> str |
Catch errors for a maximum of 3 times.
"""
- if source_lang == target_lang: # No need to translate
+ # No need to translate
+ if source_lang == target_lang:
return text
# Try cache
diff --git a/app/main.py b/app/main.py
index 9f3e9ec..e711918 100644
--- a/app/main.py
+++ b/app/main.py
@@ -702,7 +702,8 @@ async def _communicationservices_event_worker(
logger.debug("Call event received %s", event_type)
match event_type:
- case "Microsoft.Communication.CallConnected": # Call answered
+ # Call answered
+ case "Microsoft.Communication.CallConnected":
server_call_id = event.data["serverCallId"]
await on_call_connected(
call=call,
@@ -710,16 +711,19 @@ async def _communicationservices_event_worker(
server_call_id=server_call_id,
)
- case "Microsoft.Communication.CallDisconnected": # Call hung up
+ # Call hung up
+ case "Microsoft.Communication.CallDisconnected":
await on_call_disconnected(
call=call,
client=automation_client,
post_callback=_trigger_post_event,
)
- case "Microsoft.Communication.RecognizeCompleted": # Speech/IVR recognized
+ # Speech/IVR recognized
+ case "Microsoft.Communication.RecognizeCompleted":
recognition_result: str = event.data["recognitionType"]
- if recognition_result == "choices": # Handle IVR
+ # Handle IVR
+ if recognition_result == "choices":
label_detected: str = event.data["choiceResult"]["label"]
await on_ivr_recognized(
call=call,
@@ -727,7 +731,8 @@ async def _communicationservices_event_worker(
label=label_detected,
)
- case "Microsoft.Communication.RecognizeFailed": # Speech/IVR failed
+ # Speech/IVR failed
+ case "Microsoft.Communication.RecognizeFailed":
result_information = event.data["resultInformation"]
error_code: int = result_information["subCode"]
error_message: str = result_information["message"]
@@ -743,12 +748,14 @@ async def _communicationservices_event_worker(
post_callback=_trigger_post_event,
)
- case "Microsoft.Communication.PlayStarted": # Media started
+ # Media started
+ case "Microsoft.Communication.PlayStarted":
await on_play_started(
call=call,
)
- case "Microsoft.Communication.PlayCompleted": # Media played
+ # Media played
+ case "Microsoft.Communication.PlayCompleted":
await on_play_completed(
call=call,
client=automation_client,
@@ -756,7 +763,8 @@ async def _communicationservices_event_worker(
post_callback=_trigger_post_event,
)
- case "Microsoft.Communication.PlayFailed": # Media play failed
+ # Media play failed
+ case "Microsoft.Communication.PlayFailed":
result_information = event.data["resultInformation"]
error_code: int = result_information["subCode"]
await on_play_error(error_code)
diff --git a/app/models/message.py b/app/models/message.py
index c5d79c8..c216449 100644
--- a/app/models/message.py
+++ b/app/models/message.py
@@ -234,7 +234,8 @@ def remove_message_action(text: str) -> str:
return text
try:
return res.group(2) or ""
- except ValueError: # Regex failed, return original text
+ # Regex failed, return original text
+ except ValueError:
return text
@@ -255,5 +256,6 @@ def extract_message_style(text: str) -> tuple[StyleEnum, str]:
StyleEnum(res.group(1)), # style
(res.group(2) or ""), # content
)
- except ValueError: # Regex failed, return original text
+ # Regex failed, return original text
+ except ValueError:
return default_style, text