Browse documentation

Ruby SDK

Use nRouter with the ruby-openai gem

Last updated

nRouter works with the ruby-openai gem. Point uri_base at https://api.nrouter.ai/v1 and pass your sk-nrouter-... key — guardrails, caching, and rate-limits auto-apply from your org config.

Installation

gem install ruby-openai

Setup

require "openai"

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

Chat Completion

require "openai"

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

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

Per-Request Overrides

ruby-openai forwards unknown parameters, so nrouter_* fields work inline:

# Run a prompt template with variables
response = client.chat(
  parameters: {
    model: "gpt-5.5",
    messages: [{ role: "user", content: "Summarize Q1 earnings..." }],
    nrouter_prompt_template_id: "your-summarizer-id",
    nrouter_prompt_variables: { language: "Spanish", max_length: "100" },
  }
)

# Bypass cache for a single call
response = client.chat(
  parameters: {
    model: "gpt-5.5",
    messages: [{ role: "user", content: "What is the latest news?" }],
    nrouter_cache: false,
  }
)

Guardrails are not among these fields. You assign them in the dashboard at key, team, or organization scope — the narrowest scope that mentions a guardrail wins — and they run automatically on every request that scope covers.

Error Handling

begin
  client.chat(
    parameters: {
      model: "gpt-5.5",
      messages: [{ role: "user", content: "My SSN is 123-45-6789" }],
    }
  )
rescue => e
  # "guardrail_blocked" — guardrail rejected the request
  # "insufficient_credits" — top up to continue
  puts "Error: #{e.message}"
end

Response Headers

Every successful response carries:

  • x-nr-request-id — id for this call, and the join key for its spend row
  • x-nr-model — the model that actually served the request
  • x-nr-cost-statusexact when we priced the call, unpriced when we could not
  • x-nr-request-cost — USD spend for this call. Absent when x-nr-cost-status is unpriced: nRouter never reports a cost of 0 for a call it could not price
  • x-nr-input-tokens, x-nr-output-tokens, x-nr-total-tokens — token counts as reported by the provider

Next Steps

Was this page helpful?