OpenAI structured outputs with Zod in JavaScript

Authors
  • avatar
    Name
    Hamza Rahman
Published on
-
2 mins read

Use structured outputs when you need the model to return data that matches a schema instead of free-form text.

This example extracts event details into a Zod schema.

Install

npm install openai zod

Set your API key:

export OPENAI_API_KEY="your_api_key_here"

Code

import OpenAI from 'openai'
import { zodTextFormat } from 'openai/helpers/zod'
import { z } from 'zod'
const openai = new OpenAI()
const CalendarEvent = z.object({
title: z.string(),
date: z.string(),
attendees: z.array(z.string()),
})
const response = await openai.responses.parse({
model: 'gpt-5.5',
input: [
{
role: 'system',
content: 'Extract calendar event information from the user message.',
},
{
role: 'user',
content: 'Alice and Bob are joining the JavaScript meetup on Friday.',
},
],
text: {
format: zodTextFormat(CalendarEvent, 'calendar_event'),
},
})
console.log(response.output_parsed)

Example output:

{
title: 'JavaScript meetup',
date: 'Friday',
attendees: ['Alice', 'Bob']
}

Why use this?

With normal prompting, you still need to parse and validate the model output yourself. With structured outputs, your schema is part of the request, so the model is guided toward the exact shape you need.

Use this for:

  • Extracting fields from text
  • Returning app-ready JSON
  • Building form-fill helpers
  • Creating typed LLM responses

References