Module: LangchainrbRails::ActiveRecord::Hooks

Defined in:
lib/langchainrb_rails/active_record/hooks.rb

Overview

This module adds the following functionality to your ActiveRecord models:

  • ‘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
    [
      "Title: #{title}",
      "Description: #{description}",
      ...
    ]
    .compact
    .join("\n")
  end
end

Create the default schema

Recipe.class_variable_get(:@@provider).create_default_schema

Query the vector search provider

Recipe.similarity_search("carnivore dish")

Delete the default schema to start over

Recipe.class_variable_get(:@@provider).destroy_default_schema

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



38
39
40
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 38

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#as_vectorString

Used to serialize the DB record to an indexable vector text Overwrite this method in your model to customize

Returns:

  • (String)

    the text representation of the model



76
77
78
79
80
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 76

def as_vector
  # Don't vectorize the embedding ... this would happen if it already exists
  # for a record and we update.
  to_json(except: :embedding)
end

#destroy_from_vectorsearchBoolean

Remove the record from the vector search provider This method should be called in an ActiveRecord ‘after_destroy` callback

Returns:

  • (Boolean)

    true

Raises:

  • (Error)

    Removing from vector search DB failed



66
67
68
69
70
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 66

def destroy_from_vectorsearch
  self.class.class_variable_get(:@@provider).remove_texts(
    ids: [id]
  )
end

#upsert_to_vectorsearchBoolean

Index the text to the vector search provider You’d typically call this method in an ActiveRecord callback

Returns:

  • (Boolean)

    true

Raises:

  • (Error)

    Indexing to vector search DB failed



47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 47

def upsert_to_vectorsearch
  if previously_new_record?
    self.class.class_variable_get(:@@provider).add_texts(
      texts: [as_vector],
      ids: [id]
    )
  else
    self.class.class_variable_get(:@@provider).update_texts(
      texts: [as_vector],
      ids: [id]
    )
  end
end