Class: Vangrail::Tools

Inherits:
Object
  • Object
show all
Defined in:
lib/vangrail/tools.rb

Overview

Named callables a Conversation may invoke, and only after Admission says so. The handler never sees a request that was not granted.

tools = Tools.new
tools.register(:cite) { |args, convo| ... }
convo = Conversation.new(engine, allow: { cite: %i[data] }, tools: tools)
convo.ask('Cite the partition table.')
convo.invoke(:cite, arguments: page)

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(handlers = {}) ⇒ Tools

Returns a new instance of Tools.



17
18
19
20
# File 'lib/vangrail/tools.rb', line 17

def initialize(handlers = {})
  @handlers = {}
  handlers.each { |name, fn| register(name, fn) }
end

Instance Method Details

#call(name, arguments, conversation) ⇒ Object

Raises:

  • (ArgumentError)


43
44
45
46
47
# File 'lib/vangrail/tools.rb', line 43

def call(name, arguments, conversation)
  raise ArgumentError, "unknown tool #{name}" unless key?(name)

  @handlers[name.to_sym].handler.call(arguments, conversation)
end

#dupObject



49
50
51
52
53
# File 'lib/vangrail/tools.rb', line 49

def dup
  copy = self.class.new
  @handlers.each { |name, entry| copy.register(name, entry.handler, readonly: entry.readonly) }
  copy
end

#key?(name) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/vangrail/tools.rb', line 30

def key?(name)
  @handlers.key?(name.to_sym)
end

#namesObject



39
40
41
# File 'lib/vangrail/tools.rb', line 39

def names
  @handlers.keys
end

#readonly?(name) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
# File 'lib/vangrail/tools.rb', line 34

def readonly?(name)
  entry = @handlers[name.to_sym]
  entry&.readonly
end

#register(name, callable = nil, readonly: false, &block) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
# File 'lib/vangrail/tools.rb', line 22

def register(name, callable = nil, readonly: false, &block)
  fn = callable || block
  raise ArgumentError, "tool #{name} needs a callable" unless fn.respond_to?(:call)

  @handlers[name.to_sym] = Entry.new(handler: fn, readonly: readonly)
  self
end

#to_hObject



55
56
57
# File 'lib/vangrail/tools.rb', line 55

def to_h
  @handlers.transform_values(&:handler)
end