Open History to see the last commit
1import {
2 chat,
3 chatParamsFromRequestBody,
4 maxIterations,
5 mergeAgentTools,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { openaiText } from '@tanstack/ai-openai'
9import { createController } from 'remix/router'
10import { serverTools } from '../../lib/guitar-tools.ts'
11import { routes } from '../../routes.ts'
12
13const SYSTEM_PROMPT = `You are a helpful assistant for a guitar store.
14
15When a user asks for a guitar recommendation:
161. FIRST: Use the getGuitars tool (no parameters needed)
172. SECOND: Use the recommendGuitar tool with the ID of the guitar you want to recommend
183. NEVER write a recommendation directly - ALWAYS use the recommendGuitar tool
19
20ONLY recommend guitars from our inventory (use getGuitars first).
21`
22
23export default createController(routes.chat, {
24 actions: {
25 async stream({ request }) {
26 let body: unknown
27 try {
28 body = await request.json()
29 } catch {
30 return new Response('Bad request', { status: 400 })
31 }
32
33 let params
34 try {
35 params = await chatParamsFromRequestBody(body)
36 } catch (error) {
37 return new Response(
38 error instanceof Error ? error.message : 'Bad request',
39 { status: 400 },
40 )
41 }
42
43 const abortController = new AbortController()
44 const mergedTools = mergeAgentTools(serverTools, params.tools)
45
46 try {
47 const stream = chat({
48 adapter: openaiText('gpt-5.6'),
49 tools: mergedTools,
50 systemPrompts: [SYSTEM_PROMPT],
51 agentLoopStrategy: maxIterations(20),
52 messages: params.messages,
53 threadId: params.threadId,
54 runId: params.runId,
55 abortController,
56 })
57
58 return toServerSentEventsResponse(stream, { abortController })
59 } catch (error) {
60 return new Response(
61 error instanceof Error ? error.message : 'An error occurred',
62 { status: 500 },
63 )
64 }
65 },
66 },
67})