Module: ActiveRecordVector::Model::ClassMethods
- Defined in:
- lib/active_record_vector/model.rb
Instance Method Summary collapse
-
#has_vector(attribute = :embedding, options = {}) ⇒ Object
Macro to enable vector capabilities on a model attribute.
- #vector_configs ⇒ Object
Instance Method Details
#has_vector(attribute = :embedding, options = {}) ⇒ Object
Macro to enable vector capabilities on a model attribute
Example:
has_vector :embedding,
provider: :openai,
model: "text-embedding-3-small",
from: [:title, :body],
auto_generate: true
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/active_record_vector/model.rb', line 21 def has_vector(attribute = :embedding, = {}) @vector_configs ||= {} @vector_configs[attribute.to_sym] = { provider: [:provider] || :openai, model: [:model], from: Array([:from] || :content), auto_generate: .fetch(:auto_generate, true), provider_options: } # Setup auto-generation callback if supported if .fetch(:auto_generate, true) && respond_to?(:before_save) before_save do (attribute.to_sym) end end # Define semantic search scopes if supported return unless respond_to?(:scope) scope :semantic_search, lambda { |query, target_attribute: attribute, limit: 10, distance: :cosine| nearest_to(query, attribute: target_attribute, distance: distance).limit(limit) } scope :nearest_to, lambda { |query_or_vector, target_attribute: attribute, distance: :cosine| cfg = @vector_configs[target_attribute.to_sym] || {} query_vector = if query_or_vector.is_a?(Array) query_or_vector else ActiveRecordVector.provider_for(cfg[:provider], cfg[:provider_options]).(query_or_vector.to_s) end if pgvector_supported? pgvector_nearest(query_vector, target_attribute, distance) else ruby_vector_nearest(query_vector, target_attribute, distance) end } end |
#vector_configs ⇒ Object
61 62 63 |
# File 'lib/active_record_vector/model.rb', line 61 def vector_configs @vector_configs ||= {} end |