Learn how to create agents that return type-safe, structured data using Pydantic models. This tutorial teaches you how to ensure your agents return consistent, validated JSON responses that your applications can reliably process.
Sign in to save downloads to your library and vote.
Preview
๐ฏ Tutorial 2: Structured Output Agent
Learn how to create agents that return type-safe, structured data using Pydantic models. This tutorial teaches you how to ensure your agents return consistent, validated JSON responses that your applications can reliably process.
๐ฏ What You'll Learn
- Structured Outputs: Using Pydantic models to define response schemas
- Type Safety: Ensuring consistent data types and validation
- JSON Schema Generation: Automatic schema creation from Python classes
- Output Validation: Built-in validation and error handling
๐ง Core Concept: Why Structured Outputs?
Traditional AI responses are unstructured text, making them difficult to process programmatically. Structured outputs solve this by:
- Consistency: Always return the same data structure
- Validation: Automatic type checking and data validation
- Integration: Easy to integrate with databases, APIs, and applications
- Reliability: Reduce parsing errors and improve application stability
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ UNSTRUCTURED vs STRUCTURED โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ UNSTRUCTURED OUTPUT: โ
โ "The customer John Doe submitted a high priority โ
โ billing issue about charges on January 15th..." โ
โ โ
โ STRUCTURED OUTPUT: โ
โ { โ
โ "customer_name": "John Doe", โ
โ "issue_type": "billing", โ
โ "priority": "high", โ
โ "date_submitted": "2024-01-15", โ
โ "description": "Incorrect charges on account" โ
โ } โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ Tutorial Overview
This tutorial includes three focused structured output examples:
1. Support Ticket Agent (2_1_support_ticket_agent/)
- Basic structured output with enums
- Required and optional fields
- Business validation patterns
2. Product Review Agent (2_2_product_review_agent/)
- Complex sentiment analysis schema
- List fields and nested validation
- Rating classification logic
3. Email Generator Agent (2_3_email_generator_agent/)
- Simple two-field structure
- Enum validation for tone
- Content formatting patterns
๐ Project Structure
2_structured_output_agent/
โโโ README.md # This file - concept explanation
โโโ requirements.txt # Dependencies
โโโ 2_1_support_ticket_agent/ # Basic structured output
โ โโโ __init__.py
โ โโโ agent.py # Support ticket schema (35 lines)
โโโ 2_2_product_review_agent/ # Complex structured output
โ โโโ __init__.py
โ โโโ agent.py # Product review analysis (45 lines)
โโโ 2_3_email_generator_agent/ # Simple structured output
โ โโโ __init__.py
โ โโโ agent.py # Email content generation (30 lines)
โโโ app.py # Streamlit web interface (optional)
โโโ env.example # Environment variables template
๐ฏ Learning Objectives
By the end of this tutorial, you'll understand:
- โ How to define Pydantic models for agent outputs
- โ
Using the
output_typeparameter in agents - โ Complex data structures with nested models
- โ Enum validation for controlled vocabularies
- โ Optional fields and default values
- โ Custom validation methods
๐ Getting Started
-
Install OpenAI Agents SDK:
pip install openai-agents -
Install dependencies:
pip install -r requirements.txt -
Set up environment variables:
cp env.example .env # Edit .env and add your OpenAI API key -
Test the support ticket agent:
python support_ticket_agent.py -
Test the product review agent:
python product_review_agent.py -
Run the interactive web interface:
streamlit run app.py
๐งช Sample Use Cases
Support Ticket Agent
Try these customer complaints:
- "My billing statement shows duplicate charges for last month's subscription"
- "I can't log into my account and need immediate help"
- "The app keeps crashing when I try to upload files"
Product Review Agent
Try these product reviews:
- "This laptop is amazing! Great battery life and super fast. Would definitely recommend. 5 stars!"
- "The phone camera quality is poor and battery drains quickly. Not worth the price."
- "Decent product but shipping took forever. Customer service was helpful though."
๐ง Key Pydantic Patterns
1. Basic Model with Enums
class Priority(str, Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
class SupportTicket(BaseModel):
priority: Priority
category: str
2. Optional Fields with Defaults
class Review(BaseModel):
rating: int = Field(ge=1, le=5)
sentiment: str
recommend: Optional[bool] = None
3. Complex Nested Structures
class ProductReview(BaseModel):
product_info: ProductInfo
review_data: ReviewData
analysis: ReviewAnalysis
๐ Next Steps
After completing this tutorial, you'll be ready for:
- Tutorial 3: Tool Using Agent - Add custom tools and functions
- Tutorial 4: Runner Execution Methods - Master different execution patterns
- Tutorial 5: Context Management - Manage state across interactions
๐ก Pro Tips
- Design Schemas First: Plan your data structure before implementing
- Use Descriptive Fields: Clear field descriptions improve agent accuracy
- Validate Constraints: Use Pydantic validators for business rules
- Handle Optionals: Plan for missing or uncertain data
- Test Edge Cases: Try incomplete or ambiguous inputs
๐จ Troubleshooting
- Validation Errors: Check that your Pydantic model matches expected output
- Missing Fields: Ensure all required fields are included in the schema
- Type Mismatches: Verify field types match the data being returned
- Enum Errors: Make sure enum values match exactly (case-sensitive)
Ingestion metadata
- Source catalog
- awesome-llm-apps
- Repository
- Shubhamsaboo/awesome-llm-apps ยท main
- File path
- ai_agent_framework_crash_course/openai_sdk_crash_course/2_structured_output_agent/README.md
- Last refreshed
- 7/24/2026, 3:00:13 AM (51m ago)
- Refresh schedule
- Daily ยท 03:00 UTC
- Dedupe status
- Unique ยท deduped by (source, url)