@tanstack/openai-base 0.10.1 → 0.10.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/esm/adapters/chat-completions-text.d.ts +15 -7
- package/dist/esm/adapters/chat-completions-text.js +23 -7
- package/dist/esm/adapters/chat-completions-text.js.map +1 -1
- package/dist/esm/adapters/chat-completions-tool-converter.test.d.ts +1 -0
- package/dist/esm/adapters/responses-text.d.ts +15 -7
- package/dist/esm/adapters/responses-text.js +141 -105
- package/dist/esm/adapters/responses-text.js.map +1 -1
- package/dist/esm/adapters/responses-tool-converter.test.d.ts +1 -0
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +2 -2
- package/dist/esm/tools/function-tool.test.d.ts +1 -0
- package/dist/esm/utils/schema-converter.d.ts +14 -0
- package/dist/esm/utils/schema-converter.js +106 -18
- package/dist/esm/utils/schema-converter.js.map +1 -1
- package/dist/esm/utils/tool-input-normalizer.d.ts +12 -0
- package/dist/esm/utils/tool-input-normalizer.js +36 -0
- package/dist/esm/utils/tool-input-normalizer.js.map +1 -0
- package/dist/esm/utils/tool-input-normalizer.test.d.ts +1 -0
- package/package.json +3 -3
- package/src/adapters/chat-completions-text.ts +51 -18
- package/src/adapters/chat-completions-tool-converter.test.ts +64 -0
- package/src/adapters/responses-text.ts +198 -130
- package/src/adapters/responses-tool-converter.test.ts +69 -0
- package/src/index.ts +4 -1
- package/src/tools/function-tool.test.ts +62 -0
- package/src/utils/schema-converter.ts +165 -20
- package/src/utils/tool-input-normalizer.test.ts +146 -0
- package/src/utils/tool-input-normalizer.ts +55 -0
|
@@ -50,7 +50,19 @@ function stripUnsupportedFormats(node) {
|
|
|
50
50
|
* @returns Transformed schema compatible with OpenAI structured output
|
|
51
51
|
*/
|
|
52
52
|
function makeStructuredOutputCompatible(schema, originalRequired) {
|
|
53
|
-
return
|
|
53
|
+
return makeStructuredOutputCompatibleWithMap(schema, originalRequired).schema;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Strict-schema conversion plus an exact map of the nullability introduced by
|
|
57
|
+
* that conversion. Consumers can pass provider output through
|
|
58
|
+
* `undoNullWidening` before validating it against the original schema.
|
|
59
|
+
*/
|
|
60
|
+
function makeStructuredOutputCompatibleWithMap(schema, originalRequired) {
|
|
61
|
+
const { schema: strictSchema, nullWideningMap } = coerceStrictSchema(schema, originalRequired);
|
|
62
|
+
return {
|
|
63
|
+
schema: stripUnsupportedFormats(strictSchema),
|
|
64
|
+
nullWideningMap
|
|
65
|
+
};
|
|
54
66
|
}
|
|
55
67
|
/**
|
|
56
68
|
* JSON-Schema keywords outside OpenAI's strict Structured Outputs subset. A
|
|
@@ -104,6 +116,9 @@ var TYPE_INDICATOR_KEYWORDS = [
|
|
|
104
116
|
* 3. It contains an open object schema. OpenAI strict mode requires objects to
|
|
105
117
|
* set `additionalProperties: false`, which would change the semantics of a
|
|
106
118
|
* free-form map rather than merely normalizing it.
|
|
119
|
+
* 4. An `anyOf` variant itself needs null widening. The inverse map is
|
|
120
|
+
* intentionally schema-blind, so it cannot select a variant without risking
|
|
121
|
+
* removal of a genuine nullable value accepted by another variant.
|
|
107
122
|
*
|
|
108
123
|
* Conservative by design: for (1) keywords are matched as object keys, so a
|
|
109
124
|
* property literally named e.g. `oneOf` also trips it. That only costs that one
|
|
@@ -111,7 +126,16 @@ var TYPE_INDICATOR_KEYWORDS = [
|
|
|
111
126
|
* verdict that 400s the whole request.
|
|
112
127
|
*/
|
|
113
128
|
function isStrictModeCompatible(schema) {
|
|
114
|
-
return !containsStrictUnsupportedKeyword(schema) && !containsTypelessSchema(schema) && !containsOpenObject(schema);
|
|
129
|
+
return !containsStrictUnsupportedKeyword(schema) && !containsTypelessSchema(schema) && !containsOpenObject(schema) && !containsUntrackableAnyOfWidening(schema);
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Reports strict conversions whose synthesized nulls cannot be represented by
|
|
133
|
+
* the schema-blind inverse map. Optional `anyOf` wrappers remain supported:
|
|
134
|
+
* only widening introduced inside one of their variants triggers fallback.
|
|
135
|
+
*/
|
|
136
|
+
function containsUntrackableAnyOfWidening(schema) {
|
|
137
|
+
if (schema === null || typeof schema !== "object" || Array.isArray(schema)) return false;
|
|
138
|
+
return coerceStrictSchema(schema).hasUntrackableAnyOfWidening;
|
|
115
139
|
}
|
|
116
140
|
/**
|
|
117
141
|
* Reports object schemas that cannot be closed without changing their input
|
|
@@ -141,7 +165,7 @@ function containsStrictUnsupportedKeyword(node) {
|
|
|
141
165
|
}
|
|
142
166
|
/** A schema-position node that declares no type and so 400s strict mode. */
|
|
143
167
|
function isTypelessSchema(node) {
|
|
144
|
-
if (node === null || typeof node !== "object" || Array.isArray(node)) return
|
|
168
|
+
if (node === null || typeof node !== "object" || Array.isArray(node)) return true;
|
|
145
169
|
return !TYPE_INDICATOR_KEYWORDS.some((key) => key in node);
|
|
146
170
|
}
|
|
147
171
|
/**
|
|
@@ -164,49 +188,113 @@ function containsTypelessSchema(node) {
|
|
|
164
188
|
* additionalProperties). Kept private so the public entry point can apply the
|
|
165
189
|
* format-stripping pass exactly once over the fully-rewritten tree.
|
|
166
190
|
*/
|
|
191
|
+
function pruneMap(map) {
|
|
192
|
+
return Object.keys(map).length > 0 ? map : void 0;
|
|
193
|
+
}
|
|
194
|
+
function isSchemaObject(schema) {
|
|
195
|
+
return typeof schema === "object" && schema !== null && !Array.isArray(schema);
|
|
196
|
+
}
|
|
197
|
+
/** Whether every active JSON Schema constraint at this node admits null. */
|
|
198
|
+
function acceptsNull(schema) {
|
|
199
|
+
if (schema === true) return true;
|
|
200
|
+
if (!isSchemaObject(schema)) return false;
|
|
201
|
+
if ("const" in schema && schema.const !== null) return false;
|
|
202
|
+
if (Array.isArray(schema.enum) && !schema.enum.includes(null)) return false;
|
|
203
|
+
if (typeof schema.type === "string" && schema.type !== "null") return false;
|
|
204
|
+
if (Array.isArray(schema.type) && !schema.type.includes("null")) return false;
|
|
205
|
+
if (Array.isArray(schema.anyOf) && !schema.anyOf.some((variant) => acceptsNull(variant))) return false;
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
167
208
|
function coerceStrictSchema(schema, originalRequired) {
|
|
168
209
|
const result = { ...schema };
|
|
210
|
+
const nullWideningMap = {};
|
|
211
|
+
let hasUntrackableAnyOfWidening = false;
|
|
169
212
|
const required = originalRequired ?? (Array.isArray(result["required"]) ? result["required"] : []);
|
|
170
213
|
if (result.type === "object" && result.properties) {
|
|
171
214
|
const properties = { ...result.properties };
|
|
172
215
|
const allPropertyNames = Object.keys(properties);
|
|
216
|
+
const propertyMaps = {};
|
|
173
217
|
for (const propName of allPropertyNames) {
|
|
174
218
|
let prop = properties[propName];
|
|
175
219
|
const wasOptional = !required.includes(propName);
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
220
|
+
let childMap;
|
|
221
|
+
let widenedHere = false;
|
|
222
|
+
if (isSchemaObject(prop) && prop.type === "object" && prop.properties) {
|
|
223
|
+
const nested = coerceStrictSchema(prop, prop.required || []);
|
|
224
|
+
prop = nested.schema;
|
|
225
|
+
childMap = nested.nullWideningMap;
|
|
226
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
227
|
+
} else if (isSchemaObject(prop) && prop.type === "array" && prop.items) {
|
|
228
|
+
const nested = coerceStrictSchema(prop.items, prop.items.required || []);
|
|
229
|
+
prop = {
|
|
230
|
+
...prop,
|
|
231
|
+
items: nested.schema
|
|
232
|
+
};
|
|
233
|
+
childMap = nested.nullWideningMap ? { items: nested.nullWideningMap } : void 0;
|
|
234
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
235
|
+
} else if (isSchemaObject(prop) && prop.anyOf) {
|
|
236
|
+
const nested = coerceStrictSchema(prop, prop.required || []);
|
|
237
|
+
prop = nested.schema;
|
|
238
|
+
childMap = nested.nullWideningMap;
|
|
239
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
240
|
+
} else if (isSchemaObject(prop) && prop.oneOf) throw new 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");
|
|
183
241
|
if (wasOptional) {
|
|
184
|
-
|
|
185
|
-
|
|
242
|
+
const originallyAcceptedNull = acceptsNull(prop);
|
|
243
|
+
if (isSchemaObject(prop) && "const" in prop && prop.const !== null) {
|
|
244
|
+
const { const: constValue, ...withoutConst } = prop;
|
|
245
|
+
prop = {
|
|
246
|
+
...withoutConst,
|
|
247
|
+
enum: [constValue, null]
|
|
248
|
+
};
|
|
249
|
+
} else if (isSchemaObject(prop) && Array.isArray(prop.enum) && !prop.enum.includes(null)) prop = {
|
|
250
|
+
...prop,
|
|
251
|
+
enum: [...prop.enum, null]
|
|
252
|
+
};
|
|
253
|
+
if (isSchemaObject(prop) && prop.anyOf) {
|
|
254
|
+
if (!acceptsNull(prop)) prop = {
|
|
186
255
|
...prop,
|
|
187
256
|
anyOf: [...prop.anyOf, { type: "null" }]
|
|
188
257
|
};
|
|
189
|
-
} else if (prop.type && !Array.isArray(prop.type)) prop = {
|
|
258
|
+
} else if (isSchemaObject(prop) && prop.type && !Array.isArray(prop.type)) prop = {
|
|
190
259
|
...prop,
|
|
191
260
|
type: [prop.type, "null"]
|
|
192
261
|
};
|
|
193
|
-
else if (Array.isArray(prop.type) && !prop.type.includes("null")) prop = {
|
|
262
|
+
else if (isSchemaObject(prop) && Array.isArray(prop.type) && !prop.type.includes("null")) prop = {
|
|
194
263
|
...prop,
|
|
195
264
|
type: [...prop.type, "null"]
|
|
196
265
|
};
|
|
266
|
+
widenedHere = !originallyAcceptedNull && acceptsNull(prop);
|
|
197
267
|
}
|
|
198
268
|
properties[propName] = prop;
|
|
269
|
+
if (childMap || widenedHere) propertyMaps[propName] = {
|
|
270
|
+
...childMap ?? {},
|
|
271
|
+
...widenedHere ? { widened: true } : {}
|
|
272
|
+
};
|
|
199
273
|
}
|
|
200
274
|
result.properties = properties;
|
|
201
275
|
result.required = allPropertyNames;
|
|
202
276
|
result.additionalProperties = false;
|
|
277
|
+
if (Object.keys(propertyMaps).length > 0) nullWideningMap.properties = propertyMaps;
|
|
278
|
+
}
|
|
279
|
+
if (result.type === "array" && result.items) {
|
|
280
|
+
const nested = coerceStrictSchema(result.items, result.items.required || []);
|
|
281
|
+
result.items = nested.schema;
|
|
282
|
+
if (nested.nullWideningMap) nullWideningMap.items = nested.nullWideningMap;
|
|
283
|
+
hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening;
|
|
284
|
+
}
|
|
285
|
+
if (result.anyOf && Array.isArray(result.anyOf)) {
|
|
286
|
+
const variants = result.anyOf.map((variant) => coerceStrictSchema(variant, variant.required || []));
|
|
287
|
+
result.anyOf = variants.map((variant) => variant.schema);
|
|
288
|
+
hasUntrackableAnyOfWidening ||= variants.some((variant) => variant.nullWideningMap !== void 0 || variant.hasUntrackableAnyOfWidening);
|
|
203
289
|
}
|
|
204
|
-
if (result.type === "array" && result.items) result.items = coerceStrictSchema(result.items, result.items.required || []);
|
|
205
|
-
if (result.anyOf && Array.isArray(result.anyOf)) result.anyOf = result.anyOf.map((variant) => coerceStrictSchema(variant, variant.required || []));
|
|
206
290
|
if (result.oneOf) throw new 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");
|
|
207
|
-
return
|
|
291
|
+
return {
|
|
292
|
+
schema: result,
|
|
293
|
+
nullWideningMap: pruneMap(nullWideningMap),
|
|
294
|
+
hasUntrackableAnyOfWidening
|
|
295
|
+
};
|
|
208
296
|
}
|
|
209
297
|
//#endregion
|
|
210
|
-
export { isStrictModeCompatible, makeStructuredOutputCompatible, stripUnsupportedFormats };
|
|
298
|
+
export { isStrictModeCompatible, makeStructuredOutputCompatible, makeStructuredOutputCompatibleWithMap, stripUnsupportedFormats };
|
|
211
299
|
|
|
212
300
|
//# sourceMappingURL=schema-converter.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-converter.js","names":[],"sources":["../../../src/utils/schema-converter.ts"],"sourcesContent":["/**\n * String `format` values accepted by OpenAI's strict Structured Outputs subset.\n * Any other format (e.g. \"uri\", \"uri-reference\", \"regex\") causes the API to\n * reject the whole request with `400 ... '<format>' is not a valid format`.\n * MCP servers and hand-written tools routinely declare such formats, so we strip\n * the unsupported ones before sending. See:\n * https://platform.openai.com/docs/guides/structured-outputs#supported-properties\n */\nconst SUPPORTED_STRING_FORMATS = new Set([\n 'date-time',\n 'time',\n 'date',\n 'duration',\n 'email',\n 'hostname',\n 'ipv4',\n 'ipv6',\n 'uuid',\n])\n\n/**\n * Recursively drop JSON-Schema `format` keywords whose value isn't in OpenAI's\n * strict-mode allowlist. Pure — returns a fresh tree and never mutates `node`,\n * so the caller's original tool definition is left intact.\n *\n * A property *named* `format` always has a schema (object/boolean) value, never\n * a bare string, so it is preserved and recursed into; only the `format`\n * *keyword* (whose value is a string) is subject to removal.\n */\nexport function stripUnsupportedFormats(node: any): any {\n if (Array.isArray(node)) return node.map(stripUnsupportedFormats)\n if (node === null || typeof node !== 'object') return node\n\n const out: Record<string, any> = {}\n for (const [key, value] of Object.entries(node)) {\n if (\n key === 'format' &&\n typeof value === 'string' &&\n !SUPPORTED_STRING_FORMATS.has(value)\n ) {\n continue\n }\n out[key] = stripUnsupportedFormats(value)\n }\n return out\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n * - String `format` keywords must be from a fixed allowlist (others are stripped)\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nexport function makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): Record<string, any> {\n return stripUnsupportedFormats(coerceStrictSchema(schema, originalRequired))\n}\n\n/**\n * JSON-Schema keywords outside OpenAI's strict Structured Outputs subset. A\n * schema using any of these can't be coerced into a strict-valid shape, and\n * sending it with `strict: true` makes the API reject the ENTIRE request\n * (e.g. `400 Invalid schema ... 'additionalProperties' is required to be ...`).\n * Tools with such schemas are emitted with `strict: false` instead (see the\n * tool converters) so they remain callable. MCP servers (e.g. Notion) routinely\n * emit these.\n *\n * - `oneOf` / `allOf` / `not` — combinator keywords strict mode rejects\n * - `$ref` / `$defs` / `definitions` — references and definition pools whose\n * object subschemas escape the `additionalProperties: false` normalization\n * strict mode requires\n */\nconst STRICT_UNSUPPORTED_KEYWORDS: ReadonlyArray<string> = [\n 'oneOf',\n 'allOf',\n 'not',\n '$ref',\n '$defs',\n 'definitions',\n]\n\n/**\n * Keys that give a schema node a resolvable type under OpenAI's strict subset.\n * A schema-position node carrying none of these is *typeless* (e.g. the empty\n * `{}` that `z.any()` / `z.unknown()` emit). Strict mode requires every schema\n * to declare a type, so a typeless node 400s the whole request — such tools\n * must be sent with `strict: false` instead. (`oneOf`/`allOf`/`$ref` count as\n * type indicators here even though they're independently strict-unsupported;\n * the keyword check below already rejects them.)\n */\nconst TYPE_INDICATOR_KEYWORDS: ReadonlyArray<string> = [\n 'type',\n 'enum',\n 'const',\n 'anyOf',\n 'oneOf',\n 'allOf',\n '$ref',\n]\n\n/**\n * Returns `false` when `schema` cannot be made strict-compatible and must be\n * sent with `strict: false`. Two ways that happens:\n *\n * 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in\n * the tree (`oneOf`/`allOf`/`not`/`$ref`/`$defs`).\n * 2. It contains a *typeless* schema node — a property/items/anyOf entry with\n * no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`\n * produces. Strict mode rejects typeless schemas.\n * 3. It contains an open object schema. OpenAI strict mode requires objects to\n * set `additionalProperties: false`, which would change the semantics of a\n * free-form map rather than merely normalizing it.\n *\n * Conservative by design: for (1) keywords are matched as object keys, so a\n * property literally named e.g. `oneOf` also trips it. That only costs that one\n * tool its strict mode, which is strictly safer than a false \"compatible\"\n * verdict that 400s the whole request.\n */\nexport function isStrictModeCompatible(schema: unknown): boolean {\n return (\n !containsStrictUnsupportedKeyword(schema) &&\n !containsTypelessSchema(schema) &&\n !containsOpenObject(schema)\n )\n}\n\n/**\n * Reports object schemas that cannot be closed without changing their input\n * semantics. Objects with `properties` and no explicit\n * `additionalProperties` are safe because `coerceStrictSchema` closes them.\n */\nfunction containsOpenObject(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsOpenObject)\n }\n if (node === null || typeof node !== 'object') return false\n\n const schema = node as Record<string, unknown>\n const type = schema['type']\n const isObjectSchema =\n type === 'object' || (Array.isArray(type) && type.includes('object'))\n\n if (isObjectSchema) {\n if (\n 'additionalProperties' in schema &&\n schema['additionalProperties'] !== false\n ) {\n return true\n }\n\n const properties = schema['properties']\n const hasProperties =\n properties !== null &&\n typeof properties === 'object' &&\n !Array.isArray(properties)\n if (!hasProperties && schema['additionalProperties'] !== false) {\n return true\n }\n }\n\n return Object.values(schema).some(containsOpenObject)\n}\n\nfunction containsStrictUnsupportedKeyword(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsStrictUnsupportedKeyword)\n }\n if (node === null || typeof node !== 'object') return false\n for (const [key, value] of Object.entries(node)) {\n if (STRICT_UNSUPPORTED_KEYWORDS.includes(key)) return true\n if (containsStrictUnsupportedKeyword(value)) return true\n }\n return false\n}\n\n/** A schema-position node that declares no type and so 400s strict mode. */\nfunction isTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n // boolean schemas (`true`/`false`) and non-objects aren't typeless props.\n return false\n }\n return !TYPE_INDICATOR_KEYWORDS.some((key) => key in node)\n}\n\n/**\n * Walks the genuine schema positions (property values, `items`, `anyOf`\n * variants) and reports whether any is typeless. Unlike the keyword walk this\n * must respect structure: an empty `{}` is only a problem at a schema position,\n * not e.g. an empty `properties` map.\n */\nfunction containsTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n return false\n }\n const schema = node as Record<string, any>\n\n const children: Array<unknown> = []\n if (schema.properties && typeof schema.properties === 'object') {\n children.push(...Object.values(schema.properties))\n }\n if (schema.items !== undefined) {\n children.push(\n ...(Array.isArray(schema.items) ? schema.items : [schema.items]),\n )\n }\n if (Array.isArray(schema.anyOf)) {\n children.push(...schema.anyOf)\n }\n\n return children.some(\n (child) => isTypelessSchema(child) || containsTypelessSchema(child),\n )\n}\n\n/**\n * Strict-mode structural rewrite (required widening, nullability,\n * additionalProperties). Kept private so the public entry point can apply the\n * format-stripping pass exactly once over the fully-rewritten tree.\n */\nfunction coerceStrictSchema(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): Record<string, any> {\n const result = { ...schema }\n const required =\n originalRequired ??\n (Array.isArray(result['required']) ? result['required'] : [])\n\n if (result.type === 'object' && result.properties) {\n const properties = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n\n for (const propName of allPropertyNames) {\n let prop = properties[propName]\n const wasOptional = !required.includes(propName)\n\n // Step 1: Recurse into nested structures\n if (prop.type === 'object' && prop.properties) {\n prop = coerceStrictSchema(prop, prop.required || [])\n } else if (prop.type === 'array' && prop.items) {\n prop = {\n ...prop,\n items: coerceStrictSchema(prop.items, prop.items.required || []),\n }\n } else if (prop.anyOf) {\n prop = coerceStrictSchema(prop, prop.required || [])\n } else if (prop.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n // Step 2: Apply null-widening for optional properties (after recursion)\n if (wasOptional) {\n if (prop.anyOf) {\n // For anyOf, add a null variant if not already present\n if (!prop.anyOf.some((v: any) => v.type === 'null')) {\n prop = { ...prop, anyOf: [...prop.anyOf, { type: 'null' }] }\n }\n } else if (prop.type && !Array.isArray(prop.type)) {\n prop = { ...prop, type: [prop.type, 'null'] }\n } else if (Array.isArray(prop.type) && !prop.type.includes('null')) {\n prop = { ...prop, type: [...prop.type, 'null'] }\n }\n }\n\n properties[propName] = prop\n }\n\n result.properties = properties\n result.required = allPropertyNames\n result.additionalProperties = false\n }\n\n if (result.type === 'array' && result.items) {\n result.items = coerceStrictSchema(result.items, result.items.required || [])\n }\n\n if (result.anyOf && Array.isArray(result.anyOf)) {\n result.anyOf = result.anyOf.map((variant) =>\n coerceStrictSchema(variant, variant.required || []),\n )\n }\n\n if (result.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n return result\n}\n"],"mappings":";;;;;;;;;AAQA,IAAM,2CAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAWD,SAAgB,wBAAwB,MAAgB;CACtD,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,KAAK,IAAI,uBAAuB;CAChE,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU,OAAO;CAEtD,MAAM,MAA2B,CAAC;CAClC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;EAC/C,IACE,QAAQ,YACR,OAAO,UAAU,YACjB,CAAC,yBAAyB,IAAI,KAAK,GAEnC;EAEF,IAAI,OAAO,wBAAwB,KAAK;CAC1C;CACA,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,+BACd,QACA,kBACqB;CACrB,OAAO,wBAAwB,mBAAmB,QAAQ,gBAAgB,CAAC;AAC7E;;;;;;;;;;;;;;;AAgBA,IAAM,8BAAqD;CACzD;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;AAWA,IAAM,0BAAiD;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,uB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AK,OAAO,EAAE,MAAM,OAAO,CAAC;KAAE;IAAA,OAExD,IAAI,KAAK,QAAQ,CAAC,MAAM,QAAQ,KAAK,IAAI,GAC9C,OAAO;KAAE,GAAG;KAAM,MAAM,CAAC,KAAK,MAAM,MAAM;IAAE;SACvC,IAAI,MAAM,QAAQ,KAAK,IAAI,KAAK,CAAC,KAAK,KAAK,SAAS,MAAM,GAC/D,OAAO;KAAE,GAAG;KAAM,MAAM,CAAC,GAAG,KAAK,MAAM,MAAM;IAAE;GAEnD;GAEA,WAAW,YAAY;EACzB;EAEA,OAAO,aAAa;EACpB,OAAO,WAAW;EAClB,OAAO,uBAAuB;CAChC;CAEA,IAAI,OAAO,SAAS,WAAW,OAAO,OACpC,OAAO,QAAQ,mBAAmB,OAAO,OAAO,OAAO,MAAM,YAAY,CAAC,CAAC;CAG7E,IAAI,OAAO,SAAS,MAAM,QAAQ,OAAO,KAAK,GAC5C,OAAO,QAAQ,OAAO,MAAM,KAAK,YAC/B,mBAAmB,SAAS,QAAQ,YAAY,CAAC,CAAC,CACpD;CAGF,IAAI,OAAO,OACT,MAAM,IAAI,MACR,0KACF;CAGF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"schema-converter.js","names":[],"sources":["../../../src/utils/schema-converter.ts"],"sourcesContent":["import type { NullWideningMap } from '@tanstack/ai-utils'\n\n/**\n * String `format` values accepted by OpenAI's strict Structured Outputs subset.\n * Any other format (e.g. \"uri\", \"uri-reference\", \"regex\") causes the API to\n * reject the whole request with `400 ... '<format>' is not a valid format`.\n * MCP servers and hand-written tools routinely declare such formats, so we strip\n * the unsupported ones before sending. See:\n * https://platform.openai.com/docs/guides/structured-outputs#supported-properties\n */\nconst SUPPORTED_STRING_FORMATS = new Set([\n 'date-time',\n 'time',\n 'date',\n 'duration',\n 'email',\n 'hostname',\n 'ipv4',\n 'ipv6',\n 'uuid',\n])\n\n/**\n * Recursively drop JSON-Schema `format` keywords whose value isn't in OpenAI's\n * strict-mode allowlist. Pure — returns a fresh tree and never mutates `node`,\n * so the caller's original tool definition is left intact.\n *\n * A property *named* `format` always has a schema (object/boolean) value, never\n * a bare string, so it is preserved and recursed into; only the `format`\n * *keyword* (whose value is a string) is subject to removal.\n */\nexport function stripUnsupportedFormats(node: any): any {\n if (Array.isArray(node)) return node.map(stripUnsupportedFormats)\n if (node === null || typeof node !== 'object') return node\n\n const out: Record<string, any> = {}\n for (const [key, value] of Object.entries(node)) {\n if (\n key === 'format' &&\n typeof value === 'string' &&\n !SUPPORTED_STRING_FORMATS.has(value)\n ) {\n continue\n }\n out[key] = stripUnsupportedFormats(value)\n }\n return out\n}\n\n/**\n * Transform a JSON schema to be compatible with OpenAI's structured output requirements.\n * OpenAI requires:\n * - All properties must be in the `required` array\n * - Optional fields should have null added to their type union\n * - additionalProperties must be false for objects\n * - String `format` keywords must be from a fixed allowlist (others are stripped)\n *\n * @param schema - JSON schema to transform\n * @param originalRequired - Original required array (to know which fields were optional)\n * @returns Transformed schema compatible with OpenAI structured output\n */\nexport function makeStructuredOutputCompatible(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): Record<string, any> {\n return makeStructuredOutputCompatibleWithMap(schema, originalRequired).schema\n}\n\nexport interface StructuredOutputCompatibility {\n schema: Record<string, any>\n nullWideningMap: NullWideningMap | undefined\n}\n\ninterface CoercedStrictSchema extends StructuredOutputCompatibility {\n hasUntrackableAnyOfWidening: boolean\n}\n\n/**\n * Strict-schema conversion plus an exact map of the nullability introduced by\n * that conversion. Consumers can pass provider output through\n * `undoNullWidening` before validating it against the original schema.\n */\nexport function makeStructuredOutputCompatibleWithMap(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): StructuredOutputCompatibility {\n const { schema: strictSchema, nullWideningMap } = coerceStrictSchema(\n schema,\n originalRequired,\n )\n return {\n schema: stripUnsupportedFormats(strictSchema),\n nullWideningMap,\n }\n}\n\n/**\n * JSON-Schema keywords outside OpenAI's strict Structured Outputs subset. A\n * schema using any of these can't be coerced into a strict-valid shape, and\n * sending it with `strict: true` makes the API reject the ENTIRE request\n * (e.g. `400 Invalid schema ... 'additionalProperties' is required to be ...`).\n * Tools with such schemas are emitted with `strict: false` instead (see the\n * tool converters) so they remain callable. MCP servers (e.g. Notion) routinely\n * emit these.\n *\n * - `oneOf` / `allOf` / `not` — combinator keywords strict mode rejects\n * - `$ref` / `$defs` / `definitions` — references and definition pools whose\n * object subschemas escape the `additionalProperties: false` normalization\n * strict mode requires\n */\nconst STRICT_UNSUPPORTED_KEYWORDS: ReadonlyArray<string> = [\n 'oneOf',\n 'allOf',\n 'not',\n '$ref',\n '$defs',\n 'definitions',\n]\n\n/**\n * Keys that give a schema node a resolvable type under OpenAI's strict subset.\n * A schema-position node carrying none of these is *typeless* (e.g. the empty\n * `{}` that `z.any()` / `z.unknown()` emit). Strict mode requires every schema\n * to declare a type, so a typeless node 400s the whole request — such tools\n * must be sent with `strict: false` instead. (`oneOf`/`allOf`/`$ref` count as\n * type indicators here even though they're independently strict-unsupported;\n * the keyword check below already rejects them.)\n */\nconst TYPE_INDICATOR_KEYWORDS: ReadonlyArray<string> = [\n 'type',\n 'enum',\n 'const',\n 'anyOf',\n 'oneOf',\n 'allOf',\n '$ref',\n]\n\n/**\n * Returns `false` when `schema` cannot be made strict-compatible and must be\n * sent with `strict: false`. Two ways that happens:\n *\n * 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in\n * the tree (`oneOf`/`allOf`/`not`/`$ref`/`$defs`).\n * 2. It contains a *typeless* schema node — a property/items/anyOf entry with\n * no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`\n * produces. Strict mode rejects typeless schemas.\n * 3. It contains an open object schema. OpenAI strict mode requires objects to\n * set `additionalProperties: false`, which would change the semantics of a\n * free-form map rather than merely normalizing it.\n * 4. An `anyOf` variant itself needs null widening. The inverse map is\n * intentionally schema-blind, so it cannot select a variant without risking\n * removal of a genuine nullable value accepted by another variant.\n *\n * Conservative by design: for (1) keywords are matched as object keys, so a\n * property literally named e.g. `oneOf` also trips it. That only costs that one\n * tool its strict mode, which is strictly safer than a false \"compatible\"\n * verdict that 400s the whole request.\n */\nexport function isStrictModeCompatible(schema: unknown): boolean {\n return (\n !containsStrictUnsupportedKeyword(schema) &&\n !containsTypelessSchema(schema) &&\n !containsOpenObject(schema) &&\n !containsUntrackableAnyOfWidening(schema)\n )\n}\n\n/**\n * Reports strict conversions whose synthesized nulls cannot be represented by\n * the schema-blind inverse map. Optional `anyOf` wrappers remain supported:\n * only widening introduced inside one of their variants triggers fallback.\n */\nfunction containsUntrackableAnyOfWidening(schema: unknown): boolean {\n if (schema === null || typeof schema !== 'object' || Array.isArray(schema)) {\n return false\n }\n return coerceStrictSchema(schema as Record<string, any>)\n .hasUntrackableAnyOfWidening\n}\n\n/**\n * Reports object schemas that cannot be closed without changing their input\n * semantics. Objects with `properties` and no explicit\n * `additionalProperties` are safe because `coerceStrictSchema` closes them.\n */\nfunction containsOpenObject(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsOpenObject)\n }\n if (node === null || typeof node !== 'object') return false\n\n const schema = node as Record<string, unknown>\n const type = schema['type']\n const isObjectSchema =\n type === 'object' || (Array.isArray(type) && type.includes('object'))\n\n if (isObjectSchema) {\n if (\n 'additionalProperties' in schema &&\n schema['additionalProperties'] !== false\n ) {\n return true\n }\n\n const properties = schema['properties']\n const hasProperties =\n properties !== null &&\n typeof properties === 'object' &&\n !Array.isArray(properties)\n if (!hasProperties && schema['additionalProperties'] !== false) {\n return true\n }\n }\n\n return Object.values(schema).some(containsOpenObject)\n}\n\nfunction containsStrictUnsupportedKeyword(node: unknown): boolean {\n if (Array.isArray(node)) {\n return node.some(containsStrictUnsupportedKeyword)\n }\n if (node === null || typeof node !== 'object') return false\n for (const [key, value] of Object.entries(node)) {\n if (STRICT_UNSUPPORTED_KEYWORDS.includes(key)) return true\n if (containsStrictUnsupportedKeyword(value)) return true\n }\n return false\n}\n\n/** A schema-position node that declares no type and so 400s strict mode. */\nfunction isTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n // JSON Schema permits bare boolean nodes; malformed inputs may contain\n // other primitives. OpenAI's strict subset requires a declared type, so\n // preserve the containing tool by sending it in non-strict mode.\n return true\n }\n return !TYPE_INDICATOR_KEYWORDS.some((key) => key in node)\n}\n\n/**\n * Walks the genuine schema positions (property values, `items`, `anyOf`\n * variants) and reports whether any is typeless. Unlike the keyword walk this\n * must respect structure: an empty `{}` is only a problem at a schema position,\n * not e.g. an empty `properties` map.\n */\nfunction containsTypelessSchema(node: unknown): boolean {\n if (node === null || typeof node !== 'object' || Array.isArray(node)) {\n return false\n }\n const schema = node as Record<string, any>\n\n const children: Array<unknown> = []\n if (schema.properties && typeof schema.properties === 'object') {\n children.push(...Object.values(schema.properties))\n }\n if (schema.items !== undefined) {\n children.push(\n ...(Array.isArray(schema.items) ? schema.items : [schema.items]),\n )\n }\n if (Array.isArray(schema.anyOf)) {\n children.push(...schema.anyOf)\n }\n\n return children.some(\n (child) => isTypelessSchema(child) || containsTypelessSchema(child),\n )\n}\n\n/**\n * Strict-mode structural rewrite (required widening, nullability,\n * additionalProperties). Kept private so the public entry point can apply the\n * format-stripping pass exactly once over the fully-rewritten tree.\n */\nfunction pruneMap(map: NullWideningMap): NullWideningMap | undefined {\n return Object.keys(map).length > 0 ? map : undefined\n}\n\nfunction isSchemaObject(schema: unknown): schema is Record<string, any> {\n return typeof schema === 'object' && schema !== null && !Array.isArray(schema)\n}\n\n/** Whether every active JSON Schema constraint at this node admits null. */\nfunction acceptsNull(schema: unknown): boolean {\n if (schema === true) return true\n if (!isSchemaObject(schema)) return false\n\n if ('const' in schema && schema.const !== null) return false\n if (Array.isArray(schema.enum) && !schema.enum.includes(null)) return false\n\n if (typeof schema.type === 'string' && schema.type !== 'null') return false\n if (Array.isArray(schema.type) && !schema.type.includes('null')) return false\n\n if (\n Array.isArray(schema.anyOf) &&\n !schema.anyOf.some((variant: unknown) => acceptsNull(variant))\n ) {\n return false\n }\n\n return true\n}\n\nfunction coerceStrictSchema(\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n): CoercedStrictSchema {\n const result = { ...schema }\n const nullWideningMap: NullWideningMap = {}\n let hasUntrackableAnyOfWidening = false\n const required =\n originalRequired ??\n (Array.isArray(result['required']) ? result['required'] : [])\n\n if (result.type === 'object' && result.properties) {\n const properties = { ...result.properties }\n const allPropertyNames = Object.keys(properties)\n const propertyMaps: Record<string, NullWideningMap> = {}\n\n for (const propName of allPropertyNames) {\n let prop = properties[propName]\n const wasOptional = !required.includes(propName)\n let childMap: NullWideningMap | undefined\n let widenedHere = false\n\n // Step 1: Recurse into nested structures\n if (isSchemaObject(prop) && prop.type === 'object' && prop.properties) {\n const nested = coerceStrictSchema(prop, prop.required || [])\n prop = nested.schema\n childMap = nested.nullWideningMap\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.type === 'array' && prop.items) {\n const nested = coerceStrictSchema(prop.items, prop.items.required || [])\n prop = {\n ...prop,\n items: nested.schema,\n }\n childMap = nested.nullWideningMap\n ? { items: nested.nullWideningMap }\n : undefined\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.anyOf) {\n const nested = coerceStrictSchema(prop, prop.required || [])\n prop = nested.schema\n childMap = nested.nullWideningMap\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n } else if (isSchemaObject(prop) && prop.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n // Step 2: Apply null-widening for optional properties (after recursion)\n if (wasOptional) {\n const originallyAcceptedNull = acceptsNull(prop)\n\n // `type: [..., 'null']` alone does not make null valid when an enum or\n // const still excludes it; strict decoding would be forced to emit the\n // original literal instead of the synthetic omission marker.\n if (isSchemaObject(prop) && 'const' in prop && prop.const !== null) {\n const { const: constValue, ...withoutConst } = prop\n prop = { ...withoutConst, enum: [constValue, null] }\n } else if (\n isSchemaObject(prop) &&\n Array.isArray(prop.enum) &&\n !prop.enum.includes(null)\n ) {\n prop = { ...prop, enum: [...prop.enum, null] }\n }\n\n if (isSchemaObject(prop) && prop.anyOf) {\n // A genuine null branch can use type, enum, or const. Only add a\n // provider omission marker when the original union rejected null.\n if (!acceptsNull(prop)) {\n prop = { ...prop, anyOf: [...prop.anyOf, { type: 'null' }] }\n }\n } else if (\n isSchemaObject(prop) &&\n prop.type &&\n !Array.isArray(prop.type)\n ) {\n prop = { ...prop, type: [prop.type, 'null'] }\n } else if (\n isSchemaObject(prop) &&\n Array.isArray(prop.type) &&\n !prop.type.includes('null')\n ) {\n prop = { ...prop, type: [...prop.type, 'null'] }\n }\n\n widenedHere = !originallyAcceptedNull && acceptsNull(prop)\n }\n\n properties[propName] = prop\n if (childMap || widenedHere) {\n propertyMaps[propName] = {\n ...(childMap ?? {}),\n ...(widenedHere ? { widened: true } : {}),\n }\n }\n }\n\n result.properties = properties\n result.required = allPropertyNames\n result.additionalProperties = false\n if (Object.keys(propertyMaps).length > 0) {\n nullWideningMap.properties = propertyMaps\n }\n }\n\n if (result.type === 'array' && result.items) {\n const nested = coerceStrictSchema(result.items, result.items.required || [])\n result.items = nested.schema\n if (nested.nullWideningMap) {\n nullWideningMap.items = nested.nullWideningMap\n }\n hasUntrackableAnyOfWidening ||= nested.hasUntrackableAnyOfWidening\n }\n\n if (result.anyOf && Array.isArray(result.anyOf)) {\n const variants = result.anyOf.map((variant) =>\n coerceStrictSchema(variant, variant.required || []),\n )\n result.anyOf = variants.map((variant) => variant.schema)\n hasUntrackableAnyOfWidening ||= variants.some(\n (variant) =>\n variant.nullWideningMap !== undefined ||\n variant.hasUntrackableAnyOfWidening,\n )\n }\n\n if (result.oneOf) {\n throw new Error(\n 'oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types',\n )\n }\n\n return {\n schema: result,\n nullWideningMap: pruneMap(nullWideningMap),\n hasUntrackableAnyOfWidening,\n }\n}\n"],"mappings":";;;;;;;;;AAUA,IAAM,2CAA2B,IAAI,IAAI;CACvC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;AAWD,SAAgB,wBAAwB,MAAgB;CACtD,IAAI,MAAM,QAAQ,IAAI,GAAG,OAAO,KAAK,IAAI,uBAAuB;CAChE,IAAI,SAAS,QAAQ,OAAO,SAAS,UAAU,OAAO;CAEtD,MAAM,MAA2B,CAAC;CAClC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,IAAI,GAAG;EAC/C,IACE,QAAQ,YACR,OAAO,UAAU,YACjB,CAAC,yBAAyB,IAAI,KAAK,GAEnC;EAEF,IAAI,OAAO,wBAAwB,KAAK;CAC1C;CACA,OAAO;AACT;;;;;;;;;;;;;AAcA,SAAgB,+BACd,QACA,kBACqB;CACrB,OAAO,sCAAsC,QAAQ,gBAAgB,CAAC,CAAC;AACzE;;;;;;AAgBA,SAAgB,sCACd,QACA,kBAC+B;CAC/B,MAAM,EAAE,QAAQ,cAAc,oBAAoB,mBAChD,QACA,gBACF;CACA,OAAO;EACL,QAAQ,wBAAwB,YAAY;EAC5C;CACF;AACF;;;;;;;;;;;;;;;AAgBA,IAAM,8BAAqD;CACzD;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;AAWA,IAAM,0BAAiD;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;AAuBA,SAAgB,uBAAuB,QAA0B;CAC/D,OACE,CAAC,iCAAiC,MAAM,KACxC,CAAC,uBAAuB,MAAM,KAC9B,CAAC,mBAAmB,MAAM,KAC1B,CAAC,iCAAiC,MAAM;AAE5C;;;;;;AAOA,SAAS,iCAAiC,QAA0B;CAClE,IAAI,WAAW,QAAQ,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,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,CAAC,CAAC,CACpD;EACA,OAAO,QAAQ,SAAS,KAAK,YAAY,QAAQ,MAAM;EACvD,gCAAgC,SAAS,MACtC,YACC,QAAQ,oBAAoB,KAAA,KAC5B,QAAQ,2BACZ;CACF;CAEA,IAAI,OAAO,OACT,MAAM,IAAI,MACR,0KACF;CAGF,OAAO;EACL,QAAQ;EACR,iBAAiB,SAAS,eAAe;EACzC;CACF;AACF"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Tool } from '@tanstack/ai';
|
|
2
|
+
import { StructuredOutputCompatibility } from './schema-converter.js';
|
|
3
|
+
type ToolInputNormalizer = (toolName: string, input: unknown) => unknown;
|
|
4
|
+
type SchemaConverterWithMap = (schema: Record<string, any>, originalRequired?: Array<string>) => StructuredOutputCompatibility;
|
|
5
|
+
/**
|
|
6
|
+
* Build the inverse transform for the strict tool schemas sent in one request.
|
|
7
|
+
* Pass the same converter the request used so subclass schema tweaks stay
|
|
8
|
+
* aligned with undo. Non-strict tools are excluded because they were not
|
|
9
|
+
* null-widened on the wire.
|
|
10
|
+
*/
|
|
11
|
+
export declare function createToolInputNormalizer(tools: Array<Tool> | undefined, convertSchema?: SchemaConverterWithMap): ToolInputNormalizer;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { isStrictModeCompatible, makeStructuredOutputCompatibleWithMap } from "./schema-converter.js";
|
|
2
|
+
import { undoNullWidening } from "@tanstack/ai-utils";
|
|
3
|
+
//#region src/utils/tool-input-normalizer.ts
|
|
4
|
+
/**
|
|
5
|
+
* Build the inverse transform for the strict tool schemas sent in one request.
|
|
6
|
+
* Pass the same converter the request used so subclass schema tweaks stay
|
|
7
|
+
* aligned with undo. Non-strict tools are excluded because they were not
|
|
8
|
+
* null-widened on the wire.
|
|
9
|
+
*/
|
|
10
|
+
function createToolInputNormalizer(tools, convertSchema = makeStructuredOutputCompatibleWithMap) {
|
|
11
|
+
const maps = /* @__PURE__ */ new Map();
|
|
12
|
+
const seenNames = /* @__PURE__ */ new Set();
|
|
13
|
+
const ambiguousNames = /* @__PURE__ */ new Set();
|
|
14
|
+
for (const tool of tools ?? []) {
|
|
15
|
+
if (ambiguousNames.has(tool.name)) continue;
|
|
16
|
+
if (seenNames.has(tool.name)) {
|
|
17
|
+
maps.delete(tool.name);
|
|
18
|
+
ambiguousNames.add(tool.name);
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
seenNames.add(tool.name);
|
|
22
|
+
const inputSchema = tool.inputSchema ?? {
|
|
23
|
+
type: "object",
|
|
24
|
+
properties: {},
|
|
25
|
+
required: []
|
|
26
|
+
};
|
|
27
|
+
if (!isStrictModeCompatible(inputSchema)) continue;
|
|
28
|
+
const { nullWideningMap } = convertSchema(inputSchema, inputSchema.required || []);
|
|
29
|
+
if (nullWideningMap) maps.set(tool.name, nullWideningMap);
|
|
30
|
+
}
|
|
31
|
+
return (toolName, input) => undoNullWidening(input, maps.get(toolName));
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { createToolInputNormalizer };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=tool-input-normalizer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tool-input-normalizer.js","names":[],"sources":["../../../src/utils/tool-input-normalizer.ts"],"sourcesContent":["import { undoNullWidening } from '@tanstack/ai-utils'\nimport {\n isStrictModeCompatible,\n makeStructuredOutputCompatibleWithMap,\n} from './schema-converter'\nimport type { JSONSchema, Tool } from '@tanstack/ai'\nimport type { NullWideningMap } from '@tanstack/ai-utils'\nimport type { StructuredOutputCompatibility } from './schema-converter'\n\ntype ToolInputNormalizer = (toolName: string, input: unknown) => unknown\n\ntype SchemaConverterWithMap = (\n schema: Record<string, any>,\n originalRequired?: Array<string>,\n) => StructuredOutputCompatibility\n\n/**\n * Build the inverse transform for the strict tool schemas sent in one request.\n * Pass the same converter the request used so subclass schema tweaks stay\n * aligned with undo. Non-strict tools are excluded because they were not\n * null-widened on the wire.\n */\nexport function createToolInputNormalizer(\n tools: Array<Tool> | undefined,\n convertSchema: SchemaConverterWithMap = makeStructuredOutputCompatibleWithMap,\n): ToolInputNormalizer {\n const maps = new Map<string, NullWideningMap>()\n const seenNames = new Set<string>()\n const ambiguousNames = new Set<string>()\n\n for (const tool of tools ?? []) {\n if (ambiguousNames.has(tool.name)) continue\n if (seenNames.has(tool.name)) {\n maps.delete(tool.name)\n ambiguousNames.add(tool.name)\n continue\n }\n seenNames.add(tool.name)\n\n const inputSchema = (tool.inputSchema ?? {\n type: 'object',\n properties: {},\n required: [],\n }) as JSONSchema\n if (!isStrictModeCompatible(inputSchema)) continue\n\n const { nullWideningMap } = convertSchema(\n inputSchema,\n inputSchema.required || [],\n )\n if (nullWideningMap) maps.set(tool.name, nullWideningMap)\n }\n\n return (toolName, input) => undoNullWidening(input, maps.get(toolName))\n}\n"],"mappings":";;;;;;;;;AAsBA,SAAgB,0BACd,OACA,gBAAwC,uCACnB;CACrB,MAAM,uBAAO,IAAI,IAA6B;CAC9C,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,iCAAiB,IAAI,IAAY;CAEvC,KAAK,MAAM,QAAQ,SAAS,CAAC,GAAG;EAC9B,IAAI,eAAe,IAAI,KAAK,IAAI,GAAG;EACnC,IAAI,UAAU,IAAI,KAAK,IAAI,GAAG;GAC5B,KAAK,OAAO,KAAK,IAAI;GACrB,eAAe,IAAI,KAAK,IAAI;GAC5B;EACF;EACA,UAAU,IAAI,KAAK,IAAI;EAEvB,MAAM,cAAe,KAAK,eAAe;GACvC,MAAM;GACN,YAAY,CAAC;GACb,UAAU,CAAC;EACb;EACA,IAAI,CAAC,uBAAuB,WAAW,GAAG;EAE1C,MAAM,EAAE,oBAAoB,cAC1B,aACA,YAAY,YAAY,CAAC,CAC3B;EACA,IAAI,iBAAiB,KAAK,IAAI,KAAK,MAAM,eAAe;CAC1D;CAEA,QAAQ,UAAU,UAAU,iBAAiB,OAAO,KAAK,IAAI,QAAQ,CAAC;AACxE"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/openai-base",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.3",
|
|
4
4
|
"description": "Shared OpenAI SDK base adapters for TanStack AI providers using Chat Completions and Responses APIs.",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -47,13 +47,13 @@
|
|
|
47
47
|
"@tanstack/ai-utils": "^0.4.0"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@tanstack/ai": "^0.
|
|
50
|
+
"@tanstack/ai": "^0.48.0"
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@vitest/coverage-v8": "4.1.10",
|
|
54
54
|
"vite": "^8.2.1",
|
|
55
55
|
"zod": "^4.2.0",
|
|
56
|
-
"@tanstack/ai": "0.
|
|
56
|
+
"@tanstack/ai": "0.48.0"
|
|
57
57
|
},
|
|
58
58
|
"scripts": {
|
|
59
59
|
"build": "vite build",
|
|
@@ -6,7 +6,9 @@ import {
|
|
|
6
6
|
} from '@tanstack/ai/adapter-internals'
|
|
7
7
|
import { generateId } from '@tanstack/ai-utils'
|
|
8
8
|
import { extractRequestOptions } from '../utils/request-options'
|
|
9
|
-
import {
|
|
9
|
+
import { makeStructuredOutputCompatibleWithMap } from '../utils/schema-converter'
|
|
10
|
+
import { createToolInputNormalizer } from '../utils/tool-input-normalizer'
|
|
11
|
+
import type { StructuredOutputCompatibility } from '../utils/schema-converter'
|
|
10
12
|
import { buildChatCompletionsUsage } from '../usage'
|
|
11
13
|
import { convertToolsToChatCompletionsFormat } from './chat-completions-tool-converter'
|
|
12
14
|
import type OpenAI from 'openai'
|
|
@@ -25,8 +27,7 @@ import type {
|
|
|
25
27
|
DefaultMessageMetadataByModality,
|
|
26
28
|
Modality,
|
|
27
29
|
ModelMessage,
|
|
28
|
-
|
|
29
|
-
StreamChunk,
|
|
30
|
+
AdapterYieldChunk,
|
|
30
31
|
TextOptions,
|
|
31
32
|
} from '@tanstack/ai'
|
|
32
33
|
|
|
@@ -69,7 +70,7 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
69
70
|
|
|
70
71
|
async *chatStream(
|
|
71
72
|
options: TextOptions<TProviderOptions>,
|
|
72
|
-
): AsyncIterable<
|
|
73
|
+
): AsyncIterable<AdapterYieldChunk> {
|
|
73
74
|
// AG-UI lifecycle tracking (mutable state object for ESLint compatibility)
|
|
74
75
|
const aguiState = {
|
|
75
76
|
runId: generateId(this.name),
|
|
@@ -110,7 +111,7 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
110
111
|
options: TextOptions,
|
|
111
112
|
aguiState: ChatStreamState,
|
|
112
113
|
source: 'chatStream' | 'processStreamChunks',
|
|
113
|
-
): AsyncIterable<
|
|
114
|
+
): AsyncIterable<AdapterYieldChunk> {
|
|
114
115
|
// Narrow before logging: raw SDK errors can carry request metadata
|
|
115
116
|
// (including auth headers) which we must never surface to user loggers.
|
|
116
117
|
const errorPayload = toRunErrorPayload(
|
|
@@ -185,6 +186,8 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
185
186
|
|
|
186
187
|
yield {
|
|
187
188
|
type: EventType.RUN_ERROR,
|
|
189
|
+
runId: aguiState.runId,
|
|
190
|
+
threadId: aguiState.threadId,
|
|
188
191
|
model: options.model,
|
|
189
192
|
timestamp: Date.now(),
|
|
190
193
|
message: errorPayload.message,
|
|
@@ -320,7 +323,7 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
320
323
|
*/
|
|
321
324
|
async *structuredOutputStream(
|
|
322
325
|
options: StructuredOutputOptions<TProviderOptions>,
|
|
323
|
-
): AsyncIterable<
|
|
326
|
+
): AsyncIterable<AdapterYieldChunk> {
|
|
324
327
|
const { chatOptions, outputSchema } = options
|
|
325
328
|
const requestParams = this.mapOptionsToRequest(chatOptions)
|
|
326
329
|
|
|
@@ -349,7 +352,7 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
349
352
|
|
|
350
353
|
const closeReasoningLifecycle = function* (this: {
|
|
351
354
|
name: string
|
|
352
|
-
}): Generator<
|
|
355
|
+
}): Generator<AdapterYieldChunk> {
|
|
353
356
|
if (reasoningMessageId && !hasClosedReasoning) {
|
|
354
357
|
hasClosedReasoning = true
|
|
355
358
|
yield {
|
|
@@ -374,6 +377,9 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
374
377
|
content: accumulatedReasoning,
|
|
375
378
|
}
|
|
376
379
|
}
|
|
380
|
+
reasoningMessageId = undefined
|
|
381
|
+
stepId = undefined
|
|
382
|
+
hasClosedReasoning = false
|
|
377
383
|
}
|
|
378
384
|
}.bind(this)
|
|
379
385
|
|
|
@@ -644,15 +650,29 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
644
650
|
)
|
|
645
651
|
}
|
|
646
652
|
|
|
653
|
+
/**
|
|
654
|
+
* Strict conversion plus the inverse null-widening map for this request.
|
|
655
|
+
* Override this when schema conversion changes, so tool-input undo matches
|
|
656
|
+
* the wire schema.
|
|
657
|
+
*/
|
|
658
|
+
protected makeStructuredOutputCompatibleWithMap(
|
|
659
|
+
schema: Record<string, any>,
|
|
660
|
+
originalRequired?: Array<string>,
|
|
661
|
+
): StructuredOutputCompatibility {
|
|
662
|
+
return makeStructuredOutputCompatibleWithMap(schema, originalRequired)
|
|
663
|
+
}
|
|
664
|
+
|
|
647
665
|
/**
|
|
648
666
|
* Applies provider-specific transformations for structured output compatibility.
|
|
649
|
-
* Override
|
|
667
|
+
* Override `makeStructuredOutputCompatibleWithMap` when you need the inverse map
|
|
668
|
+
* to match the wire schema.
|
|
650
669
|
*/
|
|
651
670
|
protected makeStructuredOutputCompatible(
|
|
652
671
|
schema: Record<string, any>,
|
|
653
672
|
originalRequired?: Array<string>,
|
|
654
673
|
): Record<string, any> {
|
|
655
|
-
return
|
|
674
|
+
return this.makeStructuredOutputCompatibleWithMap(schema, originalRequired)
|
|
675
|
+
.schema
|
|
656
676
|
}
|
|
657
677
|
|
|
658
678
|
/**
|
|
@@ -689,7 +709,12 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
689
709
|
stream: AsyncIterable<ChatCompletionChunk>,
|
|
690
710
|
options: TextOptions,
|
|
691
711
|
aguiState: ChatStreamState,
|
|
692
|
-
): AsyncIterable<
|
|
712
|
+
): AsyncIterable<AdapterYieldChunk> {
|
|
713
|
+
const normalizeToolInput = createToolInputNormalizer(
|
|
714
|
+
options.tools,
|
|
715
|
+
(schema, required) =>
|
|
716
|
+
this.makeStructuredOutputCompatibleWithMap(schema, required),
|
|
717
|
+
)
|
|
693
718
|
let accumulatedContent = ''
|
|
694
719
|
let hasEmittedTextMessageStart = false
|
|
695
720
|
let lastModel: string | undefined
|
|
@@ -958,8 +983,10 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
958
983
|
if (toolCall.arguments) {
|
|
959
984
|
try {
|
|
960
985
|
const parsed: unknown = JSON.parse(toolCall.arguments)
|
|
961
|
-
parsedInput =
|
|
962
|
-
|
|
986
|
+
parsedInput = normalizeToolInput(
|
|
987
|
+
toolCall.name,
|
|
988
|
+
parsed && typeof parsed === 'object' ? parsed : {},
|
|
989
|
+
)
|
|
963
990
|
} catch (parseError) {
|
|
964
991
|
options.logger.errors(
|
|
965
992
|
`${this.name}.processStreamChunks tool-args JSON parse failed`,
|
|
@@ -1030,7 +1057,10 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
1030
1057
|
if (toolCall.arguments) {
|
|
1031
1058
|
try {
|
|
1032
1059
|
const parsed: unknown = JSON.parse(toolCall.arguments)
|
|
1033
|
-
parsedInput =
|
|
1060
|
+
parsedInput = normalizeToolInput(
|
|
1061
|
+
toolCall.name,
|
|
1062
|
+
parsed && typeof parsed === 'object' ? parsed : {},
|
|
1063
|
+
)
|
|
1034
1064
|
} catch (parseError) {
|
|
1035
1065
|
// Mirror the finish_reason path's logger call — a truncated
|
|
1036
1066
|
// stream emitting malformed tool-call JSON would otherwise
|
|
@@ -1114,7 +1144,7 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
1114
1144
|
// tool results that would never arrive. OpenAI's legacy
|
|
1115
1145
|
// `function_call` value (from the v1 function-calling API) is
|
|
1116
1146
|
// normalized to `tool_calls` — semantically the same termination.
|
|
1117
|
-
const finishReason: NonNullable<
|
|
1147
|
+
const finishReason: NonNullable<AdapterYieldChunk['finishReason']> =
|
|
1118
1148
|
emittedAnyToolCallEnd
|
|
1119
1149
|
? 'tool_calls'
|
|
1120
1150
|
: pendingFinishReason === 'tool_calls'
|
|
@@ -1401,9 +1431,9 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
1401
1431
|
* Handles backward compatibility with string content.
|
|
1402
1432
|
*/
|
|
1403
1433
|
protected normalizeContent(
|
|
1404
|
-
content: string | null | Array<ContentPart>,
|
|
1434
|
+
content: string | null | undefined | Array<ContentPart>,
|
|
1405
1435
|
): Array<ContentPart> {
|
|
1406
|
-
if (content === null) {
|
|
1436
|
+
if (content === null || content === undefined) {
|
|
1407
1437
|
return []
|
|
1408
1438
|
}
|
|
1409
1439
|
if (typeof content === 'string') {
|
|
@@ -1416,9 +1446,12 @@ export abstract class OpenAIBaseChatCompletionsTextAdapter<
|
|
|
1416
1446
|
* Extracts text content from a content value that may be string, null, or ContentPart array.
|
|
1417
1447
|
*/
|
|
1418
1448
|
protected extractTextContent(
|
|
1419
|
-
content: string | null | Array<ContentPart>,
|
|
1449
|
+
content: string | null | undefined | Array<ContentPart>,
|
|
1420
1450
|
): string {
|
|
1421
|
-
|
|
1451
|
+
// Tool-call-only assistant turns (e.g. an approval resume replaying the
|
|
1452
|
+
// pending call) carry no text and arrive as `null` or `undefined`; both
|
|
1453
|
+
// must collapse to '' rather than crash on `.filter`.
|
|
1454
|
+
if (content === null || content === undefined) {
|
|
1422
1455
|
return ''
|
|
1423
1456
|
}
|
|
1424
1457
|
if (typeof content === 'string') {
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import { convertFunctionToolToChatCompletionsFormat } from './chat-completions-tool-converter'
|
|
3
|
+
import type { Tool } from '@tanstack/ai'
|
|
4
|
+
|
|
5
|
+
describe('chat-completions tool converter', () => {
|
|
6
|
+
it('falls back from strict mode when an anyOf variant needs null widening', () => {
|
|
7
|
+
const out = convertFunctionToolToChatCompletionsFormat(
|
|
8
|
+
anyOfOptionalVariantTool,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
expect(out.function.strict).toBe(false)
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('falls back from strict mode for boolean schema nodes', () => {
|
|
15
|
+
const out = convertFunctionToolToChatCompletionsFormat(booleanSchemaTool)
|
|
16
|
+
|
|
17
|
+
expect(out.function.strict).toBe(false)
|
|
18
|
+
expect(out.function.parameters).toEqual(booleanSchemaTool.inputSchema)
|
|
19
|
+
})
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
const booleanSchemaInput = {
|
|
23
|
+
type: 'object',
|
|
24
|
+
properties: {},
|
|
25
|
+
required: [],
|
|
26
|
+
}
|
|
27
|
+
Reflect.set(booleanSchemaInput.properties, 'acceptAnything', true)
|
|
28
|
+
|
|
29
|
+
const booleanSchemaTool = {
|
|
30
|
+
name: 'accept_anything',
|
|
31
|
+
description: 'Accept any value',
|
|
32
|
+
inputSchema: booleanSchemaInput,
|
|
33
|
+
} satisfies Tool
|
|
34
|
+
|
|
35
|
+
const anyOfOptionalVariantTool: Tool = {
|
|
36
|
+
name: 'store_variant',
|
|
37
|
+
description: 'Store a union variant',
|
|
38
|
+
inputSchema: {
|
|
39
|
+
type: 'object',
|
|
40
|
+
properties: {
|
|
41
|
+
value: {
|
|
42
|
+
anyOf: [
|
|
43
|
+
{
|
|
44
|
+
type: 'object',
|
|
45
|
+
properties: {
|
|
46
|
+
kind: { const: 'optional' },
|
|
47
|
+
note: { type: 'string' },
|
|
48
|
+
},
|
|
49
|
+
required: ['kind'],
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
type: 'object',
|
|
53
|
+
properties: {
|
|
54
|
+
kind: { const: 'nullable' },
|
|
55
|
+
note: { type: ['string', 'null'] },
|
|
56
|
+
},
|
|
57
|
+
required: ['kind', 'note'],
|
|
58
|
+
},
|
|
59
|
+
],
|
|
60
|
+
},
|
|
61
|
+
},
|
|
62
|
+
required: ['value'],
|
|
63
|
+
},
|
|
64
|
+
}
|