From dcdcd3f636f9244208cd1a30f1b6dccd4d861c59 Mon Sep 17 00:00:00 2001 From: Tim Asp <707699+timothyasp@users.noreply.github.com> Date: Mon, 17 Apr 2023 20:24:40 -0700 Subject: [PATCH] bugfix: throw exception if structured output parser doesn't get what it wants (#3044) allows the user to catch the issue and handle it rather than failing hard. This happens more than you'd expect when using output parsers with chatgpt, especially if the temp is anything but 0. Sometimes it doesn't want to listen and just does its own thing. --- langchain/output_parsers/structured.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/langchain/output_parsers/structured.py b/langchain/output_parsers/structured.py index 566e0885..d9c7b83a 100644 --- a/langchain/output_parsers/structured.py +++ b/langchain/output_parsers/structured.py @@ -38,6 +38,12 @@ class StructuredOutputParser(BaseOutputParser): return STRUCTURED_FORMAT_INSTRUCTIONS.format(format=schema_str) def parse(self, text: str) -> Any: + if "```json" not in text: + raise OutputParserException( + f"Got invalid return object. Expected markdown code snippet with JSON " + f"object, but got:\n{text}" + ) + json_string = text.split("```json")[1].strip().strip("```").strip() try: json_obj = json.loads(json_string)