Class: Google::ADK::OpenRouterClient

Inherits:
Object
  • Object
show all
Defined in:
lib/google/adk/clients/openrouter_client.rb

Overview

Client for interacting with OpenRouter’s OpenAI-compatible API

Constant Summary collapse

API_BASE_URL =
"https://openrouter.ai/api/v1"
DEFAULT_MODEL =
"openrouter/auto"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil) ⇒ OpenRouterClient

Returns a new instance of OpenRouterClient.

Raises:



16
17
18
19
20
21
22
23
24
25
# File 'lib/google/adk/clients/openrouter_client.rb', line 16

def initialize(api_key: nil)
  @api_key = api_key || ENV["OPENROUTER_API_KEY"]
  raise ConfigurationError, "OPENROUTER_API_KEY not set" unless @api_key
  
  @client = Faraday.new(API_BASE_URL) do |conn|
    conn.request :json
    conn.response :json
    conn.adapter Faraday.default_adapter
  end
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



14
15
16
# File 'lib/google/adk/clients/openrouter_client.rb', line 14

def api_key
  @api_key
end

Instance Method Details

#generate_content(model:, messages:, tools: nil, system_instruction: nil) ⇒ Hash

Generate content using OpenRouter API

Parameters:

  • model (String)

    Model name (e.g., “openrouter/auto”, “anthropic/claude-3-haiku”)

  • messages (Array<Hash>)

    Conversation messages

  • tools (Array<Hash>) (defaults to: nil)

    Available tools (optional)

  • system_instruction (String) (defaults to: nil)

    System instruction (optional)

Returns:

  • (Hash)

    API response formatted to match Gemini response structure



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/google/adk/clients/openrouter_client.rb', line 34

def generate_content(model:, messages:, tools: nil, system_instruction: nil)
  url = "/chat/completions"
  
  # Convert messages to OpenAI format
  openai_messages = format_messages(messages)
  
  # Add system message if provided
  if system_instruction
    openai_messages.unshift({
      role: "system",
      content: system_instruction
    })
  end
  
  payload = {
    model: model || DEFAULT_MODEL,
    messages: openai_messages,
    max_tokens: 8192,
    temperature: 0.7,
    top_p: 0.95
  }
  
  # Add tools if provided
  if tools && !tools.empty?
    payload[:tools] = format_tools(tools)
    payload[:tool_choice] = "auto"
  end
  
  response = @client.post(url) do |req|
    req.headers["Authorization"] = "Bearer #{@api_key}"
    req.headers["Content-Type"] = "application/json"
    req.headers["HTTP-Referer"] = "https://github.com/google-adk"
    req.headers["X-Title"] = "Google ADK Client"
    req.body = payload
  end
  
  handle_response(response)
end