diff --git a/tests/unit/test_llm_chat.py b/tests/unit/test_llm_chat.py index 90bb483a..57a00d1d 100644 --- a/tests/unit/test_llm_chat.py +++ b/tests/unit/test_llm_chat.py @@ -408,6 +408,11 @@ def test_coerce_to_dict_or_list_valid_inputs(self): result = chat._coerce_to_dict_or_list(json_array) assert result == [{"name": "John"}, {"name": "Jane"}] + # Valid empty JSON object with whitespace + empty_json_object = " { }\n" + result = chat._coerce_to_dict_or_list(empty_json_object) + assert result == {} + # Already a dict dict_input = {"key": "value"} result = chat._coerce_to_dict_or_list(dict_input) @@ -428,6 +433,15 @@ def test_coerce_to_dict_or_list_invalid_inputs(self): with pytest.raises(ValueError, match="Cannot convert"): chat._coerce_to_dict_or_list("42") # valid JSON but not dict/list + for malformed_json in ( + "[{[}]", + "{not json}", + 'prefix {"name": } suffix', + "malformed {[}] followed by {}", + ): + with pytest.raises(ValueError, match="Cannot convert"): + chat._coerce_to_dict_or_list(malformed_json) + def test_coerce_to_list_valid_inputs(self): """Test list coercion with valid inputs.""" chat = LLMChat(system_prompt="Test", user_prompt="Test") diff --git a/tinytroupe/utils/llm.py b/tinytroupe/utils/llm.py index 0c265ce6..bc1ea3c3 100644 --- a/tinytroupe/utils/llm.py +++ b/tinytroupe/utils/llm.py @@ -933,7 +933,7 @@ def _coerce_to_dict_or_list(self, llm_output: str): # extract_json returns {} on failure, but we need dict or list if result == {} and not ( isinstance(llm_output, str) - and ("{}" in llm_output or "{" in llm_output and "}" in llm_output) + and re.fullmatch(r"\s*\{\s*\}\s*", llm_output) ): raise ValueError( "Cannot convert the LLM output to a dict or list value."