How to use it
To use JSON Mode, do three things:- In the system prompt, describe the expected JSON structure (JSON Schema-style descriptions are recommended).
- Set
response_formatto{ "type": "json_object" }so the model returns parsable JSON. - Parse the result and validate it. Once it matches expectations, pass it into your business logic.
Sample code
Here’s an example sentiment analyzer that returns JSON:Use JSON Schema to guide structure
Sometimes the model may drift from the expected shape. Adding a JSON Schema can clarify your intent. You can define required fields, meanings, and ranges. For example, the Schema below expects an object withurl and notes, both required:
Notes
- When using JSON Mode, check whether
finish_reasonisstop. If it islength, the model hitmax_tokensand the JSON may be incomplete or unparsable. - Provide input/output examples in the prompt to help the model understand your scenario and produce outputs that match expectations.