> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# 4. Pydantic Output Parser

> Define strict schemas using Pydantic and parse responses into typed Python objects

In this section, you will learn how to enforce type safety and parse unstructured text outputs from an LLM into strongly-typed Pydantic model objects.

## Objectives

1. Create validation schemas using Pydantic's `BaseModel` and `Field`.
2. Generate schema-specific format instructions automatically.
3. Configure `PydanticOutputParser` and extract structured outputs.

***

## Code Implementation

Each step of the implementation is preceded by extensive comments explaining the code logic.

### Define the Schema

First, define the structured model class using Pydantic:

```python theme={null}
from pydantic import BaseModel, Field

class PersonProfile(BaseModel):
    name: str = Field(description="The full name of the person")
    occupation: str = Field(description="The primary job/occupation of the person")
    skills: list[str] = Field(description="A list of 3-5 core professional skills")
    years_of_experience: int = Field(description="Estimated years of professional experience in their field")
```

***

### Setup Parser and Format Instructions

Instantiate the parser and retrieve instructions using the Groq provider model.

```python theme={null}
from dotenv import load_dotenv
from langchain.prompts import ChatPromptTemplate
from langchain.output_parsers import PydanticOutputParser
from langchain.chat_models import init_chat_model

load_dotenv()

# Initialize the Groq model using core abstractions
model = init_chat_model("llama-3.3-70b-versatile", model_provider="groq")

# Instantiate the parser with the schema
pydantic_parser = PydanticOutputParser(pydantic_object=PersonProfile)

# Retrieve the formatting instructions
format_instructions = pydantic_parser.get_format_instructions()

# Create prompt template
prompt = ChatPromptTemplate.from_messages([
    ("system", "Generate information based on the input name. {format_instructions}"),
    ("human", "Generate a profile for 'Ada Lovelace'.")
])
```

***

### Execute and Parse

Format the prompt, invoke the model, and parse the result.

```python theme={null}
# 1. Format the prompt
messages = prompt.format_messages(format_instructions=format_instructions)

# 2. Invoke the model to get response content
response = model.invoke(messages)

# 3. Parse the response content using the parser
result = pydantic_parser.parse(response.content)

# The result is parsed directly into a Pydantic object
print(f"Name: {result.name}")
print(f"Occupation: {result.occupation}")
print(f"Skills: {result.skills}")
print(f"Years of Experience: {result.years_of_experience}")
```

***

## Practice & Exercises

To reinforce what you've learned in this section, practice with the interactive notebook:

<CardGroup cols={1}>
  <Card title="Practice & Exercises" icon="laptop-code">
    Practice defining Pydantic validation schemas and parsing unstructured LLM responses into typed Python objects.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/GenAI%20With%20Python/public/notebooks/langchain/4_parsers_pydantic.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/genai-course/blob/master/public/notebooks/langchain/4_parsers_pydantic.ipynb) | <a href="/public/notebooks/langchain/4_parsers_pydantic.ipynb" download>📥 Download</a>
  </Card>
</CardGroup>
