Skip to content

Commit

Permalink
Add destroy_from_vectorsearch hook (#82)
Browse files Browse the repository at this point in the history
* Add destroy_from_vectorsearch hook

* Tiny spec

* Fixes

* Update README.md
  • Loading branch information
andreibondarev authored Jun 16, 2024
1 parent 403caa6 commit 88fcfe2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
10 changes: 10 additions & 0 deletions lib/langchainrb_overrides/vectorsearch/pgvector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ def update_texts(texts:, ids:)
add_texts(texts: texts, ids: ids)
end

# Remove vectors from the index
#
# @param ids [Array<String>] The ids of the vectors to remove
# @return [Boolean] true
def remove_texts(ids:)
# Since the record is being destroyed and the `embedding` is a column on the record,
# we don't need to do anything here.
true
end

# Invoke a rake task that will create an initializer (`config/initializers/langchain.rb`) file
# and db/migrations/* files
def create_default_schema
Expand Down
13 changes: 13 additions & 0 deletions lib/langchainrb_rails/active_record/hooks.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@ module ActiveRecord
# * `vectorsearch` class method to set the vector search provider
# * `similarity_search` class method to search for similar texts
# * `upsert_to_vectorsearch` instance method to upsert the record to the vector search provider
# * `destroy_from_vectorsearch` instance method to remove the record from the vector search provider
#
# Usage:
# class Recipe < ActiveRecord::Base
# vectorsearch
#
# after_save :upsert_to_vectorsearch
# after_destroy :destroy_from_vectorsearch
#
# # Overwriting how the model is serialized before it's indexed
# def as_vector
Expand Down Expand Up @@ -56,6 +58,17 @@ def upsert_to_vectorsearch
end
end

# Remove the record from the vector search provider
# This method should be called in an ActiveRecord `after_destroy` callback
#
# @return [Boolean] true
# @raise [Error] Removing from vector search DB failed
def destroy_from_vectorsearch
self.class.class_variable_get(:@@provider).remove_texts(
ids: [id]
)
end

# Used to serialize the DB record to an indexable vector text
# Overwrite this method in your model to customize
#
Expand Down
1 change: 1 addition & 0 deletions spec/langchainrb_rails/active_record/hooks_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Dummy
RSpec.describe LangchainrbRails::ActiveRecord::Hooks do
it "responds to instance methods" do
expect(::Dummy.new).to respond_to(:upsert_to_vectorsearch)
expect(::Dummy.new).to respond_to(:destroy_from_vectorsearch)
expect(::Dummy.new).to respond_to(:as_vector)
end

Expand Down

0 comments on commit 88fcfe2

Please sign in to comment.