-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
604 lines (542 loc) · 18.5 KB
/
Copy pathserver.ts
File metadata and controls
604 lines (542 loc) · 18.5 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
import express from "express";
import cors from "cors";
import path from "path";
import dotenv from "dotenv";
import { GoogleGenAI, Type } from "@google/genai";
import { createServer as createViteServer } from "vite";
dotenv.config();
const PORT = 3000;
interface RoadmapWeek {
number: number;
title: string;
focus: string;
steps: string[];
tools: string[];
}
interface RoadmapResponse {
subtitle: string;
weeks: RoadmapWeek[];
}
function getWeekCount(dur: string): number {
const lower = (dur || "").toLowerCase();
if (lower.includes("4")) return 4;
if (lower.includes("8")) return 8;
if (lower.includes("12")) return 12;
if (lower.includes("6") || lower.includes("month")) return 16;
const parsed = parseInt(dur, 10);
return isNaN(parsed) ? 4 : parsed;
}
function cleanJsonOutput(raw: string): string {
let cleaned = raw.trim();
if (cleaned.startsWith("```json")) {
cleaned = cleaned.replace(/^```json\s*/, "").replace(/\s*```$/, "");
} else if (cleaned.startsWith("```")) {
cleaned = cleaned.replace(/^```\s*/, "").replace(/\s*```$/, "");
}
return cleaned;
}
// Default Groq model managed entirely server-side
const GROQ_FALLBACK_MODELS = [
"llama-3.3-70b-versatile",
"llama-3.1-8b-instant",
"deepseek-r1-distill-llama-70b",
"gemma2-9b-it",
];
async function getAvailableGroqModels(apiKey: string): Promise<string[]> {
try {
const res = await fetch("https://api.groq.com/openai/v1/models", {
headers: { Authorization: `Bearer ${apiKey}` },
});
if (res.ok) {
const data = await res.json();
if (Array.isArray(data?.data)) {
return data.data
.map((m: any) => m.id)
.filter(
(id: string) =>
id &&
!id.includes("whisper") &&
!id.includes("guard") &&
!id.includes("vision") &&
!id.includes("tts")
);
}
}
} catch (e) {
console.warn("Could not query Groq models list:", e);
}
return [];
}
async function generateWithGroq(apiKey: string, prompt: string): Promise<string> {
const discovered = await getAvailableGroqModels(apiKey);
const candidateModels = Array.from(new Set([...discovered, ...GROQ_FALLBACK_MODELS]));
let lastError: Error | null = null;
for (const model of candidateModels) {
try {
const response = await fetch("https://api.groq.com/openai/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model,
messages: [
{
role: "system",
content:
"You are a specialized JSON-only roadmap generation API. You strictly return parseable JSON matching the requested structure without code fences or explanations.",
},
{
role: "user",
content: prompt,
},
],
temperature: 0.7,
response_format: { type: "json_object" },
}),
});
if (!response.ok) {
const errorText = await response.text();
console.warn(`Groq model '${model}' returned HTTP ${response.status}: ${errorText}`);
lastError = new Error(`Groq API returned HTTP ${response.status}: ${errorText}`);
continue;
}
const data = await response.json();
const content = data?.choices?.[0]?.message?.content || "";
if (content) {
return content;
}
} catch (err: any) {
lastError = err;
continue;
}
}
throw lastError || new Error("Failed to generate roadmap using Groq API");
}
async function getAvailableGrokModels(apiKey: string): Promise<string[]> {
try {
const response = await fetch("https://api.x.ai/v1/models", {
headers: {
Authorization: `Bearer ${apiKey}`,
},
});
if (response.ok) {
const data = await response.json();
if (Array.isArray(data?.data)) {
return data.data.map((m: any) => m.id).filter(Boolean);
}
}
} catch (err) {
console.warn("Could not query xAI models endpoint:", err);
}
return [];
}
async function generateWithGrok(apiKey: string, prompt: string): Promise<string> {
const customModel = (process.env.GROK_MODEL || "").trim();
const discoveredModels = await getAvailableGrokModels(apiKey);
const candidateModels = Array.from(
new Set([
...(customModel ? [customModel] : []),
...discoveredModels,
"grok-2-1212",
"grok-2",
"grok-beta",
"grok-3",
"grok-4",
"grok-2-vision-1212",
])
);
let lastError: Error | null = null;
for (const model of candidateModels) {
try {
const response = await fetch("https://api.x.ai/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model,
messages: [
{
role: "system",
content:
"You are a specialized JSON-only roadmap generation API. You strictly return parseable JSON matching the requested structure without code fences or explanations.",
},
{
role: "user",
content: prompt,
},
],
temperature: 0.7,
}),
});
if (!response.ok) {
const errorText = await response.text();
if (
response.status === 400 &&
(errorText.includes("Model not found") ||
errorText.includes("model_not_found") ||
errorText.includes("invalid-argument") ||
errorText.includes("does not exist"))
) {
lastError = new Error(`xAI Grok model ${model} unavailable: ${errorText}`);
continue;
}
throw new Error(`xAI Grok API returned HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
const content = data?.choices?.[0]?.message?.content || "";
if (content) {
return content;
}
} catch (err: any) {
lastError = err;
if (err.message && (err.message.includes("Model not found") || err.message.includes("unavailable"))) {
continue;
}
throw err;
}
}
throw lastError || new Error("Failed to generate roadmap using xAI Grok API");
}
async function generateWithOpenRouter(apiKey: string, prompt: string): Promise<string> {
const customModel = (process.env.OPENROUTER_MODEL || "").trim();
const candidateModels = customModel
? [customModel, "x-ai/grok-2-1212", "x-ai/grok-beta", "google/gemini-2.5-flash"]
: ["x-ai/grok-2-1212", "x-ai/grok-beta", "google/gemini-2.5-flash"];
let lastError: Error | null = null;
for (const model of candidateModels) {
try {
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
"HTTP-Referer": "http://localhost:3000",
"X-Title": "PathAI",
},
body: JSON.stringify({
model,
messages: [
{
role: "system",
content:
"You are a specialized JSON-only roadmap generation API. You strictly return parseable JSON matching the requested structure without code fences or explanations.",
},
{
role: "user",
content: prompt,
},
],
temperature: 0.7,
response_format: { type: "json_object" },
}),
});
if (!response.ok) {
const errorText = await response.text();
if (response.status === 400 || response.status === 404) {
lastError = new Error(`OpenRouter model ${model} unavailable: ${errorText}`);
continue;
}
throw new Error(`OpenRouter API returned HTTP ${response.status}: ${errorText}`);
}
const data = await response.json();
const content = data?.choices?.[0]?.message?.content || "";
if (content) {
return content;
}
} catch (err: any) {
lastError = err;
continue;
}
}
throw lastError || new Error("Failed to generate roadmap using OpenRouter API");
}
async function generateWithGemini(apiKey: string, prompt: string): Promise<string> {
const ai = new GoogleGenAI({
apiKey,
httpOptions: {
headers: {
"User-Agent": "aistudio-build",
},
},
});
const response = await ai.models.generateContent({
model: "gemini-3.6-flash",
contents: prompt,
config: {
systemInstruction:
"You are a specialized JSON-only roadmap generation API. You strictly return parseable JSON matching the requested structure without code fences or markdown.",
responseMimeType: "application/json",
responseSchema: {
type: Type.OBJECT,
properties: {
subtitle: {
type: Type.STRING,
description: "A brief poetic sentence about this specific journey (under 20 words)",
},
weeks: {
type: Type.ARRAY,
description: "Sequential list of weekly milestone cards",
items: {
type: Type.OBJECT,
properties: {
number: {
type: Type.INTEGER,
description: "Week number starting at 1",
},
title: {
type: Type.STRING,
description: "Short, evocative title for this week (3-6 words)",
},
focus: {
type: Type.STRING,
description: "One sentence outlining focus and practical progress",
},
steps: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: "3 concrete action items for this week",
},
tools: {
type: Type.ARRAY,
items: { type: Type.STRING },
description: "2 recommended tools or resources",
},
},
required: ["number", "title", "focus", "steps", "tools"],
},
},
},
required: ["subtitle", "weeks"],
},
},
});
const text = response.text;
if (!text) {
throw new Error("Empty response received from Gemini API");
}
return text;
}
function resolveProvider(): { provider: "groq" | "grok" | "openrouter" | "gemini"; apiKey: string } {
const reqProvider = (process.env.API_PROVIDER || "").trim().toLowerCase();
const groqKey = (process.env.GROQ_API_KEY || "").trim();
const grokKey = (process.env.GROK_API_KEY || process.env.XAI_API_KEY || "").trim();
const openrouterKey = (process.env.OPENROUTER_API_KEY || "").trim();
const geminiKey = (process.env.GEMINI_API_KEY || "").trim();
// If a key starts with 'gsk_', it's definitely a Groq (console.groq.com) key
if (groqKey.startsWith("gsk_")) {
return { provider: "groq", apiKey: groqKey };
}
if (grokKey.startsWith("gsk_")) {
return { provider: "groq", apiKey: grokKey };
}
// If a key starts with 'xai-', it's definitely an xAI Grok (console.x.ai) key
if (grokKey.startsWith("xai-") || grokKey) {
if (reqProvider === "grok" || reqProvider === "xai" || (!groqKey && !geminiKey && !openrouterKey)) {
return { provider: "grok", apiKey: grokKey };
}
}
// 1. Honor explicit API_PROVIDER choice
if ((reqProvider === "groq" || reqProvider === "groq.com") && (groqKey || grokKey)) {
return { provider: "groq", apiKey: groqKey || grokKey };
}
if ((reqProvider === "grok" || reqProvider === "xai" || reqProvider === "x.ai") && grokKey) {
return { provider: "grok", apiKey: grokKey };
}
if (reqProvider === "openrouter" && openrouterKey) {
return { provider: "openrouter", apiKey: openrouterKey };
}
if (reqProvider === "gemini" && geminiKey) {
return { provider: "gemini", apiKey: geminiKey };
}
// 2. If specified without key
if (reqProvider === "groq") {
return { provider: "groq", apiKey: groqKey || grokKey };
}
if (reqProvider === "grok" || reqProvider === "xai") {
return { provider: "grok", apiKey: grokKey };
}
if (reqProvider === "openrouter") {
return { provider: "openrouter", apiKey: openrouterKey };
}
if (reqProvider === "gemini") {
return { provider: "gemini", apiKey: geminiKey };
}
// 3. Automatic selection based on available keys
if (groqKey) return { provider: "groq", apiKey: groqKey };
if (grokKey) return { provider: "grok", apiKey: grokKey };
if (openrouterKey) return { provider: "openrouter", apiKey: openrouterKey };
return { provider: "gemini", apiKey: geminiKey };
}
async function handleRoadmapRequest(req: express.Request, res: express.Response) {
try {
const { from, to, dur } = req.body || {};
if (!from || !to || !dur) {
res.status(400).json({ error: "Missing required fields: from, to, dur" });
return;
}
const { provider, apiKey } = resolveProvider();
if (!apiKey) {
console.error(`API key is missing for provider '${provider}'`);
res.status(400).json({
error: `No API key found for provider '${provider}'. Please add your API key in Settings (GROQ_API_KEY, GROK_API_KEY/XAI_API_KEY from console.x.ai, or GEMINI_API_KEY).`,
});
return;
}
const weekCount = getWeekCount(dur);
const prompt = `You are a journey architect. Create a cinematic, personal roadmap for someone going from "${from}" to "${to}" over ${dur}.
Return ONLY valid JSON (no markdown code blocks, no backticks, no explanations, no preamble).
Strictly match this JSON schema:
{
"subtitle": "A brief poetic sentence about this specific journey (under 20 words)",
"weeks": [
{
"number": 1,
"title": "Poetic evocative title for this phase",
"focus": "One sentence describing the emotional or practical focus of this week",
"steps": [
"Concrete action 1",
"Concrete action 2",
"Concrete action 3"
],
"tools": [
"Tool 1",
"Tool 2"
]
}
]
}
Generate exactly ${weekCount} weeks numbered 1 to ${weekCount}.
Requirements:
- subtitle: string
- weeks: array of exactly ${weekCount} objects
- each week must have:
- "number": integer (1 to ${weekCount})
- "title": string (poetic and evocative)
- "focus": string (emotional/practical focus)
- "steps": array of exactly 3 actionable strings
- "tools": array of exactly 2 useful tools
Do not return markdown, backticks, or any conversational text. Return only valid parseable JSON.`;
let rawOutput = "";
try {
if (provider === "groq") {
rawOutput = await generateWithGroq(apiKey, prompt);
} else if (provider === "grok") {
rawOutput = await generateWithGrok(apiKey, prompt);
} else if (provider === "openrouter") {
rawOutput = await generateWithOpenRouter(apiKey, prompt);
} else {
rawOutput = await generateWithGemini(apiKey, prompt);
}
} catch (apiErr: any) {
console.error(`Provider '${provider}' generation error:`, apiErr);
res.status(502).json({
error: apiErr?.message || `Failed to generate roadmap from ${provider} API.`,
});
return;
}
const cleaned = cleanJsonOutput(rawOutput);
let parsed: RoadmapResponse;
try {
parsed = JSON.parse(cleaned);
} catch (parseErr: any) {
console.error("JSON parsing failed on AI output:", rawOutput);
res.status(502).json({
error: "AI provider returned invalid JSON format. Please try again.",
});
return;
}
if (!parsed || !parsed.subtitle || !Array.isArray(parsed.weeks)) {
res.status(502).json({
error: "AI provider returned an incomplete roadmap structure. Please try again.",
});
return;
}
parsed.weeks = parsed.weeks.slice(0, weekCount).map((w, idx) => ({
number: typeof w.number === "number" ? w.number : idx + 1,
title: w.title || `Phase ${idx + 1}`,
focus: w.focus || "Dedicate focus to your journey goals.",
steps:
Array.isArray(w.steps) && w.steps.length === 3
? w.steps
: Array.isArray(w.steps)
? w.steps.slice(0, 3)
: [
"Research core principles",
"Apply your learning",
"Reflect on progress",
],
tools:
Array.isArray(w.tools) && w.tools.length === 2
? w.tools
: Array.isArray(w.tools)
? w.tools.slice(0, 2)
: ["Visual Studio Code", "Notion"],
}));
res.json(parsed);
} catch (error: any) {
console.error("Roadmap request handler error:", error);
res.status(500).json({
error: error.message || "Failed to generate roadmap.",
});
}
}
async function startServer() {
const app = express();
// Middleware
app.use(cors());
app.use(express.json());
// Handle JSON body parse errors with JSON responses
app.use((err: any, _req: express.Request, res: express.Response, next: express.NextFunction) => {
if (err) {
res.status(400).json({ error: "Invalid JSON payload in request." });
return;
}
next();
});
// API Routes FIRST
app.post("/roadmap", handleRoadmapRequest);
app.post("/api/roadmap", handleRoadmapRequest);
// Health check
app.get("/api/health", (_req, res) => {
const { provider } = resolveProvider();
res.json({
status: "ok",
service: "PathAI Backend",
provider,
configuredProvider: process.env.API_PROVIDER || "auto",
});
});
// Specific 404 handler for API routes
app.all("/api/*", (_req, res) => {
res.status(404).json({ error: "API endpoint not found" });
});
// Global error handler for API
app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
console.error("Unhandled server error:", err);
res.status(err.status || 500).json({
error: err.message || "Internal server error",
});
});
// Vite middleware for development / static serving in production
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(`PathAI server running on http://0.0.0.0:${PORT}`);
});
}
startServer();