@tanstack/openai-base 0.9.3 → 0.9.5

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.
Files changed (66) hide show
  1. package/dist/esm/adapters/chat-completions-text.d.ts +116 -0
  2. package/dist/esm/adapters/chat-completions-text.js +967 -0
  3. package/dist/esm/adapters/chat-completions-text.js.map +1 -0
  4. package/dist/esm/adapters/chat-completions-tool-converter.d.ts +35 -0
  5. package/dist/esm/adapters/chat-completions-tool-converter.js +42 -0
  6. package/dist/esm/adapters/chat-completions-tool-converter.js.map +1 -0
  7. package/dist/esm/adapters/responses-text.d.ts +135 -0
  8. package/dist/esm/adapters/responses-text.js +1324 -0
  9. package/dist/esm/adapters/responses-text.js.map +1 -0
  10. package/dist/esm/adapters/responses-tool-converter.d.ts +42 -0
  11. package/dist/esm/adapters/responses-tool-converter.js +38 -0
  12. package/dist/esm/adapters/responses-tool-converter.js.map +1 -0
  13. package/dist/esm/index.d.ts +7 -0
  14. package/dist/esm/index.js +59 -0
  15. package/dist/esm/index.js.map +1 -0
  16. package/dist/esm/tools/apply-patch-tool.d.ts +16 -0
  17. package/dist/esm/tools/apply-patch-tool.js +17 -0
  18. package/dist/esm/tools/apply-patch-tool.js.map +1 -0
  19. package/dist/esm/tools/code-interpreter-tool.d.ts +17 -0
  20. package/dist/esm/tools/code-interpreter-tool.js +22 -0
  21. package/dist/esm/tools/code-interpreter-tool.js.map +1 -0
  22. package/dist/esm/tools/computer-use-tool.d.ts +16 -0
  23. package/dist/esm/tools/computer-use-tool.js +23 -0
  24. package/dist/esm/tools/computer-use-tool.js.map +1 -0
  25. package/dist/esm/tools/custom-tool.d.ts +13 -0
  26. package/dist/esm/tools/custom-tool.js +25 -0
  27. package/dist/esm/tools/custom-tool.js.map +1 -0
  28. package/dist/esm/tools/file-search-tool.d.ts +18 -0
  29. package/dist/esm/tools/file-search-tool.js +35 -0
  30. package/dist/esm/tools/file-search-tool.js.map +1 -0
  31. package/dist/esm/tools/function-tool.d.ts +23 -0
  32. package/dist/esm/tools/function-tool.js +33 -0
  33. package/dist/esm/tools/function-tool.js.map +1 -0
  34. package/dist/esm/tools/image-generation-tool.d.ts +23 -0
  35. package/dist/esm/tools/image-generation-tool.js +28 -0
  36. package/dist/esm/tools/image-generation-tool.js.map +1 -0
  37. package/dist/esm/tools/index.d.ts +27 -0
  38. package/dist/esm/tools/local-shell-tool.d.ts +17 -0
  39. package/dist/esm/tools/local-shell-tool.js +17 -0
  40. package/dist/esm/tools/local-shell-tool.js.map +1 -0
  41. package/dist/esm/tools/mcp-tool.d.ts +18 -0
  42. package/dist/esm/tools/mcp-tool.js +31 -0
  43. package/dist/esm/tools/mcp-tool.js.map +1 -0
  44. package/dist/esm/tools/shell-tool.d.ts +26 -0
  45. package/dist/esm/tools/shell-tool.js +25 -0
  46. package/dist/esm/tools/shell-tool.js.map +1 -0
  47. package/dist/esm/tools/tool-choice.d.ts +17 -0
  48. package/dist/esm/tools/tool-converter.d.ts +6 -0
  49. package/dist/esm/tools/tool-converter.js +61 -0
  50. package/dist/esm/tools/tool-converter.js.map +1 -0
  51. package/dist/esm/tools/web-search-preview-tool.d.ts +19 -0
  52. package/dist/esm/tools/web-search-preview-tool.js +19 -0
  53. package/dist/esm/tools/web-search-preview-tool.js.map +1 -0
  54. package/dist/esm/tools/web-search-tool.d.ts +20 -0
  55. package/dist/esm/tools/web-search-tool.js +19 -0
  56. package/dist/esm/tools/web-search-tool.js.map +1 -0
  57. package/dist/esm/usage.d.ts +34 -0
  58. package/dist/esm/usage.js +83 -0
  59. package/dist/esm/usage.js.map +1 -0
  60. package/dist/esm/utils/request-options.d.ts +14 -0
  61. package/dist/esm/utils/request-options.js +11 -0
  62. package/dist/esm/utils/request-options.js.map +1 -0
  63. package/dist/esm/utils/schema-converter.d.ts +39 -0
  64. package/dist/esm/utils/schema-converter.js +145 -0
  65. package/dist/esm/utils/schema-converter.js.map +1 -0
  66. package/package.json +4 -4
@@ -0,0 +1,83 @@
1
+ import { buildBaseUsage } from "@tanstack/ai";
2
+ function buildChatCompletionsUsage(usage) {
3
+ if (!usage) return void 0;
4
+ const result = buildBaseUsage({
5
+ promptTokens: usage.prompt_tokens || 0,
6
+ completionTokens: usage.completion_tokens || 0,
7
+ totalTokens: usage.total_tokens || 0
8
+ });
9
+ const completionDetails = usage.completion_tokens_details;
10
+ const completionTokensDetails = {
11
+ ...completionDetails?.reasoning_tokens ? { reasoningTokens: completionDetails.reasoning_tokens } : {},
12
+ ...completionDetails?.audio_tokens ? { audioTokens: completionDetails.audio_tokens } : {}
13
+ };
14
+ const promptDetails = usage.prompt_tokens_details;
15
+ const promptTokensDetails = {
16
+ ...promptDetails?.cached_tokens ? { cachedTokens: promptDetails.cached_tokens } : {},
17
+ ...promptDetails?.audio_tokens ? { audioTokens: promptDetails.audio_tokens } : {}
18
+ };
19
+ if (Object.keys(completionTokensDetails).length > 0) {
20
+ result.completionTokensDetails = completionTokensDetails;
21
+ }
22
+ if (Object.keys(promptTokensDetails).length > 0) {
23
+ result.promptTokensDetails = promptTokensDetails;
24
+ }
25
+ const providerUsageDetails = {
26
+ ...completionDetails?.accepted_prediction_tokens ? {
27
+ acceptedPredictionTokens: completionDetails.accepted_prediction_tokens
28
+ } : {},
29
+ ...completionDetails?.rejected_prediction_tokens ? {
30
+ rejectedPredictionTokens: completionDetails.rejected_prediction_tokens
31
+ } : {}
32
+ };
33
+ if (Object.keys(providerUsageDetails).length > 0) {
34
+ result.providerUsageDetails = providerUsageDetails;
35
+ }
36
+ return result;
37
+ }
38
+ function buildResponsesUsage(usage) {
39
+ if (!usage) return void 0;
40
+ const result = buildBaseUsage({
41
+ promptTokens: usage.input_tokens || 0,
42
+ completionTokens: usage.output_tokens || 0,
43
+ totalTokens: usage.total_tokens || 0
44
+ });
45
+ const cachedTokens = usage.input_tokens_details?.cached_tokens;
46
+ if (cachedTokens && cachedTokens > 0) {
47
+ result.promptTokensDetails = {
48
+ ...result.promptTokensDetails,
49
+ cachedTokens
50
+ };
51
+ }
52
+ const reasoningTokens = usage.output_tokens_details?.reasoning_tokens;
53
+ if (reasoningTokens && reasoningTokens > 0) {
54
+ result.completionTokensDetails = {
55
+ ...result.completionTokensDetails,
56
+ reasoningTokens
57
+ };
58
+ }
59
+ return result;
60
+ }
61
+ function buildImagesUsage(usage) {
62
+ if (!usage) return void 0;
63
+ const result = buildBaseUsage({
64
+ promptTokens: usage.input_tokens || 0,
65
+ completionTokens: usage.output_tokens || 0,
66
+ totalTokens: usage.total_tokens || 0
67
+ });
68
+ const inputDetails = usage.input_tokens_details;
69
+ const promptTokensDetails = {
70
+ ...inputDetails?.text_tokens ? { textTokens: inputDetails.text_tokens } : {},
71
+ ...inputDetails?.image_tokens ? { imageTokens: inputDetails.image_tokens } : {}
72
+ };
73
+ if (Object.keys(promptTokensDetails).length > 0) {
74
+ result.promptTokensDetails = promptTokensDetails;
75
+ }
76
+ return result;
77
+ }
78
+ export {
79
+ buildChatCompletionsUsage,
80
+ buildImagesUsage,
81
+ buildResponsesUsage
82
+ };
83
+ //# sourceMappingURL=usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.js","sources":["../../src/usage.ts"],"sourcesContent":["import { buildBaseUsage } from '@tanstack/ai'\nimport type { TokenUsage } from '@tanstack/ai'\nimport type OpenAI from 'openai'\n\n/**\n * Build normalized {@link TokenUsage} from an OpenAI-compatible Chat\n * Completions `usage` object.\n *\n * Shared by every provider that routes through\n * {@link OpenAIBaseChatCompletionsTextAdapter} (OpenAI Chat Completions, Grok,\n * Groq). Surfaces cached prompt tokens and reasoning/audio detail tokens when\n * the provider reports them. Returns `undefined` when the provider reported no\n * usage object, so callers omit the field rather than fabricating zeroed totals.\n */\nexport function buildChatCompletionsUsage(\n usage: OpenAI.Chat.Completions.ChatCompletion['usage'] | undefined | null,\n): TokenUsage | undefined {\n if (!usage) return undefined\n\n const result = buildBaseUsage({\n promptTokens: usage.prompt_tokens || 0,\n completionTokens: usage.completion_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n })\n\n const completionDetails = usage.completion_tokens_details\n const completionTokensDetails = {\n ...(completionDetails?.reasoning_tokens\n ? { reasoningTokens: completionDetails.reasoning_tokens }\n : {}),\n ...(completionDetails?.audio_tokens\n ? { audioTokens: completionDetails.audio_tokens }\n : {}),\n }\n\n const promptDetails = usage.prompt_tokens_details\n const promptTokensDetails = {\n ...(promptDetails?.cached_tokens\n ? { cachedTokens: promptDetails.cached_tokens }\n : {}),\n ...(promptDetails?.audio_tokens\n ? { audioTokens: promptDetails.audio_tokens }\n : {}),\n }\n\n if (Object.keys(completionTokensDetails).length > 0) {\n result.completionTokensDetails = completionTokensDetails\n }\n if (Object.keys(promptTokensDetails).length > 0) {\n result.promptTokensDetails = promptTokensDetails\n }\n\n // Predicted Outputs accepted/rejected counts have no canonical TokenUsage\n // slot but are still billed (rejected tokens included), so surface them under\n // providerUsageDetails — matching how the OpenRouter adapter exposes them.\n const providerUsageDetails = {\n ...(completionDetails?.accepted_prediction_tokens\n ? {\n acceptedPredictionTokens:\n completionDetails.accepted_prediction_tokens,\n }\n : {}),\n ...(completionDetails?.rejected_prediction_tokens\n ? {\n rejectedPredictionTokens:\n completionDetails.rejected_prediction_tokens,\n }\n : {}),\n }\n if (Object.keys(providerUsageDetails).length > 0) {\n result.providerUsageDetails = providerUsageDetails\n }\n\n return result\n}\n\n/**\n * Build normalized {@link TokenUsage} from an OpenAI Responses API\n * `ResponseUsage` object.\n *\n * Shared by every provider that routes through\n * {@link OpenAIBaseResponsesTextAdapter}. Surfaces cached prompt tokens and\n * reasoning detail tokens when present. Returns `undefined` when the provider\n * reported no usage object, so callers omit the field rather than fabricating\n * zeroed totals.\n */\nexport function buildResponsesUsage(\n usage: OpenAI.Responses.ResponseUsage | undefined | null,\n): TokenUsage | undefined {\n if (!usage) return undefined\n\n const result = buildBaseUsage({\n promptTokens: usage.input_tokens || 0,\n completionTokens: usage.output_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n })\n\n // Despite the SDK types marking these required, they can be undefined at runtime.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const cachedTokens = usage.input_tokens_details?.cached_tokens\n if (cachedTokens && cachedTokens > 0) {\n result.promptTokensDetails = {\n ...result.promptTokensDetails,\n cachedTokens,\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n const reasoningTokens = usage.output_tokens_details?.reasoning_tokens\n if (reasoningTokens && reasoningTokens > 0) {\n result.completionTokensDetails = {\n ...result.completionTokensDetails,\n reasoningTokens,\n }\n }\n\n return result\n}\n\n/**\n * Build normalized {@link TokenUsage} from an OpenAI Images API `usage` object.\n *\n * Shared by every provider that generates images through the OpenAI Images SDK\n * (OpenAI, Grok). Token-billed image models (e.g. gpt-image-1) report an input\n * breakdown of text vs image tokens, which is surfaced on `promptTokensDetails`.\n * Models that don't return usage (e.g. DALL·E) yield `undefined` so callers can\n * omit the field rather than emit zeroed totals.\n */\nexport function buildImagesUsage(\n usage: OpenAI.Images.ImagesResponse['usage'] | undefined | null,\n): TokenUsage | undefined {\n if (!usage) return undefined\n\n const result = buildBaseUsage({\n promptTokens: usage.input_tokens || 0,\n completionTokens: usage.output_tokens || 0,\n totalTokens: usage.total_tokens || 0,\n })\n\n // The SDK types input_tokens_details (and its numeric fields) as required, but\n // real responses — e.g. from DALL·E or other non-token-billed models — can\n // omit them, so treat the breakdown as optional.\n const inputDetails = usage.input_tokens_details as\n | { text_tokens?: number; image_tokens?: number }\n | undefined\n const promptTokensDetails = {\n ...(inputDetails?.text_tokens\n ? { textTokens: inputDetails.text_tokens }\n : {}),\n ...(inputDetails?.image_tokens\n ? { imageTokens: inputDetails.image_tokens }\n : {}),\n }\n if (Object.keys(promptTokensDetails).length > 0) {\n result.promptTokensDetails = promptTokensDetails\n }\n\n return result\n}\n"],"names":[],"mappings":";AAcO,SAAS,0BACd,OACwB;AACxB,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,SAAS,eAAe;AAAA,IAC5B,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,GAAG;AACpC,WAAO,sBAAsB;AAAA,MAC3B,GAAG,OAAO;AAAA,MACV;AAAA,IAAA;AAAA,EAEJ;AAGA,QAAM,kBAAkB,MAAM,uBAAuB;AACrD,MAAI,mBAAmB,kBAAkB,GAAG;AAC1C,WAAO,0BAA0B;AAAA,MAC/B,GAAG,OAAO;AAAA,MACV;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO;AACT;AAWO,SAAS,iBACd,OACwB;AACxB,MAAI,CAAC,MAAO,QAAO;AAEnB,QAAM,SAAS,eAAe;AAAA,IAC5B,cAAc,MAAM,gBAAgB;AAAA,IACpC,kBAAkB,MAAM,iBAAiB;AAAA,IACzC,aAAa,MAAM,gBAAgB;AAAA,EAAA,CACpC;AAKD,QAAM,eAAe,MAAM;AAG3B,QAAM,sBAAsB;AAAA,IAC1B,GAAI,cAAc,cACd,EAAE,YAAY,aAAa,YAAA,IAC3B,CAAA;AAAA,IACJ,GAAI,cAAc,eACd,EAAE,aAAa,aAAa,aAAA,IAC5B,CAAA;AAAA,EAAC;AAEP,MAAI,OAAO,KAAK,mBAAmB,EAAE,SAAS,GAAG;AAC/C,WAAO,sBAAsB;AAAA,EAC/B;AAEA,SAAO;AACT;"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Extract `headers` and `signal` from a `Request | RequestInit` for the OpenAI
3
+ * SDK's per-call `RequestOptions`. `Request` exposes `headers` as a `Headers`
4
+ * instance (HeadersInit-compatible) while `RequestInit` exposes `HeadersInit`
5
+ * directly — this helper accepts either shape so callers don't need to cast.
6
+ *
7
+ * Always returns an object (possibly empty) rather than `undefined` so test
8
+ * assertions that match the second argument shape via `expect.anything()` /
9
+ * `expect.objectContaining()` keep working when no request override was set.
10
+ */
11
+ export declare function extractRequestOptions(request: Request | RequestInit | undefined): {
12
+ headers?: HeadersInit;
13
+ signal?: AbortSignal | null;
14
+ };
@@ -0,0 +1,11 @@
1
+ function extractRequestOptions(request) {
2
+ if (!request) return {};
3
+ return {
4
+ ...request.headers !== void 0 && { headers: request.headers },
5
+ ...request.signal != null && { signal: request.signal }
6
+ };
7
+ }
8
+ export {
9
+ extractRequestOptions
10
+ };
11
+ //# sourceMappingURL=request-options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-options.js","sources":["../../../src/utils/request-options.ts"],"sourcesContent":["/**\n * Extract `headers` and `signal` from a `Request | RequestInit` for the OpenAI\n * SDK's per-call `RequestOptions`. `Request` exposes `headers` as a `Headers`\n * instance (HeadersInit-compatible) while `RequestInit` exposes `HeadersInit`\n * directly — this helper accepts either shape so callers don't need to cast.\n *\n * Always returns an object (possibly empty) rather than `undefined` so test\n * assertions that match the second argument shape via `expect.anything()` /\n * `expect.objectContaining()` keep working when no request override was set.\n */\nexport function extractRequestOptions(\n request: Request | RequestInit | undefined,\n): { headers?: HeadersInit; signal?: AbortSignal | null } {\n if (!request) return {}\n // Conditional spread: under exactOptionalPropertyTypes the target's\n // `headers?: HeadersInit` and `signal?: AbortSignal | null` forbid an\n // explicit `undefined`. Omit the keys entirely when the source values\n // are absent so the OpenAI SDK sees `headers: undefined` as \"not set\"\n // rather than a present-but-undefined value.\n return {\n ...(request.headers !== undefined && { headers: request.headers }),\n ...(request.signal != null && { signal: request.signal }),\n }\n}\n"],"names":[],"mappings":"AAUO,SAAS,sBACd,SACwD;AACxD,MAAI,CAAC,QAAS,QAAO,CAAA;AAMrB,SAAO;AAAA,IACL,GAAI,QAAQ,YAAY,UAAa,EAAE,SAAS,QAAQ,QAAA;AAAA,IACxD,GAAI,QAAQ,UAAU,QAAQ,EAAE,QAAQ,QAAQ,OAAA;AAAA,EAAO;AAE3D;"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Recursively drop JSON-Schema `format` keywords whose value isn't in OpenAI's
3
+ * strict-mode allowlist. Pure — returns a fresh tree and never mutates `node`,
4
+ * so the caller's original tool definition is left intact.
5
+ *
6
+ * A property *named* `format` always has a schema (object/boolean) value, never
7
+ * a bare string, so it is preserved and recursed into; only the `format`
8
+ * *keyword* (whose value is a string) is subject to removal.
9
+ */
10
+ export declare function stripUnsupportedFormats(node: any): any;
11
+ /**
12
+ * Transform a JSON schema to be compatible with OpenAI's structured output requirements.
13
+ * OpenAI requires:
14
+ * - All properties must be in the `required` array
15
+ * - Optional fields should have null added to their type union
16
+ * - additionalProperties must be false for objects
17
+ * - String `format` keywords must be from a fixed allowlist (others are stripped)
18
+ *
19
+ * @param schema - JSON schema to transform
20
+ * @param originalRequired - Original required array (to know which fields were optional)
21
+ * @returns Transformed schema compatible with OpenAI structured output
22
+ */
23
+ export declare function makeStructuredOutputCompatible(schema: Record<string, any>, originalRequired?: Array<string>): Record<string, any>;
24
+ /**
25
+ * Returns `false` when `schema` cannot be made strict-compatible and must be
26
+ * sent with `strict: false`. Two ways that happens:
27
+ *
28
+ * 1. It uses a JSON-Schema keyword outside OpenAI's strict subset anywhere in
29
+ * the tree (`oneOf`/`allOf`/`not`/`$ref`/`$defs`).
30
+ * 2. It contains a *typeless* schema node — a property/items/anyOf entry with
31
+ * no `type` (nor `enum`/`const`/combinator), e.g. the `{}` that `z.any()`
32
+ * produces. Strict mode rejects typeless schemas.
33
+ *
34
+ * Conservative by design: for (1) keywords are matched as object keys, so a
35
+ * property literally named e.g. `oneOf` also trips it. That only costs that one
36
+ * tool its strict mode, which is strictly safer than a false "compatible"
37
+ * verdict that 400s the whole request.
38
+ */
39
+ export declare function isStrictModeCompatible(schema: unknown): boolean;
@@ -0,0 +1,145 @@
1
+ const SUPPORTED_STRING_FORMATS = /* @__PURE__ */ new Set([
2
+ "date-time",
3
+ "time",
4
+ "date",
5
+ "duration",
6
+ "email",
7
+ "hostname",
8
+ "ipv4",
9
+ "ipv6",
10
+ "uuid"
11
+ ]);
12
+ function stripUnsupportedFormats(node) {
13
+ if (Array.isArray(node)) return node.map(stripUnsupportedFormats);
14
+ if (node === null || typeof node !== "object") return node;
15
+ const out = {};
16
+ for (const [key, value] of Object.entries(node)) {
17
+ if (key === "format" && typeof value === "string" && !SUPPORTED_STRING_FORMATS.has(value)) {
18
+ continue;
19
+ }
20
+ out[key] = stripUnsupportedFormats(value);
21
+ }
22
+ return out;
23
+ }
24
+ function makeStructuredOutputCompatible(schema, originalRequired) {
25
+ return stripUnsupportedFormats(coerceStrictSchema(schema, originalRequired));
26
+ }
27
+ const STRICT_UNSUPPORTED_KEYWORDS = [
28
+ "oneOf",
29
+ "allOf",
30
+ "not",
31
+ "$ref",
32
+ "$defs",
33
+ "definitions"
34
+ ];
35
+ const TYPE_INDICATOR_KEYWORDS = [
36
+ "type",
37
+ "enum",
38
+ "const",
39
+ "anyOf",
40
+ "oneOf",
41
+ "allOf",
42
+ "$ref"
43
+ ];
44
+ function isStrictModeCompatible(schema) {
45
+ return !containsStrictUnsupportedKeyword(schema) && !containsTypelessSchema(schema);
46
+ }
47
+ function containsStrictUnsupportedKeyword(node) {
48
+ if (Array.isArray(node)) {
49
+ return node.some(containsStrictUnsupportedKeyword);
50
+ }
51
+ if (node === null || typeof node !== "object") return false;
52
+ for (const [key, value] of Object.entries(node)) {
53
+ if (STRICT_UNSUPPORTED_KEYWORDS.includes(key)) return true;
54
+ if (containsStrictUnsupportedKeyword(value)) return true;
55
+ }
56
+ return false;
57
+ }
58
+ function isTypelessSchema(node) {
59
+ if (node === null || typeof node !== "object" || Array.isArray(node)) {
60
+ return false;
61
+ }
62
+ return !TYPE_INDICATOR_KEYWORDS.some((key) => key in node);
63
+ }
64
+ function containsTypelessSchema(node) {
65
+ if (node === null || typeof node !== "object" || Array.isArray(node)) {
66
+ return false;
67
+ }
68
+ const schema = node;
69
+ const children = [];
70
+ if (schema.properties && typeof schema.properties === "object") {
71
+ children.push(...Object.values(schema.properties));
72
+ }
73
+ if (schema.items !== void 0) {
74
+ children.push(
75
+ ...Array.isArray(schema.items) ? schema.items : [schema.items]
76
+ );
77
+ }
78
+ if (Array.isArray(schema.anyOf)) {
79
+ children.push(...schema.anyOf);
80
+ }
81
+ return children.some(
82
+ (child) => isTypelessSchema(child) || containsTypelessSchema(child)
83
+ );
84
+ }
85
+ function coerceStrictSchema(schema, originalRequired) {
86
+ const result = { ...schema };
87
+ const required = originalRequired ?? (Array.isArray(result["required"]) ? result["required"] : []);
88
+ if (result.type === "object" && result.properties) {
89
+ const properties = { ...result.properties };
90
+ const allPropertyNames = Object.keys(properties);
91
+ for (const propName of allPropertyNames) {
92
+ let prop = properties[propName];
93
+ const wasOptional = !required.includes(propName);
94
+ if (prop.type === "object" && prop.properties) {
95
+ prop = coerceStrictSchema(prop, prop.required || []);
96
+ } else if (prop.type === "array" && prop.items) {
97
+ prop = {
98
+ ...prop,
99
+ items: coerceStrictSchema(prop.items, prop.items.required || [])
100
+ };
101
+ } else if (prop.anyOf) {
102
+ prop = coerceStrictSchema(prop, prop.required || []);
103
+ } else if (prop.oneOf) {
104
+ throw new Error(
105
+ "oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types"
106
+ );
107
+ }
108
+ if (wasOptional) {
109
+ if (prop.anyOf) {
110
+ if (!prop.anyOf.some((v) => v.type === "null")) {
111
+ prop = { ...prop, anyOf: [...prop.anyOf, { type: "null" }] };
112
+ }
113
+ } else if (prop.type && !Array.isArray(prop.type)) {
114
+ prop = { ...prop, type: [prop.type, "null"] };
115
+ } else if (Array.isArray(prop.type) && !prop.type.includes("null")) {
116
+ prop = { ...prop, type: [...prop.type, "null"] };
117
+ }
118
+ }
119
+ properties[propName] = prop;
120
+ }
121
+ result.properties = properties;
122
+ result.required = allPropertyNames;
123
+ result.additionalProperties = false;
124
+ }
125
+ if (result.type === "array" && result.items) {
126
+ result.items = coerceStrictSchema(result.items, result.items.required || []);
127
+ }
128
+ if (result.anyOf && Array.isArray(result.anyOf)) {
129
+ result.anyOf = result.anyOf.map(
130
+ (variant) => coerceStrictSchema(variant, variant.required || [])
131
+ );
132
+ }
133
+ if (result.oneOf) {
134
+ throw new Error(
135
+ "oneOf is not supported in OpenAI structured output schemas. Check the supported outputs here: https://platform.openai.com/docs/guides/structured-outputs#supported-types"
136
+ );
137
+ }
138
+ return result;
139
+ }
140
+ export {
141
+ isStrictModeCompatible,
142
+ makeStructuredOutputCompatible,
143
+ stripUnsupportedFormats
144
+ };
145
+ //# sourceMappingURL=schema-converter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"schema-converter.js","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 *\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) && !containsTypelessSchema(schema)\n )\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"],"names":[],"mappings":"AAQA,MAAM,+CAA+B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QAAQ,YAAY,CAAA,CAAE;AAAA,IAAA;AAAA,EAEtD;AAEA,MAAI,OAAO,OAAO;AAChB,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AAEA,SAAO;AACT;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/openai-base",
3
- "version": "0.9.3",
3
+ "version": "0.9.5",
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",
@@ -44,16 +44,16 @@
44
44
  ],
45
45
  "dependencies": {
46
46
  "openai": "^6.41.0",
47
- "@tanstack/ai-utils": "0.3.0"
47
+ "@tanstack/ai-utils": "0.3.1"
48
48
  },
49
49
  "peerDependencies": {
50
- "@tanstack/ai": "^0.36.0"
50
+ "@tanstack/ai": "^0.38.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@vitest/coverage-v8": "4.0.14",
54
54
  "vite": "^7.3.3",
55
55
  "zod": "^4.2.0",
56
- "@tanstack/ai": "0.36.0"
56
+ "@tanstack/ai": "0.38.0"
57
57
  },
58
58
  "scripts": {
59
59
  "build": "vite build",