Class: SemanticCache::Embedding

Inherits:
Object
  • Object
show all
Defined in:
lib/semantic_cache/embedding.rb

Instance Method Summary collapse

Constructor Details

#initialize(model: nil, api_key: nil) ⇒ Embedding

Returns a new instance of Embedding.



8
9
10
11
12
13
# File 'lib/semantic_cache/embedding.rb', line 8

def initialize(model: nil, api_key: nil)
  config = SemanticCache.configuration
  @model = model || config.embedding_model
  @timeout = config.embedding_timeout
  @client = OpenAI::Client.new(access_token: api_key || config.openai_api_key)
end

Instance Method Details

#generate(text) ⇒ Object

Generate an embedding vector for the given text. Returns an Array of Floats.

Raises ArgumentError if text is nil or empty. Raises SemanticCache::Error on API failure or timeout.

Raises:



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/semantic_cache/embedding.rb', line 20

def generate(text)
  validate_input!(text)

  response = with_timeout do
    @client.embeddings(
      parameters: {
        model: @model,
        input: text
      }
    )
  end

  data = response.dig("data", 0, "embedding")
  raise Error, "Failed to generate embedding: #{response}" if data.nil?

  data
end

#generate_batch(texts) ⇒ Object

Generate embeddings for multiple texts in a single API call. Returns an Array of Arrays of Floats.

Raises ArgumentError if texts is empty or contains nil/blank entries. Raises SemanticCache::Error on API failure or timeout.

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/semantic_cache/embedding.rb', line 43

def generate_batch(texts)
  raise ArgumentError, "texts must be a non-empty Array" if !texts.is_a?(Array) || texts.empty?

  texts.each_with_index do |t, i|
    validate_input!(t, label: "texts[#{i}]")
  end

  response = with_timeout do
    @client.embeddings(
      parameters: {
        model: @model,
        input: texts
      }
    )
  end

  data = response["data"]
  raise Error, "Failed to generate embeddings: #{response}" if data.nil?

  data.sort_by { |d| d["index"] }.map { |d| d["embedding"] }
end