GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — RecipeHub_AI/server.ts at main · bikram73/RecipeHub_AI

Expand file tree

/

server.ts

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
246 lines (216 loc) · 7.48 KB
/

server.ts

Copy path

File metadata and controls

246 lines (216 loc) · 7.48 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import express from 'express';
import path from 'path';
import dotenv from 'dotenv';
import { createServer as createViteServer } from 'vite';
import { GoogleGenAI } from '@google/genai';
dotenv.config();
async function startServer() {
const app = express();
const PORT = 3000;
app.use(express.json({ limit: '10mb' }));
// Helper for lazy Gemini client
let aiClient: GoogleGenAI | null = null;
function getGeminiClient(): GoogleGenAI | null {
const key = process.env.GEMINI_API_KEY;
if (!key) return null;
if (!aiClient) {
aiClient = new GoogleGenAI({
apiKey: key,
httpOptions: {
headers: {
'User-Agent': 'aistudio-build',
},
},
});
}
return aiClient;
}
// 1. Health check
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
hasGeminiKey: Boolean(process.env.GEMINI_API_KEY),
timestamp: new Date().toISOString(),
});
});
// 2. AI Recipe Generator endpoint
app.post('/api/ai/generate-recipe', async (req, res) => {
try {
const { ingredients, options } = req.body;
const ai = getGeminiClient();
if (!ai) {
return res.status(200).json({ error: 'NO_KEY', recipe: null });
}
const prompt = `You are RecipeHub AI, an expert culinary chef.
Generate a gourmet, restaurant-quality recipe using available ingredients: ${Array.isArray(ingredients) ? ingredients.join(', ') : 'Chef special selection'}.
Preferences:
- Cuisine: ${options?.cuisine || 'Any'}
- Dietary: ${options?.diet || 'Any'}
- Category: ${options?.mealType || 'dinner'}
- Target Cook Time: ${options?.maxTimeMinutes || 25} minutes
- Skill Level: ${options?.skillLevel || 'Intermediate'}
Return ONLY pure, valid JSON (no markdown fences, no conversational text) matching this schema:
{
"title": "string",
"subtitle": "string",
"description": "string",
"cuisine": "string",
"category": "breakfast" | "lunch" | "dinner" | "dessert" | "snack" | "drinks" | "baking",
"difficulty": "Easy" | "Medium" | "Hard",
"prepTimeMinutes": number,
"cookTimeMinutes": number,
"servings": number,
"tags": ["string"],
"dietary": ["Vegetarian" | "Vegan" | "Gluten-Free" | "Dairy-Free" | "Keto" | "Low-Carb" | "High-Protein"],
"nutrition": {
"calories": number,
"protein": number,
"carbs": number,
"fat": number,
"fiber": number,
"sugar": number
},
"ingredients": [
{ "name": "string", "amount": number, "unit": "string", "category": "produce" | "dairy" | "meat" | "pantry" | "spices" }
],
"steps": [
{ "stepNumber": number, "instruction": "string", "timerMinutes": number, "tip": "string" }
],
"chefTips": ["string"],
"winePairing": "string"
}`;
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
config: {
responseMimeType: 'application/json',
temperature: 0.7,
},
});
const responseText = response.text?.trim() || '';
try {
const recipeData = JSON.parse(responseText);
return res.json({ recipe: recipeData });
} catch (parseErr) {
console.error('Failed to parse Gemini response as JSON:', responseText);
return res.json({ error: 'PARSE_ERROR', raw: responseText, recipe: null });
}
} catch (err: any) {
console.error('Gemini generate recipe error:', err);
res.status(500).json({ error: err.message || 'AI Generation failed', recipe: null });
}
});
// 3. AI Cooking Chat endpoint
app.post('/api/ai/chat', async (req, res) => {
try {
const { message, recipeContext } = req.body;
const ai = getGeminiClient();
if (!ai) {
return res.json({ reply: null });
}
let systemPrompt = `You are RecipeHub AI, an approachable, world-class culinary sommelier and chef. Provide concise, clear, and actionable culinary guidance. Always offer exact cooking temperatures, ratios, or step-by-step pointers. Keep answers under 150 words unless requested.`;
if (recipeContext) {
systemPrompt += `\nCurrent Recipe Context: "${recipeContext.title}" with ingredients: ${JSON.stringify(recipeContext.ingredients)}`;
}
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: `${systemPrompt}\n\nUser Question: ${message}`,
});
res.json({ reply: response.text });
} catch (err: any) {
console.error('Gemini chat error:', err);
res.status(500).json({ error: err.message });
}
});
// 4. AI Substitutions endpoint
app.post('/api/ai/substitute', async (req, res) => {
try {
const { ingredient, recipeContextName } = req.body;
const ai = getGeminiClient();
if (!ai) return res.json({ substitution: null });
const prompt = `Provide the top culinary substitutes for "${ingredient}" in cooking${recipeContextName ? ` (context: ${recipeContextName})` : ''}.
Return ONLY valid JSON matching:
{
"ingredient": "${ingredient}",
"bestOption": {
"name": "string",
"ratio": "string (e.g. 1:1 ratio or 3/4 cup per cup)",
"tasteImpact": "string",
"bestFor": "string"
},
"alternatives": [
{ "name": "string", "ratio": "string", "notes": "string" }
]
}`;
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
config: {
responseMimeType: 'application/json',
temperature: 0.3,
},
});
const parsed = JSON.parse(response.text || '{}');
res.json({ substitution: parsed });
} catch (err: any) {
console.error('Gemini substitution error:', err);
res.status(500).json({ error: err.message });
}
});
// 5. AI Recipe Improvement endpoint
app.post('/api/ai/improve', async (req, res) => {
try {
const { recipe, goal } = req.body;
const ai = getGeminiClient();
if (!ai) return res.json({ result: null });
const prompt = `Optimize the following recipe to make it "${goal}" (e.g. healthier, vegan, quicker, higher protein) without sacrificing taste depth:
Recipe: "${recipe.title}" (${recipe.cuisine})
Current calories: ${recipe.nutrition?.calories || 450}
Return ONLY valid JSON:
{
"goal": "${goal}",
"summary": "string",
"modifiedIngredients": [
{ "original": "string", "replacement": "string", "reason": "string" }
],
"techniqueChanges": ["string"],
"macroComparison": {
"originalCalories": number,
"newCalories": number,
"keyBenefit": "string"
}
}`;
const response = await ai.models.generateContent({
model: 'gemini-3.8-flash',
contents: prompt,
config: {
responseMimeType: 'application/json',
temperature: 0.5,
},
});
const parsed = JSON.parse(response.text || '{}');
res.json({ result: parsed });
} catch (err: any) {
console.error('Gemini improve error:', err);
res.status(500).json({ error: err.message });
}
});
// Vite middleware for development
if (process.env.NODE_ENV !== 'production') {
const vite = await createViteServer({
server: { middlewareMode: true },
appType: 'spa',
});
app.use(vite.middlewares);
} else {
const distPath = path.join(process.cwd(), 'dist');
app.use(express.static(distPath));
app.get('*', (req, res) => {
res.sendFile(path.join(distPath, 'index.html'));
});
}
app.listen(PORT, '0.0.0.0', () => {
console.log(`RecipeHub AI server running on http://localhost:${PORT}`);
});
}
startServer();
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.