Getting Started
Install RubyLLM and build a small support desk with chats, tools, agents, structured output, and audio and document processing.
After reading this guide, you will know:
- How to install and configure RubyLLM.
- How to chat with a model, stream its answer, and ask about files.
- How to get structured data back and read what a request cost.
- How to give the model tools and put them in an agent.
- How to transcribe audio, read documents, moderate messages, search with embeddings and reranking, and generate images, video, and speech.
- How to save conversations in Rails.
This guide builds pieces of a support desk for Acme Outfitters, an online clothing store. Customers write in about orders, returns, and invoices, and RubyLLM helps answer them. Each section shows one feature in a few lines. The rest of Start Here builds on the same example, one guide per feature.
Installation
Add RubyLLM 2.2 with Bundler:
bundle add ruby_llm --version 2.2.2
For an existing 1.x application, use the 1.x docs or follow the upgrade guide before switching versions.
RubyLLM works with JSON 2 and JSON 3. JSON 3 rejects an option that older Rails versions pass to it. Rails 7.2.4 and 8.1.3 removed that option. On earlier versions, and on Rails 8.0, keep JSON 2 in your Gemfile:
gem "json", "< 3"
Configuring a Provider
Start with an OpenAI API key. Put this at the top of your script, or in config/initializers/ruby_llm.rb in Rails:
require "ruby_llm"
RubyLLM.configure do |config|
config.openai_api_key = ENV.fetch("OPENAI_API_KEY")
end
Most examples here use OpenAI. The video, OCR, and reranking examples add the keys they need. Configure only the providers you use; see Configuration for the others and for local models.
Your First Chat
A customer writes that their parcel arrived damaged. Ask the model for a reply:
chat = RubyLLM.chat
response = chat.ask "A customer says their parcel arrived damaged. Draft a short, friendly reply."
puts response.content
# => "I'm so sorry your parcel arrived damaged. Could you send a photo of..."
The chat remembers the conversation, so you can refine the answer:
chat.ask "Make it shorter, and offer a replacement."
See Chat for instructions, choosing models, and continuing conversations.
Streaming the Answer
Pass a block to ask, and RubyLLM yields the answer in chunks as the model writes it:
chat.ask "Now write the same reply in German." do |chunk|
print chunk.content
end
See Streaming for streaming into web pages and background jobs.
Asking About Files
Customers send screenshots and PDFs. Pass a file with with::
response = RubyLLM.chat.ask "What error does this checkout screenshot show?", with: "screenshot.png"
puts response.content
with: takes a path, a URL, an IO, or an Active Storage attachment. See Attachments for supported formats.
Getting Structured Data Back
Before anyone reads a support email, triage it: what it’s about, how urgent it is, and a one-line summary. Describe those fields in a schema, and read the answer as a Hash:
class TicketTriage < Schematist::Schema
string :category, enum: %w[billing shipping returns other]
string :priority, enum: %w[low normal urgent]
string :summary, description: "One sentence for the support queue"
end
email = "My order R-1042 still hasn't arrived and I need it for a wedding on Saturday!"
triage = RubyLLM.chat.with_schema(TicketTriage).ask(email).parsed
# => {"category" => "shipping", "priority" => "urgent", "summary" => "Order R-1042 is late; needed by Saturday."}
Schematist comes with RubyLLM. See Structured Output for nested objects, arrays, and optional fields.
Reading Usage and Costs
Every response knows its tokens and what it cost:
response = RubyLLM.chat.ask "Summarize our returns policy in one sentence."
response.tokens.input
response.tokens.output
response.cost.total
See Cost and Usage Tracking for cached tokens, retries, and the Rails usage ledger, and Batches for bulk work at a lower price.
Giving the Model Tools
The model doesn’t know your help center. A tool lets it search it: a Ruby class with a description and an execute method.
class SearchDocs < RubyLLM::Tool
description "Searches the help center for articles that answer a customer's question"
parameter :query, description: "What the customer wants to know"
def execute(query:)
Article.search(query).first(3).map do |article|
{ title: article.title, url: article.url, body: article.body }
end
end
end
response = RubyLLM.chat.with_tools(SearchDocs).ask "How do I return a jacket that doesn't fit?"
puts response.content
Article.search stands for whatever search your application already has. When the model calls the tool, RubyLLM runs execute and sends the result back to the model, which then answers. See Tools for tools that act for the current customer.
Defining an Agent
The support chat needs the same model, instructions, and tools everywhere it runs. Put them in an agent:
class SupportAgent < RubyLLM::Agent
model "gpt-6.1-sol"
instructions "You answer customers of Acme Outfitters. Be brief and friendly, and link to articles you used."
tools SearchDocs
end
response = SupportAgent.new.ask "Do you ship to Canada?"
puts response.content
See Agents for runtime inputs, prompts, callbacks, and subagents, and Agentic Workflows for agents that work together.
Transcribing a Voicemail
Not every customer writes. Turn a voicemail into text, then handle it like an email:
transcript = RubyLLM.transcribe "voicemail.mp3"
puts transcript.text
See Audio Transcription for timestamps, speaker identification, and streaming.
Reading an Invoice
A customer disputes a charge and attaches a scanned invoice. OCR extracts its text as Markdown. It uses Mistral, so add its key:
RubyLLM.configure do |config|
config.mistral_api_key = ENV.fetch("MISTRAL_API_KEY")
end
invoice = RubyLLM.ocr "invoice.pdf"
puts invoice.markdown
See Document OCR for single pages and tables.
Moderating a Message
Check a message before an agent reads it or a person sees it:
moderation = RubyLLM.moderate "Your courier threw my parcel over the fence. Again."
moderation.flagged?
# => false
See Moderation for categories, scores, and images.
Searching the FAQ
Embeddings turn text into vectors, so you can find the answers closest in meaning to a question, not just in wording. Embed the FAQ once and store the vectors:
faq = [
"Returns are free within 30 days of delivery.",
"Orders ship within two business days.",
"We ship to the EU, the UK, and the US."
]
embedding = RubyLLM.embed faq
embedding.vectors # => one vector per answer
A vector search returns candidates. Reranking puts the best answer first. This example uses Cohere:
RubyLLM.configure do |config|
config.cohere_api_key = ENV.fetch("COHERE_API_KEY")
end
ranked = RubyLLM.rerank "Can I send back a jacket?", faq, model: "rerank-v3.5"
ranked.results.first.document
# => "Returns are free within 30 days of delivery."
See Embeddings, Reranking, and RAG for answering questions from your own content.
Generating Images, Video, and Speech
The help center needs an illustration for its returns article:
image = RubyLLM.paint "A friendly flat illustration of a parcel being packed for return"
image.save "returns.png"
And a short clip for its packing guide. The default video model uses xAI, so add its key:
RubyLLM.configure do |config|
config.xai_api_key = ENV.fetch("XAI_API_KEY")
end
video = RubyLLM.animate "Hands folding a sweater and packing it into a cardboard box"
video.save "packing.mp4"
The phone line reads replies aloud:
speech = RubyLLM.speak "Thanks for calling Acme Outfitters. Your order shipped this morning."
speech.save "reply.mp3"
animate waits for the video to finish. See Image Generation, Video Generation, and Text to Speech for sizes, voices, formats, and background jobs.
Using It in Rails
The install generator creates Chat and Message models backed by Active Record:
bin/rails generate ruby_llm:install
bin/rails db:migrate
bin/rails ruby_llm:load_models
chat = Chat.create!(model: "gpt-6.1-sol")
chat.ask "Do you ship to Canada?"
The API stays the same, and each message is saved as it arrives. For a working chat interface with Hotwire streaming, add:
bin/rails generate ruby_llm:chat_ui
Then visit http://localhost:3000/chats. See Rails Integration for the full setup.
Next Steps
The Start Here guides take each piece in turn:
- How RubyLLM Works: how the pieces fit together.
- Chat: conversations, instructions, models, and thinking.
- Tools:
SearchDocs,LookupOrder, and tools that act for the current customer. - Agents:
SupportAgent, inputs, prompts, callbacks, and subagents. - Configuration: API keys, default models, and contexts.
- The individual operations: images, speech, transcription, OCR, moderation, embeddings, and reranking.
- Rails Integration: the support desk on your own records and jobs.
Then go deeper where your application needs it: Chat in Depth and Tools in Depth for every option, Agentic Workflows for routing and parallel work, Durable Agents for agents that wait for people, Error Handling for failures, and Models for capabilities and prices. If you write code with an AI assistant, see AI Coding Assistants. If you’re moving from another framework or client, see Migrating to RubyLLM.