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

custom-tool.ts

65 lines1.7 KB

1import type { JSONSchema, SchemaInput, Tool } from '@tanstack/ai'
2import type { CacheControl } from '../text/text-provider-options'
3​
4export interface CustomToolConfig {
5 /**
6 * The name of the tool.
7 */
8 name: string
9 type: 'custom'
10 /**
11 * A brief description of what the tool does. Tool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema.
12 */
13 description: string
14 /**
15 * This defines the shape of the input that your tool accepts and that the model will produce.
16 */
17 input_schema: {
18 type: 'object'
19 properties: Record<string, any> | null
20 required?: Array<string> | null
21 }
22​
23 cache_control?: CacheControl | null
25​
26export function convertCustomToolToAdapterFormat(tool: Tool): CustomToolConfig {
27 const metadata =
28 (tool.metadata as { cacheControl?: CacheControl | null } | undefined) || {}
29​
30 const jsonSchema = (tool.inputSchema ?? {
31 type: 'object',
32 properties: {},
33 required: [],
34 }) as JSONSchema
35​
36 const inputSchema = {
37 type: 'object' as const,
38 properties: jsonSchema.properties || null,
39 required: jsonSchema.required || null,
40 }
41​
42 return {
43 name: tool.name,
44 type: 'custom',
45 description: tool.description,
46 input_schema: inputSchema,
47 cache_control: metadata.cacheControl || null,
48 }
50​
51export function customTool(
52 name: string,
53 description: string,
54 inputSchema: SchemaInput,
55 cacheControl?: CacheControl | null,
56): Tool {
57 return {
58 name,
59 description,
60 inputSchema,
61 metadata: {
62 cacheControl,
63 },
64 }