Skip to content

zodResponseFormat emits $ref values and definition keys with spaces #1679

@Gamrix

Description

@Gamrix

Confirm this is a Node library issue and not an underlying OpenAI API issue

  • This is an issue with the Node library

Describe the bug

Based on my conversations with OpenAI enterprise support, a lot of our OpenAI call errors are due to $ref values with literal spaces.

zodResponseFormat generates JSON Schema where reused sub-schemas are hoisted into definitions/$defs using keys derived from property names without sanitizing spaces. Corresponding $ref values
also include literal spaces (e.g., "#/$defs/example-scope_properties_group_properties_Thing With Spaces"). The OpenAI API at least sometimes choke on refs/keys containing spaces.

Expected: no literal spaces in any $ref values or definition/$defs keys.

To Reproduce

To Reproduce:
1. Install openai and zod.
2. Create a Zod schema with a reused sub-schema under a property name that includes spaces.
3. Call zodResponseFormat(schema, "example-scope") and inspect json_schema.schema.
4. Observe that at least one $ref and the corresponding definition key contain spaces.

Example observed (problematic):
refs: ["#/$defs/example-scope_properties_group_properties_Thing With Spaces"]
defs keys: ["example-scope_properties_group_properties_Thing With Spaces"]

Expectation: no spaces in any $ref or defs keys.

Code snippets

import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

// Collect all "$ref" strings from a JSON Schema object
function collectRefs(obj: any, acc: string[] = []): string[] {
    if (typeof obj.$ref === "string") acc.push(obj.$ref);
    for (const v of Object.values(obj)) collectRefs(v, acc);
    return acc;
}

// Reusable sub-schema to encourage hoisting into definitions/$defs
const Thing = z.object({ id: z.string() });

// Property name intentionally includes spaces
const Root = z.object({
    group: z.object({
      "Thing With Spaces": Thing,
      AnotherUsage: Thing, // second use -> likely hoisted + $ref
    }),
});

const scopeName = "example-scope";
const rf = zodResponseFormat(Root, scopeName);
const schema = rf.json_schema.schema;

const refs = collectRefs(schema);
console.log("refs:", refs);
console.log("defs keys:", Object.keys(schema.definitions ?? schema.$defs ?? {}));

OS

macOS (Darwin 24.6.0, arm64)

Node version

v22.14.0

Library version

5.23.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions