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

refacto: Simplify logging and reduce Function Apps unused logs

Clémence Lesnéace5e2db208c
diff --git a/bicep/app.bicep b/bicep/app.bicep
index df6db7f..5fd8b97 100644
--- a/bicep/app.bicep
+++ b/bicep/app.bicep
@@ -289,7 +289,7 @@ resource queueService 'Microsoft.Storage/storageAccounts/queueServices@2023-01-0
resource communicationServicesQueue 'Microsoft.Storage/storageAccounts/queueServices/queues@2023-01-01' = {
parent: queueService
- name: 'communication-services'
+ name: 'communication-services-${replace(localConfig.communication_services.phone_number, '+', '')}'
}
resource blobService 'Microsoft.Storage/storageAccounts/blobServices@2023-01-01' = {
diff --git a/function_app.py b/function_app.py
index bf35d93..1ddf3e5 100644
--- a/function_app.py
+++ b/function_app.py
@@ -1,10 +1,9 @@
# First imports, to make sure the following logs are first
-from helpers.logging import build_logger
+from helpers.logging import logger
from helpers.config import CONFIG
-_logger = build_logger(__name__)
-_logger.info(f"call-center-ai v{CONFIG.version}")
+logger.info(f"call-center-ai v{CONFIG.version}")
# General imports
@@ -74,7 +73,7 @@ _jinja.filters["markdown"] = lambda x: mistune.create_markdown(plugins=["abbr",
# Azure Communication Services
_source_caller = PhoneNumberIdentifier(CONFIG.communication_services.phone_number)
-_logger.info(f"Using phone number {str(CONFIG.communication_services.phone_number)}")
+logger.info(f"Using phone number {str(CONFIG.communication_services.phone_number)}")
# Cannot place calls with RBAC, need to use access key (see: https://learn.microsoft.com/en-us/azure/communication-services/concepts/authentication#authentication-options)
_automation_client = CallAutomationClient(
endpoint=CONFIG.communication_services.endpoint,
@@ -121,7 +120,7 @@ _COMMUNICATIONSERVICES_CALLABACK_TPL = urljoin(
str(CONFIG.public_domain),
"/communicationservices/event/{call_id}/{callback_secret}",
)
-_logger.info(f"Using call event URL {_COMMUNICATIONSERVICES_CALLABACK_TPL}")
+logger.info(f"Using call event URL {_COMMUNICATIONSERVICES_CALLABACK_TPL}")
@api.get(
@@ -260,7 +259,7 @@ async def call_post(initiate: CallInitiateModel) -> CallGetModel:
source_caller_id_number=_source_caller,
target_participant=PhoneNumberIdentifier(initiate.phone_number), # type: ignore
)
- _logger.info(
+ logger.info(
f"Created call with connection id: {call_connection_properties.call_connection_id}"
)
return CallGetModel.model_validate(call)
@@ -276,7 +275,7 @@ async def eventgrid_event_post(msg: func.QueueMessage) -> None:
event = EventGridEvent.from_json(msg.get_body())
event_type = event.event_type
- _logger.debug(f"Call inbound event {event_type} with data {event.data}")
+ logger.debug(f"Call inbound event {event_type} with data {event.data}")
if event_type == SystemEventNames.AcsIncomingCallEventName:
call_context: str = event.data["incomingCallContext"]
@@ -295,7 +294,7 @@ async def eventgrid_event_post(msg: func.QueueMessage) -> None:
phone_number: str = event.data["from"]
call = await _db.call_asearch_one(phone_number)
if not call:
- _logger.warning(f"Call for phone number {phone_number} not found")
+ logger.warning(f"Call for phone number {phone_number} not found")
return
await on_sms_received(
background_tasks=background_tasks,
@@ -337,10 +336,10 @@ async def _communicationservices_event_worker(
) -> None:
call = await _db.call_aget(call_id)
if not call:
- _logger.warning(f"Call {call_id} not found")
+ logger.warning(f"Call {call_id} not found")
return
if call.callback_secret != secret:
- _logger.warning(f"Secret for call {call_id} does not match")
+ logger.warning(f"Secret for call {call_id} does not match")
return
event = CloudEvent.from_dict(event_dict)
@@ -359,8 +358,8 @@ async def _communicationservices_event_worker(
else None
)
- _logger.debug(f"Call event received {event_type} for call {call}")
- _logger.debug(event.data)
+ logger.debug(f"Call event received {event_type} for call {call}")
+ logger.debug(event.data)
if event_type == "Microsoft.Communication.CallConnected": # Call answered
await on_call_connected(
@@ -509,7 +508,7 @@ async def twilio_sms(
phone_number = PhoneNumber(From)
call = await _db.call_asearch_one(phone_number)
if not call:
- _logger.warning(f"Call for phone number {phone_number} not found")
+ logger.warning(f"Call for phone number {phone_number} not found")
else:
event_status = await on_sms_received(
call=call,
diff --git a/helpers/call_events.py b/helpers/call_events.py
index ae249fe..d8d4060 100644
--- a/helpers/call_events.py
+++ b/helpers/call_events.py
@@ -5,7 +5,7 @@ from azure.communication.callautomation import (
RecognitionChoice,
)
from helpers.config import CONFIG
-from helpers.logging import build_logger, TRACER
+from helpers.logging import logger, tracer
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
@@ -34,19 +34,18 @@ from models.next import NextModel
from helpers.call_llm import llm_completion, llm_model, load_llm_chat
-_logger = build_logger(__name__)
_sms = CONFIG.sms.instance()
_db = CONFIG.database.instance()
[email protected]_as_current_span("on_new_call")
[email protected]_as_current_span("on_new_call")
async def on_new_call(
callback_url: str,
client: CallAutomationClient,
incoming_context: str,
phone_number: str,
) -> bool:
- _logger.debug(f"Incoming call handler caller ID: {phone_number}")
+ logger.debug(f"Incoming call handler caller ID: {phone_number}")
try:
answer_call_result = client.answer_call(
@@ -54,34 +53,34 @@ async def on_new_call(
cognitive_services_endpoint=CONFIG.cognitive_service.endpoint,
incoming_call_context=incoming_context,
)
- _logger.info(
+ logger.info(
f"Answered call with {phone_number} ({answer_call_result.call_connection_id})"
)
return True
except ClientAuthenticationError as e:
- _logger.error(
+ logger.error(
"Authentication error with Communication Services, check the credentials",
exc_info=True,
)
except HttpResponseError as e:
if "lifetime validation of the signed http request failed" in e.message.lower():
- _logger.debug("Old call event received, ignoring")
+ logger.debug("Old call event received, ignoring")
else:
- _logger.error(
+ logger.error(
f"Unknown error answering call with {phone_number}", exc_info=True
)
return False
[email protected]_as_current_span("on_call_connected")
[email protected]_as_current_span("on_call_connected")
async def on_call_connected(
call: CallStateModel,
client: CallAutomationClient,
) -> None:
- _logger.info("Call connected")
+ logger.info("Call connected")
call.voice_recognition_retry = 0 # Reset recognition retry counter
call.messages.append(
MessageModel(
@@ -98,24 +97,24 @@ async def on_call_connected(
) # Every time a call is answered, confirm the language
[email protected]_as_current_span("on_call_disconnected")
[email protected]_as_current_span("on_call_disconnected")
async def on_call_disconnected(
background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
) -> None:
- _logger.info("Call disconnected")
+ logger.info("Call disconnected")
await _handle_hangup(background_tasks, client, call)
[email protected]_as_current_span("on_speech_recognized")
[email protected]_as_current_span("on_speech_recognized")
async def on_speech_recognized(
background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
text: str,
) -> None:
- _logger.info(f"Voice recognition: {text}")
+ logger.info(f"Voice recognition: {text}")
call.messages.append(MessageModel(content=text, persona=MessagePersonaEnum.HUMAN))
await _db.call_aset(
call
@@ -131,14 +130,14 @@ async def on_speech_recognized(
)
[email protected]_as_current_span("on_speech_timeout_error")
[email protected]_as_current_span("on_speech_timeout_error")
async def on_speech_timeout_error(
call: CallStateModel,
client: CallAutomationClient,
contexts: Optional[list[CallContextEnum]],
) -> None:
if not (contexts and CallContextEnum.LAST_CHUNK in contexts):
- _logger.debug("Ignoring timeout if bot is still speaking")
+ logger.debug("Ignoring timeout if bot is still speaking")
return
res_context = None
@@ -161,16 +160,16 @@ async def on_speech_timeout_error(
)
[email protected]_as_current_span("on_speech_unknown_error")
[email protected]_as_current_span("on_speech_unknown_error")
async def on_speech_unknown_error(
call: CallStateModel,
client: CallAutomationClient,
error_code: int,
) -> None:
if error_code == 8511: # Failure while trying to play the prompt
- _logger.warning("Failed to play prompt")
+ logger.warning("Failed to play prompt")
else:
- _logger.warning(
+ logger.warning(
f"Recognition failed with unknown error code {error_code}, answering with default error"
)
await handle_recognize_text(
@@ -181,14 +180,14 @@ async def on_speech_unknown_error(
)
[email protected]_as_current_span("on_play_completed")
[email protected]_as_current_span("on_play_completed")
async def on_play_completed(
background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
contexts: Optional[list[CallContextEnum]],
) -> None:
- _logger.debug("Play completed")
+ logger.debug("Play completed")
if not contexts:
return
@@ -197,11 +196,11 @@ async def on_play_completed(
CallContextEnum.TRANSFER_FAILED in contexts
or CallContextEnum.GOODBYE in contexts
): # Call ended
- _logger.info("Ending call")
+ logger.info("Ending call")
await _handle_hangup(background_tasks, client, call)
elif CallContextEnum.CONNECT_AGENT in contexts: # Call transfer
- _logger.info("Initiating transfer call initiated")
+ logger.info("Initiating transfer call initiated")
await handle_transfer(
call=call,
client=client,
@@ -209,25 +208,25 @@ async def on_play_completed(
)
[email protected]_as_current_span("on_play_error")
[email protected]_as_current_span("on_play_error")
async def on_play_error(error_code: int) -> None:
- _logger.debug("Play failed")
+ logger.debug("Play failed")
# 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
- _logger.warning("Error during media play, file format is invalid")
+ logger.warning("Error during media play, file format is invalid")
elif error_code == 8536: # Action failed, file downloaded
- _logger.warning("Error during media play, file could not be downloaded")
+ logger.warning("Error during media play, file could not be downloaded")
elif error_code == 8565: # Action failed, AI services config
- _logger.error(
+ logger.error(
"Error during media play, impossible to connect with Azure AI services"
)
elif error_code == 9999: # Unknown
- _logger.warning("Error during media play, unknown internal server error")
+ logger.warning("Error during media play, unknown internal server error")
else:
- _logger.warning(f"Error during media play, unknown error code {error_code}")
+ logger.warning(f"Error during media play, unknown error code {error_code}")
[email protected]_as_current_span("on_ivr_recognized")
[email protected]_as_current_span("on_ivr_recognized")
async def on_ivr_recognized(
client: CallAutomationClient,
call: CallStateModel,
@@ -240,10 +239,10 @@ async def on_ivr_recognized(
call.initiate.lang.default_lang,
)
except ValueError:
- _logger.warning(f"Unknown IVR {label}, code not implemented")
+ logger.warning(f"Unknown IVR {label}, code not implemented")
return
- _logger.info(f"Setting call language to {lang}")
+ logger.info(f"Setting call language to {lang}")
call.lang = lang.short_code
await _db.call_aset(
call
@@ -272,19 +271,19 @@ async def on_ivr_recognized(
)
[email protected]_as_current_span("on_transfer_completed")
[email protected]_as_current_span("on_transfer_completed")
async def on_transfer_completed() -> None:
- _logger.info("Call transfer accepted event")
+ logger.info("Call transfer accepted event")
# TODO: Is there anything to do here?
[email protected]_as_current_span("on_transfer_error")
[email protected]_as_current_span("on_transfer_error")
async def on_transfer_error(
call: CallStateModel,
client: CallAutomationClient,
error_code: int,
) -> None:
- _logger.info(f"Error during call transfer, subCode {error_code}")
+ logger.info(f"Error during call transfer, subCode {error_code}")
await handle_recognize_text(
call=call,
client=client,
@@ -293,14 +292,14 @@ async def on_transfer_error(
)
[email protected]_as_current_span("on_sms_received")
[email protected]_as_current_span("on_sms_received")
async def on_sms_received(
background_tasks: BackgroundTasks,
call: CallStateModel,
client: CallAutomationClient,
message: str,
) -> bool:
- _logger.info(f"SMS received from {call.initiate.phone_number}: {message}")
+ logger.info(f"SMS received from {call.initiate.phone_number}: {message}")
call.messages.append(
MessageModel(
action=MessageActionEnum.SMS,
@@ -312,9 +311,9 @@ async def on_sms_received(
call
) # Save ASAP in DB allowing SMS answers to be more "in-sync"
if not call.in_progress:
- _logger.info("Call not in progress, answering with SMS")
+ logger.info("Call not in progress, answering with SMS")
else:
- _logger.info("Call in progress, answering with voice")
+ logger.info("Call in progress, answering with voice")
await load_llm_chat(
background_tasks=background_tasks,
call=call,
@@ -352,7 +351,7 @@ def _post_call_intelligence(
and call.messages[-2].persona == MessagePersonaEnum.ASSISTANT
and call.messages[-1].action == MessageActionEnum.HANGUP
):
- _logger.info(
+ logger.info(
"Call ended before any interaction, skipping post-call intelligence"
)
return
@@ -374,9 +373,9 @@ async def _post_call_sms(call: CallStateModel) -> None:
_, content = extract_message_style(remove_message_action(content or ""))
if not content:
- _logger.warning("Error generating SMS report")
+ logger.warning("Error generating SMS report")
return
- _logger.info(f"SMS report: {content}")
+ logger.info(f"SMS report: {content}")
# Send the SMS to both the current caller and the policyholder
success = False
@@ -387,7 +386,7 @@ async def _post_call_sms(call: CallStateModel) -> None:
continue
res = await _sms.asend(content, number)
if not res:
- _logger.warning(f"Failed sending SMS report to {number}")
+ logger.warning(f"Failed sending SMS report to {number}")
continue
success = True
@@ -406,7 +405,7 @@ async def _post_call_synthesis(call: CallStateModel) -> None:
"""
Synthesize the call and store it to the model.
"""
- _logger.debug("Synthesizing call")
+ logger.debug("Synthesizing call")
short, long = await asyncio.gather(
llm_completion(
@@ -430,11 +429,11 @@ async def _post_call_synthesis(call: CallStateModel) -> None:
_, long = extract_message_style(remove_message_action(long or ""))
if not short or not long:
- _logger.warning("Error generating synthesis")
+ logger.warning("Error generating synthesis")
return
- _logger.info(f"Short synthesis: {short}")
- _logger.info(f"Long synthesis: {long}")
+ logger.info(f"Short synthesis: {short}")
+ logger.info(f"Long synthesis: {long}")
call.synthesis = SynthesisModel(
long=long,
@@ -454,10 +453,10 @@ async def _post_call_next(call: CallStateModel) -> None:
)
if not next:
- _logger.warning("Error generating next action")
+ logger.warning("Error generating next action")
return
- _logger.info(f"Next action: {next}")
+ logger.info(f"Next action: {next}")
call.next = next
await _db.call_aset(call)
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 6cd0fda..7748601 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -1,7 +1,7 @@
from typing import Awaitable, Callable, Optional, Tuple, Type
from azure.communication.callautomation import CallAutomationClient
from helpers.config import CONFIG
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.call import CallStateModel
from models.message import (
extract_message_style,
@@ -33,7 +33,6 @@ from openai.types.chat import ChatCompletionSystemMessageParam
import time
-_logger = build_logger(__name__)
_cache = CONFIG.cache.instance()
_db = CONFIG.database.instance()
@@ -44,7 +43,7 @@ async def llm_completion(text: Optional[str], call: CallStateModel) -> Optional[
If the system prompt is None, no completion will be run and None will be returned. Otherwise, the response of the LLM will be returned.
"""
- _logger.info("Running LLM completion")
+ logger.info("Running LLM completion")
if not text:
return None
@@ -58,9 +57,9 @@ async def llm_completion(text: Optional[str], call: CallStateModel) -> Optional[
system=system,
)
except APIError as e:
- _logger.warning(f"OpenAI API call error: {e}")
+ logger.warning(f"OpenAI API call error: {e}")
except SafetyCheckError as e:
- _logger.warning(f"OpenAI safety check error: {e}")
+ logger.warning(f"OpenAI safety check error: {e}")
return content
@@ -73,7 +72,7 @@ async def llm_model(
The logic will try its best to return a model of the expected type, but it is not guaranteed. It it fails, `None` will be returned.
"""
- _logger.debug("Running LLM model")
+ logger.debug("Running LLM model")
if not text:
return None
@@ -88,7 +87,7 @@ async def llm_model(
system=system,
)
except APIError as e:
- _logger.warning(f"OpenAI API call error: {e}")
+ logger.warning(f"OpenAI API call error: {e}")
return res
@@ -106,7 +105,7 @@ def _llm_completion_system(
role="system",
),
]
- _logger.debug(f"Messages: {messages}")
+ logger.debug(f"Messages: {messages}")
return messages
@@ -124,7 +123,7 @@ async def load_llm_chat(
Returns the updated call model.
"""
- _logger.info("Loading LLM chat")
+ logger.info("Loading LLM chat")
should_play_sound = True
@@ -137,7 +136,7 @@ async def load_llm_chat(
try:
await safety_check(text)
except SafetyCheckError as e:
- _logger.warning(f"Unsafe text detected, not playing: {e}")
+ logger.warning(f"Unsafe text detected, not playing: {e}")
return
should_play_sound = False
@@ -207,7 +206,7 @@ async def load_llm_chat(
continue_chat = True
try:
while True:
- _logger.debug(f"Chat task status: {chat_task.done()}")
+ logger.debug(f"Chat task status: {chat_task.done()}")
if pointer_task.done(): # Test if another chat is running
if pointer_current == float(
@@ -215,7 +214,7 @@ async def load_llm_chat(
): # Pointer not updated
pointer_task = _pointer_task()
else: # Pointer updated by another instance
- _logger.warning("Another chat is running, stopping this one")
+ logger.warning("Another chat is running, stopping this one")
# Clean up Communication Services queue
await handle_clear_queue(call=call, client=client)
# Clean up tasks
@@ -235,7 +234,7 @@ async def load_llm_chat(
break
if hard_timeout_task.done(): # Break when hard timeout is reached
- _logger.warning(
+ logger.warning(
f"Hard timeout of {CONFIG.workflow.intelligence_hard_timeout_sec}s reached"
)
# Clean up
@@ -246,7 +245,7 @@ async def load_llm_chat(
if (
soft_timeout_task.done() and not soft_timeout_triggered
): # Speak when soft timeout is reached
- _logger.warning(
+ logger.warning(
f"Soft timeout of {CONFIG.workflow.intelligence_soft_timeout_sec}s reached"
)
soft_timeout_triggered = True
@@ -272,11 +271,11 @@ async def load_llm_chat(
await asyncio.sleep(0.5)
except Exception:
- _logger.warning("Error loading intelligence", exc_info=True)
+ logger.warning("Error loading intelligence", exc_info=True)
if is_error: # Error during chat
if not continue_chat or _iterations_remaining < 1: # Maximum retries reached
- _logger.warning("Maximum retries reached, stopping chat")
+ logger.warning("Maximum retries reached, stopping chat")
content = await CONFIG.prompts.tts.error(call)
style = MessageStyleEnum.NONE
await _user_callback(content, style)
@@ -289,7 +288,7 @@ async def load_llm_chat(
)
else: # Retry chat after an error
- _logger.info(f"Retrying chat, {_iterations_remaining - 1} remaining")
+ logger.info(f"Retrying chat, {_iterations_remaining - 1} remaining")
return await load_llm_chat(
background_tasks=background_tasks,
call=call,
@@ -299,7 +298,7 @@ async def load_llm_chat(
)
elif continue_chat: # Contiue chat
- _logger.info(f"Continuing chat, {_iterations_remaining - 1} remaining")
+ logger.info(f"Continuing chat, {_iterations_remaining - 1} remaining")
return await load_llm_chat(
background_tasks=background_tasks,
call=call,
@@ -333,7 +332,7 @@ async def _execute_llm_chat(
2. `bool`, should retry chat
4. `CallStateModel`, the updated model
"""
- _logger.debug("Running LLM chat")
+ logger.debug("Running LLM chat")
content_full = ""
async def _tools_callback(text: str, style: MessageStyleEnum) -> None:
@@ -355,8 +354,8 @@ async def _execute_llm_chat(
# Build RAG
trainings = await call.trainings()
- _logger.info(f"Enhancing LLM chat with {len(trainings)} trainings")
- _logger.debug(f"Trainings: {trainings}")
+ logger.info(f"Enhancing LLM chat with {len(trainings)} trainings")
+ logger.debug(f"Trainings: {trainings}")
# Build system prompts
system = [
@@ -385,10 +384,10 @@ async def _execute_llm_chat(
tools = []
if not use_tools:
- _logger.warning("Tools disabled for this chat")
+ logger.warning("Tools disabled for this chat")
else:
tools = await plugins.to_openai(call)
- _logger.debug(f"Tools: {tools}")
+ logger.debug(f"Tools: {tools}")
# Execute LLM inference
content_buffer_pointer = 0
@@ -415,7 +414,7 @@ async def _execute_llm_chat(
content_buffer_pointer += len(sentence)
plugins.style = await _content_callback(sentence, plugins.style)
except APIError as e:
- _logger.warning(f"OpenAI API call error: {e}")
+ logger.warning(f"OpenAI API call error: {e}")
return True, True, call
# Flush the remaining buffer
@@ -430,8 +429,8 @@ async def _execute_llm_chat(
# Delete action and style from the message as they are in the history and LLM hallucinates them
_, content_full = extract_message_style(remove_message_action(content_full))
- _logger.debug(f"Chat response: {content_full}")
- _logger.debug(f"Tool calls: {tool_calls}")
+ logger.debug(f"Chat response: {content_full}")
+ logger.debug(f"Tool calls: {tool_calls}")
# OpenAI GPT-4 Turbo sometimes return wrong tools schema, in that case, retry within limits
# TODO: Tries to detect this error earlier
@@ -439,12 +438,12 @@ async def _execute_llm_chat(
if any(
tool_call.function_name == "multi_tool_use.parallel" for tool_call in tool_calls
):
- _logger.warning(f'LLM send back invalid tool schema "multi_tool_use.parallel"')
+ logger.warning(f'LLM send back invalid tool schema "multi_tool_use.parallel"')
return True, True, call
# OpenAI GPT-4 Turbo tends to return empty content, in that case, retry within limits
if not content_full and not tool_calls:
- _logger.warning("Empty content, retrying")
+ logger.warning("Empty content, retrying")
return True, True, call
# Execute tools
diff --git a/helpers/call_utils.py b/helpers/call_utils.py
index ac7d2aa..471c6fa 100644
--- a/helpers/call_utils.py
+++ b/helpers/call_utils.py
@@ -1,7 +1,7 @@
from contextlib import asynccontextmanager
from enum import Enum
from helpers.config import CONFIG
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.call import CallStateModel
from models.message import StyleEnum as MessageStyleEnum
from typing import AsyncGenerator, Generator, Optional
@@ -24,7 +24,6 @@ import re
import json
-_logger = build_logger(__name__)
_SENTENCE_PUNCTUATION_R = r"(\. |\.$|[!?;])" # Split by sentence by punctuation
_TTS_SANITIZER_R = re.compile(
r"[^\w\s'«»“”\"\"‘’''(),.!?;:\-\+_@/]"
@@ -74,7 +73,7 @@ async def _handle_recognize_media(
"""
Play a media to a call participant and start recognizing the response.
"""
- _logger.debug(f"Recognizing media")
+ logger.debug(f"Recognizing media")
try:
assert call.voice_id, "Voice ID is required for recognizing media"
async with _use_call_client(client, call.voice_id) as call_client:
@@ -92,10 +91,10 @@ async def _handle_recognize_media(
target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore
)
except ResourceNotFoundError:
- _logger.debug(f"Call hung up before recognizing")
+ logger.debug(f"Call hung up before recognizing")
except HttpResponseError as e:
if "call already terminated" in e.message.lower():
- _logger.debug(f"Call hung up before playing")
+ logger.debug(f"Call hung up before playing")
else:
raise e
@@ -119,10 +118,10 @@ async def handle_media(
play_source=FileSource(url=sound_url),
)
except ResourceNotFoundError:
- _logger.debug(f"Call hung up before playing")
+ logger.debug(f"Call hung up before playing")
except HttpResponseError as e:
if "call already terminated" in e.message.lower():
- _logger.debug(f"Call hung up before playing")
+ logger.debug(f"Call hung up before playing")
else:
raise e
@@ -180,10 +179,10 @@ async def handle_clear_queue(
async with _use_call_client(client, call.voice_id) as call_client:
call_client.cancel_all_media_operations()
except ResourceNotFoundError:
- _logger.debug(f"Call hung up before playing")
+ logger.debug(f"Call hung up before playing")
except HttpResponseError as e:
if "call already terminated" in e.message.lower():
- _logger.debug(f"Call hung up before playing")
+ logger.debug(f"Call hung up before playing")
else:
raise e
@@ -241,7 +240,7 @@ def _audio_from_text(
"""
# Azure Speech Service TTS limit is 400 characters
if len(text) > 400:
- _logger.warning(
+ logger.warning(
f"Text is too long to be processed by TTS, truncating to 400 characters, fix this!"
)
text = text[:400]
@@ -271,8 +270,8 @@ async def handle_recognize_ivr(
Starts by playing text, then starts recognizing the response. The recognition will be interrupted by the user if they start speaking. The recognition will be played in the call language.
"""
- _logger.info(f"Playing text before IVR: {text}")
- _logger.debug(f"Recognizing IVR")
+ logger.info(f"Playing text before IVR: {text}")
+ logger.debug(f"Recognizing IVR")
try:
assert call.voice_id, "Voice ID is required for recognizing media"
async with _use_call_client(client, call.voice_id) as call_client:
@@ -290,23 +289,23 @@ async def handle_recognize_ivr(
target_participant=PhoneNumberIdentifier(call.initiate.phone_number), # type: ignore
)
except ResourceNotFoundError:
- _logger.debug(f"Call hung up before recognizing")
+ logger.debug(f"Call hung up before recognizing")
async def handle_hangup(
client: CallAutomationClient,
call: CallStateModel,
) -> None:
- _logger.debug("Hanging up call")
+ logger.debug("Hanging up call")
try:
assert call.voice_id, "Voice ID is required for recognizing media"
async with _use_call_client(client, call.voice_id) as call_client:
call_client.hang_up(is_for_everyone=True)
except ResourceNotFoundError:
- _logger.debug("Call already hung up")
+ logger.debug("Call already hung up")
except HttpResponseError as e:
if "call already terminated" in e.message.lower():
- _logger.debug("Call hung up before playing")
+ logger.debug("Call hung up before playing")
else:
raise e
@@ -317,7 +316,7 @@ async def handle_transfer(
target: str,
context: Optional[str] = None,
) -> None:
- _logger.debug(f"Transferring call to {target}")
+ logger.debug(f"Transferring call to {target}")
try:
assert call.voice_id, "Voice ID is required for recognizing media"
async with _use_call_client(client, call.voice_id) as call_client:
@@ -326,10 +325,10 @@ async def handle_transfer(
target_participant=PhoneNumberIdentifier(target),
)
except ResourceNotFoundError:
- _logger.debug(f"Call hung up before transferring")
+ logger.debug(f"Call hung up before transferring")
except HttpResponseError as e:
if "call already terminated" in e.message.lower():
- _logger.debug(f"Call hung up before transferring")
+ logger.debug(f"Call hung up before transferring")
else:
raise e
diff --git a/helpers/config_models/prompts.py b/helpers/config_models/prompts.py
index 8ba8f93..819f279 100644
--- a/helpers/config_models/prompts.py
+++ b/helpers/config_models/prompts.py
@@ -469,14 +469,14 @@ class LlmModel(BaseModel):
# Remove newlines to avoid hallucinations issues with GPT-4 Turbo
res = " ".join([line.strip() for line in res.splitlines()])
- self._logger.debug(f"LLM prompt: {res}")
+ self.logger.debug(f"LLM prompt: {res}")
return res
@cached_property
- def _logger(self) -> Logger:
- from helpers.logging import build_logger
+ def logger(self) -> Logger:
+ from helpers.logging import logger
- return build_logger(__name__)
+ return logger
class TtsModel(BaseModel):
@@ -592,15 +592,15 @@ class TtsModel(BaseModel):
initial, self.tts_lang, call.lang.short_code
)
except HttpResponseError as e:
- self._logger.warning(f"Failed to translate TTS prompt: {e}")
+ self.logger.warning(f"Failed to translate TTS prompt: {e}")
pass
return translation or initial
@cached_property
- def _logger(self) -> Logger:
- from helpers.logging import build_logger
+ def logger(self) -> Logger:
+ from helpers.logging import logger
- return build_logger(__name__)
+ return logger
class PromptsModel(BaseModel):
diff --git a/helpers/llm_tools.py b/helpers/llm_tools.py
index 4cc71fc..3da29d4 100644
--- a/helpers/llm_tools.py
+++ b/helpers/llm_tools.py
@@ -2,7 +2,7 @@ from azure.communication.callautomation import CallAutomationClient
from helpers.call_utils import ContextEnum as CallContextEnum, handle_recognize_text
from helpers.config import CONFIG
from helpers.llm_utils import function_schema
-from helpers.logging import build_logger
+from helpers.logging import logger
from inspect import getmembers, isfunction
from models.call import CallStateModel
from models.message import (
@@ -19,7 +19,6 @@ from typing_extensions import TypedDict
import asyncio
-_logger = build_logger(__name__)
_search = CONFIG.ai_search.instance()
_sms = CONFIG.sms.instance()
@@ -337,7 +336,7 @@ class LlmPlugins:
"""
await self.user_callback(customer_response, self.style)
# TODO: Implement notification to emergency services for production usage
- _logger.info(
+ logger.info(
f"Notifying {service}, location {location}, contact {contact}, reason {reason}."
)
return f"Notifying {service} for {reason}."
diff --git a/helpers/llm_utils.py b/helpers/llm_utils.py
index 0164bf5..f3eb8e0 100644
--- a/helpers/llm_utils.py
+++ b/helpers/llm_utils.py
@@ -4,7 +4,7 @@ See: https://github.com/microsoft/autogen/blob/2750391f847b7168d842dfcb815ac37bd
"""
import inspect
-from helpers.logging import build_logger
+from helpers.logging import logger
from typing import (
Any,
Callable,
@@ -23,7 +23,6 @@ from textwrap import dedent
from typing_extensions import Annotated
-_logger = build_logger(__name__)
T = TypeVar("T")
_jinja = Environment(
autoescape=True,
@@ -63,7 +62,7 @@ async def function_schema(
unannotated_with_default_s = [
f"'{k}'" for k in sorted(unannotated_with_default)
]
- _logger.warning(
+ logger.warning(
f"The following parameters of the function '{f.__name__}' with default values are not annotated: "
+ f"{', '.join(unannotated_with_default_s)}."
)
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 9a58534..ebec92b 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -9,7 +9,7 @@ from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError, ServiceRequestError
from helpers.config import CONFIG
from contextlib import asynccontextmanager
-from helpers.logging import build_logger, TRACER
+from helpers.logging import logger, tracer
from openai import (
APIConnectionError,
APIResponseValidationError,
@@ -58,11 +58,10 @@ environ["TRACELOOP_TRACE_CONTENT"] = str(
) # Instrumentation logs prompts, completions, and embeddings to span attributes, set to False to lower monitoring costs or to avoid logging PII
OpenAIInstrumentor(enrich_token_usage=True).instrument()
-_logger = build_logger(__name__)
-_logger.info(
+logger.info(
f"Using LLM models {CONFIG.llm.selected(False).model} (primary) and {CONFIG.llm.selected(True).model} (backup)"
)
-_logger.info(f"Using Content Safety {CONFIG.content_safety.endpoint}")
+logger.info(f"Using Content Safety {CONFIG.content_safety.endpoint}")
_cache = CONFIG.cache.instance()
ModelType = TypeVar("ModelType", bound=BaseModel)
@@ -85,7 +84,7 @@ class SafetyCheckError(Exception):
return self.message
[email protected]_as_current_span("completion_stream")
[email protected]_as_current_span("completion_stream")
async def completion_stream(
max_tokens: int,
messages: list[MessageModel],
@@ -111,7 +110,7 @@ async def completion_stream(
except Exception as e:
if not any(isinstance(e, exception) for exception in _retried_exceptions):
raise e
- _logger.warning(f"{e.__class__.__name__} error, trying with backup LLM")
+ logger.warning(f"{e.__class__.__name__} error, trying with backup LLM")
# Try more times with backup LLM, if it fails again, raise the error
retryed = AsyncRetrying(
@@ -153,7 +152,7 @@ async def _completion_stream_worker(
yield chunck
return
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
# Try live
to_cache: list[ChoiceDelta] = []
@@ -225,7 +224,7 @@ async def _completion_stream_worker(
await _cache.aset(cache_key, TypeAdapter(list[ChoiceDelta]).dump_json(to_cache))
[email protected]_as_current_span("completion_sync")
[email protected]_as_current_span("completion_sync")
async def completion_sync(
max_tokens: int,
system: list[ChatCompletionSystemMessageParam],
@@ -247,7 +246,7 @@ async def completion_sync(
except Exception as e:
if not any(isinstance(e, exception) for exception in _retried_exceptions):
raise e
- _logger.warning(f"{e.__class__.__name__} error, trying with backup LLM")
+ logger.warning(f"{e.__class__.__name__} error, trying with backup LLM")
# Try more times with backup LLM, if it fails again, raise the error
retryed = AsyncRetrying(
@@ -327,7 +326,7 @@ async def _completion_sync_worker(
stop=stop_after_attempt(3),
wait=wait_random_exponential(multiplier=0.5, max=30),
)
[email protected]_as_current_span("completion_model_sync")
[email protected]_as_current_span("completion_model_sync")
async def completion_model_sync(
max_tokens: int,
model: Type[ModelType],
@@ -399,14 +398,14 @@ def _limit_messages(
selected_messages += openai_message[::-1]
tokens += new_tokens
- _logger.info(f"Using {counter}/{total} messages ({tokens} tokens) as context")
+ logger.info(f"Using {counter}/{total} messages ({tokens} tokens) as context")
return [
*system,
*selected_messages[::-1],
]
[email protected]_as_current_span("safety_check")
[email protected]_as_current_span("safety_check")
async def safety_check(text: str) -> None:
"""
Raise `SafetyCheckError` if the text is safe, nothing otherwise.
@@ -419,15 +418,15 @@ async def safety_check(text: str) -> None:
try:
res = await _contentsafety_analysis(text)
except ServiceRequestError as e:
- _logger.error(f"Request error: {e}")
+ logger.error(f"Request error: {e}")
return # Assume safe
except HttpResponseError as e:
- _logger.error(f"Response error: {e}")
+ logger.error(f"Response error: {e}")
return # Assume safe
# Replace blocklist items with censored text
for match in res.blocklists_match or []:
- _logger.debug(f"Matched blocklist item: {match.blocklist_item_text}")
+ logger.debug(f"Matched blocklist item: {match.blocklist_item_text}")
text = text.replace(
match.blocklist_item_text, "*" * len(match.blocklist_item_text)
)
@@ -459,7 +458,7 @@ async def safety_check(text: str) -> None:
# True if all categories are safe
safety = hate_result and self_harm_result and sexual_result and violence_result
- _logger.debug(f'Text safety "{safety}" for text: {text}')
+ logger.debug(f'Text safety "{safety}" for text: {text}')
if not safety:
raise SafetyCheckError(
@@ -504,7 +503,7 @@ def _contentsafety_category_test(
detection = next((item for item in res if item.category == category), None)
if detection and detection.severity and detection.severity > score:
- _logger.debug(f"Matched {category} with severity {detection.severity}")
+ logger.debug(f"Matched {category} with severity {detection.severity}")
return False
return True
@@ -520,7 +519,7 @@ def _count_tokens(content: str, model: str) -> int:
encoding_name = tiktoken.encoding_name_for_model(model)
except KeyError:
encoding_name = tiktoken.encoding_name_for_model("gpt-3.5")
- _logger.warning(f"Unknown model {model}, using {encoding_name} encoding")
+ logger.warning(f"Unknown model {model}, using {encoding_name} encoding")
return len(tiktoken.get_encoding(encoding_name).encode(content))
diff --git a/helpers/logging.py b/helpers/logging.py
index 25044e4..3af4835 100644
--- a/helpers/logging.py
+++ b/helpers/logging.py
@@ -7,10 +7,10 @@ from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from os import environ
-# Logging levels
-_LOGGING_APP_LEVEL = CONFIG.monitoring.logging.app_level.value
-_LOGGING_SYS_LEVEL = CONFIG.monitoring.logging.sys_level.value
-basicConfig(level=_LOGGING_SYS_LEVEL)
+# Logger
+basicConfig(level=CONFIG.monitoring.logging.sys_level.value)
+logger = getLogger("call-center-ai")
+logger.setLevel(CONFIG.monitoring.logging.app_level.value)
# OpenTelemetry
environ["OTEL_TRACES_SAMPLER_ARG"] = str(0.5) # Sample 50% of traces
@@ -19,13 +19,7 @@ configure_azure_monitor(
) # Configure Azure monitor collection
AioHttpClientInstrumentor().instrument() # Instrument aiohttp
HTTPXClientInstrumentor().instrument() # Instrument httpx
-TRACER = trace.get_tracer(
+tracer = trace.get_tracer(
instrumenting_library_version=CONFIG.version,
instrumenting_module_name="com.github.clemlesne.call-center-ai",
) # Create a tracer that will be used in the app
-
-
-def build_logger(name: str) -> Logger:
- logger = getLogger(name)
- logger.setLevel(_LOGGING_APP_LEVEL)
- return logger
diff --git a/helpers/translation.py b/helpers/translation.py
index bea453b..aa11e2f 100644
--- a/helpers/translation.py
+++ b/helpers/translation.py
@@ -4,7 +4,7 @@ from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
from contextlib import asynccontextmanager
from helpers.config import CONFIG
-from helpers.logging import build_logger
+from helpers.logging import logger
from typing import AsyncGenerator, Optional
from tenacity import (
retry_if_exception_type,
@@ -14,8 +14,7 @@ from tenacity import (
)
-_logger = build_logger(__name__)
-_logger.info(f"Using Translation {CONFIG.ai_translation.endpoint}")
+logger.info(f"Using Translation {CONFIG.ai_translation.endpoint}")
_cache = CONFIG.cache.instance()
diff --git a/host.json b/host.json
index 836fbfd..78818a1 100644
--- a/host.json
+++ b/host.json
@@ -4,6 +4,13 @@
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.0.0, 5.0.0)"
},
+ "logging": {
+ "logLevel": {
+ "default": "Warning",
+ "Function": "Information",
+ "Host.Results": "Information"
+ }
+ },
"extensions": {
"http": {
"maxConcurrentRequests": 8,
diff --git a/models/call.py b/models/call.py
index 6358eab..9aabc5e 100644
--- a/models/call.py
+++ b/models/call.py
@@ -112,9 +112,9 @@ class CallStateModel(CallGetModel):
Is using query expansion from last messages. Then, data is sorted by score.
"""
from helpers.config import CONFIG
- from helpers.logging import TRACER
+ from helpers.logging import tracer
- with TRACER.start_as_current_span("trainings"):
+ with tracer.start_as_current_span("trainings"):
search = CONFIG.ai_search.instance()
tasks = await asyncio.gather(
*[
diff --git a/models/message.py b/models/message.py
index 5a2add4..401927b 100644
--- a/models/message.py
+++ b/models/message.py
@@ -80,9 +80,8 @@ class ToolModel(BaseModel):
return self
async def execute_function(self, plugins: object) -> None:
- from helpers.logging import build_logger, TRACER
+ from helpers.logging import logger, tracer
- logger = build_logger(__name__)
json_str = self.function_arguments
name = self.function_name
@@ -107,7 +106,7 @@ class ToolModel(BaseModel):
self.content = f"Bad arguments, available are {ToolModel._available_function_names()}. Please try again."
return
- with TRACER.start_as_current_span(
+ with tracer.start_as_current_span(
name="execute_function",
attributes={
"args": json.dumps(args),
diff --git a/persistence/ai_search.py b/persistence/ai_search.py
index 086feae..dc87223 100644
--- a/persistence/ai_search.py
+++ b/persistence/ai_search.py
@@ -8,7 +8,7 @@ from azure.search.documents.aio import SearchClient
from azure.search.documents.models import VectorizableTextQuery
from contextlib import asynccontextmanager
from helpers.config_models.ai_search import AiSearchModel
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.call import CallStateModel
from models.readiness import ReadinessStatus
from models.training import TrainingModel
@@ -25,15 +25,12 @@ from tenacity import (
)
-_logger = build_logger(__name__)
-
-
class AiSearchSearch(ISearch):
_config: AiSearchModel
def __init__(self, cache: ICache, config: AiSearchModel):
- _logger.info(f"Using AI Search {config.endpoint} with index {config.index}")
- _logger.info(
+ logger.info(f"Using AI Search {config.endpoint} with index {config.index}")
+ logger.info(
f"Note: At ~300 chars /doc, each LLM call will use approx {300 * config.top_k * config.expansion_k / 4} tokens (without tools)"
)
self._config = config
@@ -48,9 +45,9 @@ class AiSearchSearch(ISearch):
await db.get_document_count()
return ReadinessStatus.OK
except HttpResponseError as e:
- _logger.error(f"Error requesting AI Search, {e}")
+ logger.error(f"Error requesting AI Search, {e}")
except ServiceRequestError as e:
- _logger.error(f"Error connecting to AI Search, {e}")
+ logger.error(f"Error connecting to AI Search, {e}")
return ReadinessStatus.FAIL
@retry(
@@ -64,7 +61,7 @@ class AiSearchSearch(ISearch):
text: str,
lang: str,
) -> Optional[list[TrainingModel]]:
- _logger.debug(f'Searching training data for "{text}"')
+ logger.debug(f'Searching training data for "{text}"')
if not text:
return None
@@ -75,7 +72,7 @@ class AiSearchSearch(ISearch):
try:
return TypeAdapter(list[TrainingModel]).validate_json(cached)
except ValidationError:
- _logger.warning(f"Error parsing cached training: {cached}")
+ logger.warning(f"Error parsing cached training: {cached}")
pass
# Try live
@@ -123,11 +120,11 @@ class AiSearchSearch(ISearch):
)
)
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
except HttpResponseError as e:
- _logger.error(f"Error requesting AI Search, {e}")
+ logger.error(f"Error requesting AI Search, {e}")
except ServiceRequestError as e:
- _logger.error(f"Error connecting to AI Search, {e}")
+ logger.error(f"Error connecting to AI Search, {e}")
# Update cache
await self._cache.aset(
diff --git a/persistence/communication_services.py b/persistence/communication_services.py
index 8c628f1..f1eff24 100644
--- a/persistence/communication_services.py
+++ b/persistence/communication_services.py
@@ -3,21 +3,18 @@ from azure.communication.sms.aio import SmsClient
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError
from contextlib import asynccontextmanager
from helpers.config_models.communication_services import CommunicationServicesModel
-from helpers.logging import build_logger
+from helpers.logging import logger
from helpers.pydantic_types.phone_numbers import PhoneNumber
from models.readiness import ReadinessStatus
from persistence.isms import ISms
from typing import AsyncGenerator
-_logger = build_logger(__name__)
-
-
class CommunicationServicesSms(ISms):
_config: CommunicationServicesModel
def __init__(self, config: CommunicationServicesModel):
- _logger.info(f"Using Communication Services from number {config.phone_number}")
+ logger.info(f"Using Communication Services from number {config.phone_number}")
self._config = config
async def areadiness(self) -> ReadinessStatus:
@@ -28,9 +25,9 @@ class CommunicationServicesSms(ISms):
return ReadinessStatus.OK
async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
- _logger.info(f"Sending SMS to {phone_number}")
+ logger.info(f"Sending SMS to {phone_number}")
success = False
- _logger.info(f"SMS content: {content}")
+ logger.info(f"SMS content: {content}")
try:
async with self._use_client() as client:
responses: list[SmsSendResult] = await client.send(
@@ -40,20 +37,20 @@ class CommunicationServicesSms(ISms):
)
response = responses[0]
if response.successful:
- _logger.debug(f"SMS sent {response.message_id} to {response.to}")
+ logger.debug(f"SMS sent {response.message_id} to {response.to}")
success = True
else:
- _logger.warning(
+ logger.warning(
f"Failed SMS to {response.to}, status {response.http_status_code}, error {response.error_message}"
)
except ClientAuthenticationError:
- _logger.error(
+ logger.error(
"Authentication error for SMS, check the credentials", exc_info=True
)
except HttpResponseError as e:
- _logger.error(f"Error sending SMS: {e}")
+ logger.error(f"Error sending SMS: {e}")
except Exception:
- _logger.warning(f"Failed SMS to {phone_number}", exc_info=True)
+ logger.warning(f"Failed SMS to {phone_number}", exc_info=True)
return success
@asynccontextmanager
diff --git a/persistence/cosmos_db.py b/persistence/cosmos_db.py
index a965ca2..8978f30 100644
--- a/persistence/cosmos_db.py
+++ b/persistence/cosmos_db.py
@@ -5,7 +5,7 @@ from azure.cosmos.exceptions import CosmosHttpResponseError
from contextlib import asynccontextmanager
from helpers.config import CONFIG
from helpers.config_models.database import CosmosDbModel
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.call import CallStateModel
from models.readiness import ReadinessStatus
from persistence.istore import IStore
@@ -14,14 +14,11 @@ from typing import AsyncGenerator, Optional
from uuid import UUID, uuid4
-_logger = build_logger(__name__)
-
-
class CosmosDbStore(IStore):
_config: CosmosDbModel
def __init__(self, config: CosmosDbModel):
- _logger.info(f"Using Cosmos DB {config.database}/{config.container}")
+ logger.info(f"Using Cosmos DB {config.database}/{config.container}")
self._config = config
async def areadiness(self) -> ReadinessStatus:
@@ -60,9 +57,9 @@ class CosmosDbStore(IStore):
return ReadinessStatus.FAIL
return ReadinessStatus.OK
except AssertionError:
- _logger.error("Readiness test failed", exc_info=True)
+ logger.error("Readiness test failed", exc_info=True)
except CosmosHttpResponseError as e:
- _logger.error(f"Error requesting CosmosDB, {e}")
+ logger.error(f"Error requesting CosmosDB, {e}")
return ReadinessStatus.FAIL
async def _item_exists(self, test_id: str, partition_key: str) -> bool:
@@ -73,12 +70,12 @@ class CosmosDbStore(IStore):
exist = True
except CosmosHttpResponseError as e:
if e.status_code != 404:
- _logger.error(f"Error requesting CosmosDB, {e}")
+ logger.error(f"Error requesting CosmosDB, {e}")
exist = True
return exist
async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
- _logger.debug(f"Loading call {call_id}")
+ logger.debug(f"Loading call {call_id}")
call = None
try:
async with self._use_db() as db:
@@ -90,27 +87,27 @@ class CosmosDbStore(IStore):
try:
call = CallStateModel.model_validate(raw)
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
except StopAsyncIteration:
pass
except CosmosHttpResponseError as e:
- _logger.error(f"Error accessing CosmosDB, {e}")
+ logger.error(f"Error accessing CosmosDB, {e}")
return call
async def call_aset(self, call: CallStateModel) -> bool:
data = call.model_dump(mode="json", exclude_none=True)
data["id"] = str(call.call_id) # CosmosDB requires an id field
- _logger.debug(f"Saving call {call.call_id}: {data}")
+ logger.debug(f"Saving call {call.call_id}: {data}")
try:
async with self._use_db() as db:
await db.upsert_item(body=data)
return True
except CosmosHttpResponseError as e:
- _logger.error(f"Error accessing CosmosDB: {e}")
+ logger.error(f"Error accessing CosmosDB: {e}")
return False
async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
- _logger.debug(f"Loading last call for {phone_number}")
+ logger.debug(f"Loading last call for {phone_number}")
call = None
try:
async with self._use_db() as db:
@@ -128,11 +125,11 @@ class CosmosDbStore(IStore):
try:
call = CallStateModel.model_validate(raw)
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
except StopAsyncIteration:
pass
except CosmosHttpResponseError as e:
- _logger.error(f"Error accessing CosmosDB: {e}")
+ logger.error(f"Error accessing CosmosDB: {e}")
return call
async def call_asearch_all(
@@ -140,7 +137,7 @@ class CosmosDbStore(IStore):
count: int,
phone_number: Optional[str] = None,
) -> tuple[Optional[list[CallStateModel]], int]:
- _logger.debug(f"Searching calls, for {phone_number} and count {count}")
+ logger.debug(f"Searching calls, for {phone_number} and count {count}")
calls, total = await asyncio.gather(
self._call_asearch_all_calls_worker(count, phone_number),
self._call_asearch_all_total_worker(phone_number),
@@ -179,9 +176,9 @@ class CosmosDbStore(IStore):
try:
calls.append(CallStateModel.model_validate(raw))
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
except CosmosHttpResponseError as e:
- _logger.error(f"Error accessing CosmosDB, {e}")
+ logger.error(f"Error accessing CosmosDB, {e}")
return calls
async def _call_asearch_all_total_worker(
@@ -206,7 +203,7 @@ class CosmosDbStore(IStore):
)
total: int = await anext(items) # type: ignore
except CosmosHttpResponseError as e:
- _logger.error(f"Error accessing CosmosDB, {e}")
+ logger.error(f"Error accessing CosmosDB, {e}")
return total if total else 0
@asynccontextmanager
diff --git a/persistence/memory.py b/persistence/memory.py
index e972122..ab1e7ff 100644
--- a/persistence/memory.py
+++ b/persistence/memory.py
@@ -1,15 +1,12 @@
from collections import OrderedDict
from helpers.config_models.cache import MemoryModel
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.readiness import ReadinessStatus
from persistence.icache import ICache
from typing import Optional, Union
import hashlib
-_logger = build_logger(__name__)
-
-
class MemoryCache(ICache):
"""
A simple in-memory cache.
@@ -23,7 +20,7 @@ class MemoryCache(ICache):
_config: MemoryModel
def __init__(self, config: MemoryModel):
- _logger.warning(
+ logger.warning(
f"Using memory cache with {config.max_size} size limit, memory usage can be high, prefer an external cache like Redis"
)
self._config = config
diff --git a/persistence/redis.py b/persistence/redis.py
index c86880b..fa92c99 100644
--- a/persistence/redis.py
+++ b/persistence/redis.py
@@ -1,6 +1,6 @@
from contextlib import asynccontextmanager
from helpers.config_models.cache import RedisModel
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.readiness import ReadinessStatus
from opentelemetry.instrumentation.redis import RedisInstrumentor
from persistence.icache import ICache
@@ -16,7 +16,6 @@ import hashlib
# Instrument redis
RedisInstrumentor().instrument()
-_logger = build_logger(__name__)
_retry = Retry(backoff=ExponentialBackoff(), retries=3)
@@ -24,7 +23,7 @@ class RedisCache(ICache):
_config: RedisModel
def __init__(self, config: RedisModel):
- _logger.info(f"Using Redis cache {config.host}:{config.port}")
+ logger.info(f"Using Redis cache {config.host}:{config.port}")
self._config = config
async def areadiness(self) -> ReadinessStatus:
@@ -49,9 +48,9 @@ class RedisCache(ICache):
assert await db.get(test_name) is None
return ReadinessStatus.OK
except AssertionError as e:
- _logger.error(f"Readiness test failed, {e}")
+ logger.error(f"Readiness test failed, {e}")
except RedisError as e:
- _logger.error(f"Error requesting Redis, {e}")
+ logger.error(f"Error requesting Redis, {e}")
return ReadinessStatus.FAIL
async def aget(self, key: str) -> Optional[bytes]:
@@ -68,7 +67,7 @@ class RedisCache(ICache):
async with self._use_db() as db:
res = await db.get(sha_key)
except RedisError as e:
- _logger.error(f"Error getting value, {e}")
+ logger.error(f"Error getting value, {e}")
return res
async def aset(self, key: str, value: Union[str, bytes, None]) -> bool:
@@ -84,7 +83,7 @@ class RedisCache(ICache):
async with self._use_db() as db:
await db.set(sha_key, value if value else "")
except RedisError as e:
- _logger.error(f"Error setting value, {e}")
+ logger.error(f"Error setting value, {e}")
return False
return True
diff --git a/persistence/sqlite.py b/persistence/sqlite.py
index 947c501..31c81aa 100644
--- a/persistence/sqlite.py
+++ b/persistence/sqlite.py
@@ -2,7 +2,7 @@ from aiosqlite import connect as sqlite_connect, Connection as SQLiteConnection
from contextlib import asynccontextmanager
from helpers.config import CONFIG
from helpers.config_models.database import SqliteModel
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.call import CallStateModel
from models.readiness import ReadinessStatus
from opentelemetry.instrumentation.sqlite3 import SQLite3Instrumentor
@@ -17,16 +17,12 @@ import os
# Instrument sqlite
SQLite3Instrumentor().instrument()
-_logger = build_logger(__name__)
-
class SqliteStore(IStore):
_config: SqliteModel
def __init__(self, config: SqliteModel):
- _logger.info(
- f"Using SQLite database at {config.path} with table {config.table}"
- )
+ logger.info(f"Using SQLite database at {config.path} with table {config.table}")
self._config = config
async def areadiness(self) -> ReadinessStatus:
@@ -40,11 +36,11 @@ class SqliteStore(IStore):
await db.execute("SELECT 1")
return ReadinessStatus.OK
except Exception as e:
- _logger.error(f"Error requesting SQLite, {e}")
+ logger.error(f"Error requesting SQLite, {e}")
return ReadinessStatus.FAIL
async def call_aget(self, call_id: UUID) -> Optional[CallStateModel]:
- _logger.debug(f"Loading call {call_id}")
+ logger.debug(f"Loading call {call_id}")
call = None
async with self._use_db() as db:
cursor = await db.execute(
@@ -56,13 +52,13 @@ class SqliteStore(IStore):
try:
call = CallStateModel.model_validate_json(row[0])
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
return call
async def call_aset(self, call: CallStateModel) -> bool:
# TODO: Catch exceptions and return False if something goes wrong
data = call.model_dump_json(exclude_none=True)
- _logger.debug(f"Saving call {call.call_id}: {data}")
+ logger.debug(f"Saving call {call.call_id}: {data}")
async with self._use_db() as db:
await db.execute(
f"INSERT OR REPLACE INTO {self._config.table} VALUES (?, ?)",
@@ -75,7 +71,7 @@ class SqliteStore(IStore):
return True
async def call_asearch_one(self, phone_number: str) -> Optional[CallStateModel]:
- _logger.debug(f"Loading last call for {phone_number}")
+ logger.debug(f"Loading last call for {phone_number}")
call = None
async with self._use_db() as db:
cursor = await db.execute(
@@ -90,7 +86,7 @@ class SqliteStore(IStore):
try:
call = CallStateModel.model_validate_json(row[0])
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
return call
async def call_asearch_all(
@@ -98,7 +94,7 @@ class SqliteStore(IStore):
count: int,
phone_number: Optional[str] = None,
) -> tuple[Optional[list[CallStateModel]], int]:
- _logger.debug(f"Searching calls, for {phone_number} and count {count}")
+ logger.debug(f"Searching calls, for {phone_number} and count {count}")
calls, total = await asyncio.gather(
self._call_asearch_all_calls_worker(count, phone_number),
self._call_asearch_all_total_worker(phone_number),
@@ -136,7 +132,7 @@ class SqliteStore(IStore):
try:
calls.append(CallStateModel.model_validate_json(row[0]))
except ValidationError as e:
- _logger.debug(f"Parsing error: {e.errors()}")
+ logger.debug(f"Parsing error: {e.errors()}")
return calls
async def _call_asearch_all_total_worker(
@@ -169,7 +165,7 @@ class SqliteStore(IStore):
See: https://sqlite.org/cgi/src/doc/wal2/doc/wal2.md
"""
- _logger.info("First run, init database")
+ logger.info("First run, init database")
# Optimize performance for concurrent writes
await db.execute("PRAGMA journal_mode=WAL")
# Create table
diff --git a/persistence/twilio.py b/persistence/twilio.py
index adbed80..8264fcb 100644
--- a/persistence/twilio.py
+++ b/persistence/twilio.py
@@ -1,5 +1,5 @@
from helpers.config_models.sms import TwilioModel
-from helpers.logging import build_logger
+from helpers.logging import logger
from helpers.pydantic_types.phone_numbers import PhoneNumber
from models.readiness import ReadinessStatus
from persistence.isms import ISms
@@ -7,15 +7,12 @@ from twilio.base.exceptions import TwilioRestException
from twilio.rest import Client
-_logger = build_logger(__name__)
-
-
class TwilioSms(ISms):
_client: Client
_config: TwilioModel
def __init__(self, config: TwilioModel):
- _logger.info(f"Using Twilio from number {config.phone_number}")
+ logger.info(f"Using Twilio from number {config.phone_number}")
self._config = config
self._client = Client(
password=config.auth_token.get_secret_value(),
@@ -35,13 +32,13 @@ class TwilioSms(ISms):
assert balance.balance and float(balance.balance) > 0
return ReadinessStatus.OK
except AssertionError:
- _logger.error("Readiness test failed", exc_info=True)
+ logger.error("Readiness test failed", exc_info=True)
return ReadinessStatus.FAIL
async def asend(self, content: str, phone_number: PhoneNumber) -> bool:
- _logger.info(f"Sending SMS to {phone_number}")
+ logger.info(f"Sending SMS to {phone_number}")
success = False
- _logger.info(f"SMS content: {content}")
+ logger.info(f"SMS content: {content}")
try:
res = self._client.messages.create(
body=content,
@@ -50,14 +47,14 @@ class TwilioSms(ISms):
)
# TODO: How to check the delivery status? Seems present in "res.status" but not documented
if res.error_message:
- _logger.warning(
+ logger.warning(
f"Failed SMS to {phone_number}, status {res.error_code}, error {res.error_message}"
)
else:
- _logger.debug(f"SMS sent to {phone_number}")
+ logger.debug(f"SMS sent to {phone_number}")
success = True
except TwilioRestException as e:
- _logger.error(f"Error sending SMS: {e}")
+ logger.error(f"Error sending SMS: {e}")
except Exception:
- _logger.warning(f"Failed SMS to {phone_number}", exc_info=True)
+ logger.warning(f"Failed SMS to {phone_number}", exc_info=True)
return success
diff --git a/tests/conftest.py b/tests/conftest.py
index 68710b9..65420c1 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -2,7 +2,7 @@ from azure.identity import ManagedIdentityCredential, get_bearer_token_provider
from deepeval.models.gpt_model import GPTModel
from fastapi import BackgroundTasks
from helpers.config import CONFIG
-from helpers.logging import build_logger
+from helpers.logging import logger
from langchain_core.language_models import BaseChatModel
from langchain_openai import AzureChatOpenAI
from models.call import CallStateModel, CallInitiateModel
@@ -22,9 +22,6 @@ from azure.communication.callautomation import (
)
-_logger = build_logger(__name__)
-
-
class CallAutomationClientMock(CallAutomationClient):
_play_media_callback: Callable[[str], None]
@@ -50,7 +47,7 @@ class CallConnectionClientMock(CallConnectionClient):
*args,
**kwargs,
) -> None:
- _logger.info("start_recognizing_media, ignoring")
+ logger.info("start_recognizing_media, ignoring")
def play_media(
self,
@@ -65,21 +62,21 @@ class CallConnectionClientMock(CallConnectionClient):
if text.strip():
self._play_media_callback(text.strip())
else:
- _logger.warning("play_media, ignoring")
+ logger.warning("play_media, ignoring")
def transfer_call_to_participant(
self,
*args,
**kwargs,
) -> None:
- _logger.info("transfer_call_to_participant, ignoring")
+ logger.info("transfer_call_to_participant, ignoring")
def hang_up(
self,
*args,
**kwargs,
) -> None:
- _logger.info("hang_up, ignoring")
+ logger.info("hang_up, ignoring")
@pytest.fixture
diff --git a/tests/llm.py b/tests/llm.py
index 7699c9d..664d8c9 100644
--- a/tests/llm.py
+++ b/tests/llm.py
@@ -13,7 +13,7 @@ from helpers.call_events import (
on_call_connected,
)
from helpers.config import CONFIG
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.call import CallStateModel
from models.reminder import ReminderModel
from models.training import TrainingModel
@@ -24,9 +24,6 @@ import pytest
from tests.conftest import CallAutomationClientMock
-_logger = build_logger(__name__)
-
-
@pytest.mark.parametrize(
"lang, inputs, expected_output, claim_tests_incl, claim_tests_excl",
[
@@ -202,9 +199,9 @@ async def test_llm(
full_input = _remove_newlines(" ".join(inputs))
# Log for dev review
- _logger.info(f"actual_output: {actual_output}")
- _logger.info(f"claim: {call.claim}")
- _logger.info(f"full_input: {full_input}")
+ logger.info(f"actual_output: {actual_output}")
+ logger.info(f"claim: {call.claim}")
+ logger.info(f"full_input: {full_input}")
# Test claim data
for field in claim_tests_incl:
diff --git a/tests/search.py b/tests/search.py
index 617a21d..5ddce50 100644
--- a/tests/search.py
+++ b/tests/search.py
@@ -4,16 +4,13 @@ from deepeval.metrics.indicator import metric_progress_indicator
from deepeval.models.gpt_model import GPTModel
from deepeval.test_case import LLMTestCase
from helpers.config import CONFIG
-from helpers.logging import build_logger
+from helpers.logging import logger
from models.call import CallStateModel
from typing import Optional
import asyncio
import pytest
-_logger = build_logger(__name__)
-
-
class RagRelevancyMetric(BaseMetric):
model: GPTModel
score: Optional[float] = 0
@@ -150,8 +147,8 @@ async def test_relevancy(
res_models = await search.training_asearch_all(text=user_message, lang=user_lang)
res_list = [d.content for d in res_models or []]
- _logger.info(f"Message: {user_message}")
- _logger.info(f"Data: {res_list}")
+ logger.info(f"Message: {user_message}")
+ logger.info(f"Data: {res_list}")
# Configure LLM tests
test_case = LLMTestCase(