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

api.chat.ts

121 lines3.7 KB

1import { createFileRoute } from '@tanstack/react-router'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 maxIterations,
6 toServerSentEventsResponse,
7} from '@tanstack/ai'
8import { createOpenaiChat } from '@tanstack/ai-openai'
9import { byokMissing, getByokKey } from '@tanstack/ai/byok/server'
10import { openaiByok } from '@tanstack/ai-openai/byok'
11import { BUDGET_OPTIONS, chooseBudget } from '@/chat/interrupts'
12import { itinerarySchema } from '@/chat/schema'
13import { bookStay, confirmPayment, lookupPlace } from '@/chat/tools'
14import type { ChatMiddleware } from '@tanstack/ai'
15​
16const SYSTEM_PROMPT =
17 'You are a concise trip desk. Use lookupPlace for city facts. ' +
18 'Use bookStay when the user wants a hotel. ' +
19 'When the user asks to pay, charge, or hold a payment, you must call confirmPayment. ' +
20 'confirmPayment is a demo hold, not a real card charge. Do not refuse that tool. ' +
21 'If the user sends a photo, name the place if you can and suggest a stay. ' +
22 'If the user sends a PDF, read the trip facts and help from those facts. ' +
23 'After you have enough, fill the itinerary structured output. ' +
24 'Keep spoken replies short.'
25​
26const tools = [
27 lookupPlace.server(async ({ city }) => ({
28 city,
29 blurb: `${city} rewards a slow walk and one long lunch.`,
30 sources: [
31 {
32 title: `${city} overview`,
33 url: `https://en.wikipedia.org/wiki/${encodeURIComponent(city)}`,
34 },
35 ],
36 })),
37 bookStay.server(async ({ city, nights }) => ({
38 ok: true,
39 confirmation: `Held ${nights} night(s) in ${city}`,
40 })),
41 confirmPayment.server(async ({ city, amount }) => ({
42 ok: true,
43 receipt: `Held $${amount} for ${city}`,
44 })),
46​
47const budgetMiddleware: ChatMiddleware<unknown, typeof chooseBudget> = {
48 name: 'choose-budget',
49 onInterruptBoundary(ctx) {
50 if (ctx.phase !== 'beforeModel' || ctx.parentRunId) return
51 const userTurns = ctx.messages.filter((message) => message.role === 'user')
52 if (userTurns.length !== 1) return
53 return {
54 interrupts: [
55 chooseBudget.interrupt({
56 key: 'budget',
57 reason: 'budget_required',
58 message: 'Pick a budget before the desk writes.',
59 payload: {
60 city: 'this trip',
61 options: [...BUDGET_OPTIONS],
62 },
63 }),
64 ],
65 }
66 },
68​
69function readModel(forwarded: unknown): 'gpt-5.5' | 'gpt-5.2' {
70 if (
71 typeof forwarded === 'object' &&
72 forwarded !== null &&
73 'model' in forwarded &&
74 (forwarded.model === 'gpt-5.5' || forwarded.model === 'gpt-5.2')
75 ) {
76 return forwarded.model
77 }
78 return 'gpt-5.5'
80​
81async function handle(request: Request): Promise<Response> {
82 const apiKey = getByokKey(request, openaiByok)
83 if (!apiKey) return byokMissing(openaiByok)
84​
85 let params
86 try {
87 params = await chatParamsFromRequestBody(await request.json())
88 } catch (error) {
89 return new Response(
90 error instanceof Error ? error.message : 'Bad request',
91 { status: 400 },
92 )
93 }
94​
95 const model = readModel(params.forwardedProps)
96 const stream = chat({
97 adapter: createOpenaiChat(model, apiKey),
98 messages: params.messages,
99 tools,
100 interrupts: [chooseBudget],
101 outputSchema: itinerarySchema,
102 stream: true,
103 systemPrompts: [SYSTEM_PROMPT],
104 agentLoopStrategy: maxIterations(8),
105 middleware: [budgetMiddleware],
106 threadId: params.threadId,
107 runId: params.runId,
108 ...(params.parentRunId ? { parentRunId: params.parentRunId } : {}),
109 ...(params.resume ? { resume: params.resume } : {}),
110 })
111​
112 return toServerSentEventsResponse(stream)
114​
115export const Route = createFileRoute('/api/chat')({
116 server: {
117 handlers: {
118 POST: async ({ request }) => handle(request),
119 },
120 },
121})