Why Nested Pydantic Schemas Hit Limits in Structured Outputs
OpenAI Structured Outputs (: true) converts Pydantic models into a JSON Schema and compiles a grammar for constrained decoding. Deeply nested models, recursive tree structures (like nodes containing child nodes), or huge union trees can hit schema depth limits, slow down schema compilation, or fail validation if not modeled carefully.
- Self-referencing / tree models: A node that directly references itself (
children: list["Node"]) creates an unbounded or deep recursive schema. - Deeply nested chains: Having many nested sub-models in one giant schema adds complexity and can exceed nesting/schema constraints.
- Heavy unions: Large
UnionorAnyOfbranches multiply schema size quickly.
How to Avoid Recursion and Nesting Limits
- Flatten trees with IDs and parent pointers: Instead of deeply nested child objects inside child objects, return a flat list of items where each item has an
idand an optionalparent_id. Reconstruct the tree in Python after parsing. - Cap depth or split stages: If nesting is small and fixed, define explicit levels (such as
Level2Node->Level1Node), or run a two-step extraction (first top-level items, then details per item). - Keep schemas clean and strict: Use
BaseModelwith explicit types, avoid unbounded self-recursion where a flat list works, and let Pydantic validate the resulting data.
Python Example Using a Flat List Instead of Recursive Nesting
from typing import Optional
from pydantic import BaseModel, Field
from openai import OpenAI
client = OpenAI()
class CategoryItem(BaseModel):
id: str = Field(..., description="Unique identifier for this item")
name: str = Field(..., description="Display name of the category or node")
parent_id: Optional[str] = Field(
default=None,
description="ID of the parent item, or null if this is a root item",
)
class CategoryTreeFlat(BaseModel):
items: list[CategoryItem]
def build_tree(items: list[CategoryItem]) -> list[dict]:
nodes = {item.id: {"id": item.id, "name": item.name, "children": []} for item in items}
roots = []
for item in items:
current = nodes[item.id]
if item.parent_id and item.parent_id in nodes:
nodes[item.parent_id]["children"].append(current)
else:
roots.append(current)
return roots
response = client.responses.parse(
model="gpt-4o-mini",
input=[
{"role": "system", "content": "Extract a hierarchy as a flat list of items with parent_id links."},
{"role": "user", "content": "Backend has Node.js and Python; Python has FastAPI and Django."},
],
text_format=CategoryTreeFlat,
)
tree = build_tree(response.output_parsed.items)
print(tree)
Helpful Tips
- Validate parent links in code: LLMs can occasionally invent a
parent_idor create a cycle, so check IDs and handle missing parents safely when building your tree. - Keep models compact: Smaller, focused Pydantic models compile faster and are easier for the model to fill accurately.
- Use multi-pass extraction for huge hierarchies: For very large documents or deep trees, extract top sections first and expand branches in follow-up calls.
You must log in or register to comment.
