OpenAI structured outputs with Zod in JavaScript
- Authors
- 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 zodSet 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
Common mistakes
- Writing a loose schema.
z.string()for everything throws away the safety you came for. Use enums, numbers, and arrays so the parsed result matches what your code actually expects. - Marking required fields optional. Structured outputs fill the shape you describe, so if
dateis optional the model is free to skip it. Make it required when your code depends on it. - Very deep or huge schemas. Deeply nested objects are slower and more error prone, so flatten where you can, and split a giant extraction into a couple of smaller calls.
Related
- Force an LLM to return JSON in JavaScript: the beginner-friendly framing if you just need reliable JSON out of a model.
- OpenAI function calling in JavaScript: let the model trigger your functions instead of only returning data.
References
Related articles
Force an LLM to return JSON in JavaScript
Reliably get JSON from an LLM in JavaScript with OpenAI structured outputs and a Zod schema, instead of prompting for JSON and parsing fragile model text yourself.
OpenAI function calling JavaScript example
A minimal OpenAI function calling example in JavaScript using the Responses API and a local tool, including the two-step call-the-tool then answer loop.
LangChain JS agent with a custom tool
Create a small LangChain JavaScript agent with one custom tool using createAgent, tool, and a Zod schema, with a runnable end-to-end example.

