|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import warnings |
| 4 | + |
| 5 | +from rich.logging import RichHandler |
| 6 | + |
| 7 | + |
| 8 | +def _rich_handler() -> RichHandler: |
| 9 | + formatter = logging.Formatter("%(name)s - %(message)s") |
| 10 | + handler = RichHandler() |
| 11 | + handler.setFormatter(formatter) |
| 12 | + return handler |
| 13 | + |
| 14 | + |
| 15 | +logger = logging.getLogger("chatlas") |
| 16 | + |
| 17 | +if os.environ.get("CHATLAS_LOG") == "info": |
| 18 | + # By adding a RichHandler to chatlas' logger, we can guarantee that they |
| 19 | + # never get dropped, even if the root logger's handlers are not |
| 20 | + # RichHandlers. |
| 21 | + logger.setLevel(logging.INFO) |
| 22 | + logger.addHandler(_rich_handler()) |
| 23 | + logger.propagate = False |
| 24 | + |
| 25 | + # Add a RichHandler to the root logger if there are no handlers. Note that |
| 26 | + # if chatlas is imported before other libraries that set up logging, (like |
| 27 | + # openai, anthropic, or httpx), this will ensure that logs from those |
| 28 | + # libraries are also displayed in the rich console. |
| 29 | + root = logging.getLogger() |
| 30 | + if not root.handlers: |
| 31 | + root.addHandler(_rich_handler()) |
| 32 | + |
| 33 | + # Warn if there are non-RichHandler handlers on the root logger. |
| 34 | + # TODO: we could consider something a bit more abusive here, like removing |
| 35 | + # non-RichHandler handlers from the root logger, but that could be |
| 36 | + # surprising to users. |
| 37 | + bad_handlers = [ |
| 38 | + h.get_name() for h in root.handlers if not isinstance(h, RichHandler) |
| 39 | + ] |
| 40 | + if len(bad_handlers) > 0: |
| 41 | + warnings.warn( |
| 42 | + "When setting up logging handlers for CHATLAS_LOG, chatlas detected " |
| 43 | + f"non-rich handler(s) on the root logger named {bad_handlers}. " |
| 44 | + "As a result, logs handled those handlers may be dropped when the " |
| 45 | + "`echo` argument of `.chat()`, `.stream()`, etc., is something " |
| 46 | + "other than 'none'. This problem can likely be fixed by importing " |
| 47 | + "`chatlas` before other libraries that set up logging, or adding a " |
| 48 | + "RichHandler to the root logger before loading other libraries.", |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +def log_model_default(model: str) -> str: |
| 53 | + logger.info(f"Defaulting to `model = '{model}'`.") |
| 54 | + return model |
| 55 | + |
| 56 | + |
| 57 | +def log_tool_error(name: str, arguments: str, e: Exception): |
| 58 | + logger.info( |
| 59 | + f"Error invoking tool function '{name}' with arguments: {arguments}. " |
| 60 | + f"The error message is: '{e}'", |
| 61 | + ) |
0 commit comments