Module: LLM::Schema::Utils Private

Extended by:
Utils
Included in:
Utils
Defined in:
lib/llm/schema.rb

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Instance Method Summary collapse

Instance Method Details

#resolve(schema, type) ⇒ LLM::Schema::Leaf

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Resolves a parameter type into a leaf of the schema.

A proc is called for its type, and whatever it returns is resolved in turn, so a type that can only be known at runtime - an enum of the keys a store holds right now - can be declared without being evaluated when the class that declares it is defined.

Parameters:

Returns:



70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/llm/schema.rb', line 70

def resolve(schema, type)
  if LLM::Schema::Leaf === type
    type
  elsif ::Proc === type
    Deferred.new { resolve(schema, type.call) }
  elsif ::Array === type
    resolve_array(schema, type)
  elsif Class === type && type.respond_to?(:object)
    type.object
  else
    target = type.name.split("::").last.downcase
    schema.public_send(target)
  end
end

#resolve_array(schema, values) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



85
86
87
88
89
90
91
92
# File 'lib/llm/schema.rb', line 85

def resolve_array(schema, values)
  item = if values.size == 1
    resolve(schema, values[0])
  else
    schema.any_of(*values.map { resolve(schema, _1) })
  end
  schema.array(item)
end

#fetch(properties, name) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



94
95
96
# File 'lib/llm/schema.rb', line 94

def fetch(properties, name)
  properties[name] || properties.fetch(name.to_s)
end

#close(node) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a copy of a JSON schema where every object is closed with "additionalProperties": false. OpenAI and Azure reject tool parameters that leave an object open, and they validate nested objects as well as the root.

Parameters:

  • node (Object) —

    A schema, a Hash of properties, or an Array of either

Returns:



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/llm/schema.rb', line 106

def close(node)
  case node
  when LLM::Schema::Leaf
    close(node.to_h)
  when LLM::Object
    close(node.to_h)
  when Hash
    node.to_h { |key, value| [key, close(value)] }
        .then { _1[:type] == "object" ? _1.merge(additionalProperties: false) : _1 }
  when Array
    node.map { close(_1) }
  else
    node
  end
end