Ensuring that AI-generated responses adhere to specific formats is crucial for applications requiring structured data. OpenAI's Structured Outputs feature addresses this need by allowing developers to enforce response structures through JSON Schemas.
Understanding Structured Outputs
Structured Outputs is a feature that ensures the model will always generate responses that adhere to your supplied JSON Schema. By defining the expected structure of the output, developers can ensure consistency and reliability in the data generated by the model.
Implementing Structured Outputs
To utilize Structured Outputs, developers provide a JSON Schema that outlines the desired structure of the model's response. This schema acts as a blueprint, guiding the model to generate outputs that conform to the specified format. For example, if a developer requires the model to produce a JSON object with specific properties, the schema would define these properties and their data types.

PreReqs:
type: module // Update your package.json
npm i openai zod --save // Install openai zod
export OPENAI_API_KEY=YOUR_ACTUAL_API_KEY
Imports:
import Opfrom 'openai';
import { from 'openai/helpers/zod';
import { from 'zod';
Setup OpenAI client:
const { OPENAI_API_KEY } = process.env;
const openai = new OpenAI({
apiKey: OPENAI_API_KEY,
});
Example: Extracting Movie Night Plans from a User's Message
Scenario:
You want to create a system that helps people organize movie nights by extracting key details like movie name, date, and host name from a casual text message.
// Import required libraries
const { z } = require("zod"); // Zod for validation.
const OpenAI = require("openai"); // OpenAI for GPT API access.
// Step 1: Set up the OpenAI API key
const openai = new OpenAI({
apiKey: "your-api-key-here", // Replace this with your OpenAI API key.
});
// Step 2: Define the expected JSON format for movie night details
// This ensures the AI response follows a specific structure.
const MovieNightFormat = z.object({
date: z.string(), // Example: "10th March 2025"
movie: z.string(), // Example: "Inception"
host: z.string(), // Example: "John"
});
// Step 3: Create a function to process the user input and extract movie night details
async function extractMovieNightDetails() {
try {
// Use the OpenAI API to analyze the user message
const completion = await openai.beta.chat.completions.parse({
model: "gpt-4o-2024-08-06", // Specify the model to use
messages: [
{ role: "system", content: "Extract movie night details from the user's message in a structured format." },
{ role: "user", content: "Hey, John! Let’s watch Inception at my place on 10th March 2025. It’s going to be epic!" },
],
// Specify that the AI response should follow the MovieNightFormat structure
response_format: zodResponseFormat(MovieNightFormat, "movie_night"), });
// Step 4: Log the extracted movie night details
console.log("Extracted Movie Night Details:", completion.choices[0].message.parsed);
} catch (error) {
// Handle errors gracefully
console.error("Error extracting movie night details:", error.message); }
}
// Step 5: Run the function
extractMovieNightDetails();
How It Works:
Define the Structure:
MovieNightFormat ensures the AI provides the output in a clear, structured format with three fields: date, movie, and host.
Provide the Context:
The system message explains the task: "Extract movie night details."
The user message is casual and unstructured, just like how someone might text a friend.
Validate the AI Output:
The response_format: zodResponseFormat(MovieNightFormat, "movie_night") ensures the response adheres to the defined format.
Handle Errors:
A try...catch block ensures the program doesn't crash if something goes wrong.
Result:
The extracted details are printed in the console.
Sample Output:
If the input is:
"Hey, John! Let’s watch Inception at my place on 10th March 2025. It’s going to be epic!"
The console logs:
Extracted Movie Night Details: { date: "10th March 2025", movie: "Inception", host: "John" }
Comments