142 lines
7.0 KiB
JavaScript
142 lines
7.0 KiB
JavaScript
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||
import path from 'node:path';
|
||
import { parseArgs } from 'node:util';
|
||
import { scoreObjective } from './src/objective-scorer.mjs';
|
||
import { formatMarkdown, summarize } from './src/report.mjs';
|
||
import { judgeVisual } from './src/vlm-judge.mjs';
|
||
|
||
const json = async file => JSON.parse((await readFile(file, 'utf8')).replace(/^\uFEFF/u, ''));
|
||
const writeJson = (file, value) => writeFile(file, JSON.stringify(value, null, 2) + '\n');
|
||
const catalog = await json(new URL('./cases/20-templates-manifest.json', import.meta.url));
|
||
const help = [
|
||
'node evals/xiaoyi-golden/run.mjs --list',
|
||
'node evals/xiaoyi-golden/run.mjs --plan <用例计划.json> --out <报告目录> [--template <ID>] [--dry-run | --live]',
|
||
'默认离线回放。在线模式需要 XIAOYI_EVAL_VLM_ENDPOINT 和 XIAOYI_EVAL_VLM_MODEL,可通过 XIAOYI_EVAL_VLM_API_KEY 提供密钥。',
|
||
].join('\n');
|
||
|
||
function within(parent, child) {
|
||
const relative = path.relative(parent, child);
|
||
return relative === '' || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith('..' + path.sep));
|
||
}
|
||
|
||
function selectRuns(plan, templates, baseDir, destination) {
|
||
if (!Array.isArray(plan.runs)) throw Error('用例计划缺少 runs 数组');
|
||
const known = new Set(catalog.templates.map(template => template.id));
|
||
const ids = new Set();
|
||
const index = new Map();
|
||
for (const run of plan.runs) {
|
||
const { templateId, id = templateId, deliveryDir } = run;
|
||
if (!known.has(templateId) || !/^[A-Za-z0-9_-]+$/.test(id) || ids.has(id)) throw Error('用例编号无效、重复或模板未知');
|
||
if (typeof deliveryDir !== 'string' || !deliveryDir.trim()) throw Error('用例缺少成品目录 ' + id);
|
||
ids.add(id);
|
||
const root = path.resolve(baseDir, deliveryDir);
|
||
if (within(root, destination)) throw Error('报告目录须在成品目录之外 ' + id);
|
||
const entries = index.get(templateId) ?? [];
|
||
entries.push({ ...run, id, deliveryDir: root });
|
||
index.set(templateId, entries);
|
||
}
|
||
return templates.flatMap(template =>
|
||
(index.get(template.id) ?? [{ id: template.id, templateId: template.id }]).map(run => ({ run, template })));
|
||
}
|
||
|
||
function productionEvidence(production) {
|
||
if (!production) return undefined;
|
||
const { modelId, protocol, firstPass, cost } = production;
|
||
if (typeof modelId !== 'string' || !modelId.trim() || typeof protocol !== 'string' || !protocol.trim() ||
|
||
(firstPass !== undefined && typeof firstPass !== 'boolean') ||
|
||
(cost && (!/^[A-Z]{3}$/.test(cost.currency) || !Number.isFinite(cost.amount) || cost.amount < 0))) {
|
||
throw Error('生产模型、协议、首轮通过或成本记录无效');
|
||
}
|
||
return { modelId, protocol, firstPass, cost };
|
||
}
|
||
|
||
function judgePricing(plan) {
|
||
const prices = plan.judge?.pricing;
|
||
if (prices && (!/^[A-Z]{3}$/.test(prices.currency) ||
|
||
[prices.inputPerMillion, prices.outputPerMillion].some(value => !Number.isFinite(value) || value < 0))) {
|
||
throw Error('视觉评测费率无效');
|
||
}
|
||
return prices;
|
||
}
|
||
|
||
async function evaluate(run, template, { baseDir, mode, judge, prices }) {
|
||
const { id, templateId } = run;
|
||
if (!run.deliveryDir) return { id, templateId, status: 'unmeasured', reason: '尚未提供真实交付及回放证据' };
|
||
const production = productionEvidence(run.production);
|
||
const contract = { ...run.contract, outputs: catalog.defaults.outputs, sameColorDistinctSku: catalog.defaults.sameColorDistinctSku };
|
||
const objective = await scoreObjective({ deliveryDir: run.deliveryDir, contract, evidence: run.evidence });
|
||
let visual;
|
||
try {
|
||
visual = await judgeVisual({ template, visual: run.visual, baseDir, mode, judge });
|
||
} catch (error) {
|
||
visual = { status: 'unmeasured', reason: error.message };
|
||
}
|
||
const checks = [objective.status, objective.layout.status, visual.status];
|
||
const status = checks.includes('failed') ? 'failed' : checks.every(state => state === 'passed') ? 'passed' : 'unmeasured';
|
||
let judgeCost;
|
||
if (mode === 'live' && prices && visual.usage) {
|
||
const { inputTokens, outputTokens } = visual.usage;
|
||
judgeCost = { currency: prices.currency, amount: (prices.inputPerMillion * inputTokens + prices.outputPerMillion * outputTokens) / 1_000_000 };
|
||
}
|
||
return { id, templateId, status, objective, visual, production, judgeCost };
|
||
}
|
||
|
||
async function runCli() {
|
||
const { values } = parseArgs({ options: {
|
||
help: { type: 'boolean' }, list: { type: 'boolean' },
|
||
plan: { type: 'string' }, out: { type: 'string' }, template: { type: 'string', multiple: true },
|
||
'dry-run': { type: 'boolean' }, live: { type: 'boolean' },
|
||
} });
|
||
if (values.help) return console.log(help);
|
||
const selected = new Set(values.template ?? catalog.templates.map(template => template.id));
|
||
const templates = catalog.templates.filter(template => selected.has(template.id));
|
||
if (templates.length !== selected.size) throw Error('存在未知模板 ID');
|
||
if (values.list) return console.log(templates.map(template => template.id + ' ' + template.focus.join(';')).join('\n'));
|
||
if (values['dry-run'] && values.live) throw Error('离线回放和在线评测只能选择一种模式');
|
||
if (!values.plan || !values.out) throw Error('请指定 --plan 和 --out,可用 --help 查看用法');
|
||
|
||
const mode = values.live ? 'live' : 'dry-run';
|
||
const planPath = path.resolve(values.plan);
|
||
const baseDir = path.dirname(planPath);
|
||
const destination = path.resolve(values.out);
|
||
const plan = await json(planPath);
|
||
const prices = judgePricing(plan);
|
||
const judge = {
|
||
endpoint: process.env.XIAOYI_EVAL_VLM_ENDPOINT,
|
||
modelId: process.env.XIAOYI_EVAL_VLM_MODEL,
|
||
apiKey: process.env.XIAOYI_EVAL_VLM_API_KEY,
|
||
minimumScore: plan.judge?.minimumScore,
|
||
};
|
||
if (mode === 'live' && (!judge.endpoint || !judge.modelId)) throw Error('在线评测需要配置接口和固定模型');
|
||
const results = [];
|
||
const work = selectRuns(plan, templates, baseDir, destination);
|
||
for (const { run, template } of work) {
|
||
try {
|
||
results.push(await evaluate(run, template, { baseDir, mode, judge, prices }));
|
||
} catch (error) {
|
||
results.push({ id: run.id, templateId: run.templateId, status: 'unmeasured', reason: error.message });
|
||
}
|
||
}
|
||
const report = { version: 1, mode, summary: summarize(results), results };
|
||
await mkdir(destination, { recursive: true });
|
||
if (mode === 'live' && results.some(row => row.visual?.dimensions)) {
|
||
const replays = path.join(destination, 'replays');
|
||
await mkdir(replays, { recursive: true });
|
||
for (const row of results) {
|
||
if (row.visual?.dimensions) await writeJson(path.join(replays, row.id + '.json'), row.visual);
|
||
}
|
||
}
|
||
await writeJson(path.join(destination, 'report.json'), report);
|
||
await writeFile(path.join(destination, 'report.md'), formatMarkdown(report));
|
||
const { counts } = report.summary;
|
||
console.log('通过 ' + counts.passed + ',失败 ' + counts.failed + ',待验证 ' + counts.unmeasured + '。报告 ' + destination);
|
||
process.exitCode = counts.failed ? 1 : counts.unmeasured ? 2 : 0;
|
||
}
|
||
|
||
try {
|
||
await runCli();
|
||
} catch (error) {
|
||
console.error(error.message);
|
||
process.exitCode = 2;
|
||
}
|