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



116
117
118
119
120
121
122
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 116

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).



85
86
87
88
89
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 85

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



96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/langchainrb_rails/active_record/hooks.rb', line 96

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



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

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