AI Hints
Home›LangChain Tutorial›Shapes, Labels, Extraction
LangChain · Lesson 31 of 120

Lists and Nested Data

Richer shapes.

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

Real data has shape. A reading list contains several books, and each book has its own fields. Pydantic models can contain other models, and lists of them.

Lists and Nested Data
From the video: Lists and Nested Data
  • Data has shape
  • A list of books
  • Models inside models

A reading list

Here, a reading list has a theme, and a list of book picks. Each pick has a title, an author, and a short reason. We ask for a reading list about space, with three books. Run it. We get a reading list object, and can loop over its picks like any Python list.

nested.pypython
from pydantic import BaseModel
from langchain.chat_models import init_chat_model

class Pick(BaseModel):
    title: str
    author: str
    reason: str

class ReadingList(BaseModel):
    theme: str
    picks: list[Pick]

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
rl = model.with_structured_output(ReadingList).invoke(
    "A reading list of exactly 3 classic books about space. Reasons under 8 words.")
print("theme:", rl.theme)
for p in rl.picks:
    print(f"- {p.title} ({p.author}): {p.reason}")
Output
theme: Classic Space Literature
- 2001: A Space Odyssey (Arthur C. Clarke): AI mutinies on deep space journey.
- The War of the Worlds (H.G. Wells): Martian invasion devastates Victorian England.
- Foundation (Isaac Asimov): Galactic empire faces dark age.

Keeping shapes manageable

Nesting is powerful, but keep it reasonable. Two or three levels are fine. Very deep or very large schemas confuse models, and cost tokens. Say how many items you want, in the prompt. And prefer simple types, like strings and numbers, at the bottom of the tree.

keyvalue
2–3 levelsfine
Too deepconfuses the model
Item countssay how many
Leavessimple types

Summary

Pydantic models can nest, and hold lists of other models, so you can request rich, structured answers. Next, choosing from a fixed set of labels.

Key takeaways
  • Models inside models
  • list[Pick]
  • Keep it shallow
Next up: Classification — fixed labels