Class: RagRuby::Embedders::Cohere

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

Constant Summary collapse

ENDPOINT =
"https://api.cohere.ai/v1/embed"

Instance Method Summary collapse

Constructor Details

#initialize(model: "embed-english-v3.0", api_key: nil) ⇒ Cohere

Returns a new instance of Cohere.

Raises:

  • (ArgumentError)


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

def initialize(model: "embed-english-v3.0", api_key: nil)
  @model = model
  @api_key = api_key || ENV["COHERE_API_KEY"]
  raise ArgumentError, "Cohere API key is required (set COHERE_API_KEY or pass api_key:)" unless @api_key
end

Instance Method Details

#dimension ⇒ Object



48
49
50
# File 'lib/rag_ruby/embedders/cohere.rb', line 48

def dimension
  1024
end

#embed(text) ⇒ Object



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

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

#embed_batch(texts) ⇒ Object

Raises:



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
# File 'lib/rag_ruby/embedders/cohere.rb', line 22

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

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

  response = http.request(req)

  unless response.is_a?(Net::HTTPSuccess)
    raise "Cohere API error (#{response.code}): #{response.body}"
  end

  parsed = JSON.parse(response.body)
  embeddings = parsed["embeddings"]
  raise RagRuby::Error, "No embeddings in Cohere response" if embeddings.nil? || embeddings.empty?
  embeddings
end