Skip to main content
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.

Overview

There are two primary approaches for structured responses:
  1. JSON Mode: Basic JSON formatting without schema validation
  2. JSON Schema Mode: Structured responses with strict schema validation and Pydantic integration

Provider support for response schema

You can use response_format with any provider. The Gateway either uses the provider’s native structured output or converts your schema into a tool the model must call and then puts the result in message.content.
Anthropic and JSON schema constraints: The code examples in this doc use Pydantic’s ge=0 for fields such as age. Anthropic’s API does not support these constraint parameters in the schema. If you use structured output with Anthropic models, omit ge, le and similar numeric/string constraints from your schema (or use a schema without them). The code will work with Anthropic once those constraints are removed.

JSON Mode

JSON mode ensures the model’s output is valid JSON without enforcing a specific structure:
Output:

JSON Schema Mode

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.
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.
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.