Class: ActiveHarness::Providers::OpenRouter

Inherits:
Base
  • Object
show all
Defined in:
lib/active_harness/providers/openrouter.rb

Overview

OpenRouter — OpenAI-compatible API that proxies many models.

Constant Summary collapse

API_URL =
URI("https://openrouter.ai/api/v1/chat/completions")

Constants inherited from Base

Base::HTTP, Base::STREAMING_HTTP

Instance Method Summary collapse

Instance Method Details

#call(model:, messages:, temperature: 0.7, stream: nil) ⇒ Hash

Returns { content:, provider:, model: }.

Parameters:

  • model (String)
  • messages (Array<Hash>)
    content:, …
  • temperature (Float) (defaults to: 0.7)
  • stream (Proc, nil) (defaults to: nil)

    if given, called with each token as it arrives

Returns:

  • (Hash)

    { content:, provider:, model: }



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/active_harness/providers/openrouter.rb', line 14

def call(model:, messages:, temperature: 0.7, stream: nil)
  headers = {
    "Content-Type"  => "application/json",
    "Authorization" => "Bearer #{api_key}",
    "HTTP-Referer"  => "https://github.com/the-teacher/ActiveHarness"
  }
  body = { model: model, messages: messages, temperature: temperature }

  if stream
    body[:stream] = true
    content = post_json_stream(API_URL, headers: headers, body: body, on_token: stream)
    return { content: content, provider: :openrouter, model: model }
  end

  raw  = post_json(API_URL, headers: headers, body: body)
  data = parse!(raw)
  handle_error!(data)

  {
    content:  data.dig("choices", 0, "message", "content").to_s.strip,
    provider: :openrouter,
    model:    data["model"] || model,
    usage:    extract_usage_openai(data)
  }
end