Class: Spectre::Openai::Embeddings

Inherits:
Object
  • Object
show all
Defined in:
lib/spectre/openai/embeddings.rb

Constant Summary collapse

API_URL =
'https://api.openai.com/v1/embeddings'
DEFAULT_MODEL =
'text-embedding-3-small'

Class Method Summary collapse

Class Method Details

.create(text, model: DEFAULT_MODEL) ⇒ Array<Float>

Class method to generate embeddings for a given text

Parameters:

  • text (String)

    the text input for which embeddings are to be generated

  • model (String) (defaults to: DEFAULT_MODEL)

    the model to be used for generating embeddings, defaults to DEFAULT_MODEL

Returns:

  • (Array<Float>)

    the generated embedding vector

Raises:

  • (APIKeyNotConfiguredError)

    if the API key is not set

  • (RuntimeError)

    for general API errors or unexpected issues



20
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
# File 'lib/spectre/openai/embeddings.rb', line 20

def self.create(text, model: DEFAULT_MODEL)
  api_key = Spectre.api_key
  raise APIKeyNotConfiguredError, "API key is not configured" unless api_key

  uri = URI(API_URL)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.read_timeout = 10 # seconds
  http.open_timeout = 10 # seconds

  request = Net::HTTP::Post.new(uri.path, {
    'Content-Type' => 'application/json',
    'Authorization' => "Bearer #{api_key}"
  })

  request.body = { model: model, input: text }.to_json
  response = http.request(request)

  unless response.is_a?(Net::HTTPSuccess)
    raise "OpenAI API Error: #{response.code} - #{response.message}: #{response.body}"
  end

  JSON.parse(response.body).dig('data', 0, 'embedding')
rescue JSON::ParserError => e
  raise "JSON Parse Error: #{e.message}"
rescue Net::OpenTimeout, Net::ReadTimeout => e
  raise "Request Timeout: #{e.message}"
end