Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

function-tool.ts

64 lines1.9 KB

1import {
2 isStrictModeCompatible,
3 makeStructuredOutputCompatible,
4 stripUnsupportedFormats,
5} from '../utils/schema-converter'
6import type { FunctionTool as FunctionToolConfig } from 'openai/resources/responses/responses'
7import type { JSONSchema, Tool } from '@tanstack/ai'
8​
9export type { FunctionToolConfig }
10​
11/** @deprecated Renamed to `FunctionToolConfig`. Will be removed in a future release. */
12export type FunctionTool = FunctionToolConfig
13​
14/**
15 * Converts a standard Tool to OpenAI FunctionTool format.
16 *
17 * Tool schemas are already converted to JSON Schema in the ai layer.
18 * We apply OpenAI-specific transformations for strict mode:
19 * - All properties in required array
20 * - Optional fields made nullable
21 * - additionalProperties: false
22 *
23 * This enables strict mode for all tools automatically.
24 *
25 * Some tool schemas (e.g. MCP server tools that use `oneOf`, `$ref`, or
26 * `$defs`) cannot be expressed under OpenAI's strict Structured Outputs
27 * subset. For those we fall back to a non-strict tool definition — stripping
28 * only the formats OpenAI rejects — so the tool is still usable instead of
29 * failing the request with a 400 "Invalid schema" error.
30 */
31export function convertFunctionToolToAdapterFormat(
32 tool: Tool,
33): FunctionToolConfig {
34 const inputSchema = (tool.inputSchema ?? {
35 type: 'object',
36 properties: {},
37 required: [],
38 }) as JSONSchema
39​
40 if (!isStrictModeCompatible(inputSchema)) {
41 return {
42 type: 'function',
43 name: tool.name,
44 description: tool.description,
45 parameters: stripUnsupportedFormats(inputSchema),
46 strict: false,
47 } satisfies FunctionToolConfig
48 }
49​
50 const jsonSchema = makeStructuredOutputCompatible(
51 inputSchema,
52 inputSchema.required || [],
53 )
54​
55 jsonSchema.additionalProperties = false
56​
57 return {
58 type: 'function',
59 name: tool.name,
60 description: tool.description,
61 parameters: jsonSchema,
62 strict: true,
63 } satisfies FunctionToolConfig