Module: Langchain::ToolDefinition

Overview

Extends a class to be used as a tool in the assistant. A tool is a collection of functions (methods) used to perform specific tasks.

Usage

  1. Extend your class with ToolDefinition

  2. Use #define_function to define each function of the tool

Key Concepts

These methods support various data types and nested structures, allowing for flexible and expressive tool definitions.

Examples:

Defining a tool with various property types and configurations

define_function :sample_function, description: "Demonstrates various property types and configurations" do
  property :string_prop, type: "string", description: "A simple string property"
  property :number_prop, type: "number", description: "A number property"
  property :integer_prop, type: "integer", description: "An integer property"
  property :boolean_prop, type: "boolean", description: "A boolean property"
  property :enum_prop, type: "string", description: "An enum property", enum: ["option1", "option2", "option3"]
  property :required_prop, type: "string", description: "A required property", required: true
  property :array_prop, type: "array", description: "An array property" do
    item type: "string", description: "Array item"
  end
  property :object_prop, type: "object", description: "An object property" do
    property :nested_string, type: "string", description: "Nested string property"
    property :nested_number, type: "number", description: "Nested number property"
  end
end

Defined Under Namespace

Classes: FunctionSchemas, ParameterBuilder

Instance Method Summary collapse

Instance Method Details

#define_function(method_name, description:) { ... } ⇒ Object

Defines a function for the tool

Parameters:

  • method_name (Symbol)

    Name of the method to define

  • description (String)

    Description of the function

Yields:

  • Block that defines the parameters for the function



43
44
45
# File 'lib/langchain/tool_definition.rb', line 43

def define_function(method_name, description:, &block)
  function_schemas.add_function(method_name:, description:, &block)
end

#function_schemasFunctionSchemas

Returns the FunctionSchemas instance for this tool

Returns:



50
51
52
# File 'lib/langchain/tool_definition.rb', line 50

def function_schemas
  @function_schemas ||= FunctionSchemas.new(tool_name)
end

#tool_nameString

Returns the snake_case version of the class name as the tool’s name

Returns:

  • (String)

    The snake_case version of the class name



57
58
59
60
61
62
# File 'lib/langchain/tool_definition.rb', line 57

def tool_name
  @tool_name ||= name
    .gsub("::", "_")
    .gsub(/(?<=[A-Z])(?=[A-Z][a-z])|(?<=[a-z\d])(?=[A-Z])/, "_")
    .downcase
end