Open History to see the last commit
1/**
2 * defineTool and defineTools Examples
3 *
4 * This example demonstrates the new type-safe tool definition utilities that provide:
5 * 1. Automatic type inference for execute function arguments
6 * 2. Cleaner, more concise tool definitions
7 * 3. Full TypeScript autocomplete and validation
8 * 4. Better developer experience
9 */
11import { AI, defineTool, defineTools } from "@tanstack/ai";
12import { OpenAIAdapter } from "@tanstack/ai-openai";
14// ============================================
15// Example 1: Using defineTool for single tool
16// ============================================
18const getWeatherTool = defineTool({
19 name: "getWeather",
20 description: "Get the current weather for a location",
21 parameters: {
22 type: "object",
23 properties: {
24 location: {
25 type: "string",
26 description: "City name (e.g., 'New York', 'London')",
27 },
28 units: {
29 type: "string",
30 description: "Temperature units: 'celsius' or 'fahrenheit'",
31 },
32 },
33 required: ["location"], // Only location is required
34 },
35 execute: async (args) => {
36 // ✨ args is automatically typed as:
37 // { location: string; units?: string }
39 console.log("Location:", args.location); // ✅ Type-safe!
40 console.log("Units:", args.units); // ✅ Optional, type-safe!
42 // Simulate API call
43 return JSON.stringify({
44 location: args.location,
45 temperature: 72,
46 units: args.units || "fahrenheit",
47 condition: "sunny",
48 });
49 },
50});
52// ============================================
53// Example 2: Using defineTools for multiple tools
54// ============================================
56const tools = defineTools({
57 getWeather: {
58 description: "Get the current weather for a location",
59 parameters: {
60 type: "object",
61 properties: {
62 location: { type: "string", description: "City name" },
63 units: { type: "string", description: "celsius or fahrenheit" },
64 },
65 required: ["location"],
66 },
67 execute: async (args) => {
68 // ✨ args automatically typed as { location: string; units?: string }
69 return JSON.stringify({ temp: 72, condition: "sunny" });
70 },
71 },
73 getTime: {
74 description: "Get the current time in a timezone",
75 parameters: {
76 type: "object",
77 properties: {
78 timezone: {
79 type: "string",
80 description: "IANA timezone (e.g., 'America/New_York')",
81 },
82 },
83 required: [], // All properties optional
84 },
85 execute: async (args) => {
86 // ✨ args automatically typed as { timezone?: string }
87 const tz = args.timezone || "UTC";
88 return new Date().toLocaleString("en-US", { timeZone: tz });
89 },
90 },
92 calculateSum: {
93 description: "Calculate the sum of two numbers",
94 parameters: {
95 type: "object",
96 properties: {
97 a: { type: "number", description: "First number" },
98 b: { type: "number", description: "Second number" },
99 },
100 required: ["a", "b"],
101 },
102 execute: async (args) => {
103 // ✨ args automatically typed as { a: number; b: number }
104 const sum = args.a + args.b;
105 return `The sum of ${args.a} and ${args.b} is ${sum}`;
106 },
107 },
109 searchDatabase: {
110 description: "Search the database with optional filters",
111 parameters: {
112 type: "object",
113 properties: {
114 query: { type: "string", description: "Search query" },
115 limit: { type: "number", description: "Max results" },
116 category: { type: "string", description: "Category filter" },
117 },
118 required: ["query"],
119 },
120 execute: async (args) => {
121 // ✨ args automatically typed as:
122 // { query: string; limit?: number; category?: string }
124 console.log("Search query:", args.query); // Required
125 console.log("Limit:", args.limit ?? 10); // Optional with default
126 console.log("Category:", args.category); // Optional
128 return JSON.stringify({ results: [], total: 0 });
129 },
130 },
131});
133// ============================================
134// Example 3: Using tools with AI instance
135// ============================================
137const ai = new AI({
138 adapters: {
139 openai: new OpenAIAdapter({
140 apiKey: process.env.OPENAI_API_KEY!,
141 }),
142 },
143 tools, // ← Pass tools object directly
144});
146async function chatWithTools() {
147 const result = await ai.chat({
148 adapter: "openai",
149 model: "gpt-4",
150 messages: [
151 { role: "user", content: "What's the weather in New York?" },
152 ],
153 tools: ["getWeather"], // ✨ Type-safe! Autocomplete shows available tools
154 });
156 console.log("Response:", result.content);
157}
159// ============================================
160// Example 4: Before vs After Comparison
161// ============================================
163// ❌ BEFORE: Verbose, manual typing, error-prone
164const oldStyleTools = {
165 getWeather: {
166 type: "function" as const,
167 function: {
168 name: "getWeather",
169 description: "Get the current weather",
170 parameters: {
171 type: "object",
172 properties: {
173 location: { type: "string" },
174 },
175 required: ["location"],
176 },
177 },
178 execute: async ({ location }: { location: string }) => {
179 // Have to manually type args ^^^
180 return JSON.stringify({ temp: 72 });
181 },
182 },
183} as const;
185// ✅ AFTER: Concise, auto-typed, type-safe
186const newStyleTools = defineTools({
187 getWeather: {
188 description: "Get the current weather",
189 parameters: {
190 type: "object",
191 properties: {
192 location: { type: "string" },
193 },
194 required: ["location"],
195 },
196 execute: async (args) => {
197 // args automatically typed! ✨
198 return JSON.stringify({ temp: 72 });
199 },
200 },
201});
203// ============================================
204// Example 5: Complex parameter types
205// ============================================
207const advancedTools = defineTools({
208 updateUser: {
209 description: "Update user information",
210 parameters: {
211 type: "object",
212 properties: {
213 userId: { type: "string", description: "User ID" },
214 name: { type: "string", description: "User name" },
215 email: { type: "string", description: "User email" },
216 age: { type: "number", description: "User age" },
217 active: { type: "boolean", description: "Is user active" },
218 tags: { type: "array", description: "User tags" },
219 metadata: { type: "object", description: "Additional metadata" },
220 },
221 required: ["userId"],
222 },
223 execute: async (args) => {
224 // ✨ args typed as:
225 // {
226 // userId: string;
227 // name?: string;
228 // email?: string;
229 // age?: number;
230 // active?: boolean;
231 // tags?: any[];
232 // metadata?: Record<string, any>;
233 // }
235 console.log("Updating user:", args.userId);
236 if (args.name) console.log("New name:", args.name);
237 if (args.email) console.log("New email:", args.email);
238 if (args.age !== undefined) console.log("New age:", args.age);
240 return JSON.stringify({ success: true });
241 },
242 },
243});
245// ============================================
246// Example 6: Combining defineTool with defineTools
247// ============================================
249// Define some tools individually
250const weatherTool = defineTool({
251 name: "getWeather",
252 description: "Get weather",
253 parameters: {
254 type: "object",
255 properties: {
256 location: { type: "string" },
257 },
258 required: ["location"],
259 },
260 execute: async (args) => JSON.stringify({ temp: 72 }),
261});
263// Define others as a group
264const utilityTools = defineTools({
265 getTime: {
266 description: "Get current time",
267 parameters: {
268 type: "object",
269 properties: {},
270 required: [],
271 },
272 execute: async () => new Date().toISOString(),
273 },
274 getDate: {
275 description: "Get current date",
276 parameters: {
277 type: "object",
278 properties: {},
279 required: [],
280 },
281 execute: async () => new Date().toDateString(),
282 },
283});
285// Combine them
286const allTools = {
287 ...utilityTools,
288 weather: weatherTool,
289};
291// ============================================
292// Example 7: Real-world e-commerce example
293// ============================================
295interface Product {
296 id: string;
297 name: string;
298 price: number;
299 inStock: boolean;
300}
302const products: Product[] = [
303 { id: "1", name: "Guitar", price: 599, inStock: true },
304 { id: "2", name: "Amplifier", price: 299, inStock: true },
305 { id: "3", name: "Drum Kit", price: 899, inStock: false },
306];
308const ecommerceTools = defineTools({
309 getProducts: {
310 description: "Get all products from the catalog",
311 parameters: {
312 type: "object",
313 properties: {
314 category: { type: "string", description: "Filter by category" },
315 inStockOnly: { type: "boolean", description: "Show only in-stock items" },
316 },
317 required: [],
318 },
319 execute: async (args) => {
320 let filtered = products;
322 if (args.inStockOnly) {
323 filtered = filtered.filter(p => p.inStock);
324 }
326 return JSON.stringify(filtered);
327 },
328 },
330 getProductDetails: {
331 description: "Get detailed information about a specific product",
332 parameters: {
333 type: "object",
334 properties: {
335 productId: { type: "string", description: "Product ID" },
336 },
337 required: ["productId"],
338 },
339 execute: async (args) => {
340 const product = products.find(p => p.id === args.productId);
342 if (!product) {
343 return JSON.stringify({ error: "Product not found" });
344 }
346 return JSON.stringify(product);
347 },
348 },
350 checkInventory: {
351 description: "Check if a product is in stock",
352 parameters: {
353 type: "object",
354 properties: {
355 productId: { type: "string", description: "Product ID" },
356 quantity: { type: "number", description: "Desired quantity" },
357 },
358 required: ["productId"],
359 },
360 execute: async (args) => {
361 const product = products.find(p => p.id === args.productId);
363 if (!product) {
364 return JSON.stringify({ available: false, reason: "Product not found" });
365 }
367 return JSON.stringify({
368 available: product.inStock,
369 productName: product.name,
370 requestedQuantity: args.quantity || 1,
371 });
372 },
373 },
374});
376const ecommerceAI = new AI({
377 adapters: {
378 openai: new OpenAIAdapter({ apiKey: process.env.OPENAI_API_KEY! }),
379 },
380 tools: ecommerceTools,
381 systemPrompts: [
382 "You are a helpful e-commerce assistant.",
383 "Use the available tools to help customers find and purchase products.",
384 ],
385});
387async function handleCustomerQuery() {
388 const result = await ecommerceAI.chat({
389 adapter: "openai",
390 model: "gpt-4",
391 messages: [
392 { role: "user", content: "Show me guitars that are in stock" },
393 ],
394 tools: ["getProducts", "getProductDetails", "checkInventory"],
395 });
397 console.log("Assistant:", result.content);
398}
400// ============================================
401// Example 8: Type inference demonstration
402// ============================================
404const typedTools = defineTools({
405 // All required parameters
406 strictTool: {
407 description: "All parameters required",
408 parameters: {
409 type: "object",
410 properties: {
411 name: { type: "string" },
412 age: { type: "number" },
413 },
414 required: ["name", "age"],
415 },
416 execute: async (args) => {
417 // args: { name: string; age: number }
418 // No optional properties!
419 const name: string = args.name; // ✅
420 const age: number = args.age; // ✅
421 return `${name} is ${age} years old`;
422 },
423 },
425 // No required parameters
426 flexibleTool: {
427 description: "All parameters optional",
428 parameters: {
429 type: "object",
430 properties: {
431 filter: { type: "string" },
432 limit: { type: "number" },
433 },
434 required: [],
435 },
436 execute: async (args) => {
437 // args: { filter?: string; limit?: number }
438 // All properties optional!
439 const filter = args.filter ?? "all";
440 const limit = args.limit ?? 10;
441 return `Showing ${limit} results for ${filter}`;
442 },
443 },
445 // Mixed required/optional
446 mixedTool: {
447 description: "Some required, some optional",
448 parameters: {
449 type: "object",
450 properties: {
451 userId: { type: "string" },
452 update: { type: "string" },
453 notify: { type: "boolean" },
454 },
455 required: ["userId"], // Only userId is required
456 },
457 execute: async (args) => {
458 // args: { userId: string; update?: string; notify?: boolean }
459 console.log("User:", args.userId); // Required
460 console.log("Update:", args.update); // Optional
461 console.log("Notify:", args.notify); // Optional
462 return "Done";
463 },
464 },
465});
467// ============================================
468// Example 9: Error handling
469// ============================================
471const robustTools = defineTools({
472 processData: {
473 description: "Process data with error handling",
474 parameters: {
475 type: "object",
476 properties: {
477 data: { type: "string", description: "JSON data to process" },
478 },
479 required: ["data"],
480 },
481 execute: async (args) => {
482 try {
483 const parsed = JSON.parse(args.data);
484 return JSON.stringify({ success: true, result: parsed });
485 } catch (error) {
486 return JSON.stringify({
487 success: false,
488 error: "Invalid JSON data",
489 });
490 }
491 },
492 },
493});
495// ============================================
496// Example 10: Async operations
497// ============================================
499const asyncTools = defineTools({
500 fetchData: {
501 description: "Fetch data from an API",
502 parameters: {
503 type: "object",
504 properties: {
505 url: { type: "string", description: "API endpoint" },
506 timeout: { type: "number", description: "Timeout in ms" },
507 },
508 required: ["url"],
509 },
510 execute: async (args) => {
511 // Simulate API call
512 await new Promise(resolve =>
513 setTimeout(resolve, args.timeout || 1000)
514 );
516 return JSON.stringify({
517 url: args.url,
518 data: { message: "Data fetched successfully" },
519 });
520 },
521 },
522});
524// Run examples
525async function main() {
526 console.log("=== Example 3: Chat with tools ===");
527 await chatWithTools();
529 console.log("\n=== Example 7: E-commerce ===");
530 await handleCustomerQuery();
531}
533// Uncomment to run:
534// main().catch(console.error);
536export {
537 getWeatherTool,
538 tools,
539 advancedTools,
540 ecommerceTools,
541 typedTools,
542 robustTools,
543 asyncTools,
544};