Skip to content

Commit

Permalink
fix exception when generating boolean schemas (#5585)
Browse files Browse the repository at this point in the history
  • Loading branch information
eiriktsarpalis authored Oct 30, 2024
1 parent 8327c2f commit bf0e0a4
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
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);
}
}

0 comments on commit bf0e0a4

Please sign in to comment.