Skip to content

Commit

Permalink
Switch print statements to use logger (Azure-Samples#640)
Browse files Browse the repository at this point in the history
* Switch print statements to use logger

Required by Azure-Samples#637

* Fix log format
  • Loading branch information
adamdougal authored Apr 9, 2024
1 parent ba2a2ec commit 7f1a917
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 9 deletions.
4 changes: 3 additions & 1 deletion code/backend/batch/utilities/helpers/ConfigHelper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import logging
from .AzureBlobStorageHelper import AzureBlobStorageClient
from ..document_chunking.Strategies import ChunkingSettings, ChunkingStrategy
from ..document_loading import LoadingSettings, LoadingStrategy
Expand All @@ -10,6 +11,7 @@
from .EnvHelper import EnvHelper

CONFIG_CONTAINER_NAME = "config"
logger = logging.getLogger(__name__)


class Config:
Expand Down Expand Up @@ -81,7 +83,7 @@ def get_active_config_or_default():
config_file = blob_client.download_file("active.json")
config = Config(json.loads(config_file))
except Exception:
print("Returning default config")
logger.info("Returning default config")

return config

Expand Down
6 changes: 4 additions & 2 deletions code/backend/batch/utilities/orchestrator/OrchestratorBase.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
# Create an abstract class for orchestrator
import logging
from uuid import uuid4
from typing import List, Optional
from abc import ABC, abstractmethod
from ..loggers.TokenLogger import TokenLogger
from ..loggers.ConversationLogger import ConversationLogger
from ..helpers.ConfigHelper import ConfigHelper

logger = logging.getLogger(__name__)


class OrchestratorBase(ABC):
def __init__(self) -> None:
super().__init__()
self.config = ConfigHelper.get_active_config_or_default()
self.message_id = str(uuid4())
self.tokens = {"prompt": 0, "completion": 0, "total": 0}
print(f"New message id: {self.message_id} with tokens {self.tokens}")
logger.debug(f"New message id: {self.message_id} with tokens {self.tokens}")
self.token_logger: TokenLogger = TokenLogger()
self.conversation_logger: ConversationLogger = ConversationLogger()

Expand Down
2 changes: 1 addition & 1 deletion code/backend/batch/utilities/parser/OutputParserTool.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def parse(
continue

doc = source_documents[idx]
print(f"doc{idx}", doc)
logger.debug(f"doc{idx}: {doc}")

# Then update the citation object in the response, it needs to have filepath and chunk_id to render in the UI as a file
messages[0]["content"]["citations"].append(
Expand Down
11 changes: 7 additions & 4 deletions code/backend/batch/utilities/tools/ContentSafetyChecker.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from azure.ai.contentsafety import ContentSafetyClient
from azure.core.credentials import AzureKeyCredential
from azure.identity import DefaultAzureCredential
Expand All @@ -7,6 +8,8 @@
from .AnswerProcessingBase import AnswerProcessingBase
from ..common.Answer import Answer

logger = logging.getLogger(__name__)


class ContentSafetyChecker(AnswerProcessingBase):
def __init__(self):
Expand Down Expand Up @@ -47,12 +50,12 @@ def _filter_text_and_replace(self, text, response_template):
try:
response = self.content_safety_client.analyze_text(request)
except HttpResponseError as e:
print("Analyze text failed.")
if e.error:
print(f"Error code: {e.error.code}")
print(f"Error message: {e.error.message}")
logger.error(
f"Analyze text failed. Error code: {e.error.code}. Error message: {e.error.message}."
)
raise
print(e)
logger.exception("Analyze text failed.")
raise

filtered_text = text
Expand Down
5 changes: 4 additions & 1 deletion code/backend/batch/utilities/tools/QuestionAnswerTool.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from typing import List
from .AnsweringToolBase import AnsweringToolBase

Expand All @@ -11,6 +12,8 @@
from ..common.Answer import Answer
from ..common.SourceDocument import SourceDocument

logger = logging.getLogger(__name__)


class QuestionAnswerTool(AnsweringToolBase):
def __init__(self) -> None:
Expand Down Expand Up @@ -44,7 +47,7 @@ def answer_question(self, question: str, chat_history: List[dict], **kwargs: dic
result = answer_generator({"question": question, "sources": sources_text})

answer = result["text"]
print(f"Answer: {answer}")
logger.debug(f"Answer: {answer}")

# Generate Answer Object
source_documents = []
Expand Down

0 comments on commit 7f1a917

Please sign in to comment.