Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Addresses Issue #245 for better logging #332

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

patilvishal0597
Copy link

Added logger_util to enable package and class wide logging in langchain-aws. Added logging for invoke and ainvoke.

Added a logger util for configuration of logger. Tested logging of invoke, ainvoke, and converse request/responses

Behaviour:

LANGCHAIN_AWS_DEBUG = LANGCHAIN_AWS_DEBUG_ROOT = True --> Logs debug messages across boto3 and application

LANGCHAIN_AWS_DEBUG = True; LANGCHAIN_AWS_DEBUG_ROOT = True --> Logs only applcation debug messages

LANGCHAIN_AWS_DEBUG = False; LANGCHAIN_AWS_DEBUG_ROOT = True --> Logs only application info messages

LANGCHAIN_AWS_DEBUG = LANGCHAIN_AWS_DEBUG_ROOT = False --> Logs only application info messages

Invoke call:

llm = ChatBedrock(
        model_id="us.anthropic.claude-3-5-sonnet-20241022-v2:0",
        region_name="us-east-1",
        model_kwargs={
            "max_tokens": 100,
            "top_p": 0.9,
            "temperature": 0.1,
        },
    )

# input to llm
messages = [
        (
            "system",
            "You are a helpful assistant that translates English to French. Translate the user sentence.",
        ),
        ("human", "I love going out for a walk when the weather is bright and sunny."),
    ]

# Invoke the llm
response = llm.invoke(messages)

Logging output:

Debug logs with LANGCHAIN_AWS_DEBUG and LANGCHAIN_AWS_DEBUG_ROOT env vars as True

...
...
....
2025-01-15 14:30:31 DEBUG | [connectionpool.py:1051] | urllib3.connectionpool - Starting new HTTPS connection (1): bedrock-runtime.us-east-1.amazonaws.com:443
2025-01-15 14:30:33 DEBUG | [connectionpool.py:546] | urllib3.connectionpool - https://bedrock-runtime.us-east-1.amazonaws.com:443 "POST /model/us.anthropic.claude-3-5-sonnet-20241022-v2%3A0/invoke HTTP/11" 200 299
2025-01-15 14:30:33 DEBUG | [parsers.py:241] | botocore.parsers - Response headers: {'Date': 'Wed, 15 Jan 2025 22:30:33 GMT', 'Content-Type': 'application/json', 'Content-Length': '299', 'Connection': 'keep-alive', 'x-amzn-RequestId': 'xxxxxx', 'X-Amzn-Bedrock-Invocation-Latency': '1077', 'X-Amzn-Bedrock-Output-Token-Count': '22', 'X-Amzn-Bedrock-Input-Token-Count': '40'}
2025-01-15 14:30:33 DEBUG | [parsers.py:242] | botocore.parsers - Response body:
<botocore.response.StreamingBody object at 0x108e595d0>
2025-01-15 14:30:33 DEBUG | [hooks.py:238] | botocore.hooks - Event needs-retry.bedrock-runtime.InvokeModel: calling handler <botocore.retryhandler.RetryHandler object at 0x108e58c80>
2025-01-15 14:30:33 DEBUG | [retryhandler.py:211] | botocore.retryhandler - No retry needed.
2025-01-15 14:30:33 INFO | [bedrock.py:603] | root - The output message sent by user: content="J'aime me promener quand il fait beau et ensoleillé." additional_kwargs={'usage': {'prompt_tokens': 40, 'completion_tokens': 22, 'total_tokens': 62}, 'stop_reason': 'end_turn', 'model_id': 'us.anthropic.claude-3-5-sonnet-20241022-v2:0'} response_metadata={} usage_metadata={'input_tokens': 40, 'output_tokens': 22, 'total_tokens': 62}
J'aime me promener quand il fait beau et ensoleillé.
(base) vishankp@7cf34de71c79 aws % 

Logging output when LANGCHAIN_AWS_DEBUG and LANGCHAIN_AWS_DEBUG_ROOT flags are False and logger is initialized with a module_name:

2025-01-15 14:39:40 INFO | langchain_aws.chat_models.bedrock - The input message sent by user: [SystemMessage(content='You are a helpful assistant that translates English to French. Translate the user sentence.', additional_kwargs={}, response_metadata={}), HumanMessage(content='I love going out for a walk when the weather is bright and sunny.', additional_kwargs={}, response_metadata={})]
2025-01-15 14:39:40 ERROR | langchain_aws.chat_models.bedrock - Testing error log
2025-01-15 14:39:41 INFO | langchain_aws.chat_models.bedrock - The output message sent by user: content="J'aime me promener quand il fait beau et ensoleillé." additional_kwargs={'usage': {'prompt_tokens': 40, 'completion_tokens': 22, 'total_tokens': 62}, 'stop_reason': 'end_turn', 'model_id': 'us.anthropic.claude-3-5-sonnet-20241022-v2:0'} response_metadata={} usage_metadata={'input_tokens': 40, 'output_tokens': 22, 'total_tokens': 62}
J'aime me promener quand il fait beau et ensoleillé.

Copy link
Collaborator

@michaelnchin michaelnchin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @patilvishal0597, looks good overall. Added a few minor comments.

import os

# Environment variable to set the application logger(s) in debug mode during runtime
__DEBUG = True if os.environ.get("LANGCHAIN_AWS_DEBUG") else False
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

os.environ.get() returns a string - this line will set __DEBUG to True in any case where LANGCHAIN_AWS_DEBUG has been defined. So we might see unexpected behavior if the user sets something like LANGCHAIN_AWS_DEBUG=false.

An explicit string comparison like this would work better:

__DEBUG = os.getenv("LANGCHAIN_AWS_DEBUG", "").lower() in ["true", "1"]

# Flag for root debug logger to set the root debug logger in debug mode during runtime
# Root debug logger will print boto3 as well as application debug logs if set to true
# This flag will be set to true if LANGCHAIN_AWS_DEBUG = LANGCHAIN_AWS_DEBUG_ROOT = true
__ROOT_DEBUG = __DEBUG if os.environ.get("LANGCHAIN_AWS_DEBUG_ROOT") else False
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as for __DEBUG on Line 5.

Comment on lines 13 to 17
# else ERROR
if __DEBUG:
DEFAULT_LOG_LEVEL: int = logging.DEBUG
else:
DEFAULT_LOG_LEVEL: int = logging.INFO
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment says ERROR, but conditional uses INFO level.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changing the default log level to "ERROR"

Comment on lines 21 to 22
DEFAULT_LOG_FILE = os.environ.get("LANGCHAIN_AWS_LOG_OUTPUT", "-")
if DEFAULT_LOG_FILE == "-":
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a reason for overriding with - here? Can we use the os.environ.get() default value so that the conditional doesn't need to check for an explicit value?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added - as a default value in case the DEFAULT_LOG_FILE value isn't set. Do we want to have a default value as None to make this cleaner?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's unnecessary to set None explicitly - os.environ.get already returns None by default if the variable doesn't exist.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in the new commit


# Environment variable to set the application logger(s) in debug mode during runtime
LANGCHAIN_AWS_DEBUG: str = os.environ.get("LANGCHAIN_AWS_DEBUG", "false")
__DEBUG: bool = True if LANGCHAIN_AWS_DEBUG.lower() in ["true", "1"] else False
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: simplify to

__DEBUG: bool = LANGCHAIN_AWS_DEBUG.lower() in ["true", "1"]

Comment on lines 55 to 56
except ImportError:
colorama = None
coloredlogs = None

DEFAULT_LOG_FORMATTER: logging.Formatter = logging.Formatter(DEFAULT_LOG_FORMAT)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO we shouldn't fail this silently - add an logger statement in case users are interested in enabling coloring

@patilvishal0597 patilvishal0597 force-pushed the issue-245-better-logging branch from c3768d5 to 694f93f Compare January 24, 2025 22:43
Copy link
Collaborator

@michaelnchin michaelnchin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM - thanks @patilvishal0597 !

Added `logger_util` to enable package and class wide logging in `langchain-aws`.
Added logging for `invoke` and `ainvoke`.

langchain-ai#245
@patilvishal0597 patilvishal0597 force-pushed the issue-245-better-logging branch from 4c98e33 to 9c2432e Compare January 24, 2025 23:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants