The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(core): raise `OutputParserException` for non-dict JSON outputs (#32236)
Yash Vishwanath Tobrea8828b1bda57
diff --git a/libs/core/langchain_core/utils/json.py b/libs/core/langchain_core/utils/json.pyindex 1306bb9d73..768471ae53 100644--- a/libs/core/langchain_core/utils/json.py+++ b/libs/core/langchain_core/utils/json.py@@ -190,6 +190,12 @@ def parse_and_check_json_markdown(text: str, expected_keys: list[str]) -> dict:except json.JSONDecodeError as e:msg = f"Got invalid JSON object. Error: {e}"raise OutputParserException(msg) from e+ if not isinstance(json_obj, dict):+ error_message = (+ f"Expected JSON object (dict), but got: {type(json_obj).__name__}. "+ )+ raise OutputParserException(error_message, llm_output=text)+for key in expected_keys:if key not in json_obj:msg = (diff --git a/libs/core/tests/unit_tests/output_parsers/test_json.py b/libs/core/tests/unit_tests/output_parsers/test_json.pyindex 4198a46714..ebc8766751 100644--- a/libs/core/tests/unit_tests/output_parsers/test_json.py+++ b/libs/core/tests/unit_tests/output_parsers/test_json.py@@ -10,7 +10,11 @@ from langchain_core.output_parsers.json import (SimpleJsonOutputParser,)from langchain_core.utils.function_calling import convert_to_openai_function-from langchain_core.utils.json import parse_json_markdown, parse_partial_json+from langchain_core.utils.json import (+ parse_and_check_json_markdown,+ parse_json_markdown,+ parse_partial_json,+)from tests.unit_tests.pydantic_utils import _schemaGOOD_JSON = """```json@@ -204,13 +208,20 @@ def test_parse_json_with_part_code_blocks() -> None:def test_parse_json_with_code_blocks_and_newlines() -> None:parsed = parse_json_markdown(JSON_WITH_MARKDOWN_CODE_BLOCK_AND_NEWLINES)-assert parsed == {"action": "Final Answer","action_input": '```bar\n<div id="1" class="value">\n\ttext\n</div>```',}+def test_parse_non_dict_json_output() -> None:+ text = "```json\n1\n```"+ with pytest.raises(OutputParserException) as exc_info:+ parse_and_check_json_markdown(text, expected_keys=["foo"])++ assert "Expected JSON object (dict)" in str(exc_info.value)++TEST_CASES_ESCAPED_QUOTES = [JSON_WITH_ESCAPED_DOUBLE_QUOTES_IN_NESTED_JSON,]