Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/structured-output-undo-null-widening.md
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.
3 changes: 2 additions & 1 deletion packages/ai-utils/src/index.ts
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'
103 changes: 103 additions & 0 deletions packages/ai-utils/src/transforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@
* therefore become `{}`; arbitrary class instances become a plain-object
* snapshot of just their own enumerable string properties. Don't pass
* non-JSON values.
*
* Schema-blind: strips EVERY null, including ones a `.nullable()` field
* legitimately allows. When the original schema is available, prefer
* {@link undoNullWidening}, which only strips the nulls strict-mode widening
* synthesized.
*/
export function transformNullsToUndefined<T>(obj: T): T {
if (obj === null) {
Expand All @@ -44,3 +49,101 @@ export function transformNullsToUndefined<T>(obj: T): T {
}
return result as T
}

/**
* Minimal structural view of a JSON Schema node — just the keywords
* {@link undoNullWidening} consults. Kept local so `@tanstack/ai-utils` stays
* dependency-free; the richer `JSONSchema` from `@tanstack/ai` is structurally
* assignable to it.
*/
export type JsonSchemaNode = {
type?: string | Array<string>
properties?: Record<string, JsonSchemaNode>
items?: JsonSchemaNode | Array<JsonSchemaNode>
anyOf?: Array<JsonSchemaNode>
oneOf?: Array<JsonSchemaNode>
[key: string]: unknown
}

/**
* Whether the schema node permits `null` — directly via `type` or through an
* `anyOf`/`oneOf` branch (how Valibot's `nullable`/`nullish` and Zod serialize).
*/
function allowsNull(schema: JsonSchemaNode): boolean {
if (schema.type === 'null') return true
if (Array.isArray(schema.type) && schema.type.includes('null')) return true
const variants = schema.anyOf ?? schema.oneOf
return variants ? variants.some(allowsNull) : false
}

/**
* For a composite (object/array) value under an `anyOf`/`oneOf` schema, pick the
* non-null branch describing that value's real shape so recursion can follow it
* (e.g. a `nullable(object({...}))` serializes as `anyOf: [object, null]`).
*/
function resolveSchema(schema: JsonSchemaNode, value: unknown): JsonSchemaNode {
const variants = schema.anyOf ?? schema.oneOf
if (!variants) return schema
const isArray = Array.isArray(value)
const match = variants.find((variant) => {
if (variant.type === 'null') return false
return isArray
? variant.type === 'array' || variant.items !== undefined
: variant.type === 'object' || variant.properties !== undefined
})
return match ?? schema
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

function walk(value: unknown, schema: JsonSchemaNode | undefined): unknown {
if (value === null) {
// Strip only when the schema is present AND definitively disallows null —
// i.e. the null was synthesized by strict-mode null-widening of an optional
// field. Keep nulls a `.nullable()` field genuinely allows, and — being
// conservative — nulls under shapes the schema doesn't describe.
return schema && !allowsNull(schema) ? undefined : null
}
if (typeof value !== 'object') return value
// Unknown shape (no schema, or `additionalProperties`): leave it untouched
// rather than guess which nulls are synthetic.
if (!schema) return value

if (Array.isArray(value)) {
const resolved = resolveSchema(schema, value)
const itemSchema = Array.isArray(resolved.items)
? resolved.items[0]
: resolved.items
return value.map((item) => walk(item, itemSchema))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

const resolved = resolveSchema(schema, value)
const props = resolved.properties
const result: Record<string, unknown> = {}
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
const next = walk(child, props?.[key])
// A synthesized null collapsed to undefined → omit the key so the field
// reads as absent (`key in result === false`), matching how `.optional()`
// treats absence.
if (next === undefined) continue
result[key] = next
}
return result
}

/**
* Schema-aware inverse of strict-mode null-widening for structured output.
*
* To satisfy OpenAI-style strict schemas, optional fields are widened to
* `required` with `null` added to their type, so the provider returns `null`
* for an absent optional. Validating that `null` against the ORIGINAL schema
* fails, because `.optional()` means `T | undefined`, not `T | null`.
*
* Unlike {@link transformNullsToUndefined}, this consults the original
* (un-widened) JSON Schema and only drops nulls the schema does NOT permit —
* the synthesized ones. Nulls a `.nullable()`/`.nullish()` field genuinely
* allows are preserved, so both `optional` and `nullable` fields round-trip
* correctly. With no schema, the value is returned untouched.
*/
export function undoNullWidening<T>(value: T, schema?: JsonSchemaNode): T {
if (!schema) return value
return walk(value, schema) as T
}
99 changes: 98 additions & 1 deletion packages/ai-utils/tests/transforms.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { describe, it, expect } from 'vitest'
import { transformNullsToUndefined } from '../src/transforms'
import type { JsonSchemaNode } from '../src/transforms'
import {
transformNullsToUndefined,
undoNullWidening,
} from '../src/transforms'
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

describe('transformNullsToUndefined', () => {
it('should convert null values to undefined', () => {
Expand Down Expand Up @@ -49,3 +53,96 @@ describe('transformNullsToUndefined', () => {
expect(result).toEqual({ a: { b: { c: { e: 'keep' } } } })
})
})

describe('undoNullWidening', () => {
// Mirrors the un-widened JSON Schema a Valibot/Zod object produces:
// req: string (required) -> v.string()
// opt: string, not required -> v.optional(v.string())
// nul: anyOf[string, null] -> v.nullable(v.string())
const schema: JsonSchemaNode = {
type: 'object',
properties: {
req: { type: 'string' },
opt: { type: 'string' },
nul: { anyOf: [{ type: 'string' }, { type: 'null' }] },
},
required: ['req', 'nul'],
}

it('drops a synthesized null on an optional field (key becomes absent)', () => {
const result = undoNullWidening({ req: 'a', opt: null }, schema)
expect(result).toEqual({ req: 'a' })
expect('opt' in (result as object)).toBe(false)
})

it('keeps a genuine null on a nullable field', () => {
const result = undoNullWidening({ req: 'a', nul: null }, schema)
expect(result).toEqual({ req: 'a', nul: null })
})

it('handles optional and nullable nulls in the same object', () => {
const result = undoNullWidening({ req: 'a', opt: null, nul: null }, schema)
expect(result).toEqual({ req: 'a', nul: null })
})

it('leaves present values untouched', () => {
const result = undoNullWidening({ req: 'a', opt: 'b', nul: 'c' }, schema)
expect(result).toEqual({ req: 'a', opt: 'b', nul: 'c' })
})

it('recurses into a nullable object via its anyOf branch', () => {
const nested: JsonSchemaNode = {
type: 'object',
properties: {
obj: {
anyOf: [
{
type: 'object',
properties: { inner: { type: 'string' }, note: { type: 'string' } },
required: ['inner'],
},
{ type: 'null' },
],
},
},
required: ['obj'],
}
// obj itself is present (kept), but its optional `note` came back null.
const result = undoNullWidening({ obj: { inner: 'x', note: null } }, nested)
expect(result).toEqual({ obj: { inner: 'x' } })
})

it('strips synthesized nulls inside array items', () => {
const arrSchema: JsonSchemaNode = {
type: 'object',
properties: {
items: {
type: 'array',
items: {
type: 'object',
properties: { id: { type: 'string' }, label: { type: 'string' } },
required: ['id'],
},
},
},
required: ['items'],
}
const result = undoNullWidening(
{ items: [{ id: '1', label: null }, { id: '2', label: 'two' }] },
arrSchema,
)
expect(result).toEqual({ items: [{ id: '1' }, { id: '2', label: 'two' }] })
})

it('returns the value untouched when no schema is supplied', () => {
const value = { a: null, b: 1 }
expect(undoNullWidening(value)).toBe(value)
})

it('leaves nulls under unknown (schemaless) properties untouched', () => {
// `extra` is not described by the schema — we cannot prove its null is
// synthetic, so it is preserved.
const result = undoNullWidening({ req: 'a', extra: null } as object, schema)
expect(result).toEqual({ req: 'a', extra: null })
})
})
1 change: 1 addition & 0 deletions packages/ai/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
"@ag-ui/core": "^0.0.52",
"@standard-schema/spec": "^1.1.0",
"@tanstack/ai-event-client": "workspace:*",
"@tanstack/ai-utils": "workspace:*",
"partial-json": "^0.1.7"
},
"peerDependencies": {
Expand Down
18 changes: 17 additions & 1 deletion packages/ai/src/activities/chat/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { devtoolsMiddleware } from '@tanstack/ai-event-client'
import { undoNullWidening } from '@tanstack/ai-utils'
import { stripToSpecMiddleware } from '../../strip-to-spec-middleware'
import { streamToText } from '../../stream-to-response.js'
import { resolveDebugOption } from '../../logger/resolve'
Expand All @@ -19,6 +20,7 @@ import {
} from './tools/tool-calls'
import {
convertSchemaToJsonSchema,
isStandardJSONSchema,
isStandardSchema,
parseWithStandardSchema,
} from './tools/schema-converter'
Expand Down Expand Up @@ -2699,13 +2701,27 @@ async function runAgenticStructuredOutput<
throw new Error('Failed to convert output schema to JSON Schema')
}

// The un-widened schema (no `forStructuredOutput`) still distinguishes
// genuinely-nullable fields from optional ones, so we can undo strict-mode's
// null-widening before validating: optional fields are widened to
// `required` + nullable for the provider, which then returns `null` for an
// absent optional — a `null` the original `.optional()` (`T | undefined`)
// schema would otherwise reject. `undoNullWidening` drops only those
// synthesized nulls, preserving the ones a `.nullable()` field allows.
const validationSchema = isStandardJSONSchema(outputSchema)
? convertSchemaToJsonSchema(outputSchema)
: undefined

// Validation runs INSIDE the engine (per spec §7.3) so validation failures
// route through the engine's terminal-hook chooser as `onError`. We pass a
// `validate` callback when the schema is a Standard Schema; otherwise we
// pass through the raw data and the engine returns it unchanged.
const validate = isStandardSchema(outputSchema)
? (data: unknown): unknown =>
parseWithStandardSchema<InferSchemaType<TSchema>>(outputSchema, data)
parseWithStandardSchema<InferSchemaType<TSchema>>(
outputSchema,
undoNullWidening(data, validationSchema),
)
: undefined

// Per issue #605: same capability check as the streaming path. When the
Expand Down
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 })
})
})
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.