Module: AgentHarness::EmbeddingAdapter

Defined in:
lib/agent_harness/embedding_adapter.rb

Overview

Builds a request-local Faraday adapter for headers and cancellation.

Class Method Summary collapse

Class Method Details

.build(headers:, cancellation: nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/agent_harness/embedding_adapter.rb', line 12

def build(headers:, cancellation: nil)
  Class.new(Faraday::Adapter::NetHttp) do
    define_method(:call) do |env|
      raise CancelledError, "Embedding request cancelled" if cancellation&.call

      env.request_headers.update(headers)
      super(env).on_complete { |response| EmbeddingAdapter.order_rows(response) }
    end
  end
end

.order_rows(response) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/agent_harness/embedding_adapter.rb', line 23

def order_rows(response)
  payload = JSON.parse(response.body)
  rows = payload["data"]
  return unless rows.is_a?(Array)

  indices = rows.map { |row| row["index"] if row.is_a?(Hash) }
  unless indices.all?(Integer) && indices.sort == (0...rows.length).to_a
    raise MalformedEmbeddingError, "Provider returned invalid embedding indices"
  end

  payload["data"] = rows.sort_by { |row| row.fetch("index") }
  response.body = JSON.generate(payload)
rescue JSON::ParserError
  nil
end