Skip to content

Commit

Permalink
feat: add warning for .optional() usage in OpenAI API schemas
Browse files Browse the repository at this point in the history
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
  • Loading branch information
devin-ai-integration[bot] committed Dec 9, 2024
1 parent fbd9685 commit 2ace9e4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/_vendor/zod-to-json-schema/parsers/optional.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ import { JsonSchema7Type, parseDef } from '../parseDef';
import { Refs } from '../Refs';

export const parseOptionalDef = (def: ZodOptionalDef, refs: Refs): JsonSchema7Type | undefined => {
if (refs.openaiStrictMode) {
const fieldName = refs.propertyPath?.slice(-1)[0] || 'unknown';
console.warn(
`Warning: Field "${fieldName}" uses .optional() which is not supported by OpenAI API Structured Outputs. ` +
`Please use .nullable() instead. ` +
`See: https://platform.openai.com/docs/guides/structured-outputs#all-fields-must-be-required`
);
}

if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
return parseDef(def.innerType._def, refs);
}
Expand Down
18 changes: 18 additions & 0 deletions tests/helpers/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,24 @@ describe('zodResponseFormat', () => {
`);
});

it('warns when using optional fields with OpenAI API', () => {
const consoleSpy = jest.spyOn(console, 'warn');

zodResponseFormat(
z.object({
required: z.string(),
optional: z.string().optional(),
}),
'test',
);

expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('uses .optional() which is not supported by OpenAI API Structured Outputs')
);

consoleSpy.mockRestore();
});

it('automatically adds properties with defaults to `required`', () => {
expect(
zodResponseFormat(
Expand Down

0 comments on commit 2ace9e4

Please sign in to comment.