Skip to content

Commit

Permalink
Allow objects in json schemas without additionalProperties set
Browse files Browse the repository at this point in the history
  • Loading branch information
lapp0 authored and rlouf committed May 22, 2024
1 parent 7863f8e commit 6f655ca
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
24 changes: 23 additions & 1 deletion outlines/fsm/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -312,8 +312,30 @@ def to_regex(

allow_empty = "?" if int(instance.get("minProperties", 0)) == 0 else ""

additional_properties = instance.get("additionalProperties")

if additional_properties is None or additional_properties is True:
# JSON Schema behavior: If the additionalProperties of an object is
# unset or True, it is unconstrained object.
# We handle this by setting additionalProperties to anyOf: {all types}

legal_values = [
{"type": "string"},
{"type": "number"},
{"type": "boolean"},
{"type": "null"}
# { "type": "array" }, # TODO: enable arrays within object-types
]

# We set the object depth to 2 to keep the expression finite, but the "depth"
# key is not a true component of the JSON Schema specification.
depth = instance.get("depth", 2)
if depth > 0:
legal_values.append({"type": "object", "depth": depth - 1})
additional_properties = {"anyOf": legal_values}

value_pattern = to_regex(
resolver, instance["additionalProperties"], whitespace_pattern
resolver, additional_properties, whitespace_pattern
)
key_value_pattern = (
f"{STRING}{whitespace_pattern}:{whitespace_pattern}{value_pattern}"
Expand Down
13 changes: 13 additions & 0 deletions tests/fsm/test_json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,19 @@ def test_format(schema, regex, examples):
('{"time":20:20:39Z}', False), # missing quotes for value
],
),
# Unconstrained Object
(
{
"title": "Foo",
"type": "object",
},
[
("{}", True),
('{"a": 1, "b": null}', True),
('{"a": {"z": {"g": 4}}, "b": null}', True),
("1234", False), # not an object
],
),
],
)
def test_format_without_regex(schema, examples):
Expand Down

0 comments on commit 6f655ca

Please sign in to comment.