Back to roadmaps openai Course

Structured Outputs: Enforcing JSON Schemas

OpenAI supports Structured Outputs, ensuring the model outputs a JSON payload that strictly adheres to a developer-defined JSON Schema.


1. Why Use Structured Outputs?

Traditional models can occasionally hallucinate incorrect keys, generate wrong data types, or return invalid JSON. Structured Outputs eliminate this uncertainty, guaranteeing:

  • 100% Schema Compliance: The model will never generate properties missing from your schema or violate type definitions.
  • No Manual Validation Needed: You do not need to write complex validation logic to verify key existence before parsing.

2. Implementing Structured Outputs

Use the response_format configuration with json_schema structure attributes:

import { openai } from "../lib/openai";

// Define the expected output structure schema
const ArticleSchema = {
  name: "article_parser",
  strict: true, // Forces 100% compliance
  schema: {
    type: "object",
    properties: {
      title: { type: "string" },
      summary: { type: "string", description: "A one-sentence summary of the article." },
      category: { type: "string", enum: ["tech", "finance", "health", "lifestyle"] },
      tags: {
        type: "array",
        items: { type: "string" }
      }
    },
    required: ["title", "summary", "category", "tags"],
    additionalProperties: false // Must be set to false for strict validation
  }
};

async function parseArticle(articleText: string) {
  const completion = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [
      { role: "system", content: "Parse the article text into the requested structured keys." },
      { role: "user", content: articleText }
    ],
    // Enforce the custom schema structure
    response_format: {
      type: "json_schema",
      json_schema: ArticleSchema,
    }
  });

  const rawResult = completion.choices[0].message.content || "";
  
  // Directly typecast because compliance is guaranteed
  const parsedArticle = JSON.parse(rawResult);
  console.log("Structured Category:", parsedArticle.category);
  console.log("Structured Tags List:", parsedArticle.tags);
}

3. Strict Schema Rules

To use structured outputs with strict: true, you must adhere to these rules:

  1. Set additionalProperties to false: You must explicitly disable extra properties inside the schema structure.
  2. List all properties as required: Every field declared in properties must also be specified inside the required keys list. If you want a field to be optional, declare it as a union type containing null within the schema.
Published on Last updated: