diff --git a/src/Libraries/Microsoft.Extensions.AI/Utilities/AIJsonUtilities.Schema.cs b/src/Libraries/Microsoft.Extensions.AI/Utilities/AIJsonUtilities.Schema.cs index 46fe45342f2..eb8f0d52a07 100644 --- a/src/Libraries/Microsoft.Extensions.AI/Utilities/AIJsonUtilities.Schema.cs +++ b/src/Libraries/Microsoft.Extensions.AI/Utilities/AIJsonUtilities.Schema.cs @@ -138,8 +138,6 @@ public static JsonElement CreateJsonSchema( JsonSerializerOptions? serializerOptions = null, AIJsonSchemaCreateOptions? inferenceOptions = null) { - _ = Throw.IfNull(serializerOptions); - serializerOptions ??= DefaultOptions; inferenceOptions ??= AIJsonSchemaCreateOptions.Default; @@ -278,24 +276,24 @@ JsonNode TransformSchemaNode(JsonSchemaExporterContext ctx, JsonNode schema) { objSchema.Add(AdditionalPropertiesPropertyName, (JsonNode)false); } - } - - if (ctx.Path.IsEmpty) - { - // We are at the root-level schema node, update/append parameter-specific metadata // Some consumers of the JSON schema, including Ollama as of v0.3.13, don't understand // schemas with "type": [...], and only understand "type" being a single value. // STJ represents .NET integer types as ["string", "integer"], which will then lead to an error. - if (TypeIsArrayContainingInteger(schema)) + if (TypeIsArrayContainingInteger(objSchema)) { // We don't want to emit any array for "type". In this case we know it contains "integer" // so reduce the type to that alone, assuming it's the most specific type. - // This makes schemas for Int32 (etc) work with Ollama + // This makes schemas for Int32 (etc) work with Ollama. JsonObject obj = ConvertSchemaToObject(ref schema); obj[TypePropertyName] = "integer"; _ = obj.Remove(PatternPropertyName); } + } + + if (ctx.Path.IsEmpty) + { + // We are at the root-level schema node, update/append parameter-specific metadata if (!string.IsNullOrWhiteSpace(key.Description)) { @@ -354,7 +352,7 @@ static JsonObject ConvertSchemaToObject(ref JsonNode schema) } } - private static bool TypeIsArrayContainingInteger(JsonNode schema) + private static bool TypeIsArrayContainingInteger(JsonObject schema) { if (schema["type"] is JsonArray typeArray) { diff --git a/test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/AIJsonUtilitiesTests.cs b/test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/AIJsonUtilitiesTests.cs index db482d26804..d7ff5c6783e 100644 --- a/test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/AIJsonUtilitiesTests.cs +++ b/test/Libraries/Microsoft.Extensions.AI.Abstractions.Tests/AIJsonUtilitiesTests.cs @@ -158,4 +158,11 @@ public enum MyEnumValue A = 1, B = 2 } + + [Fact] + public static void ResolveJsonSchema_CanBeBoolean() + { + JsonElement schema = AIJsonUtilities.CreateJsonSchema(typeof(object)); + Assert.Equal(JsonValueKind.True, schema.ValueKind); + } }