01. Pydantic output parser (PydanticOutputParser)

PydanticOuputParser

PydanticOutputParser More output of the language model Convert to structured information This is a class that helps you do it. Instead of a simple text-like response, Provide information that users need in a clear and systematic form You can.

By utilizing this class, the output of the language model is converted to a specific data model, making it easier to process and utilize information.

PydanticOutputParser (This is also true for most OutputParser) Two key methods are implemented Should be.

  • get_format_instructions() : Provides instructions (instruction) that define the format of the information the language model should output. For example, you can return the fields of the data that the language model needs to output and instructions describing its shape as a string. The role of the instructions (instruction) at this time is very important. Following these guidelines, language models can structure outputs and convert them to specific data models.

  • parse() : Accept the output of the language model (assuming it in string) to analyze and convert it into a specific structure. Using a tool like Pydantic, the entered string is verified according to a predefined schema, and converted into a data structure that follows that schema.

Reference - Pydantic official document

Copy

from dotenv import load_dotenv

load_dotenv()

Copy

True

Copy

# LangSmith Set up tracking. https://smith.langchain.com
# !pip install langchain-teddynote
from langchain_teddynote import logging

# Enter a project name.
logging.langsmith("CH03-OutputParser")

Copy

Copy

Copy

Here is an example of the email body.

Copy

Example when not using output parser

Copy

Copy

Copy

Copy

Given the above email content, we will parse the information in the email using the class defined in the Pydantic style below.

For reference, inside Field description This is the explanation for extracting key information from the answer in the form of silver text. LLM You will see this description and extract the information you need. Therefore, this explanation should be accurate and clear.

Copy

Copy

Copy

Define the prompt.

  1. question : I get a question from User.

  2. email_conversation : Enter the contents of the email body.

  3. format : Specify the format.

Copy

Next, create Chain.

Copy

Run the chain and check the results.

Copy

Copy

Finally parser Using parse the results EmailSummary Convert to object.

Copy

Copy

Create chain with parser added

It can be created as a Pydantic object that defines the output result.

Copy

Copy

with_structured_output( )

.with_structured_output(Pydantic) If you add an output parser using, you can convert the output to a Pydantic object.

Copy

Copy

Copy

Reference

One regret .with_structured_output() function stream() It does not support features.

PreviousCH03 Output ParsersNext02. Comma SeparatedListOutputParser

Last updated