AI Hints
Home›LangChain Tutorial›Structured Output
LangChain · Lesson 29 of 120

Pydantic Models

Describing data.

⏱ 2 min read▶ Video at 31:06🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

To ask for structured data, we first describe it. The usual way in Python is a Pydantic model, a class that lists each field, and its type.

Pydantic Models
From the video: Pydantic Models
  • Describe the data
  • Pydantic models
  • Fields and types

A Pydantic model

Here's a book model. Title is a string, year is an integer, and genres is a list of strings. Field adds a description, which the language model will also see. Creating a book checks every field. Run it. The year, written as a string, is converted to a number. And a book with a missing title is rejected.

pydantic_model.pypython
from pydantic import BaseModel, Field, ValidationError

class Book(BaseModel):
    title: str
    year: int = Field(description="year first published")
    genres: list[str]

b = Book(title="Dune", year="1965", genres=["sci-fi"])
print(b.year + 1, b)

try:
    Book(year=1950, genres=[])
except ValidationError as e:
    print("rejected:", e.errors()[0]["msg"], e.errors()[0]["loc"])
Output
1966 title='Dune' year=1965 genres=['sci-fi']
rejected: Field required ('title',)

Good field habits

A few habits help the model fill your fields well. Use clear names. Add a description to any field that could be unclear. Use specific types, like int, or a fixed set of choices. And make fields optional, when the information might not exist.

keyvalue
Clear namestitle, not t
Descriptionsfor unclear fields
Specific typesint, list, choices
Optionalif it may be missing

Summary

Pydantic models describe data as a class of typed fields, and check every value. Next, asking the model to fill one in.

Key takeaways
  • class Book(BaseModel)
  • Typed fields
  • Field(description=...)
Next up: with_structured_output — typed answers