[Bug] Zod unions inside schema fail due to missing `additionalProperties: false` (in strict mode)
Description
Minimal reproduction sample:
import { OpenAIResponsesProviderOptions, openai } from '@ai-sdk/openai';
import { streamObject } from 'ai';
import { z } from 'zod';
const { textStream } = streamObject({
model: openai('gpt-5.1'),
schema: z.object({
item: z.union([
z.object({ type: z.literal('item1') }),
z.object({ type: z.literal('item2') }),
]),
}),
prompt: 'Generate an item',
providerOptions: {
openai: {
strictJsonSchema: true,
} satisfies OpenAIResponsesProviderOptions,
},
});
for await (const textPart of textStream) {
console.log(textPart);
}
Raises this error:
APICallError [AI_APICallError]: Invalid schema for response_format 'response': In context=('properties', 'items', 'anyOf', '0'), 'additionalProperties' is required to be supplied and to be false.
at <anonymous> (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/@[email protected][email protected]/node_modules/@ai-sdk/provider-utils/src/response-handler.ts:57:16)
at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
at async postToApi (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/@[email protected][email protected]/node_modules/@ai-sdk/provider-utils/src/post-to-api.ts:118:28)
at async OpenAIResponsesLanguageModel.doStream (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/@[email protected][email protected]/node_modules/@ai-sdk/openai/src/responses/openai-responses-language-model.ts:727:50)
at async fn (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/[email protected][email protected]/node_modules/ai/src/generate-object/stream-object.ts:560:23)
at async <anonymous> (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/[email protected][email protected]/node_modules/ai/src/telemetry/record-span.ts:18:22)
at async _retryWithExponentialBackoff (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/[email protected][email protected]/node_modules/ai/src/util/retry-with-exponential-backoff.ts:96:12)
at async fn (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/[email protected][email protected]/node_modules/ai/src/generate-object/stream-object.ts:528:13)
at async <anonymous> (/Users/jeto/dev/projects/***/***/node_modules/.pnpm/[email protected][email protected]/node_modules/ai/src/telemetry/record-span.ts:18:22) {
cause: undefined,
url: 'https://api.openai.com/v1/responses',
- Also happens with discriminated unions.
- Also happens with ai@beta (which has strict JSON schemas by default).
This is possible when using OpenAI's own structured model output in streaming mode feature.
Am I missing a flag of some sort?
AI SDK Version
- ai: 5.0.116
- @ai-sdk/openai: 2.0.88
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
If anyone encouters this, here's a possible workaround in the meantime, based on a rewrite of this function to handle anyOf and the other similar keys:
import { JSONSchema7, Schema, jsonSchema } from 'ai';
function addAdditionalPropertiesToJsonSchema(
jsonSchema: JSONSchema7,
): JSONSchema7 {
if (jsonSchema.type === 'object') {
jsonSchema.additionalProperties = false;
const properties = jsonSchema.properties;
if (properties != null) {
for (const property in properties) {
properties[property] = addAdditionalPropertiesToJsonSchema(
properties[property] as JSONSchema7,
);
}
}
}
if (jsonSchema.type === 'array' && jsonSchema.items != null) {
if (Array.isArray(jsonSchema.items)) {
jsonSchema.items = jsonSchema.items.map(item =>
addAdditionalPropertiesToJsonSchema(item as JSONSchema7),
);
} else {
jsonSchema.items = addAdditionalPropertiesToJsonSchema(
jsonSchema.items as JSONSchema7,
);
}
}
if (jsonSchema.anyOf != null) {
jsonSchema.anyOf = jsonSchema.anyOf.map(schema =>
addAdditionalPropertiesToJsonSchema(schema as JSONSchema7),
);
}
if (jsonSchema.allOf != null) {
jsonSchema.allOf = jsonSchema.allOf.map(schema =>
addAdditionalPropertiesToJsonSchema(schema as JSONSchema7),
);
}
if (jsonSchema.oneOf != null) {
jsonSchema.oneOf = jsonSchema.oneOf.map(schema =>
addAdditionalPropertiesToJsonSchema(schema as JSONSchema7),
);
}
return jsonSchema;
}
function asStrictZodSchema<T>(schema: Schema<T>): Schema<T> {
addAdditionalPropertiesToJsonSchema(schema.jsonSchema);
return jsonSchema(schema.jsonSchema);
}
Usage:
schema: asStrictZodSchema(zodSchema(z.object({
item: z.union([
z.object({ type: z.literal('item1') }),
z.object({ type: z.literal('item2') }),
]),
}))),
When schemas are not supported by strict mode, you can opt out by setting the strictJsonSchema provider option to false.
https://ai-sdk.dev/providers/ai-sdk-providers/openai#responses-models
Your new function looks good, would you mind creating a PR and adding a few test cases?
When schemas are not supported by strict mode, you can opt out by setting the
strictJsonSchemaprovider option tofalse.https://ai-sdk.dev/providers/ai-sdk-providers/openai#responses-models
Yes (it's even disabled by default in v5), but I'm using the same Zod schemas for objects/types that my app relies on, so strict mode ensures the LLM never generates anything that doesn't match.
Your new function looks good, would you mind creating a PR and adding a few test cases?
Thanks! Won't have too much time this week but I may give it a go in a bit.
@Jeto143 I can also take it on!
Motivated to fix this so my team can upgrade to v6 :)
Identify issue type
Identified as Bug
Confidence: High
Rationale
The SDK's strict-schema conversion does not process object schemas nested within union constructs, producing an invalid schema that OpenAI rejects. This is a concrete failure in existing behavior.
Evidence
- A minimal reproduction using
streamObject, OpenAI strict JSON Schema mode, and a Zod union fails with an API error requiringadditionalProperties: falsewithinanyOf. - The same failure occurs with discriminated unions and the v6 beta, where strict schemas are enabled by default.
- The proposed workaround extends the SDK's schema transformation to traverse
anyOf,allOf, andoneOf; a maintainer requested a PR and tests for this change.