Structured Output Parser
Author: Yoolim Han
Proofread : BokyungisaGod
This is a part of LangChain Open Tutorial
Overview
The StructuredOutputParser is a valuable tool for formatting Large Language Model (LLM) responses into dictionary structures, enabling the return of multiple fields as key/value pairs.
While Pydantic and JSON parsers offer robust capabilities, the StructuredOutputParser is particularly effective for less powerful models, such as local models with fewer parameters. It is especially beneficial for models with lower intelligence compared to advanced models like GPT or Claude.
By utilizing the StructuredOutputParser, developers can maintain data integrity and consistency across various LLM applications, even when operating with models that have reduced parameter counts.
Table of Contents
References
Environment Setup
Set up the environment. You may refer to Environment Setup for more details.
[Note]
langchain-opentutorialis a package that provides a set of easy-to-use environment setup along with useful functions and utilities for tutorials.You can checkout the
langchain-opentutorialfor more details.
You can alternatively setOPENAI_API_KEY in .env file and load it.
[Note] This is not necessary if you've already set OPENAI_API_KEY in previous steps.
Implementing the StructuredOutputParser
StructuredOutputParserUsing ResponseSchema with StructuredOutputParser
ResponseSchema with StructuredOutputParserDefine a response schema using the
ResponseSchemaclass to include the answer to the user's question and adescriptionof the source (website) used.Initialize
StructuredOutputParserwithresponse_schemasto structure the output according to the defined response schema.
[Note]
When using local models, Pydantic parsers may frequently fail to work properly. In such cases, using StructuredOutputParser can be a good alternative solution.
Embedding Response Schemas into Prompts
Create a PromptTemplate to format user questions and embed parsing instructions for structured outputs.
Integrating with ChatOpenAI and Running the Chain
ChatOpenAI and Running the ChainCombine the PromptTemplate , ChatOpenAI model , and StructuredOutputParser into a chain . Finally, run the chain with a specific question to produce results.
Using Streamed Outputs
Use the chain.stream method to receive a streaming response to the question , "How many players are on a soccer team?"
Last updated