Class: RubyLLM::Tool

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_llm/tool.rb

Defined Under Namespace

Classes: Builder, Parameter

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Tool

Returns a new instance of Tool.



54
55
56
57
# File 'lib/ruby_llm/tool.rb', line 54

def initialize(name)
  @name = name
  @parameters = {}
end

Instance Attribute Details

#descriptionObject (readonly)

Returns the value of attribute description.



45
46
47
# File 'lib/ruby_llm/tool.rb', line 45

def description
  @description
end

#handlerObject (readonly)

Returns the value of attribute handler.



45
46
47
# File 'lib/ruby_llm/tool.rb', line 45

def handler
  @handler
end

#nameObject (readonly)

Returns the value of attribute name.



45
46
47
# File 'lib/ruby_llm/tool.rb', line 45

def name
  @name
end

#parametersObject (readonly)

Returns the value of attribute parameters.



45
46
47
# File 'lib/ruby_llm/tool.rb', line 45

def parameters
  @parameters
end

Class Method Details

.define(name, &block) ⇒ Object



47
48
49
50
51
52
# File 'lib/ruby_llm/tool.rb', line 47

def self.define(name, &block)
  tool = new(name)
  builder = Builder.new(tool)
  builder.instance_eval(&block)
  tool
end

.from_method(method, description: nil) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/ruby_llm/tool.rb', line 75

def from_method(method, description: nil)
  define(method.name.to_s) do
    description description if description

    method.parameters.each do |type, name|
      param name, required: (type == :req)
    end

    handler do |args|
      method.owner.new.public_send(method.name, **args)
    end
  end
end

Instance Method Details

#call(args) ⇒ Object

Raises:



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/ruby_llm/tool.rb', line 59

def call(args)
  raise Error, "No handler defined for tool #{name}" unless @handler

  begin
    RubyLLM.logger.debug "Calling tool #{name}(#{args.inspect})"
    args = symbolize_keys(args)
    result = @handler.call(args)
    RubyLLM.logger.debug "Tool #{name}(#{args.inspect}) returned: #{result.inspect}"
    result
  rescue StandardError => e
    RubyLLM.logger.error "Tool #{name}(#{args.inspect}) failed with error #{e.message}"
    { error: e.message }
  end
end