这是indexloc提供的服务,不要输入任何密码
Skip to content

Generated OpenAPI schemas use "nullable" instead of ["type","null"] #5432

@marekkobida

Description

@marekkobida

When generating JSON Schema for OpenAI, the current z.toJSONSchema(..., { target: 'openapi-3.0' }) output produces invalid structures that are not accepted by the OpenAI API.

According to the OpenAI documentation:

All fields in properties must be marked as required.
You can denote optional fields by adding null as a type option (see example below).
OpenAI Function Calling · Strict Mode

However, toJSONSchema still emits nullable: true, which is not valid in the JSON Schema format OpenAI expects.

Example:

import z from 'zod';

const Schema = z.object({
  option1: z.union([z.string(), z.null()]),
  option2: z.string().nullable(),
  option3: z.nullable(z.string()),
});

const schema = z.toJSONSchema(Schema, {
  target: 'openapi-3.0',
});

console.log(schema);

Output:

{
    "additionalProperties": false,
    "properties": {
        "option1": {
            "anyOf": [
                {
                    "enum": [
                        null
                    ],
                    "nullable": true,
                    "type": "string"
                },
                {
                    "type": "string"
                }
            ]
        },
        "option2": {
            "nullable": true,
            "type": "string"
        },
        "option3": {
            "nullable": true,
            "type": "string"
        }
    },
    "required": [
        "option1",
        "option2",
        "option3"
    ],
    "type": "object"
}

Expected:

{
    "additionalProperties": false,
    "properties": {
        "option1": {
            "type": [
                "null",
                "string"
            ]
        },
        "option2": {
            "type": [
                "null",
                "string"
            ]
        },
        "option3": {
            "type": [
                "null",
                "string"
            ]
        }
    },
    "required": [
        "option1",
        "option2",
        "option3"
    ],
    "type": "object"
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions