Response Format
The chat completions API supports structured response formats, enabling you to receive consistent, predictable outputs in JSON format. This is useful for parsing responses programmatically.JSON Response Options
Basic JSON Mode: Getting Valid JSON Without Structure Constraints
Basic JSON Mode: Getting Valid JSON Without Structure Constraints
JSON mode ensures the model’s output is valid JSON without enforcing a specific structure:Output:
JSON Schema Mode: Enforcing Specific Data Structures
JSON Schema Mode: Enforcing Specific Data Structures
JSON Schema mode provides strict structure validation using predefined schemas:
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.
Advanced Schema Integration
Python Type Validation with Pydantic Models
Python Type Validation with 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.
Streamlined Pydantic Integration with OpenAI's Beta Parse API
Streamlined Pydantic Integration with 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.