-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2559 lines (2311 loc) · 90.9 KB
/
app.js
File metadata and controls
2559 lines (2311 loc) · 90.9 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 providerCatalog = {
openai: {
label: "OpenAI",
endpoint: "https://api.openai.com/v1/responses",
models: ["gpt-4o", "gpt-5.2"]
},
anthropic: {
label: "Anthropic",
endpoint: "/api/anthropic/messages",
models: ["claude-sonnet-4-20250514", "claude-sonnet-4-6"]
}
};
const els = {
providerChecklist: document.getElementById("providerChecklist"),
modelChecklist: document.getElementById("modelChecklist"),
providerAllBtn: document.getElementById("providerAllBtn"),
providerNoneBtn: document.getElementById("providerNoneBtn"),
modelAllBtn: document.getElementById("modelAllBtn"),
modelNoneBtn: document.getElementById("modelNoneBtn"),
temperature: document.getElementById("temperatureInput"),
runCount: document.getElementById("runCountInput"),
structuredOutputToggle: document.getElementById("structuredOutputToggle"),
openaiApiKey: document.getElementById("openaiApiKeyInput"),
anthropicApiKey: document.getElementById("anthropicApiKeyInput"),
showApiKeysToggle: document.getElementById("showApiKeysToggle"),
prompt: document.getElementById("promptInput"),
imageInput: document.getElementById("imageInput"),
imageList: document.getElementById("imageList"),
imagePreview: document.getElementById("imagePreview"),
jsonlFiles: document.getElementById("jsonlFileInput"),
jsonlFileList: document.getElementById("jsonlFileList"),
batchImageBase: document.getElementById("batchImageBaseInput"),
singleModeBtn: document.getElementById("singleModeBtn"),
batchModeBtn: document.getElementById("batchModeBtn"),
exposureModeBtn: document.getElementById("exposureModeBtn"),
singleInputSection: document.getElementById("singleInputSection"),
batchInputSection: document.getElementById("batchInputSection"),
exposureInputSection: document.getElementById("exposureInputSection"),
batchPreview: document.getElementById("batchPreview"),
requestExample: document.getElementById("requestExample"),
submit: document.getElementById("submitBtn"),
runBatch: document.getElementById("runBatchBtn"),
runExposure: document.getElementById("runExposureBtn"),
save: document.getElementById("saveBtn"),
stop: document.getElementById("stopBtn"),
reset: document.getElementById("resetBtn"),
status: document.getElementById("status"),
progress: document.getElementById("batchProgress"),
progressText: document.getElementById("batchProgressText"),
output: document.getElementById("outputBox"),
meta: document.getElementById("meta"),
resultTableBody: document.getElementById("resultTableBody"),
// Exposure search
exposureSampleSize: document.getElementById("exposureSampleSize"),
exposureSearchAll: document.getElementById("exposureSearchAll"),
exposureSeed: document.getElementById("exposureSeed"),
exposureQueryLen: document.getElementById("exposureQueryLen"),
exposureNgramN: document.getElementById("exposureNgramN"),
useBraveSearch: document.getElementById("useBraveSearch"),
braveApiKeyInput: document.getElementById("braveApiKeyInput"),
braveKeyRow: document.getElementById("braveKeyRow"),
exposureResultsSection: document.getElementById("exposureResultsSection"),
exposureStatus: document.getElementById("exposureStatus"),
exposureProgress: document.getElementById("exposureProgress"),
exposureProgressText: document.getElementById("exposureProgressText"),
exposureSummary: document.getElementById("exposureSummary"),
exposureTableBody: document.getElementById("exposureTableBody"),
saveExposureBtn: document.getElementById("saveExposureBtn"),
saveExposureFullBtn: document.getElementById("saveExposureFullBtn"),
// Memorization test
memorModeBtn: document.getElementById("memorModeBtn"),
memorInputSection: document.getElementById("memorInputSection"),
memorSampleSize: document.getElementById("memorSampleSize"),
memorSeed: document.getElementById("memorSeed"),
runTSGuessing: document.getElementById("runTSGuessing"),
runOptionShuffle: document.getElementById("runOptionShuffle"),
runMemor: document.getElementById("runMemorBtn"),
memorResultsSection:document.getElementById("memorResultsSection"),
memorStatus: document.getElementById("memorStatus"),
memorProgress: document.getElementById("memorProgress"),
memorProgressText: document.getElementById("memorProgressText"),
memorSummary: document.getElementById("memorSummary"),
memorTSBody: document.getElementById("memorTSBody"),
memorShuffleBody: document.getElementById("memorShuffleBody"),
saveMemorBtn: document.getElementById("saveMemorBtn")
};
let lastRunData = null;
let previewUrls = [];
let selectedFiles = [];
let selectedJsonlFiles = [];
let inputMode = "single";
const openAiUploadedFileCache = new Map();
let stopRequested = false;
let activeRequestController = null;
// Exposure search state
let exposureResults = [];
let exposureStopRequested = false;
// Memorization test state
let memorResults = [];
let memorStopRequested = false;
let lastMemorMeta = null;
const CERT_DATASETS = {
CAC: "/cert_eval/data/CAC.jsonl",
CACM: "/cert_eval/data/CACM.jsonl",
CCM: "/cert_eval/data/CCM.jsonl",
CPC: "/cert_eval/data/CPC.jsonl"
};
init();
function init() {
renderProviderChecklist();
els.temperature.addEventListener("input", renderRequestExample);
els.structuredOutputToggle.addEventListener("change", renderRequestExample);
els.showApiKeysToggle.addEventListener("change", applyApiKeyVisibility);
els.providerAllBtn.addEventListener("click", () => setChecklistSelection(els.providerChecklist, true, "provider"));
els.providerNoneBtn.addEventListener("click", () => setChecklistSelection(els.providerChecklist, false, "provider"));
els.modelAllBtn.addEventListener("click", () => setChecklistSelection(els.modelChecklist, true, "model"));
els.modelNoneBtn.addEventListener("click", () => setChecklistSelection(els.modelChecklist, false, "model"));
els.singleModeBtn.addEventListener("click", () => setInputMode("single"));
els.batchModeBtn.addEventListener("click", () => setInputMode("batch"));
els.exposureModeBtn.addEventListener("click", () => setInputMode("exposure"));
els.memorModeBtn.addEventListener("click", () => setInputMode("memor"));
els.imageInput.addEventListener("change", renderSelectedImages);
els.jsonlFiles.addEventListener("change", handleJsonlFileSelection);
els.batchImageBase.addEventListener("input", previewBatchFiles);
els.submit.addEventListener("click", handleSubmitSingle);
els.runBatch.addEventListener("click", handleSubmitBatch);
els.runExposure.addEventListener("click", runExposureSearch);
els.runMemor.addEventListener("click", runMemorizationTest);
els.saveMemorBtn.addEventListener("click", saveMemorResults);
els.stop.addEventListener("click", handleStop);
els.save.addEventListener("click", saveRunToFile);
els.reset.addEventListener("click", resetUI);
els.useBraveSearch.addEventListener("change", () => {
els.braveKeyRow.classList.toggle("hidden", !els.useBraveSearch.checked);
});
els.saveExposureBtn.addEventListener("click", saveExposureResults);
els.saveExposureFullBtn.addEventListener("click", saveExposureResultsFull);
onProviderChange();
resetUI();
}
function setInputMode(mode) {
inputMode = mode;
const single = mode === "single";
const batch = mode === "batch";
const exposure = mode === "exposure";
const memor = mode === "memor";
els.singleInputSection.classList.toggle("hidden", !single);
els.batchInputSection.classList.toggle("hidden", !batch);
els.exposureInputSection.classList.toggle("hidden", !exposure);
els.memorInputSection.classList.toggle("hidden", !memor);
els.singleModeBtn.classList.toggle("active", single);
els.batchModeBtn.classList.toggle("active", batch);
els.exposureModeBtn.classList.toggle("active", exposure);
els.memorModeBtn.classList.toggle("active", memor);
els.singleModeBtn.setAttribute("aria-pressed", String(single));
els.batchModeBtn.setAttribute("aria-pressed", String(batch));
els.exposureModeBtn.setAttribute("aria-pressed", String(exposure));
els.memorModeBtn.setAttribute("aria-pressed", String(memor));
els.submit.classList.toggle("hidden", !single);
els.runBatch.classList.toggle("hidden", !batch);
els.runExposure.classList.toggle("hidden", !exposure);
els.runMemor.classList.toggle("hidden", !memor);
if (!exposure) els.exposureResultsSection.classList.add("hidden");
if (!memor) els.memorResultsSection.classList.add("hidden");
}
function renderProviderChecklist() {
els.providerChecklist.innerHTML = "";
for (const [key, info] of Object.entries(providerCatalog)) {
const row = document.createElement("label");
row.className = "check-item";
const cb = document.createElement("input");
cb.type = "checkbox";
cb.value = key;
cb.checked = true;
cb.dataset.kind = "provider";
cb.addEventListener("change", onProviderChange);
const text = document.createElement("span");
text.textContent = info.label;
row.appendChild(cb);
row.appendChild(text);
els.providerChecklist.appendChild(row);
}
populateModelsForSelectedProviders();
}
function onProviderChange() {
populateModelsForSelectedProviders();
renderRequestExample();
}
function populateModelsForSelectedProviders() {
const selectedProviders = getSelectedProviders();
const previouslySelected = new Set(
Array.from(els.modelChecklist.querySelectorAll('input[data-kind="model"]:checked')).map((cb) => cb.value)
);
els.modelChecklist.innerHTML = "";
for (const providerKey of selectedProviders) {
const info = providerCatalog[providerKey];
for (const model of info.models) {
const value = `${providerKey}::${model}`;
const row = document.createElement("label");
row.className = "check-item";
const cb = document.createElement("input");
cb.type = "checkbox";
cb.value = value;
cb.dataset.kind = "model";
cb.checked = previouslySelected.size ? previouslySelected.has(value) : true;
cb.addEventListener("change", renderRequestExample);
const text = document.createElement("span");
text.textContent = getModelDisplayName(providerKey, model);
row.appendChild(cb);
row.appendChild(text);
els.modelChecklist.appendChild(row);
}
}
}
function setChecklistSelection(container, checked, kind) {
const nodes = container.querySelectorAll(`input[data-kind="${kind}"]`);
for (const cb of nodes) {
cb.checked = checked;
}
if (kind === "provider") {
onProviderChange();
} else {
renderRequestExample();
}
}
function getSelectedProviders() {
return Array.from(els.providerChecklist.querySelectorAll('input[data-kind="provider"]:checked')).map((cb) => cb.value);
}
function getSelectedCombos() {
return Array.from(els.modelChecklist.querySelectorAll('input[data-kind="model"]:checked')).map((cb) => {
const [providerKey, model] = cb.value.split("::");
return { providerKey, model, label: cb.parentElement?.textContent || cb.value };
});
}
function getModelDisplayName(providerKey, model) {
if (providerKey === "anthropic" && model === "claude-sonnet-4-20250514") {
return "claude-sonnet-4";
}
return model;
}
function applyApiKeyVisibility() {
const type = els.showApiKeysToggle.checked ? "text" : "password";
els.openaiApiKey.type = type;
els.anthropicApiKey.type = type;
}
function renderSelectedImages() {
selectedFiles = Array.from(els.imageInput.files || []);
els.imageInput.value = "";
refreshSelectedImagesUI();
}
function handleJsonlFileSelection() {
const incoming = Array.from(els.jsonlFiles.files || []);
for (const file of incoming) {
const exists = selectedJsonlFiles.some(
(f) => f.name === file.name && f.size === file.size && f.lastModified === file.lastModified
);
if (!exists) {
selectedJsonlFiles.push(file);
}
}
els.jsonlFiles.value = "";
renderSelectedJsonlFiles();
previewBatchFiles();
}
function renderSelectedJsonlFiles() {
els.jsonlFileList.innerHTML = "";
if (!selectedJsonlFiles.length) {
els.jsonlFileList.textContent = "No JSONL files selected.";
return;
}
selectedJsonlFiles.forEach((file, idx) => {
const row = document.createElement("div");
row.className = "jsonl-item";
const name = document.createElement("span");
name.className = "jsonl-name";
name.textContent = file.name;
const remove = document.createElement("button");
remove.type = "button";
remove.className = "mini secondary";
remove.textContent = "Remove";
remove.addEventListener("click", () => {
selectedJsonlFiles.splice(idx, 1);
renderSelectedJsonlFiles();
previewBatchFiles();
});
row.appendChild(name);
row.appendChild(remove);
els.jsonlFileList.appendChild(row);
});
}
function refreshSelectedImagesUI() {
els.imageList.textContent = selectedFiles.length
? `${selectedFiles.length} image(s): ${selectedFiles.map((f) => f.name).join(", ")}`
: "No images selected.";
renderImagePreview(selectedFiles);
}
function renderImagePreview(files) {
for (const url of previewUrls) {
URL.revokeObjectURL(url);
}
previewUrls = [];
els.imagePreview.innerHTML = "";
files.forEach((file, idx) => {
const url = URL.createObjectURL(file);
previewUrls.push(url);
const wrapper = document.createElement("div");
wrapper.className = "thumb-wrap";
const img = document.createElement("img");
img.src = url;
img.alt = file.name;
img.title = file.name;
img.className = "thumb";
const btn = document.createElement("button");
btn.type = "button";
btn.className = "thumb-remove";
btn.textContent = "x";
btn.title = `Remove ${file.name}`;
btn.addEventListener("click", () => removeSelectedImage(idx));
wrapper.appendChild(img);
wrapper.appendChild(btn);
els.imagePreview.appendChild(wrapper);
});
}
function removeSelectedImage(index) {
selectedFiles.splice(index, 1);
refreshSelectedImagesUI();
}
function renderRequestExample() {
const combos = getSelectedCombos();
if (!combos.length) {
els.requestExample.textContent = "{\n \"error\": \"Select at least one model\"\n}";
return;
}
const first = combos[0];
const userPrompt = buildUserPrompt("What is shown in the image?");
const payload = buildExamplePayload(first.providerKey, first.model, userPrompt, getTemperature());
els.requestExample.textContent = JSON.stringify(payload, null, 2);
}
async function handleSubmitSingle() {
const combos = getSelectedCombos();
const prompt = els.prompt.value.trim();
const temperature = getTemperature();
const runCount = getRunCount();
if (!combos.length) {
setStatus("Select at least one provider/model.", true);
return;
}
if (!prompt) {
setStatus("Please enter a prompt.", true);
return;
}
for (const combo of combos) {
if (!getApiKeyForProvider(combo.providerKey)) {
setStatus(`Please enter the API key for ${providerCatalog[combo.providerKey].label}.`, true);
return;
}
}
setLoading(true);
stopRequested = false;
els.output.textContent = "";
els.meta.textContent = "";
clearResultTable();
setProgress(0, 100);
try {
const encodedImages = await Promise.all(selectedFiles.map(fileToBase64));
const userPrompt = buildUserPrompt(prompt);
const runResults = [];
const totalSteps = combos.length * runCount;
let completed = 0;
for (const combo of combos) {
if (stopRequested) break;
const apiKey = getApiKeyForProvider(combo.providerKey);
const openAiContentParts =
combo.providerKey === "openai" ? await prepareOpenAiContentParts(apiKey, encodedImages) : null;
for (let i = 0; i < runCount; i += 1) {
if (stopRequested) break;
setStatus(`Running ${combo.label} (${i + 1}/${runCount})...`, false);
const startedAt = performance.now();
const payload = buildPayload(combo.providerKey, combo.model, userPrompt, encodedImages, temperature, openAiContentParts);
const result = await sendRequest(combo.providerKey, apiKey, payload);
const elapsedMs = Math.round(performance.now() - startedAt);
const run = {
provider: combo.providerKey,
model: getModelDisplayName(combo.providerKey, combo.model),
modelId: combo.model,
runIndex: i + 1,
elapsedMs,
text: result.text || "(No text in response)",
usage: result.usage || null
};
runResults.push(run);
appendOutput(`[${combo.label}] Run ${run.runIndex}/${runCount} (${elapsedMs} ms)\n${run.text}\n\n`);
appendResultRow({
sourceFile: "single",
questionId: "-",
provider: run.provider,
model: run.model,
runIndex: run.runIndex,
elapsedMs: run.elapsedMs,
expectedAnswer: "",
modelOutput: run.text
});
completed += 1;
setProgress(completed, totalSteps);
}
}
const totalMs = runResults.reduce((sum, r) => sum + r.elapsedMs, 0);
const avgMs = runResults.length ? Math.round(totalMs / runResults.length) : 0;
els.meta.textContent = `Combos: ${combos.length} | Runs: ${runResults.length} | Total time: ${totalMs} ms | Avg/run: ${avgMs} ms | Temperature: ${temperature}`;
setStatus(stopRequested ? "Stopped by user." : "Completed.", false);
lastRunData = {
mode: "single",
savedAt: new Date().toISOString(),
settings: {
combos,
temperature,
runCount,
structuredOutput: !!els.structuredOutputToggle.checked
},
input: { prompt, userPrompt },
images: encodedImages.map((img, idx) => ({
name: selectedFiles[idx]?.name || `image-${idx + 1}`,
mimeType: img.mimeType,
base64: img.base64
})),
output: runResults
};
} catch (error) {
if (stopRequested && error?.name === "AbortError") {
setStatus("Stopped by user.", false);
} else {
setStatus(`Error: ${error.message}`, true);
}
} finally {
activeRequestController = null;
setLoading(false);
}
}
async function handleSubmitBatch() {
const combos = getSelectedCombos();
const temperature = getTemperature();
const runCount = getRunCount();
if (!combos.length) {
setStatus("Select at least one provider/model.", true);
return;
}
for (const combo of combos) {
if (!getApiKeyForProvider(combo.providerKey)) {
setStatus(`Please enter the API key for ${providerCatalog[combo.providerKey].label}.`, true);
return;
}
}
setLoading(true);
stopRequested = false;
els.output.textContent = "";
els.meta.textContent = "";
clearResultTable();
setProgress(0, 100);
try {
const baseUrlForBatch = getBatchImageBaseUrl();
const batchSources = await loadBatchSources(baseUrlForBatch);
if (!batchSources.length) {
throw new Error("Upload one or more JSONL files.");
}
const questions = [];
for (const source of batchSources) {
const parsed = parseJsonlText(source.text, source.name);
questions.push(...parsed.map((item) => ({ ...item, __source: source })));
}
if (!questions.length) {
throw new Error("No valid questions found in uploaded JSONL files.");
}
await previewBatchFiles();
const diagnostics = await diagnoseQuestionImageUris(questions, baseUrlForBatch);
if (diagnostics.unresolved.length) {
appendOutput("Image path diagnostics (unresolved before run):\n");
for (const item of diagnostics.unresolved.slice(0, 50)) {
appendOutput(`- [${item.questionId}] ${item.uri}\n`);
}
if (diagnostics.unresolved.length > 50) {
appendOutput(`... and ${diagnostics.unresolved.length - 50} more unresolved image paths\n`);
}
appendOutput("\n");
} else {
appendOutput("Image path diagnostics: no unresolved image paths.\n\n");
}
const totalSteps = questions.length * combos.length * runCount;
let completed = 0;
const records = [];
appendOutput(`Loaded ${questions.length} questions from ${batchSources.length} file(s).\n\n`);
for (let qIdx = 0; qIdx < questions.length; qIdx += 1) {
if (stopRequested) break;
const q = questions[qIdx];
const qPrompt = buildQuestionPrompt(q);
const userPrompt = buildUserPrompt(qPrompt);
const encodedImages = await loadQuestionImages(q, q.__source.baseUrl);
for (const combo of combos) {
if (stopRequested) break;
const apiKey = getApiKeyForProvider(combo.providerKey);
const openAiContentParts =
combo.providerKey === "openai" ? await prepareOpenAiContentParts(apiKey, encodedImages) : null;
for (let runIdx = 0; runIdx < runCount; runIdx += 1) {
if (stopRequested) break;
setStatus(`Q${qIdx + 1}/${questions.length} | ${combo.label} | ${runIdx + 1}/${runCount}`, false);
const startedAt = performance.now();
const payload = buildPayload(combo.providerKey, combo.model, userPrompt, encodedImages, temperature, openAiContentParts);
const result = await sendRequest(combo.providerKey, apiKey, payload);
const elapsedMs = Math.round(performance.now() - startedAt);
const text = result.text || "(No text in response)";
const record = {
sourceFile: q.__source.name,
questionId: q.id || `row-${qIdx + 1}`,
questionIndex: qIdx + 1,
provider: combo.providerKey,
model: getModelDisplayName(combo.providerKey, combo.model),
modelId: combo.model,
runIndex: runIdx + 1,
elapsedMs,
expectedAnswer: q.answer || null,
modelOutput: text,
usage: result.usage || null,
imageCount: encodedImages.length
};
records.push(record);
appendResultRow(record);
appendOutput(
`[${q.__source.name}] Q${qIdx + 1}/${questions.length} (${record.questionId}) | ${combo.label} | Run ${runIdx + 1}/${runCount} | ${elapsedMs} ms\n${text}\n\n`
);
completed += 1;
setProgress(completed, totalSteps);
}
}
}
const totalTime = records.reduce((sum, r) => sum + r.elapsedMs, 0);
const avgTime = records.length ? Math.round(totalTime / records.length) : 0;
els.meta.textContent = `Batch done | Questions: ${questions.length} | Combos: ${combos.length} | Runs: ${records.length} | Total time: ${totalTime} ms | Avg/run: ${avgTime} ms | Temperature: ${temperature}`;
setStatus(stopRequested ? "Stopped by user." : "Batch completed.", false);
lastRunData = {
mode: "batch",
savedAt: new Date().toISOString(),
settings: {
combos,
temperature,
runCount,
structuredOutput: !!els.structuredOutputToggle.checked
},
sources: batchSources.map((s) => s.name),
output: records
};
} catch (error) {
if (stopRequested && error?.name === "AbortError") {
setStatus("Stopped by user.", false);
} else {
setStatus(`Error: ${error.message}`, true);
}
} finally {
activeRequestController = null;
setLoading(false);
}
}
async function loadBatchSources(baseUrlOverride = null) {
const uploaded = [...selectedJsonlFiles];
if (!uploaded.length) return [];
const sources = [];
for (const file of uploaded) {
const text = await file.text();
sources.push({ name: file.name, text, baseUrl: baseUrlOverride });
}
return sources;
}
async function previewBatchFiles() {
const uploaded = [...selectedJsonlFiles];
if (!uploaded.length) {
els.batchPreview.textContent = "No JSONL file loaded.";
return;
}
const baseUrl = getBatchImageBaseUrl();
let totalQuestions = 0;
let totalImageRefs = 0;
let resolvableImageRefs = 0;
let missingImageRefs = 0;
const perFileLines = [];
const checkedCache = new Map();
const missingItems = [];
for (const file of uploaded) {
const text = await file.text();
const rows = parseJsonlText(text, file.name, { silent: true });
totalQuestions += rows.length;
let fileImageRefs = 0;
let fileResolvable = 0;
let fileMissing = 0;
for (const row of rows) {
const images = Array.isArray(row.images) ? row.images : [];
for (const img of images) {
const uri = img && typeof img === "object" ? String(img.uri || "").trim() : "";
if (!uri) continue;
fileImageRefs += 1;
const ok = await canResolveImageUri(uri, baseUrl, checkedCache);
if (ok) {
fileResolvable += 1;
} else {
fileMissing += 1;
missingItems.push({
file: file.name,
questionId: row.id || "unknown",
uri
});
}
}
}
totalImageRefs += fileImageRefs;
resolvableImageRefs += fileResolvable;
missingImageRefs += fileMissing;
perFileLines.push(`${file.name}: questions=${rows.length}, images=${fileImageRefs}, resolvable=${fileResolvable}, missing=${fileMissing}`);
}
const header =
`Files: ${uploaded.length}\n` +
`Total questions: ${totalQuestions}\n` +
`Image refs: ${totalImageRefs} | Resolvable: ${resolvableImageRefs} | Missing: ${missingImageRefs}\n`;
let missingBlock = "";
if (missingItems.length) {
const top = missingItems.slice(0, 30);
const lines = top.map((m) => `- [${m.file}] ${m.questionId}: ${m.uri}`);
const more = missingItems.length > top.length ? `\n... and ${missingItems.length - top.length} more` : "";
missingBlock = `\n\nMissing image references:\n${lines.join("\n")}${more}`;
}
els.batchPreview.textContent = `${header}\n${perFileLines.join("\n")}${missingBlock}`;
}
function parseJsonlText(text, sourceName, options = {}) {
const silent = !!options.silent;
const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
const out = [];
for (let i = 0; i < lines.length; i += 1) {
try {
out.push(JSON.parse(lines[i]));
} catch {
if (!silent) {
appendOutput(`Skipping invalid JSONL line ${i + 1} in ${sourceName}.\n`);
}
}
}
return out;
}
function getBatchImageBaseUrl() {
const raw = String(els.batchImageBase.value || "").trim();
if (!raw) return null;
try {
const normalized = raw.endsWith("/") ? raw : `${raw}/`;
return new URL(normalized, window.location.href).href;
} catch {
return null;
}
}
function buildQuestionPrompt(q) {
const parts = [];
if (q.question) parts.push(q.question);
if (q.choices && typeof q.choices === "object") {
parts.push("");
parts.push("Choices:");
for (const key of ["A", "B", "C", "D"]) {
if (q.choices[key] != null) parts.push(`${key}. ${q.choices[key]}`);
}
}
if (q.table_markdown) {
parts.push("");
parts.push("Table:");
parts.push(String(q.table_markdown));
}
return parts.join("\n").trim();
}
async function loadQuestionImages(question, baseUrl) {
if (!Array.isArray(question.images) || question.images.length === 0) return [];
const encoded = [];
for (const img of question.images) {
const uri = img && typeof img === "object" ? img.uri : null;
if (!uri) continue;
const loaded = await tryLoadImageFromUri(uri, baseUrl);
if (loaded) encoded.push(loaded);
}
return encoded;
}
async function tryLoadImageFromUri(uri, baseUrl) {
const candidates = resolveImageUriCandidates(uri, baseUrl);
for (const fullUrl of candidates) {
try {
const resp = await fetch(fullUrl, { method: "GET", cache: "no-store" });
if (!resp.ok) continue;
const blob = await resp.blob();
const base64 = await blobToBase64(blob);
return { mimeType: blob.type || "image/png", base64 };
} catch {
// try next candidate
}
}
return null;
}
function resolveImageUri(uri, baseUrl) {
const candidates = resolveImageUriCandidates(uri, baseUrl);
return candidates.length ? candidates[0] : null;
}
function resolveImageUriCandidates(uri, baseUrl) {
const raw = String(uri || "").trim();
if (!raw) return [];
if (/^data:/i.test(raw) || /^https?:\/\//i.test(raw)) return [raw];
const out = [];
const pushUnique = (value) => {
if (value && !out.includes(value)) out.push(value);
};
const tryResolve = (value, base) => {
try {
return new URL(value, base).href;
} catch {
return null;
}
};
// Primary: user-specified image base.
if (baseUrl) {
pushUnique(tryResolve(raw, baseUrl));
// If baseUrl already points to data/, and uri starts with data/, avoid data/data.
if (raw.toLowerCase().startsWith("data/")) {
pushUnique(tryResolve(raw.slice(5), baseUrl));
}
}
// Fallbacks relative to current page.
pushUnique(tryResolve(raw, window.location.href));
pushUnique(tryResolve(raw, window.location.origin));
return out;
}
async function canResolveImageUri(uri, baseUrl, cache) {
const candidates = resolveImageUriCandidates(uri, baseUrl);
if (!candidates.length) return false;
for (const resolved of candidates) {
if (/^data:/i.test(resolved)) return true;
if (cache.has(resolved)) {
if (cache.get(resolved)) return true;
continue;
}
try {
// Some local/static servers fail HEAD even when GET works.
let resp = await fetch(resolved, { method: "HEAD", cache: "no-store" });
if (!resp.ok) {
resp = await fetch(resolved, { method: "GET", cache: "no-store" });
}
const ok = resp.ok;
cache.set(resolved, ok);
if (ok) return true;
} catch {
cache.set(resolved, false);
}
}
return false;
}
function blobToBase64(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const result = String(reader.result || "");
resolve(result.includes(",") ? result.split(",")[1] : result);
};
reader.onerror = () => reject(new Error("Failed to encode image blob"));
reader.readAsDataURL(blob);
});
}
function buildPayload(providerKey, model, userPrompt, encodedImages, temperature, openAiContentParts = null) {
if (providerKey === "openai") {
const contentParts = Array.isArray(openAiContentParts)
? openAiContentParts
: encodedImages.map((img) => ({
type: "input_image",
image_url: `data:${img.mimeType};base64,${img.base64}`
}));
return {
model,
temperature,
input: [
{
role: "user",
content: [
{ type: "input_text", text: userPrompt },
...contentParts
]
}
]
};
}
if (providerKey === "anthropic") {
const anthropicContent = [{ type: "text", text: userPrompt }];
for (const img of encodedImages || []) {
const mime = String(img?.mimeType || "").toLowerCase();
if (mime === "application/pdf") {
anthropicContent.push({
type: "document",
source: {
type: "base64",
media_type: "application/pdf",
data: img.base64
}
});
continue;
}
if (["image/jpeg", "image/png", "image/gif", "image/webp"].includes(mime)) {
anthropicContent.push({
type: "image",
source: {
type: "base64",
media_type: mime,
data: img.base64
}
});
}
}
return {
model,
temperature,
max_tokens: 1024,
messages: [
{
role: "user",
content: anthropicContent
}
]
};
}
throw new Error(`Unsupported provider: ${providerKey}`);
}
async function sendRequest(providerKey, apiKey, payload) {
const provider = providerCatalog[providerKey];
const headers = { "Content-Type": "application/json" };
if (providerKey === "openai") {
headers.Authorization = `Bearer ${apiKey}`;
} else if (providerKey === "anthropic") {
headers["x-api-key"] = apiKey;
headers["anthropic-version"] = "2023-06-01";
}
let response;
activeRequestController = new AbortController();
try {
response = await fetch(provider.endpoint, {
method: "POST",
headers,
body: JSON.stringify(payload),
signal: activeRequestController.signal
});
} catch (error) {
if (error?.name === "AbortError") {
throw error;
}
throw new Error(`Network error calling ${provider.label}: ${error.message}`);
} finally {
activeRequestController = null;
}
const data = await response.json();
if (!response.ok) {
throw new Error(data?.error?.message || `HTTP ${response.status}`);
}
return parseProviderResponse(providerKey, data);
}
function parseProviderResponse(providerKey, data) {
if (providerKey === "openai") {
let text = "";
if (typeof data.output_text === "string" && data.output_text.trim().length > 0) {
text = data.output_text;
} else {
const chunks = [];
for (const item of data.output || []) {
for (const part of item.content || []) {
if ((part.type === "output_text" || part.type === "text") && typeof part.text === "string") {
chunks.push(part.text);
}
}
}
text = chunks.join("\n").trim();
}
return { text, usage: data.usage };
}
if (providerKey === "anthropic") {
const text = (data.content || [])
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n")
.trim();
return { text, usage: data.usage };
}
return { text: "", usage: null };
}
function buildExamplePayload(providerKey, model, userPrompt, temperature) {
return buildPayload(providerKey, model, userPrompt, [{ mimeType: "image/png", base64: "<base64-image>" }], temperature);
}
function isPdfMimeType(mimeType) {
return String(mimeType || "").toLowerCase() === "application/pdf";
}
function base64ToBlob(base64, mimeType) {
const binary = atob(base64);
const len = binary.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i += 1) {
bytes[i] = binary.charCodeAt(i);
}
return new Blob([bytes], { type: mimeType || "application/octet-stream" });
}
function cacheKeyForEncodedAsset(asset) {
const mime = String(asset?.mimeType || "").toLowerCase();
const b64 = String(asset?.base64 || "");
return `${mime}|${b64.length}|${b64.slice(0, 64)}|${b64.slice(-64)}`;
}