Class: DSPy::Tools::Toolset::ToolProxy

Inherits:
Base
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/dspy/tools/toolset.rb

Overview

Inner class that wraps a method as a tool, compatible with DSPy::Tools::Base interface

Instance Method Summary collapse

Methods inherited from Base

call_schema, tool_description, tool_name

Constructor Details

#initialize(instance, method_name, tool_name, description) ⇒ ToolProxy

Returns a new instance of ToolProxy.



149
150
151
152
153
154
# File 'lib/dspy/tools/toolset.rb', line 149

def initialize(instance, method_name, tool_name, description)
  @instance = instance
  @method_name = method_name
  @tool_name_override = tool_name
  @description_override = description
end

Instance Method Details

#call(**kwargs) ⇒ Object



179
180
181
# File 'lib/dspy/tools/toolset.rb', line 179

def call(**kwargs)
  @instance.send(@method_name, **kwargs)
end

#descriptionObject



162
163
164
# File 'lib/dspy/tools/toolset.rb', line 162

def description
  @description_override
end

#dynamic_call(args_json) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/dspy/tools/toolset.rb', line 184

def dynamic_call(args_json)
  schema = @instance.class.schema_for_method(@method_name)

  if schema[:properties].empty?
    @instance.send(@method_name)
  else
    # Parse arguments
    args = case args_json
          when Hash
            args_json
          when String
            begin
              JSON.parse(args_json)
            rescue JSON::ParserError
              return "Error: Invalid JSON input"
            end
          else
            return "Error: Expected Hash or JSON string"
          end

    # Convert string keys to symbols and validate types
    kwargs = {}
    schema[:properties].each do |param_name, param_schema|
      key = param_name.to_s
      if args.key?(key)
        kwargs[param_name] = convert_argument_type(args[key], param_schema)
      elsif schema[:required].include?(key)
        return "Error: Missing required parameter: #{key}"
      end
    end

    @instance.send(@method_name, **kwargs)
  end
rescue => e
  "Error: #{e.message}"
end

#nameObject



157
158
159
# File 'lib/dspy/tools/toolset.rb', line 157

def name
  @tool_name_override
end

#schemaObject



167
168
169
170
171
172
173
174
175
# File 'lib/dspy/tools/toolset.rb', line 167

def schema
  schema_obj = @instance.class.schema_for_method(@method_name)
  tool_info = {
    name: name,
    description: description,
    parameters: schema_obj
  }
  JSON.generate(tool_info)
end