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

function-tool.ts

42 lines1.3 KB

1import { makeMistralStructuredOutputCompatibleWithMap } from '../utils/schema-converter'
2import type { JSONSchema, Tool } from '@tanstack/ai'
3import type { ChatCompletionTool } from '../message-types'
4​
5export type FunctionTool = ChatCompletionTool
6​
7/**
8 * Converts a standard Tool to Mistral ChatCompletionTool format.
9 *
10 * Tool schemas are already JSON Schema in the ai layer. When the schema can
11 * be inverted, rewrite it for strict mode (required, nullable optionals,
12 * `additionalProperties: false`) and set `strict: true`. Otherwise leave the
13 * schema intact and set `strict: false`.
14 */
15export function convertFunctionToolToAdapterFormat(tool: Tool): FunctionTool {
16 const baseSchema = (tool.inputSchema ?? {
17 type: 'object',
18 properties: {},
19 required: [],
20 }) as JSONSchema
21​
22 const inputSchema: JSONSchema =
23 baseSchema.type === 'object' && !baseSchema.properties
24 ? { ...baseSchema, properties: {} }
25 : { ...baseSchema }
26​
27 const { schema: jsonSchema, strict } =
28 makeMistralStructuredOutputCompatibleWithMap(
29 inputSchema,
30 inputSchema.required || [],
31 )
32​
33 return {
34 type: 'function',
35 function: {
36 name: tool.name,
37 description: tool.description,
38 parameters: jsonSchema,
39 strict,
40 },
41 } satisfies FunctionTool