Class: RagRuby::Embedders::Voyage

Inherits:
Base
  • Object
show all
Defined in:
lib/rag_ruby/embedders/voyage.rb

Constant Summary collapse

ENDPOINT =
"https://api.voyageai.com/v1/embeddings"

Instance Method Summary collapse

Constructor Details

#initialize(model: "voyage-3", api_key: nil) ⇒ Voyage

Returns a new instance of Voyage.

Raises:

  • (ArgumentError)


12
13
14
15
16
# File 'lib/rag_ruby/embedders/voyage.rb', line 12

def initialize(model: "voyage-3", api_key: nil)
  @model = model
  @api_key = api_key || ENV["VOYAGE_API_KEY"]
  raise ArgumentError, "Voyage API key is required (set VOYAGE_API_KEY or pass api_key:)" unless @api_key
end

Instance Method Details

#dimension ⇒ Object



43
44
45
# File 'lib/rag_ruby/embedders/voyage.rb', line 43

def dimension
  1024
end

#embed(text) ⇒ Object



18
19
20
# File 'lib/rag_ruby/embedders/voyage.rb', line 18

def embed(text)
  embed_batch([text]).first
end

#embed_batch(texts) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rag_ruby/embedders/voyage.rb', line 22

def embed_batch(texts)
  uri = URI.parse(ENDPOINT)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.open_timeout = 30
  http.read_timeout = 60

  req = Net::HTTP::Post.new(uri)
  req["Authorization"] = "Bearer #{@api_key}"
  req["Content-Type"] = "application/json"
  req.body = JSON.generate(model: @model, input: texts)

  response = http.request(req)
  unless response.is_a?(Net::HTTPSuccess)
    raise RagRuby::Error, "Voyage API error (#{response.code}): #{response.body}"
  end

  parsed = JSON.parse(response.body)
  parsed["data"].sort_by { |d| d["index"] }.map { |d| d["embedding"] }
end