const ONE_OF_ERROR = 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types' function isSchemaObject(schema: unknown): schema is Record { return typeof schema === 'object' && schema !== null && !Array.isArray(schema) } /** Target of a `$ref` to the root or to a root definition pool entry. */ function resolveRef(ref: string, root: Record): unknown { if (ref === '#') return root const match = /^#\/(\$defs|definitions)\/([^/]+)$/.exec(ref) if (!match) return undefined const pool = match[1] ?? '' const name = (match[2] ?? '').replace(/~1/g, '/').replace(/~0/g, '~') const defs = root[pool] if (!isSchemaObject(defs)) return undefined return defs[name] } /** Whether every active JSON Schema constraint at this node admits null. */ function acceptsNull( schema: unknown, root: Record, seen: ReadonlySet = new Set(), ): boolean { if (schema === true) return true if (!isSchemaObject(schema)) return false if ('const' in schema && schema.const !== null) return false if (Array.isArray(schema.enum) && !schema.enum.includes(null)) return false if (typeof schema.type === 'string' && schema.type !== 'null') return false if (Array.isArray(schema.type) && !schema.type.includes('null')) return false if ( Array.isArray(schema.anyOf) && !schema.anyOf.some((variant: unknown) => acceptsNull(variant, root, seen)) ) { return false } // An unresolvable or circular `$ref` is assumed to admit null. if (typeof schema.$ref === 'string') { const target = resolveRef(schema.$ref, root) if (target !== undefined && !seen.has(target)) { return acceptsNull(target, root, new Set(seen).add(target)) } } return true } /** * zod 4 writes a recursive reference as `allOf: [{ $ref }]`. Strict mode has * no `allOf`, so use the bare `$ref`. */ function unwrapSingleRefAllOf( schema: Record, ): Record { if ( !Array.isArray(schema.allOf) || schema.allOf.length !== 1 || !isSchemaObject(schema.allOf[0]) || typeof schema.allOf[0].$ref !== 'string' ) { return schema } const { allOf, ...rest } = schema return { ...rest, ...allOf[0] } } function coerceStrictSchema( schema: Record, originalRequired: Array | undefined, root: Record, ): Record { const result = { ...unwrapSingleRefAllOf(schema) } const required = originalRequired ?? (Array.isArray(result['required']) ? result['required'] : []) if (result.type === 'object' && result.properties) { const properties = { ...result.properties } const allPropertyNames = Object.keys(properties) for (const propName of allPropertyNames) { let prop = properties[propName] if (isSchemaObject(prop)) prop = unwrapSingleRefAllOf(prop) const wasOptional = !required.includes(propName) // Step 1: Recurse into nested structures if (prop.type === 'object' && prop.properties) { prop = coerceStrictSchema(prop, prop.required || [], root) } else if (prop.type === 'array' && prop.items) { prop = { ...prop, items: coerceStrictSchema( prop.items, prop.items.required || [], root, ), } } else if (prop.anyOf) { prop = coerceStrictSchema(prop, prop.required || [], root) } else if (prop.oneOf) { throw new Error(ONE_OF_ERROR) } // Step 2: Apply null-widening for optional properties (after recursion) if (wasOptional) { if (prop.anyOf) { // For anyOf, add a null variant if not already present if (!prop.anyOf.some((v: any) => v.type === 'null')) { prop = { ...prop, anyOf: [...prop.anyOf, { type: 'null' }] } } } else if (isSchemaObject(prop) && typeof prop.$ref === 'string') { // A required bare `$ref` back to an enclosing object can never // terminate, so give the omitted case an explicit null branch. if (!acceptsNull(prop, root)) { prop = { anyOf: [prop, { type: 'null' }] } } } else if (prop.type && !Array.isArray(prop.type)) { prop = { ...prop, type: [prop.type, 'null'] } } else if (Array.isArray(prop.type) && !prop.type.includes('null')) { prop = { ...prop, type: [...prop.type, 'null'] } } } properties[propName] = prop } result.properties = properties result.required = allPropertyNames result.additionalProperties = false } if (result.type === 'array' && result.items) { result.items = coerceStrictSchema( result.items, result.items.required || [], root, ) } if (result.anyOf && Array.isArray(result.anyOf)) { result.anyOf = result.anyOf.map((variant) => coerceStrictSchema(variant, variant.required || [], root), ) } if (result.oneOf) { throw new Error(ONE_OF_ERROR) } // Definition pools are reached through `$ref`, so they need the same strict // conversion as the inline schemas. The input pool is not mutated. for (const defsKey of ['$defs', 'definitions']) { const defs = result[defsKey] if (!isSchemaObject(defs)) continue result[defsKey] = Object.fromEntries( Object.entries(defs).map(([name, def]) => { if (!isSchemaObject(def)) return [name, def] return [name, coerceStrictSchema(def, def.required || [], root)] }), ) } return result } /** * Transform a JSON schema to be compatible with OpenAI-style structured output requirements. * The base requirements (which OpenRouter inherits because it routes to upstream OpenAI-compatible * structured-output backends) are: * - All properties must be in the `required` array * - Optional fields should have null added to their type union * - additionalProperties must be false for objects * - Object schemas in `$defs` / `definitions` get the same conversion. An optional * `$ref` gains a null alternative so a recursive schema can end. * * @param schema - JSON schema to transform * @param originalRequired - Original required array (to know which fields were optional) * @returns Transformed schema compatible with strict structured output */ export function makeStructuredOutputCompatible( schema: Record, originalRequired?: Array, ): Record { return coerceStrictSchema(schema, originalRequired, schema) }