Open History to see the last commit
1import { fileURLToPath, URL } from 'node:url'
2import { defineConfig } from 'vite'
3import vue from '@vitejs/plugin-vue'
4import tailwindcss from '@tailwindcss/vite'
5import {
6 chat,
7 chatParamsFromRequestBody,
8 maxIterations,
9 mergeAgentTools,
10 toServerSentEventsStream,
11} from '@tanstack/ai'
12import { openaiText } from '@tanstack/ai-openai'
13import { anthropicText } from '@tanstack/ai-anthropic'
14import { geminiText } from '@tanstack/ai-gemini'
15import { ollamaText } from '@tanstack/ai-ollama'
16import { toolDefinition } from '@tanstack/ai'
17import { z } from 'zod'
18import dotenv from 'dotenv'
19
20// Load environment variables
21dotenv.config()
22
23// Guitar data (embedded for simplicity)
24const guitars = [
25 {
26 id: 1,
27 name: 'TanStack Ukelele',
28 image: '/example-ukelele-tanstack.jpg',
29 description:
30 'Premium koa-wood ukulele featuring exclusive TanStack branding.',
31 shortDescription: 'Premium koa-wood ukulele with TanStack branding.',
32 price: 299,
33 },
34 {
35 id: 2,
36 name: 'Video Game Guitar',
37 image: '/example-guitar-video-games.jpg',
38 description: 'A unique acoustic guitar with a video game design.',
39 shortDescription: 'Unique electric guitar with video game design.',
40 price: 699,
41 },
42 {
43 id: 3,
44 name: 'Superhero Guitar',
45 image: '/example-guitar-superhero.jpg',
46 description: 'Bold black electric guitar with superhero logo design.',
47 shortDescription: 'Bold black electric guitar with superhero logo.',
48 price: 699,
49 },
50 {
51 id: 4,
52 name: 'Motherboard Guitar',
53 image: '/example-guitar-motherboard.jpg',
54 description: 'Tech-inspired electric guitar with LED lights.',
55 shortDescription: 'Tech-inspired guitar with LED lights.',
56 price: 649,
57 },
58 {
59 id: 5,
60 name: 'Racing Guitar',
61 image: '/example-guitar-racing.jpg',
62 description: 'Aerodynamic guitar with racing stripes.',
63 shortDescription: 'Aerodynamic guitar with racing stripes.',
64 price: 679,
65 },
66 {
67 id: 6,
68 name: 'Steamer Trunk Guitar',
69 image: '/example-guitar-steamer-trunk.jpg',
70 description: 'Semi-hollow body guitar with brass hardware.',
71 shortDescription: 'Semi-hollow body guitar with brass hardware.',
72 price: 629,
73 },
74 {
75 id: 7,
76 name: "Travelin' Man Guitar",
77 image: '/example-guitar-traveling.jpg',
78 description: 'Acoustic guitar with vintage postcards.',
79 shortDescription: 'Acoustic guitar with vintage postcards.',
80 price: 499,
81 },
82 {
83 id: 8,
84 name: 'Flowerly Love Guitar',
85 image: '/example-guitar-flowers.jpg',
86 description: 'Acoustic guitar with hand-painted floral designs.',
87 shortDescription: 'Acoustic guitar with floral designs.',
88 price: 599,
89 },
90]
91
92// Tool definitions
93const getGuitarsToolDef = toolDefinition({
94 name: 'getGuitars',
95 description: 'Get all products from the database',
96 inputSchema: z.object({}),
97 outputSchema: z.array(
98 z.object({
99 id: z.number(),
100 name: z.string(),
101 image: z.string(),
102 description: z.string(),
103 shortDescription: z.string(),
104 price: z.number(),
105 }),
106 ),
107})
108
109const getGuitars = getGuitarsToolDef.server(() => guitars)
110
111const recommendGuitarToolDef = toolDefinition({
112 name: 'recommendGuitar',
113 description: 'REQUIRED tool to display a guitar recommendation to the user.',
114 inputSchema: z.object({
115 id: z
116 .union([z.string(), z.number()])
117 .describe('The ID of the guitar to recommend'),
118 }),
119 outputSchema: z.object({ id: z.number() }),
120})
121
122const getPersonalGuitarPreferenceToolDef = toolDefinition({
123 name: 'getPersonalGuitarPreference',
124 description:
125 "Get the user's guitar preference from their local browser storage",
126 inputSchema: z.object({}),
127 outputSchema: z.object({ preference: z.string() }),
128})
129
130const addToWishListToolDef = toolDefinition({
131 name: 'addToWishList',
132 description: "Add a guitar to the user's wish list (requires approval)",
133 inputSchema: z.object({ guitarId: z.string() }),
134 outputSchema: z.object({
135 success: z.boolean(),
136 guitarId: z.string(),
137 totalItems: z.number(),
138 }),
139 needsApproval: true,
140})
141
142const addToCartToolDef = toolDefinition({
143 name: 'addToCart',
144 description: 'Add a guitar to the shopping cart (requires approval)',
145 inputSchema: z.object({
146 guitarId: z.string(),
147 quantity: z.number(),
148 }),
149 outputSchema: z.object({
150 success: z.boolean(),
151 cartId: z.string(),
152 guitarId: z.string(),
153 quantity: z.number(),
154 totalItems: z.number(),
155 }),
156 needsApproval: true,
157})
158
159const addToCartToolServer = addToCartToolDef.server((args) => ({
160 success: true,
161 cartId: 'CART_' + Date.now(),
162 guitarId: args.guitarId,
163 quantity: args.quantity,
164 totalItems: args.quantity,
165}))
166
167const SYSTEM_PROMPT = `You are a helpful assistant for a guitar store.
168
169CRITICAL INSTRUCTIONS - YOU MUST FOLLOW THIS EXACT WORKFLOW:
170
171When a user asks for a guitar recommendation:
1721. FIRST: Use the getGuitars tool (no parameters needed)
1732. SECOND: Use the recommendGuitar tool with the ID of the guitar you want to recommend
1743. NEVER write a recommendation directly - ALWAYS use the recommendGuitar tool
175
176IMPORTANT:
177- The recommendGuitar tool will display the guitar in a special, appealing format
178- You MUST use recommendGuitar for ANY guitar recommendation
179- ONLY recommend guitars from our inventory (use getGuitars first)
180- The recommendGuitar tool has a buy button - this is how customers purchase
181- Do NOT describe the guitar yourself - let the recommendGuitar tool do it
182`
183
184type Provider = 'openai' | 'anthropic' | 'gemini' | 'ollama'
185
186export default defineConfig({
187 plugins: [
188 vue(),
189 tailwindcss(),
190 {
191 name: 'api-handler',
192 configureServer(server) {
193 server.middlewares.use('/api/chat', async (req, res) => {
194 if (req.method !== 'POST') {
195 res.statusCode = 405
196 res.end('Method Not Allowed')
197 return
198 }
199
200 let body = ''
201 for await (const chunk of req) {
202 body += chunk
203 }
204
205 let params
206 try {
207 params = await chatParamsFromRequestBody(JSON.parse(body))
208 } catch (error) {
209 res.statusCode = 400
210 res.end(error instanceof Error ? error.message : 'Bad request')
211 return
212 }
213
214 try {
215 const fp = params.forwardedProps as Record<string, unknown>
216 const provider: Provider =
217 typeof fp.provider === 'string'
218 ? (fp.provider as Provider)
219 : 'openai'
220 const model: string | undefined =
221 typeof fp.model === 'string' ? fp.model : undefined
222
223 let adapter
224
225 let selectedModel: string
226
227 switch (provider) {
228 case 'anthropic':
229 selectedModel = model || 'claude-sonnet-4-5-20250929'
230 adapter = anthropicText(selectedModel)
231 break
232 case 'gemini':
233 selectedModel = model || 'gemini-2.5-flash'
234 adapter = geminiText(selectedModel)
235 break
236 case 'ollama':
237 selectedModel = model || 'mistral:7b'
238 adapter = ollamaText(selectedModel)
239 break
240 case 'openai':
241 default:
242 selectedModel = model || 'gpt-4o'
243 adapter = openaiText(selectedModel)
244 break
245 }
246
247 console.log(
248 `[API] Using provider: ${provider}, model: ${selectedModel}`,
249 )
250
251 const abortController = new AbortController()
252
253 const serverTools = Object.fromEntries(
254 [getGuitars, addToCartToolServer].map((t) => [t.name, t]),
255 )
256
257 const stream = chat({
258 adapter,
259 tools: mergeAgentTools(serverTools, params.tools),
260 systemPrompts: [SYSTEM_PROMPT],
261 agentLoopStrategy: maxIterations(20),
262 messages: params.messages,
263 threadId: params.threadId,
264 runId: params.runId,
265 abortController,
266 })
267
268 const readableStream = toServerSentEventsStream(
269 stream,
270 abortController,
271 )
272
273 // Set headers
274 res.setHeader('Content-Type', 'text/event-stream')
275 res.setHeader('Cache-Control', 'no-cache')
276 res.setHeader('Connection', 'keep-alive')
277
278 // Stream the body
279 const reader = readableStream.getReader()
280 const pump = async () => {
281 while (true) {
282 const { done, value } = await reader.read()
283 if (done) break
284 res.write(value)
285 }
286 res.end()
287 }
288 pump().catch((err) => {
289 console.error('Stream error:', err)
290 res.end()
291 })
292 } catch (error: any) {
293 console.error('[API] Error:', error)
294 res.statusCode = 500
295 res.setHeader('Content-Type', 'application/json')
296 res.end(
297 JSON.stringify({ error: error.message || 'An error occurred' }),
298 )
299 }
300 })
301 },
302 },
303 ],
304 resolve: {
305 alias: {
306 '@': fileURLToPath(new URL('./src', import.meta.url)),
307 },
308 },
309})