Implementation:Openai Openai node Zod Union Parser
| Knowledge Sources | |
|---|---|
| Domains | SDK, Schema_Conversion, Validation |
| Last Updated | 2026-02-15 12:00 GMT |
Overview
The Zod Union Parser converts Zod union and discriminatedUnion schemas into their JSON Schema equivalents, optimizing for compact representations when possible.
Description
The parseUnionDef function handles the conversion of ZodUnionDef and ZodDiscriminatedUnionDef types into JSON Schema 7 output. It employs several optimization strategies to produce the most concise schema representation possible rather than always falling back to a generic anyOf construct.
The first optimization checks whether all union options are primitive types (string, number, bigint, boolean, null) without any validation checks. If so, it produces a compact { type: ['string', 'number'] } schema using a type array instead of anyOf. The second optimization detects when all options are literal values and produces a combined { type: ..., enum: [...] } schema. A third optimization handles the case where all options are ZodEnum types and merges their values into a single enum. For OpenAPI 3 targets (refs.target === 'openApi3'), the function always uses the anyOf form since type arrays are not supported.
When none of the optimizations apply, the asAnyOf fallback function recursively calls parseDef for each union option, building an { anyOf: [...] } schema. Options that produce empty schemas are filtered out when strictUnions is enabled. The function handles both regular unions (where options is an array) and discriminated unions (where options is a Map).
Usage
This parser is invoked automatically by the central parseDef dispatch for ZodUnion and ZodDiscriminatedUnion types. It is part of the internal zod-to-json-schema pipeline and is not called directly by SDK consumers.
Code Reference
Source Location
- Repository: openai-node
- File: src/_vendor/zod-to-json-schema/parsers/union.ts
Signature
export function parseUnionDef(
def: ZodUnionDef | ZodDiscriminatedUnionDef<any, any>,
refs: Refs,
): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined;
export type JsonSchema7UnionType = JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType;
export const primitiveMappings: {
ZodString: 'string';
ZodNumber: 'number';
ZodBigInt: 'integer';
ZodBoolean: 'boolean';
ZodNull: 'null';
};
Import
import OpenAI from 'openai';
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| def | ZodDiscriminatedUnionDef | Yes | The Zod union or discriminated union definition. Contains an options field that is either an array of Zod types or a Map (for discriminated unions).
|
| refs | Refs |
Yes | Conversion context including target, strictUnions, currentPath, and other configuration.
|
Outputs
| Name | Type | Description |
|---|---|---|
| type | JsonSchema7Primitive[] | Type or type array for primitive-only unions. |
| enum | number | bigint | boolean | null)[] | Enum values for literal-only unions. |
| anyOf | JsonSchema7Type[] |
Array of JSON Schema alternatives for complex unions. |
Usage Examples
// The union parser is used internally during schema conversion.
// Below shows the Zod schemas and their resulting JSON Schema output.
import { z } from 'zod';
import { zodResponseFormat } from 'openai/helpers/zod';
// Primitive union -> optimized to type array
// z.union([z.string(), z.number()])
// => { type: ['string', 'number'] }
// Literal union -> optimized to enum
// z.union([z.literal('a'), z.literal('b'), z.literal('c')])
// => { type: 'string', enum: ['a', 'b', 'c'] }
// Complex union -> falls back to anyOf
const Shape = z.discriminatedUnion('type', [
z.object({ type: z.literal('circle'), radius: z.number() }),
z.object({ type: z.literal('square'), side: z.number() }),
]);
// => { anyOf: [
// { type: 'object', properties: { type: { type: 'string', const: 'circle' }, radius: { type: 'number' } } },
// { type: 'object', properties: { type: { type: 'string', const: 'square' }, side: { type: 'number' } } }
// ] }
const format = zodResponseFormat(z.object({ shape: Shape }), 'shape_info');