DEVSAIO

Call AI models from Ruby (net/http)

A small Ruby helper for chat completions with any DEVSAIO model, plus a Rails usage tip.

DEVSAIO team · 1 min read
Share on X
ruby
require "net/http"
require "json"

def ai_chat(prompt, model: "claude-sonnet-4-6", max_tokens: 800)
  uri = URI("https://devsaio.lol/v1/chat/completions")
  req = Net::HTTP::Post.new(uri, {
    "Authorization" => "Bearer #{ENV.fetch('DEVSAIO_API_KEY')}",
    "Content-Type" => "application/json"
  })
  req.body = { model: model, max_tokens: max_tokens, messages: [{ role: "user", content: prompt }] }.to_json
  res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: 120) { |h| h.request(req) }
  data = JSON.parse(res.body)
  raise "AI error #{res.code}: #{data.dig('error', 'message')}" unless res.is_a?(Net::HTTPSuccess)
  data.dig("choices", 0, "message", "content")
end

puts ai_chat("Suggest 5 names for a Ruby gem that parses invoices.")

In Rails

Put the key in Rails credentials or an environment variable, wrap the helper in a service object, and call it from a background job (Sidekiq, Solid Queue) so slow AI responses never block a web request.

The popular ruby-openai gem also supports a custom uri_base if you prefer a library.

Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading