LangChain is the framework for building natural language processing models like LLMs (Large language Models). It allows the user to build applications that understand the prompt written in a natural language like English as it is the most used language across the globe. It also enables the use of the Enum parser to convert the list of strings into single values or store them one by one.
This guide will explain the process of using the Enum parser in LangChain.
How to Use Enum Parser in LangChain?
To use the enum parser in LangChain, simply follow this step-by-step guide:
Installation of LangChain Module
Start the process of the Enum parser in LangChain by installing the LangChain module via the following Python code:
Install Enum Library
After installing LangChain, import the EnumOutputParser library to use it in LangChain:
Use the Enum library to create a scoped class with Enum as its parameter named “shape” to initialize the list of items for the class:
class shape(Enum):
Circle = "circle"
Cube = "cube"
Triangle = "triangle"
Define the variable named parser to assign the EnumOutputParser library with the class as its argument:
Testing Parser
Call the parse() function to test the parser with the name of the shape as its argument:
The argument of the parse() function may contain the space and it will remove it before saving it in the list:
parser.parse("cube")
The function also allows the use of the escape sequence with the character for the next line:
parser.parse("tringle\n")
Bonus Tip: Finding Errors
The function displays the error if the argument list is not defined in the scope of the class:
parser.parse("square")
The following screenshot displays the error as the argument is not the expected value as it is not defined in the class:
Solution
The above error occurs when the argument of the parse() function is not defined in the class and its solution is to define it in the class and then call it as displayed below:
Square = "square"
Call the function with the valid argument which is defined in the class:
That is all about using the Enum parser in LangChain.
Conclusion
To use the Enum parser in LangChain, simply install LangChain to import the EnumOutputParser library to call its functions. After that, import the Enum library to define a scoped class with the enum as its argument and assign a list of values defined in the class. Then, simply call the parse() function with the expected value as its parameter and it generates an error if the argument is not defined in the class. This guide has explained the process of using the Enum parser in LangChain.