mirror of
https://github.com/hwchase17/langchain.git
synced 2025-08-24 03:52:08 +00:00
fix(json): raise OutputParserException for non-dict JSON outputs
This commit is contained in:
parent
7d2a13f519
commit
0072311906
@ -187,6 +187,11 @@ def parse_and_check_json_markdown(text: str, expected_keys: list[str]) -> dict:
|
|||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
msg = f"Got invalid JSON object. Error: {e}"
|
msg = f"Got invalid JSON object. Error: {e}"
|
||||||
raise OutputParserException(msg) from e
|
raise OutputParserException(msg) from e
|
||||||
|
if not isinstance(json_obj, dict):
|
||||||
|
raise OutputParserException(
|
||||||
|
f"Expected JSON object (dict), but got: {type(json_obj).__name__}. Raw content: {json_obj}",
|
||||||
|
llm_output=text
|
||||||
|
)
|
||||||
for key in expected_keys:
|
for key in expected_keys:
|
||||||
if key not in json_obj:
|
if key not in json_obj:
|
||||||
msg = (
|
msg = (
|
||||||
|
@ -5,7 +5,10 @@ from typing import Any
|
|||||||
import pytest
|
import pytest
|
||||||
from pydantic import BaseModel, Field
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
from langchain_core.exceptions import OutputParserException
|
from langchain.output_parsers.json import parse_and_check_json_markdown
|
||||||
|
from langchain.schema import OutputParserException
|
||||||
|
|
||||||
|
|
||||||
from langchain_core.output_parsers.json import (
|
from langchain_core.output_parsers.json import (
|
||||||
SimpleJsonOutputParser,
|
SimpleJsonOutputParser,
|
||||||
)
|
)
|
||||||
@ -210,6 +213,13 @@ def test_parse_json_with_code_blocks_and_newlines() -> None:
|
|||||||
"action_input": '```bar\n<div id="1" class="value">\n\ttext\n</div>```',
|
"action_input": '```bar\n<div id="1" class="value">\n\ttext\n</div>```',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def test_parse_non_dict_json_output():
|
||||||
|
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 = [
|
TEST_CASES_ESCAPED_QUOTES = [
|
||||||
JSON_WITH_ESCAPED_DOUBLE_QUOTES_IN_NESTED_JSON,
|
JSON_WITH_ESCAPED_DOUBLE_QUOTES_IN_NESTED_JSON,
|
||||||
|
Loading…
Reference in New Issue
Block a user