Developers

Call Claude, GPT and Gemini from Ruby

Ruby's standard Net::HTTP library can call the Somnus endpoint directly, which fits Rails background jobs well.

Install

bash
(no install — standard library)

Basic request

ruby
require "net/http"
require "json"

uri = URI("https://gateway-production-c837.up.railway.app/v1/chat/completions")
req = Net::HTTP::Post.new(uri, {
  "Authorization" => "Bearer #{ENV.fetch("SOMNUS_API_KEY")}",
  "Content-Type" => "application/json",
})
req.body = <<~JSON
{
  "model": "claude-sonnet-5",
  "messages": [
    {"role": "user", "content": "Explain recursion in one sentence."}
  ]
}
JSON
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
puts JSON.parse(res.body).dig("choices", 0, "message", "content")

Streaming

ruby
require "net/http"
require "json"

uri = URI("https://gateway-production-c837.up.railway.app/v1/chat/completions")
req = Net::HTTP::Post.new(uri, {
  "Authorization" => "Bearer #{ENV.fetch("SOMNUS_API_KEY")}",
  "Content-Type" => "application/json",
})
req.body = <<~JSON
{
  "model": "claude-sonnet-5",
  "messages": [
    {"role": "system", "content": "You are a friendly, concise assistant."},
    {"role": "user", "content": "Write a haiku about the sea."}
  ],
  "stream": true
}
JSON
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
puts JSON.parse(res.body).dig("choices", 0, "message", "content")

JSON output

ruby
require "net/http"
require "json"

uri = URI("https://gateway-production-c837.up.railway.app/v1/chat/completions")
req = Net::HTTP::Post.new(uri, {
  "Authorization" => "Bearer #{ENV.fetch("SOMNUS_API_KEY")}",
  "Content-Type" => "application/json",
})
req.body = <<~JSON
{
  "model": "claude-sonnet-5",
  "messages": [
    {"role": "system", "content": "Reply only with JSON."},
    {"role": "user", "content": "Return {\"city\": ..., \"country\": ...} for the Eiffel Tower."}
  ],
  "response_format": {"type": "json_object"}
}
JSON
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
puts JSON.parse(res.body).dig("choices", 0, "message", "content")

Ruby notes

  • Run AI calls in background jobs, not in the request cycle.
  • Keep the key in Rails credentials or ENV.
  • Parse responses with JSON.parse.

Questions

Which models can I use?

Any of the 50+ models on Somnus — change the model string. The examples use claude-sonnet-5.

Where do I get a key?

Create an account, and your key appears in the dashboard with $5 of free credit.

Run this code with free credit

Create an account and get $5 of free API credit — enough to try every example on this page.

Get $5 free credit

Related

Browse more: Alternatives · Compare · Use cases · Developers · Solutions · Tools

WindowsStart with $5 free