# RubyLLM
---
RubyLLM is an AI framework for Ruby and Rails. Build conversations and agents, generate media, process documents, and work with model providers through one Ruby API. The guides at https://rubyllm.com/ introduce each feature; this reference documents its classes, arguments, and results.

    RubyLLM.configure do |config|
      config.openai_api_key = ENV['OPENAI_API_KEY']
    end

    chat = RubyLLM.chat
    chat.ask "What is the capital of France?"

## Conversations, tools, and agents

RubyLLM.chat returns a Chat that holds the conversation. Chat#ask accepts text and attachments, runs tools as needed, and returns a Message. Give it a block to receive Chunk objects as the response streams:

    chat.ask("Summarize this report", with: "report.pdf") do |chunk|
      print chunk.content
    end

Configure the request with chainable methods:

*   Chat#with_schema requests structured output; Message#parsed reads it.
*   Chat#with_thinking sets thinking effort, budget, or display preferences.
*   Chat#with_citations requests source citations, read through Message#citations.
*   Chat#with_fallbacks tries other models when a request fails.
*   Chat#with_caching enables prompt caching; Message#cache_until_here marks a reusable prefix. Chat#with_compaction manages long conversations.

Subclass Tool and implement `execute` to give the model an application action. Tool.requires_approval pauses a call until a person approves it, and Tool#ask until they answer a question; Chat#pending_questions returns the Question objects a chat waits on. Tool#progress reports what a running tool is doing to Chat#after_tool_progress as a Progress. A tool that returns a Task pauses its call until Tool#resume finishes it. Chat#with_provider_tools enables provider-executed tools such as web search, code execution, and remote MCP. Their calls appear as ServerToolCall values, with Citation values for what the answer cites and WebSource values for the pages a search returned. MCP is a Model Context Protocol client: describe a server to connect to in an MCP class, and Chat#with_mcp gives the model its tools. RubyLLM.mcp connects to one inline. Chat#with_code_execution lets the model run Ruby, Python, JavaScript, and shell code in a Sandbox, by default the one set with Configuration#sandbox
and read through RubyLLM.sandbox. The model can ask to run one call in a wider sandbox the application lists, and each such call waits for approval. Chat#with_skills gives the model Skill folders in the open Agent Skills format: each request lists them, the model loads the instructions and files it needs with its `load_skill` tool, and code execution runs their scripts. Skill.roots holds the directories they come from.

Agent defines a reusable configuration with model, instructions, tools, schema, and runtime inputs. Chat#ask_later, Chat#generate, Chat#run_tools, and Chat#step expose the conversation loop for jobs and application logic.

## Images, video, and speech

Individual operations do not require a chat. Image, Video, and Speech results share +save(path)+ and `to_blob`:

    RubyLLM.paint("A red panda coding Ruby, watercolor").save("panda.png")
    RubyLLM.animate("A paper boat sailing down a gutter").save("boat.mp4")
    RubyLLM.speak("Welcome to RubyLLM.").save("welcome.mp3")

Image.paint accepts source images and masks for editing. Video.animate accepts reference media, video edits, and extensions on supported models. RubyLLM.animate waits for the clip; RubyLLM.animate_later returns a VideoJob that you can poll. Speech.speak also streams SpeechChunk objects while retaining the complete audio result.

## Documents, audio, and retrieval

    transcript = RubyLLM.transcribe("meeting.wav")
    document = RubyLLM.ocr("report.pdf", pages: [0, 1])
    embedding = RubyLLM.embed("Ruby is a programmer's best friend")

Transcription provides text, timestamps, and speaker information when the model reports them; streaming yields TranscriptionChunk objects. OCR returns document pages and combined markdown. Embedding returns vectors for text or supported media, and RubyLLM.rerank returns a Rerank whose results order documents by relevance. SearchResults lets a Tool return source documents that the model can cite.

RubyLLM.upload returns an UploadedFile for reuse across requests. RubyLLM.download returns a DownloadedFile with the same saving interface:

    RubyLLM.download(file.id, provider: file.provider).save("report.pdf")

## Tokenization, moderation, and research

RubyLLM.count_tokens and Chat#count_tokens count a model request without generating a response. RubyLLM.tokenize returns plain-text token IDs and a count as a Tokenization, excluding chat formatting and attachments.

    result = RubyLLM.tokenize("Hello Ruby", model: "grok-4.3", provider: :xai)
    result.ids
    result.count

RubyLLM.moderate screens text and images, returning Moderation results with categories, scores, and `flagged?`. RubyLLM.research runs a hosted research task and returns its report as a Message; RubyLLM.research_later returns a ResearchJob for polling and cancellation. Hosted agent identities are selected separately from model IDs.

## Evaluations

Evaluation runs your application against a dataset of cases and grades each result. Implement Evaluation#perform to return a value, Message, Chat, or Agent. Without declared criteria, a model checks each result against the case's `expected_output`. Evaluations can also use an Agent or a Judge as their evaluator, and Ruby assertions. Datasets live under app/evals, named after the class:

    class SupportEvaluation < RubyLLM::Evaluation
      def perform(input)
        SupportAgent.new.ask(input)
      end
    end
    SupportEvaluation.run.passed?

Evaluation.run returns an Evaluation::Report with each trial's verdicts, tokens, and cost. The `ruby_llm:eval` Rake task, Evaluation::RSpec, and Evaluation::Minitest run the same cases from the command line and tests.

## Typed judgments

Judge defines reusable probability, choice, and score questions. Its `judge` method evaluates supplied text, structured data, or images passed as `with:` and returns a Judgment:

    class Urgency < RubyLLM::Judge
      probability :urgent, "Does this need attention today?"
    end
    Urgency.judge("Please help today.").urgent.probability

RubyLLM.judge accepts question definitions as a Hash. Probability, Choice, and Score answers retain uncertainty; Judgment reports the model, tokens, and cost. Questions share the supplied input and do not retain chat history.

## Batches, usage, and configuration

RubyLLM.batch submits staged chats or EmbeddingRequest objects for provider-side processing. Batch exposes progress, results, token usage, and cost. RubyLLM.cache creates a managed CachedContent resource for reuse with Chat#with_caching.

Tokens and Cost report usage and pricing. Chat totals include retries and attempts that produced no message. Provider-reported costs take precedence over estimates; unknown usage and prices remain `nil`. RubyLLM.with_owner attributes the usage of operations to a record. OpenTelemetry.enable enables optional tracing alongside existing subscribers. Your application configures the OpenTelemetry SDK and exporters.

RubyLLM.workflow groups instrumentation and usage from ordinary Ruby code into named Workflow steps.

RubyLLM.configure sets global Configuration; RubyLLM.context creates isolated settings for a request or tenant. Models finds, filters, and describes the model catalog. Provider supplies endpoints, authentication, and protocol selection; Protocol implements request and response formats. Error subclasses normalize provider failures.

## Rails integration

ActiveRecord::ActsAs adds `acts_as_chat` and `acts_as_message` to your application's models. ActiveRecord::ChatMethods and ActiveRecord::MessageMethods provide the conversation API with persistence, Active Storage attachments, and support for Hotwire streaming and jobs. Approvals and cancellation survive requests and processes.

Your application owns chats and messages; RubyLLM owns and writes ActiveRecord::Usage, ActiveRecord::ToolCall, ActiveRecord::Model, ActiveRecord::Batch, ActiveRecord::MCPCredential, ActiveRecord::ProviderFile, ActiveRecord::QueuedMessage, and ActiveRecord::ChatFile, which your application can read and query. ActiveRecord::Record configures their shared database connection. Agent can create and reload your chat records through Agent.chat_class. Individual operations also work directly in Rails services and jobs.
---
# Constants:

VERSION
:   The version of the ruby_llm gem, as a string.

# Class methods:

    animate
    animate_later
    batch
    cache
    chat
    config
    configure
    context
    count_tokens
    download
    embed
    embed_later
    judge
    mcp
    models
    moderate
    ocr
    paint
    providers
    render_prompt
    rerank
    research
    research_later
    sandbox
    speak
    tokenize
    transcribe
    upload
    with_owner
    with_usage_owner
    workflow

# RubyLLM::animate
---
    animate(...)

---

Generates a video from a text prompt, blocks until the provider finishes rendering it, and returns a Video. Arguments are forwarded to Video.animate.

    video = RubyLLM.animate("a paper boat sailing down a rainy gutter")
    video.save("boat.mp4")

# RubyLLM::animate_later
---
    animate_later(...)

---

Submits a video generation job and returns a VideoJob immediately, without waiting for the result. Arguments are forwarded to VideoJob.animate_later.

    job = RubyLLM.animate_later("a paper boat sailing down a gutter")
    job.wait
    job.video.save("boat.mp4")

# RubyLLM::batch
---
    batch(chats)

---

Submits requests staged with Chat#ask_later or ::embed_later as a provider-side batch and returns a Batch. A batch takes chats or embedding requests, not both. Look up an existing batch with Batch.find.

    chats = documents.map do |doc|
      RubyLLM.chat(model: 'claude-haiku-4-5').ask_later(doc.text)
    end
    batch = RubyLLM.batch(chats)

# RubyLLM::cache
---
    cache(...)

---

Creates a provider-side prompt cache and returns a CachedContent that chats can attach with Chat#with_caching. Arguments are forwarded to CachedContent.create.

    cache = RubyLLM.cache(big_document, model: 'gemini-3.7-flash', ttl: 3600)
    chat = RubyLLM.chat(model: 'gemini-3.7-flash').with_caching(id: cache)

# RubyLLM::chat
---
    chat(...)

---

Creates a Chat conversation. Arguments are forwarded to Chat.new: `model:`, `provider:`, `protocol:`, `assume_model_exists:`, and `context:`. With no arguments, uses the configured default model.

    chat = RubyLLM.chat
    chat.ask "What is the capital of France?"

    chat = RubyLLM.chat(model: 'claude-sonnet-5')

# RubyLLM::config
---
    config()

---

Returns the global Configuration instance.

# RubyLLM::configure
---
    configure() { |config| ... }

---

Yields the global configuration for block-style setup. Call this once at startup to set API keys and defaults.

    RubyLLM.configure do |config|
      config.openai_api_key = ENV['OPENAI_API_KEY']
    end

# RubyLLM::context
---
    context() { |context_config| ... }

---

Returns a Context, an isolated set of configuration overrides. Duplicates the global configuration and yields the copy if a block is given. The context offers the same entry points as the top-level RubyLLM module (Context#chat, Context#embed, and so on) using its own configuration.

    context = RubyLLM.context do |config|
      config.openai_api_key = 'sk-customer-specific-key'
    end
    context.chat.ask "Hello"

# RubyLLM::count_tokens
---
    count_tokens(text, model: nil, provider: nil)

---

Counts the tokens `text` would consume as a single user message, without requesting a completion. Builds a minimal Chat and delegates to Chat#count_tokens. Returns an Integer.

    RubyLLM.count_tokens("What is the capital of France?", model: 'claude-haiku-4-5')

# RubyLLM::download
---
    download(...)

---

Downloads a provider file and returns a DownloadedFile. Save it with DownloadedFile#save or read its bytes with DownloadedFile#to_blob. Arguments are forwarded to UploadedFile.download.

    RubyLLM.download(file.id, provider: :openai).save("report.pdf")

# RubyLLM::embed
---
    embed(...)

---

Generates a vector embedding for a text, or one embedding per element when given an array of strings. Returns an Embedding. Arguments are forwarded to Embedding.embed.

    embedding = RubyLLM.embed("Ruby is a programmer's best friend")
    embedding.vector # => [0.018, -0.027, ...]

# RubyLLM::embed_later
---
    embed_later(text, model: nil, provider: nil, dimensions: nil)

---

Stages a text for embedding without contacting the provider, and returns an EmbeddingRequest. Submit an array of staged requests as a provider-side batch with ::batch; once the batch completes, each request's EmbeddingRequest#result holds its Embedding.

    requests = texts.map { |text| RubyLLM.embed_later(text) }
    batch = RubyLLM.batch(requests)

# RubyLLM::judge
---
    judge(...)

---

Judges text, structured data, or images against typed questions and returns a Judgment. Accepts the same arguments as Judge.judge. Subclass Judge to define reusable questions with probability, choice, and score. Uses Configuration#default_judgment_model unless a model is supplied.

    RubyLLM.judge("Please help today",
      questions: { urgent: { type: :probability, instructions: "Is this urgent?" } })

# RubyLLM::mcp
---
    mcp(...)

---

Connects to a Model Context Protocol server without writing an MCP class. Pass `url:` for a Streamable HTTP server, `command:` for a local server that speaks over stdio, or `transport:` and `name:` for a server reached any other way, as MCP.transport describes. Also accepts `name:`, `bearer_token:`, `headers:`, `env:`, `directory:`, `timeout:`, `prefix:`, `input_requests:`, `log_level:`, `extensions:`, which takes a name or a Hash of names to the settings of MCP.extension, and `oauth:`, which takes `true` or the options of MCP.oauth.

    docs = RubyLLM.mcp(url: "https://learn.microsoft.com/api/mcp")
    files = RubyLLM.mcp(command: ["npx", "-y", "@modelcontextprotocol/server-filesystem", "."])
    RubyLLM.mcp(url: server.endpoint, prefix: "mcp_#{server.id}", oauth: { owner: server })

Returns an MCP.

# RubyLLM::models
---
    models()

---

Returns the Models registry, used to browse, find, and refresh model metadata.

    RubyLLM.models.find("claude-haiku-4-5")
    RubyLLM.models.refresh

# RubyLLM::moderate
---
    moderate(...)

---

Checks text or image attachments against the provider's moderation model and returns a Moderation result. Arguments are forwarded to Moderation.moderate. An explicitly selected provider can use a configured moderation resource without a model.

    result = RubyLLM.moderate("Some user input text")
    result.flagged? # => false

# RubyLLM::ocr
---
    ocr(...)

---

Extracts the text of a document or image and returns an OCR result. Arguments are forwarded to OCR.ocr.

    ocr = RubyLLM.ocr("contract.pdf")
    ocr.markdown

# RubyLLM::paint
---
    paint(...)

---

Generates or edits an image and returns an Image, or an array when the provider returns several images. Pass `with:` for source images, `mask:` for a mask, and `count:` for multiple results. See Image.paint.

    image = RubyLLM.paint("a sunset over mountains in watercolor style")
    image.save("sunset.png")

# RubyLLM::providers
---
    providers()

---

Returns the registered provider classes.

    RubyLLM.providers.map(&:slug)
    # => ["anthropic", "azure", "bedrock", ...]

# RubyLLM::render_prompt
---
    render_prompt(name, **locals)

---

Renders the ERB prompt template `name` and returns the result as a String. The name resolves to a `.txt.erb` file under app/prompts. Keyword arguments become locals in the template. Templates and partials support `-%>` newline trimming.

    instructions = RubyLLM.render_prompt(
      "support/instructions",
      product_name: "BillingHub"
    )
    chat.with_instructions(instructions)

Raises PromptNotFoundError if the template file does not exist.

# RubyLLM::rerank
---
    rerank(...)

---

Ranks documents by relevance to a query on providers with a rerank endpoint. Arguments are forwarded to Rerank.rerank.

    rerank = RubyLLM.rerank("what is ruby", docs,
                            model: "voyageai/rerank-2.5-lite", provider: :openrouter)
    rerank.results.first.document

# RubyLLM::research
---
    research(...)

---

Runs a hosted research task and returns its report as a Message. Requires explicit `provider:` and `agent:`. See ResearchJob.research.

# RubyLLM::research_later
---
    research_later(...)

---

Submits a hosted research task and returns a ResearchJob immediately. Requires explicit `provider:` and `agent:`. See ResearchJob.research_later.

# RubyLLM::sandbox
---
    sandbox()

---

Returns the sandbox set with Configuration#sandbox, or `nil` when none is configured. Check whether it can run on this machine with `supported?`:

    RubyLLM.sandbox.supported? # => true

Raises ConfigurationError when the configured value is not a sandbox.

# RubyLLM::speak
---
    speak(...)

---

Synthesizes speech from text and returns a Speech. Given a block, yields SpeechChunk objects as audio arrives. Arguments are forwarded to Speech.speak.

    speech = RubyLLM.speak "Hello, welcome to RubyLLM!"
    speech.save("welcome.mp3")

# RubyLLM::tokenize
---
    tokenize(...)

---

Tokenizes plain text and returns a Tokenization with its token IDs and count. Excludes chat formatting and billable generation usage. See Tokenization.tokenize for options.

# RubyLLM::transcribe
---
    transcribe(...)

---

Transcribes an audio file and returns a Transcription. Arguments are forwarded to Transcription.transcribe. Given a block, the transcript streams as TranscriptionChunk objects.

    transcription = RubyLLM.transcribe("meeting.wav")
    transcription.text

    RubyLLM.transcribe("meeting.wav", model: "gpt-4o-transcribe") do |chunk|
      print chunk.delta
    end

# RubyLLM::upload
---
    upload(...)

---

Uploads a file to a provider and returns an UploadedFile that can be reused across chats. Arguments are forwarded to UploadedFile.upload.

    file = RubyLLM.upload("document.pdf", provider: :anthropic)
    chat.ask "Summarize this document", with: file

# RubyLLM::with_owner
---
    with_owner(owner, &)

---

Attributes the usage of every operation inside the block to `owner`, such as a user or an account record, and returns the block's value. In Rails, the usage ledger stores the owner alongside any chat and message associations; everywhere, the `usage.ruby_llm` event carries it as `owner`. An operation's own `owner:` keyword wins, and nested blocks restore the outer owner when they end. Each fiber and thread keeps its own owner, and fibers and threads started inside the block inherit it.

    RubyLLM.with_owner(current_user) do
      RubyLLM.transcribe("memo.m4a")
      RubyLLM.paint("a paper boat in the rain")
    end

A chat's own Chat#with_owner wins inside it.

# RubyLLM::with_usage_owner
---
    with_usage_owner(owner, &)

---

Deprecated alias for ::with_owner.

# RubyLLM::workflow
---
    workflow(name, id: nil, metadata: nil, &)

---

Runs ordinary Ruby code as a named, instrumented workflow. Every RubyLLM event emitted inside the block includes the workflow ID and name. Wrap meaningful regions with Workflow#step to add step correlation.

    RubyLLM.workflow("Write article", id: "article-42") do |workflow|
      notes = workflow.step("Research") { researcher.ask(topic).content }
      workflow.step("Draft") { writer.ask(notes).content }
    end

If `id:` is omitted, RubyLLM generates one. Pass `metadata:` to attach application data to every nested event as `workflow_metadata`. Workflows may nest; an inner workflow keeps its own identity and records its parent as `workflow_parent_id`. In Rails, the usage ledger stores the workflow and step of every attempt inside the block. The block's return value is returned unchanged.
