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

guitar-tools.ts

291 lines8.2 KB

1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3import guitars from '@/data/example-guitars'
4​
5export const runtimeLoyaltyTiers = ['standard', 'gold', 'platinum'] as const
6export const runtimePreferredStyles = [
7 'acoustic',
8 'electric',
9 'experimental',
10] as const
11​
12export type RuntimeLoyaltyTier = (typeof runtimeLoyaltyTiers)[number]
13export type RuntimePreferredStyle = (typeof runtimePreferredStyles)[number]
14​
15export type ClientRuntimeContext = {
16 userId: string
17 tenantId: string
18 loyaltyTier: RuntimeLoyaltyTier
19 preferredStyle: RuntimePreferredStyle
21​
22export type ServerRuntimeContext = ClientRuntimeContext & {
23 requestSource: 'react-chat'
24 serverRegion: string
26​
27const runtimeContextBaseOutputSchema = z.object({
28 userId: z.string(),
29 tenantId: z.string(),
30 loyaltyTier: z.enum(runtimeLoyaltyTiers),
31 preferredStyle: z.enum(runtimePreferredStyles),
32})
33​
34export const inspectClientRuntimeContextToolDef = toolDefinition({
35 name: 'inspectClientRuntimeContext',
36 description: 'Read typed runtime context that is available in the browser.',
37 inputSchema: z.object({}),
38 outputSchema: runtimeContextBaseOutputSchema.extend({
39 source: z.literal('client'),
40 }),
41})
42​
43export const inspectServerRuntimeContextToolDef = toolDefinition({
44 name: 'inspectServerRuntimeContext',
45 description:
46 'Read typed runtime context that the server mapped from the chat request.',
47 inputSchema: z.object({}),
48 outputSchema: runtimeContextBaseOutputSchema.extend({
49 requestSource: z.literal('react-chat'),
50 serverRegion: z.string(),
51 source: z.literal('server'),
52 }),
53})
54​
55// Tool definition for getting guitars
56export const getGuitarsToolDef = toolDefinition({
57 name: 'getGuitars',
58 description: 'Get all products from the database',
59 inputSchema: z.object({}),
60 outputSchema: z.array(
61 z.object({
62 id: z.number(),
63 name: z.string(),
64 image: z.string(),
65 description: z.string(),
66 shortDescription: z.string(),
67 price: z.number(),
68 }),
69 ),
70})
71​
72// Server implementation
73export const getGuitars = getGuitarsToolDef.server((_, context) => {
74 context?.emitCustomEvent('tool:progress', {
75 tool: 'getGuitars',
76 message: `Fetching ${guitars.length} guitars from inventory`,
77 })
78 return guitars
79})
80​
81// Tool definition for guitar recommendation
82export const recommendGuitarToolDef = toolDefinition({
83 name: 'recommendGuitar',
84 description:
85 'REQUIRED tool to display a guitar recommendation to the user. This tool MUST be used whenever recommending a guitar - do NOT write recommendations yourself. This displays the guitar in a special appealing format with a buy button.',
86 inputSchema: z.object({
87 id: z
88 .union([z.string(), z.number()])
89 .describe(
90 'The ID of the guitar to recommend (from the getGuitars results)',
91 ),
92 }),
93 outputSchema: z.object({
94 id: z.number(),
95 }),
96})
97​
98// Tool definition for personal preference
99export const getPersonalGuitarPreferenceToolDef = toolDefinition({
100 name: 'getPersonalGuitarPreference',
101 description:
102 "Get the user's guitar preference from their local browser storage",
103 inputSchema: z.object({}),
104 outputSchema: z.object({
105 preference: z.string(),
106 }),
107})
108​
109// Tool definition for wish list (needs approval)
110export const addToWishListToolDef = toolDefinition({
111 name: 'addToWishList',
112 description: "Add a guitar to the user's wish list (requires approval)",
113 inputSchema: z.object({
114 guitarId: z.string(),
115 }),
116 outputSchema: z.object({
117 success: z.boolean(),
118 guitarId: z.string(),
119 totalItems: z.number(),
120 }),
121 needsApproval: true,
122})
123​
124// Tool definition for add to cart (server + client)
125export const addToCartToolDef = toolDefinition({
126 name: 'addToCart',
127 description: 'Add a guitar to the shopping cart (requires approval)',
128 inputSchema: z.object({
129 guitarId: z.string(),
130 quantity: z.number(),
131 }),
132 outputSchema: z.object({
133 success: z.boolean(),
134 cartId: z.string(),
135 guitarId: z.string(),
136 quantity: z.number(),
137 totalItems: z.number(),
138 }),
139 needsApproval: true,
140})
141​
142// --- Lazy tools (discovered on demand) ---
143​
144// Compare two or more guitars side by side
145export const compareGuitarsToolDef = toolDefinition({
146 name: 'compareGuitars',
147 description:
148 'Compare two or more guitars side by side, showing their differences in price, type, and features.',
149 inputSchema: z.object({
150 guitarIds: z
151 .array(z.number())
152 .min(2)
153 .describe('Array of guitar IDs to compare (minimum 2)'),
154 }),
155 outputSchema: z.object({
156 comparison: z.array(
157 z.object({
158 id: z.number(),
159 name: z.string(),
160 price: z.number(),
161 description: z.string(),
162 priceDifference: z.string(),
163 }),
164 ),
165 cheapest: z.string(),
166 mostExpensive: z.string(),
167 }),
168 lazy: true,
169})
170​
171export const compareGuitars = compareGuitarsToolDef.server((args) => {
172 const selected = args.guitarIds
173 .map((id) => guitars.find((g) => g.id === id))
174 .filter(Boolean) as (typeof guitars)[number][]
175​
176 const prices = selected.map((g) => g.price)
177 const minPrice = Math.min(...prices)
178 const maxPrice = Math.max(...prices)
179​
180 return {
181 comparison: selected.map((g) => ({
182 id: g.id,
183 name: g.name,
184 price: g.price,
185 description: g.shortDescription,
186 priceDifference:
187 g.price === minPrice
188 ? 'Cheapest'
189 : `+$${g.price - minPrice} more than cheapest`,
190 })),
191 cheapest: selected.find((g) => g.price === minPrice)!.name,
192 mostExpensive: selected.find((g) => g.price === maxPrice)!.name,
193 }
194})
195​
196// Calculate monthly financing for a guitar
197export const calculateFinancingToolDef = toolDefinition({
198 name: 'calculateFinancing',
199 description:
200 'Calculate monthly payment plans for a guitar purchase. Supports 6, 12, and 24 month terms.',
201 inputSchema: z.object({
202 guitarId: z
203 .number()
204 .describe('The ID of the guitar to calculate financing for'),
205 months: z
206 .number()
207 .describe('Number of months for the payment plan (6, 12, or 24)'),
208 }),
209 outputSchema: z.object({
210 guitarName: z.string(),
211 totalPrice: z.number(),
212 months: z.number(),
213 monthlyPayment: z.number(),
214 apr: z.number(),
215 totalWithInterest: z.number(),
216 }),
217 lazy: true,
218})
219​
220export const calculateFinancing = calculateFinancingToolDef.server((args) => {
221 const guitar = guitars.find((g) => g.id === args.guitarId)
222 if (!guitar) {
223 throw new Error(`Guitar with ID ${args.guitarId} not found`)
224 }
225​
226 const apr = args.months <= 6 ? 0 : args.months <= 12 ? 5.9 : 9.9
227 const monthlyRate = apr / 100 / 12
228 const monthlyPayment =
229 apr === 0
230 ? guitar.price / args.months
231 : (guitar.price * monthlyRate) /
232 (1 - Math.pow(1 + monthlyRate, -args.months))
233​
234 return {
235 guitarName: guitar.name,
236 totalPrice: guitar.price,
237 months: args.months,
238 monthlyPayment: Math.round(monthlyPayment * 100) / 100,
239 apr,
240 totalWithInterest: Math.round(monthlyPayment * args.months * 100) / 100,
241 }
242})
243​
244// Search guitars by features/keywords
245export const searchGuitarsToolDef = toolDefinition({
246 name: 'searchGuitars',
247 description:
248 'Search guitars by keyword in their name or description. Useful for finding guitars matching specific features like "acoustic", "electric", "LED", "vintage", etc.',
249 inputSchema: z.object({
250 query: z
251 .string()
252 .describe(
253 'Search keyword or phrase to match against guitar names and descriptions',
254 ),
255 }),
256 outputSchema: z.object({
257 results: z.array(
258 z.object({
259 id: z.number(),
260 name: z.string(),
261 price: z.number(),
262 shortDescription: z.string(),
263 matchedIn: z.string(),
264 }),
265 ),
266 totalFound: z.number(),
267 }),
268 lazy: true,
269})
270​
271export const searchGuitars = searchGuitarsToolDef.server((args) => {
272 const query = args.query.toLowerCase()
273 const results = guitars
274 .filter(
275 (g) =>
276 g.name.toLowerCase().includes(query) ||
277 g.description.toLowerCase().includes(query),
278 )
279 .map((g) => ({
280 id: g.id,
281 name: g.name,
282 price: g.price,
283 shortDescription: g.shortDescription,
284 matchedIn: g.name.toLowerCase().includes(query) ? 'name' : 'description',
285 }))
286​
287 return {
288 results,
289 totalFound: results.length,
290 }
291})