Browse documentation

Ruby SDK

Connect Ruby applications to nRouter using the ruby-openai gem with custom base URI settings, virtual keys, server-side guardrails, and budget ceilings.

Connect Ruby and Rails applications to the nRouter unified AI gateway (https://api.nrouter.ai/v1) using the standard ruby-openai gem. Configure NROUTER_API_KEY authentication, stream tokens in real-time with blocks, and inspect x-nr-* gateway headers for live cost and latency tracking.

Installation

Add to your Gemfile and run bundle install:

gem "ruby-openai"

Set your virtual API key in your environment:

export NROUTER_API_KEY="sk-nrouter-xxxxxxxxxxxx"

Chat Completion

Point uri_base to https://api.nrouter.ai/v1:

require "openai"

client = OpenAI::Client.new(
  access_token: ENV.fetch("NROUTER_API_KEY"),
  uri_base: "https://api.nrouter.ai/v1",
)

response = client.chat(
  parameters: {
    model: "gpt-5.4-mini",
    messages: [{ role: "user", content: "Hello, nRouter!" }],
  }
)

puts response.dig("choices", 0, "message", "content")

SSE Streaming

Stream tokens chunk-by-chunk using a Ruby block:

require "openai"

client = OpenAI::Client.new(
  access_token: ENV.fetch("NROUTER_API_KEY"),
  uri_base: "https://api.nrouter.ai/v1",
)

client.chat(
  parameters: {
    model: "claude-haiku-4-5-20251001",
    messages: [{ role: "user", content: "Write a short poem." }],
    stream: proc { |chunk| print chunk.dig("choices", 0, "delta", "content") }
  }
)
puts

Error Handling

Gateway refusals surface as Faraday errors — see Errors & Rate Limits:

begin
  response = client.chat(parameters: { model: "gpt-5.4-mini", messages: [{ role: "user", content: "Hello" }] })
rescue Faraday::ClientError => e
  puts "Client error [#{e.response[:status]}]: #{e.response[:body]}"
rescue Faraday::ServerError => e
  puts "Server error: #{e.message}"
end

Next Steps

Was this page helpful?