Class: Truffle::Tool

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

Overview

A tool the agent can call.

A tool is a name, a human-readable description (the model reads this to decide when to call it), a JSON-Schema parameter spec, and a callable that actually runs. Build one with the block DSL:

weather = Truffle::Tool.define("get_weather", "Look up the weather for a city") do
param :city, :string, "City name, e.g. 'Berlin'", required: true
param :units, :string, "celsius or fahrenheit"
run { |city:, units: "celsius"| WeatherApi.fetch(city, units) }
end

The block runs in a small builder context so param and run read cleanly.

Defined Under Namespace

Classes: Builder

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, description:, parameters:, handler:) ⇒ Tool

Returns a new instance of Tool.



20
21
22
23
24
25
# File 'lib/truffle/tool.rb', line 20

def initialize(name:, description:, parameters:, handler:)
  @name = name.to_s
  @description = description.to_s
  @parameters = parameters
  @handler = handler
end

Instance Attribute Details

#descriptionObject (readonly)

Returns the value of attribute description.



18
19
20
# File 'lib/truffle/tool.rb', line 18

def description
  @description
end

#handlerObject (readonly)

Returns the value of attribute handler.



18
19
20
# File 'lib/truffle/tool.rb', line 18

def handler
  @handler
end

#nameObject (readonly)

Returns the value of attribute name.



18
19
20
# File 'lib/truffle/tool.rb', line 18

def name
  @name
end

#parametersObject (readonly)

Returns the value of attribute parameters.



18
19
20
# File 'lib/truffle/tool.rb', line 18

def parameters
  @parameters
end

Class Method Details

.define(name, description, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/truffle/tool.rb', line 27

def self.define(name, description, &block)
  builder = Builder.new
  builder.instance_eval(&block) if block
  new(
    name: name,
    description: description,
    parameters: builder.schema,
    handler: builder.handler
  )
end

Instance Method Details

#call(arguments) ⇒ Object

Run the tool. arguments is a Hash with string keys (as the model emits); they are symbolized so the handler can use keyword arguments.



40
41
42
43
44
# File 'lib/truffle/tool.rb', line 40

def call(arguments)
  kwargs = (arguments || {}).each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
  result = handler.call(**kwargs)
  result.is_a?(String) ? result : result.inspect
end

#to_schemaObject

JSON-Schema-shaped function spec, provider-neutral. Providers wrap this in whatever envelope they need (OpenAI: function:{...}).



48
49
50
51
52
53
54
# File 'lib/truffle/tool.rb', line 48

def to_schema
  {
    name: name,
    description: description,
    parameters: parameters
  }
end