AI browser automation lets a Rails app hand a task like “find the price of every plan on this page” to a language model that drives a real browser: it opens pages, follows links and reads the result, instead of you scripting every click. In this post I build a small, working version with RubyLLM and playwright-ruby-client, run it from Active Job, and cover the guardrails that keep it from doing something you didn’t ask for.
When AI Browser Automation Is Worth It
Most data you need from another site doesn’t need an AI at all. If the site has an API, use the API. If the page layout is stable, a plain Playwright or Capybara script is faster, cheaper and deterministic.
An LLM in the loop earns its cost when the steps aren’t known in advance:
- The information is spread over several pages and the path changes between sites.
- You’re pulling the same kind of fact (a price, an opening time, a contact email) from many sites with different layouts.
- An internal tool or legacy admin panel has no API, and the task is described better in words than in selectors.
If you only need clean page text for an AI pipeline, and not navigation, a crawler is simpler. I cover that in grounding Rails AI agents with Firecrawl.
How the Pieces Fit
The design is the same one I use for any AI feature: the model decides what to do, and your Ruby code decides how, through a small set of tools.
- Playwright drives a headless Chromium. The Ruby gem talks to Playwright’s Node.js driver, so the server needs Node.js and the browser installed.
- RubyLLM handles the model and the tool-calling loop. You define tools as Ruby classes; the model picks which one to call and with what arguments, RubyLLM runs it and sends the result back, until the model has an answer.
- Your Rails app owns the browser session, the rules about which sites are allowed, and where the result goes.
The model never gets a raw browser. It gets two narrow tools: open a URL, and click a link by its visible text. Both return the page’s visible text, which is all the model needs to read.
Setting Up the Gems and the Browser
Add the gems:
# Gemfile
gem "ruby_llm", "~> 2.2"
gem "playwright-ruby-client"playwright-ruby-client doesn’t bundle Playwright itself. Install the matching playwright-core version and a browser, as its README describes:
PLAYWRIGHT_CLI_VERSION=$(bundle exec ruby -e 'require "playwright/version"; puts Playwright::COMPATIBLE_PLAYWRIGHT_VERSION')
npm install "playwright-core@$PLAYWRIGHT_CLI_VERSION"
./node_modules/.bin/playwright-core install chromiumThen configure a model provider for RubyLLM:
# config/initializers/ruby_llm.rb
RubyLLM.configure do |config|
config.openai_api_key = ENV.fetch("OPENAI_API_KEY")
endThe Browser Tools
First, a small session object. It holds the Playwright page and enforces the one rule that matters most: the agent can only visit the host you allowed.
# app/models/browser_session.rb
class BrowserSession
attr_reader :page
def initialize(page, allowed_host:)
@page = page
@allowed_host = allowed_host
end
def visit(url)
raise ArgumentError, "Blocked URL: #{url}" unless URI(url).host == @allowed_host
page.goto(url)
end
endThen the two tools. Each one returns either the page text or an error hash, so a failed click becomes something the model can read and recover from instead of an exception that kills the job.
# app/tools/open_page.rb
class OpenPage < RubyLLM::Tool
description "Open a URL and return the page's visible text"
parameter :url, description: "Absolute URL to open"
def initialize(session) = @session = session
def execute(url:)
@session.visit(url)
@session.page.inner_text("body").truncate(4_000)
rescue ArgumentError, Playwright::Error => e
{ error: e.message }
end
end
# app/tools/click_link.rb
class ClickLink < RubyLLM::Tool
description "Click a link by its visible text and return the new page's text"
parameter :text, description: "Exact visible text of the link"
def initialize(session) = @session = session
def execute(text:)
@session.page.get_by_role("link", name: text, exact: true).click
@session.page.inner_text("body").truncate(4_000)
rescue Playwright::Error => e
{ error: e.message }
end
endTruncating the text keeps each tool result small, which keeps token costs and latency down. Clicking by visible link text, rather than letting the model invent CSS selectors, removes a whole class of “selector not found” failures.
Running It from a Background Job
A browser task takes seconds to minutes, so it belongs in Active Job, not in a controller:
# app/jobs/browser_research_job.rb
class BrowserResearchJob < ApplicationJob
queue_as :default
def perform(research)
Playwright.create(playwright_cli_executable_path: Rails.root.join("node_modules/.bin/playwright-core").to_s) do |playwright|
playwright.chromium.launch(headless: true) do |browser|
session = BrowserSession.new(browser.new_page, allowed_host: URI(research.start_url).host)
answer = RubyLLM.chat
.with_tools(OpenPage.new(session), ClickLink.new(session))
.with_instructions("Answer only from what the tools return. Reply in one short paragraph.")
.ask("Open #{research.start_url}. #{research.question}")
research.update!(answer: answer.content)
end
end
end
endThe block form of Playwright.create and launch closes the browser even when the job raises, so a failed run doesn’t leave a Chromium process behind.
I ran the session, both tools and the agent loop as a plain Ruby script with RubyLLM 2.2.3 and playwright-ruby-client 1.65, using a local model (qwen3.5 9B through Ollama) against a two-page test site. Asked for “the price of every plan, including the team plan”, the model called open_page, then click_link with “See team plan”, and answered with all three prices. A request for a URL on another host came back as {error: "Blocked URL: ..."}. I didn’t run the job class inside a Rails app; it’s the same code wrapped in perform.
Guardrails That Matter
A model that can drive a browser can do damage, so keep it on a short leash.
- Allowlist hosts. The
BrowserSession#visitcheck is the most important line in this post. Without it, a page the agent reads can tell it to visit somewhere else. Pages are untrusted input to the model, the same way user text is. - Give it read-only tools. Opening pages and clicking links is enough for research. Don’t add tools that fill forms or submit payments unless a person approves each action.
- Keep credentials out of the prompt. If a task needs a logged-in session, log in with your own Playwright code using Rails credentials, then hand the agent the authenticated page. Never put a password in a message to the model.
- Bound the run. Cap the job’s runtime and how many tool calls it can make, and log every call (tool name, arguments, result size). That log is how you debug a wrong answer and spot a model wandering in circles.
- Check the site’s terms. Automating someone else’s site can break their terms of service even when the data is public. Prefer an official API when one exists.
Running It in Production
Headless Chromium uses a few hundred megabytes of memory per browser, so don’t run many of these jobs in your web process. Put them on a dedicated queue with low concurrency, on a worker that has Node.js and the browser installed. If you deploy with Docker, the browser and its system libraries go in that worker’s image.
If installing a browser on your servers isn’t an option, playwright-ruby-client can also connect to a remote Playwright server with Playwright.connect_to_browser_server, so the Ruby side stays the same.
Before you trust the answers, build a small set of known questions with known answers and run them whenever you change the prompt, the tools or the model. I explain how in LLM evals for Rails.
Frequently asked questions
Do I need Node.js to use Playwright from Ruby?
Yes. playwright-ruby-client is a Ruby client for Playwright’s driver, which runs on Node.js. Install a playwright-core version that matches the gem’s COMPATIBLE_PLAYWRIGHT_VERSION, or connect to a remote Playwright server instead.
Which model should I use for AI browser automation?
Any model with reliable tool calling. I tested this code with a small local model through Ollama and it handled a two-step task. Larger hosted models make fewer wrong turns on messy real sites; measure on your own tasks before you pick.
Can the agent fill in forms or log in for me?
It can if you give it a tool that does that, but I don’t recommend it for anything with side effects. Handle logins in your own code, and require a person’s approval for any action that changes data.
Is AI browser automation better than a normal scraper?
Not when the page structure is stable. A normal Playwright or Capybara script is faster, cheaper and predictable. Use an AI agent when the steps vary between sites or aren’t known in advance.
Conclusion
AI browser automation in Rails comes down to three pieces: Playwright to drive the browser, RubyLLM to run the tool-calling loop, and a background job to keep it out of your web requests. The part that makes it safe is small and boring: a host allowlist, read-only tools, credentials kept out of prompts, and a log of every tool call. Start with one research task you do by hand today, build it with two tools like the ones above, and only add more power when you’ve seen it behave.
If you want AI features like this built into your Rails app, that’s what my AI software development service covers. Book a discovery call to talk through your use case.


