-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1190 lines (1082 loc) · 36.6 KB
/
server.js
File metadata and controls
1190 lines (1082 loc) · 36.6 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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require("express");
const path = require("path");
const dotenv = require("dotenv");
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3000;
const AI_BASE = process.env.AI_BUILDER_API_BASE || "https://space.ai-builders.com/backend";
const AI_TOKEN = process.env.AI_BUILDER_TOKEN || "";
const AI_MODEL = process.env.AI_BUILDER_MODEL || "grok-4-fast";
app.use(express.json({ limit: "1mb" }));
app.use(express.static(path.join(__dirname, "public")));
app.get("/api/health", (req, res) => {
res.json({ status: "ok" });
});
app.post("/api/session", async (req, res) => {
const payload = req.body || {};
const category = sanitizeText(payload.category || "");
const location = sanitizeText(payload.location || "");
const language = normalizeLanguage(payload.language);
const candidates = normalizeCandidates(payload.candidates || []);
const minQuestions = Number.isInteger(payload.minQuestions) ? payload.minQuestions : 3;
const maxQuestions = Number.isInteger(payload.maxQuestions) ? payload.maxQuestions : 10;
if (candidates.length < 3 || candidates.length > 6) {
return res.status(400).json({
error: "Please provide between 3 and 6 candidates.",
});
}
const context = {
category: category || "general consumer product",
location,
language,
candidates,
minQuestions,
maxQuestions,
};
if (!AI_TOKEN) {
return res.json(buildFallbackPlan(context, {
warning: "Missing AI token. Returning fallback plan.",
}));
}
try {
const aiData = await callAiPlan(context);
const normalized = normalizePlan(aiData, context);
res.json({ status: "ready", plan: normalized });
} catch (error) {
console.error("AI plan failed:", error);
res.json(buildFallbackPlan(context, {
warning: "AI request failed. Returning fallback plan.",
}));
}
});
app.post("/api/next", async (req, res) => {
const payload = req.body || {};
const category = sanitizeText(payload.category || "");
const location = sanitizeText(payload.location || "");
const language = normalizeLanguage(payload.language);
const candidates = normalizeCandidates(payload.candidates || []);
const answers = Array.isArray(payload.answers) ? payload.answers.map(normalizeAnswer) : [];
const previousQuestions = Array.isArray(payload.previousQuestions)
? payload.previousQuestions.map(sanitizeText).filter(Boolean)
: [];
const questionCount = Number.isInteger(payload.questionCount)
? payload.questionCount
: answers.length;
const minQuestions = Number.isInteger(payload.minQuestions) ? payload.minQuestions : 3;
const maxQuestions = Number.isInteger(payload.maxQuestions) ? payload.maxQuestions : 10;
if (candidates.length < 3 || candidates.length > 6) {
return res.status(400).json({
error: "Please provide between 3 and 6 candidates.",
});
}
const context = {
category: category || "general consumer product",
location,
language,
candidates,
answers,
previousQuestions,
questionCount,
minQuestions,
maxQuestions,
};
if (!AI_TOKEN) {
return res.json(buildFallbackResponse(context, {
warning: "Missing AI token. Returning fallback question.",
}));
}
try {
const aiData = await callAiDecision(context);
const normalized = normalizeAiOutput(aiData, context);
res.json(normalized);
} catch (error) {
console.error("AI request failed:", error);
res.json(buildFallbackResponse(context, {
warning: "AI request failed. Returning fallback question.",
}));
}
});
app.post("/api/result", async (req, res) => {
const payload = req.body || {};
const category = sanitizeText(payload.category || "");
const location = sanitizeText(payload.location || "");
const additionalInfo = sanitizeText(payload.additionalInfo || "");
const language = normalizeLanguage(payload.language);
const candidates = normalizeCandidates(payload.candidates || []);
const answers = Array.isArray(payload.answers) ? payload.answers.map(normalizeAnswer) : [];
const scores = normalizeScores(payload.scores || {}, candidates);
if (candidates.length < 3 || candidates.length > 6) {
return res.status(400).json({
error: "Please provide between 3 and 6 candidates.",
});
}
const context = {
category: category || "general consumer product",
location,
additionalInfo,
language,
candidates,
answers,
scores,
};
const ranking = buildRankingFromScores(scores, candidates);
if (!AI_TOKEN) {
return res.json(buildResultFallback(context, ranking, {
warning: "Missing AI token. Returning fallback result.",
}));
}
try {
const aiData = await callAiResult(context);
const normalized = normalizeResultOutput(aiData, context, ranking);
res.json(normalized);
} catch (error) {
console.error("AI result failed:", error);
res.json(buildResultFallback(context, ranking, {
warning: "AI request failed. Returning fallback result.",
}));
}
});
function sanitizeText(value) {
if (typeof value !== "string") {
return "";
}
return value.replace(/\s+/g, " ").trim();
}
function normalizeLanguage(value) {
const text = sanitizeText(String(value || "")).toLowerCase();
if (text.startsWith("en")) {
return "en";
}
if (text.startsWith("zh")) {
return "zh";
}
return "zh";
}
function getLanguageLabel(language) {
return language === "zh" ? "Simplified Chinese" : "English";
}
function normalizeCandidates(list) {
if (!Array.isArray(list)) {
return [];
}
const unique = new Set();
const result = [];
list.forEach((item) => {
const text = sanitizeText(item);
if (!text) {
return;
}
if (!unique.has(text.toLowerCase())) {
unique.add(text.toLowerCase());
result.push(text);
}
});
return result.slice(0, 6);
}
function normalizeAnswer(answer) {
if (!answer || typeof answer !== "object") {
return null;
}
return {
questionId: sanitizeText(answer.questionId || ""),
question: sanitizeText(answer.question || ""),
optionId: sanitizeText(answer.optionId || ""),
optionLabel: sanitizeText(answer.optionLabel || ""),
value: sanitizeText(answer.value || ""),
dimension: sanitizeText(answer.dimension || ""),
};
}
async function callAiPlan(context) {
const languageLabel = getLanguageLabel(context.language);
const systemPrompt = [
"You are QuickPick Plan Builder.",
"Return JSON only. No markdown or commentary.",
"Create a full question plan so the UI can ask without waiting.",
"Use candidate names exactly as provided.",
"Use the user's location to tune price/availability tradeoffs.",
`All user-facing text must be in ${languageLabel}.`,
"Each option must include impact_scores for every candidate as integers between -12 and 12.",
"Questions must be short, scenario-based, and high impact.",
"Provide between minQuestions and maxQuestions, prefer 5-7 if allowed.",
"Keep all text short: <= 18 words per sentence.",
].join("\n");
const userPrompt = JSON.stringify({
category: context.category,
location: context.location || "unspecified",
language: languageLabel,
candidates: context.candidates,
minQuestions: context.minQuestions,
maxQuestions: context.maxQuestions,
output_schema: {
base_scores: [{ name: "candidate name", score: "0-100" }],
questions: [
{
id: "string",
text: "string",
dimension: "string",
info_gain_reason: "string",
options: [
{
id: "string",
label: "string",
value: "string",
impact_hint: "string",
impact_scores: {
"candidate name": "integer -12..12",
},
},
],
},
],
},
});
return callAiJson({
systemPrompt,
userPrompt,
maxTokens: 1400,
});
}
async function callAiResult(context) {
const languageLabel = getLanguageLabel(context.language);
const systemPrompt = [
"You are QuickPick, an explainable recommendation engine.",
"Return JSON only. No markdown or commentary.",
"Use the user's location to explain price or availability differences.",
"Use the user's additional context if provided.",
"Use baseline_scores as the starting point and adjust if needed.",
"Be detailed but concise.",
"Ranking reasons must be 2-3 sentences.",
"Key reasons: 4-6 items, each 1-2 sentences.",
"Tradeoff map: 1-2 sentences per item.",
"Actions: 3-5 items, each one sentence.",
`All user-facing text must be in ${languageLabel}.`,
"Explain using scenario-based language without jargon.",
].join("\n");
const userPrompt = JSON.stringify({
category: context.category,
location: context.location || "unspecified",
additional_context: context.additionalInfo || "none",
language: languageLabel,
baseline_scores: context.candidates.map((name) => ({
name,
score: clampNumber(context.scores[name], 0, 100, 50),
})),
candidates: context.candidates,
answers: context.answers,
output_schema: {
confidence: "number between 0 and 1",
adjusted_scores: [
{
name: "candidate name",
score: "0-100",
reason: "2-3 sentence reason tied to additional_context",
},
],
ranking: [
{
name: "candidate name",
score: "0-100",
reason: "2-3 sentence reason tied to answers",
},
],
key_reasons: ["string"],
tradeoff_map: [
{
dimension: "string",
winner: "candidate name",
why: "string",
},
],
counterfactuals: [
{
toggle: "string",
change: "string",
new_top: "candidate name",
new_ranking: [
{
name: "candidate name",
score: "0-100",
},
],
},
],
actions: ["string"],
third_option: {
title: "string",
why: "string",
criteria: "string",
},
},
});
try {
return await callAiJson({
systemPrompt,
userPrompt,
maxTokens: 2000,
});
} catch (error) {
const compactSystemPrompt = [
"You are QuickPick, an explainable recommendation engine.",
"Return JSON only. No markdown or commentary.",
"Use location and additional context if provided.",
"Use baseline_scores as the starting point and adjust if needed.",
"Ranking reasons must be 1-2 sentences.",
"Key reasons: 3-5 items, each one sentence.",
"Tradeoff map: one sentence per item.",
"Actions: 3-4 items, each one sentence.",
`All user-facing text must be in ${languageLabel}.`,
"Use clear, simple language without jargon.",
].join("\n");
return callAiJson({
systemPrompt: compactSystemPrompt,
userPrompt,
maxTokens: 1400,
});
}
}
async function callAiJson({ systemPrompt, userPrompt, maxTokens }) {
const debug = process.env.DEBUG_AI === "1";
const fallbackModel = process.env.AI_BUILDER_FALLBACK_MODEL || "grok-4-fast";
const modelsToTry = AI_MODEL && AI_MODEL !== fallbackModel
? [AI_MODEL, fallbackModel]
: [AI_MODEL];
let lastError = null;
for (const model of modelsToTry) {
try {
const response = await fetch(`${AI_BASE}/v1/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${AI_TOKEN}`,
},
body: JSON.stringify({
model,
temperature: 0.4,
max_tokens: maxTokens,
response_format: { type: "json_object" },
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userPrompt },
],
}),
});
if (!response.ok) {
const detail = await response.text();
throw new Error(`AI request failed: ${response.status} ${detail}`);
}
const data = await response.json();
const content = data && data.choices && data.choices[0] && data.choices[0].message
? data.choices[0].message.content
: "";
if (debug) {
console.log("AI model:", model);
console.log("AI message:", data && data.choices && data.choices[0] ? data.choices[0].message : null);
console.log("AI raw content:", typeof content, String(content).slice(0, 500));
}
const cleaned = stripJsonFences(String(content));
const parsed = safeJsonParse(cleaned);
if (!parsed) {
throw new Error("AI response was not valid JSON.");
}
return parsed;
} catch (error) {
lastError = error;
if (!shouldFallback(error) || model === fallbackModel) {
break;
}
}
}
throw lastError || new Error("AI request failed.");
}
async function callAiDecision(context) {
const debug = process.env.DEBUG_AI === "1";
const languageLabel = getLanguageLabel(context.language);
const systemPrompt = [
"You are QuickPick, a decision engine for consumer product shortlists.",
"Goal: ask one high impact question at a time, update ranking, and stop once confident.",
"Constraints:",
"- Ask short, scenario-based questions. Avoid jargon and precise numbers.",
"- Provide 3 to 5 options. Each option must be quick to choose.",
"- Every question must include an info_gain_reason that explains why it changes ranking.",
"- Provide ranking for all candidates every time.",
"- Provide tradeoff_map with 3 to 6 dimensions.",
"- Provide 2 to 4 counterfactual toggles with alternative ranking.",
"- If none fit, return a third_option suggestion with why and criteria.",
"- Use the user's location to tune price/availability tradeoffs.",
`- All user-facing text must be in ${languageLabel}.`,
"- Keep all text short: <= 18 words per sentence; avoid extra clauses.",
"Output JSON only. No markdown.",
].join("\n");
const userPrompt = JSON.stringify({
category: context.category,
location: context.location || "unspecified",
language: languageLabel,
candidates: context.candidates,
answers: context.answers,
previousQuestions: context.previousQuestions,
questionCount: context.questionCount,
minQuestions: context.minQuestions,
maxQuestions: context.maxQuestions,
output_schema: {
should_stop: "boolean",
confidence: "number between 0 and 1",
question: {
id: "string",
text: "string",
dimension: "string",
info_gain_reason: "string",
options: [
{
id: "string",
label: "string",
value: "string",
impact_hint: "string",
},
],
},
ranking: [
{
name: "candidate name",
score: "0-100",
reason: "short reason tied to answers",
},
],
key_reasons: ["string"],
tradeoff_map: [
{
dimension: "string",
winner: "candidate name",
why: "string",
},
],
counterfactuals: [
{
toggle: "string",
change: "string",
new_top: "candidate name",
new_ranking: [
{
name: "candidate name",
score: "0-100",
},
],
},
],
actions: ["string"],
third_option: {
title: "string",
why: "string",
criteria: "string",
},
},
});
const fallbackModel = process.env.AI_BUILDER_FALLBACK_MODEL || "grok-4-fast";
const modelsToTry = AI_MODEL && AI_MODEL !== fallbackModel
? [AI_MODEL, fallbackModel]
: [AI_MODEL];
let lastError = null;
for (const model of modelsToTry) {
try {
const response = await fetch(`${AI_BASE}/v1/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${AI_TOKEN}`,
},
body: JSON.stringify({
model,
temperature: 0.4,
max_tokens: 1400,
response_format: { type: "json_object" },
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userPrompt },
],
}),
});
if (!response.ok) {
const detail = await response.text();
throw new Error(`AI request failed: ${response.status} ${detail}`);
}
const data = await response.json();
const content = data && data.choices && data.choices[0] && data.choices[0].message
? data.choices[0].message.content
: "";
if (debug) {
console.log("AI model:", model);
console.log("AI message:", data && data.choices && data.choices[0] ? data.choices[0].message : null);
console.log("AI raw content:", typeof content, String(content).slice(0, 500));
}
const cleaned = stripJsonFences(String(content));
const parsed = safeJsonParse(cleaned);
if (!parsed) {
throw new Error("AI response was not valid JSON.");
}
return parsed;
} catch (error) {
lastError = error;
if (!shouldFallback(error) || model === fallbackModel) {
break;
}
}
}
throw lastError || new Error("AI request failed.");
}
function safeJsonParse(value) {
if (typeof value !== "string") {
return null;
}
try {
return JSON.parse(value);
} catch (error) {
const start = value.indexOf("{");
const end = value.lastIndexOf("}");
if (start === -1 || end === -1 || end <= start) {
return null;
}
try {
return JSON.parse(value.slice(start, end + 1));
} catch (error2) {
return null;
}
}
}
function stripJsonFences(value) {
if (typeof value !== "string") {
return value;
}
let output = value.trim();
if (output.startsWith("```")) {
output = output.replace(/^```(?:json)?\s*/i, "");
output = output.replace(/```$/i, "");
}
return output.trim();
}
function shouldFallback(error) {
if (!error) {
return false;
}
const message = typeof error === "string" ? error : error.message || "";
return message.includes("valid JSON");
}
function normalizeScores(scores, candidates) {
const normalized = {};
candidates.forEach((candidate) => {
normalized[candidate] = 50;
});
if (scores && typeof scores === "object") {
Object.keys(scores).forEach((key) => {
const candidate = candidates.find((name) => name.toLowerCase() === key.toLowerCase());
if (!candidate) {
return;
}
normalized[candidate] = clampNumber(scores[key], 0, 100, normalized[candidate]);
});
}
return normalized;
}
function buildRankingFromScores(scores, candidates) {
const entries = candidates.map((candidate) => ({
name: candidate,
score: clampNumber(scores[candidate], 0, 100, 50),
reason: "",
}));
return entries.sort((a, b) => b.score - a.score);
}
function normalizeAiOutput(aiData, context) {
const confidence = clampNumber(aiData.confidence, 0, 1, 0.5);
const shouldStop = typeof aiData.should_stop === "boolean"
? aiData.should_stop
: (context.questionCount >= context.minQuestions && confidence >= 0.82)
|| context.questionCount >= context.maxQuestions;
const normalizedRanking = normalizeRanking(aiData.ranking, context.candidates);
const question = normalizeQuestion(aiData.question, context, shouldStop);
return {
status: shouldStop ? "final" : "question",
confidence,
question,
ranking: normalizedRanking,
key_reasons: normalizeStringList(aiData.key_reasons, 4),
tradeoff_map: normalizeTradeoffs(aiData.tradeoff_map, context.candidates, context.language),
counterfactuals: normalizeCounterfactuals(aiData.counterfactuals, context.candidates, context.language),
actions: normalizeStringList(aiData.actions, 5),
third_option: normalizeThirdOption(aiData.third_option),
};
}
function normalizeResultOutput(aiData, context, fallbackRanking) {
const adjustedScores = normalizeAdjustedScores(aiData.adjusted_scores, context.candidates);
let ranking = normalizeRanking(aiData.ranking || fallbackRanking, context.candidates);
if (adjustedScores && adjustedScores.length) {
const reasonMap = new Map();
if (Array.isArray(aiData.ranking)) {
aiData.ranking.forEach((item) => {
const name = sanitizeText(item && item.name ? item.name : "").toLowerCase();
if (name) {
reasonMap.set(name, sanitizeText(item && item.reason ? item.reason : ""));
}
});
}
ranking = adjustedScores
.slice()
.sort((a, b) => b.score - a.score)
.map((item) => ({
name: item.name,
score: item.score,
reason: reasonMap.get(item.name.toLowerCase()) || "",
}));
}
return {
status: "final",
confidence: clampNumber(aiData.confidence, 0, 1, 0.75),
question: null,
ranking,
key_reasons: normalizeStringList(aiData.key_reasons, 6),
tradeoff_map: normalizeTradeoffs(aiData.tradeoff_map, context.candidates, context.language),
counterfactuals: normalizeCounterfactuals(aiData.counterfactuals, context.candidates, context.language),
actions: normalizeStringList(aiData.actions, 6),
third_option: normalizeThirdOption(aiData.third_option),
};
}
function buildFallbackResponse(context, meta) {
const fallback = getFallbackQuestion(context.questionCount, context.candidates, context.language);
const shouldStop = context.questionCount >= context.maxQuestions;
const ranking = normalizeRanking([], context.candidates);
const strings = getLanguageStrings(context.language);
return {
status: shouldStop ? "final" : "question",
confidence: 0.45,
question: shouldStop ? null : fallback,
ranking,
key_reasons: strings.fallback_reasons,
tradeoff_map: buildFallbackTradeoffs(context.candidates, context.language),
counterfactuals: buildFallbackCounterfactuals(context.candidates, context.language),
actions: strings.fallback_actions,
third_option: null,
warning: meta && meta.warning ? meta.warning : undefined,
};
}
function buildResultFallback(context, ranking, meta) {
const strings = getLanguageStrings(context.language);
return {
status: "final",
confidence: 0.6,
question: null,
ranking,
key_reasons: strings.fallback_reasons_result,
tradeoff_map: buildFallbackTradeoffs(context.candidates, context.language),
counterfactuals: buildFallbackCounterfactuals(context.candidates, context.language),
actions: strings.fallback_actions,
third_option: null,
warning: meta && meta.warning ? meta.warning : undefined,
};
}
function buildFallbackPlan(context, meta) {
const questions = [];
const targetCount = Math.min(context.maxQuestions, Math.max(context.minQuestions, 5));
for (let i = 0; i < targetCount; i += 1) {
const base = getFallbackQuestion(i, context.candidates, context.language);
questions.push(applyFallbackImpacts(base, context.candidates, i));
}
return {
status: "ready",
plan: {
base_scores: context.candidates.map((name) => ({ name, score: 50 })),
questions,
},
warning: meta && meta.warning ? meta.warning : undefined,
};
}
function applyFallbackImpacts(question, candidates, seed) {
const options = question.options.map((option, index) => ({
...option,
impact_scores: buildImpactScores(null, candidates, seed + index),
}));
return { ...question, options };
}
function normalizeRanking(ranking, candidates) {
const baseScores = candidates.map((name, index) => ({
name,
score: Math.max(100 - index * 8, 60),
reason: "",
}));
if (!Array.isArray(ranking) || ranking.length === 0) {
return baseScores;
}
const mapped = ranking.map((item, index) => ({
name: sanitizeText(item && item.name ? item.name : candidates[index] || ""),
score: clampNumber(item && item.score, 0, 100, Math.max(95 - index * 10, 55)),
reason: sanitizeText(item && item.reason ? item.reason : ""),
})).filter((item) => item.name);
const seen = new Set(mapped.map((item) => item.name.toLowerCase()));
candidates.forEach((candidate) => {
if (!seen.has(candidate.toLowerCase())) {
mapped.push({ name: candidate, score: 60, reason: "" });
}
});
return mapped;
}
function normalizeAdjustedScores(list, candidates) {
if (!Array.isArray(list)) {
return null;
}
const mapped = list.map((item) => ({
name: sanitizeText(item && item.name ? item.name : ""),
score: clampNumber(item && item.score, 0, 100, 50),
})).filter((item) => item.name);
if (!mapped.length) {
return null;
}
const seen = new Set(mapped.map((item) => item.name.toLowerCase()));
candidates.forEach((candidate) => {
if (!seen.has(candidate.toLowerCase())) {
mapped.push({ name: candidate, score: 50 });
}
});
return mapped;
}
function getLanguageStrings(language) {
if (language === "zh") {
return {
fallback_reasons: [
"AI 暂不可用,使用默认问答。",
"仍会根据你的答案收敛结果。",
],
fallback_reasons_result: [
"AI 暂不可用,使用默认结果。",
"排序基于你的答案影响。",
],
fallback_actions: [
"优先对比前两名的实际体验。",
"确认保修年限与本地售后覆盖。",
"关注套餐与促销窗口。",
],
tradeoffs: [
{ dimension: "易用性", why: "默认更容易上手。" },
{ dimension: "性价比", why: "成本与能力更平衡。" },
{ dimension: "升级空间", why: "更适合未来扩展。" },
],
counterfactuals: [
{ toggle: "如果预算更紧", change: "性价比更重要。" },
{ toggle: "如果性能最关键", change: "性能权重更高。" },
],
};
}
return {
fallback_reasons: [
"Using a fallback path while AI is unavailable.",
"We will still narrow choices based on your answers.",
],
fallback_reasons_result: [
"Using a fallback path while AI is unavailable.",
"Ranking is based on your answer impacts.",
],
fallback_actions: [
"Shortlist the top two and compare hands-on if possible.",
"Check warranty length and service coverage in your area.",
"Look for bundles or seasonal pricing changes.",
],
tradeoffs: [
{ dimension: "simplicity", why: "Straightforward default choice." },
{ dimension: "value", why: "Balances cost with capability." },
{ dimension: "upgrade headroom", why: "Leaves room for future needs." },
],
counterfactuals: [
{ toggle: "If budget tightens", change: "The value pick becomes more attractive." },
{ toggle: "If performance is critical", change: "The most capable option rises to the top." },
],
};
}
function normalizePlan(plan, context) {
const baseScores = normalizeBaseScores(plan && plan.base_scores, context.candidates);
const rawQuestions = Array.isArray(plan && plan.questions) ? plan.questions : [];
const questions = rawQuestions
.map((question, index) => normalizePlanQuestion(question, context, index))
.filter(Boolean);
const targetCount = Math.min(context.maxQuestions, Math.max(context.minQuestions, 5));
while (questions.length < targetCount) {
const fallback = applyFallbackImpacts(
getFallbackQuestion(questions.length, context.candidates, context.language),
context.candidates,
questions.length,
);
questions.push(fallback);
}
return {
base_scores: baseScores,
questions: questions.slice(0, context.maxQuestions),
};
}
function normalizePlanQuestion(question, context, index) {
if (!question || typeof question !== "object") {
return null;
}
const options = Array.isArray(question.options) ? question.options.slice(0, 5) : [];
if (options.length < 2) {
return applyFallbackImpacts(
getFallbackQuestion(index, context.candidates, context.language),
context.candidates,
index,
);
}
const normalizedOptions = options.map((option, optionIndex) => ({
id: sanitizeText(option.id || `o${index + 1}-${optionIndex + 1}`),
label: sanitizeText(option.label || ""),
value: sanitizeText(option.value || ""),
impact_hint: sanitizeText(option.impact_hint || ""),
impact_scores: buildImpactScores(option.impact_scores, context.candidates, optionIndex),
})).filter((option) => option.label);
if (normalizedOptions.length < 2) {
return applyFallbackImpacts(
getFallbackQuestion(index, context.candidates, context.language),
context.candidates,
index,
);
}
return {
id: sanitizeText(question.id || `q${index + 1}`),
text: sanitizeText(question.text || ""),
dimension: sanitizeText(question.dimension || ""),
info_gain_reason: sanitizeText(question.info_gain_reason || ""),
options: normalizedOptions,
};
}
function normalizeBaseScores(baseScores, candidates) {
const scores = candidates.map((name) => ({ name, score: 50 }));
if (!Array.isArray(baseScores)) {
return scores;
}
const mapped = baseScores.map((item) => ({
name: sanitizeText(item && item.name ? item.name : ""),
score: clampNumber(item && item.score, 0, 100, 50),
})).filter((item) => item.name);
const seen = new Set(mapped.map((item) => item.name.toLowerCase()));
candidates.forEach((candidate) => {
if (!seen.has(candidate.toLowerCase())) {
mapped.push({ name: candidate, score: 50 });
}
});
return mapped;
}
function buildImpactScores(impactScores, candidates, fallbackIndex) {
const normalized = {};
let hasValues = false;
candidates.forEach((candidate, index) => {
let score = 0;
if (impactScores && typeof impactScores === "object") {
const key = Object.keys(impactScores).find((name) => name.toLowerCase() === candidate.toLowerCase());
if (key) {
score = clampNumber(impactScores[key], -12, 12, 0);
}
}
if (score !== 0) {
hasValues = true;
}
normalized[candidate] = score;
});
if (!hasValues) {
const favored = candidates[fallbackIndex % candidates.length];
candidates.forEach((candidate, index) => {
normalized[candidate] = candidate === favored ? 8 : index === 0 ? 2 : 0;
});
}
return normalized;
}
function normalizeQuestion(question, context, shouldStop) {
if (shouldStop) {
return null;
}
if (!question || typeof question !== "object") {
return getFallbackQuestion(context.questionCount, context.candidates, context.language);
}
const options = Array.isArray(question.options) ? question.options.slice(0, 5) : [];
if (options.length < 2) {
return getFallbackQuestion(context.questionCount, context.candidates, context.language);
}
return {
id: sanitizeText(question.id || `q${context.questionCount + 1}`),
text: sanitizeText(question.text || ""),
dimension: sanitizeText(question.dimension || ""),
info_gain_reason: sanitizeText(question.info_gain_reason || ""),
options: options.map((option, index) => ({
id: sanitizeText(option.id || `o${index + 1}`),
label: sanitizeText(option.label || ""),
value: sanitizeText(option.value || ""),