browser-assistant 2.9.27 → 2.9.29
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/extension/automation-policy.js +3 -3
- package/extension/content.js +18 -6
- package/extension/editor-bridge.js +30 -18
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/server/main.py +52 -14
- package/server/vision_images.py +105 -2
|
@@ -335,10 +335,10 @@
|
|
|
335
335
|
return null;
|
|
336
336
|
}
|
|
337
337
|
const nativeRegion = doc.querySelector('#generic-question-container');
|
|
338
|
-
const nativeLabels = [...(nativeRegion?.querySelectorAll('.drag-and-drop-option-label') || [])]
|
|
338
|
+
const nativeLabels = [...(nativeRegion?.querySelectorAll('.drag-and-drop-option-label') || [])]
|
|
339
|
+
.filter(label => visible(label) && label.parentElement?.querySelector('.drag-icon-container[draggable="true"]'));
|
|
339
340
|
const nativePrompt = nativeRegion?.querySelector('#generic-question-wrapper-id');
|
|
340
|
-
if (nativeLabels.length >= 2 && nativeLabels.length <= 30 && nativePrompt
|
|
341
|
-
&& nativeLabels.every(label => label.parentElement.querySelector('.drag-icon-container[draggable="true"]'))) {
|
|
341
|
+
if (nativeLabels.length >= 2 && nativeLabels.length <= 30 && nativePrompt) {
|
|
342
342
|
const options = nativeLabels.map((label, index) => ({ index, text: textOf(label), node: label.parentElement }));
|
|
343
343
|
if (new Set(options.map(option => option.text)).size === options.length)
|
|
344
344
|
return {
|
package/extension/content.js
CHANGED
|
@@ -483,7 +483,7 @@ function mountJournalCountdown(signal) {
|
|
|
483
483
|
return `${normalizeAutomationText(questionText)}|${options.map(option => normalizeAutomationText(option.text)).join('|')}`;
|
|
484
484
|
}
|
|
485
485
|
function hasSameQuestionOptions(before, after) {
|
|
486
|
-
if (!before || !after || before.options.length !== after.options.length)
|
|
486
|
+
if (!before || !after || before.selectionType !== after.selectionType || before.options.length !== after.options.length)
|
|
487
487
|
return false;
|
|
488
488
|
if (normalizeAutomationText(before.identityText || before.text) !== normalizeAutomationText(after.identityText || after.text))
|
|
489
489
|
return false;
|
|
@@ -862,7 +862,7 @@ function mountJournalCountdown(signal) {
|
|
|
862
862
|
throw new Error('Target policy does not permit submission on this page.');
|
|
863
863
|
}
|
|
864
864
|
const fresh = getAuthorizedQuestion(context);
|
|
865
|
-
if (fresh && fresh.signature !== question.signature) {
|
|
865
|
+
if (fresh && (fresh.signature !== question.signature || fresh.selectionType !== question.selectionType)) {
|
|
866
866
|
throw new Error('Question changed before submission. No Submit was clicked.');
|
|
867
867
|
}
|
|
868
868
|
if (adapter.isSaving?.(document)) {
|
|
@@ -1987,6 +1987,7 @@ function mountJournalCountdown(signal) {
|
|
|
1987
1987
|
text: `${requestText}\nQuestion format: ${question.type === 'short-answer' ? 'Free response. Return only the exact value to enter in the JSON answer field, without an option label, explanation, or Markdown.' : question.selectionType === 'multiple' ? 'select all that apply; return every correct option as "Option A: ...; Option B: ...".' : 'select one answer.'}\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`,
|
|
1988
1988
|
...(question.type === 'ordering' ? { text: `${requestText}\nReorder ALL items. Return the complete permutation as a JSON array of 1-based item numbers in the answer field (example: [2,1,3]). Check every item appears exactly once.\n${question.options.map((option, index) => `${index + 1}. ${option.text}`).join('\n')}` } : {}),
|
|
1989
1989
|
url: window.location.href, practice_type: 'mcq', verify_answer: true,
|
|
1990
|
+
require_answer_agreement: question.selectionType === 'multiple',
|
|
1990
1991
|
};
|
|
1991
1992
|
const visuals = window.BrowserAssistantQuestionVisuals;
|
|
1992
1993
|
if (visuals?.nodes(question).length) {
|
|
@@ -2005,7 +2006,7 @@ function mountJournalCountdown(signal) {
|
|
|
2005
2006
|
updateAutomationUI();
|
|
2006
2007
|
response = await requestPracticeAnswer(question, runId, '/solve-vision', {
|
|
2007
2008
|
image: snapshot.images[0], images: snapshot.images.slice(1),
|
|
2008
|
-
|
|
2009
|
+
...requestBody,
|
|
2009
2010
|
});
|
|
2010
2011
|
}
|
|
2011
2012
|
else {
|
|
@@ -2034,6 +2035,11 @@ function mountJournalCountdown(signal) {
|
|
|
2034
2035
|
stopAutomation('PAUSED');
|
|
2035
2036
|
break;
|
|
2036
2037
|
}
|
|
2038
|
+
if (question.selectionType === 'multiple' && response.data.selection_set_verified !== true) {
|
|
2039
|
+
if (await continueAfterUnverifiedQuestion(question, runId, 'The complete checkbox answer could not be verified.'))
|
|
2040
|
+
continue;
|
|
2041
|
+
break;
|
|
2042
|
+
}
|
|
2037
2043
|
let results;
|
|
2038
2044
|
try {
|
|
2039
2045
|
results = JSON.parse(response.data.results);
|
|
@@ -2795,6 +2801,7 @@ function mountJournalCountdown(signal) {
|
|
|
2795
2801
|
practice_type: context.question ? 'mcq' : practiceType,
|
|
2796
2802
|
language: context.question ? undefined : requestedLanguage,
|
|
2797
2803
|
verify_answer: true,
|
|
2804
|
+
require_answer_agreement: context.question?.selectionType === 'multiple',
|
|
2798
2805
|
allow_overview: !context.question && practiceType === 'auto' && !requestedLanguage,
|
|
2799
2806
|
});
|
|
2800
2807
|
if (!res.ok) {
|
|
@@ -2813,7 +2820,7 @@ function mountJournalCountdown(signal) {
|
|
|
2813
2820
|
}
|
|
2814
2821
|
if (!Array.isArray(parsed) || !parsed.length)
|
|
2815
2822
|
throw new Error('The complete question could not be read. No guessed answer was returned.');
|
|
2816
|
-
assertVerifiedScanAnswers(parsed, data.answer_verified, context.question);
|
|
2823
|
+
assertVerifiedScanAnswers(parsed, data.answer_verified, context.question, data.selection_set_verified);
|
|
2817
2824
|
if (parsed.some(item => item?.type === 'code') && data.code_reviewed !== true) {
|
|
2818
2825
|
throw new Error('The code has not passed review against the screenshot.');
|
|
2819
2826
|
}
|
|
@@ -2840,7 +2847,7 @@ function mountJournalCountdown(signal) {
|
|
|
2840
2847
|
}
|
|
2841
2848
|
}
|
|
2842
2849
|
}
|
|
2843
|
-
function assertVerifiedScanAnswers(results, verified, question) {
|
|
2850
|
+
function assertVerifiedScanAnswers(results, verified, question, selectionSetVerified = false) {
|
|
2844
2851
|
if (question && (!Array.isArray(results) || results.length !== 1 || results[0]?.type !== 'mcq')) {
|
|
2845
2852
|
throw new Error('Expected one verified answer for the current question.');
|
|
2846
2853
|
}
|
|
@@ -2849,6 +2856,9 @@ function mountJournalCountdown(signal) {
|
|
|
2849
2856
|
if (verified !== true) {
|
|
2850
2857
|
throw new Error('Answer verification is required. Restart the updated Browser Assistant backend.');
|
|
2851
2858
|
}
|
|
2859
|
+
if (question?.selectionType === 'multiple' && selectionSetVerified !== true) {
|
|
2860
|
+
throw new Error('The complete checkbox answer could not be verified.');
|
|
2861
|
+
}
|
|
2852
2862
|
if (question && question.type !== 'short-answer' && question.type !== 'ordering'
|
|
2853
2863
|
&& !answerIndexesFromResult(results, question).length) {
|
|
2854
2864
|
throw new Error('The verified answer did not match the displayed options exactly.');
|
|
@@ -2939,12 +2949,14 @@ function mountJournalCountdown(signal) {
|
|
|
2939
2949
|
image: snapshot.images[0], images: snapshot.images.slice(1),
|
|
2940
2950
|
text: context.text,
|
|
2941
2951
|
url: location.href, practice_type: 'mcq', verify_answer: true,
|
|
2952
|
+
require_answer_agreement: question.selectionType === 'multiple',
|
|
2942
2953
|
});
|
|
2943
2954
|
}
|
|
2944
2955
|
else {
|
|
2945
2956
|
res = await apiRequest('/solve', 'POST', {
|
|
2946
2957
|
text: question ? context.text : extractSmartText(), url: context.url,
|
|
2947
2958
|
practice_type: question ? 'mcq' : practiceType, verify_answer: Boolean(question) || practiceType !== 'code',
|
|
2959
|
+
require_answer_agreement: question?.selectionType === 'multiple',
|
|
2948
2960
|
});
|
|
2949
2961
|
}
|
|
2950
2962
|
if (!res.ok) {
|
|
@@ -2976,7 +2988,7 @@ function mountJournalCountdown(signal) {
|
|
|
2976
2988
|
parsed = [{ type: "mcq", question: "Result", reasoning: "", answer: raw.substring(0, 200) }];
|
|
2977
2989
|
}
|
|
2978
2990
|
}
|
|
2979
|
-
assertVerifiedScanAnswers(parsed, data.answer_verified, question);
|
|
2991
|
+
assertVerifiedScanAnswers(parsed, data.answer_verified, question, data.selection_set_verified);
|
|
2980
2992
|
displayResults(parsed, data.provider);
|
|
2981
2993
|
}
|
|
2982
2994
|
catch (error) {
|
|
@@ -309,8 +309,11 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
309
309
|
.map(label => ({
|
|
310
310
|
label, row: label.parentElement, text: normalize(label.textContent),
|
|
311
311
|
handle: label.parentElement?.querySelector('.drag-icon-container[draggable="true"]'),
|
|
312
|
-
}))
|
|
313
|
-
|
|
312
|
+
}))
|
|
313
|
+
// The portal renders a copy of the option while dragging. Only
|
|
314
|
+
// the real option has a draggable handle.
|
|
315
|
+
.filter(row => row.handle);
|
|
316
|
+
return visible.length === expectedTexts.length && visible.every(row => uniqueTexts.has(row.text))
|
|
314
317
|
&& new Set(visible.map(row => row.text)).size === uniqueTexts.size ? visible : [];
|
|
315
318
|
};
|
|
316
319
|
const before = rows();
|
|
@@ -322,6 +325,7 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
322
325
|
const moving = before[from].text;
|
|
323
326
|
const destination = before[to].text;
|
|
324
327
|
const findRow = text => rows().find(row => row.text === text);
|
|
328
|
+
const didMove = () => rows()[to]?.text === moving;
|
|
325
329
|
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
|
326
330
|
const center = node => {
|
|
327
331
|
const rect = node.getBoundingClientRect();
|
|
@@ -344,7 +348,8 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
344
348
|
...init, clientX: mouse.clientX, clientY: mouse.clientY,
|
|
345
349
|
}));
|
|
346
350
|
};
|
|
347
|
-
|
|
351
|
+
const portalGrip = before[from].row.hasAttribute('data-handler-id') || before[from].handle.querySelector('svg');
|
|
352
|
+
for (const mode of portalGrip ? ['handle', 'row', 'press'] : ['row', 'handle', 'press']) {
|
|
348
353
|
if (mode === 'press' && typeof MouseEvent !== 'function')
|
|
349
354
|
break;
|
|
350
355
|
const current = unchangedRows();
|
|
@@ -363,11 +368,12 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
363
368
|
const row = findRow(destination);
|
|
364
369
|
if (!row)
|
|
365
370
|
return null;
|
|
371
|
+
const node = mode === 'handle' ? row.handle : row.label;
|
|
372
|
+
const { clientX } = center(node);
|
|
373
|
+
const bounds = (mode === 'handle' ? row.handle : row.row).getBoundingClientRect();
|
|
374
|
+
const clientY = bounds.top + bounds.height * (from > to ? 0.25 : 0.75);
|
|
366
375
|
if (mode === 'handle')
|
|
367
|
-
return
|
|
368
|
-
const { clientX } = center(row.label);
|
|
369
|
-
const rect = row.row.getBoundingClientRect();
|
|
370
|
-
const clientY = rect.top + rect.height * (from > to ? 0.25 : 0.75);
|
|
376
|
+
return { node, clientX, clientY };
|
|
371
377
|
const hit = document.elementFromPoint?.(clientX, clientY);
|
|
372
378
|
return { node: hit && row.row.contains(hit) ? hit : row.label, clientX, clientY };
|
|
373
379
|
};
|
|
@@ -382,7 +388,6 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
382
388
|
source = armed.row;
|
|
383
389
|
}
|
|
384
390
|
started = send({ ...center(findRow(moving)?.handle || handle), node: source }, 'dragstart');
|
|
385
|
-
// A cancelled start can mean the row has yet to be enabled by its handle.
|
|
386
391
|
if (!started)
|
|
387
392
|
continue;
|
|
388
393
|
// A drag handler can render fresh row nodes between events.
|
|
@@ -392,15 +397,22 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
392
397
|
if (!entered)
|
|
393
398
|
break;
|
|
394
399
|
send(entered, 'dragenter');
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
400
|
+
// The portal can commit the move on hover. Stop targeting the
|
|
401
|
+
// destination once its position changes.
|
|
402
|
+
await wait(0);
|
|
403
|
+
if (!didMove()) {
|
|
404
|
+
const hovered = target();
|
|
405
|
+
if (!hovered)
|
|
406
|
+
break;
|
|
407
|
+
send(hovered, 'dragover');
|
|
408
|
+
await wait(220);
|
|
409
|
+
if (!didMove()) {
|
|
410
|
+
const dropped = target();
|
|
411
|
+
if (!dropped)
|
|
412
|
+
break;
|
|
413
|
+
send(dropped, 'drop');
|
|
414
|
+
}
|
|
415
|
+
}
|
|
404
416
|
}
|
|
405
417
|
finally {
|
|
406
418
|
if (started) {
|
|
@@ -413,7 +425,7 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
413
425
|
}
|
|
414
426
|
for (let attempt = 0; attempt < 10; attempt++) {
|
|
415
427
|
await wait(160);
|
|
416
|
-
if (
|
|
428
|
+
if (didMove())
|
|
417
429
|
return { ok: true };
|
|
418
430
|
}
|
|
419
431
|
}
|
package/extension/manifest.json
CHANGED
package/package.json
CHANGED
package/server/main.py
CHANGED
|
@@ -30,6 +30,7 @@ from vision_images import (compress_image_base64, unique_image_blocks, collect_i
|
|
|
30
30
|
solve_relu_parallel_choice,
|
|
31
31
|
ordering_question, solve_sorted_list_merge_order, solve_stack_empty_order, solve_pseudocode_choice,
|
|
32
32
|
solve_stack_push_order, solve_stack_pop_order,
|
|
33
|
+
multiple_choice_question, solve_linked_stack_choices, cross_check_multiple_choice,
|
|
33
34
|
reading_response_constraints,
|
|
34
35
|
VisionRateLimitError, VisionUnconfirmedError)
|
|
35
36
|
|
|
@@ -194,7 +195,7 @@ async def lifespan(_app: FastAPI):
|
|
|
194
195
|
client.close()
|
|
195
196
|
|
|
196
197
|
|
|
197
|
-
app = FastAPI(title="Browser Assistant API", version="2.9.
|
|
198
|
+
app = FastAPI(title="Browser Assistant API", version="2.9.29", lifespan=lifespan)
|
|
198
199
|
install_local_guards(app)
|
|
199
200
|
|
|
200
201
|
@app.exception_handler(HTTPException)
|
|
@@ -229,6 +230,7 @@ class VisionContent(BaseModel):
|
|
|
229
230
|
language: str | None = None
|
|
230
231
|
text: str = ""
|
|
231
232
|
verify_answer: bool = False
|
|
233
|
+
require_answer_agreement: bool = False
|
|
232
234
|
allow_overview: bool = False
|
|
233
235
|
images: list[str] = [] # Additional complete question/option illustrations.
|
|
234
236
|
|
|
@@ -1313,6 +1315,7 @@ async def solve_questions(content: PageContent):
|
|
|
1313
1315
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
1314
1316
|
system_prompt = build_system_prompt(content.practice_type, language)
|
|
1315
1317
|
ordering = ordering_question(trimmed_text)
|
|
1318
|
+
multiple_choice = multiple_choice_question(trimmed_text)
|
|
1316
1319
|
reading_constraints = reading_response_constraints(trimmed_text) if content.require_answer_agreement else None
|
|
1317
1320
|
if ordering:
|
|
1318
1321
|
system_prompt = (
|
|
@@ -1320,6 +1323,14 @@ async def solve_questions(content: PageContent):
|
|
|
1320
1323
|
'step number once. Return exactly one JSON array item with type "mcq", the question, a brief '
|
|
1321
1324
|
'reasoning string, and an answer array of the original step numbers in their new order.'
|
|
1322
1325
|
)
|
|
1326
|
+
elif multiple_choice:
|
|
1327
|
+
system_prompt = (
|
|
1328
|
+
'Solve the checkbox question by evaluating every displayed option independently against the question. '
|
|
1329
|
+
'A checkbox question can have one or more correct answers. Select every correct option and nothing else. '
|
|
1330
|
+
'Return one JSON array item with type "mcq", the question, a brief reasoning string, and an answer string '
|
|
1331
|
+
'containing each selected option in letter order as "Option A: exact text; Option B: exact text". '
|
|
1332
|
+
'If any required evidence is missing, return [].'
|
|
1333
|
+
)
|
|
1323
1334
|
elif reading_constraints:
|
|
1324
1335
|
_, _, keyword = reading_constraints
|
|
1325
1336
|
rule = (f'Use two to five words including the unchanged word {keyword}. Preserve the meaning of the original sentence. '
|
|
@@ -1357,7 +1368,17 @@ REPAIR MODE:
|
|
|
1357
1368
|
detect_requested_language(content.text) is not None or content.language is not None,
|
|
1358
1369
|
)
|
|
1359
1370
|
strict_code_review = require_code and (content.review_before_submit or not FAST_CODE_MODE or STRICT_REPAIR_REVIEW)
|
|
1360
|
-
|
|
1371
|
+
checkbox = multiple_choice is not None and not require_code
|
|
1372
|
+
verify_answers = not require_code and (checkbox or content.verify_answer or content.require_answer_agreement or not FAST_SCAN_MODE)
|
|
1373
|
+
if checkbox:
|
|
1374
|
+
if not multiple_choice[1]:
|
|
1375
|
+
raise HTTPException(422, detail={'code': 'answer_unconfirmed',
|
|
1376
|
+
'message': 'The complete set of displayed checkbox options is required.'})
|
|
1377
|
+
item = solve_linked_stack_choices(multiple_choice)
|
|
1378
|
+
if item is not None:
|
|
1379
|
+
return {"results": json.dumps([item], ensure_ascii=False), "provider": "local linked-list stack check [verified]",
|
|
1380
|
+
"language": language, "answer_verified": True, "answer_agreement": True,
|
|
1381
|
+
"selection_set_verified": True, "code_reviewed": False}
|
|
1361
1382
|
if ordering and not require_code:
|
|
1362
1383
|
item = solve_sorted_list_merge_order(ordering)
|
|
1363
1384
|
provider = 'local merge-step check'
|
|
@@ -1373,13 +1394,13 @@ REPAIR MODE:
|
|
|
1373
1394
|
if item is not None:
|
|
1374
1395
|
return {"results": json.dumps([item], ensure_ascii=False), "provider": f"{provider} [verified]",
|
|
1375
1396
|
"language": language, "answer_verified": True, "code_reviewed": False}
|
|
1376
|
-
if not require_code and not content.require_answer_agreement and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1397
|
+
if not require_code and not checkbox and not content.require_answer_agreement and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1377
1398
|
local_result = local_choice_result(trimmed_text, language)
|
|
1378
1399
|
if local_result is not None:
|
|
1379
1400
|
return local_result
|
|
1380
1401
|
|
|
1381
1402
|
async def confirm_answers(cleaned, source_model=None):
|
|
1382
|
-
if not verify_answers or not any(item['type'] == 'mcq' for item in json.loads(cleaned)):
|
|
1403
|
+
if not verify_answers or (not checkbox and not any(item['type'] == 'mcq' for item in json.loads(cleaned))):
|
|
1383
1404
|
return cleaned, False
|
|
1384
1405
|
|
|
1385
1406
|
async def independent_solve(prompt_messages):
|
|
@@ -1394,10 +1415,13 @@ REPAIR MODE:
|
|
|
1394
1415
|
return await try_groq(prompt_messages, model=source_model, temperature=0.0)
|
|
1395
1416
|
|
|
1396
1417
|
try:
|
|
1397
|
-
|
|
1398
|
-
messages, cleaned, independent_solve,
|
|
1399
|
-
|
|
1400
|
-
|
|
1418
|
+
if checkbox:
|
|
1419
|
+
checked = await cross_check_multiple_choice(messages, cleaned, independent_solve, multiple_choice[1])
|
|
1420
|
+
else:
|
|
1421
|
+
checked = await cross_check_text_answers(
|
|
1422
|
+
messages, cleaned, independent_solve, question_text=trimmed_text,
|
|
1423
|
+
require_agreement=content.require_answer_agreement,
|
|
1424
|
+
)
|
|
1401
1425
|
except Exception as exc:
|
|
1402
1426
|
if isinstance(exc, VisionUnconfirmedError):
|
|
1403
1427
|
message = str(exc)
|
|
@@ -1433,7 +1457,8 @@ REPAIR MODE:
|
|
|
1433
1457
|
cleaned, verified = await confirm_answers(cleaned, model_id)
|
|
1434
1458
|
return {"results": cleaned, "provider": f"groq ({model_id})" + (' [cross-checked]' if verified else ''),
|
|
1435
1459
|
"language": language, "answer_verified": verified,
|
|
1436
|
-
"answer_agreement": verified and content.require_answer_agreement,
|
|
1460
|
+
"answer_agreement": verified and (checkbox or content.require_answer_agreement),
|
|
1461
|
+
"selection_set_verified": verified and checkbox,
|
|
1437
1462
|
"code_reviewed": strict_code_review and language != 'web'}
|
|
1438
1463
|
else:
|
|
1439
1464
|
errors.append(f"{model_id}: returned empty/unparseable results")
|
|
@@ -1472,7 +1497,8 @@ REPAIR MODE:
|
|
|
1472
1497
|
"results": cleaned,
|
|
1473
1498
|
"provider": f"ollama ({OLLAMA_MODEL})" + (' [cross-checked]' if verified else ''),
|
|
1474
1499
|
"answer_verified": verified,
|
|
1475
|
-
"answer_agreement": verified and content.require_answer_agreement,
|
|
1500
|
+
"answer_agreement": verified and (checkbox or content.require_answer_agreement),
|
|
1501
|
+
"selection_set_verified": verified and checkbox,
|
|
1476
1502
|
"language": language,
|
|
1477
1503
|
"code_reviewed": strict_code_review and language != 'web',
|
|
1478
1504
|
}
|
|
@@ -1547,7 +1573,12 @@ async def _solve_vision(content: VisionContent):
|
|
|
1547
1573
|
raise HTTPException(422, f'Image {index}: {exc}') from exc
|
|
1548
1574
|
is_code_scan = content.practice_type == "code" or (content.practice_type == "auto" and bool(content.language))
|
|
1549
1575
|
allow_overview = content.allow_overview and content.practice_type == 'auto' and not is_code_scan and not content.text.strip()
|
|
1550
|
-
if
|
|
1576
|
+
checkbox_question = None if is_code_scan else multiple_choice_question(content.text)
|
|
1577
|
+
if ((checkbox_question is not None and not checkbox_question[1])
|
|
1578
|
+
or (content.require_answer_agreement and checkbox_question is None)):
|
|
1579
|
+
raise HTTPException(422, detail={'code': 'vision_unconfirmed',
|
|
1580
|
+
'message': 'Every displayed checkbox option is required for verification.'})
|
|
1581
|
+
if not is_code_scan and checkbox_question is None and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1551
1582
|
local_result = local_choice_result(content.text, content.language or CODE_DEFAULT_LANGUAGE)
|
|
1552
1583
|
if local_result is not None:
|
|
1553
1584
|
return local_result
|
|
@@ -1562,7 +1593,7 @@ async def _solve_vision(content: VisionContent):
|
|
|
1562
1593
|
loop = asyncio.get_running_loop()
|
|
1563
1594
|
errors = []
|
|
1564
1595
|
rate_limit_resets = []
|
|
1565
|
-
comparison = None if is_code_scan else relative_percentage_question(content.text)
|
|
1596
|
+
comparison = None if is_code_scan or checkbox_question is not None else relative_percentage_question(content.text)
|
|
1566
1597
|
unconfirmed = False
|
|
1567
1598
|
vision_token_limit = 4096 if is_code_scan else VISION_MAX_TOKENS
|
|
1568
1599
|
|
|
@@ -1708,6 +1739,9 @@ async def _solve_vision(content: VisionContent):
|
|
|
1708
1739
|
async def vision_verifier(prompt_messages, model):
|
|
1709
1740
|
return await complete_vision(prompt_messages, model, verification=True)
|
|
1710
1741
|
|
|
1742
|
+
async def checkbox_verifier(prompt_messages):
|
|
1743
|
+
return await vision_verifier(prompt_messages, vision_model)
|
|
1744
|
+
|
|
1711
1745
|
cleaned = await generate_validated_result(
|
|
1712
1746
|
vision_generator,
|
|
1713
1747
|
solution_messages,
|
|
@@ -1733,9 +1767,12 @@ async def _solve_vision(content: VisionContent):
|
|
|
1733
1767
|
except ValueError as exc:
|
|
1734
1768
|
raise VisionUnconfirmedError('The code could not be confirmed against the screenshot.') from exc
|
|
1735
1769
|
code_reviewed = True
|
|
1736
|
-
if
|
|
1770
|
+
if checkbox_question is not None:
|
|
1771
|
+
cleaned = await cross_check_multiple_choice(solution_messages, cleaned, checkbox_verifier,
|
|
1772
|
+
checkbox_question[1])
|
|
1773
|
+
elif comparison and not has_mcq:
|
|
1737
1774
|
raise VisionUnconfirmedError('Expected a chart comparison answer.')
|
|
1738
|
-
|
|
1775
|
+
elif has_mcq and not is_code_scan:
|
|
1739
1776
|
cleaned = await cross_check_visual_answers(
|
|
1740
1777
|
solution_messages, cleaned, vision_model, vision_verifier, comparison,
|
|
1741
1778
|
require_agreement=content.verify_answer,
|
|
@@ -1744,6 +1781,7 @@ async def _solve_vision(content: VisionContent):
|
|
|
1744
1781
|
"results": cleaned,
|
|
1745
1782
|
"provider": f"groq-vision ({vision_model})" + (' [cross-checked]' if has_mcq and not is_code_scan else ''),
|
|
1746
1783
|
"answer_verified": has_mcq and not is_code_scan,
|
|
1784
|
+
"selection_set_verified": checkbox_question is not None,
|
|
1747
1785
|
"code_reviewed": code_reviewed,
|
|
1748
1786
|
"language": language,
|
|
1749
1787
|
}
|
package/server/vision_images.py
CHANGED
|
@@ -473,8 +473,7 @@ def matrix_question(messages):
|
|
|
473
473
|
return any(MATRIX_SYNTAX.search(str(message.get('content', ''))) for message in messages[1:])
|
|
474
474
|
|
|
475
475
|
|
|
476
|
-
def
|
|
477
|
-
"""Accept a complete verdict, including common provider wrappers."""
|
|
476
|
+
def _verification_payload(raw):
|
|
478
477
|
raw = re.sub(r'^\s*<think>.*?</think>\s*', '', raw, count=1, flags=re.S | re.I)
|
|
479
478
|
raw = re.sub(r'^```(?:json)?\s*|\s*```$', '', raw.strip(), flags=re.I)
|
|
480
479
|
try:
|
|
@@ -483,6 +482,12 @@ def parse_answer_check(raw, count):
|
|
|
483
482
|
raise ValueError('The vision provider returned malformed verification JSON.') from exc
|
|
484
483
|
if not isinstance(payload, dict):
|
|
485
484
|
raise ValueError('The verification response must be a JSON object.')
|
|
485
|
+
return payload
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def parse_answer_check(raw, count):
|
|
489
|
+
"""Accept a complete verdict, including common provider wrappers."""
|
|
490
|
+
payload = _verification_payload(raw)
|
|
486
491
|
answers = payload.get('answers')
|
|
487
492
|
if payload.get('readable') is False and answers == []:
|
|
488
493
|
raise VisionUnconfirmedError('Required visual evidence was reported unreadable.')
|
|
@@ -512,6 +517,58 @@ def displayed_single_choices(text):
|
|
|
512
517
|
return parse_labeled_choices(option_text)
|
|
513
518
|
|
|
514
519
|
|
|
520
|
+
MULTIPLE_CHOICE_FORMAT = re.compile(
|
|
521
|
+
r'^(?:Question format: select all that apply(?:[.;][^\r\n]*)?|Select ALL correct options\.)[ \t]*\r?$',
|
|
522
|
+
re.I | re.M,
|
|
523
|
+
)
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
def multiple_choice_question(text):
|
|
527
|
+
"""Read a checkbox prompt and every option from the extension's question format."""
|
|
528
|
+
marker = list(MULTIPLE_CHOICE_FORMAT.finditer(text))
|
|
529
|
+
if not marker:
|
|
530
|
+
return None
|
|
531
|
+
marker = marker[-1]
|
|
532
|
+
prompt = text[:marker.start()].strip()
|
|
533
|
+
option_text = text[marker.end():].strip()
|
|
534
|
+
choices = parse_labeled_choices(option_text[2:]) if prompt and option_text.startswith('A.') else {}
|
|
535
|
+
return prompt, choices
|
|
536
|
+
|
|
537
|
+
|
|
538
|
+
def _format_choice_set(choices, selected):
|
|
539
|
+
return '; '.join(f'Option {letter}: {label}' for letter, label in choices.items() if letter in selected)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def solve_linked_stack_choices(question):
|
|
543
|
+
if question is None:
|
|
544
|
+
return None
|
|
545
|
+
prompt, choices = question
|
|
546
|
+
|
|
547
|
+
def normalize(value):
|
|
548
|
+
return ' '.join(value.replace('\x60', '').lower().split()).rstrip(' .?')
|
|
549
|
+
|
|
550
|
+
normalized_prompt = normalize(prompt)
|
|
551
|
+
linked_stack = r'in a stack implemented (?:using|with) a linked list'
|
|
552
|
+
if re.fullmatch(rf'which of the following are true about the pop\s*\(\s*\) operation {linked_stack}',
|
|
553
|
+
normalized_prompt):
|
|
554
|
+
correct = ('it removes the top element from the stack', 'check if the stack is empty')
|
|
555
|
+
incorrect = ('it returns the top element without removing it', 'it adds an element to the top of the stack')
|
|
556
|
+
reasoning = 'Check for an empty stack before removing the top node. Reading without removing is peek; adding is push.'
|
|
557
|
+
elif re.fullmatch(rf'which statements are true regarding the push\s*\(\s*\) operation(?: {linked_stack})?',
|
|
558
|
+
normalized_prompt):
|
|
559
|
+
correct = ('it creates a new node with temp pointing to it', 'it updates the top pointer to the new node')
|
|
560
|
+
incorrect = ('it checks if the stack is full before pushing', 'it deletes the previous top node')
|
|
561
|
+
reasoning = ('Allocate a node, link it to the current top, and update top. This linked-list stack has no '
|
|
562
|
+
'stated fixed capacity and retains all earlier nodes.')
|
|
563
|
+
else:
|
|
564
|
+
return None
|
|
565
|
+
normalized_choices = {letter: normalize(option) for letter, option in choices.items()}
|
|
566
|
+
if len(choices) != len(correct) + len(incorrect) or set(normalized_choices.values()) != set(correct + incorrect):
|
|
567
|
+
return None
|
|
568
|
+
selected = {letter for letter, option in normalized_choices.items() if option in correct}
|
|
569
|
+
return {'type': 'mcq', 'question': prompt, 'answer': _format_choice_set(choices, selected), 'reasoning': reasoning}
|
|
570
|
+
|
|
571
|
+
|
|
515
572
|
def solve_pseudocode_choice(text):
|
|
516
573
|
choices = displayed_single_choices(text)
|
|
517
574
|
if not choices:
|
|
@@ -627,6 +684,52 @@ def bind_displayed_choice(value, choices, *, matrix_math):
|
|
|
627
684
|
return unique.pop() if len(unique) == 1 else None
|
|
628
685
|
|
|
629
686
|
|
|
687
|
+
async def cross_check_multiple_choice(messages, results, complete, choices):
|
|
688
|
+
"""Require independence plus a verdict for every checkbox before verifying a selection."""
|
|
689
|
+
items = json.loads(results)
|
|
690
|
+
if not choices or len(items) != 1 or items[0].get('type') != 'mcq':
|
|
691
|
+
raise VisionUnconfirmedError('Expected one checkbox question with all displayed options.')
|
|
692
|
+
answer = items[0].get('answer')
|
|
693
|
+
matrix_math = matrix_question(messages)
|
|
694
|
+
parts = re.split(r';\s*(?=(?:Option\s+)?[A-Z]\s*[:.)])', answer, flags=re.I) if isinstance(answer, str) else []
|
|
695
|
+
selected = [bind_displayed_choice(part, choices, matrix_math=matrix_math) for part in parts]
|
|
696
|
+
first = frozenset(selected) if selected and None not in selected and len(set(selected)) == len(selected) else None
|
|
697
|
+
|
|
698
|
+
instruction = (
|
|
699
|
+
'Independently evaluate EVERY displayed checkbox option using the original question, context and any '
|
|
700
|
+
'attached evidence. Decide whether each option separately satisfies the question. Ignore any existing '
|
|
701
|
+
'selection in the images. A checkbox question can have one or more correct options. Do not stop after '
|
|
702
|
+
'finding the first correct option. If any required evidence or verdict is uncertain, return '
|
|
703
|
+
'{"readable":false,"options":[]}. Otherwise return only JSON with readable=true and an options array '
|
|
704
|
+
'containing {"letter":"A","correct":true} or {"letter":"A","correct":false} for each displayed letter '
|
|
705
|
+
f'exactly once, in this order: {", ".join(choices)}.'
|
|
706
|
+
)
|
|
707
|
+
check_messages = [{'role': 'system', 'content': instruction}, *messages[1:]]
|
|
708
|
+
previous = None
|
|
709
|
+
for attempt in range(2):
|
|
710
|
+
raw = await complete(check_messages)
|
|
711
|
+
try:
|
|
712
|
+
payload = _verification_payload(raw)
|
|
713
|
+
except (ValueError, TypeError):
|
|
714
|
+
payload = {}
|
|
715
|
+
verdicts = payload.get('options')
|
|
716
|
+
current = None
|
|
717
|
+
if (payload.get('readable') is True and isinstance(verdicts, list) and len(verdicts) == len(choices)
|
|
718
|
+
and all(isinstance(verdict, dict) and verdict.get('letter') == letter
|
|
719
|
+
and type(verdict.get('correct')) is bool for letter, verdict in zip(choices, verdicts))):
|
|
720
|
+
current = frozenset(verdict['letter'] for verdict in verdicts if verdict['correct'])
|
|
721
|
+
if current and (current == first or current == previous):
|
|
722
|
+
if current != first:
|
|
723
|
+
items[0].pop('reasoning', None)
|
|
724
|
+
items[0]['answer'] = _format_choice_set(choices, current)
|
|
725
|
+
return json.dumps(items, ensure_ascii=False)
|
|
726
|
+
if not attempt:
|
|
727
|
+
previous = current
|
|
728
|
+
check_messages = [*check_messages, {'role': 'user', 'content':
|
|
729
|
+
'Re-evaluate each displayed option independently and return a verdict for every displayed letter.'}]
|
|
730
|
+
raise VisionUnconfirmedError('The independent checks could not confirm the complete checkbox answer.')
|
|
731
|
+
|
|
732
|
+
|
|
630
733
|
async def cross_check_text_answers(messages, results, complete, *, question_text='', require_agreement=False):
|
|
631
734
|
items = json.loads(results)
|
|
632
735
|
if not items or any(item.get('type') != 'mcq' for item in items):
|