Skip to main content

Choose an output mode

A compatible endpoint does not imply json_schema support for every model. Test the target model with a minimal Schema. Resolve unsupported-parameter errors before changing modes; avoid silently accepting invalid business data after a fallback.

Runnable example: extract a product

Complete the TypeScript SDK setup. Save as structured-output.mts and run node structured-output.mts. The example requests a product name and quantity using strict Schema, then independently checks a nonempty name and a nonnegative safe integer quantity.
An example successful output shape:
The exact product wording can vary. Valid JSON does not establish factual correctness; check allowed products, ranges, and business operations too. For larger objects, use an existing JSON Schema validator or data-model library instead of manual field checks.

Handle failures

  • finish_reason=length: the output may be truncated; do not repair the JSON and treat it as complete.
  • message.refusal or absent content: use a refusal/failure branch before parsing.
  • Unsupported Schema or failed validation: retain a failed state, inspect the request and model capabilities, and avoid unbounded retries.
  • Streaming: JSON fragments generally cannot be parsed separately. Confirm completion before parsing the full text; discard interrupted structured results.
OpenAI-style strict Schema generally requires additionalProperties: false on objects and properties listed in required. Nullable fields need an appropriate Schema and support from the selected model.

Responses uses a different field

Chat Completions uses response_format: {type: "json_schema", json_schema: {...}}. Responses uses text: {format: {type: "json_schema", name, schema, strict}}. Do not copy response_format unchanged into a Responses request. API parameters · Errors and retries

TypeScript: structured extraction with Responses

Save as responses-structured.mts, configure the TypeScript SDK, and run node responses-structured.mts. The channel must support strict Schema through Responses text.format; Chat Completions support alone does not establish this capability.
The successful structure matches the Chat example: a product name and a nonnegative safe-integer quantity. Before parsing, this example checks response and message completion, rejects refusals, tool calls, and empty text, then validates JSON and business fields. A refusal may appear in output[].content[] even when the overall status is completed. Reference: OpenAI structured outputs. 简体中文

Complete JSON-mode example

JSON mode and result validation adds Chat / Responses json_object examples, required nullable fields, integer ranges, and failure short-circuiting. It complements this page’s json_schema examples.