function toolDefinition<TInput, TOutput, TName>(config): ToolDefinition<TInput, TOutput, TName>;
定义于: activities/chat/tools/tool-definition.ts:183
创建一个同构工具定义,可以直接使用或实例化用于服务器/客户端
该定义包含所有工具元数据(名称、描述、schemas),并且可以
支持任何符合标准 JSON Schema 规范的库(Zod v4+、ArkType、Valibot 等)或纯 JSON Schema 对象。
TInput extends SchemaInput = SchemaInput
TOutput extends SchemaInput = SchemaInput
TName extends string = string
ToolDefinitionConfig<TInput, TOutput, TName>
ToolDefinition<TInput, TOutput, TName>
import { toolDefinition } from '@tanstack/ai';
import { z } from 'zod';
// Using Zod (natively supports Standard JSON Schema)
const addToCartTool = toolDefinition({
name: 'addToCart',
description: 'Add a guitar to the shopping cart (requires approval)',
needsApproval: true,
inputSchema: z.object({
guitarId: z.string(),
quantity: z.number(),
}),
outputSchema: z.object({
success: z.boolean(),
cartId: z.string(),
totalItems: z.number(),
}),
});
// Use directly in chat (server-side, no execute function)
chat({
tools: [addToCartTool],
// ...
});
// Or create server-side implementation
const addToCartServer = addToCartTool.server(async (args) => {
// args is typed as { guitarId: string; quantity: number }
return {
success: true,
cartId: 'CART_' + Date.now(),
totalItems: args.quantity,
};
});
// Or create client-side implementation
const addToCartClient = addToCartTool.client(async (args) => {
// Client-specific logic (e.g., localStorage)
return { success: true, cartId: 'local', totalItems: 1 };
});