Skip to content

fix(opensearch): Return Distance and respect the provided ScoreThreshold#112

Merged
HavenDV merged 1 commit intotryAGI:mainfrom
dandeto:main
Jan 3, 2025
Merged

fix(opensearch): Return Distance and respect the provided ScoreThreshold#112
HavenDV merged 1 commit intotryAGI:mainfrom
dandeto:main

Conversation

@dandeto
Copy link
Contributor

@dandeto dandeto commented Jan 3, 2025

I don't see the "Ready for review" template mentioned in contributing.md, but this is a simple PR, so it shouldn't require too much explanation. The only modifications were to SearchAsync in OpenSearchVectorCollection.

The Distance property is filled out in the postgres and mongodb abstractions, but it always returns 0 when using OpenSearch. I have a usecase for wanting to know the distance. Rather than using opensearch's convenient "Documents" API, I switched to using the "Hits" API which provides some additional information, such as the score for each hit.

Another feature that was not implemented was utilizing the ScoreThreshold optionally passed in by the user to filter out hits that are below the desired threshold. I added a second condition to the linq where clause to implement this.

I have an application using langchain that I used to test this function before and after my adjustments, and I can verify that the Distance is passed back and the ScoreThreshold is respected.

Summary by CodeRabbit

  • Bug Fixes

    • Improved search result filtering by introducing a score threshold mechanism
    • Enhanced vector search accuracy by refining result processing logic
  • Performance

    • Added ability to set a default score threshold for more precise search results
    • Introduced Distance property to capture hit scores more effectively

@CLAassistant
Copy link

CLAassistant commented Jan 3, 2025

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 3, 2025

Walkthrough

The pull request introduces modifications to the OpenSearchVectorCollection class, specifically in the SearchAsync method. The changes focus on enhancing the search result processing logic by adding a default ScoreThreshold and modifying how search results are filtered and mapped. The core functionality remains consistent, with improvements in handling search result scoring and distance calculation.

Changes

File Change Summary
src/OpenSearch/src/OpenSearchVectorCollection.cs - Added default ScoreThreshold setting
- Modified search result filtering to use response.Hits
- Introduced Distance property capturing hit score
- Refined result mapping logic

Poem

🐰 In OpenSearch's vector domain,
A rabbit hops through search's terrain,
Scores now dance with threshold's might,
Filtering results crisp and bright,
A vector quest of 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>, 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
Contributor

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

🧹 Nitpick comments (1)
src/OpenSearch/src/OpenSearchVectorCollection.cs (1)

121-127: Clarify the distinction between score and distance.

You are assigning hit.Score to Distance, but in most vector search paradigms, a higher score implies higher similarity, which can be the opposite of distance if using certain metrics. If your goal is to track similarity rather than an actual distance, consider renaming the property for clarity. Otherwise, ensure this matches your end users' expectations of "distance."

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fec0d0c and e1c801c.

📒 Files selected for processing (1)
  • src/OpenSearch/src/OpenSearchVectorCollection.cs (2 hunks)
🔇 Additional comments (1)
src/OpenSearch/src/OpenSearchVectorCollection.cs (1)

101-101: Check the default ScoreThreshold value.

Defaulting ScoreThreshold to 0.0f allows all hits to pass the threshold. Consider whether this aligns with your desired logic. If you intend to exclude marginally relevant hits, setting a slightly higher default might be beneficial.

Could you confirm that 0.0f is the intended default, or would you like a different default (e.g., 0.5f)?

Comment on lines +119 to +120
Items = response.Hits
.Where(hit => !string.IsNullOrWhiteSpace(hit.Source.Text) && hit.Score >= settings.ScoreThreshold)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle empty or null embeddings edge case.

The code calls request.Embeddings.First(), but there's no check to ensure that request.Embeddings is not empty. If request.Embeddings is empty, this could lead to a runtime exception. You might want to add a guard clause or throw an argument exception if no embeddings are provided.

+ if (request.Embeddings == null || !request.Embeddings.Any())
+ {
+     throw new ArgumentException("At least one embedding must be provided.", nameof(request.Embeddings));
+ }

Committable suggestion skipped: line range outside the PR's diff.

@HavenDV HavenDV enabled auto-merge (squash) January 3, 2025 04:13
@HavenDV HavenDV merged commit 2066036 into tryAGI:main Jan 3, 2025
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.

3 participants