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.



66
67
68
69
# File 'lib/langchain/tool_definition.rb', line 66

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



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/langchain/tool_definition.rb', line 77

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



104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/langchain/tool_definition.rb', line 104

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



120
121
122
# File 'lib/langchain/tool_definition.rb', line 120

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



97
98
99
# File 'lib/langchain/tool_definition.rb', line 97

def to_openai_format
  @schemas.values
end