Zod is a TypeScript-first schema validation library: you define schemas you can use to validate data, from a simple string to a complex nested object, and the types are inferred from the schema. The OpenAI SDKs let you define object schemas using z.object in JavaScript, so the same Zod schema both constrains the model output and validates the parsed result in your code. Using Zod instead of hand-writing JSON Schema keeps the schema and the TypeScript types from diverging.
What you need
- A TypeScript project with zod installed
- The fields the model must return, with their types
- The OpenAI JavaScript SDK or another SDK that accepts Zod schemas
Step 1: Write the schema as a Zod object
Define the object with z.object, giving each field a type, for example z.string for a name and z.array for a list, and mark required fields. Keep the schema small: every field is a promise the model must keep.
Step 2: Pass the schema as the response format
Pass the Zod object to the SDK as the text format for the call. The model output is then constrained to the schema, so the reply should parse without extra repair.
Step 3: Validate the parsed result before use
Read the parsed result from the SDK response and validate it with the same schema before your code uses it. Structured outputs guarantee schema adherence, but your application still needs to validate business rules the schema does not express.
Worked example: synthetic Zod schema for an event
The table below is a synthetic example. It shows the expected result of defining a Zod schema; no call was made.
| Field | Zod type | Required? |
|---|---|---|
| name | z.string() | Yes |
| date | z.string() | Yes |
| participants | z.array(z.string()) | Yes |
| notes | z.string().optional() | No |
Expected result (UNTESTED). the schema defines 3 required fields and 1 optional field, and the parsed result validates against it. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- Zod is tested against TypeScript 5.5 and later; older versions may work but are not officially supported.
- Structured outputs constrain completed, non-refusal output to the schema; refusals and incomplete responses still need handling.
- A schema cannot express business rules, such as a date being in the future; validate those in code.
- To prevent JSON Schema and code types from diverging, use the native SDK schema helpers where available.
