Overview
There are two primary approaches for structured responses:- JSON Mode: Basic JSON formatting without schema validation
- JSON Schema Mode: Structured responses with strict schema validation and Pydantic integration
JSON Mode
Basic JSON Mode
Basic JSON Mode
JSON mode ensures the model’s output is valid JSON without enforcing a specific structure:Output:
JSON Schema Mode
Using JSON Schema
Using JSON Schema
JSON Schema mode provides strict structure validation using predefined schemas:Output:
When using JSON schema with strict mode set to true, all properties defined in the schema must be included in the required array. If any property is defined but not marked as required, the API will return a 400 Bad Request Error.
Using Pydantic Models
Using Pydantic Models
Pydantic provides automatic validation, serialization, and type hints for structured data:
When using OpenAI models with Pydantic Models, there should not be any optional fields in the pydantic model when strict mode is true. This is because the corresponding JSON schema will have missing fields in the “required” section.
Using OpenAI's Beta Parse API
Using OpenAI's Beta Parse API
The beta parse client provides the most streamlined approach for Pydantic integration:This approach allows for optional fields in your Pydantic model and provides a cleaner API for structured responses.