Exercise#2 Pydantic Parser

References

Python Pydantic Package

LangChain PydanticOutputParser

Objective

In this exercise, you will use the PydanticOutputParser to implement the behavior explained in the following prompt. This prompt may or may not work as-is with the LLM of your choice. As a result, you will need to adjust it as part of the exercise. The output from the LLMChain, should be an instance of a Python class. This Python class should have a list of word-number pairs.

generate {number} pairs of random word and an odd numbers.
the numbers should be between 5 and 50.

Format instructions:
{format_instructions}

Exercise Steps

  1. Refer to the PydanticOutputParser Documentation for details on use of this class

  2. Create Python classes for output schema. (Hint: OR use the class definition below)

  3. Setup output parser

  4. Create the Prompt Template & LLMChain

  5. Test the code

Class definition
from pydantic import BaseModel, Field
from langchain.output_parsers import PydanticOutputParser

# Create the class to represent the word-number pair
class WordNumberCombo(BaseModel):
    word: str = Field(description="this is a random word")
    odd_number: int = Field(description="this is an odd number between 5 and 50")

# Create the actual class for output. Its a list of word-number pairs
class ArrayWordNumberCombo(BaseModel):
    result: list[WordNumberCombo]

Solution

The solution to the exercise is available in the notebook:

ex-1-enum-output-parser.png

Google colab

  • Make sure to follow instructions for setting up packages
Open In Colab