Basic Usage
UseResponseFormat::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 thewithResponseFormat() 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:- The schema is sent to the provider as part of the API request.
- The model structures its response to match the schema.
- For providers with native support (like OpenAI), validation happens at the API level before the response is returned.
- Polyglot forwards the native schema request. It does not emulate schema enforcement for providers that lack it.
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:
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