Skip to content

Content tag ids zendesk#7

Open
ajabhish wants to merge 4 commits intomainfrom
content-tag-ids-zendesk
Open

Content tag ids zendesk#7
ajabhish wants to merge 4 commits intomainfrom
content-tag-ids-zendesk

Conversation

@ajabhish
Copy link
Copy Markdown
Owner

@ajabhish ajabhish commented Aug 20, 2024

User description

Description

[Provide a brief description of the changes in this PR]

How Has This Been Tested?

[Describe the tests you ran to verify your changes]

Accepted Risk

[Any know risks or failure modes to point out to reviewers]

Related Issue(s)

[If applicable, link to the issue(s) this PR addresses]

Checklist:

  • All of the automated tests pass
  • All PR comments are addressed and marked resolved
  • If there are migrations, they have been rebased to latest main
  • If there are new dependencies, they are added to the requirements
  • If there are new environment variables, they are added to all of the deployment methods
  • If there are new APIs that don't require auth, they are added to PUBLIC_ENDPOINT_SPECS
  • Docker images build and basic functionalities work
  • Author has done a final read through of the PR right before merge

PR Type

enhancement, bug fix


Description

  • Enhanced the Zendesk connector to fetch and store content tags, improving the metadata associated with documents.
  • Implemented retries and pagination for the content tag fetching process to ensure robustness.
  • Updated the _article_to_document function to include content tags in the document metadata.
  • Added a main block for testing the connector, allowing for easier local testing and debugging.

Changes walkthrough 📝

Relevant files
Enhancement
connector.py
Enhance Zendesk connector with content tags and retries   

backend/danswer/connectors/zendesk/connector.py

  • Added functionality to fetch and store content tags from Zendesk.
  • Integrated retries and pagination for fetching content tags.
  • Updated document metadata to include content tags.
  • Added a main block for testing the connector.
  • +79/-4   

    💡 PR-Agent usage:
    Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    Greptile Summary

    This PR enhances the Zendesk connector by adding support for content tags, improving metadata collection for Zendesk articles.

    • Added _set_content_tags method in ZendeskConnector class to fetch and store content tags from Zendesk API
    • Updated _article_to_document function to include content tags in document metadata
    • Implemented retry mechanism for content tag fetching using @retry decorator
    • Added pagination handling for content tag retrieval to support large datasets
    • Included a main block for testing the connector with environment variables

    Summary by CodeRabbit

    • New Features

      • Enhanced ZendeskConnector to include content tags in document metadata, improving data richness.
      • Added a mechanism to fetch and handle content tags from the Zendesk API, ensuring robustness with error handling and retries.
    • Usability Improvements

      • Updated the main execution block to provide clear usage examples for new users.

    @qodo-code-review qodo-code-review Bot added enhancement New feature or request bug fix labels Aug 20, 2024
    @archie-ai-code-explain-pr-review
    Copy link
    Copy Markdown

    PR Review Summary 🔍

    This PR enhances the ZendeskConnector by adding support for content tags, implementing pagination for fetching tags, and introducing retry logic. The changes appear to improve the connector's functionality and robustness. However, there are some potential security and error handling concerns that should be addressed before merging.

    Logical error analysis

    • The _set_content_tags method doesn't handle rate limiting. Consider implementing exponential backoff or respecting Zendesk's rate limits.
    • In _article_to_document, the content_tags dictionary is accessed without checking if it's populated, potentially causing KeyErrors.
    • The main block at the end of the file uses hardcoded environment variables, which may not be present in all environments.

    🧪 Test coverage analysis

    • No new tests have been added for the content tag functionality. Consider adding unit tests for _set_content_tags and _article_to_document.
    • The main block at the end of the file suggests manual testing. Automated integration tests would be more reliable.

    🔒 Security analysis

    • The _set_content_tags method uses plain HTTP authentication. Consider using a more secure authentication method or at least ensure HTTPS is enforced.
    • Sensitive information (email, token) is potentially exposed in error messages. Avoid logging these details in production.

    @coderabbitai
    Copy link
    Copy Markdown

    coderabbitai Bot commented Aug 20, 2024

    Walkthrough

    The recent updates to the ZendeskConnector class enhance its functionality by adding support for content tags in document metadata. A new method retrieves these tags from the Zendesk API, improving the richness of the processed data. Additionally, the connector's usability is boosted with a clear example of instantiation and document polling, streamlining the workflow for users.

    Changes

    Files Change Summary
    backend/danswer/connectors/zendesk/connector.py - Modified _article_to_document to accept content_tags parameter for enriched metadata.
    - Added _set_content_tags method for fetching content tags with error handling.
    - Introduced content_tags attribute to store tags.
    - Updated load_credentials to set up content tags post-initialization.
    - Improved main execution block for clearer usage example.

    Poem

    🐇 In the meadow, changes bloom,
    New tags added, dispel the gloom.
    Metadata rich, documents shine,
    Zendesk’s secrets, now align.
    Hop, skip, and jump, all is right,
    A connector’s magic, pure delight! ✨


    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>.
      • 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 show all the console.log statements in this repository.
      • @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 as 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.

    Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

    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.

    @qodo-code-review
    Copy link
    Copy Markdown

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 Security concerns

    Sensitive information exposure:
    The main block at the end of the file (lines 159-176) reads sensitive information (ZENDESK_SUBDOMAIN, ZENDESK_EMAIL, ZENDESK_TOKEN) directly from environment variables. While this is likely for testing purposes, it's important to ensure that this code is not accidentally left in production builds, as it could potentially expose sensitive information if not properly handled.

    ⚡ Key issues to review

    Error Handling
    The error handling in the _set_content_tags method could be improved. Currently, it only prints the error message, which may not be sufficient for proper debugging or logging in a production environment.

    Code Duplication
    The authentication credentials (subdomain, email, token) are passed multiple times in different methods. Consider refactoring to store these as instance variables to reduce duplication and improve maintainability.

    @qodo-code-review
    Copy link
    Copy Markdown

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Best practice
    Use a proper logging mechanism instead of print statements for error reporting

    Instead of using print for error logging, consider using a proper logging mechanism.
    This would provide more control over log levels and output destinations.

    backend/danswer/connectors/zendesk/connector.py [100]

    -print(f"Error fetching content tags: {str(e)}")
    +import logging
    +logging.error(f"Error fetching content tags: {str(e)}")
     
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: Replacing print with a logging mechanism is a best practice that enhances the flexibility and control over error reporting, allowing for better management of log levels and output destinations.

    9
    Use a more specific exception type for better error handling

    Consider using a more specific exception type instead of the generic Exception in
    the error handling of the _set_content_tags method. This would allow for more
    precise error handling and debugging.

    backend/danswer/connectors/zendesk/connector.py [99-100]

    -except Exception as e:
    +except requests.RequestException as e:
         print(f"Error fetching content tags: {str(e)}")
     
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Using a more specific exception type like requests.RequestException improves error handling by targeting network-related errors specifically, which is more appropriate for the context of making HTTP requests.

    8
    Maintainability
    Refactor pagination handling into a separate method for improved modularity and readability

    The _set_content_tags method could benefit from pagination handling in a separate
    method. This would improve readability and make the code more modular.

    backend/danswer/connectors/zendesk/connector.py [81-98]

    +def _fetch_page(self, base_url, auth, params):
    +    response = requests.get(base_url, auth=auth, params=params)
    +    if response.status_code != 200:
    +        raise requests.HTTPError(f"Error: {response.status_code}\n{response.text}")
    +    return response.json()
    +
     while True:
    -    # Make the GET request
    -    response = requests.get(base_url, auth=auth, params=params)
    +    data = self._fetch_page(base_url, auth, params)
    +    content_tag_list = data.get("records", [])
    +    for tag in content_tag_list:
    +        self.content_tags[tag["id"]] = tag["name"]
     
    -    # Check if the request was successful
    -    if response.status_code == 200:
    -        data = response.json()
    -        content_tag_list = data.get("records", [])
    -        for tag in content_tag_list:
    -            self.content_tags[tag["id"]] = tag["name"]
    +    if not data.get("meta", {}).get("has_more", False):
    +        break
    +    params["page[after]"] = data["meta"]["after_cursor"]
     
    -        # Check if there are more pages
    -        if data.get("meta", {}).get("has_more", False):
    -            params["page[after]"] = data["meta"]["after_cursor"]
    -        else:
    -            break
    -    else:
    -        raise Exception(f"Error: {response.status_code}\n{response.text}")
    -
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Extracting pagination handling into a separate method improves code modularity and readability, making the _set_content_tags method cleaner and easier to maintain.

    7
    Enhancement
    Simplify metadata creation using a dictionary comprehension

    The _article_to_document function could be simplified by using a dictionary
    comprehension for the metadata creation. This would make the code more concise and
    potentially more efficient.

    backend/danswer/connectors/zendesk/connector.py [30-41]

    -# build metadata
    -metadata: dict[str, str | list[str]] = {
    -    "labels": [str(label) for label in article.label_names if label],
    -    "content_tags": [
    -        content_tags[tag_id]
    -        for tag_id in article.content_tag_ids
    -        if tag_id in content_tags
    -    ],
    +metadata = {
    +    k: v for k, v in {
    +        "labels": [str(label) for label in article.label_names if label],
    +        "content_tags": [content_tags[tag_id] for tag_id in article.content_tag_ids if tag_id in content_tags],
    +    }.items() if v
     }
     
    -# remove empty values
    -metadata = {k: v for k, v in metadata.items() if v}
    -
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Using a dictionary comprehension to create metadata makes the code more concise and potentially more efficient, although the improvement is minor.

    6

    Copy link
    Copy Markdown

    @greptile-apps greptile-apps Bot left a comment

    Choose a reason for hiding this comment

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

    LGTM

    1 file(s) reviewed, no comment(s)
    Edit PR Review Bot Settings

    Copy link
    Copy Markdown

    @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: 0

    Outside diff range, codebase verification and nitpick comments (2)
    backend/danswer/connectors/zendesk/connector.py (2)

    67-100: Use a logging framework for error messages.

    The _set_content_tags method uses a print statement for error logging. Consider using a logging framework to provide more control over logging levels and outputs.

    Replace the print statement with a logging call:

    - print(f"Error fetching content tags: {str(e)}")
    + import logging
    + logger = logging.getLogger(__name__)
    + logger.error(f"Error fetching content tags: {str(e)}")

    159-176: Add exception handling to the main block.

    The main block demonstrates the usage of ZendeskConnector. Consider adding exception handling to manage potential errors during execution.

    Add a try-except block around the main execution:

    try:
        connector = ZendeskConnector()
        connector.load_credentials(
            {
                "zendesk_subdomain": os.environ["ZENDESK_SUBDOMAIN"],
                "zendesk_email": os.environ["ZENDESK_EMAIL"],
                "zendesk_token": os.environ["ZENDESK_TOKEN"],
            }
        )
        current = time.time()
        one_day_ago = current - 24 * 60 * 60  # 1 day
        document_batches = connector.poll_source(one_day_ago, current)
        print(next(document_batches))
    except Exception as e:
        print(f"An error occurred: {e}")
    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

    Files that changed from the base of the PR and between a54ea9f and 334ed14.

    Files selected for processing (1)
    • backend/danswer/connectors/zendesk/connector.py (6 hunks)
    Additional comments not posted (2)
    backend/danswer/connectors/zendesk/connector.py (2)

    65-66: Verify correct usage of content_tags.

    The content_tags attribute is a new addition to the ZendeskConnector class. Ensure that it is correctly populated and used throughout the class.

    Run the following script to verify the usage of content_tags:

    Verification successful

    content_tags is correctly integrated and used in ZendeskConnector.

    The content_tags attribute is correctly initialized, populated, and utilized within the ZendeskConnector class. It is used to map content tag IDs to their names and is passed to the _article_to_document function, ensuring that articles are processed with the correct tags.

    • content_tags is initialized as an empty dictionary.
    • Populated in the _set_content_tags method by fetching data from the Zendesk API.
    • Used in the _article_to_document function to convert articles to documents with their associated tags.

    This confirms that the implementation of content_tags is consistent and correct.

    Scripts executed

    The following scripts were executed for the analysis:

    Script:

    #!/bin/bash
    # Description: Verify correct usage of `content_tags` in `ZendeskConnector`.
    
    # Test: Search for all occurrences of `content_tags` to ensure correct usage.
    rg --type python 'content_tags'
    

    Length of output: 62


    Script:

    #!/bin/bash
    # Description: Verify correct usage of `content_tags` in `ZendeskConnector`.
    
    # Test: Search for all occurrences of `content_tags` in Python files.
    rg 'content_tags' --glob '*.py' -A 3
    

    Length of output: 2952


    24-38: Verify handling of missing content tags.

    The function now includes content_tags in the metadata. Ensure that the logic handles cases where content_tags might be empty or missing specific tags.

    Run the following script to check for handling of missing content tags:

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    2 participants