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

feat: logging status code and error on the sdk #26

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

DanielAthina
Copy link

@DanielAthina DanielAthina commented Sep 18, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced logging capabilities with additional metadata for status codes and errors in various logging functions.
    • Introduced a centralized error logging method to streamline error handling during API interactions.
  • Bug Fixes

    • Improved error handling in the OpenAI API wrapper to ensure consistent logging of exceptions and response times.
  • Chores

    • Updated logging functions to provide more detailed insights into API responses and errors for better debugging.

Copy link

coderabbitai bot commented Sep 18, 2024

Walkthrough

The pull request introduces enhancements to the logging and error handling capabilities across several modules in the athina_logger package. Key changes include the addition of status_code and error attributes in the AthinaMeta class, modifications to logging functions to incorporate these new parameters, and improved error handling in API interactions. The changes aim to provide more detailed insights into the operational status and errors encountered during inference and API calls.

Changes

Files Change Summary
athina_logger/athina_meta.py Added status_code: Optional[int] and error: Optional[Any] attributes to AthinaMeta class.
athina_logger/inference_logger.py Modified log_inference and _log_inference_asynchronously functions to include status_code and error parameters; added _serialize_error method for error handling.
athina_logger/openai_wrapper.py Enhanced log_to_athina function to log status_code and error; added error handling in API call with a new _log_exception_to_athina method.
athina_logger/request_helper.py Updated make_post_request function to log API responses and return None on errors instead of raising exceptions, altering error handling behavior.

Poem

In the land of logs where errors play,
A rabbit hops with joy today! 🐇
With status codes and errors bright,
Our logging's now a wondrous sight.
Hooray for changes, let them ring,
In Athina's realm, we dance and sing! 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai generate interesting stats about this repository and render them as a table.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9ebb7b1 and 6264cde.

Files selected for processing (4)
  • athina_logger/athina_meta.py (2 hunks)
  • athina_logger/inference_logger.py (3 hunks)
  • athina_logger/openai_wrapper.py (5 hunks)
  • athina_logger/request_helper.py (1 hunks)
Additional context used
Ruff
athina_logger/request_helper.py

26-26: Local variable error_message is assigned to but never used

Remove assignment to unused variable error_message

(F841)


27-27: Local variable details_message is assigned to but never used

Remove assignment to unused variable details_message

(F841)

athina_logger/inference_logger.py

45-46: SyntaxError: Expected an indented block after except clause

Additional comments not posted (15)
athina_logger/athina_meta.py (2)

17-17: LGTM!

The addition of the custom_eval_metrics attribute with the correct type hint looks good.


18-18: LGTM!

The addition of the status_code attribute with the correct type hint looks good.

athina_logger/request_helper.py (2)

20-23: LGTM!

The added print statements improve logging capabilities by providing visibility into the response data from the OpenAI API. This can be helpful for debugging purposes.


32-33: Verify the impact of the change in error handling behavior.

The change in error handling for requests.exceptions.RequestException alters the control flow and how errors are communicated to the caller. Returning None instead of raising the exception could lead to unexpected behavior in the calling code if it is not updated to handle the new behavior.

Consider reverting the change to maintain the expected behavior of raising the exception:

         except requests.exceptions.RequestException as e:
-            print(f"Request exception: {e}")
-            return None
+            raise e

Alternatively, ensure that the calling code is updated to handle the new behavior of returning None in case of a requests.exceptions.RequestException.

To verify the impact of this change, run the following script:

athina_logger/inference_logger.py (6)

39-40: LGTM!

The addition of status_code and error parameters to the log_inference function aligns with the PR objective and allows capturing more details about the inference request. The parameter types are correctly annotated.


43-43: LGTM!

The args tuple is correctly updated to include the new status_code and error parameters, which are then passed to the _log_inference_asynchronously method.


49-49: LGTM!

The _log_inference_asynchronously method signature is correctly updated to include the new status_code and error parameters, which are then used in the method body to include additional details in the payload.


79-80: LGTM!

The payload dictionary is correctly updated to include the new status_code and a serialized version of the error using the newly added _serialize_error method. This allows for more detailed logging of inference events, capturing the status code and any associated error information.


84-91: LGTM!

The inclusion of traceback.print_exc() in the error handling of the _log_inference_asynchronously method provides more detailed error output in case of failures during the logging operation. This change enhances the debugging experience by providing more context about the errors.


93-117: LGTM!

The new _serialize_error method handles various types of error inputs, including dictionaries, strings, and exceptions, to extract and format the error message appropriately. It provides a consistent way to serialize errors for logging.

The method correctly handles different scenarios:

  • For dictionary inputs, it attempts to extract the inner error message by parsing the string as a dictionary.
  • For string and exception inputs, it returns the error message as is.

This change enhances the error handling in the logging process and ensures that the error information is captured in a standardized format.

athina_logger/openai_wrapper.py (5)

Line range hint 33-56: LGTM!

The changes to include status_code and error in the logging payload are implemented correctly. This ensures that error details are consistently captured and logged to Athina.


100-106: LGTM!

The exception handling and error logging in the wrapper method are implemented correctly. This ensures that any exceptions during the OpenAI API call are captured and logged to Athina before re-raising the exception.


138-145: LGTM!

The exception handling and error logging in the _response_interceptor method for streaming responses are implemented correctly. This ensures that any exceptions during the processing of streaming responses are captured and logged to Athina before re-raising the exception.


149-162: LGTM!

The exception handling and error logging in the _response_interceptor method for non-streaming responses are implemented correctly. This ensures that any exceptions during the logging of non-streaming responses are captured and logged to Athina before re-raising the exception.


163-190: LGTM!

The _log_exception_to_athina method is implemented correctly. It centralizes the error logging logic and ensures consistent error reporting to Athina. The method constructs an error dictionary, updates the athina_meta object with the error details, and logs the error using the log_to_athina function.

custom_eval_metrics: Optional[Dict] = None
status_code: Optional[int] = None
error: Optional[Any] = None,
Copy link

Choose a reason for hiding this comment

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

Consider using a more specific type hint for the error attribute.

Using Any as the type hint for the error attribute is very broad and could lead to inconsistencies in the stored error data. This could make it difficult to handle and process the stored error data consistently.

Consider using a more specific type hint, such as a custom Error class or a Union of specific error types, to ensure consistency in the stored error data.

Comment on lines 26 to +30
error_message = response_json.get('error', 'Unknown Error')
details_message = response_json.get(
'details', {}).get('message', 'No Details')
raise CustomException(
response.status_code, f'{error_message}: {details_message}')
response.status_code, f'{response_json}')
Copy link

Choose a reason for hiding this comment

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

Fix the error handling behavior and remove unused variables.

The changes in this code segment have the following issues:

  • The expected behavior of raising a CustomException with a detailed error message has been changed to include the entire response JSON. This could affect how the calling code handles failures.
  • The local variables error_message and details_message are assigned but never used due to the changes in error handling.

Consider applying the following fixes:

-                error_message = response_json.get('error', 'Unknown Error')
-                details_message = response_json.get(
-                    'details', {}).get('message', 'No Details')
                 raise CustomException(
                     response.status_code, f'{response_json}')

If the new error handling behavior is intended, ensure that the calling code is updated to handle the change. Otherwise, consider reverting the change to maintain the expected behavior of raising a CustomException with a detailed error message:

                 error_message = response_json.get('error', 'Unknown Error')
                 details_message = response_json.get(
                     'details', {}).get('message', 'No Details')
-                raise CustomException(
-                    response.status_code, f'{response_json}')
+                raise CustomException(
+                    response.status_code, f'{error_message}: {details_message}')
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
error_message = response_json.get('error', 'Unknown Error')
details_message = response_json.get(
'details', {}).get('message', 'No Details')
raise CustomException(
response.status_code, f'{error_message}: {details_message}')
response.status_code, f'{response_json}')
raise CustomException(
response.status_code, f'{response_json}')
Tools
Ruff

26-26: Local variable error_message is assigned to but never used

Remove assignment to unused variable error_message

(F841)


27-27: Local variable details_message is assigned to but never used

Remove assignment to unused variable details_message

(F841)

Comment on lines +35 to +36
print(f"Unexpected error: {e}")
return None
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Potential issues identified with the error handling change

The change in error handling for make_post_request function could lead to unexpected behavior in some parts of the codebase. Here are the specific concerns:

  1. In athina_logger/log_stream_inference/openai_chat_completion_stream.py and athina_logger/log_stream_inference/openai_completion_stream.py, exceptions are currently re-raised. Returning None instead of raising an exception could lead to a TypeError if the code assumes a response object.

  2. In athina_logger/tracing/trace.py, the make_post_request function is called without a try-except block. Returning None could lead to unexpected behavior if the code assumes a response object.

To address these issues:

  • Consider reverting the change in make_post_request to maintain the expected behavior of raising exceptions.
  • If keeping the new behavior, update the calling code in the mentioned files to handle the possibility of receiving None as a return value.
Analysis chain

Verify the impact of the change in error handling behavior.

Similar to the previous comment, the change in error handling for unexpected exceptions alters the control flow and how errors are communicated to the caller. Returning None instead of raising the exception could lead to unexpected behavior in the calling code if it is not updated to handle the new behavior.

Consider reverting the change to maintain the expected behavior of raising the exception:

         except Exception as e:
-            print(f"Unexpected error: {e}")
-            return None
+            raise e

Alternatively, ensure that the calling code is updated to handle the new behavior of returning None in case of an unexpected exception.

To verify the impact of this change, run the following script:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the `make_post_request` function.

# Test: Search for the function usage. Expect: Calling code handles the new behavior of returning `None`.
rg --type python -A 5 $'make_post_request'

Length of output: 72


Script:

#!/bin/bash
# Description: Find Python files and search for make_post_request function usage

# Find all Python files
python_files=$(fd -e py)

# Search for make_post_request in Python files
for file in $python_files; do
    echo "Searching in $file:"
    grep -n "make_post_request" "$file" -A 5
    echo "---"
done

Length of output: 8357

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