Repository navigation
fix(ai): undo strict-mode null-widening before structured-output validation #732
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AlemTuzlak
merged 9 commits into
TanStack:main
from
DrewHoo:fix/structured-output-schema-aware-null-normalization
Jun 23, 2026
Merged
Changes from 1 commit
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
16af8c9
fix(ai): undo strict-mode null-widening before structured-output vali…
DrewHoo 3f44678
fix(ai-utils): handle tuple items and ambiguous anyOf branches in und…
DrewHoo 95e6295
refactor(ai): record null-widening map at conversion time instead of …
tombeckenham c6dedf9
fix(ai): un-widen structured-output nulls in the engine for both stre…
tombeckenham f63c35b
test(ai): cover native-combined + streaming-rewrite null normalizatio…
tombeckenham 5b263ad
test(openai-base): assert structuredOutputStream passes provider null…
tombeckenham 49f7a48
ci: apply automated fixes
autofix-ci[bot] 0c1be6c
test(react-native-smoke): register @tanstack/ai-utils in resolution c…
DrewHoo 88368c4
Merge branch 'main' into fix/structured-output-schema-aware-null-norm…
DrewHoo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| --- | ||
| '@tanstack/ai-utils': minor | ||
| '@tanstack/ai': patch | ||
| --- | ||
|
|
||
| Fix structured output validation rejecting `null` for optional fields. | ||
|
|
||
| Strict-mode structured output widens optional fields to `required` + nullable, so the provider returns `null` for an absent optional. Validating that `null` against the original schema then failed, because `.optional()` means `T | undefined`, not `T | null` — surfacing as a `StandardSchemaValidationError` (e.g. `Invalid type: Expected string but received null`). This was most visible through `@tanstack/ai-openrouter`, whose adapter preserves provider nulls. | ||
|
|
||
| The engine now undoes the widening before validation: it drops the synthesized nulls while preserving the ones a `.nullable()`/`.nullish()` field genuinely allows, so both optional and nullable fields round-trip correctly. | ||
|
|
||
| - `@tanstack/ai-utils` adds `undoNullWidening(value, schema)` — a schema-aware counterpart to `transformNullsToUndefined` that only strips nulls the original JSON Schema disallows. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| export { generateId } from './id' | ||
| export { getApiKeyFromEnv } from './env' | ||
| export { transformNullsToUndefined } from './transforms' | ||
| export { transformNullsToUndefined, undoNullWidening } from './transforms' | ||
| export type { JsonSchemaNode } from './transforms' | ||
| export { arrayBufferToBase64, base64ToArrayBuffer } from './base64' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
packages/ai/tests/chat-structured-output-null-normalization.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| /** | ||
| * Structured output: schema-aware null normalization. | ||
| * | ||
| * To satisfy OpenAI-style strict schemas, optional fields are widened to | ||
| * `required` + nullable, so the provider returns `null` for an absent optional. | ||
| * Validating that `null` against the original schema (`.optional()` === | ||
| * `T | undefined`, NOT `T | null`) used to throw. The engine now undoes the | ||
| * widening before validation — dropping synthesized nulls while preserving the | ||
| * ones a `.nullable()` field genuinely allows. | ||
| */ | ||
| import { describe, expect, it } from 'vitest' | ||
| import { z } from 'zod' | ||
| import { chat } from '../src/activities/chat/index' | ||
| import { createMockAdapter } from './test-utils' | ||
|
|
||
| const messages = [{ role: 'user' as const, content: 'go' }] | ||
|
|
||
| describe('structured output null normalization', () => { | ||
| it('drops a provider null for an optional field so validation passes', async () => { | ||
| const outputSchema = z.object({ | ||
| title: z.string(), | ||
| note: z.string().optional(), | ||
| }) | ||
| const { adapter } = createMockAdapter({ | ||
| // Strict-mode widening makes the provider return `null` for the absent | ||
| // optional. A schema-blind round-trip would fail validation here. | ||
| structuredOutput: async () => ({ | ||
| data: { title: 'Ship it', note: null }, | ||
| rawText: '{"title":"Ship it","note":null}', | ||
| }), | ||
| }) | ||
|
|
||
| const result = await chat({ adapter, messages, outputSchema }) | ||
|
|
||
| expect(result).toEqual({ title: 'Ship it' }) | ||
| expect('note' in result).toBe(false) | ||
| }) | ||
|
|
||
| it('keeps a genuine null for a nullable field', async () => { | ||
| const outputSchema = z.object({ | ||
| title: z.string(), | ||
| tag: z.string().nullable(), | ||
| }) | ||
| const { adapter } = createMockAdapter({ | ||
| structuredOutput: async () => ({ | ||
| data: { title: 'Ship it', tag: null }, | ||
| rawText: '{"title":"Ship it","tag":null}', | ||
| }), | ||
| }) | ||
|
|
||
| const result = await chat({ adapter, messages, outputSchema }) | ||
|
|
||
| expect(result).toEqual({ title: 'Ship it', tag: null }) | ||
| }) | ||
| }) |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.