Open History to see the last commit
1import { createFileRoute } from "@tanstack/react-router";
2import { chat, maxIterations, toServerSentEventsResponse } from "@tanstack/ai";
3import { anthropicText } from "@tanstack/ai-anthropic";
4
5import {
6 getProducts,
7 recommendProductToolDef,
8} from "@/lib/product-tools";
9
10const SYSTEM_PROMPT = `You are a helpful assistant for a store that sells TanStack-themed products.
11
12You should be practical, friendly, and opinionated about helping teams choose the right product for their goals.
13
14CRITICAL INSTRUCTIONS - YOU MUST FOLLOW THIS EXACT WORKFLOW:
15
16When a user asks for a product recommendation:
171. FIRST: Use the getProducts tool (no parameters needed)
182. SECOND: Use the recommendProduct tool with the ID of the product you want to recommend
193. NEVER write a recommendation directly - ALWAYS use the recommendProduct tool
20
21IMPORTANT:
22- The recommendProduct tool will display the product in a special format
23- You MUST use recommendProduct for ANY product recommendation
24- ONLY recommend products from our inventory (use getProducts first)
25- The recommendProduct tool has a view details button
26- Do NOT describe the product yourself - let the recommendProduct tool do it
27`;
28
29export const Route = createFileRoute("/api/product-chat")({
30 server: {
31 handlers: {
32 POST: async ({ request }) => {
33 const requestSignal = request.signal;
34
35 if (requestSignal.aborted) {
36 return new Response(null, { status: 499 });
37 }
38
39 const abortController = new AbortController();
40
41 try {
42 const body = await request.json();
43 const { messages } = body;
44
45 const adapter = anthropicText("claude-haiku-4-5");
46
47 const stream = chat({
48 adapter,
49 tools: [
50 getProducts,
51 recommendProductToolDef,
52 ],
53 systemPrompts: [SYSTEM_PROMPT],
54 agentLoopStrategy: maxIterations(5),
55 messages,
56 abortController,
57 });
58
59 return toServerSentEventsResponse(stream, { abortController });
60 } catch (error: any) {
61 if (error.name === "AbortError" || abortController.signal.aborted) {
62 return new Response(null, { status: 499 });
63 }
64 return new Response(
65 JSON.stringify({ error: "Failed to process chat request" }),
66 {
67 status: 500,
68 headers: { "Content-Type": "application/json" },
69 }
70 );
71 }
72 },
73 },
74 },
75});