Module: Spectre::Embeddable

Includes:
Logging
Defined in:
lib/spectre/embeddable.rb

Defined Under Namespace

Modules: ClassMethods Classes: EmbeddingValidationError, NoEmbeddableFieldsError

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Logging

#log_debug, #log_error, #log_info, #logger

Class Method Details

.included(base) ⇒ Object



13
14
15
# File 'lib/spectre/embeddable.rb', line 13

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

Instance Method Details

#as_vectorString

Converts the specified fields into a JSON representation suitable for embedding.

Returns:

  • (String)

    A JSON string representing the vectorized content of the specified fields.

Raises:



23
24
25
26
27
28
# File 'lib/spectre/embeddable.rb', line 23

def as_vector
  raise NoEmbeddableFieldsError, "Embeddable fields are not defined" if self.class.embeddable_fields.empty?

  vector_data = self.class.embeddable_fields.map { |field| [field, send(field)] }.to_h
  vector_data.to_json
end

#embed!(validation: nil, embedding_field: :embedding, timestamp_field: :embedded_at) ⇒ Object

Embeds the vectorized content and saves it to the specified fields.

Examples:

embed!(validation: ->(record) { !record.response.nil? }, embedding_field: :custom_embedding, timestamp_field: :custom_embedded_at)

Parameters:

  • validation (Proc, nil) (defaults to: nil)

    A validation block that returns true if the embedding should proceed.

  • embedding_field (Symbol) (defaults to: :embedding)

    The field in which to store the generated embedding (default: :embedding).

  • timestamp_field (Symbol) (defaults to: :embedded_at)

    The field in which to store the embedding timestamp (default: :embedded_at).

Raises:



41
42
43
44
45
46
47
48
49
50
# File 'lib/spectre/embeddable.rb', line 41

def embed!(validation: nil, embedding_field: :embedding, timestamp_field: :embedded_at)
  if validation && !validation.call(self)
    raise EmbeddingValidationError, "Validation failed for embedding"
  end

  embedding_value = Spectre.provider_module::Embeddings.create(as_vector)
  send("#{embedding_field}=", embedding_value)
  send("#{timestamp_field}=", Time.now)
  save!
end