Open History to see the last commit
1import type { NullWideningMap } from '@tanstack/ai-utils'
2import type { Tool } from '@tanstack/ai'
3import type { InternalLogger } from '@tanstack/ai/adapter-internals'
4
5/**
6 * String `format` values accepted by OpenAI's strict Structured Outputs subset.
7 * Any other format (e.g. "uri", "uri-reference", "regex") causes the API to
8 * reject the whole request with `400 ... '<format>' is not a valid format`.
9 * MCP servers and hand-written tools routinely declare such formats, so we strip
10 * the unsupported ones before sending. See:
11 * https://platform.openai.com/docs/guides/structured-outputs#supported-properties
12 */
13const SUPPORTED_STRING_FORMATS = new Set([
14 'date-time',
15 'time',
16 'date',
17 'duration',
18 'email',
19 'hostname',
20 'ipv4',
21 'ipv6',
22 'uuid',
23])
24
25/**
26 * Recursively drop JSON-Schema `format` keywords whose value isn't in OpenAI's
27 * strict-mode allowlist. Pure — returns a fresh tree and never mutates `node`,
28 * so the caller's original tool definition is left intact.
29 *
30 * A property *named* `format` always has a schema (object/boolean) value, never
31 * a bare string, so it is preserved and recursed into; only the `format`
32 * *keyword* (whose value is a string) is subject to removal.
33 */
34export function stripUnsupportedFormats(node: any): any {
35 if (Array.isArray(node)) return node.map(stripUnsupportedFormats)
36 if (node === null || typeof node !== 'object') return node
37
38 // `Object.fromEntries` keeps an own key named `__proto__`. An assignment
39 // `out['__proto__'] = x` would set the prototype instead.
40 return Object.fromEntries(
41 Object.entries(node)
42 .filter(
43 ([key, value]) =>
44 key !== 'format' ||
45 typeof value !== 'string' ||
46 SUPPORTED_STRING_FORMATS.has(value),
47 )
48 .map(([key, value]) => [key, stripUnsupportedFormats(value)]),
49 )
50}
51
52/**
53 * Transform a JSON schema to be compatible with OpenAI's structured output requirements.
54 * OpenAI requires:
55 * - All properties must be in the `required` array
56 * - Optional fields should have null added to their type union
57 * - additionalProperties must be false for objects
58 * - String `format` keywords must be from a fixed allowlist (others are stripped)
59 *
60 * @param schema - JSON schema to transform
61 * @param originalRequired - Original required array (to know which fields were optional)
62 * @returns Transformed schema compatible with OpenAI structured output
63 */
64export function makeStructuredOutputCompatible(
65 schema: Record<string, any>,
66 originalRequired?: Array<string>,
67): Record<string, any> {
68 return makeStructuredOutputCompatibleWithMap(schema, originalRequired).schema
69}
70
71export interface StructuredOutputCompatibility {
72 schema: Record<string, any>
73 nullWideningMap: NullWideningMap | undefined
74}
75
76interface CoercedStrictSchema extends StructuredOutputCompatibility {
77 hasUntrackableAnyOfWidening: boolean
78}
79
80/**
81 * Strict-schema conversion plus an exact map of the nullability introduced by
82 * that conversion. Consumers can pass provider output through
83 * `undoNullWidening` before validating it against the original schema.
84 */
85export function makeStructuredOutputCompatibleWithMap(
86 schema: Record<string, any>,
87 originalRequired?: Array<string>,
88): StructuredOutputCompatibility {
89 const { schema: strictSchema, nullWideningMap } = coerceStrictSchema(
90 schema,
91 originalRequired,
92 )
93 return {
94 schema: stripUnsupportedFormats(strictSchema),
95 nullWideningMap,
96 }
97}
98
99/**
100 * JSON-Schema keywords outside OpenAI's strict Structured Outputs subset. A
101 * schema using any of these can't be coerced into a strict-valid shape, and
102 * sending it with `strict: true` makes the API reject the ENTIRE request
103 * (e.g. `400 Invalid schema ... 'additionalProperties' is required to be ...`).
104 * Tools with such schemas are emitted with `strict: false` instead (see the
105 * tool converters) so they remain callable. MCP servers (e.g. Notion) routinely
106 * emit these.
107 *
108 * - `oneOf` / `allOf` / `not` — combinator keywords strict mode rejects
109 * - `prefixItems` — 2020-12 tuple keyword. openai-node's strict transform
110 * rejects it, so we send those tools with `strict: false` instead
111 * - `$ref` / `$defs` / `definitions` — references and definition pools whose
112 * object subschemas escape the `additionalProperties: false` normalization
113 * strict mode requires
114 */
115const STRICT_UNSUPPORTED_KEYWORDS: ReadonlyArray<string> = [
116 'oneOf',
117 'allOf',
118 'not',
119 'prefixItems',
120 '$ref',
121 '$defs',
122 'definitions',
123]
124
125/**
126 * Keys that give a schema node a resolvable type under OpenAI's strict subset.
127 * A schema-position node carrying none of these is *typeless* (e.g. the empty
128 * `{}` that `z.any()` / `z.unknown()` emit). Strict mode requires every schema
129 * to declare a type, so a typeless node 400s the whole request — such tools
130 * must be sent with `strict: false` instead. (`oneOf`/`allOf`/`$ref` count as
131 * type indicators here even though they're independently strict-unsupported;
132 * the keyword check below already rejects them.)
133 */
134const TYPE_INDICATOR_KEYWORDS: ReadonlyArray<string> = [
135 'type',
136 'enum',
137 'const',
138 'anyOf',
139 'oneOf',
140 'allOf',
141 '$ref',
142]
143
144/**
145 * Returns `false` when `schema` cannot be made strict-compatible and must be
146 * sent with `strict: false`. Two ways that happens:
147 *
148 * 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in
149 * the tree (`oneOf`/`allOf`/`not`/`prefixItems`/`$ref`/`$defs`).
150 * 2. It contains a *typeless* schema node — a property/items/anyOf entry with
151 * no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`
152 * produces. Strict mode rejects typeless schemas.
153 * 3. It contains an open object schema. OpenAI strict mode requires objects to
154 * set `additionalProperties: false`, which would change the semantics of a
155 * free-form map rather than merely normalizing it.
156 * 4. An `anyOf` variant itself needs null widening. The inverse map is
157 * intentionally schema-blind, so it cannot select a variant without risking
158 * removal of a genuine nullable value accepted by another variant.
159 *
160 * Conservative by design: for (1) keywords are matched as object keys, so a
161 * property literally named e.g. `oneOf` also trips it. That only costs that one
162 * tool its strict mode, which is strictly safer than a false "compatible"
163 * verdict that 400s the whole request.
164 */
165export function isStrictModeCompatible(schema: unknown): boolean {
166 return strictModeFallbackReason(schema) === undefined
167}
168
169/**
170 * Why `schema` must be sent with `strict: false`, or `undefined` when it can be
171 * strict. Runs the same checks as `isStrictModeCompatible`, in the same order.
172 */
173export function strictModeFallbackReason(schema: unknown): string | undefined {
174 const keyword = findStrictUnsupportedKeyword(schema)
175 if (keyword !== undefined) {
176 return `schema uses ${keyword}, which strict mode does not support`
177 }
178 if (containsTypelessSchema(schema)) {
179 return 'schema has a node with no type (for example z.any() or z.unknown())'
180 }
181 if (containsOpenObject(schema)) {
182 return 'schema has an open object (for example z.record())'
183 }
184 if (containsUntrackableAnyOfWidening(schema)) {
185 return 'schema has an optional field inside an anyOf variant'
186 }
187 return undefined
188}
189
190/** Options that every `openai-base` text adapter accepts in its config. */
191export interface OpenAIBaseTextAdapterOptions {
192 /**
193 * In development, warn once per tool that is sent with `strict: false`
194 * because its schema cannot be strict. Set to `false` to turn the warning
195 * off. It never runs when `NODE_ENV` is `production`. Default: `true`.
196 */
197 strictFallbackWarning?: boolean
198}
199
200// ponytail: keyed on the Tool object, so a tool defined once warns once per
201// process. Tools rebuilt per request (e.g. from MCP) warn once per request.
202const warnedStrictFallback = new WeakSet<Tool>()
203
204/**
205 * Warn once per tool that is sent with `strict: false` because its schema
206 * cannot be strict. The tool still works, but the model is not held to the
207 * schema, so the developer must know (#1213).
208 */
209export function warnStrictFallback(
210 tools: Array<Tool> | undefined,
211 logger: InternalLogger,
212): void {
213 // Development only. `process` is absent on some runtimes (e.g. Workers).
214 if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production')
215 return
216 for (const tool of tools ?? []) {
217 if (!tool.inputSchema || warnedStrictFallback.has(tool)) continue
218 const reason = strictModeFallbackReason(tool.inputSchema)
219 if (reason === undefined) continue
220 warnedStrictFallback.add(tool)
221 logger.warn(`tool "${tool.name}" sent with strict: false: ${reason}`, {
222 tool: tool.name,
223 })
224 }
225}
226
227/**
228 * Reports strict conversions whose synthesized nulls cannot be represented by
229 * the schema-blind inverse map. Optional `anyOf` wrappers remain supported:
230 * only widening introduced inside one of their variants triggers fallback.
231 */
232function containsUntrackableAnyOfWidening(schema: unknown): boolean {
233 if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {
234 return false
235 }
236 return coerceStrictSchema(schema as Record<string, any>)
237 .hasUntrackableAnyOfWidening
238}
239
240/**
241 * Reports object schemas that cannot be closed without changing their input
242 * semantics. Objects with `properties` and no explicit
243 * `additionalProperties` are safe because `coerceStrictSchema` closes them.
244 */
245function containsOpenObject(node: unknown): boolean {
246 if (Array.isArray(node)) {
247 return node.some(containsOpenObject)
248 }
249 if (node === null || typeof node !== 'object') return false
250
251 const schema = node as Record<string, unknown>
252 const type = schema['type']
253 const isObjectSchema =
254 type === 'object' || (Array.isArray(type) && type.includes('object'))
255
256 if (isObjectSchema) {
257 if (
258 'additionalProperties' in schema &&
259 schema['additionalProperties'] !== false
260 ) {
261 return true
262 }
263
264 const properties = schema['properties']
265 const hasProperties =
266 properties !== null &&
267 typeof properties === 'object' &&
268 !Array.isArray(properties)
269 if (!hasProperties && schema['additionalProperties'] !== false) {
270 return true
271 }
272 }
273
274 return Object.values(schema).some(containsOpenObject)
275}
276
277function findStrictUnsupportedKeyword(node: unknown): string | undefined {
278 if (Array.isArray(node)) {
279 for (const item of node) {
280 const found = findStrictUnsupportedKeyword(item)
281 if (found !== undefined) return found
282 }
283 return undefined
284 }
285 if (node === null || typeof node !== 'object') return undefined
286 for (const [key, value] of Object.entries(node)) {
287 if (STRICT_UNSUPPORTED_KEYWORDS.includes(key)) return key
288 const found = findStrictUnsupportedKeyword(value)
289 if (found !== undefined) return found
290 }
291 return undefined
292}
293
294/** A schema-position node that declares no type and so 400s strict mode. */
295function isTypelessSchema(node: unknown): boolean {
296 if (node === null || typeof node !== 'object' || Array.isArray(node)) {
297 // JSON Schema permits bare boolean nodes; malformed inputs may contain
298 // other primitives. OpenAI's strict subset requires a declared type, so
299 // preserve the containing tool by sending it in non-strict mode.
300 return true
301 }
302 return !TYPE_INDICATOR_KEYWORDS.some((key) => key in node)
303}
304
305/**
306 * Walks the genuine schema positions (property values, `items`, `anyOf`
307 * variants) and reports whether any is typeless. Unlike the keyword walk this
308 * must respect structure: an empty `{}` is only a problem at a schema position,
309 * not e.g. an empty `properties` map.
310 */
311function containsTypelessSchema(node: unknown): boolean {
312 if (node === null || typeof node !== 'object' || Array.isArray(node)) {
313 return false
314 }
315 const schema = node as Record<string, any>
316
317 const children: Array<unknown> = []
318 if (schema.properties && typeof schema.properties === 'object') {
319 children.push(...Object.values(schema.properties))
320 }
321 if (schema.items !== undefined) {
322 children.push(
323 ...(Array.isArray(schema.items) ? schema.items : [schema.items]),
324 )
325 }
326 if (Array.isArray(schema.anyOf)) {
327 children.push(...schema.anyOf)
328 }
329
330 return children.some(
331 (child) => isTypelessSchema(child) || containsTypelessSchema(child),
332 )
333}
334
335/**
336 * Strict-mode structural rewrite (required widening, nullability,
337 * additionalProperties). Kept private so the public entry point can apply the
338 * format-stripping pass exactly once over the fully-rewritten tree.
339 */
340function pruneMap(map: NullWideningMap): NullWideningMap | undefined {
341 return Object.keys(map).length > 0 ? map : undefined
342}
343
344function isSchemaObject(schema: unknown): schema is Record<string, any> {
345 return typeof schema === 'object' && schema !== null && !Array.isArray(schema)
346}
347
348/** Whether every active JSON Schema constraint at this node admits null. */
349function acceptsNull(schema: unknown): boolean {
350 if (schema === true) return true
351 if (!isSchemaObject(schema)) return false
352
353 if ('const' in schema && schema.const !== null) return false
354 if (Array.isArray(schema.enum) && !schema.enum.includes(null)) return false
355
356 if (typeof schema.type === 'string' && schema.type !== 'null') return false
357 if (Array.isArray(schema.type) && !schema.type.includes('null')) return false
358
359 if (
360 Array.isArray(schema.anyOf) &&
361 !schema.anyOf.some((variant: unknown) => acceptsNull(variant))
362 ) {
363 return false
364 }
365
366 return true
367}
368
369function coerceStrictSchema(
370 schema: Record<string, any>,
371 originalRequired?: Array<string>,
372): CoercedStrictSchema {
373 const result = { ...schema }
374 const nullWideningMap: NullWideningMap = {}
375 let hasUntrackableAnyOfWidening = false
376 const required =
377 originalRequired ??
378 (Array.isArray(result['required']) ? result['required'] : [])
379
380 if (result.type === 'object' && result.properties) {
381 const properties = { ...result.properties }
382 const allPropertyNames = Object.keys(properties)
383 // Entries, not assignment: `map['__proto__'] = x` sets the prototype
384 // and drops a property that is really named `__proto__`.
385 const propertyMaps: Array<[string, NullWideningMap]> = []
386
387 for (const propName of allPropertyNames) {
388 let prop = properties[propName]
389 const wasOptional = !required.includes(propName)
390 let childMap: NullWideningMap | undefined
391 let widenedHere = false
392
393 // Step 1: Recurse into nested structures
394 if (isSchemaObject(prop) && prop.type === 'object' && prop.properties) {
395 const nested = coerceStrictSchema(prop, prop.required || [])
396 prop = nested.schema
397 childMap = nested.nullWideningMap
398 hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
399 } else if (isSchemaObject(prop) && prop.type === 'array') {
400 const nested = coerceStrictSchema(prop, [])
401 prop = nested.schema
402 childMap = nested.nullWideningMap
403 hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
404 } else if (isSchemaObject(prop) && prop.anyOf) {
405 const nested = coerceStrictSchema(prop, prop.required || [])
406 prop = nested.schema
407 childMap = nested.nullWideningMap
408 hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
409 } else if (isSchemaObject(prop) && prop.oneOf) {
410 throw new Error(
411 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',
412 )
413 }
414
415 // Step 2: Apply null-widening for optional properties (after recursion)
416 if (wasOptional) {
417 const originallyAcceptedNull = acceptsNull(prop)
418
419 // `type: [..., 'null']` alone does not make null valid when an enum or
420 // const still excludes it; strict decoding would be forced to emit the
421 // original literal instead of the synthetic omission marker.
422 if (isSchemaObject(prop) && 'const' in prop && prop.const !== null) {
423 const { const: constValue, ...withoutConst } = prop
424 prop = { ...withoutConst, enum: [constValue, null] }
425 } else if (
426 isSchemaObject(prop) &&
427 Array.isArray(prop.enum) &&
428 !prop.enum.includes(null)
429 ) {
430 prop = { ...prop, enum: [...prop.enum, null] }
431 }
432
433 if (isSchemaObject(prop) && prop.anyOf) {
434 // A genuine null branch can use type, enum, or const. Only add a
435 // provider omission marker when the original union rejected null.
436 if (!acceptsNull(prop)) {
437 prop = { ...prop, anyOf: [...prop.anyOf, { type: 'null' }] }
438 }
439 } else if (
440 isSchemaObject(prop) &&
441 prop.type &&
442 !Array.isArray(prop.type)
443 ) {
444 prop = { ...prop, type: [prop.type, 'null'] }
445 } else if (
446 isSchemaObject(prop) &&
447 Array.isArray(prop.type) &&
448 !prop.type.includes('null')
449 ) {
450 prop = { ...prop, type: [...prop.type, 'null'] }
451 }
452
453 widenedHere = !originallyAcceptedNull && acceptsNull(prop)
454 }
455
456 properties[propName] = prop
457 if (childMap || widenedHere) {
458 propertyMaps.push([
459 propName,
460 {
461 ...(childMap ?? {}),
462 ...(widenedHere ? { widened: true } : {}),
463 },
464 ])
465 }
466 }
467
468 result.properties = properties
469 result.required = allPropertyNames
470 result.additionalProperties = false
471 if (propertyMaps.length > 0) {
472 nullWideningMap.properties = Object.fromEntries(propertyMaps)
473 }
474 }
475
476 if (result.type === 'array' && result.items) {
477 if (Array.isArray(result.items)) {
478 const itemMaps: Array<NullWideningMap> = []
479 result.items = result.items.map((item) => {
480 if (!isSchemaObject(item)) {
481 itemMaps.push({})
482 return item
483 }
484 const nested = coerceStrictSchema(item, item.required || [])
485 itemMaps.push(nested.nullWideningMap ?? {})
486 hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
487 return nested.schema
488 })
489 if (itemMaps.some((map) => Object.keys(map).length > 0)) {
490 nullWideningMap.items = itemMaps
491 }
492 } else {
493 const nested = coerceStrictSchema(
494 result.items,
495 result.items.required || [],
496 )
497 result.items = nested.schema
498 if (nested.nullWideningMap) {
499 nullWideningMap.items = nested.nullWideningMap
500 }
501 hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening
502 }
503 }
504
505 if (result.anyOf && Array.isArray(result.anyOf)) {
506 const variants = result.anyOf.map((variant) =>
507 coerceStrictSchema(variant, variant.required || []),
508 )
509 result.anyOf = variants.map((variant) => variant.schema)
510 hasUntrackableAnyOfWidening ||= variants.some(
511 (variant) =>
512 variant.nullWideningMap !== undefined ||
513 variant.hasUntrackableAnyOfWidening,
514 )
515 }
516
517 if (result.oneOf) {
518 throw new Error(
519 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',
520 )
521 }
522
523 return {
524 schema: result,
525 nullWideningMap: pruneMap(nullWideningMap),
526 hasUntrackableAnyOfWidening,
527 }
528}