class RubyLLM::Tool
A Tool is an action an AI model can call during a chat. Subclasses describe themselves with ::description, declare their arguments, and implement execute:
class Weather < RubyLLM::Tool description "Gets current weather for a location" def execute(latitude:, longitude:) response = Faraday.get "https://api.open-meteo.com/v1/forecast", latitude: latitude, longitude: longitude, current: "temperature_2m,wind_speed_10m" JSON.parse(response.body) end end chat.with_tools(Weather).ask "What's the weather in Berlin?"
When no parameters are declared, the argument schema is inferred from execute’s keyword arguments: required keywords become required string parameters and optional keywords become optional ones. Use ::parameter or ::parameters when arguments need explicit types, descriptions, or structure.
Public Class Methods
Source
# File lib/ruby_llm/tool.rb, line 331 def defer @deferred = true end
Keeps this tool’s definition out of the model’s context until the provider’s tool search loads it. Pass +defer: false+ to Chat#with_tools to offer it up front in one chat. See Chat#deferred_tools.
class DeepResearch < RubyLLM::Tool description "Runs a multi-step web investigation" defer end
# File lib/ruby_llm/tool.rb, line 165 def description(text = nil) return @description unless text @description = text end
Sets the description the model sees for this tool, or returns the current description when called without an argument.
class Weather < RubyLLM::Tool description "Gets current weather for a location" end
Source
# File lib/ruby_llm/tool.rb, line 286 def exclusive @exclusive = true end
Declares that this tool runs by itself. When a chat runs a round of tool calls concurrently (see Chat#with_tool_options), an exclusive call waits for the calls before it to finish, and the calls after it wait for it, while the other tools still run in parallel. Use it for tools that share state, such as a browser page. When an exclusive call waits for an approval or a Task, the calls after it stay pending until it finishes.
class BrowserClick < RubyLLM::Tool exclusive end
Source
# File lib/ruby_llm/tool.rb, line 291 def exclusive? @exclusive || false end
Returns whether this tool was declared with ::exclusive.
Source
# File lib/ruby_llm/tool.rb, line 356 def inline_limit(characters = (get = true)) return @inline_limit if get unless characters == false || (characters.is_a?(Integer) && characters.positive?) raise ArgumentError, 'inline_limit takes a positive number of characters or false' end @inline_limit = characters end
Sets how many characters this tool’s results may have and still go to the model whole. In a chat with a file store, a longer result is saved as a file, and the model gets its start and the file’s path. It overrides the chat’s own limit (see Chat#with_file_store). false always sends results whole, for tools that already return what they find in pages. Without an argument, returns the declared value, or nil.
class ExportOrders < RubyLLM::Tool inline_limit 50_000 end
# File lib/ruby_llm/tool.rb, line 186 def namespace(value = (get = true), description: nil) return @namespace if get @namespace = value&.to_s @namespace_description = description @namespace end
Puts the tool in a namespace, or returns its namespace. Tools in different namespaces can share a name. description: tells the model what the namespace’s tools are for, on APIs that describe namespaces. Pass nil to remove an inherited namespace.
class CustomerLookup < RubyLLM::Tool namespace "crm", description: "Customer records and orders" end
A native client toolset, such as Anthropic’s computer toolset, calls the tools in its own namespace:
class Screenshot < RubyLLM::Tool namespace "computer" end
Source
# File lib/ruby_llm/tool.rb, line 205 def parameter(name, **) declared_parameters[name] = Parameter.new(name, **) end
Declares a parameter for the tool. options accepts type: (defaults to 'string'), description:, and required: (defaults to true).
class Distance < RubyLLM::Tool description "Calculates distance between two cities" parameter :origin, description: "Origin city name" parameter :destination, description: "Destination city name" parameter :units, type: :string, description: "metric or imperial", required: false end
# File lib/ruby_llm/tool.rb, line 230 def parameters(schema = nil, &block) if schema.nil? && block.nil? raise ArgumentError, 'parameters requires a schema or a block; declare single arguments with parameter' end @parameters_schema_definition = SchemaDefinition.new(schema:, block:) self end
Sets the JSON Schema for the tool’s arguments. Accepts a schema hash, a Schematist::Schema class or instance, or a block written in the schematist DSL. Returns self.
class Scheduler < RubyLLM::Tool description "Books a meeting" parameters do object :window, description: "Time window to reserve" do string :start, description: "ISO8601 start time" string :finish, description: "ISO8601 end time" end array :participants, of: :string end end
Raises ArgumentError when called without a schema or a block.
# File lib/ruby_llm/tool.rb, line 313 def provider_options(options = (get = true)) return @provider_options ||= {} if get raise ArgumentError, 'provider_options does not accept nil' if options.nil? @provider_options = options.to_h self end
Sets provider-specific metadata, such as Anthropic’s cache_control hints, merged verbatim into the tool payload sent to the provider. Without an argument, returns the current options.
provider_options cache_control: { type: "ephemeral" }
Raises ArgumentError if options is nil.
# File lib/ruby_llm/tool.rb, line 265 def requires_approval(&resolver) @requires_approval = true @approval_resolver = resolver end
Declares that this tool must be approved before it executes. The conversation loop pauses the tool call until a decision is recorded with Chat#approve or Chat#decline, so Chat#complete returns cleanly and can be called again once the decision exists. In Rails the decision persists on the tool call record and survives process restarts.
class IssueRefund < RubyLLM::Tool requires_approval def execute(order_id:) Refunds.issue!(order_id) end end
Pass a block to resolve the decision yourself instead of using the recorded one. The block receives the ToolCall and returns true to execute, false to deny, or nil while the decision is pending.
The block never runs at class definition. The loop consults it whenever it needs the decision, which can be several times while the call is pending, including after a crashed job resumes, so write it as an idempotent read. If it also creates the approval request, make that a find-or-create.
requires_approval { |tool_call| Approvals.status(tool_call.id) }
# File lib/ruby_llm/tool.rb, line 71
Registers a handler for exceptions a call raises when a chat runs the tool, from execute, resume, or a call the tool overrides. Name the handler with with: or pass a block; either runs on the tool instance. The handler’s return value becomes the call’s result, as if execute had returned it, so the model reads it and the chat goes on. Re-raise inside a handler to stop the chat with the exception, as an unhandled one does. Handlers only run for calls a chat makes. Calling call or execute yourself is supported and runs without handlers, so exceptions reach you.
class ApplicationTool < RubyLLM::Tool rescue_from StandardError, with: :report_failure rescue_from Faraday::Error do |error| { error: "The service didn't answer (#{error.class.name.split("::").last}). Try again later." } end private def report_failure(error) Rails.error.report(error, context: { tool: name }) { error: "This tool failed unexpectedly. Trying the same call again won't help." } end end
Handlers are searched in reverse declaration order, a class’s own before its parent’s, so the last matching one wins. Subclasses use their parents’ handlers, including ones declared after the subclass, so a handler on Tool itself also covers RubyLLM’s own tools, such as CodeExecution. Declare handlers for a server’s tools on its MCP class. A question from Tool#ask and a cancelled chat never reach a handler.
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/tool.rb, line 144 def tool_name return @tool_name if @tool_name normalized = name.to_s.dup.force_encoding('UTF-8').unicode_normalize(:nfkd) ascii_name = normalized.encode('ASCII', replace: '').gsub(/[^a-zA-Z0-9_-]/, '-') derived = Support::Utils.underscore(ascii_name).delete_suffix('_tool') @tool_name = derived if name derived end
Returns the name the model calls this tool by, derived from the class name: underscored, reduced to ASCII, with a trailing “_tool” removed. Override this method to choose a different name.
WeatherLookup.tool_name # => "weather_lookup"
Public Instance Methods
# File lib/ruby_llm/tool.rb, line 574 def ask(message, choices: nil, url: nil, &fields) if [choices, url, fields].compact.size > 1 raise ArgumentError, 'ask takes choices:, url:, or a block of fields: one kind of answer at a time' end state = (Fiber[ASKING] ||= { 'input' => nil, 'asked' => 0 }) index = state['asked'] state['asked'] += 1 requests = Array(state['input']&.[]('requests')) schema = SchemaDefinition.new(block: fields).json_schema if fields question = Question.asked(index, message, choices:, url:, schema:) stored = answered_as(requests[index], question) return stored.asked_answer(fields) if stored asked = requests.first(index).map { |data| Question.from_h(data) } raise InputRequiredError.new(name, { 'requests' => [*asked, question] }) end
Asks the person who runs the chat message while execute runs, and returns their answer. The call pauses until they answer (see Chat#pending_questions), then execute runs again from the top, and this time ask returns the answer:
def execute(destination:) seat = ask("Window or aisle?", choices: %w[window aisle]) or return "No seat chosen." Flights.book!(destination, seat:) end
Code before ask runs again too, so make it safe to repeat: ask first, then act. A call may ask several questions, one after another, and each run asks them in the same order. An answer reaches only the question it was given to: when a run asks something else in its place, such as after skipping a question or with other choices, the call pauses on the new question, and the questions after it are asked again.
Without options, ask takes free text and returns the String. With choices: it returns the one the person picked, as a String: a choice given as 17 comes back as "17". With a block, it asks for the fields the block declares, in the DSL of Tool.parameters, and returns their values by name. With url:, it asks the person to visit a page, such as to connect an account, and returns true once they say they did.
A Hash of choices: gives each value the title to show for it, and ask returns the value. A value whose title is nil is shown as itself.
ask("Which card?", choices: { "17" => "River bank", "42" => "Money bank" }) # => "42" passenger = ask("Who is flying?") do string :name, description: "As on the passport" integer :age, required: false end passenger # => {name: "Ada Lovelace", age: 36} ask("Connect your calendar", url: authorization_url)
Returns nil when the person declines. Outside a chat, nothing can pause the call, so ask raises InputRequiredError. Raises ArgumentError when given more than one of choices:, url:, and a block.
# File lib/ruby_llm/tool.rb, line 518 def call(tool_call: nil, **arguments) normalized_args = arguments.transform_keys(&:to_sym) validation_error = validate_keyword_arguments(normalized_args) return { error: "Invalid tool arguments: #{validation_error}" } if validation_error RubyLLM.logger.debug { "Tool #{name} called with: #{normalized_args.inspect}" } normalized_args[TOOL_CALL_KEYWORD] = tool_call if execute_accepts_tool_call? result = asking { halting { execute(**normalized_args) } } RubyLLM.logger.debug { "Tool #{name} returned: #{result.inspect}" } result end
Source
# File lib/ruby_llm/tool.rb, line 468 def defer @deferred = true self end
Keeps this tool, and no other of its class, out of the model’s context until tool search loads it, as ::defer does for the class. Returns self. Chat#with_tools and Chat#with_mcp take defer: to decide for every tool they register instead.
chat.with_tools(CurrentTime.new, *connector_tools.map(&:defer))
Source
# File lib/ruby_llm/tool.rb, line 475 def deferred? @deferred || self.class.deferred? end
Source
# File lib/ruby_llm/tool.rb, line 421 def description self.class.description end
Returns the tool description declared on the class with ::description.
Source
# File lib/ruby_llm/tool.rb, line 438 def exclusive? self.class.exclusive? end
Returns whether this tool runs by itself in a concurrent round of tool calls: whether its class was declared with ::exclusive.
Source
# File lib/ruby_llm/tool.rb, line 607 def execute(...) raise NotImplementedError, 'Subclasses must implement #execute' end
Runs the tool with the arguments chosen by the model. Subclasses must implement this method; the base implementation raises NotImplementedError. The return value is sent back to the model. Return a Hash like { error: "..." } to report a recoverable failure.
Declare an optional tool_call: keyword to receive the ToolCall being executed. The keyword is reserved: it never appears in the tool’s argument schema and is filled in by RubyLLM, not by the model.
def execute(query:, tool_call: nil) AuditLog.create!(tool_call_id: tool_call&.id) Search.run(query) end
Source
# File lib/ruby_llm/tool.rb, line 656 def halt(result = nil) throw HALT, Halt.new(result) end
Ends the turn with result as this call’s result: the model is not asked to respond once the round’s other calls finish. It stops execute where it is called, so call it, or return it, when the tool has said the last word, such as filing a ticket a triage turn exists for. The result reaches the conversation as any other, and the next Chat#ask starts a new turn. See Chat#complete?.
def execute(category:) ticket.update!(category:) halt "Filed as #{category}" end
Source
# File lib/ruby_llm/tool.rb, line 444 def inline_limit self.class.inline_limit end
Returns the limit declared on the class with ::inline_limit: a number of characters, false, or nil to use the chat’s.
Source
# File lib/ruby_llm/tool.rb, line 402 def name self.class.tool_name end
Returns the name the model calls this tool by, delegating to ::tool_name. Override either one to choose a different name.
WeatherLookup.new.name # => "weather_lookup"
Source
# File lib/ruby_llm/tool.rb, line 408 def namespace self.class.namespace end
Returns the tool’s namespace, or nil when it has none. See ::namespace.
Source
# File lib/ruby_llm/tool.rb, line 496 def parameters_schema return @parameters_schema if defined?(@parameters_schema) @parameters_schema = begin definition = self.class.parameters_schema_definition if definition&.present? definition.json_schema elsif declared_parameters.any? SchemaDefinition.from_parameters(declared_parameters)&.json_schema else SchemaDefinition.from_parameters(inferred_parameters, allow_empty: true)&.json_schema end end end
Returns the JSON Schema for the tool’s arguments, whether declared explicitly or inferred from the execute signature.
# File lib/ruby_llm/tool.rb, line 674 def progress(message = nil, value: nil, total: nil) Support::ProgressReporter.report(Progress.new(value:, total:, message:)) nil end
Reports what the tool is doing while execute runs, so an application can show it before the result arrives. Chat#after_tool_progress callbacks receive it as a Progress. Pass value: and total: when you can count the work. Outside a chat, the report goes nowhere.
def execute(url:) progress "Downloading #{File.basename(url)}" pages = Scanner.pages(url) pages.each_with_index.map do |page, index| progress "Reading page #{index + 1} of #{pages.size}", value: index + 1, total: pages.size page.text end.join("\n") end
Source
# File lib/ruby_llm/tool.rb, line 457 def provider_options self.class.provider_options end
Returns the provider-specific tool metadata declared on the class.
# File lib/ruby_llm/tool.rb, line 428 def requires_approval?(tool_call = nil) # rubocop:disable Lint/UnusedMethodArgument self.class.requires_approval? end
Returns whether tool_call must be approved before it runs: whether this tool was declared with ::requires_approval. A subclass may override it to decide from the call’s arguments.
Source
# File lib/ruby_llm/tool.rb, line 623 def resume(task, **arguments) raise NotImplementedError, "#{self.class} returned a Task, so it must implement #resume" end
Carries on a call that paused on task, the Task execute returned, with the call’s arguments. Each Chat#complete calls it once for every paused call of the round. Return the call’s result to finish it, or a Task, task itself or a new one, to keep it paused. Tools that return a Task must implement this method; the base implementation raises NotImplementedError.
def resume(task, **) envelope = Signatures.find(task.data["envelope_id"]) envelope.signed? ? "Signed on #{envelope.signed_on}" : task end
Source
# File lib/ruby_llm/tool.rb, line 634 def task(state, tool_call: nil) Task.load(state, tool_call:) end