Principle:Openai Openai node Schema To JSON Conversion
| Knowledge Sources | |
|---|---|
| Domains | Schema_Validation, Type_Safety |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
A principle for converting runtime type validation schemas into JSON Schema format suitable for language model structured output constraints.
Description
Schema to JSON Conversion bridges the gap between application-level type definitions (using libraries like Zod) and the JSON Schema format required by the OpenAI API for structured outputs. The conversion must produce strict JSON Schema — meaning all properties are required, no additional properties are allowed, and the schema is fully deterministic. This ensures the model's output exactly matches the application's type expectations.
The conversion supports both Zod v3 (via vendored zod-to-json-schema) and Zod v4 (via native z4.toJSONSchema() with post-processing for strictness).
Usage
Use this principle whenever you need to constrain a language model's output to match a specific data structure. This is the first step in the structured output pipeline, before configuring the response format and making the API call.
Theoretical Basis
The conversion follows a Visitor Pattern that traverses the Zod schema tree:
function zodToJsonSchema(zodSchema, options):
// 1. Dispatch on Zod type discriminator
switch zodSchema.type:
case 'ZodObject': return convertObject(zodSchema)
case 'ZodArray': return convertArray(zodSchema)
case 'ZodString': return { type: 'string' }
case 'ZodNumber': return { type: 'number' }
case 'ZodEnum': return { enum: zodSchema.values }
...
// 2. Apply strict mode transformations:
// - Set additionalProperties: false on all objects
// - Make all properties required
// - Extract shared definitions to $defs
// 3. Return JSON Schema Draft 7 compatible object
The strict mode transformation is essential because the OpenAI API requires deterministic schemas where the model cannot introduce unexpected fields.