diff --git a/lmformatenforcer/jsonschemaparser.py b/lmformatenforcer/jsonschemaparser.py index 01631cd..7df02e4 100644 --- a/lmformatenforcer/jsonschemaparser.py +++ b/lmformatenforcer/jsonschemaparser.py @@ -615,7 +615,7 @@ def can_end(self) -> bool: def get_allowed_control_characters(self): num_items = self.num_items_seen is_on_top = self.root.context.active_parser.object_stack[-1] == self - if (not is_on_top) and self.root.last_non_whitespace_character != "[": + if (not is_on_top) and self.root.context.active_parser.last_non_whitespace_character != "[": # If there is an active parser above us, and the last character is not [, # there is an active item parser on the stack that we did not count yet. num_items += 1 @@ -623,7 +623,7 @@ def get_allowed_control_characters(self): has_enough_items = self.min_items is None or num_items >= self.min_items can_add_another_item = self.max_items is None or num_items < self.max_items - if can_add_another_item: + if num_items > 0 and can_add_another_item: control_characters += "," if has_enough_items: control_characters += "]" diff --git a/tests/test_jsonschemaparser.py b/tests/test_jsonschemaparser.py index fd3556b..3d8c6f5 100644 --- a/tests/test_jsonschemaparser.py +++ b/tests/test_jsonschemaparser.py @@ -344,3 +344,13 @@ class EmptyListOKModel(BaseModel): no_strings = '{"num":1,"list_of_strings":[\n]}' _test_json_schema_parsing_with_string(no_strings, EmptyListOKModel.model_json_schema(), True) + + +def test_comma_cannot_start_list(): + class FlightRoute(BaseModel): + airports: List[str] + output_notok = """ { "airports": [,"name"] } """ + output_ok = """ { "airports": ["name"] } """ + + _test_json_schema_parsing_with_string(output_ok, FlightRoute.model_json_schema(), True) + _test_json_schema_parsing_with_string(output_notok, FlightRoute.model_json_schema(), False)