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

app.ts

446 lines12.9 KB

1import { Hono } from 'hono'
2import {
3 chat,
4 chatParamsFromRequestBody,
5 EventType,
6 maxIterations,
7 mergeAgentTools,
8 toolDefinition,
9 toHttpResponse,
10 toServerSentEventsResponse,
11} from '@tanstack/ai'
12import { openaiText, OPENAI_CHAT_MODELS } from '@tanstack/ai-openai'
13import type { ModelMessage, StreamChunk, UIMessage } from '@tanstack/ai'
14import type { OpenAIChatModel } from '@tanstack/ai-openai'
15​
16const DEFAULT_OPENAI_MODEL = 'gpt-5.2'
17const OPENAI_CHAT_MODEL_NAMES: ReadonlySet<string> = new Set(OPENAI_CHAT_MODELS)
18​
19export const LIVE_RECIPE_SERVER_ERROR =
20 'OPENAI_API_KEY is required to run the live recipe example'
21​
22type RecipePrompt = {
23 messages: Array<ModelMessage | UIMessage>
24 systemPrompts: Array<string>
26​
27const recipeOutputSchema = {
28 type: 'object',
29 properties: {
30 title: { type: 'string' },
31 summary: { type: 'string' },
32 servings: { type: 'number' },
33 totalMinutes: { type: 'number' },
34 tags: { type: 'array', items: { type: 'string' } },
35 ingredients: {
36 type: 'array',
37 items: {
38 type: 'object',
39 properties: {
40 name: { type: 'string' },
41 amount: { type: 'string' },
42 pantry: { type: 'boolean' },
43 },
44 required: ['name', 'amount', 'pantry'],
45 additionalProperties: false,
46 },
47 },
48 steps: {
49 type: 'array',
50 items: {
51 type: 'object',
52 properties: {
53 title: { type: 'string' },
54 text: { type: 'string' },
55 minutes: { type: 'number' },
56 },
57 required: ['title', 'text', 'minutes'],
58 additionalProperties: false,
59 },
60 },
61 tips: { type: 'array', items: { type: 'string' } },
62 warnings: { type: 'array', items: { type: 'string' } },
63 revision: { type: 'number' },
64 fromPrompt: { type: 'array', items: { type: 'string' } },
65 },
66 required: [
67 'title',
68 'summary',
69 'servings',
70 'totalMinutes',
71 'tags',
72 'ingredients',
73 'steps',
74 'tips',
75 'warnings',
76 'revision',
77 'fromPrompt',
78 ],
79 additionalProperties: false,
81​
82const RECIPE_SYSTEM_PROMPT = `You are a live recipe assistant for a React Native streaming demo.
83​
84Always return exactly one complete recipe matching the provided structured output schema.
85Use the full conversation history. When the latest user message is a follow-up such as "make it vegan", "remove mushrooms", "less spicy", or "for 4 people", revise the previous assistant recipe instead of starting from scratch.
86Create a new recipe on every user turn, and make the revision field one higher than the latest previous recipe revision when one is present.
87Call useful server tools when pantry details, substitutions, nutrition, or allergen constraints would improve the recipe. Incorporate tool results into the final recipe, but do not mention internal tool mechanics to the user.
88Respect explicit constraints from the latest user message over earlier recipe details. If the user asks to remove an ingredient, do not include that ingredient. If the user changes serving count, update servings and ingredient amounts.
89Keep titles, summaries, steps, tips, and warnings concise.`
90​
91function isOpenAIChatModel(value: string): value is OpenAIChatModel {
92 return OPENAI_CHAT_MODEL_NAMES.has(value)
94​
95function getOpenAIModel(): OpenAIChatModel {
96 const configuredModel = process.env.OPENAI_MODEL ?? DEFAULT_OPENAI_MODEL
97 if (!isOpenAIChatModel(configuredModel)) {
98 throw new Error(
99 `OPENAI_MODEL must be one of the known @tanstack/ai-openai chat models. Received: ${configuredModel}`,
100 )
101 }
102 return configuredModel
104​
105function requireOpenAIApiKey(): string {
106 const apiKey = process.env.OPENAI_API_KEY
107 if (!apiKey) {
108 throw new Error(LIVE_RECIPE_SERVER_ERROR)
109 }
110 return apiKey
112​
113function supportsReasoning(model: OpenAIChatModel) {
114 return (
115 model.startsWith('gpt-5') ||
116 model.startsWith('o1') ||
117 model.startsWith('o3') ||
118 model.startsWith('o4')
119 )
121​
122/** Reasoning models stream a summary of their thinking. */
123function getOpenAIReasoning(model: OpenAIChatModel) {
124 if (!supportsReasoning(model)) return undefined
125 return { level: 'medium', summary: true } as const
127​
128export function createRecipePrompt(
129 messages: Array<ModelMessage | UIMessage>,
130): RecipePrompt {
131 return {
132 messages,
133 systemPrompts: [RECIPE_SYSTEM_PROMPT],
134 }
136​
137function isRecord(value: unknown): value is Record<string, unknown> {
138 return !!value && typeof value === 'object'
140​
141function readString(value: unknown, key: string): string {
142 if (!isRecord(value)) return ''
143 const field = value[key]
144 return typeof field === 'string' ? field : ''
146​
147function readNumber(value: unknown, key: string): number {
148 if (!isRecord(value)) return 0
149 const field = value[key]
150 return typeof field === 'number' ? field : 0
152​
153function readStringArray(value: unknown, key: string): Array<string> {
154 if (!isRecord(value)) return []
155 const field = value[key]
156 if (!Array.isArray(field)) return []
157 return field.filter((item): item is string => typeof item === 'string')
159​
160const getPantrySnapshot = toolDefinition({
161 name: 'getPantrySnapshot',
162 description:
163 'Return available pantry ingredients, fresh ingredients, and household dietary notes for recipe planning.',
164 inputSchema: {
165 type: 'object',
166 properties: {
167 focus: {
168 type: 'string',
169 description: 'The recipe planning focus for the pantry lookup.',
170 },
171 },
172 required: ['focus'],
173 additionalProperties: false,
174 },
175 outputSchema: {
176 type: 'object',
177 properties: {
178 staples: { type: 'array', items: { type: 'string' } },
179 fresh: { type: 'array', items: { type: 'string' } },
180 allergens: { type: 'array', items: { type: 'string' } },
181 notes: { type: 'string' },
182 },
183 required: ['staples', 'fresh', 'allergens', 'notes'],
184 additionalProperties: false,
185 },
186}).server((args) => {
187 const focus = readString(args, 'focus') || 'recipe planning'
188 return {
189 staples: [
190 'canned tomatoes',
191 'spaghetti',
192 'olive oil',
193 'chili flakes',
194 'white beans',
195 'brown rice',
196 'coconut milk',
197 ],
198 fresh: ['garlic', 'parsley', 'lemon', 'mushrooms', 'spinach'],
199 allergens: ['gluten'],
200 notes: `Pantry lookup for: ${focus}. Ask the model to adapt if the user removes an ingredient or changes servings.`,
201 }
202})
203​
204const suggestIngredientSubstitutions = toolDefinition({
205 name: 'suggestIngredientSubstitutions',
206 description:
207 'Suggest practical substitutions when the user removes ingredients or asks for dietary changes.',
208 inputSchema: {
209 type: 'object',
210 properties: {
211 ingredient: {
212 type: 'string',
213 description: 'Ingredient to replace or avoid.',
214 },
215 dietaryGoal: {
216 type: 'string',
217 description:
218 'Dietary goal such as vegan, gluten-free, mild, or high-protein.',
219 },
220 },
221 required: ['ingredient', 'dietaryGoal'],
222 additionalProperties: false,
223 },
224 outputSchema: {
225 type: 'object',
226 properties: {
227 replacements: { type: 'array', items: { type: 'string' } },
228 guidance: { type: 'string' },
229 },
230 required: ['replacements', 'guidance'],
231 additionalProperties: false,
232 },
233}).server((args) => {
234 const ingredient = readString(args, 'ingredient') || 'the removed ingredient'
235 const dietaryGoal = readString(args, 'dietaryGoal') || 'the requested diet'
236 return {
237 replacements: [
238 'white beans',
239 'spinach',
240 'roasted peppers',
241 'zucchini',
242 'chickpeas',
243 ],
244 guidance: `For ${dietaryGoal}, omit ${ingredient} entirely and choose replacements that preserve texture and protein without violating the latest user request.`,
245 }
246})
247​
248const estimateRecipeNutrition = toolDefinition({
249 name: 'estimateRecipeNutrition',
250 description:
251 'Provide rough nutrition guidance for a planned recipe and serving count.',
252 inputSchema: {
253 type: 'object',
254 properties: {
255 recipeIdea: {
256 type: 'string',
257 description: 'Short description of the recipe being planned.',
258 },
259 servings: {
260 type: 'number',
261 description: 'Number of servings requested by the user.',
262 },
263 },
264 required: ['recipeIdea', 'servings'],
265 additionalProperties: false,
266 },
267 outputSchema: {
268 type: 'object',
269 properties: {
270 perServing: {
271 type: 'object',
272 properties: {
273 calories: { type: 'number' },
274 proteinGrams: { type: 'number' },
275 fiberGrams: { type: 'number' },
276 },
277 required: ['calories', 'proteinGrams', 'fiberGrams'],
278 additionalProperties: false,
279 },
280 note: { type: 'string' },
281 },
282 required: ['perServing', 'note'],
283 additionalProperties: false,
284 },
285}).server((args) => {
286 const recipeIdea = readString(args, 'recipeIdea') || 'the planned recipe'
287 const servings = readNumber(args, 'servings') || 2
288 return {
289 perServing: {
290 calories: 420,
291 proteinGrams: 18,
292 fiberGrams: 9,
293 },
294 note: `Rough estimate for ${servings} servings of ${recipeIdea}; keep nutrition language approximate.`,
295 }
296})
297​
298const checkAllergenGuidance = toolDefinition({
299 name: 'checkAllergenGuidance',
300 description:
301 'Return allergen and safety guidance for ingredients or dietary constraints.',
302 inputSchema: {
303 type: 'object',
304 properties: {
305 ingredients: {
306 type: 'array',
307 items: { type: 'string' },
308 description: 'Ingredients the model is considering.',
309 },
310 dietaryConstraints: {
311 type: 'array',
312 items: { type: 'string' },
313 description: 'Constraints from the conversation.',
314 },
315 },
316 required: ['ingredients', 'dietaryConstraints'],
317 additionalProperties: false,
318 },
319 outputSchema: {
320 type: 'object',
321 properties: {
322 warnings: { type: 'array', items: { type: 'string' } },
323 guidance: { type: 'string' },
324 },
325 required: ['warnings', 'guidance'],
326 additionalProperties: false,
327 },
328}).server((args) => {
329 const ingredients = readStringArray(args, 'ingredients')
330 const dietaryConstraints = readStringArray(args, 'dietaryConstraints')
331 const warnings = ingredients.some((ingredient) =>
332 ingredient.toLowerCase().includes('spaghetti'),
333 )
334 ? ['Spaghetti usually contains gluten; use gluten-free pasta if needed.']
335 : []
336​
337 return {
338 warnings,
339 guidance: `Apply constraints: ${dietaryConstraints.join(', ') || 'none'}. Keep warnings practical and visible in the final recipe.`,
340 }
341})
342​
343const serverTools = [
344 getPantrySnapshot,
345 suggestIngredientSubstitutions,
346 estimateRecipeNutrition,
347 checkAllergenGuidance,
349​
350async function createChatStream(
351 body: unknown,
352): Promise<AsyncIterable<StreamChunk>> {
353 const params = await chatParamsFromRequestBody(body)
354 const recipePrompt = createRecipePrompt(params.messages)
355 requireOpenAIApiKey()
356 const model = getOpenAIModel()
357 const tools = mergeAgentTools(serverTools, params.tools)
358 const reasoning = getOpenAIReasoning(model)
359​
360 return chat({
361 adapter: openaiText(model),
362 tools,
363 messages: recipePrompt.messages,
364 systemPrompts: recipePrompt.systemPrompts,
365 threadId: params.threadId,
366 runId: params.runId,
367 parentRunId: params.parentRunId,
368 agentLoopStrategy: maxIterations(6),
369 outputSchema: recipeOutputSchema,
370 stream: true,
371 ...(reasoning ? { reasoning } : {}),
372 }) as AsyncIterable<StreamChunk>
374​
375function getErrorMessage(error: unknown): string {
376 return error instanceof Error ? error.message : 'Bad request'
378​
379function getRequestRunContext(body: unknown) {
380 if (!body || typeof body !== 'object') return {}
381​
382 const threadId =
383 'threadId' in body && typeof body.threadId === 'string'
384 ? body.threadId
385 : undefined
386 const runId =
387 'runId' in body && typeof body.runId === 'string' ? body.runId : undefined
388​
389 return {
390 ...(threadId ? { threadId } : {}),
391 ...(runId ? { runId } : {}),
392 }
394​
395async function* createErrorStream(
396 error: unknown,
397 body: unknown,
398): AsyncIterable<StreamChunk> {
399 const message = getErrorMessage(error)
400​
401 yield {
402 type: EventType.RUN_ERROR,
403 ...getRequestRunContext(body),
404 message,
405 code: 'REACT_NATIVE_EXAMPLE_SERVER_ERROR',
406 error: {
407 message,
408 code: 'REACT_NATIVE_EXAMPLE_SERVER_ERROR',
409 },
410 }
412​
413export const app = new Hono()
414​
415app.get('/health', (c) => c.json({ ok: true }))
416​
417app.post('/chat/http', async (c) => {
418 let body: unknown
419 try {
420 body = await c.req.json()
421 const stream = await createChatStream(body)
422 return toHttpResponse(stream, {
423 headers: {
424 'Content-Type': 'application/x-ndjson',
425 'Cache-Control': 'no-cache',
426 },
427 })
428 } catch (error) {
429 return toHttpResponse(createErrorStream(error, body), {
430 headers: {
431 'Content-Type': 'application/x-ndjson',
432 'Cache-Control': 'no-cache',
433 },
434 })
435 }
436})
437​
438app.post('/chat/sse', async (c) => {
439 let body: unknown
440 try {
441 body = await c.req.json()
442 return toServerSentEventsResponse(await createChatStream(body))
443 } catch (error) {
444 return toServerSentEventsResponse(createErrorStream(error, body))
445 }
446})