File size: 7,944 Bytes
d7089de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const manifestPath = fs.existsSync(path.join(__dirname, "benchlocal.pack.json"))
  ? path.join(__dirname, "benchlocal.pack.json")
  : path.join(__dirname, "benchlocal.pack.txt");

const scenariosPath = fs.existsSync(path.join(__dirname, "scenarios.json"))
  ? path.join(__dirname, "scenarios.json")
  : path.join(__dirname, "scenarios.txt");

function readJsonSafe(filePath, fallback) {
  try {
    if (fs.existsSync(filePath)) {
      const raw = fs.readFileSync(filePath, "utf8").replace(/^\uFEFF/, "").trim();
      return JSON.parse(raw);
    }
  } catch (err) {
    console.error(`[GPQA-Polyglot] Ошибка чтения ${filePath}:`, err.message);
  }
  return fallback;
}

const defaultManifest = {
  schemaVersion: 1,
  protocolVersion: 1,
  id: "GPQA-mini",
  name: "GPQA-Polyglot (45 задач STEM уровня PhD)",
  version: "1.0.0",
  description: "Сложный Google-Proof бенчмарк уровня аспирантуры (10 вариантов ответов A-J, случайный порог 10%): 15 RU, 15 EN и 15 MIX задач",
  entry: "./index.mjs", // ИСПРАВЛЕНО (было: entry": "./index.mjs",)
  samplingDefaults: { temperature: 0.0 },
  capabilities: { tools: false, multiTurn: false, streamingProgress: false, verification: false }
};

export const manifest = readJsonSafe(manifestPath, defaultManifest);

function loadScenarios() {
  return readJsonSafe(scenariosPath, []);
}

export function listScenarios() {
  return loadScenarios().map(s => ({
    id: s.id,
    name: s.name,
    category: s.category || "Общие",
    description: s.name
  }));
}

export function getScenarios() {
  return listScenarios();
}

/**

 * Валидатор извлечения ответа:

 * 1. Ищет конструкцию "Final Answer: (X)" или "Final Answer: X".

 * 2. Если префикс опущен, ищет последнюю пару скобок с буквой: (X) или [X].

 */
export function extractAnswer(rawText) {
  const text = (rawText || "").trim();
  if (!text) return null;

  // Поддерживает как вариант со скобками: (A), так и без них: Final Answer: A
  const pattern = /(?:final\s*(?:verdict|answer)|итоговый\s*(?:ответ|вердикт)|ответ)[\s:=]*[\[\(]?\s*([A-J])\s*[\]\)]?/gi;
  const explicitMatches = Array.from(text.matchAll(pattern));
  if (explicitMatches.length > 0) {
    return explicitMatches[explicitMatches.length - 1][1].toUpperCase();
  }

  const bracketMatches = Array.from(text.matchAll(/[\[\(]([A-J])[\]\)]/g));
  if (bracketMatches.length > 0) {
    return bracketMatches[bracketMatches.length - 1][1].toUpperCase();
  }

  return null;
}

function resolveHelpers(context) {
  if (context && typeof context.getRequiredProvider === "function") {
    return context;
  }
  if (context?.helpers && typeof context.helpers.getRequiredProvider === "function") {
    return context.helpers;
  }
  return {
    getRequiredProvider(providerId) {
      const providers = context?.providers || [];
      const found = Array.isArray(providers)
        ? providers.find((p) => p.id === providerId || p.provider === providerId)
        : providers[providerId];
      return found || { baseUrl: "http://127.0.0.1:11434/v1", apiKey: "none" };
    },
    getInferenceEndpoint(modelId) {
      return context?.endpoints?.[modelId] || null;
    }
  };
}

export async function prepare(context) {
  const helpers = resolveHelpers(context);

  return {
    async runScenario(input) {
      const allScenarios = loadScenarios();
      const scenario = allScenarios.find(s => s.id === input.scenario.id);
      if (!scenario) {
        return {
          scenarioId: input.scenario.id,
          status: "fail",
          score: 0,
          summary: "Сценарий не найден",
          rawLog: "error=Scenario not found"
        };
      }

      const provider = helpers.getRequiredProvider(input.model.provider, { enabledOnly: true });
      const inference = helpers.getInferenceEndpoint ? helpers.getInferenceEndpoint(input.model.id) : null;

      const rawBaseUrl = (inference && inference.status === "running" ? inference.baseUrl : provider?.baseUrl) || "http://127.0.0.1:11434/v1";
      const baseUrl = rawBaseUrl.replace(/\/+$/, "");
      const apiKey = provider?.apiKey || "none";

      const requestBody = {
        model: input.model.model,
        messages: [{ role: "user", content: scenario.prompt }],
        temperature: 0,
        max_tokens: 4096
      };

      let text = "";
      let rawResponseData = null;

      try {
        const response = await fetch(`${baseUrl}/chat/completions`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`
          },
          body: JSON.stringify(requestBody)
        });

        if (!response.ok) {
          throw new Error(`HTTP ${response.status} ${response.statusText}`);
        }

        rawResponseData = await response.json();
        text = (rawResponseData.choices?.[0]?.message?.content || "").trim();
      } catch (err) {
        return {
          scenarioId: scenario.id,
          status: "fail",
          score: 0,
          summary: `Ошибка API: ${err.message}`,
          rawLog: `error=${err.message}`
        };
      }

      const extracted = extractAnswer(text);
      const passed = extracted === scenario.correct_answer.toUpperCase();

      const rawLog = [
        `model=${input.model.model}`,
        `scenario=${scenario.id} ${scenario.name}`,
        `category=${scenario.category}`,
        `user_turn_1=${scenario.prompt}`,
        `assistant_turn_1=${text}`,
        `extracted_choice=${extracted || "NONE"}`,
        `expected_choice=${scenario.correct_answer}`,
        `verdict=${passed ? "pass" : "fail"}`,
        `score=${passed ? 100 : 0}`,
        `summary=${passed ? "Правильный ответ" : `Неверно (выбрано: ${extracted || 'ничего'}, ожидалось: ${scenario.correct_answer})`}`,
        `\n--- RAW API RESPONSE ---`,
        JSON.stringify(rawResponseData, null, 2)
      ].join("\n");

      return {
        scenarioId: scenario.id,
        status: passed ? "pass" : "fail",
        score: passed ? 100 : 0,
        summary: passed ? "Правильный ответ" : `Выбрано '${extracted || "нет"}', ожидалось '${scenario.correct_answer}'`,
        rawLog: rawLog
      };
    },

    async dispose() {}
  };
}

export function scoreModelResults(results) {
  const scored = results || [];
  const allScenarios = loadScenarios();
  const scenarioMap = new Map(allScenarios.map(s => [s.id, s]));

  const total = scored.reduce((sum, r) => sum + (r.score || 0), 0);
  const max = scored.length * 100;

  const categoryStats = {};
  for (const r of scored) {
    const s = scenarioMap.get(r.scenarioId);
    const cat = s?.category || "Общие";
    if (!categoryStats[cat]) {
      categoryStats[cat] = { total: 0, count: 0 };
    }
    categoryStats[cat].total += (r.score || 0);
    categoryStats[cat].count += 1;
  }

  const categories = Object.entries(categoryStats).map(([name, stat]) => ({
    name,
    score: stat.count > 0 ? Math.round((stat.total / (stat.count * 100)) * 100) : 0
  }));

  return {
    totalScore: max > 0 ? Math.round((total / max) * 100) : 0,
    categories
  };
}

export default {
  manifest,
  listScenarios,
  getScenarios,
  prepare,
  createRuntime: prepare,
  scoreModelResults
};