Add context to an output parsing error on Pydantic schema to improve exception handling (#7344)

## Changes

- [X] Fill the `llm_output` param when there is an output parsing error
in a Pydantic schema so that we can get the original text that failed to
parse when handling the exception

## Background

With this change, we could do something like this:

```
output_parser = PydanticOutputParser(pydantic_object=pydantic_obj)
chain = ConversationChain(..., output_parser=output_parser)
try:
    response: PydanticSchema = chain.predict(input=input)
except OutputParserException as exc:
    logger.error(
        'OutputParserException while parsing chatbot response: %s', exc.llm_output,
    )
```
---------

Co-authored-by: Bagatur <baskaryan@gmail.com>
This commit is contained in:
Manuel Saelices 2023-07-07 20:49:37 +02:00 committed by GitHub
parent 1ac6deda89
commit 01dca1e438
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -28,7 +28,7 @@ class PydanticOutputParser(BaseOutputParser[T]):
except (json.JSONDecodeError, ValidationError) as e:
name = self.pydantic_object.__name__
msg = f"Failed to parse {name} from completion {text}. Got: {e}"
raise OutputParserException(msg)
raise OutputParserException(msg, llm_output=text)
def get_format_instructions(self) -> str:
schema = self.pydantic_object.schema()