Skip to content

Commit 2ace9e4

Browse files
feat: add warning for .optional() usage in OpenAI API schemas
This commit adds a warning when .optional() is used in schemas for OpenAI API Structured Outputs, recommending the use of .nullable() instead. - Added warning in optional.ts that triggers when openaiStrictMode is true - Added test to verify warning behavior Fixes openai#1180
1 parent fbd9685 commit 2ace9e4

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Diff for: src/_vendor/zod-to-json-schema/parsers/optional.ts

+9
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@ import { JsonSchema7Type, parseDef } from '../parseDef';
33
import { Refs } from '../Refs';
44

55
export const parseOptionalDef = (def: ZodOptionalDef, refs: Refs): JsonSchema7Type | undefined => {
6+
if (refs.openaiStrictMode) {
7+
const fieldName = refs.propertyPath?.slice(-1)[0] || 'unknown';
8+
console.warn(
9+
`Warning: Field "${fieldName}" uses .optional() which is not supported by OpenAI API Structured Outputs. ` +
10+
`Please use .nullable() instead. ` +
11+
`See: https://platform.openai.com/docs/guides/structured-outputs#all-fields-must-be-required`
12+
);
13+
}
14+
615
if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
716
return parseDef(def.innerType._def, refs);
817
}

Diff for: tests/helpers/zod.test.ts

+18
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,24 @@ describe('zodResponseFormat', () => {
8888
`);
8989
});
9090

91+
it('warns when using optional fields with OpenAI API', () => {
92+
const consoleSpy = jest.spyOn(console, 'warn');
93+
94+
zodResponseFormat(
95+
z.object({
96+
required: z.string(),
97+
optional: z.string().optional(),
98+
}),
99+
'test',
100+
);
101+
102+
expect(consoleSpy).toHaveBeenCalledWith(
103+
expect.stringContaining('uses .optional() which is not supported by OpenAI API Structured Outputs')
104+
);
105+
106+
consoleSpy.mockRestore();
107+
});
108+
91109
it('automatically adds properties with defaults to `required`', () => {
92110
expect(
93111
zodResponseFormat(

0 commit comments

Comments
 (0)