Optional Fields and Default Values
What You'll Learn
You'll learn how to make Pydantic schemas flexible enough to handle unpredictable or incomplete LLM outputs by marking fields as optional and providing sensible defaults.
Why This Matters
LLMs don't always return complete data. Sometimes they skip fields, especially when information isn't explicitly provided in the prompt or when the model makes judgment calls about relevance. Without optional fields, your code would crash every time the LLM omits something.
Core Concepts
Optional Fields
By default, Pydantic requires all fields to be present. Use Optional[Type] from Python's typing module to mark fields that might be missing:
from typing import Optional
from pydantic import BaseModel
class UserProfile(BaseModel):
name: str
email: str
phone: Optional[str] = None # May be omitted
age: Optional[int] = None
Now the LLM can return {"name": "Alice", "email": "alice@example.com"} without causing an error. Missing optional fields will be set to None.
Default Values
Instead of None, provide meaningful defaults:
class ProductReview(BaseModel):
product: str
rating: int
comment: Optional[str] = "No comment provided"
verified: bool = False
If the LLM doesn't specify verified, it automatically becomes False rather than None, making your downstream logic cleaner.
When to Use What
- Use
Optional[Type] = Nonewhen absence is meaningful (phone number might not exist) - Use default values when you want fallback behavior (unverified until proven otherwise)
- Combine both for maximum robustness
Key Takeaway: Optional fields and default values make your schemas resilient to incomplete LLM outputs, preventing crashes and enabling graceful handling of partial data without sacrificing type safety.