Class: ChatgptRb::Function

Inherits:
Object
  • Object
show all
Defined in:
lib/chatgpt_rb/function.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name: nil, description: nil, parameters: [], implementation: nil) ⇒ Function

Returns a new instance of Function.

Parameters:

  • name (String, nil) (defaults to: nil)
  • description (String, nil) (defaults to: nil)
  • parameters (Array<ChatgptRb::Parameter>) (defaults to: [])
  • implementation (Lambda, nil) (defaults to: nil)


9
10
11
12
13
14
# File 'lib/chatgpt_rb/function.rb', line 9

def initialize(name: nil, description: nil, parameters: [], implementation: nil)
  @name = name
  @description = description
  @parameters = parameters
  @implementation = implementation
end

Instance Attribute Details

#descriptionObject

Returns the value of attribute description.



3
4
5
# File 'lib/chatgpt_rb/function.rb', line 3

def description
  @description
end

#implementationObject

Returns the value of attribute implementation.



3
4
5
# File 'lib/chatgpt_rb/function.rb', line 3

def implementation
  @implementation
end

#nameObject

Returns the value of attribute name.



3
4
5
# File 'lib/chatgpt_rb/function.rb', line 3

def name
  @name
end

#parametersObject

Returns the value of attribute parameters.



3
4
5
# File 'lib/chatgpt_rb/function.rb', line 3

def parameters
  @parameters
end

Instance Method Details

#as_jsonHash

Returns:

  • (Hash)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/chatgpt_rb/function.rb', line 24

def as_json
  {
    type: "function",
    function: {
      name:,
      description:,
      parameters: {
        type: "object",
        properties: parameters.each_with_object({}) do |parameter, hash|
          hash[parameter.name] = parameter.as_json
        end,
        required: parameters.select(&:required?).map(&:name),
      },
    }.compact
  }
end

#validate!Object

Raises:

  • (ArgumentError)


16
17
18
19
20
21
# File 'lib/chatgpt_rb/function.rb', line 16

def validate!
  metaschema = JSON::Validator.validator_for_name("draft4").metaschema
  return if JSON::Validator.validate(metaschema, as_json[:function])

  raise ArgumentError, "Invalid function declaration for #{name}: #{as_json[:function]}"
end