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