Skip to content

Commit bf0e0a4

Browse files
fix exception when generating boolean schemas (#5585)
1 parent 8327c2f commit bf0e0a4

File tree

2 files changed

+15
-10
lines changed

2 files changed

+15
-10
lines changed

src/Libraries/Microsoft.Extensions.AI/Utilities/AIJsonUtilities.Schema.cs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,6 @@ public static JsonElement CreateJsonSchema(
138138
JsonSerializerOptions? serializerOptions = null,
139139
AIJsonSchemaCreateOptions? inferenceOptions = null)
140140
{
141-
_ = Throw.IfNull(serializerOptions);
142-
143141
serializerOptions ??= DefaultOptions;
144142
inferenceOptions ??= AIJsonSchemaCreateOptions.Default;
145143

@@ -278,24 +276,24 @@ JsonNode TransformSchemaNode(JsonSchemaExporterContext ctx, JsonNode schema)
278276
{
279277
objSchema.Add(AdditionalPropertiesPropertyName, (JsonNode)false);
280278
}
281-
}
282-
283-
if (ctx.Path.IsEmpty)
284-
{
285-
// We are at the root-level schema node, update/append parameter-specific metadata
286279

287280
// Some consumers of the JSON schema, including Ollama as of v0.3.13, don't understand
288281
// schemas with "type": [...], and only understand "type" being a single value.
289282
// STJ represents .NET integer types as ["string", "integer"], which will then lead to an error.
290-
if (TypeIsArrayContainingInteger(schema))
283+
if (TypeIsArrayContainingInteger(objSchema))
291284
{
292285
// We don't want to emit any array for "type". In this case we know it contains "integer"
293286
// so reduce the type to that alone, assuming it's the most specific type.
294-
// This makes schemas for Int32 (etc) work with Ollama
287+
// This makes schemas for Int32 (etc) work with Ollama.
295288
JsonObject obj = ConvertSchemaToObject(ref schema);
296289
obj[TypePropertyName] = "integer";
297290
_ = obj.Remove(PatternPropertyName);
298291
}
292+
}
293+
294+
if (ctx.Path.IsEmpty)
295+
{
296+
// We are at the root-level schema node, update/append parameter-specific metadata
299297

300298
if (!string.IsNullOrWhiteSpace(key.Description))
301299
{
@@ -354,7 +352,7 @@ static JsonObject ConvertSchemaToObject(ref JsonNode schema)
354352
}
355353
}
356354

357-
private static bool TypeIsArrayContainingInteger(JsonNode schema)
355+
private static bool TypeIsArrayContainingInteger(JsonObject schema)
358356
{
359357
if (schema["type"] is JsonArray typeArray)
360358
{

test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/AIJsonUtilitiesTests.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,4 +158,11 @@ public enum MyEnumValue
158158
A = 1,
159159
B = 2
160160
}
161+
162+
[Fact]
163+
public static void ResolveJsonSchema_CanBeBoolean()
164+
{
165+
JsonElement schema = AIJsonUtilities.CreateJsonSchema(typeof(object));
166+
Assert.Equal(JsonValueKind.True, schema.ValueKind);
167+
}
161168
}

0 commit comments

Comments
 (0)