Rails

Ruby on Rails with an OpenAI-compatible uncensored API

Use Abliterator from Rails with the official openai gem: a client in an initializer, a JSON action, SSE streaming with ActionController::Live, and Active Job retries.

Reviewed RailsRuby

Quick answer

Add the openai gem, create OpenAI::Client.new(api_key: ENV.fetch("ABL_API_KEY"), base_url: "https://abliterator.ai/v1") in config/initializers, and stream with chat.completions.stream_raw inside an ActionController::Live action.

The official openai Ruby gem accepts a base_url, so it talks to Abliterator with no patches. Rails supplies the rest: an initializer for the client, ActionController::Live for streaming and Active Job for background work. The gem needs Ruby 3.3+, which was not available on the machine used to check this page, so the snippets were syntax-checked with ruby -c and compared line by line against the gem's source and README.

Install

bundle add openai
export ABL_API_KEY="sk-abl-v1-..."

Create config/initializers/abl.rb:

LLM = OpenAI::Client.new(
  api_key: ENV.fetch("ABL_API_KEY"),
  base_url: "https://abliterator.ai/v1",
  timeout: 120,
  max_retries: 2
)

One client per process is enough; it pools connections internally. Prefer Rails.application.credentials over the environment if that is how your app stores secrets.

A JSON action

class ExplanationsController < ApplicationController
  def create
    completion = LLM.chat.completions.create(
      model: "deepseek-v4.1-flash-abliterated",
      max_tokens: 500,
      messages: [
        {role: "system", content: "Explain web server log lines to a junior analyst: normal or suspicious, and why."},
        {role: "user", content: params.require(:line)}
      ]
    )
    render json: {
      explanation: completion.choices.first.message.content,
      cost: completion.usage[:cost]
    }
  end
end

Stream with ActionController::Live

stream_raw returns an enumerable of ChatCompletionChunk objects. Write each delta to the response stream as an SSE event:

class ReportsController < ApplicationController
  include ActionController::Live

  def stream
    response.headers["Content-Type"] = "text/event-stream"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Last-Modified"] = Time.now.httpdate

    chunks = LLM.chat.completions.stream_raw(
      model: "kimi-k3.1-pro-abliterated",
      messages: [{role: "user", content: "Write a tabletop exercise for a ransomware attack on a hospital's scheduling system."}]
    )
    chunks.each do |chunk|
      text = chunk.choices.first&.delta&.content
      response.stream.write("data: #{text.to_json}\n\n") if text
    end
    response.stream.write("data: [DONE]\n\n")
  rescue ActionController::Live::ClientDisconnected
    logger.info("client left the report stream")
  ensure
    response.stream.close
  end
end

The Last-Modified header stops Rack::ETag from buffering the body to compute an ETag. Live actions run in their own thread, so the database connection they use must be returned; avoid long ActiveRecord work inside the loop.

Background labeling with Active Job

Long or bulk calls belong in a job. retry_on handles Abliterator's 429s with backoff instead of failing the job:

class LabelTicketJob < ApplicationJob
  queue_as :default
  retry_on OpenAI::Errors::RateLimitError, wait: :polynomially_longer, attempts: 6
  retry_on OpenAI::Errors::APIConnectionError, wait: 10.seconds, attempts: 3

  def perform(ticket_id, text)
    completion = LLM.chat.completions.create(
      model: "deepseek-v4.1-flash-abliterated",
      max_tokens: 5,
      messages: [
        {role: "system", content: "Label this security ticket: phishing, malware, account_takeover or other. One word."},
        {role: "user", content: text}
      ]
    )
    label = completion.choices.first.message.content.strip
    Rails.logger.info("ticket #{ticket_id} labeled #{label}")
  end
end

Enqueue with LabelTicketJob.perform_later(ticket.id, ticket.body). Limit worker concurrency to stay under your plan's concurrent requests (/docs/rate-limits).

Troubleshooting

  • KeyError: key not found: "ABL_API_KEY" at boot. The initializer runs for every process, including rails assets:precompile in CI. Set the variable there too, or use ENV["ABL_API_KEY"] and check it at call time.
  • The stream arrives in one block. Some middleware buffers. Keep the Last-Modified header, avoid Rack::Deflater on the route, and turn off proxy buffering.
  • Puma threads run out during streams. Each Live stream holds a Puma thread until it ends. Size max_threads for your expected concurrent streams.
  • 404 Not Found. base_url must be https://abliterator.ai/v1; the gem appends chat/completions to it.
  • ArgumentError: Please use #create for the non-streaming use case. You passed stream: false to stream_raw. Drop the flag.

Frequently asked questions

Should I use the openai gem or ruby-openai?

This page uses the official openai gem from OpenAI, which takes base_url and api_key. The community ruby-openai gem also works with Abliterator through its uri_base option, but its method names differ.

Which Ruby version does the openai gem need?

Ruby 3.3 or later, according to the gem's README. Rails 8 apps already meet that.

How do I read Abliterator's cost field from Ruby?

The gem exposes fields it does not model through hash-style access, so completion.usage[:cost] returns the USD cost Abliterator reports.