Structured Output

Constrain model output with JSON Schema and Zod, and handle refusals and incomplete responses correctly.

🎯 Introduction

Suppose a backend needs to populate three fields from a product description: name, category, and price. If the model returns "This is a mouse priced at about RMB 199", the frontend must extract information from natural language, and the format may vary between answers.

We need an object the program can read directly. This article uses structured output in the official OpenAI SDK to generate data in a specified format.


🧱 Why Asking for JSON Is Not Enough

You can prompt the model to "return JSON only", but it may still add explanations, omit fields, or return unexpected data types. A string that passes JSON.parse() does not necessarily meet your application's requirements.

For example, the program expects:

{
    "name": "Wireless mouse",
    "category": "Electronics",
    "price": 199
}

The following is valid JSON, but does not match the required structure:

{
    "title": "Wireless mouse",
    "price": "RMB 199"
}

Distinguish these two steps: the model generates data under structural constraints, and the application checks whether it meets business requirements.


🛠 Define Fields with Zod

Continue using Node.js 24.x and openai@7.62.0, and install zod@4.1.0 for this article:

npm install --save-exact zod@4.1.0

Create 05.structured.mjs:

import OpenAI from "openai";
import { z } from "zod";
import { zodTextFormat } from "openai/helpers/zod";

const client = new OpenAI();

const Product = z.object({
    name: z.string(),
    category: z.enum(["Electronics", "Home", "Clothing"]),
    price: z.number()
});

const response = await client.responses.parse({
    model: process.env.OPENAI_MODEL,
    input: "Product information: a black wireless mouse in the Electronics category, priced at RMB 199. Extract the fields.",
    text: {
        format: zodTextFormat(Product, "product")
    }
});

if (response.status !== "completed" || !response.output_parsed) {
    throw new Error("No complete, parseable product data was returned");
}

console.log(response.output_parsed);

There are three key points:

  1. z.object() defines a product object with an explicit type for each field.
  2. zodTextFormat(Product, "product") converts the Zod structure into an output format the model API can use. product names this structure.
  3. responses.parse() attempts to parse the structured result after the request. output_parsed is an object you can read directly.

Here, price is the number 199, rather than the string "RMB 199". Structured output does not guarantee the price is true. This article extracts information from supplied text without verifying product facts.


🧱 Structural Constraints and Business Validation

Structural constraints help the model return fields matching the schema, but your application may impose further conditions, such as a positive price or a category that exists in the database.

Validate business rules after obtaining the object. Append this snippet after the response example above; it is not a standalone file:

const product = response.output_parsed;

if (product.price <= 0) {
    throw new Error("The product price must be greater than zero");
}

console.log("Ready to save:", product);

Production systems must also validate the business sources of field values. Do not treat generated data as trusted facts.

Structured output does not guarantee a usable object every time. Handle an empty output_parsed or incomplete status when the model refuses, generation reaches a limit, or the API fails.

⚖️ When to Use Structured Output

ScenarioRecommended output
Chat replies and article explanationsPlain text
Product information extractionA structured object
Intent classificationAn object with fixed enum values
Frontend form autofillAn object matching the form fields

If the application needs natural language for display, there is no need to force it into JSON. Choose the output based on what the program does next.


❓ Knowledge Check

Q1: Are JSON output and structured output the same?

Not exactly. Valid JSON may still have missing fields or incorrect types. Structured output also requires conformance to specified field and type rules.

Q2: Does Zod eliminate the need for backend validation?

No. A schema primarily handles data structure. The application remains responsible for business rules such as price ranges, user permissions, and whether a record exists in the database.


🧪 Exercise

Add a numeric stock field to extract inventory counts. Change the input to "USB-C hub, Electronics, priced at RMB 129, 35 units in stock".

Success criteria: The output contains name, category, price, and stock, and you validate that stock is nonnegative. Try an input without stock information, observe the result, and consider whether the business layer should supply missing information or reject saving it.


🎉 You can now obtain objects that your program can process. Next, you will let the model request calls to business functions.