diff --git a/lib/langchainrb_overrides/vectorsearch/pgvector.rb b/lib/langchainrb_overrides/vectorsearch/pgvector.rb index 505f6a9..ed7c9a5 100644 --- a/lib/langchainrb_overrides/vectorsearch/pgvector.rb +++ b/lib/langchainrb_overrides/vectorsearch/pgvector.rb @@ -55,6 +55,16 @@ def update_texts(texts:, ids:) add_texts(texts: texts, ids: ids) end + # Remove vectors from the index + # + # @param ids [Array] 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 diff --git a/lib/langchainrb_rails/active_record/hooks.rb b/lib/langchainrb_rails/active_record/hooks.rb index c107778..fca1e39 100644 --- a/lib/langchainrb_rails/active_record/hooks.rb +++ b/lib/langchainrb_rails/active_record/hooks.rb @@ -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 @@ -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 # diff --git a/spec/langchainrb_rails/active_record/hooks_spec.rb b/spec/langchainrb_rails/active_record/hooks_spec.rb index ee8a6cd..f683541 100644 --- a/spec/langchainrb_rails/active_record/hooks_spec.rb +++ b/spec/langchainrb_rails/active_record/hooks_spec.rb @@ -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