API guides
Structured outputs
Use schema-constrained output when your application needs predictable fields rather than free-form prose. Support and accepted schema features vary by model; validate every result before using it.
Choose the output mode
- Plain text is appropriate for a human-readable reply.
- JSON mode requests valid JSON but does not by itself enforce your field schema.
- JSON Schema output requests a particular structure on supported models. A refusal, length limit, or transport error can still prevent a usable result.
Request a schema
Install openai and jsonschema for Python. The example uses the Chat Completions response_format field and validates the final response locally. Verify schema support for the model before production use.
python -m pip install openai jsonschema
Handle failures
- Validate the parsed object against your schema. Valid JSON is not necessarily a valid business object.
- Handle refusals, empty content, and length-limited replies separately. Do not interpret them as successful extraction.
- Use simple schemas first. Provider translations and supported keywords differ; a schema accepted by one model may not be accepted by another.
- For streaming, assemble the complete answer before parsing or validating JSON.