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

tool-input-normalizer.ts

42 lines1.4 KB

1import { undoNullWidening } from '@tanstack/ai-utils'
2import { makeMistralStructuredOutputCompatibleWithMap } from './schema-converter'
3import type { JSONSchema, Tool } from '@tanstack/ai'
4import type { NullWideningMap } from '@tanstack/ai-utils'
5​
6export type ToolInputNormalizer = (toolName: string, input: unknown) => unknown
7​
8/**
9 * Per-request inverse of Mistral optional-null widening. Recomputes maps from
10 * each tool's input schema; duplicate names and non-strict schemas are left
11 * untouched so we never guess.
12 */
13export function createToolInputNormalizer(
14 tools: Array<Tool> | undefined,
15): ToolInputNormalizer {
16 const maps = new Map<string, NullWideningMap>()
17 const seenNames = new Set<string>()
18 const ambiguousNames = new Set<string>()
19​
20 for (const tool of tools ?? []) {
21 if (ambiguousNames.has(tool.name)) continue
22 if (seenNames.has(tool.name)) {
23 maps.delete(tool.name)
24 ambiguousNames.add(tool.name)
25 continue
26 }
27 seenNames.add(tool.name)
28​
29 const inputSchema = (tool.inputSchema ?? {
30 type: 'object',
31 properties: {},
32 required: [],
33 }) as JSONSchema
34 const { nullWideningMap } = makeMistralStructuredOutputCompatibleWithMap(
35 inputSchema,
36 inputSchema.required || [],
37 )
38 if (nullWideningMap) maps.set(tool.name, nullWideningMap)
39 }
40​
41 return (toolName, input) => undoNullWidening(input, maps.get(toolName))