Class: Langchain::ToolDefinition::FunctionSchemas

Inherits:
Object
  • Object
show all
Defined in:
lib/langchain/tool_definition.rb

Overview

Manages schemas for functions

Instance Method Summary collapse

Constructor Details

#initialize(tool_name) ⇒ FunctionSchemas

Returns a new instance of FunctionSchemas.


80
81
82
83
# File 'lib/langchain/tool_definition.rb', line 80

def initialize(tool_name)
  @schemas = {}
  @tool_name = tool_name
end

Instance Method Details

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

Adds a function to the schemas

Parameters:

  • method_name (Symbol)

    Name of the method to add

  • description (String)

    Description of the function

Yields:

  • Block that defines the parameters for the function

Raises:

  • (ArgumentError)

    If a block is defined and no parameters are specified for the function


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/langchain/tool_definition.rb', line 91

def add_function(method_name:, description:, &block)
  name = "#{@tool_name}__#{method_name}"

  if block_given? # rubocop:disable Performance/BlockGivenWithExplicitBlock
    parameters = ParameterBuilder.new(parent_type: "object").build(&block)

    if parameters[:properties].empty?
      raise ArgumentError, "Function parameters must have at least one property defined within it, if a block is provided"
    end
  end

  @schemas[method_name] = {
    type: "function",
    function: {name:, description:, parameters:}.compact
  }
end

#to_anthropic_formatString

Converts schemas to Anthropic-compatible format

Returns:

  • (String)

    JSON string of schemas in Anthropic format


118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/langchain/tool_definition.rb', line 118

def to_anthropic_format
  @schemas.values.map do |schema|
    # Adds a default input_schema if no parameters are present
    schema[:function][:parameters] ||= {
      type: "object",
      properties: {},
      required: []
    }

    schema[:function].transform_keys(parameters: :input_schema)
  end
end

#to_google_gemini_formatString

Converts schemas to Google Gemini-compatible format

Returns:

  • (String)

    JSON string of schemas in Google Gemini format


134
135
136
# File 'lib/langchain/tool_definition.rb', line 134

def to_google_gemini_format
  @schemas.values.map { |schema| schema[:function] }
end

#to_openai_formatString

Converts schemas to OpenAI-compatible format

Returns:

  • (String)

    JSON string of schemas in OpenAI format


111
112
113
# File 'lib/langchain/tool_definition.rb', line 111

def to_openai_format
  @schemas.values
end