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

function-tool.ts

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