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

ollama[minor]: Port embeddings to ollama package #5

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

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?

Port embeddings functionality to the ollama package by adding OllamaEmbeddings class, updating ChatOllamaInput interface, and including new types and tests.

Why are these changes being made?

This change integrates the embeddings feature into the ollama package, allowing for embedding operations using the Ollama model. It also refactors the code to use camelCase options for consistency and maintainability.


PR Type

enhancement, tests


Description

  • Introduced OllamaEmbeddings class to handle embedding operations using the Ollama model.
  • Updated ChatOllamaInput interface to include OllamaCamelCaseOptions for more consistent parameter handling.
  • Added integration tests for OllamaEmbeddings to ensure functionality of embedding methods.
  • Exported new modules to facilitate embedding operations and type definitions.

Changes walkthrough 📝

Relevant files
Enhancement
chat_models.ts
Update ChatOllamaInput interface with camelCase options   

libs/langchain-ollama/src/chat_models.ts

  • Added OllamaCamelCaseOptions to ChatOllamaInput interface.
  • Removed several parameters from ChatOllamaInput.
  • +4/-34   
    embeddings.ts
    Add OllamaEmbeddings class for embedding functionality     

    libs/langchain-ollama/src/embeddings.ts

  • Introduced OllamaEmbeddings class for embedding operations.
  • Implemented _convertOptions method for camelCase to snake_case
    conversion.
  • Added methods for embedding documents and queries.
  • +151/-0 
    index.ts
    Update exports to include embeddings and types                     

    libs/langchain-ollama/src/index.ts

    • Exported new modules embeddings.js and types.js.
    +2/-0     
    types.ts
    Define OllamaCamelCaseOptions interface for request options

    libs/langchain-ollama/src/types.ts

    • Defined OllamaCamelCaseOptions interface.
    +36/-0   
    Tests
    embeddings.int.test.ts
    Add integration tests for OllamaEmbeddings                             

    libs/langchain-ollama/src/tests/embeddings.int.test.ts

  • Added integration tests for OllamaEmbeddings.
  • Tested embedQuery and embedDocuments methods.
  • +19/-0   

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

    Summary by CodeRabbit

    • New Features

      • Introduced a streamlined ChatOllamaInput interface with enhanced configuration options.
      • Added the OllamaEmbeddings class for generating embeddings for documents and queries.
      • Expanded module exports to include functionalities from new embeddings and types files.
      • Defined a new OllamaCamelCaseOptions interface for customizable model configuration.
    • Bug Fixes

      • Removed deprecated properties from ChatOllamaInput to simplify its usage.
    • Tests

      • Added unit tests for the OllamaEmbeddings class to validate core functionalities.

    Copy link
    Author

    korbit-ai bot commented Aug 15, 2024

    Clone of the PR langchain-ai/langchainjs#6464

    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

    Walkthrough

    The recent changes enhance the functionality and usability of the langchain-ollama library by introducing a new OllamaEmbeddings class and refining the ChatOllamaInput interface. This update streamlines input options, adding extensibility through OllamaCamelCaseOptions, while removing less critical parameters. New tests ensure the reliability of embedding methods. Overall, these modifications aim to create a more user-friendly experience for developers working with embeddings and chat models.

    Changes

    Files Change Summary
    libs/langchain-ollama/src/chat_models.ts, libs/langchain-ollama/src/types.ts Modified ChatOllamaInput to extend OllamaCamelCaseOptions, removing several properties for a streamlined interface. Added OllamaCamelCaseOptions interface for enhanced configuration.
    libs/langchain-ollama/src/embeddings.ts Introduced OllamaEmbeddings class, allowing customizable embeddings generation with methods for embedding documents and queries.
    libs/langchain-ollama/src/index.ts Enhanced exports to include functionalities from embeddings.js and types.js, broadening the module's interface.
    libs/langchain-ollama/src/tests/embeddings.int.test.ts Added tests for OllamaEmbeddings methods to ensure consistent and valid output.

    Poem

    In a world where bunnies hop and play,
    New changes brighten up our day!
    Embeddings dance in joyful glee,
    As options sprout like flowers, you see.
    With every line of code we greet,
    A user-friendly path, oh so sweet! 🐇✨


    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 4 potential issues.

    Comment on lines +63 to +68
    constructor(fields?: OllamaEmbeddingsParams) {
    super({ maxConcurrency: 1, ...fields });

    this.client = new Ollama({
    host: fields?.baseUrl,
    });
    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 headers property is defined and set in the constructor, but it's not being used in the API calls. To ensure custom headers are applied, you should pass the headers to the Ollama client when it's initialized. Update the constructor to include headers in the Ollama client initialization:

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

    Comment on lines +1 to +36
    export interface OllamaCamelCaseOptions {
    numa?: boolean;
    numCtx?: number;
    numBatch?: number;
    numGpu?: number;
    mainGpu?: number;
    lowVram?: boolean;
    f16Kv?: boolean;
    logitsAll?: boolean;
    vocabOnly?: boolean;
    useMmap?: boolean;
    useMlock?: boolean;
    embeddingOnly?: boolean;
    numThread?: number;
    numKeep?: number;
    seed?: number;
    numPredict?: number;
    topK?: number;
    topP?: number;
    tfsZ?: number;
    typicalP?: number;
    repeatLastN?: number;
    temperature?: number;
    repeatPenalty?: number;
    presencePenalty?: number;
    frequencyPenalty?: number;
    mirostat?: number;
    mirostatTau?: number;
    mirostatEta?: number;
    penalizeNewline?: boolean;
    /**
    * @default "5m"
    */
    keepAlive?: string | number;
    stop?: string[];
    }
    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 OllamaCamelCaseOptions interface could benefit from more specific type constraints and documentation. For example, properties like numCtx, numBatch, numGpu, etc., should probably be non-negative integers. The temperature property typically ranges from 0 to 1. Consider adding these constraints and including JSDoc comments to explain the purpose and expected values for each property. This will improve type safety and make the interface more self-documenting.

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

    Comment on lines +4 to +9
    test("Test OllamaEmbeddings.embedQuery", async () => {
    const embeddings = new OllamaEmbeddings();
    const res = await embeddings.embedQuery("Hello world");
    expect(res).toHaveLength(1024);
    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 for OllamaEmbeddings look good for basic functionality, but they don't cover error handling or edge cases. Consider adding tests for:

    1. Empty string inputs
    2. Very long inputs (to test any potential length limits)
    3. Network errors or API failures (you may need to mock the API calls)
    4. Invalid inputs

    This will ensure the OllamaEmbeddings class behaves correctly under various conditions and improves the overall reliability of the package.

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

    @@ -0,0 +1,36 @@
    export interface OllamaCamelCaseOptions {
    Copy link
    Author

    Choose a reason for hiding this comment

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

    category Objects and Data Structures

    The OllamaCamelCaseOptions interface has a large number of optional parameters, which can make it difficult to use and understand. Consider breaking down this interface into smaller, more specific interfaces to improve readability and maintainability. Also, if some parameters are necessary for the interface to function correctly, consider making them required.

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

    @furwellness
    Copy link
    Owner

    /review

    Copy link

    codiumai-pr-agent-free bot commented Aug 20, 2024

    PR Reviewer Guide 🔍

    (Review updated until commit 677f974)

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

    Error Handling
    The embeddingWithRetry method doesn't have explicit error handling. Consider adding try-catch blocks or error handling mechanisms to manage potential API failures or network issues.

    Type Safety
    The _convertOptions method uses a type assertion (as keyof OllamaOptions) which might lead to runtime errors if the keys don't match. Consider using a more type-safe approach.

    @furwellness furwellness reopened this Aug 20, 2024
    @furwellness furwellness changed the base branch from cloned_main_96bba to main August 20, 2024 23:01
    @codiumai-pr-agent-free codiumai-pr-agent-free bot added enhancement New feature or request tests labels Aug 20, 2024
    @furwellness
    Copy link
    Owner

    @coderabbitai full review

    Copy link

    coderabbitai bot commented Aug 20, 2024

    Actions performed

    Full review triggered.

    Copy link

    Persistent review updated to latest commit 677f974

    Copy link

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Test coverage
    Add a test case for invalid input to ensure proper error handling in the OllamaEmbeddings class

    Consider adding a test case that checks the behavior of the OllamaEmbeddings class
    when invalid input is provided, such as an empty string or array, to ensure proper
    error handling.

    libs/langchain-ollama/src/tests/embeddings.int.test.ts [4-19]

     test("Test OllamaEmbeddings.embedQuery", async () => {
       const embeddings = new OllamaEmbeddings();
       const res = await embeddings.embedQuery("Hello world");
       expect(res).toHaveLength(1024);
       expect(typeof res[0]).toBe("number");
     });
     
     test("Test OllamaEmbeddings.embedDocuments", async () => {
       const embeddings = new OllamaEmbeddings();
       const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
       expect(res).toHaveLength(2);
       expect(res[0]).toHaveLength(1024);
       expect(typeof res[0][0]).toBe("number");
       expect(res[1]).toHaveLength(1024);
       expect(typeof res[1][0]).toBe("number");
     });
     
    +test("Test OllamaEmbeddings with invalid input", async () => {
    +  const embeddings = new OllamaEmbeddings();
    +  await expect(embeddings.embedQuery("")).rejects.toThrow();
    +  await expect(embeddings.embedDocuments([])).rejects.toThrow();
    +});
    +
    • Apply this suggestion
    Suggestion importance[1-10]: 9

    Why: This suggestion significantly improves test coverage by ensuring that the class handles invalid inputs correctly, which is essential for maintaining software reliability and robustness.

    9
    Error handling
    Add error handling to the embedding request method for better error reporting and potential retry logic

    The embeddingWithRetry method could benefit from error handling to provide more
    informative error messages or implement specific retry logic if the API call fails.

    libs/langchain-ollama/src/embeddings.ts [139-150]

     private async embeddingWithRetry(texts: string[]): Promise<number[][]> {
    -  const res = await this.caller.call(() =>
    -    this.client.embed({
    -      model: this.model,
    -      input: texts,
    -      keep_alive: this.keepAlive,
    -      options: this.requestOptions,
    -      truncate: this.truncate,
    -    })
    -  );
    -  return res.embeddings;
    +  try {
    +    const res = await this.caller.call(() =>
    +      this.client.embed({
    +        model: this.model,
    +        input: texts,
    +        keep_alive: this.keepAlive,
    +        options: this.requestOptions,
    +        truncate: this.truncate,
    +      })
    +    );
    +    return res.embeddings;
    +  } catch (error) {
    +    console.error("Error in embedding request:", error);
    +    throw new Error(`Failed to get embeddings: ${error.message}`);
    +  }
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 8

    Why: Adding error handling is crucial for robustness, providing informative error messages and allowing for potential retry logic, which is important for a method that makes external API calls.

    8
    Type safety
    Use a more specific type for the requestOptions property to improve type safety

    Consider using a more specific type for the requestOptions property in the
    OllamaEmbeddings class. Instead of Partial, you could use
    Partial<Pick<OllamaOptions, keyof OllamaCamelCaseOptions>> to ensure that only the
    properties defined in OllamaCamelCaseOptions are allowed.

    libs/langchain-ollama/src/embeddings.ts [57]

    -requestOptions?: Partial<OllamaOptions>;
    +requestOptions?: Partial<Pick<OllamaOptions, keyof OllamaCamelCaseOptions>>;
     
    • Apply this suggestion
    Suggestion importance[1-10]: 7

    Why: This suggestion improves type safety by ensuring that only properties defined in OllamaCamelCaseOptions are allowed, which can prevent potential errors and improve code maintainability.

    7
    Performance
    Simplify the option conversion logic using a Map for better performance and readability

    The _convertOptions method could be simplified by using a Map instead of an object
    for the mapping, which would allow for a more concise implementation and potentially
    better performance for lookups.

    libs/langchain-ollama/src/embeddings.ts [88-128]

    -const mapping: Record<keyof OllamaCamelCaseOptions, string> = {
    -  embeddingOnly: "embedding_only",
    -  frequencyPenalty: "frequency_penalty",
    -  keepAlive: "keep_alive",
    +const mapping = new Map<keyof OllamaCamelCaseOptions, keyof OllamaOptions>([
    +  ["embeddingOnly", "embedding_only"],
    +  ["frequencyPenalty", "frequency_penalty"],
    +  ["keepAlive", "keep_alive"],
       // ... (other mappings)
    -};
    +]);
     
     for (const [key, value] of Object.entries(requestOptions)) {
    -  const snakeCasedOption = mapping[key as keyof OllamaCamelCaseOptions];
    +  const snakeCasedOption = mapping.get(key as keyof OllamaCamelCaseOptions);
       if (snakeCasedOption) {
    -    snakeCasedOptions[snakeCasedOption as keyof OllamaOptions] = value;
    +    snakeCasedOptions[snakeCasedOption] = value;
       }
     }
     
    • Apply this suggestion
    Suggestion importance[1-10]: 6

    Why: Using a Map can simplify the code and potentially improve performance, but the performance gain might be negligible in this context. The suggestion mainly enhances code readability.

    6

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

    Review details

    Configuration used: CodeRabbit UI
    Review profile: CHILL

    Commits

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

    Files selected for processing (5)
    • libs/langchain-ollama/src/chat_models.ts (3 hunks)
    • libs/langchain-ollama/src/embeddings.ts (1 hunks)
    • libs/langchain-ollama/src/index.ts (1 hunks)
    • libs/langchain-ollama/src/tests/embeddings.int.test.ts (1 hunks)
    • libs/langchain-ollama/src/types.ts (1 hunks)
    Additional comments not posted (8)
    libs/langchain-ollama/src/index.ts (1)

    2-3: LGTM! Expanded module exports.

    The addition of exports from embeddings.js and types.js enhances the module's interface, providing access to more functionalities.

    libs/langchain-ollama/src/tests/embeddings.int.test.ts (2)

    4-9: Existing comment acknowledged: Enhance test coverage.

    The current tests are good for basic functionality. Consider adding tests for edge cases and error handling as suggested in the existing comments.


    11-19: Existing comment acknowledged: Enhance test coverage.

    The current tests are good for basic functionality. Consider adding tests for edge cases and error handling as suggested in the existing comments.

    libs/langchain-ollama/src/types.ts (1)

    1-36: Existing comment acknowledged: Improve type constraints and documentation.

    Consider adding more specific type constraints and JSDoc comments for better type safety and self-documentation, as suggested in the existing comments.

    libs/langchain-ollama/src/embeddings.ts (2)

    63-68: Existing comment acknowledged: Ensure headers are used in API calls.

    Ensure that the headers property is utilized in the API calls to apply custom headers, as suggested in the existing comments.


    84-129: LGTM! Well-implemented _convertOptions method.

    The _convertOptions method effectively converts camelCase options to snake_case, ensuring consistency with the API requirements.

    libs/langchain-ollama/src/chat_models.ts (2)

    31-31: LGTM! Streamlined ChatOllamaInput interface.

    The extension of ChatOllamaInput with OllamaCamelCaseOptions simplifies the interface, promoting modularity and maintainability.


    59-61: Verify impact of interface changes.

    Ensure that the removal of properties from ChatOllamaInput does not break existing code. Verify that all necessary adjustments have been made in the codebase.

    Run the following script to check for usages of ChatOllamaInput:

    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