class RubyLLM::Agent
An Agent is a reusable chat configuration defined as a class. Subclasses declare a model, instructions, tools, and other settings once, then build configured chats wherever they are needed.
class SupportAgent < RubyLLM::Agent model "gpt-6-luna" instructions "You are a concise support assistant." tools SearchDocs, LookupAccount end SupportAgent.new.ask "How do I reset my API key?"
::chat returns a configured Chat. When ::chat_class names an ActiveRecord chat class, ::create, ::create!, and ::find return configured records of that class instead.
Configuration that depends on runtime state goes in blocks or lambdas. Most blocks run after a chat is built, with chat and any declared ::inputs available as methods. The model block runs before a chat exists. A deferred context block also runs before Chat construction in plain Ruby, but receives the Rails chat record while Rails configures it:
class WorkAssistant < RubyLLM::Agent inputs :workspace instructions { "You are helping #{workspace.name}" } end WorkAssistant.chat(workspace: workspace)
Agent instances delegate Chat’s conversation API (ask, complete, with_tools, and so on) to the wrapped chat, which is available via chat. Direct transcript replacement stays on the wrapped chat because Rails-backed chat models own their message association. Read the conversation through messages.
Attributes
Public Class Methods
# File lib/ruby_llm/agent.rb, line 1224
Registers a Chat#after_fallback callback on every chat the agent builds or finds. See ::after_message.
# File lib/ruby_llm/agent.rb, line 1231
Registers a Chat#after_file_write callback on every chat the agent builds or finds. See ::after_message.
# File lib/ruby_llm/agent.rb, line 1125
Registers a Chat#after_message callback on every chat the agent builds or finds, Agent::find records included. Name a method or pass a block; either runs on the agent instance, so its inputs, chat, and private methods are available, and receives the callback’s arguments when it takes them. if: and unless: take a method name, a lambda, or an Array of them, like Rails callbacks. Subclasses inherit the callbacks declared when they are defined. Returns the agent class.
For a chat from ::chat or ::find, the agent is bound to the chat without running initialize, as for ::rescue_from handlers, so read inputs and chat rather than instance variables initialize sets. Wrapping a configured chat in a new agent, as SupportAgent.new(chat:) does, moves its callbacks to that agent instead of registering them twice.
class SupportAgent < RubyLLM::Agent inputs :ticket after_message :log_reply, if: -> { ticket.urgent? } before_tool_call { |tool_call| Rails.logger.info "Calling #{tool_call.name}" } private def log_reply(message) = ticket.notes.create!(body: message.content) end
The other chat callbacks have macros of the same name and shape: ::before_request, ::before_message, ::before_tool_call, ::around_tool_call, ::after_tool_result, ::after_tool_progress, ::before_fallback, ::after_fallback, and ::after_file_write. Raises ArgumentError for both a method name and a block, neither, or another option.
# File lib/ruby_llm/agent.rb, line 1210
Registers a Chat#after_tool_progress callback on every chat the agent builds or finds. See ::after_message.
# File lib/ruby_llm/agent.rb, line 1203
Registers a Chat#after_tool_result callback on every chat the agent builds or finds. See ::after_message.
Source
# File lib/ruby_llm/agent.rb, line 1238
Registers block as a Chat#around_join callback on every chat the agent builds or finds. Subclasses inherit the callbacks declared when they are defined. Returns the list of callbacks.
class SupportAgent < RubyLLM::Agent around_join do |queued, join| join.call(sender: queued.sender) end end
Raises ArgumentError without a block.
# File lib/ruby_llm/agent.rb, line 1182
Registers a Chat#around_tool_call callback on every chat the agent builds or finds. The method or block receives the ToolCall and a block that runs the tool. A method yields to it; a block takes it as +&run+:
class SupportAgent < RubyLLM::Agent inputs :account around_tool_call :in_tenant private def in_tenant(tool_call, &) = ActsAsTenant.with_tenant(account, &) end
When if: or unless: skips the callback, the tool runs without it. See ::after_message.
# File lib/ruby_llm/agent.rb, line 1217
Registers a Chat#before_fallback callback on every chat the agent builds or finds. See ::after_message.
# File lib/ruby_llm/agent.rb, line 1168
Registers a Chat#before_message callback on every chat the agent builds or finds. See ::after_message.
# File lib/ruby_llm/agent.rb, line 1161
Registers a Chat#before_request callback on every chat the agent builds or finds. See ::after_message.
# File lib/ruby_llm/agent.rb, line 1175
Registers a Chat#before_tool_call callback on every chat the agent builds or finds. See ::after_message.
# File lib/ruby_llm/agent.rb, line 447 def caching(enabled = true, **options, &block) # rubocop:disable Metrics/PerceivedComplexity, Style/OptionalBooleanParameter return caching(**enabled.transform_keys(&:to_sym), **options, &block) if enabled.is_a?(Hash) return caching(id: enabled, **options, &block) if enabled.is_a?(CachedContent) unless [true, false].include?(enabled) raise ArgumentError, 'caching accepts false, a CachedContent, or caching options' end raise ArgumentError, 'caching accepts options or a block, not both' if options.any? && block raise ArgumentError, 'caching false does not accept options or a block' if !enabled && (options.any? || block) @caching = block || (enabled ? options : false) end
Enables prompt caching for chats this agent builds, applied via Chat#with_caching. With no options, the provider’s default behavior applies. Pass false to stop RubyLLM from sending cache controls. A provider may still cache prompts implicitly. A block defers evaluation until the chat is built. Accepts keywords or an options Hash.
caching caching false caching cache caching ttl: "1h" caching { { ttl: workspace.cache_ttl } }
Source
# File lib/ruby_llm/agent.rb, line 607 def chat(**kwargs) input_values, chat_options = partition_inputs(kwargs) context_value = resolved_context(inputs: input_values) chat = build_chat(inputs: input_values, options: chat_options, resolved_context: context_value) apply_configuration(chat, input_values:, persist_instructions: true, resolved_context: context_value) chat end
Builds a Chat configured with this agent’s declarations and returns it. Keywords matching declared ::inputs become runtime inputs; the rest are forwarded to RubyLLM.chat.
chat = WorkAssistant.chat chat.ask "Hello"
Source
# File lib/ruby_llm/agent.rb, line 557 def chat_class(value = nil) return @chat_class if value.nil? @chat_class = value remove_instance_variable(:@resolved_chat_class) if instance_variable_defined?(:@resolved_chat_class) end
Sets the ActiveRecord chat class this agent creates and finds, activating Rails mode (::create, ::create!, ::find, and ::sync_instructions). Accepts the class or its name as a string. Called with no argument, returns the configured value.
chat_class Chat
Source
# File lib/ruby_llm/agent.rb, line 429 def citations(value = true) # rubocop:disable Style/OptionalBooleanParameter raise ArgumentError, 'citations accepts true or false' unless [true, false].include?(value) @citations = value end
Enables citations for chats this agent builds, applied via Chat#with_citations. Pass false to disable them.
citations citations false
# File lib/ruby_llm/agent.rb, line 344 def code_execution(enabled = true, **options) # rubocop:disable Style/OptionalBooleanParameter raise ArgumentError, 'code_execution takes no block. Pass a lambda as mounts: for each run' if block_given? @code_execution = CodeExecution.options(enabled, options) end
Lets chats this agent builds run code in the configured sandbox, applied via Chat#with_code_execution. Accepts the same options as keywords or a Hash. Pass false to disable it. Passing nil or a block raises ArgumentError.
code_execution code_execution false code_execution languages: [:ruby, :python], gems: %w[prawn] code_execution sandbox: ReadOnlySandbox, escalate_to: [WorkspaceSandbox] code_execution mounts: -> { { "templates" => chat.templates_dir } }
A mounts lambda runs before each run, with chat and the agent’s inputs in scope, like the agent’s other lambdas.
Source
# File lib/ruby_llm/agent.rb, line 307 def compaction(options = {}) options = {} if options == true unless options == false || options.is_a?(Hash) raise ArgumentError, 'compaction accepts true, false, or compaction options' end @compaction = options end
Enables context compaction for chats this agent builds, applied via Chat#with_compaction. With no options, the provider’s own defaults apply. Pass false to disable it.
compaction compaction false compaction at: 50_000
# File lib/ruby_llm/agent.rb, line 536 def context(value = nil, &block) raise ArgumentError, 'Pass a context or a block, not both' if value && block validate_context_proc(value) return @context if value.nil? && !block @context = if block block.arity.zero? ? block : RubyLLM.context(&block) else value end end
Sets a Context whose configuration chats this agent builds should use, applied via Chat#with_context. A block taking a configuration argument creates an isolated Context when the agent class is defined. A zero-argument block or Proc value defers evaluation until a chat is built or configured, with declared ::inputs available as methods. In plain Ruby, chat is nil; in Rails mode, chat is the record being configured. Called with no argument or block, returns the configured context or deferred Proc.
context SharedContext context { |config| config.request_timeout = 180 } context -> { RubyLLM.context { |config| config.openai_api_key = api_key } }
# File lib/ruby_llm/agent.rb, line 329 def context_budget(budget = {}, **, &) = (@context_budget = context_budget_option(budget, **, &))
Keeps tool results within shares of the model’s context window in chats this agent builds, applied via Chat#with_context_budget, in place of Configuration#context_budget. Pass nil for no budget.
context_budget per_result: 0.25, per_request: 0.7 context_budget window: 128_000, per_request: 0.7 context_budget nil
A block is evaluated for each chat, with the agent’s inputs and chat in scope, and returns the options, or nil for no budget.
context_budget { { window: model_window, per_request: 0.7 } if model_window }
Source
# File lib/ruby_llm/agent.rb, line 622 def create(**) with_rails_chat_record(:create, **) end
Creates a ::chat_class record, applies this agent’s configuration to it, and returns it. Keywords matching declared ::inputs become runtime inputs; the rest are forwarded to the model’s create.
chat = WorkAssistant.create(user: current_user)
Raises ArgumentError if ::chat_class is not configured.
Source
# File lib/ruby_llm/agent.rb, line 631 def create!(**) with_rails_chat_record(:create!, **) end
Like ::create, but calls the model’s create!, raising if the record is invalid.
chat = WorkAssistant.create!(user: current_user)
Source
# File lib/ruby_llm/agent.rb, line 1098
Sets what the agent does, which a model reads when the agent is one of its tools (see ::to_tool), or returns it when called without an argument.
class ResearchAgent < RubyLLM::Agent description "Researches a question across the web and reports back" end
# File lib/ruby_llm/agent.rb, line 407 def end_user(value = nil, &block) = value.nil? && !block ? @end_user : (@end_user = block || value)
Sets the safety identifier for chats this agent builds, applied via Chat#with_end_user. A block defers evaluation until the chat is built, so the id can come from the agent’s inputs. Called with no arguments, returns the configured value.
end_user "tenant-42" end_user { workspace.public_id }
# File lib/ruby_llm/agent.rb, line 510 def fallbacks(*models, on: Fallback::DEFAULT_ERRORS, drop_unsupported: false) return @fallbacks || [] if (bare = models.empty? && !drop_unsupported) && on.equal?(Fallback::DEFAULT_ERRORS) raise ArgumentError, 'To set fallback options, provide at least one fallback model' if bare @fallbacks = models.flatten.compact @fallback_options = { on:, drop_unsupported: } end
Sets fallback models for chats this agent builds, applied via Chat#with_fallbacks. Called with no arguments, returns the configured models. Keep the default on:: providers signal overload as HTTP 529 or 503, and the default covers both.
fallbacks "gpt-4.1-mini", "claude-haiku-4-5" fallbacks "gpt-4.1-mini", on: [*RubyLLM::Fallback::DEFAULT_ERRORS, RubyLLM::ContextLengthExceededError] fallbacks drop_unsupported: true
# File lib/ruby_llm/agent.rb, line 370 def file_store(store = Chat::FileReferences::DEFAULT_STORE, inline_limit: Chat::FileReferences::INLINE_LIMIT, tools: FileStore::Tools::DEFAULT) raise ArgumentError, 'file_store takes no block. Pass the store as a lambda instead' if block_given? return @file_store = false if store.nil? Chat::FileReferences.validate(store, inline_limit:, tools:, store_lambda: true) @file_store = { store:, inline_limit:, tools: }.freeze end
Attaches a file store to chats this agent builds, with the tools to work with it, applied via Chat#with_file_store, which takes the same arguments. A store lambda runs once for each chat, with chat and the agent’s inputs in scope, like the agent’s other lambdas. Pass nil to remove the store a parent agent declared. A block raises ArgumentError: pass the lambda as the store instead.
file_store file_store inline_limit: 20_000, tools: :read file_store :memory file_store -> { "tmp/chats/#{chat.id}" } file_store nil
Each chat gets a store of its own: without store, a new FileStore::Memory, or for a persisted chat, its files in Active Storage, kept for the chat’s owner (see ::owner). A folder path on its own is shared by every chat, so use a lambda to give each chat its own folder.
Source
# File lib/ruby_llm/agent.rb, line 642 def find(id, **kwargs) raise ArgumentError, 'chat_class must be configured to use find' unless resolved_chat_class input_values, = partition_inputs(kwargs) record = resolved_chat_class.find(id) apply_configuration(record, input_values:, persist_instructions: false) record end
Finds the ::chat_class record with id and applies this agent’s configuration at runtime, without persisting instructions. Returns the record.
chat = WorkAssistant.find(params[:id])
Raises ArgumentError if ::chat_class is not configured.
Source
# File lib/ruby_llm/agent.rb, line 477 def headers(**headers, &block) return @headers || {} if headers.empty? && !block_given? @headers = block_given? ? block : headers end
Sets custom HTTP headers for chats this agent builds, applied via Chat#with_headers. A block defers evaluation until the chat is built. Called with no arguments, returns the configured value.
Source
# File lib/ruby_llm/agent.rb, line 576 def inputs(*names) return @input_names || [] if names.empty? @input_names = names.flatten.map(&:to_sym) end
# File lib/ruby_llm/agent.rb, line 244 def instructions(text = nil, append: false, persist: true, cache_until_here: false, **prompt_locals, &block) return instruction_declarations if text.nil? && prompt_locals.empty? && !block_given? (@instruction_declarations ||= []) << { value: block || text || { prompt: 'instructions', locals: prompt_locals }, append: append, persist: persist, cache_until_here: cache_until_here } end
Adds system instructions for chats this agent builds. Accepts a string, a block evaluated when the chat is built, or keyword locals for the agent’s conventional prompt template (for a WorkAssistant agent, app/prompts/work_assistant/instructions.txt.erb). Multiple declarations are applied in order.
instructions "You are a helpful assistant." instructions { "You are helping #{workspace.name}" } instructions display_name: -> { chat.user.display_name_or_email } instructions append: true, persist: false do "Today is #{Date.current}" end
The class’s own declarations take precedence over its conventional template. Inherited declarations are used only when neither exists. In Rails mode, declarations persist when the record is created unless persist: false; ::find always reapplies them without rewriting history. Called with no arguments, returns the declarations.
# File lib/ruby_llm/agent.rb, line 273 PASSTHROUGH_OPTIONS.each do |option| define_method(option) do |value = nil| return instance_variable_get(:"@#{option}") if value.nil? instance_variable_set(:"@#{option}", value) end end
Caps the number of tokens chats this agent builds may generate. Called with no argument, returns the configured value.
max_output_tokens 1000
# File lib/ruby_llm/agent.rb, line 185 def mcp(*servers, defer: nil, &block) if servers.empty? && !block_given? @mcp_defer = defer unless defer.nil? return @mcp || [] end @mcp_defer = defer @mcp = block_given? ? block : servers.flatten end
Connects MCP servers to chats this agent builds, applied via Chat#with_mcp. A block defers construction until the chat is built, with the declared ::inputs available. Called with no arguments, returns the declared servers.
mcp Files mcp { [Linear.new(user: user), Files] }
Pass defer: as Chat#with_mcp takes it, or a lambda that decides when the chat is built:
mcp GitHub, defer: true
With defer: alone it applies to the servers a parent agent declared.
# File lib/ruby_llm/agent.rb, line 136 def model(model_id = nil, **options, &block) return @chat_kwargs || {} if model_id.nil? && options.empty? && !block_given? model_value = block || model_id options[:model] = model_value unless model_value.nil? @chat_kwargs = options end
Sets the model used by chats this agent builds. Extra options are forwarded to RubyLLM.chat, including provider: to disambiguate the model and protocol: to override its wire protocol. A block picks the model when the chat is built, with the declared ::inputs available as methods. Called with no arguments, returns the configured chat keywords.
model "gpt-6-luna" model "gpt-6.1-sol", provider: :openai, protocol: :responses model { quality == :high ? "gpt-6.1-sol" : "gpt-6-luna" }
A model: passed to ::chat, ::new, ::create, or ::create! replaces the declared model and its options, so the caller’s model resolves on its own provider unless the caller also passes provider:. Options declared without a model stay. Later, ::find, ::new with chat:, and ::sync_instructions apply the options only to a record on the declared model, and always when a block declares it, since the block’s choice is unknown until it runs.
The block runs before the chat exists, so it can read inputs but not chat.
# File lib/ruby_llm/agent.rb, line 1023 def initialize(chat: nil, inputs: nil, persist_instructions: true, **kwargs) input_values, chat_options = self.class.partition_inputs(kwargs) input_values = input_values.merge(inputs || {}) if chat bind(chat, input_values) self.class.apply_configuration(@chat, input_values:, persist_instructions:, agent: self) return end context_value = self.class.resolved_context(inputs: input_values) bind(self.class.build_chat(inputs: input_values, options: chat_options, resolved_context: context_value), input_values) self.class.apply_configuration( @chat, input_values:, persist_instructions:, resolved_context: context_value, agent: self ) end
Returns a new agent wrapping chat:, or wrapping a newly built chat when chat: is nil. Applies the agent’s configuration either way. Keywords matching declared inputs (and the inputs: hash) become runtime inputs; the rest are forwarded to RubyLLM.chat when the agent builds its own chat. Pass persist_instructions: false to apply instructions at runtime only, without persisting them on a Rails-backed record.
agent = WorkAssistant.new agent.ask "Hello" record = Chat.find(params[:id]) WorkAssistant.new(chat: record)
Source
# File lib/ruby_llm/agent.rb, line 421 def owner(value = nil, &block) = value.nil? && !block ? @owner : (@owner = block || value)
Sets whoever the usage of chats this agent builds or finds is attributed to, applied via Chat#with_owner. A block defers evaluation until the chat is built, so the owner can come from the agent’s inputs or, for a persisted chat, from chat. A persisted chat keeps the files of its Active Storage store for the owner too, and the owner wins over the association its acts_as_chat owner: names. Subclasses inherit it. Called with no arguments, returns the configured value.
owner { account } owner { chat.user }
# File lib/ruby_llm/agent.rb, line 468 def provider_options(**provider_options, &block) return @provider_options || {} if provider_options.empty? && !block_given? @provider_options = block_given? ? block : provider_options end
Sets options in the provider’s request vocabulary for chats this agent builds, applied via Chat#with_provider_options. A block defers evaluation until the chat is built. Called with no arguments, returns the configured value.
provider_options service_tier: "flex"
# File lib/ruby_llm/agent.rb, line 219 def provider_tools(*tools, **tools_with_options, &block) return @provider_tools || [] if tools.empty? && tools_with_options.empty? && !block_given? @provider_tools = block_given? ? block : RubyLLM::Tools::ProviderTools.normalize(tools, tools_with_options) end
Enables provider-executed tools for chats this agent builds, applied via Chat#with_provider_tools. Accepts the same aliases, options, and raw Hashes; a block defers evaluation until the chat is built and returns a list, or a Hash of aliases and options like the keywords. Called with no arguments, returns the declared entries.
provider_tools :web_search provider_tools web_search: { allowed_domains: ["ruby-lang.org"] } provider_tools { { web_search: { max_uses: max_searches } } }
# File lib/ruby_llm/agent.rb, line 1053
Registers a handler for exceptions raised by the chat operations of this agent’s instances and of the chats and records ::chat, ::create, ::create!, and ::find return: ask, say, ask_later, complete, generate, run_tools, step, count_tokens, and compact. Name the handler with with: or pass a block; either runs on the agent instance, so the agent’s chat, inputs, and class name are available for instrumentation.
class ApplicationAgent < RubyLLM::Agent rescue_from RubyLLM::RateLimitError, RubyLLM::ConnectionError, with: :handle_transient rescue_from RubyLLM::BadRequestError do |error| error_tracker.notify(error) raise end private def handle_transient(error) metrics.increment("llm.api_error", type: "transient") raise end end
Handlers are searched in reverse declaration order, so the last matching one wins. Re-raise inside a handler to let the caller see the exception; otherwise the handler’s return value becomes the operation’s return value. Exceptions no handler matches are re-raised. Subclasses use their parents’ handlers, including ones declared after the subclass, and their own come first.
Exception classes may be named as Strings, which defers constant lookup until an exception is raised. A class that can never match a StandardError, such as Interrupt, raises ArgumentError.
Source
# File lib/ruby_llm/agent.rb, line 495 def schema(value = nil, &block) return @schema if value.nil? && !block_given? @schema = block_given? ? block : value end
Sets the structured output schema for chats this agent builds, applied via Chat#with_schema. Accepts a schema class, a JSON schema hash, or a block. A plain block is built with the Schematist::Schema DSL; a lambda is evaluated when the chat is built. Called with no arguments, returns the configured value.
schema PersonSchema schema do string :verdict, enum: ["pass", "revise"] string :feedback end
Source
# File lib/ruby_llm/agent.rb, line 392 def skills(*skills) raise ArgumentError, 'skills takes no block. Name the skills, or pass true for every skill' if block_given? return @skills if skills.empty? @skills = Skill.selection(skills) end
Gives chats this agent builds the skills named, applied via Chat#with_skills when the chat is built. Symbols name folders under Skill.roots, Strings and Pathnames are paths to skill folders, true is every skill under the roots, and false removes the skills a parent agent declared. An agent without a skills declaration has no skills. Called with no arguments, returns the declaration: the names, true, false, or nil. A block raises ArgumentError.
skills :invoices, :refunds skills true skills false
# File lib/ruby_llm/agent.rb, line 660 def sync_instructions(chat_or_id, **kwargs) raise ArgumentError, 'chat_class must be configured to use sync_instructions' unless resolved_chat_class input_values, = partition_inputs(kwargs) record = chat_or_id.is_a?(resolved_chat_class) ? chat_or_id : resolved_chat_class.find(chat_or_id) apply_chat_options(record) runtime = runtime_context(chat: record, inputs: input_values) apply_context(record, runtime) apply_instructions( record, runtime, inputs: input_values, persist: true, persistent_only: true ) record end
Re-renders this agent’s instructions and persists them on the given ::chat_class record (or the record found by that id). Keywords matching declared ::inputs become runtime inputs. Returns the record.
WorkAssistant.sync_instructions(chat)
Raises ArgumentError if ::chat_class is not configured.
Source
# File lib/ruby_llm/agent.rb, line 256
Sets the sampling temperature for chats this agent builds. Called with no argument, returns the configured value.
temperature 0.2
# File lib/ruby_llm/agent.rb, line 292 def thinking(enabled = true, **options) # rubocop:disable Style/OptionalBooleanParameter return thinking(**enabled.transform_keys(&:to_sym), **options) if enabled.is_a?(Hash) validate_thinking_options(enabled, options) @thinking = enabled ? options : false end
Enables thinking for chats this agent builds, applied via Chat#with_thinking. With no options, RubyLLM chooses from the model’s registered controls. Accepts keywords or an options Hash. Pass false to disable it. Passing nil raises ArgumentError.
thinking thinking false thinking effort: :low thinking budget: 10_000 thinking display: :summarized
Source
# File lib/ruby_llm/agent.rb, line 1110
Returns an AgentTool that runs this agent as a subagent: a model hands it a task and gets its answer back. Keywords matching ::inputs are given to every run; the agent’s other inputs become parameters the model fills. Chat#with_tools and ::tools take an Agent class too, and convert it with no inputs.
chat.with_tools(ResearchAgent.to_tool(workspace: current_workspace)) chat.with_tools(ResearchAgent)
Raises ArgumentError for an agent class without a name.
# File lib/ruby_llm/agent.rb, line 203 def tool_options(**options, &block) return @tool_options || {} if options.empty? && !block_given? @tool_options = block_given? ? block : options end
Sets how chats this agent builds use their tools, applied via Chat#with_tool_options. Accepts choice:, calls:, concurrency:, workers:, and rounds:. A block defers evaluation until the chat is built. Called with no arguments, returns the configured options.
tool_options choice: :required, calls: :one tool_options rounds: 25, calls: 50
# File lib/ruby_llm/agent.rb, line 160 def tools(*tools, defer: nil, &block) if tools.empty? && !block_given? @tools_defer = defer unless defer.nil? return @tools || [] end @tools_defer = defer @tools = block_given? ? block : tools.flatten end
Declares the tools for chats this agent builds. A block defers construction until the chat is built. Configure how the model uses them with ::tool_options. Called with no arguments, returns the declared tools.
tools SearchDocs, LookupAccount tools { [TodoTool.new(chat: chat)] }
Pass defer: as Chat#with_tools takes it, or a lambda that decides when the chat is built:
tools SearchDocs, LookupAccount, defer: true tools(defer: -> { many_tools? }) { connected_tools }
With defer: alone it applies to the tools a parent agent declared.
Public Instance Methods
# File lib/ruby_llm/agent.rb, line 1696
Delegates to Chat#add_message. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1446
Delegates to Chat#after_fallback. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1464
Delegates to Chat#after_file_write. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1410
Delegates to Chat#after_message. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1434
Delegates to Chat#after_tool_progress. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1422
Delegates to Chat#after_tool_result. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1482
Delegates to Chat#answer. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1476
Delegates to Chat#approve. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1452
Delegates to Chat#around_join. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1428
Delegates to Chat#around_tool_call. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1738
Delegates to Chat#ask, routing exceptions through the handlers declared with ::rescue_from.
# File lib/ruby_llm/agent.rb, line 1758
Stages a message through Chat#ask_later without calling the provider. Returns the wrapped chat. Exceptions use ::rescue_from handlers.
Source
# File lib/ruby_llm/agent.rb, line 1440
Delegates to Chat#before_fallback. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1404
Delegates to Chat#before_message. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1398
Delegates to Chat#before_request. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1416
Delegates to Chat#before_tool_call. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1494
Deprecated: use Message#cache_until_here or with_instructions(cache_until_here:). Delegates to Chat#cache_until_here, which warns. RubyLLM 3.0 removes it.
Source
# File lib/ruby_llm/agent.rb, line 1574
Delegates to Chat#caching. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1470
Delegates to Chat#cancel. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1672
Delegates to Chat#cancelled?. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1580
Delegates to Chat#citations. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1586
Delegates to Chat#code_execution. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1799 Chat::Rescuable::OPERATIONS.each do |operation| define_method(operation) do |*args, **kwargs, &block| rescuing { chat.public_send(operation, *args, **kwargs, &block) } end end
Compacts the model context through Chat#compact and returns its Message. Exceptions use ::rescue_from handlers.
Source
# File lib/ruby_llm/agent.rb, line 1604
Delegates to Chat#compaction. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1745
Delegates to Chat#complete, routing exceptions through the handlers declared with ::rescue_from.
Source
# File lib/ruby_llm/agent.rb, line 1666
Delegates to Chat#complete?. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1568
Delegates to Chat#concurrency. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1616
Delegates to Chat#context. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1610
Delegates to Chat#context_budget. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1392
Delegates to Chat#convert_unsupported_attachments. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1726
Delegates to Chat#cost. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1786
Counts request tokens through Chat#count_tokens without generating a response. Returns an Integer. Exceptions use ::rescue_from handlers.
# File lib/ruby_llm/agent.rb, line 1488
Delegates to Chat#decline. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1526
Delegates to Chat#deferred_tools. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1652
Source
# File lib/ruby_llm/agent.rb, line 1622
Delegates to Chat#end_user. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1628
Delegates to Chat#fallbacks. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1598
Delegates to Chat#file_store. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1765
Generates one response through Chat#generate without executing tools. Returns a Message. Exceptions use ::rescue_from handlers.
Source
# File lib/ruby_llm/agent.rb, line 1556
Delegates to Chat#headers. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1458
Delegates to Chat#join_queued_messages. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1646
Returns Chat#max_output_tokens from the wrapped chat.
Source
# File lib/ruby_llm/agent.rb, line 1532
Delegates to Chat#mcp. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1514
Delegates to Chat#messages. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1502
Delegates to Chat#model. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1660
Delegates to Chat#model_id. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1808 def owner (chat.respond_to?(:to_llm) ? chat.to_llm : chat).owner end
Returns whoever the usage of the agent’s chat is attributed to, as Chat#owner describes. For a persisted chat, reads it from the record’s chat, since the record leaves owner to the application.
Source
# File lib/ruby_llm/agent.rb, line 1684
Delegates to Chat#pending_questions. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1690
Delegates to Chat#pending_tasks. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1508
Delegates to Chat#provider. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1550
Delegates to Chat#provider_options. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1538
Delegates to Chat#provider_tools. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1702
Delegates to Chat#queue. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1708
Delegates to Chat#queued_messages. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1732
Delegates to Chat#render. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1090
Runs the ::rescue_from handler matching exception and returns its value, or re-raises when no handler matches. The chat operations call this for you.
Source
# File lib/ruby_llm/agent.rb, line 1772
Runs pending tools through Chat#run_tools, respecting approval decisions. Returns the wrapped chat. Exceptions use ::rescue_from handlers.
# File lib/ruby_llm/agent.rb, line 1752
Delegates to Chat#say, the alias for Chat#ask, with ::rescue_from handling.
Source
# File lib/ruby_llm/agent.rb, line 1562
Delegates to Chat#schema. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1592
Delegates to Chat#skills. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1779
Advances the conversation through Chat#step. Returns a Message or nil when no progress is possible. Exceptions use ::rescue_from handlers.
Source
# File lib/ruby_llm/agent.rb, line 1634
Delegates to Chat#thinking. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1720
Delegates to Chat#tokens. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1544
Delegates to Chat#tool_options. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1520
Delegates to Chat#tools. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1678
Delegates to Chat#waiting?. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1338
Delegates to Chat#with_caching. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1308
Delegates to Chat#with_citations. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1344
Delegates to Chat#with_code_execution. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1332
Delegates to Chat#with_compaction. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1362
Delegates to Chat#with_context. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1326
Delegates to Chat#with_context_budget. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1314
Delegates to Chat#with_end_user. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1386
Delegates to Chat#with_fallbacks. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1356
Delegates to Chat#with_file_store. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1374
Delegates to Chat#with_headers. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1254
Delegates to Chat#with_instructions. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1296
Delegates to Chat#with_max_output_tokens. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1266
Delegates to Chat#with_mcp. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1284
Delegates to Chat#with_model. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1320
Delegates to Chat#with_owner. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1368
Delegates to Chat#with_provider_options. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1272
Delegates to Chat#with_provider_tools. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1380
Delegates to Chat#with_schema. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1350
Delegates to Chat#with_skills. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1290
Delegates to Chat#with_temperature. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1302
Delegates to Chat#with_thinking. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1278
Delegates to Chat#with_tool_options. See that method for arguments and return values.
# File lib/ruby_llm/agent.rb, line 1260
Delegates to Chat#with_tools. See that method for arguments and return values.
Source
# File lib/ruby_llm/agent.rb, line 1714
Delegates to Chat#withdraw. See that method for arguments and return values.