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

google[minor]: Move Vertex embeddings to integration package #6

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

Conversation

korbit-ai[bot]
Copy link

@korbit-ai korbit-ai bot commented Aug 15, 2024

User description

Will need to break this up into different PRs to make it pass CI

CC @afirstenberg

Description by Korbit AI

Note

This feature is in early access. You can enable or disable it in the Korbit Console.

What change is being made?

Move Vertex embeddings to the integration package and deprecate the old imports.

Why are these changes being made?

This change is part of a refactor to better organize the codebase by moving the Vertex embeddings functionality to a dedicated integration package. This improves modularity and maintainability. The deprecation warnings guide users to the new import paths, ensuring a smooth transition.


PR Type

enhancement, tests


Description

  • Moved Vertex embeddings to a dedicated integration package to improve modularity and maintainability.
  • Added deprecation warnings for old imports, guiding users to new import paths.
  • Introduced new classes for handling embeddings across different authentication methods and platforms.
  • Added integration tests for the new GoogleVertexAIEmbeddings class.
  • Updated type parameters and constructor parameters in connection and authentication classes.

Changes walkthrough 📝

Relevant files
Enhancement
14 files
googlevertexai.ts
Add deprecation warnings for Vertex AI embeddings.             

libs/langchain-community/src/embeddings/googlevertexai.ts

  • Added deprecation warnings for Google Vertex AI embeddings imports.
  • Suggested new import paths for deprecated components.
  • +5/-0     
    googlevertexai-connection.ts
    Add logging for constructed URL in connection.                     

    libs/langchain-community/src/utils/googlevertexai-connection.ts

  • Added a console log for the constructed URL in
    GoogleVertexAILLMConnection.
  • +3/-1     
    connection.ts
    Update type parameters in GoogleAIConnection class.           

    libs/langchain-google-common/src/connection.ts

    • Changed type parameters in GoogleAIConnection class.
    +4/-4     
    embeddings.ts
    Introduce GoogleEmbeddings class for embeddings handling.

    libs/langchain-google-common/src/embeddings.ts

  • Introduced new GoogleEmbeddings class for handling embeddings.
  • Added methods for embedding documents and queries.
  • +202/-0 
    index.ts
    Export new embeddings module.                                                       

    libs/langchain-google-common/src/index.ts

    • Exported new embeddings module.
    +1/-0     
    auth.ts
    Update constructor parameter type for GAuthClient.             

    libs/langchain-google-gauth/src/auth.ts

    • Updated constructor parameter type for GAuthClient.
    +2/-2     
    embeddings.ts
    Add GoogleEmbeddings class for GoogleAuth.                             

    libs/langchain-google-gauth/src/embeddings.ts

    • Added GoogleEmbeddings class for GoogleAuth.
    +39/-0   
    index.ts
    Export new embeddings module.                                                       

    libs/langchain-google-gauth/src/index.ts

    • Exported new embeddings module.
    +1/-0     
    embeddings.ts
    Add GoogleVertexAIEmbeddings class for web integration.   

    libs/langchain-google-vertexai-web/src/embeddings.ts

    • Added GoogleVertexAIEmbeddings class for web integration.
    +25/-0   
    index.ts
    Export new embeddings module.                                                       

    libs/langchain-google-vertexai-web/src/index.ts

    • Exported new embeddings module.
    +1/-0     
    embeddings.ts
    Add GoogleVertexAIEmbeddings class for Vertex AI.               

    libs/langchain-google-vertexai/src/embeddings.ts

    • Added GoogleVertexAIEmbeddings class for Vertex AI.
    +25/-0   
    index.ts
    Export new embeddings module.                                                       

    libs/langchain-google-vertexai/src/index.ts

    • Exported new embeddings module.
    +1/-0     
    embeddings.ts
    Add GoogleEmbeddings class for web authentication.             

    libs/langchain-google-webauth/src/embeddings.ts

    • Added GoogleEmbeddings class for web authentication.
    +38/-0   
    index.ts
    Export new embeddings module.                                                       

    libs/langchain-google-webauth/src/index.ts

    • Exported new embeddings module.
    +1/-0     
    Tests
    1 files
    embeddings.int.test.ts
    Add integration tests for GoogleVertexAIEmbeddings.           

    libs/langchain-google-vertexai-web/src/tests/embeddings.int.test.ts

    • Added integration tests for GoogleVertexAIEmbeddings.
    +29/-0   

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

    Copy link
    Author

    korbit-ai bot commented Aug 15, 2024

    Clone of the PR langchain-ai/langchainjs#6459

    Copy link
    Author

    korbit-ai bot commented Aug 15, 2024

    My review is in progress 📖 - I will have feedback for you in a few minutes!

    Copy link

    coderabbitai bot commented Aug 15, 2024

    Warning

    Rate limit exceeded

    @furwellness has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 25 seconds before requesting another review.

    How to resolve this issue?

    After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

    We recommend that you space out your commits to avoid hitting the rate limit.

    How do rate limits work?

    CodeRabbit enforces hourly rate limits for each developer per organization.

    Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

    Please see our FAQ for further information.

    Commits

    Files that changed from the base of the PR and between 9db8299 and ace0d6c.


    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.

    Copy link
    Author

    @korbit-ai korbit-ai bot left a comment

    Choose a reason for hiding this comment

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

    I have reviewed your code and found 5 potential issues.

    Comment on lines +11 to +14
    /**
    * Integration with a chat model.
    */
    export class GoogleVertexAIEmbeddings extends GoogleEmbeddings {
    Copy link
    Author

    Choose a reason for hiding this comment

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

    category Functionality severity potentially major

    The class comment for GoogleVertexAIEmbeddings is incorrect. It currently states 'Integration with a chat model', but this class is actually for generating embeddings using Google Vertex AI. Please update the comment to accurately reflect the purpose of this class, such as 'Integration with Google Vertex AI for generating embeddings'.

    Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

    model: "textembedding-gecko",
    });
    const res = await embeddings.embedQuery("Hello world");
    expect(typeof res[0]).toBe("number");
    Copy link
    Author

    Choose a reason for hiding this comment

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

    category Functionality

    The current tests only check if the first element of each embedding is a number. To improve the test coverage, add assertions to verify that all elements of the embeddings are numbers within an expected range (e.g., between -1 and 1 for normalized embeddings). Also, check if the embedding vectors have the expected dimensionality for the chosen model.

    Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

    Comment on lines +215 to +217
    console.log(
    `https://${this.endpoint}/v1/projects/${projectId}/locations/${this.location}/publishers/google/models/${this.model}:${method}`
    );
    Copy link
    Author

    Choose a reason for hiding this comment

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

    category Functionality

    I noticed that a console.log statement has been added which prints out the full URL, including sensitive information like the project ID, endpoint, and model name. This could potentially lead to security vulnerabilities if the logs are exposed. Consider removing this console.log statement or replacing it with a more secure logging method that doesn't expose sensitive information in production environments.

    Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

    Comment on lines 1 to +3
    export * from "./chat_models.js";
    export * from "./llms.js";
    export * from "./embeddings.js";
    Copy link
    Author

    Choose a reason for hiding this comment

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

    category Documentation

    It would be helpful to add inline comments explaining the purpose and functionality of the exported modules. This will make it easier for other developers to understand the code and contribute to it. For example, you could add a comment like // Exporting the chat models module which contains... before the export * from './chat_models.js'; line.

    Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

    Comment on lines +4 to +10
    test("Test GoogleVertexAIEmbeddings.embedQuery", async () => {
    const embeddings = new GoogleVertexAIEmbeddings({
    model: "textembedding-gecko",
    });
    const res = await embeddings.embedQuery("Hello world");
    expect(typeof res[0]).toBe("number");
    });
    Copy link
    Author

    Choose a reason for hiding this comment

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

    category Functionality

    The current test cases for GoogleVertexAIEmbeddings are a good start, but they're not comprehensive enough to ensure full functionality. Consider adding more test cases to cover different scenarios such as empty input, very long input, and input with special characters. Also, verify the length and structure of the returned embeddings to ensure they meet the expected format for the chosen models.

    Chat with Korbit by mentioning @korbit-ai, and give a 👍 or 👎 to help Korbit improve your reviews.

    @furwellness furwellness reopened this Aug 20, 2024
    @furwellness furwellness changed the base branch from cloned_main_de3a4 to main August 20, 2024 23:03
    Copy link

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Debugging Code
    Console log statement added for debugging purposes should be removed before merging to production.

    Code Duplication
    The embedDocuments method contains nested mapping and flattening operations that could be simplified for better readability and performance.

    @furwellness
    Copy link
    Owner

    @coderabbitai full review

    Copy link

    coderabbitai bot commented Aug 20, 2024

    Actions performed

    Full review triggered.

    Copy link

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Security
    Remove unnecessary console.log statement to improve security and code cleanliness

    Remove the console.log statement as it's not necessary for production code and may
    expose sensitive information.

    libs/langchain-community/src/utils/googlevertexai-connection.ts [215-217]

    -console.log(
    -  `https://${this.endpoint}/v1/projects/${projectId}/locations/${this.location}/publishers/google/models/${this.model}:${method}`
    -);
    +// Console log removed
     
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: Removing the console.log statement is a good practice for production code as it can expose sensitive information and clutter the output. This suggestion improves security and code cleanliness.

    9
    Error handling
    Add error handling for unexpected API response structures to improve robustness

    Consider adding error handling for the case where the API response doesn't contain
    the expected data structure, to improve robustness.

    libs/langchain-google-common/src/embeddings.ts [179-187]

    -const result: number[][] =
    -  responses
    -    ?.map(
    -      (response) =>
    -        (response?.data as any)?.predictions?.map(
    -          (result: any) => result.embeddings.values
    -        ) ?? []
    -    )
    -    .flat() ?? [];
    +const result: number[][] = responses
    +  ?.map((response) => {
    +    if (!response?.data?.predictions) {
    +      throw new Error("Unexpected API response structure");
    +    }
    +    return response.data.predictions.map((result: any) => {
    +      if (!result?.embeddings?.values) {
    +        throw new Error("Embedding values not found in API response");
    +      }
    +      return result.embeddings.values;
    +    });
    +  })
    +  .flat() ?? [];
     
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Adding error handling for unexpected API response structures is crucial for robustness, ensuring that the application can gracefully handle unexpected scenarios and provide meaningful error messages.

    8
    Maintainability
    Use a named constant for the chunk size to improve code maintainability

    Consider using a constant or configuration value for the chunk size (5) in the
    embedDocuments method, to improve maintainability and allow for easy adjustments.

    libs/langchain-google-common/src/embeddings.ts [166-171]

    +const VERTEX_AI_MAX_INSTANCES = 5; // Vertex AI accepts max 5 instances per prediction
     const instanceChunks: GoogleEmbeddingsInstance[][] = chunkArray(
       documents.map((document) => ({
         content: document,
       })),
    -  5
    -); // Vertex AI accepts max 5 instances per prediction
    +  VERTEX_AI_MAX_INSTANCES
    +);
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: Using a named constant for the chunk size enhances maintainability by making the code more readable and allowing easy adjustments if the chunk size changes in the future.

    7
    Best practice
    Remove commented-out code to improve code cleanliness

    Remove the commented-out console.log statement in the test file, as it's not
    providing any value and may lead to confusion.

    libs/langchain-google-vertexai-web/src/tests/embeddings.int.test.ts [24]

    -// console.log(res);
    +// Commented-out console.log removed
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Removing commented-out code helps maintain code cleanliness and reduces potential confusion, although it is a minor improvement.

    6

    @furwellness
    Copy link
    Owner

    No comment from coderabbit

    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