Skip to content

Fix exception when generating boolean schemas #5585

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,6 @@ public static JsonElement CreateJsonSchema(
JsonSerializerOptions? serializerOptions = null,
AIJsonSchemaCreateOptions? inferenceOptions = null)
{
_ = Throw.IfNull(serializerOptions);

serializerOptions ??= DefaultOptions;
inferenceOptions ??= AIJsonSchemaCreateOptions.Default;

Expand Down Expand Up @@ -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))
{
Expand Down Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Loading