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.
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 BaseModelfrom langchain.chat_models import init_chat_modelclass Pick(BaseModel): title: str author: str reason: strclass 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.
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.