Open History to see the last commit
1import { createFileRoute } from '@tanstack/react-router'
2import { chat } from '@tanstack/ai'
3import { anthropicText } from '@tanstack/ai-anthropic'
4import { geminiText } from '@tanstack/ai-gemini'
5import { grokText } from '@tanstack/ai-grok'
6import { openaiText } from '@tanstack/ai-openai'
7import { ollamaText } from '@tanstack/ai-ollama'
8import { openRouterText } from '@tanstack/ai-openrouter'
9import { z } from 'zod'
10import type { AnyTextAdapter } from '@tanstack/ai'
11
12type Provider =
13 | 'openai'
14 | 'anthropic'
15 | 'gemini'
16 | 'ollama'
17 | 'grok'
18 | 'openrouter'
19
20// Schema for structured recipe output
21const RecipeSchema = z.object({
22 name: z.string().describe('The name of the recipe'),
23 description: z.string().describe('A brief description of the dish'),
24 prepTime: z.string().describe('Preparation time (e.g., "15 minutes")'),
25 cookTime: z.string().describe('Cooking time (e.g., "30 minutes")'),
26 servings: z.number().describe('Number of servings'),
27 difficulty: z.enum(['easy', 'medium', 'hard']).describe('Difficulty level'),
28 ingredients: z
29 .array(
30 z.object({
31 item: z.string().describe('Ingredient name'),
32 amount: z.string().describe('Amount needed (e.g., "2 cups")'),
33 notes: z.string().optional().describe('Optional preparation notes'),
34 }),
35 )
36 .describe('List of ingredients'),
37 instructions: z
38 .array(z.string())
39 .describe('Step-by-step cooking instructions'),
40 tips: z.array(z.string()).optional().describe('Optional cooking tips'),
41 nutritionPerServing: z
42 .object({
43 calories: z.number().optional(),
44 protein: z.string().optional(),
45 carbs: z.string().optional(),
46 fat: z.string().optional(),
47 })
48 .optional()
49 .describe('Nutritional information per serving'),
50})
51
52export type Recipe = z.infer<typeof RecipeSchema>
53
54export const Route = createFileRoute('/api/structured')({
55 server: {
56 handlers: {
57 POST: async ({ request }) => {
58 const body = await request.json()
59 const { recipeName, mode = 'structured' } = body
60 const data = body.data || {}
61 const provider: Provider = data.provider || body.provider || 'openai'
62 // Don't set a global default - let each adapter use its own default model
63 const model: string | undefined = data.model || body.model
64
65 try {
66 // Default models per provider
67 const defaultModels: Record<Provider, string> = {
68 anthropic: 'claude-sonnet-4-5',
69 gemini: 'gemini-2.5-flash',
70 grok: 'grok-build-0.1',
71 ollama: 'mistral:7b',
72 openai: 'gpt-4o',
73 openrouter: 'openai/gpt-4o',
74 }
75
76 // Determine the actual model being used
77 const actualModel = model || defaultModels[provider]
78
79 // Pre-define adapter factories per provider. The map is typed as the
80 // text-adapter union so each provider's adapter unifies cleanly when
81 // handed to chat() below.
82 const adapterConfig: Record<Provider, () => AnyTextAdapter> = {
83 anthropic: () => anthropicText(actualModel as any),
84 gemini: () => geminiText(actualModel as any),
85 grok: () => grokText(actualModel as any),
86 ollama: () => ollamaText(actualModel as any),
87 openai: () => openaiText(actualModel as any),
88 openrouter: () => openRouterText(actualModel as any),
89 }
90
91 // Select the provider's text adapter
92 const adapter = adapterConfig[provider]()
93
94 console.log(
95 `>> ${mode} output with model: ${actualModel} on provider: ${provider}`,
96 )
97
98 if (mode === 'structured') {
99 // Structured output mode - returns validated object
100 const result = await chat({
101 adapter,
102 messages: [
103 {
104 role: 'user',
105 content: `Generate a complete recipe for: ${recipeName}. Include all ingredients with amounts, step-by-step instructions, prep/cook times, and difficulty level.`,
106 },
107 ],
108 outputSchema: RecipeSchema,
109 })
110
111 return new Response(
112 JSON.stringify({
113 mode: 'structured',
114 recipe: result,
115 provider,
116 model: actualModel,
117 }),
118 {
119 status: 200,
120 headers: { 'Content-Type': 'application/json' },
121 },
122 )
123 } else {
124 // One-shot markdown mode - returns streamed text
125 const markdown = await chat({
126 adapter,
127 stream: false,
128 messages: [
129 {
130 role: 'user',
131 content: `Generate a complete recipe for: ${recipeName}.
133Format the recipe in beautiful markdown with:
134- A title with the recipe name
135- A brief description
136- Prep time, cook time, and servings
137- Ingredients list with amounts
138- Numbered step-by-step instructions
139- Optional tips section
140- Nutritional info if applicable
141
142Make it detailed and easy to follow.`,
143 },
144 ],
145 })
146
147 console.log('>> markdown:', markdown)
148
149 return new Response(
150 JSON.stringify({
151 mode: 'oneshot',
152 markdown,
153 provider,
154 model: actualModel,
155 }),
156 {
157 status: 200,
158 headers: { 'Content-Type': 'application/json' },
159 },
160 )
161 }
162 } catch (error: any) {
163 console.error(
164 '[API Route] Error in structured output request:',
165 error,
166 )
167 return new Response(
168 JSON.stringify({
169 error: error.message || 'An error occurred',
170 }),
171 {
172 status: 500,
173 headers: { 'Content-Type': 'application/json' },
174 },
175 )
176 }
177 },
178 },
179 },
180})