ai icon indicating copy to clipboard operation
ai copied to clipboard

JSON Schema: 'definitions' are not supported with output mode 'array' (OpenAI).

Open jpkleemans opened this issue 1 year ago • 6 comments

Description

When using the array output mode with generateObject or streamObject, I can't include definitions in the JSON Schema. This is because the package wraps my schema inside its own array schema, preventing access to the root level. Since OpenAI only allows definitions at the root level, this setup causes the following error: Reference can only point to definitions defined at the top level of the schema.

AI SDK Version

  • ai: 4.3.15
  • @ai-sdk/openai: 1.3.22

jpkleemans avatar May 23 '25 08:05 jpkleemans

Identify issue type

Identified type: Bug
Confidence: High

Rationale: The issue reports a concrete failure when using JSON Schema definitions with existing object generation APIs in array mode, resulting in an OpenAI schema error.

Evidence:

  • Using array output mode with generateObject or streamObject prevents including JSON Schema definitions.
  • The SDK wraps the user schema inside its own array schema, so OpenAI cannot resolve root-level definitions.
  • The reported error is: Reference can only point to definitions defined at the top level of the schema.

lgrammel avatar Jul 02 '26 10:07 lgrammel

This still reproduces with AI SDK 7 and Output.array().

Bug

Array output wraps the element schema under properties.elements.items. When the element schema contains definitions or $defs, those definitions move into items, while references such as #/definitions/Shared still resolve from the generated schema root.

This produces an invalid reference and OpenAI rejects the schema because definitions must be at the top level.

Simple solution

When constructing the array wrapper, extract definitions and $defs from the element schema alongside $schema. Place them on the generated schema root, and place the remaining element schema under items.

This preserves existing references such as #/definitions/Shared and #/$defs/Shared.

The change should apply to both Output.array() and the deprecated generateObject / streamObject array output path.

n1ckoates avatar Aug 12 '26 17:08 n1ckoates

Bug Reproduction - AI SDK 7

Bug was reproduced.

Branch: main PR: successful reproduction pull request

Details

  • Live OpenAI gpt-4o-mini calls from examples/ai-functions/src/reproduction/issue-6454-openai-array-definitions.ts returned HTTP 400 for generateText, streamText, deprecated generateObject, and deprecated streamObject; both definitions and $defs references failed, while the expected result was one validated array element.
  • Equivalent direct OpenAI requests succeeded when definitions or $defs remained at the generated schema root, establishing the AI SDK array wrapper as the failure boundary.
  • packages/ai/src/generate-text/output.ts and packages/ai/src/generate-object/output-strategy.ts move the complete element schema under properties.elements.items, leaving root-relative references unable to resolve.
  • Regression coverage in packages/ai/src/generate-text/output.test.ts and packages/ai/src/generate-object/output-strategy.test.ts fails on main for both definition keywords and expects them to remain at the wrapper root.
  • Live responses are recorded in packages/openai/src/responses/__fixtures__/issue-6454-nested-definitions-error.json and packages/openai/src/responses/__fixtures__/issue-6454-root-definitions-success.json; packages/openai/src/responses/openai-responses-language-model.test.ts confirms the provider adapter preserves correctly rooted definitions.
  • The issue reproduces with the compatible workspace versions [email protected] and @ai-sdk/[email protected], so it is not limited to the originally reported AI SDK 4 package combination.

Relevant Documentation

  • https://developers.openai.com/api/docs/guides/structured-outputs
  • https://ai-sdk.dev/docs/reference/ai-sdk-core/output

ai-sdk-factory[bot] avatar Aug 12 '26 17:08 ai-sdk-factory[bot]

Bugfix - AI SDK 7

Created bugfix and opened PR: #18802

Root Cause

Both array schema wrappers moved the complete element schema, including definitions and $defs, under properties.elements.items while references still resolved from the generated root. Live HTTP 400 responses and failing regression tests confirmed the defect.

Summary

Array output wrappers now hoist definitions and $defs to the generated schema root while retaining the remaining element schema under items. A patch changeset was added.

Testing

Added regression coverage for definitions and $defs across Output.array() and the deprecated array output strategy.

ai-sdk-factory[bot] avatar Aug 12 '26 18:08 ai-sdk-factory[bot]

:rocket: Published in:

Package Version
ai 7.0.65 github npm
@ai-sdk/angular 3.0.65 github npm
@ai-sdk/code-mode 1.0.22 github npm
@ai-sdk/gateway 4.0.52 github npm
@ai-sdk/google 4.0.44 github npm
@ai-sdk/google-vertex 5.0.53 github npm
@ai-sdk/harness 1.0.71 github npm
@ai-sdk/harness-acp 1.0.8 github npm
@ai-sdk/harness-claude-code 1.0.74 github npm
@ai-sdk/harness-codex 1.0.73 github npm
@ai-sdk/harness-deepagents 1.0.71 github npm
@ai-sdk/harness-grok-build 1.0.7 github npm
@ai-sdk/harness-opencode 1.0.72 github npm
@ai-sdk/harness-pi 1.0.72 github npm
@ai-sdk/langchain 3.0.65 github npm
@ai-sdk/llamaindex 3.0.65 github npm
@ai-sdk/otel 1.0.65 github npm
@ai-sdk/policy-opa 1.0.65 github npm
@ai-sdk/react 4.0.68 github npm
@ai-sdk/rsc 3.0.65 github npm
@ai-sdk/sandbox-just-bash 1.0.71 github npm
@ai-sdk/sandbox-vercel 1.0.71 github npm
@ai-sdk/svelte 5.0.65 github npm
@ai-sdk/tui 1.0.66 github npm
@ai-sdk/vue 4.0.65 github npm
@ai-sdk/workflow 1.0.65 github npm
@ai-sdk/workflow-harness 1.0.71 github npm

github-actions[bot] avatar Aug 13 '26 19:08 github-actions[bot]

The definitions / $defs cases fixed by #18802 work, but a related case remains in [email protected]: an array element schema with $ref: "#" now refers to the SDK's { elements: [...] } wrapper instead of the element itself.

This affects ordinary recursive Zod schemas. The generated provider schema rejects a valid nested tree and accepts a child that Zod rejects.

Reproduction

No API key or model call needed. In an empty directory:

npm init -y
npm install --save-exact [email protected] [email protected] [email protected]

Save as repro.mjs and run node repro.mjs:

import { Output } from 'ai';
import { Ajv } from 'ajv';
import { z } from 'zod';

const Tree = z.object({
  label: z.string(),
  get children() { return z.array(Tree); },
});
const validTree = {
  label: 'Root',
  children: [{ label: 'Child', children: [] }],
};
const wrongTree = { label: 'Root', children: [{ elements: [] }] };
const format = await Output.array({ element: Tree }).responseFormat;
if (format?.type !== 'json' || format.schema == null) throw new Error('Missing schema');
const validate = new Ajv().compile(format.schema);

console.log('Valid tree: Zod =', Tree.safeParse(validTree).success,
  ', provider schema =', validate({ elements: [validTree] }));
console.log('Validation errors:', validate.errors);
console.log('Wrong tree: Zod =', Tree.safeParse(wrongTree).success,
  ', provider schema =', validate({ elements: [wrongTree] }));

Actual:

Valid tree: Zod = true , provider schema = false
Validation errors: ... /elements/0/children/0 must have required property 'elements'
Wrong tree: Zod = false , provider schema = true

Expected: the provider schema accepts the valid tree and rejects the wrong tree, matching Zod.

Checks

Using MockLanguageModelV4, I also captured the schema passed to generateText, streamText, generateObject, and streamObject. All four have this mismatch. On both Node 22.20.0 and 24.13.0, the test suite has 8 failing assertions (valid/wrong recursive children for each API) and 14 passing controls (leaf nodes, both definition keywords, and Output.object).

Both wrapper implementations still contain this behavior on main at 12845693d7a6a517dc633d6b6a2e4f5bfd24d2ec: Output.array and legacy array strategy. They move the element under properties.elements.items without preserving what its root self-reference points to. A fix should preserve that reference while retaining the working definitions / $defs cases.

These checks validate the generated schema locally; I have not tested a live provider response.

I used AI assistance to investigate and prepare the reproduction and tests.

brennanbutler01 avatar Sep 18 '26 03:09 brennanbutler01