Skip to content

Commit 2c9b91a

Browse files
authored
fix: schema generation (#862)
1 parent e7d9a3d commit 2c9b91a

File tree

2 files changed

+12
-1
lines changed

2 files changed

+12
-1
lines changed

lib/openai/helpers/structured_output/union_of.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ class UnionOf
2121
#
2222
# @return [Hash{Symbol=>Object}]
2323
def to_json_schema_inner(state:)
24+
# rubocop:disable Metrics/BlockLength
2425
OpenAI::Helpers::StructuredOutput::JsonSchemaConverter.cache_def!(state, type: self) do
2526
path = state.fetch(:path)
2627
mergeable_keys = {[:anyOf] => 0, [:type] => 0}
@@ -33,7 +34,9 @@ def to_json_schema_inner(state:)
3334
end
3435

3536
schemas.each do |schema|
36-
mergeable_keys.each_key { mergeable_keys[_1] += 1 if schema.keys == _1 }
37+
mergeable_keys.each_key do
38+
mergeable_keys[_1] += 1 if schema.keys == _1 && schema[_1].is_a?(Array)
39+
end
3740
end
3841
mergeable = mergeable_keys.any? { _1.last == schemas.length }
3942
if mergeable
@@ -48,6 +51,7 @@ def to_json_schema_inner(state:)
4851
}
4952
end
5053
end
54+
# rubocop:enable Metrics/BlockLength
5155
end
5256

5357
private_class_method :new

test/openai/helpers/structured_output_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ class M3 < OpenAI::Helpers::StructuredOutput::BaseModel
3939
U1 = OpenAI::Helpers::StructuredOutput::UnionOf[Integer, A1]
4040
U2 = OpenAI::Helpers::StructuredOutput::UnionOf[M2, M3]
4141
U3 = OpenAI::Helpers::StructuredOutput::UnionOf[A1, A1]
42+
U4 = OpenAI::Helpers::StructuredOutput::UnionOf[String, NilClass]
4243

4344
def test_coerce
4445
cases = {
@@ -117,6 +118,12 @@ def test_to_schema
117118
additionalProperties: false
118119
}
119120
]
121+
},
122+
U4 => {
123+
anyOf: [
124+
{type: "string"},
125+
{type: "null"}
126+
]
120127
}
121128
}
122129
cases.each do |input, expected|

0 commit comments

Comments
 (0)