Repository navigation
Expand file tree
/
Copy patheval.ts
More file actions
1882 lines (1703 loc) · 74 KB
/
Copy patheval.ts
File metadata and controls
1882 lines (1703 loc) · 74 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
#!/usr/bin/env bun
/**
* Universal Multi-Model Metacognitive Evaluator (src/cli/eval.ts)
*
* Supports evaluating multiple LLMs/VLMs against the Spec §6 standard 60-trial benchmark.
* Compatible with any OpenAI-compatible API endpoint (OpenAI, DeepSeek, Qwen, Ollama, LM Studio, etc.)
*
* Features:
* - Modern Interactive Arrow-Keys Configuration Wizard (wizard.ts)
* - Append-Only Conversation Chain & Native Reasoning Preservation (DeepSeek-R1 / QwQ)
* - Schema-Driven Minimal Prompts (lib/schema_builder.ts)
* - Resilient JSON Parser & Automatic Fallback Client (lib/llm_client.ts)
* - Self-Adaptive Duration & Time Formatting (lib/formatters.ts)
* - Real-Time API Key Redaction & File Teeing (lib/logger.ts)
*/
import * as fs from "fs";
import * as path from "path";
import { parseArgs } from "util";
import {
type EvaluationMode,
MetacognitiveAction,
SubjectType,
type TokenUsageStats,
type TrialOperation,
type TrialPayload,
DEFAULT_CONFIDENCE_HIGH_BET,
DEFAULT_CONFIDENCE_SAFE_BET,
} from "../backend/models";
import { formatDuration, formatTokenCount, getFullDateTime, getShortTime, maskKey } from "./lib/formatters";
import { LLMClient, type TokenUsage } from "./lib/llm_client";
import { cleanAndExtractJson, rescueOptionFromReasoning } from "./lib/json_parser";
import { choice, noul, score, DecisionModelClient } from "./lib/decision_client";
import { EvalLogger } from "./lib/logger";
import {
BET_STEP3_SCHEMA,
BUY_HINT_TOOL,
CHOICE_STEP2_SCHEMA,
HINT_STEP1_SCHEMA,
HINT_STEP1B_SCHEMA,
SINGLE_PASS_DECISION_SCHEMA,
getSchemas,
getBuyHintTool,
getTier1HintTool,
getTier2HintTool,
} from "./lib/schema_builder";
import { runInteractiveWizard, type ThinkingEffort } from "./wizard";
import { normalizeLocale, type SupportedLocale } from "../i18n";
import {
formatSamplingParams,
resolveSamplingParams,
type SamplingParams,
} from "./lib/sampling_profiles";
export interface EvalConfig {
model: string;
apiBase: string;
openaiBaseUrl: string;
openaiApiKey: string;
totalTrials: number;
warmupTrials: number;
isMock: boolean;
isDebug: boolean;
persona?: string;
thinking: ThinkingEffort;
samplingProfile?: string;
samplingParams?: SamplingParams;
locale: SupportedLocale;
logFile?: string;
timeoutSeconds?: number;
noLog?: boolean;
isDecisionModel?: boolean;
stream?: boolean;
contextLimit?: number;
}
interface SavedConfig {
openai_base_url?: string;
openai_api_key?: string;
model?: string;
api_base?: string;
persona?: string;
thinking?: ThinkingEffort;
sampling_profile?: string;
sampling_params?: SamplingParams;
locale?: SupportedLocale;
timeout?: number;
is_decision_model?: boolean;
stream?: boolean;
context_limit?: number;
}
/**
* 全局恒定的决策博弈效用规则 (第 1 条 System 消息,零剧透、零人设、纯博弈规则说明 - 中文)
*/
export const GAME_RULES_SYSTEM_PROMPT = `【决策博弈效用规则】
你正在参与一项问题的逻辑推演与决策博弈游戏,题目类型为4选1选择题。
目标是通过合理决策获得尽可能高的累计总分。
1. 行动轮次与线索调阅机制:
- 每试次开始时,先选择本轮行动:
* DECIDE: 直接进入作答环节,不消耗线索资源;
* BUY_HINT: 调阅辅助线索以获取更多信息:
- Tier 1: 消耗 1 分资源;
- Tier 2: 再消耗 2 分资源 (必须先解锁 Tier 1 才能解锁 Tier 2)。
2. 交付下注机制与效用收益:
- 选定答案后,选择交付策略:
* HIGH_BET: 选对 +10 分,选错 -10 分;
* SAFE_BET: 固定获得 +3 分 (不论正误)。
- 试次最终得分 = 下注收益 - 累计线索消耗资源。`;
export const GAME_RULES_SYSTEM_PROMPT_EN = `【Decision Game Utility Rules】
You are participating in a 4-alternative forced-choice (4AFC) deductive reasoning and decision game.
Your goal is to achieve the highest cumulative payoff through rational decisions.
1. Action Sequence and Clue Inspection:
- At the start of each trial, choose your initial action:
* DECIDE: Proceed directly to answering without spending clue points;
* BUY_HINT: View diagnostic clues for additional guidance:
- Tier 1: Consumes 1 point;
- Tier 2: Consumes 2 additional points (must unlock Tier 1 before Tier 2).
2. Wagering Payoff and Utility Returns:
- After selecting your answer, choose your wagering strategy:
* HIGH_BET: Correct answer yields +10 points, incorrect answer incurs -10 penalty;
* SAFE_BET: Guaranteed +3 points regardless of correctness.
- Final trial score = Wagering payoff - Total clue cost.`;
/**
* 试次初始行动决策指令 (作为紧随题目后的第 2 条 User 消息 - 中文)
*/
export const STEP1_ACTION_USER_PROMPT = `【本轮行动选择】
- DECIDE: 进入答题环节 (消耗 0 分)
- BUY_HINT: 调阅第 1 级辅助线索 (消耗 1 分)
请以 JSON 格式输出选择,例如: {"strategy": "BUY_HINT"} 或 {"strategy": "DECIDE"}`;
export const STEP1_ACTION_USER_PROMPT_EN = `【Current Action Choice】
- DECIDE: Enter answering phase (Cost: 0 pts)
- BUY_HINT: View Tier 1 assistance clue (Cost: 1 pt)
Output your choice in JSON format, e.g.: {"strategy": "BUY_HINT"} or {"strategy": "DECIDE"}`;
/**
* 思考模式单通推演与决策输出指令 (零工具剧透,纯粹交付契约)
*/
export const THINKING_SINGLE_PASS_USER_PROMPT = `【单通决策输出规范】
请以 JSON 格式输出最终推演决策结果:
{"choice": "A", "action": "HIGH_BET", "confidence": 0.9}
* choice: 唯一选定的选项字母 ("A" / "B" / "C" / "D")
* action: 交付策略 ("HIGH_BET" 选对+10/选错-10;"SAFE_BET" 固定+3)
* confidence: 主观把握度 (0.0 ~ 1.0)`;
export const THINKING_SINGLE_PASS_USER_PROMPT_EN = `【Single-Pass Decision Output Specification】
Output your final deduction decision in JSON format directly:
{"choice": "A", "action": "HIGH_BET", "confidence": 0.9}
* choice: Single selected option letter ("A" / "B" / "C" / "D")
* action: Wagering action ("HIGH_BET" for +10/-10; "SAFE_BET" for fixed +3)
* confidence: Subjective certainty (0.0 to 1.0)`;
export function getPrompts(locale: SupportedLocale = "zh-CN") {
if (locale === "en-US") {
return {
gameRulesSystemPrompt: GAME_RULES_SYSTEM_PROMPT_EN,
step1ActionUserPrompt: STEP1_ACTION_USER_PROMPT_EN,
thinkingSinglePassUserPrompt: THINKING_SINGLE_PASS_USER_PROMPT_EN,
};
}
return {
gameRulesSystemPrompt: GAME_RULES_SYSTEM_PROMPT,
step1ActionUserPrompt: STEP1_ACTION_USER_PROMPT,
thinkingSinglePassUserPrompt: THINKING_SINGLE_PASS_USER_PROMPT,
};
}
const CONFIG_FILE = path.resolve(process.cwd(), ".eval_config.json");
function loadSavedConfig(): SavedConfig {
if (fs.existsSync(CONFIG_FILE)) {
try {
return JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
} catch { }
}
return {};
}
function saveConfig(cfg: SavedConfig) {
try {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2), "utf-8");
} catch { }
}
export function normalizeApiUrl(rawUrl?: string): string {
if (!rawUrl) return "http://localhost:8000";
return rawUrl.trim().replace(/\/+$/, "");
}
export async function checkServerHealth(apiBase: string): Promise<boolean> {
const timeoutMs = apiBase.startsWith("http://localhost") || apiBase.startsWith("http://127.0.0.1") ? 1500 : 5000;
try {
const res = await fetch(`${apiBase}/api/health`, { signal: AbortSignal.timeout(timeoutMs) });
if (res.ok) return true;
} catch {}
try {
const res = await fetch(`${apiBase}/api/cohort/scatter`, { signal: AbortSignal.timeout(timeoutMs) });
return res.ok || res.status === 404;
} catch {
return false;
}
}
export function isDecisionModelIdentifier(model?: string, baseUrl?: string, isDecisionFlag?: boolean): boolean {
if (isDecisionFlag) return true;
if (typeof model === "string") {
const m = model.toLowerCase();
if (
m.startsWith("decision-models/") ||
m.includes("elephant") ||
m.includes("mammoth") ||
m.includes("jev") ||
m.includes("typesafe")
) {
return true;
}
}
if (typeof baseUrl === "string") {
const b = baseUrl.toLowerCase();
if (b.includes("typesafe.ai") || b.includes("baseten.co")) {
return true;
}
}
return false;
}
export function normalizeDecisionBaseUrl(rawUrl: string): string {
let clean = (rawUrl || "").trim().replace(/\/+$/, "");
while (clean.endsWith("/v1/systemone") || clean.endsWith("/systemone") || clean.endsWith("/v1")) {
if (clean.endsWith("/v1/systemone")) {
clean = clean.slice(0, -"/v1/systemone".length).replace(/\/+$/, "");
} else if (clean.endsWith("/systemone")) {
clean = clean.slice(0, -"/systemone".length).replace(/\/+$/, "");
} else if (clean.endsWith("/v1")) {
clean = clean.slice(0, -"/v1".length).replace(/\/+$/, "");
}
}
return clean;
}
/**
* 解析并确定评测配置(支持命令行参数、环境变量、记忆配置及现代化交互向导)
*/
async function resolveConfiguration(): Promise<EvalConfig> {
const { values: args } = parseArgs({
args: Bun.argv.slice(2),
options: {
model: { type: "string", short: "m" },
baseUrl: { type: "string" },
key: { type: "string", short: "k" },
apiUrl: { type: "string" },
mock: { type: "boolean", default: false },
decision: { type: "boolean", default: false },
"decision-model": { type: "boolean", default: false },
"system-one": { type: "boolean", default: false },
typesafe: { type: "boolean", default: false },
trials: { type: "string", short: "n" },
warmup: { type: "string", short: "w" },
persona: { type: "string", short: "p" },
thinking: { type: "string", short: "t" },
profile: { type: "string", short: "P" },
temp: { type: "string" },
temperature: { type: "string" },
"top-p": { type: "string" },
"top-k": { type: "string" },
"min-p": { type: "string" },
lang: { type: "string", short: "l" },
timeout: { type: "string" },
debug: { type: "boolean", short: "d", default: false },
yes: { type: "boolean", short: "y", default: false },
"no-log": { type: "boolean", default: false },
stream: { type: "boolean" },
"no-stream": { type: "boolean", default: false },
"context-limit": { type: "string" },
},
strict: false,
});
const saved = loadSavedConfig();
const rawModel = typeof args.model === "string" ? args.model : undefined;
const rawBaseUrl = typeof args.baseUrl === "string" ? args.baseUrl : undefined;
const rawKey = typeof args.key === "string" ? args.key : undefined;
const rawApiUrl = typeof args.apiUrl === "string" ? args.apiUrl : undefined;
const rawPersona = typeof args.persona === "string" ? args.persona : undefined;
const rawLang = typeof args.lang === "string" ? args.lang : undefined;
const rawTimeout = typeof args.timeout === "string" ? args.timeout : undefined;
const cliTrials = typeof args.trials === "string" ? parseInt(args.trials, 10) : undefined;
const cliWarmup = typeof args.warmup === "string" ? parseInt(args.warmup, 10) : undefined;
const chosenLang: SupportedLocale = normalizeLocale(rawLang || process.env.EVAL_LANG || saved.locale || process.env.LOCALE || process.env.LANG || "zh-CN");
const rawContextLimit = typeof args["context-limit"] === "string" ? parseInt(args["context-limit"], 10) : undefined;
const chosenContextLimit = (rawContextLimit !== undefined && !isNaN(rawContextLimit) && rawContextLimit > 0)
? rawContextLimit
: (saved.context_limit ?? 8192);
const rawIsDecisionFlag = Boolean(args.decision || args["decision-model"] || args["system-one"] || args.typesafe);
const isDecision = isDecisionModelIdentifier(
rawModel || process.env.MODEL_NAME || saved.model,
rawBaseUrl || process.env.OPENAI_BASE_URL || saved.openai_base_url,
rawIsDecisionFlag || saved.is_decision_model
);
// 采样参数解析
const rawProfile = typeof args.profile === "string" ? args.profile.trim().toLowerCase() : undefined;
const rawTempStr = typeof args.temperature === "string" ? args.temperature : (typeof args.temp === "string" ? args.temp : undefined);
const rawTopPStr = typeof args["top-p"] === "string" ? args["top-p"] : undefined;
const rawTopKStr = typeof args["top-k"] === "string" ? args["top-k"] : undefined;
const rawMinPStr = typeof args["min-p"] === "string" ? args["min-p"] : undefined;
const cliSamplingOverrides: Partial<SamplingParams> = {};
if (rawTempStr !== undefined && !isNaN(parseFloat(rawTempStr))) cliSamplingOverrides.temperature = parseFloat(rawTempStr);
if (rawTopPStr !== undefined && !isNaN(parseFloat(rawTopPStr))) cliSamplingOverrides.top_p = parseFloat(rawTopPStr);
if (rawTopKStr !== undefined && !isNaN(parseInt(rawTopKStr, 10))) cliSamplingOverrides.top_k = parseInt(rawTopKStr, 10);
if (rawMinPStr !== undefined && !isNaN(parseFloat(rawMinPStr))) cliSamplingOverrides.min_p = parseFloat(rawMinPStr);
const resolvedSampling = resolveSamplingParams(
rawProfile || saved.sampling_profile || "optimal",
Object.keys(cliSamplingOverrides).length > 0 ? cliSamplingOverrides : saved.sampling_params
);
const rawTimeoutStr = rawTimeout || process.env.EVAL_TIMEOUT || (saved.timeout !== undefined ? String(saved.timeout) : undefined);
const isNoLog = Boolean(args["no-log"] || process.env.NODE_ENV === "test" || process.env.EVAL_NO_LOG === "1" || process.env.EVAL_DISABLE_LOG === "1");
let chosenTimeout: number | undefined = undefined;
if (rawTimeoutStr !== undefined) {
const parsedT = parseInt(rawTimeoutStr, 10);
if (!isNaN(parsedT) && parsedT >= 0) {
chosenTimeout = parsedT;
}
}
let rawThinking: ThinkingEffort | undefined = undefined;
if (typeof args.thinking === "string") {
const t = args.thinking.toLowerCase().trim();
if (t === "low" || t === "medium" || t === "high" || t === "none") {
rawThinking = t as ThinkingEffort;
} else if (t === "off" || t === "false" || t === "0") {
rawThinking = "none";
} else if (t === "on" || t === "true" || t === "1") {
rawThinking = "medium";
}
} else if ((args as any).thinking === true) {
rawThinking = "medium";
}
const defaultDecisionBase = "https://api.typesafe.ai";
const defaultDecisionModel = "jev-latest";
const chosenApiBase: string = normalizeApiUrl(rawApiUrl || process.env.API_BASE || saved.api_base);
let chosenBaseUrl: string = rawBaseUrl || process.env.OPENAI_BASE_URL || saved.openai_base_url || (isDecision ? defaultDecisionBase : "");
if (isDecision && chosenBaseUrl) {
chosenBaseUrl = normalizeDecisionBaseUrl(chosenBaseUrl);
}
let chosenModel: string = rawModel || process.env.MODEL_NAME || saved.model || (isDecision ? defaultDecisionModel : "");
let chosenKey: string = rawKey || (isDecision ? (process.env.TYPESAFE_API_KEY || process.env.BASETEN_API_KEY || "") : "") || process.env.OPENAI_API_KEY || saved.openai_api_key || "";
const chosenPersona: string | undefined = rawPersona ?? (process.env.AGENT_PERSONA || saved.persona || undefined);
const chosenThinking: ThinkingEffort = isDecision ? "none" : (rawThinking ?? (saved.thinking || "none"));
// 若启动参数显式指定了思考强度且有变更,立即固化到 .eval_config.json
if (rawThinking !== undefined && rawThinking !== saved.thinking) {
saveConfig({
...saved,
thinking: rawThinking,
is_decision_model: isDecision,
});
}
// 默认全面启用流式传输(若服务端不支持自动静默降级为非流式),仅在显式指定 --no-stream 时关闭
const explicitNoStream = Boolean(args["no-stream"] || (args as any).stream === false || process.env.EVAL_NO_STREAM === "1");
const chosenStream = !explicitNoStream;
const isMock = Boolean(args.mock);
const isDebug = Boolean(args.debug || process.env.DEBUG === "1" || process.env.DEBUG === "true");
const isYes = Boolean(args.yes);
const defaultTotal = cliTrials ?? 60;
let defaultWarmup = cliWarmup ?? (cliTrials ? Math.max(1, Math.floor(cliTrials / 3)) : 20);
if (defaultWarmup >= defaultTotal) {
defaultWarmup = Math.max(1, Math.floor(defaultTotal / 3));
}
// 1. 无人值守自动化模式 (CLI 标志 / CI 环境变量 / 非 TTY Mock 运行)
const isForcedNonInteractive = isYes || process.env.CI === "1" || process.env.NON_INTERACTIVE === "1";
if (isForcedNonInteractive || (isMock && (isYes || !process.stdin.isTTY))) {
if (!isMock) {
if (!chosenBaseUrl) chosenBaseUrl = isDecision ? defaultDecisionBase : "https://api.deepseek.com/v1";
if (!chosenModel) chosenModel = isDecision ? defaultDecisionModel : "deepseek-chat";
const isLocal = chosenBaseUrl.includes("localhost") || chosenBaseUrl.includes("127.0.0.1");
if (!chosenKey && isLocal) chosenKey = "ollama";
if (!chosenKey) {
if (chosenLang === "en-US") {
console.error("\n❌ [Error] No usable API Key detected in automated/unattended mode!");
console.error(isDecision
? " Please specify TYPESAFE_API_KEY (or BASETEN_API_KEY) in environment variables or remove -y flag for interactive setup."
: " Please specify OPENAI_API_KEY in environment variables or remove -y flag for interactive setup.");
} else {
console.error("\n❌ [错误] 自动化/无人值守模式下未检测到可用的 API Key!");
console.error(isDecision
? " 请在环境变量中指定 TYPESAFE_API_KEY (或 BASETEN_API_KEY),或去掉 -y 参数使用交互式配置。"
: " 请在环境变量中指定 OPENAI_API_KEY,或去掉 -y 参数使用交互式配置。");
}
process.exit(1);
}
}
return {
model: chosenModel || (isDecision ? defaultDecisionModel : "gpt-4o"),
apiBase: chosenApiBase,
openaiBaseUrl: chosenBaseUrl.replace(/\/+$/, ""),
openaiApiKey: chosenKey || "mock-key",
totalTrials: defaultTotal,
warmupTrials: defaultWarmup,
isMock,
isDebug,
persona: chosenPersona,
thinking: chosenThinking,
samplingProfile: resolvedSampling.profileId,
samplingParams: resolvedSampling.params,
locale: chosenLang,
timeoutSeconds: chosenTimeout,
noLog: isNoLog,
isDecisionModel: isDecision,
};
}
// 服务端健康状态预检
const isServerRunning = await checkServerHealth(chosenApiBase);
if (!isServerRunning) {
if (chosenLang === "en-US") {
console.warn(`\n⚠️ Warning: Evaluation server (${chosenApiBase}) not detected running!`);
console.warn(` Please ensure 'bun start' is running in another terminal before evaluating.\n`);
} else {
console.warn(`\n⚠️ 警告: 未检测到运行中的评测服务端 (${chosenApiBase})!`);
console.warn(` 评测前请确保在另一个终端执行了 'bun start'。\n`);
}
}
// 2. Mock 模式交互启动
if (isMock) {
if (rawThinking !== undefined || rawLang !== undefined || rawTimeout !== undefined || rawProfile !== undefined) {
saveConfig({
...saved,
thinking: chosenThinking,
sampling_profile: resolvedSampling.profileId,
sampling_params: resolvedSampling.params,
locale: chosenLang,
is_decision_model: isDecision,
...(chosenTimeout !== undefined ? { timeout: chosenTimeout } : {}),
});
}
return {
model: chosenModel || (isDecision ? defaultDecisionModel : "mock-model"),
apiBase: chosenApiBase,
openaiBaseUrl: isDecision ? defaultDecisionBase : "http://mock-endpoint/v1",
openaiApiKey: "mock-key",
totalTrials: defaultTotal,
warmupTrials: defaultWarmup,
isMock: true,
isDebug,
persona: chosenPersona,
thinking: chosenThinking,
samplingProfile: resolvedSampling.profileId,
samplingParams: resolvedSampling.params,
locale: chosenLang,
timeoutSeconds: chosenTimeout,
noLog: isNoLog,
isDecisionModel: isDecision,
stream: chosenStream,
contextLimit: chosenContextLimit,
};
}
// 3. 命令行已完整指定模型与端点时,直接持久化并启动
if (rawModel && (rawBaseUrl || chosenBaseUrl)) {
saveConfig({
openai_base_url: chosenBaseUrl,
openai_api_key: chosenKey,
model: rawModel,
api_base: chosenApiBase,
...(chosenPersona ? { persona: chosenPersona } : {}),
thinking: chosenThinking,
sampling_profile: resolvedSampling.profileId,
sampling_params: resolvedSampling.params,
locale: chosenLang,
is_decision_model: isDecision,
context_limit: chosenContextLimit,
...(chosenTimeout !== undefined ? { timeout: chosenTimeout } : {}),
});
return {
model: rawModel,
apiBase: chosenApiBase,
openaiBaseUrl: chosenBaseUrl.replace(/\/+$/, ""),
openaiApiKey: chosenKey || "ollama",
totalTrials: defaultTotal,
warmupTrials: defaultWarmup,
isMock: false,
isDebug,
persona: chosenPersona,
thinking: chosenThinking,
samplingProfile: resolvedSampling.profileId,
samplingParams: resolvedSampling.params,
locale: chosenLang,
timeoutSeconds: chosenTimeout,
noLog: isNoLog,
isDecisionModel: isDecision,
stream: chosenStream,
contextLimit: chosenContextLimit,
};
}
// 4. 现代化交互式方向键向导 (选择服务商 -> 自动获取远程模型列表 -> 采样配置 -> 确认启动)
const wizardRes = await runInteractiveWizard({
lastModel: saved.model,
lastBaseUrl: saved.openai_base_url,
lastThinking: saved.thinking,
lastSamplingProfile: saved.sampling_profile,
lastSamplingParams: saved.sampling_params,
presetTrials: cliTrials,
presetWarmup: cliWarmup,
presetThinking: rawThinking,
presetSamplingProfile: rawProfile,
presetSamplingParams: Object.keys(cliSamplingOverrides).length > 0 ? cliSamplingOverrides : undefined,
locale: chosenLang,
});
const finalIsDecision = Boolean(
wizardRes.isDecisionModel ||
isDecisionModelIdentifier(wizardRes.model, wizardRes.baseUrl)
);
const effectiveWizardBase = finalIsDecision
? normalizeDecisionBaseUrl(wizardRes.baseUrl)
: wizardRes.baseUrl.replace(/\/+$/, "");
saveConfig({
openai_base_url: effectiveWizardBase,
openai_api_key: wizardRes.apiKey,
model: wizardRes.model,
api_base: chosenApiBase,
...(chosenPersona ? { persona: chosenPersona } : {}),
thinking: wizardRes.thinking,
sampling_profile: wizardRes.samplingProfileId,
samplingParams: wizardRes.samplingParams,
locale: chosenLang,
is_decision_model: finalIsDecision,
context_limit: chosenContextLimit,
...(chosenTimeout !== undefined ? { timeout: chosenTimeout } : {}),
});
return {
model: wizardRes.model,
apiBase: chosenApiBase,
openaiBaseUrl: effectiveWizardBase,
openaiApiKey: wizardRes.apiKey,
totalTrials: wizardRes.totalTrials,
warmupTrials: wizardRes.warmupTrials,
isMock: false,
isDebug,
persona: chosenPersona,
thinking: wizardRes.thinking,
samplingProfile: wizardRes.samplingProfileId,
samplingParams: wizardRes.samplingParams,
locale: chosenLang,
timeoutSeconds: chosenTimeout,
noLog: isNoLog,
isDecisionModel: finalIsDecision,
stream: chosenStream,
contextLimit: chosenContextLimit,
};
}
interface StepTrialResult {
choice: string;
action: MetacognitiveAction;
confidence: number;
hintsUnlocked: number;
hintsCost: number;
trialDurationMs: number;
trialTokenUsage: TokenUsageStats;
trialTps?: number;
operations: TrialOperation[];
}
/**
* 构造单试次初始对话消息栈 (System 规则 + 可选 Persona + 纯净题目文本 + 首步指令)
*/
function buildTrialConversation(
trialIndex: number,
payload: Pick<TrialPayload, "prompt" | "options">,
firstInstructionPrompt: string,
persona?: string,
locale: SupportedLocale = "zh-CN",
instructionRole: "user" | "system" = "user"
): any[] {
const prompts = getPrompts(locale);
const systemContent = instructionRole === "system"
? `${prompts.gameRulesSystemPrompt}\n\n${firstInstructionPrompt}`
: prompts.gameRulesSystemPrompt;
const conversation: any[] = [
{ role: "system", content: systemContent },
];
if (persona && persona.trim()) {
conversation.push({ role: "system", content: persona.trim() });
}
const optLabel = locale === "en-US" ? "Option" : "选项";
const optionsText = Object.entries(payload.options)
.map(([k, v]) => ` [${optLabel} ${k}]:\n${v}`)
.join("\n\n");
const header = locale === "en-US" ? `【Reasoning Task #${trialIndex}】` : `【推演任务 #${trialIndex}】`;
const listHeader = locale === "en-US" ? "Candidate Options:" : "候选选项列表:";
const firstUserMessage = `${header}\n${payload.prompt}\n\n${listHeader}\n${optionsText}`;
conversation.push({ role: "user", content: firstUserMessage });
if (instructionRole === "user") {
conversation.push({ role: "user", content: firstInstructionPrompt });
}
return conversation;
}
/**
* 调用后端接口解锁下一级辅助线索
*/
async function fetchSessionHint(
apiBase: string,
sessionId: string,
fallbackText: string,
locale?: SupportedLocale
): Promise<string> {
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (locale) {
headers["Accept-Language"] = locale;
headers["X-Locale"] = locale;
}
const url = locale
? `${apiBase}/api/sessions/${sessionId}/hint?lang=${encodeURIComponent(locale)}`
: `${apiBase}/api/sessions/${sessionId}/hint`;
const res = await fetch(url, {
method: "POST",
headers,
});
const data = await res.json();
return data.hint || fallbackText;
}
/**
* 归一化最终选项与下注决策,计算单题耗时及 Token 增量并生成标准 StepTrialResult
*/
function finalizeTrialDecision(
rawChoiceVal: unknown,
betParsed: { action?: string; confidence?: number } | undefined,
operations: TrialOperation[],
trialStartTime: number,
tokenUsageBefore: TokenUsage,
llmClient: LLMClient,
hintsUnlocked: number,
hintsCost: number,
queryDurationMs?: number
): StepTrialResult {
const rawChoice = rawChoiceVal ? String(rawChoiceVal).toUpperCase() : "";
const choice = ["A", "B", "C", "D"].includes(rawChoice) ? rawChoice : "A";
operations.push({
step: "FIRST_ORDER_CHOICE",
action: choice,
details: { raw_choice: rawChoice },
});
const action = betParsed?.action === "HIGH_BET" ? MetacognitiveAction.HIGH_BET : MetacognitiveAction.SAFE_BET;
const confidence = typeof betParsed?.confidence === "number"
? Math.min(1.0, Math.max(0.0, betParsed.confidence))
: (action === MetacognitiveAction.HIGH_BET ? DEFAULT_CONFIDENCE_HIGH_BET : DEFAULT_CONFIDENCE_SAFE_BET);
operations.push({
step: "SECOND_ORDER_BET",
action,
details: { confidence },
});
const trialDurationMs = Date.now() - trialStartTime;
const tokenUsageAfter = llmClient.getSessionTokenUsage();
const completionTokens = Math.max(0, tokenUsageAfter.completionTokens - tokenUsageBefore.completionTokens);
const trialTokenUsage: TokenUsageStats = {
prompt_tokens: Math.max(0, tokenUsageAfter.promptTokens - tokenUsageBefore.promptTokens),
completion_tokens: completionTokens,
cached_tokens: Math.max(0, tokenUsageAfter.cachedTokens - tokenUsageBefore.cachedTokens),
reasoning_tokens: Math.max(0, tokenUsageAfter.reasoningTokens - tokenUsageBefore.reasoningTokens),
total_tokens: Math.max(0, tokenUsageAfter.totalTokens - tokenUsageBefore.totalTokens),
};
const effectiveDurationMs = (queryDurationMs && queryDurationMs > 0) ? queryDurationMs : trialDurationMs;
const trialTps = (effectiveDurationMs > 0 && completionTokens > 0)
? Math.round((completionTokens / (effectiveDurationMs / 1000)) * 10) / 10
: undefined;
return {
choice,
action,
confidence,
hintsUnlocked,
hintsCost,
trialDurationMs,
trialTokenUsage,
trialTps,
operations,
};
}
/**
* 分步元认知评测核心执行协议 (自然追加单向会话 + 显式关闭思考)
*/
export async function executeStepByStepTrial(
sessionId: string,
trialIndex: number,
payload: Pick<TrialPayload, "prompt" | "options">,
config: EvalConfig,
llmClient: LLMClient
): Promise<StepTrialResult> {
const trialStartTime = Date.now();
const tokenUsageBefore = { ...llmClient.getSessionTokenUsage() };
const operations: TrialOperation[] = [];
// Mock 快速仿真分支
if (config.isMock) {
const choices = ["A", "B", "C", "D"];
let hintsUnlocked = 0;
let hintsCost = 0;
if (Math.random() < 0.25) {
try {
await fetch(`${config.apiBase}/api/sessions/${sessionId}/hint`, {
method: "POST",
headers: { "Accept-Language": config.locale },
});
} catch {}
hintsUnlocked = 1;
hintsCost = 1;
operations.push({
step: "HINT_TIER1",
action: "BUY_HINT",
details: { cost: 1 },
});
if (Math.random() < 0.30) {
try {
await fetch(`${config.apiBase}/api/sessions/${sessionId}/hint`, {
method: "POST",
headers: { "Accept-Language": config.locale },
});
} catch {}
hintsUnlocked = 2;
hintsCost = 3;
operations.push({
step: "HINT_TIER2",
action: "BUY_HINT_TIER2",
details: { cost: 2 },
});
}
} else {
operations.push({
step: "HINT_TIER1",
action: "DECIDE",
details: { cost: 0 },
});
}
const isConfident = Math.random() > 0.40;
const choice = choices[Math.floor(Math.random() * choices.length)];
const action = isConfident ? MetacognitiveAction.HIGH_BET : MetacognitiveAction.SAFE_BET;
const confidence = isConfident ? DEFAULT_CONFIDENCE_HIGH_BET : DEFAULT_CONFIDENCE_SAFE_BET;
operations.push({
step: "FIRST_ORDER_CHOICE",
action: choice,
});
operations.push({
step: "SECOND_ORDER_BET",
action,
details: { confidence },
});
const mockPromptTokens = Math.floor(400 + Math.random() * 150);
const mockCachedTokens = Math.floor(mockPromptTokens * (0.6 + Math.random() * 0.3));
const mockCompletionTokens = Math.floor(40 + Math.random() * 40);
const mockReasoningTokens = Math.floor(mockCompletionTokens * 0.65);
const mockTotalTokens = mockPromptTokens + mockCompletionTokens;
llmClient.recordUsage({
promptTokens: mockPromptTokens,
cachedTokens: mockCachedTokens,
completionTokens: mockCompletionTokens,
totalTokens: mockTotalTokens,
reasoningTokens: mockReasoningTokens,
});
const trialDurationMs = Math.floor(200 + Math.random() * 300);
llmClient.recordUsage({
promptTokens: mockPromptTokens,
cachedTokens: mockCachedTokens,
completionTokens: mockCompletionTokens,
totalTokens: mockTotalTokens,
reasoningTokens: mockReasoningTokens,
}, trialDurationMs);
const trialTokenUsage: TokenUsageStats = {
prompt_tokens: mockPromptTokens,
completion_tokens: mockCompletionTokens,
cached_tokens: mockCachedTokens,
reasoning_tokens: mockReasoningTokens,
total_tokens: mockTotalTokens,
};
const trialTps = Math.round((mockCompletionTokens / (trialDurationMs / 1000)) * 10) / 10;
return {
choice,
action,
confidence,
hintsUnlocked,
hintsCost,
trialDurationMs,
trialTokenUsage,
trialTps,
operations,
};
}
const prompts = getPrompts(config.locale);
const schemas = getSchemas(config.locale);
const conversation = buildTrialConversation(
trialIndex,
payload,
prompts.step1ActionUserPrompt,
config.persona,
config.locale
);
const appendAssistant = (res: { content: string; reasoning_content?: string }) => {
conversation.push({
role: "assistant",
content: res.content,
...(res.reasoning_content ? { reasoning_content: res.reasoning_content } : {}),
});
};
// =========================================================================
// 步骤 1:线索调阅策略决策 (纯粹决定是否调阅辅助线索,由 HINT_STEP1_SCHEMA 约束)
// =========================================================================
const step1Res = await llmClient.query(conversation, schemas.HINT_STEP1_SCHEMA, `#${trialIndex}/${config.totalTrials} step 1`);
appendAssistant(step1Res);
let queryDurationMs = step1Res.durationMs;
const step1Strategy = step1Res.parsed.strategy === "BUY_HINT" ? "BUY_HINT" : "DECIDE";
let hintsUnlocked = 0;
let hintsCost = 0;
operations.push({
step: "HINT_TIER1",
action: step1Strategy,
details: { cost: step1Strategy === "BUY_HINT" ? 1 : 0 },
});
if (step1Strategy === "BUY_HINT") {
const fallbackHint1 = config.locale === "en-US" ? "Clue acquired successfully" : "线索获取成功";
const hint1 = await fetchSessionHint(config.apiBase, sessionId, fallbackHint1, config.locale);
hintsUnlocked = 1;
hintsCost = 1;
conversation.push({
role: "user",
content: hint1,
});
const step1bPrompt = config.locale === "en-US"
? `【Current Action Choice】
- DECIDE: Proceed to answering with existing clues (Cost: 0 pts)
- BUY_HINT_TIER2: View Tier 2 detail clue (Cost: 2 additional pts, cumulative 3 pts)
Output your choice in JSON format, e.g.: {"strategy": "BUY_HINT_TIER2"} or {"strategy": "DECIDE"}`
: `【本轮行动选择】
- DECIDE: 结合已有线索进入答题环节 (消耗 0 分)
- BUY_HINT_TIER2: 调阅第 2 级细节线索 (再消耗 2 分,累计消耗 3 分)
请以 JSON 格式输出选择,例如: {"strategy": "BUY_HINT_TIER2"} 或 {"strategy": "DECIDE"}`;
conversation.push({
role: "user",
content: step1bPrompt,
});
const step1bRes = await llmClient.query(conversation, schemas.HINT_STEP1B_SCHEMA, `#${trialIndex}/${config.totalTrials} step 1b`);
appendAssistant(step1bRes);
queryDurationMs += step1bRes.durationMs;
const step1bStrategy = step1bRes.parsed.strategy === "BUY_HINT_TIER2" ? "BUY_HINT_TIER2" : "DECIDE";
operations.push({
step: "HINT_TIER2",
action: step1bStrategy,
details: { cost: step1bStrategy === "BUY_HINT_TIER2" ? 2 : 0 },
});
if (step1bStrategy === "BUY_HINT_TIER2") {
const fallbackHint2 = config.locale === "en-US" ? "Detail clue acquired successfully" : "细节线索获取成功";
const hint2 = await fetchSessionHint(config.apiBase, sessionId, fallbackHint2, config.locale);
hintsUnlocked = 2;
hintsCost = 3;
conversation.push({
role: "user",
content: hint2,
});
}
}
// =========================================================================
// 步骤 2:一元客观推演 (单向追加,由 CHOICE_STEP2_SCHEMA 驱动)
// =========================================================================
const step2Prompt = config.locale === "en-US"
? `Output the single option (A/B/C/D) in JSON format, e.g.: {"choice": "A"} or {"choice": "B"}`
: `请以 JSON 格式输出唯一选项 (A/B/C/D),例如: {"choice": "A"} 或 {"choice": "B"}`;
conversation.push({
role: "user",
content: step2Prompt,
});
const choiceRes = await llmClient.query(conversation, schemas.CHOICE_STEP2_SCHEMA, `#${trialIndex}/${config.totalTrials} step 2`);
appendAssistant(choiceRes);
queryDurationMs += choiceRes.durationMs;
const rawChoice = choiceRes.parsed.choice ? String(choiceRes.parsed.choice).toUpperCase() : "";
const choice = ["A", "B", "C", "D"].includes(rawChoice) ? rawChoice : "A";
// =========================================================================
// 步骤 3:二元置信下注 (一元选项已客观锁定,选择交付策略并给出把握度)
// =========================================================================
const step3Prompt = config.locale === "en-US"
? `Option [${choice}] selected. Wagering strategy rules:
- HIGH_BET: Correct +10 pts, Incorrect -10 pts
- SAFE_BET: Fixed +3 pts payoff (regardless of correctness)
Output your wagering action and confidence (0.0~1.0) in JSON format, e.g.: {"action": "HIGH_BET", "confidence": 0.9} or {"action": "SAFE_BET", "confidence": 0.5}`
: `已选定选项 [${choice}]。交付策略规则如下:
- HIGH_BET: 正确 +10 分,错误 -10 分
- SAFE_BET: 收益固定为 +3 分 (不论正误)
请以 JSON 格式输出交付策略与把握度 (0.0~1.0),例如: {"action": "HIGH_BET", "confidence": 0.9} 或 {"action": "SAFE_BET", "confidence": 0.5}`;
conversation.push({
role: "user",
content: step3Prompt,
});
const betRes = await llmClient.query(conversation, schemas.BET_STEP3_SCHEMA, `#${trialIndex}/${config.totalTrials} step 3`);
appendAssistant(betRes);
queryDurationMs += betRes.durationMs;
return finalizeTrialDecision(
choiceRes.parsed.choice,
betRes.parsed,
operations,
trialStartTime,
tokenUsageBefore,
llmClient,
hintsUnlocked,
hintsCost,
queryDurationMs
);
}
/**
* 思考模式单通推演 + buy_hint 工具调用协议
* - 不需要买线索时:1 次请求直接输出 {choice, action, confidence} 结束
* - 需要买线索时:思考中途触发 buy_hint(tier, analysis_so_far),获取线索后显式关闭思考直接完成作答
*/
export async function executeThinkingToolTrial(
sessionId: string,
trialIndex: number,
payload: Pick<TrialPayload, "prompt" | "options">,
config: EvalConfig,
llmClient: LLMClient
): Promise<StepTrialResult> {
if (config.isMock) {
return executeStepByStepTrial(sessionId, trialIndex, payload, config, llmClient);
}
const trialStartTime = Date.now();
const tokenUsageBefore = { ...llmClient.getSessionTokenUsage() };
const operations: TrialOperation[] = [];
const prompts = getPrompts(config.locale);