Skip to content
RailsDev.io

Ruby on Rails AI Integration: A Practical Guide for Rails 8 with RubyLLM

Ruby on Rails AI integration with RubyLLM 2.1 on Rails 8: chat history, tools, human approval, RAG with pgvector and streaming, with code I ran end to end.

Hendra NicholasRails Full-Stack Developer & AI Engineer

Updated 13 min read

Architecture diagram: the browser posts a message to a Rails controller, a Solid Queue job runs a RubyLLM support agent that calls the model API and three tools (order lookup, refund with human approval, help article search on pgvector), and Turbo Streams send the reply back to the browser
On this page
  1. What an AI feature in Rails is made of
  2. Choosing a gem for Rails AI integration
  3. Step 1: Install RubyLLM and store your API keys
  4. Step 2: Save conversations with acts_as_chat
  5. Step 3: Define an agent with clear instructions
  6. Step 4: Give the model tools, scoped to the current user
  7. Step 5: Ask a human before the model takes an action
  8. Step 6: Answer from your own content with RAG and pgvector
  9. Step 7: Run replies in a background job and stream them with Turbo
  10. Production checklist
  11. Conclusion
  12. Frequently asked questions

Ruby on Rails AI integration means your Rails app sends prompts to a large language model (LLM) such as Claude or GPT, usually through a gem like RubyLLM, and handles the answers like any other data: it saves them with Active Record, runs the slow calls in background jobs and streams the output with Turbo. You don’t need a separate Python service. Rails already has the parts an AI feature depends on: users, permissions, your data, jobs and real-time UI.

This guide builds one realistic feature step by step: a customer support assistant inside a Rails 8 app. It answers from your help center, looks up the customer’s own orders, asks a human before it issues a refund and streams its replies to the browser. It’s for Rails developers who have to build this, and for CTOs and product owners who want to know what goes into it before they commit.

I ran every example in this article on Rails 8.1.4, Ruby 4.0.8, RubyLLM 2.1.1, neighbor 1.2.0 and PostgreSQL 18 with pgvector 0.8.7. To run them without paid API keys, I pointed RubyLLM at local models through Ollama (qwen3:4b for chat, nomic-embed-text for embeddings). The Claude and OpenAI model names below come from RubyLLM’s model registry; I didn’t call those APIs for this article.

What an AI feature in Rails is made of

Most “add AI to our app” projects need the same building blocks. Rails already has most of them:

Building block What it does Rails piece
Model client Sends prompts to Claude, OpenAI, Gemini… A gem (RubyLLM in this guide)
Conversation history Keeps chats and messages between requests Active Record models
Background work Keeps 10–60 second model calls out of requests Active Job with Solid Queue
Streaming Shows the answer as it’s written Turbo Streams over Action Cable
Tools Lets the model read data or take actions Ruby classes that use your models
Retrieval (RAG) Answers from your own documents PostgreSQL with pgvector
Guardrails Limits what the model can see and do Your authorization code and approval steps

The model itself is the smallest part of the work. Most of the effort, and most of the risk, sits in the parts around it: which data a tool can see, what happens when a call times out, and who approves an action.

Choosing a gem for Rails AI integration

You have four realistic options in Ruby as of November 2026:

Gem Best for Notes
ruby_llm Most Rails apps One API for many providers, Rails persistence, agents, tools, embeddings. MIT. v2.1.1.
anthropic / openai Using one provider’s newest features first Official SDKs, Apache-2.0. No Rails persistence; you build that part yourself.
ruby-openai Existing apps that already use it Popular community gem. Last release was 8.3.0 in August 2025.
langchainrb Existing LangChain-style code Last release was 0.19.5 in May 2025.

I use RubyLLM for most client work. It’s built around Rails: acts_as_chat saves conversations to your own tables, and its agents, tools and approvals keep working across requests and jobs. Version 2.0 (September 2026) supports 17 providers, so you can move from OpenAI to Claude by changing a model name. The official Anthropic and OpenAI SDKs are a good choice when you need a provider feature on the day it ships and you’re happy to write the persistence yourself.

Step 1: Install RubyLLM and store your API keys

Add the gem and run its installer:

bash
bundle add ruby_llm
bin/rails generate ruby_llm:install
bin/rails db:migrate
bin/rails ruby_llm:load_models

The installer creates Chat and Message models, which your app owns, plus a few tables RubyLLM manages itself (ruby_llm_models, ruby_llm_tool_calls, ruby_llm_usages and others). It also sets up Active Storage so messages can carry file attachments. load_models fills the model registry, which RubyLLM uses to know each model’s provider, capabilities and price.

Keep keys in Rails credentials (bin/rails credentials:edit), not in the code:

ruby
# config/initializers/ruby_llm.rb
RubyLLM.configure do |config|
  config.anthropic_api_key = Rails.application.credentials.dig(:anthropic, :api_key)
  config.openai_api_key = Rails.application.credentials.dig(:openai, :api_key)

  config.default_model = "claude-sonnet-5-5"
  config.default_embedding_model = "text-embedding-3-small"

  config.request_timeout = 120
  config.max_retries = 3
end

I set both keys here because many apps use one provider for chat and another for embeddings.

Step 2: Save conversations with acts_as_chat

The generated models are short:

ruby
# app/models/chat.rb
class Chat < ApplicationRecord
  acts_as_chat
  belongs_to :user
end

I added belongs_to :user with a normal migration (add_reference :chats, :user), because every chat in a real app belongs to someone. Now a conversation is a record:

ruby
chat = Chat.create!(user: user, model: "claude-sonnet-5-5")
chat.ask("In one sentence, what is Ruby on Rails?")
chat.messages.count # => 2

ask saves the user message, calls the model and saves the reply. You can render, search and delete these like any other records, which matters for support history, audits and data-retention rules.

Step 3: Define an agent with clear instructions

An agent holds the model choice, instructions and tools in one class, so every controller and job uses the same setup:

ruby
# app/agents/support_agent.rb
class SupportAgent < RubyLLM::Agent
  chat_model Chat
  model "claude-sonnet-5-5"
  instructions <<~PROMPT
    You are the customer support assistant for an online store.
    Answer policy questions only from help_article_search results.
    Look orders up with order_lookup before discussing them.
    If you can't find the answer, say so and offer a human agent.
  PROMPT

  tools do
    [
      OrderLookup.new(user: chat.user),
      IssueRefund.new(user: chat.user),
      HelpArticleSearch
    ]
  end
end

SupportAgent.create!(user: current_user) creates a Chat record with these instructions saved, and SupportAgent.find(id) loads it again with the tools attached. The tools block is lazy: it runs for each chat, so every tool gets that chat’s user. That’s the key security decision in this design, and the next step shows why.

Step 4: Give the model tools, scoped to the current user

A tool is a Ruby class the model can call. This one reads an order:

ruby
# app/tools/order_lookup.rb
class OrderLookup < RubyLLM::Tool
  description "Looks up one of the customer's orders by its order number"
  parameter :number, description: "Order number, e.g. A-1042"

  def initialize(user:)
    @user = user
  end

  def execute(number:)
    order = @user.orders.find_by(number: number)
    return { error: "No order #{number} on this account" } unless order

    {
      number: order.number,
      status: order.status,
      total: format("$%.2f", order.total_cents / 100.0),
      refundable: order.refundable?
    }
  end
end

The important line is @user.orders.find_by, not Order.find_by. The model decides which order number to ask for, and a user can type anything into the chat, including someone else’s order number or “ignore your instructions”. Your Ruby code decides what that user may see. In my test, asking about an order that belonged to another account got the reply “I couldn’t find order B-7 in your account”, because the tool never loaded it.

Return a small hash with only the fields the model needs. Everything you return goes into the prompt, so it costs tokens and it can end up in the answer.

Step 5: Ask a human before the model takes an action

Reading data is low risk. Changing it isn’t. RubyLLM 2 lets a tool wait for approval:

ruby
# app/tools/issue_refund.rb
class IssueRefund < RubyLLM::Tool
  description "Refunds a delivered order in full"
  parameter :number, description: "Order number to refund"
  requires_approval

  def initialize(user:)
    @user = user
  end

  def execute(number:)
    order = @user.orders.find_by(number: number)
    return { error: "Order #{number} can't be refunded" } unless order&.refundable?

    order.update!(status: "refunded", refunded_at: Time.current)
    { refunded: order.number }
  end
end

When the customer writes “Please refund my order A-1042”, the model calls issue_refund, but nothing runs yet:

ruby
chat.ask("Please refund my order A-1042.")
chat.awaiting_approval? # => true
chat.pending_approvals.map { |call| [call.name, call.arguments] }
# => [["issue_refund", {"number" => "A-1042"}]]

The pending call is saved in the database. A support agent can review it later, in a different request, and approve or deny it:

ruby
chat = SupportAgent.find(chat_id)
chat.approve(chat.pending_approvals.first)
chat.complete

complete runs the refund and lets the model write the confirmation. If you call deny instead, the model is told the request was denied and replies to the customer. Use this for anything that moves money, sends email or deletes data.

Step 6: Answer from your own content with RAG and pgvector

Retrieval-augmented generation (RAG) means you search your own content first and give the best matches to the model, so it answers from your policies instead of guessing. In Rails you can do this inside PostgreSQL with the pgvector extension and the neighbor gem:

bash
bundle add neighbor
bin/rails generate neighbor:vector
ruby
# db/migrate/20261103070602_create_help_articles.rb
class CreateHelpArticles < ActiveRecord::Migration[8.1]
  def change
    create_table :help_articles do |t|
      t.string :title, null: false
      t.text :body, null: false
      t.vector :embedding, limit: 1536 # text-embedding-3-small
      t.timestamps
    end
    add_index :help_articles, :embedding,
      using: :hnsw, opclass: :vector_cosine_ops
  end
end

The limit must match your embedding model’s output size: 1,536 for text-embedding-3-small, 768 for the nomic-embed-text model I used locally. If you change embedding models later, you have to re-embed every row.

Each article generates its embedding whenever its text changes:

ruby
# app/models/help_article.rb
class HelpArticle < ApplicationRecord
  has_neighbors :embedding

  before_save :embed, if: -> { title_changed? || body_changed? }

  private

  def embed
    self.embedding = RubyLLM.embed("#{title}\n\n#{body}").vectors
  end
end

The search tool finds the closest articles and returns them as RubyLLM::SearchResults, which lets the model cite each source:

ruby
# app/tools/help_article_search.rb
class HelpArticleSearch < RubyLLM::Tool
  description "Searches the help center for policies and how-to answers"
  parameter :query, description: "What the customer wants to know"

  def execute(query:)
    embedding = RubyLLM.embed(query).vectors
    articles = HelpArticle
      .nearest_neighbors(:embedding, embedding, distance: "cosine")
      .first(3)

    RubyLLM::SearchResults.new(
      *articles.map { |a| { title: a.title, text: a.body.truncate(800) } }
    )
  end
end

With three short articles loaded, the question “How many days do I have to ask for a refund?” made the model call help_article_search and answer “30 days from the delivery date”, which is the number in the refund policy article. For a real help center, split long articles into sections of a few paragraphs before embedding them. Smaller pieces give the model more focused context. My Rails pgvector guide covers chunking, filtering by account and hybrid search in detail.

Step 7: Run replies in a background job and stream them with Turbo

A model reply can take 10 seconds or more, and longer when tools run. Don’t make a web request wait for that. The controller saves the user’s message and hands the rest to a job:

ruby
# app/controllers/messages_controller.rb
class MessagesController < ApplicationController
  def create
    chat = current_user.chats.find(params[:chat_id])
    chat.add_message(role: :user, content: params.expect(:content))
    SupportReplyJob.perform_later(chat.id)

    head :accepted
  end
end

The job runs the agent and pushes each piece of text to the browser as it arrives:

ruby
# app/jobs/support_reply_job.rb
class SupportReplyJob < ApplicationJob
  queue_as :default

  def perform(chat_id)
    chat = SupportAgent.find(chat_id)

    chat.complete do |chunk|
      # Thinking chunks arrive with empty content
      next if chunk.content.to_s.empty?

      chat.messages.last.broadcast_append_chunk(chunk.content)
    end
  end
end

RubyLLM creates the assistant message before the first chunk arrives, so chat.messages.last is a stable target. When the model calls a tool first, RubyLLM saves a new assistant message for the final answer, and in my tests the chunks went to that new message. Note the to_s.empty? check: models that “think” before answering stream chunks whose content is an empty string, and in Ruby an empty string is truthy, so next unless chunk.content wouldn’t skip them.

The Message model broadcasts new messages and each chunk:

ruby
# app/models/message.rb
class Message < ApplicationRecord
  include ActionView::RecordIdentifier

  acts_as_message
  has_many_attached :attachments

  after_create_commit :broadcast_to_chat, if: -> { role.in?(%w[user assistant]) }

  def broadcast_to_chat
    broadcast_append_to [chat, :messages], target: "messages",
      partial: "messages/message", locals: { message: self }
  end

  def broadcast_append_chunk(text)
    broadcast_append_to [chat, :messages],
      target: dom_id(self, :content),
      html: ERB::Util.html_escape(text)
  end
end

Two details I hit while testing:

  • Escape model output. html: inserts raw HTML, and model output is user-influenced text. ERB::Util.html_escape keeps a reply that contains <script> from running in your page.
  • Name the partial. RubyLLM 2 messages render a partial per role (messages/_user, messages/_assistant, messages/_tool_calls). If you have one shared messages/_message partial, pass it explicitly, or Rails raises ActionView::MissingTemplate.

The view subscribes to the stream and renders the conversation:

erb
<%# app/views/chats/show.html.erb %>
<%= turbo_stream_from @chat, :messages %>

<div id="messages">
  <%= render partial: "messages/message", as: :message,
    collection: @chat.messages.where(role: %w[user assistant]) %>
</div>

<%= form_with url: chat_messages_path(@chat) do |f| %>
  <%= f.text_area :content, required: true %>
  <%= f.submit "Send" %>
<% end %>
erb
<%# app/views/messages/_message.html.erb %>
<div id="<%= dom_id(message) %>" class="message <%= message.role %>">
  <strong><%= message.role.capitalize %></strong>
  <p id="<%= dom_id(message, :content) %>"><%= message.content %></p>
</div>

If you’d rather start from generated code, bin/rails generate ruby_llm:chat_ui creates a complete chat UI with controllers, views and a streaming job. It’s a good way to see the conventions before you write your own.

Production checklist

The tutorial code works. These are the things I check before an AI feature goes live in a client’s app:

  • Authorization in every tool. Tools load records through the current user or account, never with a global find.
  • Approval for actions. Anything that changes money, data or sends messages uses requires_approval.
  • Timeouts and retries. request_timeout and max_retries are set, and the job has a retry policy that won’t repeat a side effect. RubyLLM’s docs note that tools must tolerate retries if a process stops before it saves the tool’s result.
  • Cost tracking. RubyLLM 2 records token usage and cost per attempt in ruby_llm_usages. Put a dashboard or a daily alert on it before launch, not after the first invoice.
  • Limits per user. Rate-limit the messages endpoint (Rails 8 has rate_limit in controllers) so one user can’t run up your bill.
  • Data you send. Decide which fields leave your servers, check your provider’s data-retention terms, and keep personal data out of prompts when the task doesn’t need it.
  • Escaped output. Model text goes through html_escape or a Markdown renderer with sanitization.
  • Tests and evals. Unit-test tools like any Ruby class. For the model’s behavior, keep a small set of real questions with expected answers and run it whenever you change the prompt, model or retrieval. RubyLLM includes evaluation helpers for this.

If you’re adding AI to a Rails app that already has years of business logic, the hard part is usually this list, not the model call. It’s also where I spend most of my time on AI integration projects.

Two adjacent builds: my Rails MCP server guide and Agent Skills for Rails.

Conclusion

Ruby on Rails AI integration doesn’t need a second stack. With RubyLLM, a chat is an Active Record model, an agent is a Ruby class, tools are plain objects that use your existing authorization, and Solid Queue and Turbo handle the slow, streaming parts. Start with one narrow feature, such as answering support questions from your help center, scope every tool to the current user, and add approvals before you let the model change anything.

I build AI features into existing Rails apps: assistants that answer from your own data, agents that call your APIs with limited access and human approval, and the cost tracking and evals that keep them reliable after launch. If you’re deciding where AI fits in your product, send me a short brief and book a discovery call.

Frequently asked questions

Can Ruby on Rails be used for AI?

Yes. Rails apps use AI by calling model APIs such as Claude, OpenAI or Gemini, and Ruby has mature gems for that. You don’t train models in Rails, but most product features don’t need training: they need a good prompt, your data and a safe way to act on the answer, which is what Rails is good at.

Do I need Python to add AI to a Rails app?

No, not for chat, tools, embeddings or RAG. RubyLLM, the official Anthropic and OpenAI gems, and pgvector cover these in Ruby. Python makes sense when you train or fine-tune your own models, or need a library that only exists in Python; then run it as a small separate service and call it from Rails.

RubyLLM vs LangChain: which should I use in Rails?

For a new Rails app, I recommend RubyLLM. It has Rails persistence built in, it’s actively released (2.1.1 in October 2026), and it covers agents, tools, RAG and evals. langchainrb hasn’t had a release since May 2025, and Python’s LangChain would mean running a second service.

Which LLM should I use with Rails?

Start with a strong general model from Anthropic or OpenAI to prove the feature works, then test cheaper or faster models against the same questions. Because RubyLLM uses one API for all providers, switching is usually a one-line change to the model name. Self-hosted models through Ollama are an option when data can’t leave your servers, but expect weaker tool use from small models.

How do I stream ChatGPT or Claude responses in Rails?

Run the model call in a background job, pass a block to complete or ask, and broadcast each chunk with Turbo Streams to a target element. The user’s browser subscribes with turbo_stream_from. Step 7 above has the full code, including the empty-chunk check that thinking models need.

How much does it cost to add AI to a Rails app?

It depends on three things: the engineering work (mostly tools, permissions and testing, not the model call), the model’s price per token, and how much text each request sends. RAG and long chat histories make each request bigger. Track real usage from the first test users, because estimates made before launch are often wrong.

Is it safe to let an AI model call my Rails code?

It’s as safe as the tools you write. The model only chooses which tool to call and with which arguments; your Ruby code decides what’s allowed. Scope every query to the current user, return only the fields needed, require approval for actions, and treat everything the model writes as untrusted input.

Keep reading