Tool – dare delle mani al modello
Un modello linguistico scrive soltanto testo. Non può controllare il meteo di oggi, un ordine nel tuo database o il prezzo nel tuo negozio – sa solo ciò che ha imparato durante l'addestramento. I tool (strumenti) cambiano le cose: descrivi una classe Ruby, il modello può chiedere che venga chiamata, RubyLLM la esegue e gli rimanda il risultato, e il modello scrive la sua risposta usandolo.
Un tool è una sottoclasse di RubyLLM::Tool con una description (a che cosa serve – il modello la legge), i suoi parameter e un metodo execute:
install_gem "ruby_llm"
require "ruby_llm"
require "chunky_llm" # Chunky Mini, il piccolo modello di questa pagina
class Weather < RubyLLM::Tool
description "Gets the current weather for a city"
parameter :city, description: "Name of the city, such as Bern"
def execute(city:)
reports = { "Bern" => "sunny, 21 °C", "Lugano" => "rain, 17 °C", "Basel" => "cloudy, 19 °C" }
reports.fetch(city) { { error: "No weather data for #{city}" } }
end
end
chat = RubyLLM.chat.with_tools(Weather)
chat.ask("What's the weather in Bern?").contentLa nostra stazione meteo è un hash, ma execute potrebbe benissimo interrogare un vero servizio meteo. Che cosa è successo? Lo mostrano i messaggi:
chat.messages.each do |m|
calls = m.tool_calls.to_h.values.map { |call| "#{call.name}(#{call.arguments})" }
puts "#{m.role.to_s.ljust(9)} #{calls.join(', ')} #{m.content}"
end
nilQuattro messaggi per una domanda:
user– la domanda.assistant– nessun testo, ma una chiamata di tool (tool call): il modello chiedeweatherconcity: "Bern". Ha scelto il tool in base alla sua descrizione e ha preso l'argomento dalla domanda.tool– RubyLLM ha eseguitoWeather#executee ha messo il risultato nella chat.assistant– con il risultato, il modello scrive la risposta.
RubyLLM ripete questo ciclo da solo finché il modello risponde senza chiedere un tool. Una domanda per cui il tool non è adatto non riceve nessuna chiamata:
chat.ask("Who created Ruby?").contentUn modello può chiamare più tool insieme, o lo stesso tool più volte – qui una volta per città:
RubyLLM.chat.with_tools(Weather).ask("What's the weather in Basel and Lugano?").contentOsservare il ciclo
before_tool_call e after_tool_result sono callback: blocchi che la chat chiama prima e dopo ogni tool. Le app li usano per mostrare «Controllo il meteo…» o per registrare che cosa ha fatto il modello:
log = []
watched = RubyLLM.chat.with_tools(Weather)
watched.before_tool_call { |call| log << "calls #{call.name} with #{call.arguments}" }
watched.after_tool_result { |result| log << "gets #{result.inspect}" }
watched.ask("Is it raining in Atlantis?")
logAd Atlantide non c'è meteo, quindi execute restituisce { error: ... }. È il modo giusto per un errore previsto: il modello legge l'errore e può dirlo all'utente, invece di far andare in crash il programma.
Parametri con tipi
Senza tipo un parametro è una stringa. type: :integer, :number o :boolean dicono al modello che cosa inviare – RubyLLM descrive il tool come JSON Schema:
class Dice < RubyLLM::Tool
description "Rolls a die and returns the number it shows"
parameter :sides, type: :integer, description: "How many sides the die has"
def execute(sides:)
rand(1..sides)
end
end
puts Dice.new.parameters_schema
RubyLLM.chat.with_tools(Dice).ask("Roll a die with 20 sides!").contentAgenti
Lo stesso modello, le stesse istruzioni e gli stessi tool in molti punti di un'app? Mettili in un agente (agent): una classe che dice come sono impostate le sue chat. new crea una chat che ha già tutto:
class WeatherDesk < RubyLLM::Agent
instructions "You answer questions about the weather in one short sentence."
tools Weather
end
WeatherDesk.new.ask("Weather in Basel?").contentI tool veri raggiungono il mondo: un'API meteo con Faraday (che RubyLLM porta con sé), i tuoi modelli Active Record, una ricerca. Un tool agisce con gli argomenti del modello, quindi controllali come faresti con i dati di un modulo – un tool che cancella o paga qualcosa riceve requires_approval, e la chat aspetta il sì di una persona. bin/rails generate ruby_llm:tool Weather scrive una classe tool, ruby_llm:agent un agente. RubyLLM prende anche tool da server MCP (RubyLLM::MCP) e permette a un modello di eseguire codice in una sandbox (code_execution).
Shipping con la descrizione «Calculates the shipping cost of a parcel from its weight» e un parametro :kilos di tipo :number; execute restituisce il prezzo: 7 franchi più 2 franchi al chilo. Poi chiedi a una chat con il tool: «What does shipping a 3 kg parcel cost?» La cella restituisce la risposta.install_gem "ruby_llm"
require "ruby_llm"
require "chunky_llm" # Chunky Mini, il piccolo modello di questa pagina
# class Shipping < RubyLLM::Tool
# description "..."
# parameter :kilos, type: :number, description: "..."
#
# def execute(kilos:)
# end
# end