Method: OpenRouter::Client#complete

Defined in:
lib/open_router/client.rb

#complete(messages, model: "openrouter/auto", providers: [], transforms: [], extras: {}, stream: nil) ⇒ Hash

Performs a chat completion request to the OpenRouter API.

Parameters:

  • messages (Array<Hash>)

    Array of message hashes with role and content, like [“user”, content: “What is the meaning of life?”]

  • model (String|Array) (defaults to: "openrouter/auto")

    Model identifier, or array of model identifiers if you want to fallback to the next model in case of failure

  • providers (Array<String>) (defaults to: [])

    Optional array of provider identifiers, ordered by priority

  • transforms (Array<String>) (defaults to: [])

    Optional array of strings that tell OpenRouter to apply a series of transformations to the prompt before sending it to the model. Transformations are applied in-order

  • extras (Hash) (defaults to: {})

    Optional hash of model-specific parameters to send to the OpenRouter API

  • stream (Proc, nil) (defaults to: nil)

    Optional callable object for streaming

Returns:

  • (Hash)

    The completion response.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/open_router/client.rb', line 31

def complete(messages, model: "openrouter/auto", providers: [], transforms: [], extras: {}, stream: nil)
  parameters = { messages: }
  if model.is_a?(String)
    parameters[:model] = model
  elsif model.is_a?(Array)
    parameters[:models] = model
    parameters[:route] = "fallback"
  end
  parameters[:provider] = { provider: { order: providers } } if providers.any?
  parameters[:transforms] = transforms if transforms.any?
  parameters[:stream] = stream if stream
  parameters.merge!(extras)

  post(path: "/chat/completions", parameters:).tap do |response|
    raise ServerError, response.dig("error", "message") if response.presence&.dig("error", "message").present?
    raise ServerError, "Empty response from OpenRouter. Might be worth retrying once or twice." if stream.blank? && response.blank?

    return response.with_indifferent_access if response.is_a?(Hash)
  end
end