in lib/openai/internal/type/union.rb [131:188]
def hash = variants.hash
def coerce(value, state:)
if (target = resolve_variant(value))
return OpenAI::Internal::Type::Converter.coerce(target, value, state: state)
end
strictness = state.fetch(:strictness)
exactness = state.fetch(:exactness)
state[:strictness] = strictness == :strong ? true : strictness
alternatives = []
known_variants.each do |_, variant_fn|
target = variant_fn.call
exact = state[:exactness] = {yes: 0, no: 0, maybe: 0}
state[:branched] += 1
coerced = OpenAI::Internal::Type::Converter.coerce(target, value, state: state)
yes, no, maybe = exact.values
if (no + maybe).zero? || (!strictness && yes.positive?)
exact.each { exactness[_1] += _2 }
state[:exactness] = exactness
return coerced
elsif maybe.positive?
alternatives << [[-yes, -maybe, no], exact, coerced]
end
end
case alternatives.sort_by(&:first)
in []
exactness[:no] += 1
if strictness == :strong
message = "no possible conversion of #{value.class} into a variant of #{target.inspect}"
raise ArgumentError.new(message)
end
value
in [[_, exact, coerced], *]
exact.each { exactness[_1] += _2 }
coerced
end
.tap { state[:exactness] = exactness }
ensure
state[:strictness] = strictness
end