Skip to main content
JSON Schema mode takes structured output a step further by validating the response against a predefined schema. When the provider supports it natively, the schema is enforced at the API level, guaranteeing that the response matches the exact structure you defined.

Basic Usage

Use ResponseFormat::jsonSchema() to create a response format with a schema definition. Polyglot forwards the schema directly to the provider:

Using the Fluent API

You can also set the response format with the withResponseFormat() method, using the ResponseFormat::jsonSchema() factory:

Complex Nested Schemas

JSON Schema mode shines when you need complex, nested data structures. The provider will enforce every level of the schema:

How Schema Validation Works

With JSON Schema mode, the validation pipeline depends on the provider:
  1. The schema is sent to the provider as part of the API request.
  2. The model structures its response to match the schema.
  3. For providers with native support (like OpenAI), validation happens at the API level before the response is returned.
  4. Polyglot forwards the native schema request. It does not emulate schema enforcement for providers that lack it.
When strict is set to true, the provider will reject any response that does not conform to the schema and retry internally. This gives you strong guarantees about the output structure.

Provider Support

Provider support for JSON Schema varies significantly: You can query support programmatically:
For providers without native JSON Schema support, consider using JSON object mode with detailed prompts, or use the Instructor layer above Polyglot for automatic fallback strategies.

When to Use JSON Schema Mode

JSON Schema mode is ideal for:
  • Applications requiring strictly typed data with guaranteed structure
  • Integration with databases or APIs that expect specific field names and types
  • Data extraction with complex, nested structures
  • Ensuring consistent response formats across many requests
  • Any situation where a malformed response would cause downstream failures