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

tools.ts

89 lines2.2 KB

1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3import guitars from '@/lib/guitar-data'
4​
5export const getGuitarsToolDef = toolDefinition({
6 name: 'getGuitars',
7 description: 'Get all guitars from inventory',
8 inputSchema: z.object({}),
9 outputSchema: z.array(
10 z.object({
11 id: z.number(),
12 name: z.string(),
13 shortDescription: z.string(),
14 price: z.number(),
15 }),
16 ),
17})
18​
19export const getGuitars = getGuitarsToolDef.server(() => {
20 return guitars.map((g) => ({
21 id: g.id,
22 name: g.name,
23 shortDescription: g.shortDescription,
24 price: g.price,
25 }))
26})
27​
28export const compareGuitarsToolDef = toolDefinition({
29 name: 'compareGuitars',
30 description: 'Compare two or more guitars side by side',
31 inputSchema: z.object({
32 guitarIds: z.array(z.number()).min(2),
33 }),
34 outputSchema: z.object({
35 comparison: z.array(
36 z.object({
37 id: z.number(),
38 name: z.string(),
39 price: z.number(),
40 }),
41 ),
42 cheapest: z.string(),
43 mostExpensive: z.string(),
44 }),
45})
46​
47export const compareGuitars = compareGuitarsToolDef.server((args) => {
48 const selected = args.guitarIds
49 .map((id) => guitars.find((g) => g.id === id))
50 .filter(Boolean) as typeof guitars
51​
52 if (selected.length === 0) {
53 return { comparison: [], cheapest: 'N/A', mostExpensive: 'N/A' }
54 }
55​
56 const prices = selected.map((g) => g.price)
57 return {
58 comparison: selected.map((g) => ({
59 id: g.id,
60 name: g.name,
61 price: g.price,
62 })),
63 cheapest: selected.find((g) => g.price === Math.min(...prices))!.name,
64 mostExpensive: selected.find((g) => g.price === Math.max(...prices))!.name,
65 }
66})
67​
68export const addToCartToolDef = toolDefinition({
69 name: 'addToCart',
70 description: 'Add a guitar to the shopping cart',
71 inputSchema: z.object({
72 guitarId: z.string(),
73 quantity: z.number(),
74 }),
75 outputSchema: z.object({
76 success: z.boolean(),
77 cartId: z.string(),
78 guitarId: z.string(),
79 quantity: z.number(),
80 }),
81 needsApproval: true,
82})
83​
84export const addToCart = addToCartToolDef.server((args) => ({
85 success: true,
86 cartId: 'CART_' + Date.now(),
87 guitarId: args.guitarId,
88 quantity: args.quantity,
89}))