claude-flow 3.10.4 → 3.10.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent-planning.smoke.d.ts +18 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent-planning.smoke.js +253 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent.d.ts +198 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-agent.js +651 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.d.ts +133 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.js +281 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.smoke.d.ts +22 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-causal-memory.smoke.js +300 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.d.ts +138 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.js +260 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.smoke.d.ts +19 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-convergence.smoke.js +246 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.d.ts +123 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.js +312 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.smoke.d.ts +21 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.smoke.js +327 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.d.ts +125 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.js +350 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.smoke.d.ts +21 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.smoke.js +228 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-e2e-smoke.d.ts +27 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-e2e-smoke.js +136 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-extract.smoke.d.ts +45 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-extract.smoke.js +242 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/features.d.ts +46 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/features.js +170 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.d.ts +105 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.js +260 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.smoke.d.ts +20 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/predictor.smoke.js +235 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/train-data-loader.d.ts +51 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-hardness/train-data-loader.js +179 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-judge.d.ts +88 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-judge.js +437 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-loader.d.ts +87 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-loader.js +326 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/file_read.d.ts +35 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/file_read.js +403 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/grounded_query.d.ts +126 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/grounded_query.js +225 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/index.d.ts +32 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/index.js +36 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/types.d.ts +62 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/types.js +12 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/web_search.d.ts +30 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-tools/web_search.js +210 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.d.ts +88 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.js +297 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.smoke.d.ts +20 -0
- package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-voting.smoke.js +332 -0
- package/v3/@claude-flow/cli/dist/src/commands/gaia-bench.d.ts +40 -0
- package/v3/@claude-flow/cli/dist/src/commands/gaia-bench.js +597 -0
- package/v3/@claude-flow/cli/dist/src/commands/index.js +2 -0
- package/v3/@claude-flow/cli/dist/src/commands/init.js +41 -4
- package/v3/@claude-flow/cli/dist/src/init/executor.js +25 -6
- package/v3/@claude-flow/cli/dist/src/init/mcp-generator.js +9 -4
- package/v3/@claude-flow/cli/package.json +1 -1
|
@@ -0,0 +1,437 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GAIA Judge — ADR-133-PR6
|
|
3
|
+
*
|
|
4
|
+
* Two-stage answer scorer for the GAIA benchmark:
|
|
5
|
+
*
|
|
6
|
+
* Stage 1 — Fast path: normalized exact-match.
|
|
7
|
+
* Normalise = lowercase + strip surrounding whitespace + strip surrounding
|
|
8
|
+
* single/double quotes + collapse internal whitespace runs to one space.
|
|
9
|
+
* Roughly 30 % of GAIA Level-1 answers satisfy this; no API call required.
|
|
10
|
+
*
|
|
11
|
+
* Stage 2 — LLM-as-judge: when exact-match fails, ask Claude Sonnet whether
|
|
12
|
+
* the candidate answer is semantically equivalent to the ground truth.
|
|
13
|
+
* The prompt embeds GAIA's official evaluation guideline (see
|
|
14
|
+
* https://huggingface.co/datasets/gaia-benchmark/GAIA for full spec).
|
|
15
|
+
*
|
|
16
|
+
* Caching: judgment results are persisted under
|
|
17
|
+
* ~/.cache/ruflo/gaia/judgments/<hash>.json
|
|
18
|
+
* keyed on (question_id, candidate_answer, model_id, JUDGE_PROMPT_VERSION).
|
|
19
|
+
* Re-running the same pair hits the cache and returns instantly.
|
|
20
|
+
*
|
|
21
|
+
* API pattern: raw fetch() against https://api.anthropic.com/v1/messages —
|
|
22
|
+
* mirrors the pattern established in gaia-agent.ts (ADR-133-PR3).
|
|
23
|
+
*
|
|
24
|
+
* Refs: ADR-133, #2156
|
|
25
|
+
*/
|
|
26
|
+
import { createHash } from 'node:crypto';
|
|
27
|
+
import * as fs from 'node:fs';
|
|
28
|
+
import * as path from 'node:path';
|
|
29
|
+
import * as os from 'node:os';
|
|
30
|
+
import { execSync } from 'node:child_process';
|
|
31
|
+
// ---------------------------------------------------------------------------
|
|
32
|
+
// Constants
|
|
33
|
+
// ---------------------------------------------------------------------------
|
|
34
|
+
const ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages';
|
|
35
|
+
const ANTHROPIC_API_VERSION = '2023-06-01';
|
|
36
|
+
const DEFAULT_JUDGE_MODEL = 'claude-sonnet-4-6';
|
|
37
|
+
const DEFAULT_CACHE_DIR = path.join(os.homedir(), '.cache', 'ruflo', 'gaia', 'judgments');
|
|
38
|
+
/**
|
|
39
|
+
* Bump this string whenever the judge prompt changes so stale cached verdicts
|
|
40
|
+
* are automatically invalidated (different key → cache miss).
|
|
41
|
+
*/
|
|
42
|
+
const JUDGE_PROMPT_VERSION = 'v1';
|
|
43
|
+
// Sonnet pricing (input/output per million tokens, 2026-05-27).
|
|
44
|
+
const SONNET_INPUT_COST_PER_M = 3.0;
|
|
45
|
+
const SONNET_OUTPUT_COST_PER_M = 15.0;
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
// Normalisation
|
|
48
|
+
// ---------------------------------------------------------------------------
|
|
49
|
+
/**
|
|
50
|
+
* GAIA normalisation as specified in the dataset paper:
|
|
51
|
+
* - strip surrounding whitespace
|
|
52
|
+
* - lowercase
|
|
53
|
+
* - strip a single pair of surrounding quotes (single or double)
|
|
54
|
+
* - collapse internal whitespace runs to one space
|
|
55
|
+
*/
|
|
56
|
+
export function normaliseAnswer(raw) {
|
|
57
|
+
if (raw == null)
|
|
58
|
+
return '';
|
|
59
|
+
let s = raw.trim().toLowerCase();
|
|
60
|
+
// Strip one pair of surrounding quotes
|
|
61
|
+
if ((s.startsWith('"') && s.endsWith('"')) ||
|
|
62
|
+
(s.startsWith("'") && s.endsWith("'"))) {
|
|
63
|
+
s = s.slice(1, -1);
|
|
64
|
+
}
|
|
65
|
+
// Collapse internal whitespace
|
|
66
|
+
s = s.replace(/\s+/g, ' ').trim();
|
|
67
|
+
return s;
|
|
68
|
+
}
|
|
69
|
+
// ---------------------------------------------------------------------------
|
|
70
|
+
// Unit-aware numeric matching
|
|
71
|
+
// ---------------------------------------------------------------------------
|
|
72
|
+
/**
|
|
73
|
+
* Attempt to match a candidate numeric answer to an expected answer where the
|
|
74
|
+
* question implies a unit scale.
|
|
75
|
+
*
|
|
76
|
+
* Examples that this catches:
|
|
77
|
+
* candidate="17000", expected="17", question contains "thousand"
|
|
78
|
+
* → candidate / 1000 ≈ expected → MATCH
|
|
79
|
+
* candidate="17", expected="17000", question contains "thousand"
|
|
80
|
+
* → candidate × 1000 ≈ expected → MATCH (reverse direction)
|
|
81
|
+
*
|
|
82
|
+
* Returns true only when a numeric match is found under one of the scale
|
|
83
|
+
* multipliers mentioned in the question text. Returns false for non-numeric
|
|
84
|
+
* inputs or when no multiplier matches.
|
|
85
|
+
*
|
|
86
|
+
* @param candidate - The raw string from the model (may include commas/spaces).
|
|
87
|
+
* @param expected - The raw ground-truth string.
|
|
88
|
+
* @param questionText - The original question (used to detect multiplier words).
|
|
89
|
+
*/
|
|
90
|
+
export function unitAwareNumberMatch(candidate, expected, questionText) {
|
|
91
|
+
// Strip commas, spaces, and trailing unit suffixes for numeric parsing
|
|
92
|
+
const toNum = (s) => parseFloat(s.replace(/[,\s]/g, ''));
|
|
93
|
+
const candNum = toNum(candidate);
|
|
94
|
+
const expNum = toNum(expected);
|
|
95
|
+
if (isNaN(candNum) || isNaN(expNum))
|
|
96
|
+
return false;
|
|
97
|
+
// Exact numeric equality (handles "17" vs "17.0", etc.)
|
|
98
|
+
if (Math.abs(candNum - expNum) < 0.001 * (Math.abs(expNum) + 1))
|
|
99
|
+
return true;
|
|
100
|
+
if (!questionText)
|
|
101
|
+
return false;
|
|
102
|
+
const qLower = questionText.toLowerCase();
|
|
103
|
+
const MULTIPLIERS = [
|
|
104
|
+
['trillion', 1e12],
|
|
105
|
+
['billion', 1e9],
|
|
106
|
+
['million', 1e6],
|
|
107
|
+
['thousand', 1e3],
|
|
108
|
+
['hundred', 1e2],
|
|
109
|
+
];
|
|
110
|
+
for (const [word, mult] of MULTIPLIERS) {
|
|
111
|
+
if (!qLower.includes(word))
|
|
112
|
+
continue;
|
|
113
|
+
// Model returned raw, expected is already in scaled units
|
|
114
|
+
// e.g. model says "17000", question asks "how many thousand hours", expected is "17"
|
|
115
|
+
if (Math.abs(candNum / mult - expNum) < 0.01 * (Math.abs(expNum) + 1))
|
|
116
|
+
return true;
|
|
117
|
+
// Reverse: model returned scaled, expected is raw
|
|
118
|
+
if (Math.abs(candNum - expNum / mult) < 0.01 * (Math.abs(candNum) + 1))
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
// Cache helpers
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
function cacheKey(questionId, candidateAnswer, judgeModel) {
|
|
127
|
+
const raw = `${questionId}||${candidateAnswer}||${judgeModel}||${JUDGE_PROMPT_VERSION}`;
|
|
128
|
+
return createHash('sha256').update(raw).digest('hex');
|
|
129
|
+
}
|
|
130
|
+
function cacheRead(cacheDir, key) {
|
|
131
|
+
const file = path.join(cacheDir, `${key}.json`);
|
|
132
|
+
try {
|
|
133
|
+
const txt = fs.readFileSync(file, 'utf-8');
|
|
134
|
+
return JSON.parse(txt);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function cacheWrite(cacheDir, key, result) {
|
|
141
|
+
try {
|
|
142
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
143
|
+
fs.writeFileSync(path.join(cacheDir, `${key}.json`), JSON.stringify(result, null, 2), 'utf-8');
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
// Non-fatal — cache write failure should not abort a benchmark run.
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
// ---------------------------------------------------------------------------
|
|
150
|
+
// API key resolution (mirrors gaia-agent.ts resolveAnthropicApiKey)
|
|
151
|
+
// ---------------------------------------------------------------------------
|
|
152
|
+
function resolveApiKey(supplied) {
|
|
153
|
+
if (supplied && supplied.trim())
|
|
154
|
+
return supplied.trim();
|
|
155
|
+
const envKey = process.env.ANTHROPIC_API_KEY;
|
|
156
|
+
if (envKey && envKey.trim())
|
|
157
|
+
return envKey.trim();
|
|
158
|
+
try {
|
|
159
|
+
const out = execSync('gcloud secrets versions access latest --secret=ANTHROPIC_API_KEY 2>/dev/null', { encoding: 'utf-8', timeout: 10_000 }).trim();
|
|
160
|
+
if (out)
|
|
161
|
+
return out;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
/* fall through */
|
|
165
|
+
}
|
|
166
|
+
throw new Error('ANTHROPIC_API_KEY not found. Set the env var or store it in GCP Secret Manager under ' +
|
|
167
|
+
'"ANTHROPIC_API_KEY".');
|
|
168
|
+
}
|
|
169
|
+
// ---------------------------------------------------------------------------
|
|
170
|
+
// LLM-as-judge prompt
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
/**
|
|
173
|
+
* Build the judge system prompt.
|
|
174
|
+
*
|
|
175
|
+
* References the GAIA official scoring guideline:
|
|
176
|
+
* "The evaluation of the answer is done by exact string match after
|
|
177
|
+
* normalisation. For numerical answers, units are ignored unless
|
|
178
|
+
* the question explicitly asks for them. For named-entity answers,
|
|
179
|
+
* common aliases are accepted. For open-ended questions where an exact
|
|
180
|
+
* match is not possible, the answer is judged correct if it is semantically
|
|
181
|
+
* equivalent to the ground truth and contains all required information."
|
|
182
|
+
* Source: https://huggingface.co/datasets/gaia-benchmark/GAIA (README, §Evaluation)
|
|
183
|
+
*/
|
|
184
|
+
function buildJudgeSystemPrompt() {
|
|
185
|
+
return [
|
|
186
|
+
'You are a precise judge evaluating whether a candidate answer to a',
|
|
187
|
+
'question-answering benchmark is correct.',
|
|
188
|
+
'',
|
|
189
|
+
'SCORING RULES (from the GAIA benchmark specification):',
|
|
190
|
+
'1. Exact-string equivalence (after normalisation) is always correct.',
|
|
191
|
+
'2. For NUMERICAL answers: ignore units unless the question explicitly requests them.',
|
|
192
|
+
' "3.14" and "approximately 3.14" for "what is pi to 2 decimal places" are both correct.',
|
|
193
|
+
'3. For NAMED-ENTITY answers: accept common aliases and alternative spellings.',
|
|
194
|
+
' "UK" and "United Kingdom" are equivalent.',
|
|
195
|
+
'4. For LIST answers: the candidate must contain all required items; extra items are ok.',
|
|
196
|
+
'5. Do NOT accept answers that are vague or incomplete when the ground truth is specific.',
|
|
197
|
+
' "a European city" is NOT correct if the ground truth is "Paris".',
|
|
198
|
+
'',
|
|
199
|
+
'You MUST respond with a single JSON object on one line, exactly this shape:',
|
|
200
|
+
'{"passed": true, "reason": "..."} or {"passed": false, "reason": "..."}',
|
|
201
|
+
'The "reason" must be 200 characters or fewer.',
|
|
202
|
+
'Do not output anything outside the JSON object.',
|
|
203
|
+
].join('\n');
|
|
204
|
+
}
|
|
205
|
+
function buildJudgeUserMessage(question, groundTruth, candidate) {
|
|
206
|
+
return [
|
|
207
|
+
`QUESTION: ${question}`,
|
|
208
|
+
`GROUND TRUTH: ${groundTruth}`,
|
|
209
|
+
`CANDIDATE ANSWER: ${candidate}`,
|
|
210
|
+
'',
|
|
211
|
+
'Is the candidate answer correct per the scoring rules above?',
|
|
212
|
+
].join('\n');
|
|
213
|
+
}
|
|
214
|
+
async function callJudge(systemPrompt, userMessage, model, apiKey) {
|
|
215
|
+
const messages = [
|
|
216
|
+
{ role: 'user', content: userMessage },
|
|
217
|
+
];
|
|
218
|
+
const body = JSON.stringify({
|
|
219
|
+
model,
|
|
220
|
+
max_tokens: 256,
|
|
221
|
+
system: systemPrompt,
|
|
222
|
+
messages,
|
|
223
|
+
});
|
|
224
|
+
const response = await fetch(ANTHROPIC_API_URL, {
|
|
225
|
+
method: 'POST',
|
|
226
|
+
headers: {
|
|
227
|
+
'Content-Type': 'application/json',
|
|
228
|
+
'x-api-key': apiKey,
|
|
229
|
+
'anthropic-version': ANTHROPIC_API_VERSION,
|
|
230
|
+
},
|
|
231
|
+
body,
|
|
232
|
+
});
|
|
233
|
+
if (!response.ok) {
|
|
234
|
+
const errText = await response.text().catch(() => '(no body)');
|
|
235
|
+
throw new Error(`Anthropic API error ${response.status}: ${errText}`);
|
|
236
|
+
}
|
|
237
|
+
const data = (await response.json());
|
|
238
|
+
const textBlock = data.content.find((c) => c.type === 'text');
|
|
239
|
+
const rawText = textBlock?.text ?? '';
|
|
240
|
+
// Parse the JSON the model produced
|
|
241
|
+
let passed = false;
|
|
242
|
+
let reason = '';
|
|
243
|
+
try {
|
|
244
|
+
// The model might wrap the JSON in a code fence — strip it
|
|
245
|
+
const jsonStr = rawText.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '').trim();
|
|
246
|
+
const parsed = JSON.parse(jsonStr);
|
|
247
|
+
passed = Boolean(parsed.passed);
|
|
248
|
+
reason = String(parsed.reason ?? '').slice(0, 200);
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
// Fallback: scan the text for obvious pass/fail signals
|
|
252
|
+
const lower = rawText.toLowerCase();
|
|
253
|
+
passed = lower.includes('"passed": true') || lower.includes('"passed":true');
|
|
254
|
+
reason = `parse error — raw: ${rawText.slice(0, 100)}`;
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
passed,
|
|
258
|
+
reason,
|
|
259
|
+
tokensIn: data.usage.input_tokens,
|
|
260
|
+
tokensOut: data.usage.output_tokens,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
// Public API
|
|
265
|
+
// ---------------------------------------------------------------------------
|
|
266
|
+
/**
|
|
267
|
+
* Judge a single GAIA answer.
|
|
268
|
+
*
|
|
269
|
+
* @param question - Object with `id` (task_id), `expected` (ground truth),
|
|
270
|
+
* and optional `questionText` (the full question string,
|
|
271
|
+
* used for unit-aware numeric matching in Stage 1).
|
|
272
|
+
* @param candidateAnswer - The answer produced by the agent; `null` counts as a miss.
|
|
273
|
+
* @param options - Optional overrides (model, cache dir, API key, etc.).
|
|
274
|
+
* @returns - JudgeResult with pass/fail, scoring path, and cost metrics.
|
|
275
|
+
*/
|
|
276
|
+
export async function judgeAnswer(question, candidateAnswer, options) {
|
|
277
|
+
const judgeModel = options?.judgeModel ?? DEFAULT_JUDGE_MODEL;
|
|
278
|
+
const cacheDir = options?.cacheDir ?? DEFAULT_CACHE_DIR;
|
|
279
|
+
const candidate = candidateAnswer ?? '';
|
|
280
|
+
// ── Stage 0: null / empty candidate is always a miss ──
|
|
281
|
+
if (!candidate.trim()) {
|
|
282
|
+
return {
|
|
283
|
+
questionId: question.id,
|
|
284
|
+
passed: false,
|
|
285
|
+
scoringPath: 'exact-match',
|
|
286
|
+
candidateAnswer: candidate,
|
|
287
|
+
groundTruth: question.expected,
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
// ── Stage 1a: normalised exact-match (no API call) ──
|
|
291
|
+
const normCandidate = normaliseAnswer(candidate);
|
|
292
|
+
const normExpected = normaliseAnswer(question.expected);
|
|
293
|
+
if (normCandidate === normExpected) {
|
|
294
|
+
return {
|
|
295
|
+
questionId: question.id,
|
|
296
|
+
passed: true,
|
|
297
|
+
scoringPath: 'exact-match',
|
|
298
|
+
candidateAnswer: candidate,
|
|
299
|
+
groundTruth: question.expected,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
// ── Stage 1b: unit-aware numeric match (no API call) ──
|
|
303
|
+
// Handles cases like model returns "17000" but expected is "17" and
|
|
304
|
+
// the question asks "how many thousand hours".
|
|
305
|
+
if (unitAwareNumberMatch(normCandidate, normExpected, question.questionText)) {
|
|
306
|
+
return {
|
|
307
|
+
questionId: question.id,
|
|
308
|
+
passed: true,
|
|
309
|
+
scoringPath: 'exact-match',
|
|
310
|
+
candidateAnswer: candidate,
|
|
311
|
+
groundTruth: question.expected,
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
// ── Cache lookup (before calling the LLM) ──
|
|
315
|
+
const key = cacheKey(question.id, candidate, judgeModel);
|
|
316
|
+
if (!options?.skipCache) {
|
|
317
|
+
const cached = cacheRead(cacheDir, key);
|
|
318
|
+
if (cached !== null) {
|
|
319
|
+
return { ...cached, scoringPath: 'cache' };
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
// ── Stage 2: LLM-as-judge ──
|
|
323
|
+
const apiKey = resolveApiKey(options?.apiKey);
|
|
324
|
+
const systemPrompt = buildJudgeSystemPrompt();
|
|
325
|
+
const userMessage = buildJudgeUserMessage(question.questionText ?? question.expected, question.expected, candidate);
|
|
326
|
+
const { passed, reason, tokensIn, tokensOut } = await callJudge(systemPrompt, userMessage, judgeModel, apiKey);
|
|
327
|
+
const costUsd = (tokensIn / 1_000_000) * SONNET_INPUT_COST_PER_M +
|
|
328
|
+
(tokensOut / 1_000_000) * SONNET_OUTPUT_COST_PER_M;
|
|
329
|
+
const result = {
|
|
330
|
+
questionId: question.id,
|
|
331
|
+
passed,
|
|
332
|
+
scoringPath: 'llm-judge',
|
|
333
|
+
candidateAnswer: candidate,
|
|
334
|
+
groundTruth: question.expected,
|
|
335
|
+
judgeReason: reason,
|
|
336
|
+
judgeModel,
|
|
337
|
+
judgeTokensIn: tokensIn,
|
|
338
|
+
judgeTokensOut: tokensOut,
|
|
339
|
+
judgeCostUsd: costUsd,
|
|
340
|
+
};
|
|
341
|
+
// Persist to cache (even failures — avoids repeated LLM calls on re-run)
|
|
342
|
+
cacheWrite(cacheDir, key, result);
|
|
343
|
+
return result;
|
|
344
|
+
}
|
|
345
|
+
// ---------------------------------------------------------------------------
|
|
346
|
+
// Smoke runner
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
/**
|
|
349
|
+
* Self-contained smoke test. Run with:
|
|
350
|
+
* npx tsx src/benchmarks/gaia-judge.ts
|
|
351
|
+
*
|
|
352
|
+
* Does NOT require an ANTHROPIC_API_KEY for the exact-match cases.
|
|
353
|
+
* The LLM-judge cases require a live key and cost ~$0.001 total.
|
|
354
|
+
*
|
|
355
|
+
* Expected cost: ≤ 2 Sonnet judge calls × ~300 tokens ≈ $0.001
|
|
356
|
+
*/
|
|
357
|
+
async function runSmoke() {
|
|
358
|
+
const PASS = '\x1b[32mPASS\x1b[0m';
|
|
359
|
+
const FAIL = '\x1b[31mFAIL\x1b[0m';
|
|
360
|
+
let failures = 0;
|
|
361
|
+
function check(label, condition) {
|
|
362
|
+
if (condition) {
|
|
363
|
+
console.log(` ${PASS} ${label}`);
|
|
364
|
+
}
|
|
365
|
+
else {
|
|
366
|
+
console.log(` ${FAIL} ${label}`);
|
|
367
|
+
failures++;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
// Use a temp cache dir so smoke runs are isolated
|
|
371
|
+
const tmpCacheDir = path.join(os.tmpdir(), `gaia-judge-smoke-${Date.now()}`);
|
|
372
|
+
const baseOpts = { cacheDir: tmpCacheDir };
|
|
373
|
+
console.log('\n=== gaia-judge smoke ===\n');
|
|
374
|
+
// ── Stage 1a: normaliseAnswer unit tests (no API call, no judgeAnswer) ──
|
|
375
|
+
console.log('-- Stage 1a: normaliseAnswer --');
|
|
376
|
+
check('normalise("346") === "346"', normaliseAnswer('346') === '346');
|
|
377
|
+
check('normalise(" YES ") === "yes"', normaliseAnswer(' YES ') === 'yes');
|
|
378
|
+
check('normalise(\'"Paris"\') === "paris"', normaliseAnswer('"Paris"') === 'paris');
|
|
379
|
+
check('normalise("hello world") === "hello world"', normaliseAnswer('hello world') === 'hello world');
|
|
380
|
+
check('normalise(null) === ""', normaliseAnswer(null) === '');
|
|
381
|
+
check('"346" !== "347" after normalise', normaliseAnswer('346') !== normaliseAnswer('347'));
|
|
382
|
+
// ── Stage 1b: exact-match hit and null-candidate cases (no API call) ──
|
|
383
|
+
console.log('\n-- Stage 1b: exact-match path --');
|
|
384
|
+
const r1 = await judgeAnswer({ id: 'em-1', expected: '346' }, '346', baseOpts);
|
|
385
|
+
check('exact match "346" vs "346" → pass, exact-match path', r1.passed && r1.scoringPath === 'exact-match');
|
|
386
|
+
const r3 = await judgeAnswer({ id: 'em-3', expected: 'yes' }, ' YES ', baseOpts);
|
|
387
|
+
check('normalised "yes" vs " YES " → pass, exact-match path', r3.passed && r3.scoringPath === 'exact-match');
|
|
388
|
+
const r4 = await judgeAnswer({ id: 'em-4', expected: 'Paris' }, '"Paris"', baseOpts);
|
|
389
|
+
check('quote-stripped "Paris" vs \'"Paris"\' → pass, exact-match path', r4.passed && r4.scoringPath === 'exact-match');
|
|
390
|
+
const r5 = await judgeAnswer({ id: 'em-5', expected: 'hello world' }, 'hello world', baseOpts);
|
|
391
|
+
check('whitespace-collapsed "hello world" → pass, exact-match path', r5.passed && r5.scoringPath === 'exact-match');
|
|
392
|
+
const rNull = await judgeAnswer({ id: 'em-null', expected: '346' }, null, baseOpts);
|
|
393
|
+
check('null candidate → fail, exact-match path', !rNull.passed && rNull.scoringPath === 'exact-match');
|
|
394
|
+
// ── LLM-judge cases (requires ANTHROPIC_API_KEY) ──
|
|
395
|
+
const hasKey = !!(process.env.ANTHROPIC_API_KEY?.trim());
|
|
396
|
+
if (!hasKey) {
|
|
397
|
+
console.log('\n-- Stage 2: llm-judge (SKIPPED — no ANTHROPIC_API_KEY) --');
|
|
398
|
+
}
|
|
399
|
+
else {
|
|
400
|
+
console.log('\n-- Stage 2: llm-judge --');
|
|
401
|
+
// Case 1: semantically equivalent (should pass)
|
|
402
|
+
const r6 = await judgeAnswer({ id: 'llm-1', expected: 'Paris' }, 'The capital of France is Paris', baseOpts);
|
|
403
|
+
check(`llm-judge "Paris" vs "The capital of France is Paris" → pass (path=${r6.scoringPath})`, r6.passed);
|
|
404
|
+
// Case 2: numerically wrong (should fail)
|
|
405
|
+
const r7 = await judgeAnswer({ id: 'llm-2', expected: '3.14159' }, 'approximately three', baseOpts);
|
|
406
|
+
check(`llm-judge "3.14159" vs "approximately three" → fail (path=${r7.scoringPath})`, !r7.passed);
|
|
407
|
+
const llmCost = (r6.judgeCostUsd ?? 0) + (r7.judgeCostUsd ?? 0);
|
|
408
|
+
console.log(` cost: $${llmCost.toFixed(5)} (${(r6.judgeTokensIn ?? 0) + (r7.judgeTokensIn ?? 0)} in, ${(r6.judgeTokensOut ?? 0) + (r7.judgeTokensOut ?? 0)} out)`);
|
|
409
|
+
// ── Cache hit verification ──
|
|
410
|
+
console.log('\n-- Stage 3: cache hit --');
|
|
411
|
+
// Re-run case 1 — must return from cache
|
|
412
|
+
const r8 = await judgeAnswer({ id: 'llm-1', expected: 'Paris' }, 'The capital of France is Paris', baseOpts);
|
|
413
|
+
check('second run of llm-1 → cache hit', r8.scoringPath === 'cache');
|
|
414
|
+
check('cache hit preserves original verdict', r8.passed === r6.passed);
|
|
415
|
+
// skipCache forces an LLM call even if cached
|
|
416
|
+
const r9 = await judgeAnswer({ id: 'llm-1', expected: 'Paris' }, 'The capital of France is Paris', { ...baseOpts, skipCache: true });
|
|
417
|
+
check('skipCache=true bypasses cache → llm-judge', r9.scoringPath === 'llm-judge');
|
|
418
|
+
}
|
|
419
|
+
// Cleanup temp cache dir
|
|
420
|
+
try {
|
|
421
|
+
fs.rmSync(tmpCacheDir, { recursive: true, force: true });
|
|
422
|
+
}
|
|
423
|
+
catch { /* ignore */ }
|
|
424
|
+
console.log(`\n=== smoke ${failures === 0 ? 'PASSED' : `FAILED (${failures} assertion(s))`} ===\n`);
|
|
425
|
+
if (failures > 0)
|
|
426
|
+
process.exit(1);
|
|
427
|
+
}
|
|
428
|
+
// Run smoke when executed directly
|
|
429
|
+
const isMain = process.argv[1] && (process.argv[1].endsWith('gaia-judge.ts') ||
|
|
430
|
+
process.argv[1].endsWith('gaia-judge.js'));
|
|
431
|
+
if (isMain) {
|
|
432
|
+
runSmoke().catch((err) => {
|
|
433
|
+
console.error('Smoke failed:', err);
|
|
434
|
+
process.exit(1);
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
//# sourceMappingURL=gaia-judge.js.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GAIA Dataset Loader — ADR-133-PR1
|
|
3
|
+
*
|
|
4
|
+
* Authenticates to Hugging Face, downloads the `gaia-benchmark/GAIA`
|
|
5
|
+
* validation split, caches it under ~/.cache/ruflo/gaia/, and exposes
|
|
6
|
+
* a typed `loadGaia()` API consumed by the capability-gaia subcommand.
|
|
7
|
+
*
|
|
8
|
+
* Token resolution order (mirrors performance-capability.ts ANTHROPIC_API_KEY pattern):
|
|
9
|
+
* 1. $HF_TOKEN env var
|
|
10
|
+
* 2. gcloud secrets versions access latest --secret=huggingface-token
|
|
11
|
+
* 3. Fail with a clear error message
|
|
12
|
+
*
|
|
13
|
+
* This file is deliberately a skeleton / PR-1 checkpoint. The full
|
|
14
|
+
* dataset download is gated behind a real HF_TOKEN; a 5-question smoke
|
|
15
|
+
* fixture is provided for offline / CI-without-HF testing.
|
|
16
|
+
*
|
|
17
|
+
* Refs: ADR-133, #2156
|
|
18
|
+
*/
|
|
19
|
+
export type GaiaLevel = 1 | 2 | 3;
|
|
20
|
+
export interface GaiaQuestion {
|
|
21
|
+
/** Unique identifier from the HF dataset. */
|
|
22
|
+
task_id: string;
|
|
23
|
+
/** Difficulty level: 1 (easiest) → 3 (hardest). */
|
|
24
|
+
level: GaiaLevel;
|
|
25
|
+
/** The question text sent to the agent. */
|
|
26
|
+
question: string;
|
|
27
|
+
/** Ground-truth final answer (string normalised, no surrounding whitespace). */
|
|
28
|
+
final_answer: string;
|
|
29
|
+
/** Optional file attachment filename; resolved to an absolute path by the loader. */
|
|
30
|
+
file_name: string | null;
|
|
31
|
+
/** Absolute path to the cached attachment, or null if no attachment. */
|
|
32
|
+
file_path: string | null;
|
|
33
|
+
/** Steps annotation (meta-data, not used by agent). */
|
|
34
|
+
annotator_metadata?: Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
export interface LoadGaiaOptions {
|
|
37
|
+
/** Level filter (default: 1). */
|
|
38
|
+
level?: GaiaLevel;
|
|
39
|
+
/** Maximum questions to return (default: all). */
|
|
40
|
+
limit?: number;
|
|
41
|
+
/** Skip HF download; use the built-in 5-question smoke fixture instead. */
|
|
42
|
+
smokeOnly?: boolean;
|
|
43
|
+
/** Override the cache directory (default: ~/.cache/ruflo/gaia). */
|
|
44
|
+
cacheDir?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Resolve a Hugging Face API token using two fallbacks:
|
|
48
|
+
* 1. $HF_TOKEN env var
|
|
49
|
+
* 2. `gcloud secrets versions access latest --secret=huggingface-token`
|
|
50
|
+
*
|
|
51
|
+
* Throws with a clear error if neither is available.
|
|
52
|
+
*/
|
|
53
|
+
export declare function resolveHfToken(): string;
|
|
54
|
+
/**
|
|
55
|
+
* Export the default cache directory path (no side effects).
|
|
56
|
+
*/
|
|
57
|
+
export declare function getDefaultCacheDir(): string;
|
|
58
|
+
/**
|
|
59
|
+
* Minimal offline fixture for smoke tests and CI environments without HF_TOKEN.
|
|
60
|
+
* Answers are verified by hand against publicly known facts.
|
|
61
|
+
* All questions are Level 1 (no file attachments, no multi-hop tool use required).
|
|
62
|
+
*
|
|
63
|
+
* IMPORTANT: Verify every answer key with `node -e 'console.log(…)'` before
|
|
64
|
+
* adding entries to this list — three answer-key bugs were caught in session #2156.
|
|
65
|
+
*/
|
|
66
|
+
export declare const SMOKE_FIXTURE: GaiaQuestion[];
|
|
67
|
+
/**
|
|
68
|
+
* Download all attachment files referenced by the questions list.
|
|
69
|
+
* Mutates each question's `file_path` field in place.
|
|
70
|
+
* Skips questions without a file_name.
|
|
71
|
+
*/
|
|
72
|
+
export declare function resolveAttachments(questions: GaiaQuestion[], token: string, cacheDir: string): Promise<void>;
|
|
73
|
+
/**
|
|
74
|
+
* Load GAIA validation questions.
|
|
75
|
+
*
|
|
76
|
+
* - With `smokeOnly: true` (or when HF_TOKEN is unavailable): returns the 5-question
|
|
77
|
+
* smoke fixture — no network call, no token required.
|
|
78
|
+
* - Otherwise: authenticates to HF, downloads level N questions, caches locally.
|
|
79
|
+
*
|
|
80
|
+
* @throws if HF_TOKEN is missing and smokeOnly is false
|
|
81
|
+
*/
|
|
82
|
+
export declare function loadGaia(options?: LoadGaiaOptions): Promise<GaiaQuestion[]>;
|
|
83
|
+
/**
|
|
84
|
+
* Returns the cache directory path (does not create it).
|
|
85
|
+
*/
|
|
86
|
+
export declare function getGaiaCacheDir(override?: string): string;
|
|
87
|
+
//# sourceMappingURL=gaia-loader.d.ts.map
|