Skip to content
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

Enable Tuples / prefixItems in build_regex_from_schema() #912

Merged
merged 1 commit into from
May 24, 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
9 changes: 9 additions & 0 deletions outlines/fsm/json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,15 @@ def to_regex(

return rf"({'|'.join(xor_patterns)})"

# Create pattern for Tuples, per JSON Schema spec, `prefixItems` determines types at each idx
elif "prefixItems" in instance:
element_patterns = [
to_regex(resolver, t, whitespace_pattern) for t in instance["prefixItems"]
]
comma_split_pattern = rf"{whitespace_pattern},{whitespace_pattern}"
tuple_inner = comma_split_pattern.join(element_patterns)
return rf"\[{whitespace_pattern}{tuple_inner}{whitespace_pattern}\]"

# The enum keyword is used to restrict a value to a fixed set of values. It
# must be an array with at least one element, where each element is unique.
elif "enum" in instance:
Expand Down
9 changes: 9 additions & 0 deletions tests/fsm/test_json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,15 @@ def test_match_number(pattern, does_match):
rf"({STRING}{INTEGER})",
[('"a"1', True), ('"a"', False), ('"1"', False)],
),
# Tuple / prefixItems
(
{
"title": "Foo",
"prefixItems": [{"type": "string"}, {"type": "integer"}],
},
rf"\[{WHITESPACE}{STRING}{WHITESPACE},{WHITESPACE}{INTEGER}{WHITESPACE}\]",
[('["a", 1]', True), ('["a", 1, 1]', False), ("[]", False)],
),
# Nested schema
(
{
Expand Down
Loading