Module: LangchainrbRails::ActiveRecord::Hooks::ClassMethods

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

Instance Method Summary collapse

Instance Method Details

#ask(question, k: 4) {|String| ... } ⇒ String

Ask a question and return the answer

standard:disable Style/ArgumentsForwarding

Parameters:

  • question (String)

    The question to ask

  • k (Integer) (defaults to: 4)

    The number of results to have in context

Yields:

  • (String)

    Stream responses back one String at a time

Returns:

  • (String)

    The answer to the question



129
130
131
132
133
134
135
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 129

def ask(question, k: 4, &block)
  class_variable_get(:@@provider).ask(
    question: question,
    k: k,
    &block
  ).chat_completion
end

#embed!Object

Iterates over records and generate embeddings. Will re-generate for ALL records (not just records with embeddings).



98
99
100
101
102
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 98

def embed!
  find_each do |record|
    record.upsert_to_vectorsearch
  end
end

#similarity_search(query, k: 1) ⇒ ActiveRecord::Relation

Search for similar texts

Parameters:

  • query (String)

    The query to search for

  • k (Integer) (defaults to: 1)

    The number of results to return

Returns:

  • (ActiveRecord::Relation)

    The ActiveRecord relation



109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 109

def similarity_search(query, k: 1)
  records = class_variable_get(:@@provider).similarity_search(
    query: query,
    k: k
  )

  return records if LangchainrbRails.config.vectorsearch.is_a?(Langchain::Vectorsearch::Pgvector)

  # We use "__id" when Weaviate is the provider
  ids = records.map { |record| record.try("id") || record.dig("__id") }
  where(id: ids)
end

#vectorsearchObject

Set the vector search provider

Parameters:

  • provider (Object)

    The ‘Langchain::Vectorsearch::*` instance



86
87
88
89
90
91
92
93
94
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 86

def vectorsearch
  class_variable_set(:@@provider, LangchainrbRails.config.vectorsearch.dup)

  # Pgvector-specific configuration
  if LangchainrbRails.config.vectorsearch.is_a?(Langchain::Vectorsearch::Pgvector)
    has_neighbors(:embedding)
    class_variable_get(:@@provider).model = self
  end
end