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.
This commit is contained in:
Tim Asp 2023-04-17 20:24:40 -07:00 committed by GitHub
parent afd3e70ae5
commit dcdcd3f636
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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)