Module: Anthropic::Helpers::InputSchema::JsonSchemaConverter

Included in:
ArrayOf, BaseModel, Boolean, EnumOf, UnionOf
Defined in:
lib/anthropic/helpers/input_schema/json_schema_converter.rb

Overview

To customize the JSON schema conversion for a type, implement the ‘JsonSchemaConverter` interface.

Constant Summary collapse

POINTERS =

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

Object.new.tap do
  _1.define_singleton_method(:inspect) do
    "#<#{Anthropic::Helpers::InputSchema::JsonSchemaConverter}::POINTERS>"
  end
end.freeze
NO_REF =

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

Object.new.tap do
  _1.define_singleton_method(:inspect) do
    "#<#{Anthropic::Helpers::InputSchema::JsonSchemaConverter}::NO_REF>"
  end
end.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.assoc_meta!(schema, meta:) ⇒ 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.

Parameters:

  • schema (Hash{Symbol=>Object})


65
66
67
68
# File 'lib/anthropic/helpers/input_schema/json_schema_converter.rb', line 65

def assoc_meta!(schema, meta:)
  xformed = meta.transform_keys(Anthropic::Helpers::InputSchema::PROPERTY_MAPPING)
  schema.merge!(xformed)
end

.cache_def!(state, type:, &blk) ⇒ 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.

Parameters:

  • state (Hash{Symbol=>Object})

    @option state [HashObject=>String] :defs

    @option state [Array<String>] :path

  • type (Object)
  • blk (Proc)


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/anthropic/helpers/input_schema/json_schema_converter.rb', line 82

def cache_def!(state, type:, &blk)
  defs, path = state.fetch_values(:defs, :path)
  if (stored = defs[type])
    pointers = stored.fetch(Anthropic::Helpers::InputSchema::JsonSchemaConverter::POINTERS)
    pointers.first.except(Anthropic::Helpers::InputSchema::JsonSchemaConverter::NO_REF).tap do
      pointers << _1
    end
  else
    ref_path = String.new
    ref = {"$ref": ref_path}
    stored = {
      Anthropic::Helpers::InputSchema::JsonSchemaConverter::POINTERS => [ref]
    }
    defs.store(type, stored)
    schema = blk.call
    ref_path.replace("#/$defs/#{path.join('/')}")
    stored.update(schema)
    ref
  end
end

.to_json_schema(type) ⇒ Hash{Symbol=>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.

Parameters:

Returns:

  • (Hash{Symbol=>Object})


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/anthropic/helpers/input_schema/json_schema_converter.rb', line 108

def to_json_schema(type)
  defs = {}
  state = {defs: defs, path: []}
  schema = Anthropic::Helpers::InputSchema::JsonSchemaConverter.to_json_schema_inner(
    type,
    state: state
  )
  reused_defs = {}
  defs.each_value do |acc|
    sch = acc.except(Anthropic::Helpers::InputSchema::JsonSchemaConverter::POINTERS)
    pointers = acc.fetch(Anthropic::Helpers::InputSchema::JsonSchemaConverter::POINTERS)

    no_refs, refs = pointers.partition do
      _1.delete(Anthropic::Helpers::InputSchema::JsonSchemaConverter::NO_REF)
    end

    case refs
    in [ref]
      ref.replace(ref.except(:$ref).merge(sch))
    in [_, ref, *]
      reused_defs.store(ref.fetch(:$ref), sch)
      refs.each do
        next if (meta = _1.except(:$ref)).empty?
        # JSON Schema does not allow keyword properties to be defined alongside a $ref.
        # If we have a keyword property associated with a $ref, it must be wrapped in an allOf.
        _1.replace(allOf: [_1.slice(:$ref), meta])
      end
    else
    end
    no_refs.each { _1.replace(_1.except(:$ref).merge(sch)) }
  end

  xformed = reused_defs.transform_keys { _1.delete_prefix("#/$defs/") }
  xformed.empty? ? schema : {"$defs": xformed}.update(schema)
end

.to_json_schema_inner(type, state:) ⇒ Hash{Symbol=>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.

Parameters:

Returns:

  • (Hash{Symbol=>Object})

Raises:

  • (ArgumentError)


155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
# File 'lib/anthropic/helpers/input_schema/json_schema_converter.rb', line 155

def to_json_schema_inner(type, state:)
  case type
  in {"$ref": String}
    return type
  in Anthropic::Helpers::InputSchema::JsonSchemaConverter
    return type.to_json_schema_inner(state: state)
  in Class
    case type
    in -> { _1 <= NilClass }
      return {type: "null"}
    in -> { _1 <= Integer }
      return {type: "integer"}
    in -> { _1 <= Float }
      return {type: "number"}
    in -> { _1 <= Symbol || _1 <= String }
      return {type: "string"}
    else
    end
  in _ if Anthropic::Internal::Util.primitive?(type)
    return {const: type.is_a?(Symbol) ? type.to_s : type}
  else
  end

  models = %w[
    NilClass
    String
    Symbol
    Integer
    Float
    Anthropic::Boolean
    Anthropic::ArrayOf
    Anthropic::EnumOf
    Anthropic::UnionOf
    Anthropic::BaseModel
  ]
  # rubocop:disable Layout/LineLength
  message = "#{type} does not implement the #{Anthropic::Helpers::InputSchema::JsonSchemaConverter} interface. Please use one of the supported types: #{models}"
  # rubocop:enable Layout/LineLength
  raise ArgumentError.new(message)
end

.to_nilable(schema) ⇒ Hash{Symbol=>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.

Parameters:

  • schema (Hash{Symbol=>Object})

Returns:

  • (Hash{Symbol=>Object})


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/anthropic/helpers/input_schema/json_schema_converter.rb', line 43

def to_nilable(schema)
  null = "null"
  case schema
  in {"$ref": String} | {allOf: _}
    # For references (simple or with allOf pattern for descriptions),
    # wrap in anyOf with null. The allOf pattern is used when we need
    # to add a description to a $ref (JSON Schema doesn't allow
    # additional properties alongside $ref).
    {anyOf: [schema, {type: null}]}
  in {anyOf: schemas}
    null = {type: null}
    schemas.any? { _1 == null || _1 == {type: ["null"]} } ? schema : {anyOf: [*schemas, null]}
  in {type: String => type}
    type == null ? schema : schema.update(type: [type, null])
  in {type: Array => types}
    types.include?(null) ? schema : schema.update(type: [*types, null])
  end
end

Instance Method Details

#to_json_schema_inner(state:) ⇒ Hash{Symbol=>Object}

The exact JSON schema produced is subject to improvement between minor release versions.

Parameters:

  • state (Hash{Symbol=>Object})

    @option state [HashObject=>String] :defs

    @option state [Array<String>] :path

Returns:

  • (Hash{Symbol=>Object})


32
# File 'lib/anthropic/helpers/input_schema/json_schema_converter.rb', line 32

def to_json_schema_inner(state:) = (raise NotImplementedError)