Skip to content

Commit

Permalink
quality: Code comment formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
clemlesne committed Dec 8, 2024
1 parent d56181d commit a4d693f
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 25 deletions.
1 change: 0 additions & 1 deletion app/helpers/call_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ class CallHangupException(Exception):
pass



class ContextEnum(str, Enum):
"""
Enum for call context.
Expand Down
5 changes: 4 additions & 1 deletion app/helpers/config_models/conversation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
3 changes: 2 additions & 1 deletion app/helpers/llm_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,8 @@ def _update_claim_field(self, update: UpdateClaimDict) -> str:
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()}'

Expand Down
25 changes: 14 additions & 11 deletions app/helpers/llm_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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(
Expand All @@ -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}"
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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}"
)
Expand Down
3 changes: 2 additions & 1 deletion app/helpers/translation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 16 additions & 8 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,32 +702,37 @@ 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,
client=automation_client,
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,
client=automation_client,
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"]
Expand All @@ -743,20 +748,23 @@ 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,
contexts=operation_contexts,
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)
Expand Down
6 changes: 4 additions & 2 deletions app/models/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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

0 comments on commit a4d693f

Please sign in to comment.