Optional Fields and Default Values
What You'll Learn
You'll learn how to design flexible schemas that gracefully handle partial or incomplete LLM outputs by marking fields as optional and providing sensible defaults.
The Core Problem
Sometimes an LLM won't provide every piece of information you've requested—either because the input doesn't warrant it, the model made a judgment call, or the data simply isn't available. If your schema demands every field, you'll face validation errors and failed outputs. Optional fields solve this.
Making Fields Optional
Think of optional fields like survey questions where "prefer not to answer" is valid. In Pydantic (which you've learned), you mark a field optional by wrapping its type in Optional[...] or using the union syntax with None:
from typing import Optional
from pydantic import BaseModel
class ProductReview(BaseModel):
sentiment: str
rating: int
summary: Optional[str] = None # May be omitted
reviewer_name: Optional[str] = "Anonymous" # Default provided
Here, summary can be absent (will be None), and reviewer_name defaults to "Anonymous" if not provided.
When to Use Defaults vs None
- Use
Nonewhen the absence of data is meaningful (e.g., "no summary available") - Use specific defaults when you want fallback behavior (e.g., "Anonymous" for missing names)
This pattern is critical when extracting information from varied inputs—some texts might not contain reviewer names, and that's okay.
Nullable vs Optional
A field can be both optional (doesn't need to be in the JSON) and nullable (can explicitly be set to null). Design schemas based on your downstream logic needs.
Key Takeaway: Optional fields with thoughtful defaults make your structured output schemas resilient to incomplete LLM responses, preventing validation failures while maintaining data integrity.