browser-assistant 2.9.43 → 2.9.45
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 +11 -3
- package/extension/content.js +19 -4
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/server/code_contract.py +42 -3
- package/server/main.py +21 -9
- package/server/vision_images.py +36 -11
|
@@ -123,7 +123,7 @@
|
|
|
123
123
|
renderer.replaceWith(doc.createTextNode(` ${JSON.stringify(cells).replace(/"/g, '')} `));
|
|
124
124
|
}
|
|
125
125
|
};
|
|
126
|
-
const textOf = (element) => {
|
|
126
|
+
const textOf = (element, preserveCode = false) => {
|
|
127
127
|
if (!element)
|
|
128
128
|
return '';
|
|
129
129
|
const clone = element.cloneNode(true);
|
|
@@ -134,8 +134,16 @@
|
|
|
134
134
|
? browserAssistantCachedMcqSnippet(editors[index]) : undefined;
|
|
135
135
|
if (typeof source === 'string')
|
|
136
136
|
block.textContent = '\n' + source + '\n';
|
|
137
|
+
else if (preserveCode) {
|
|
138
|
+
const lines = [...editors[index].querySelectorAll('.ace_line,.view-line,.CodeMirror-line')];
|
|
139
|
+
if (lines.length)
|
|
140
|
+
block.textContent = '\n' + lines.map(line => line.textContent || '').join('\n') + '\n';
|
|
141
|
+
}
|
|
137
142
|
});
|
|
138
143
|
clone.querySelectorAll('.ace_gutter,.line-numbers,.line-numbers-rows,.linenumber,.margin-view-overlays,script,style').forEach(node => node.remove());
|
|
144
|
+
if (preserveCode && element.querySelector('pre,code,.ace_editor,.CodeMirror,.monaco-editor')) {
|
|
145
|
+
return (clone.textContent || '').trim();
|
|
146
|
+
}
|
|
139
147
|
return (clone.textContent || '').replace(/\s+/g, ' ').trim();
|
|
140
148
|
};
|
|
141
149
|
const optionIdentity = element => {
|
|
@@ -408,10 +416,10 @@
|
|
|
408
416
|
|| input?.closest('label')
|
|
409
417
|
|| (control.matches('label') ? control : null);
|
|
410
418
|
const optionControl = label && input ? label : control;
|
|
411
|
-
const optionText = textOf(label) || textOf(control) || control.getAttribute('aria-label') || control.getAttribute('value') || '';
|
|
419
|
+
const optionText = textOf(label, true) || textOf(control, true) || control.getAttribute('aria-label') || control.getAttribute('value') || '';
|
|
412
420
|
return {
|
|
413
421
|
index, input, control: optionControl, node: label || control,
|
|
414
|
-
text: optionText.
|
|
422
|
+
text: optionText.trim(),
|
|
415
423
|
identityText: optionIdentity(label || control) || optionText.replace(/\s+/g, ' ').trim(),
|
|
416
424
|
isSelected: () => Boolean(input?.checked || optionControl.getAttribute('aria-checked') === 'true'),
|
|
417
425
|
};
|
package/extension/content.js
CHANGED
|
@@ -524,8 +524,10 @@ function mountJournalCountdown(signal) {
|
|
|
524
524
|
}
|
|
525
525
|
if (question.type !== 'short-answer' && question.options.length < 2)
|
|
526
526
|
return null;
|
|
527
|
-
|
|
528
|
-
|
|
527
|
+
// Keep snippet line breaks/indentation in the model input. Identity
|
|
528
|
+
// comparison and signatures normalize presentation whitespace separately.
|
|
529
|
+
return { ...question, text: question.text.trim(), options: question.options.map((option, index) => ({
|
|
530
|
+
...option, index, text: option.text.trim(),
|
|
529
531
|
})), signature: questionSignature(question.identityText || question.text, question.options)
|
|
530
532
|
+ (window.BrowserAssistantQuestionVisuals?.nodes(question).length ? `|visual:${window.BrowserAssistantQuestionVisuals.fingerprint(question)}` : '') };
|
|
531
533
|
}
|
|
@@ -1542,6 +1544,11 @@ function mountJournalCountdown(signal) {
|
|
|
1542
1544
|
stopAutomation('UNAUTHORIZED');
|
|
1543
1545
|
return false;
|
|
1544
1546
|
}
|
|
1547
|
+
if (initial.target.id === 'ccbp-learning-practice' && isClassQuizRoute(location.pathname)) {
|
|
1548
|
+
automation.error = `${reason} Classroom quiz paused for review; no unconfirmed answer was submitted.`;
|
|
1549
|
+
stopAutomation('PAUSED');
|
|
1550
|
+
return false;
|
|
1551
|
+
}
|
|
1545
1552
|
const fresh = getAuthorizedQuestion(initial);
|
|
1546
1553
|
const sameQuestion = fresh?.signature === question.signature && hasSameQuestionOptions(question, fresh);
|
|
1547
1554
|
const practice = initial.target.id === 'ccbp-learning-practice'
|
|
@@ -1981,6 +1988,8 @@ function mountJournalCountdown(signal) {
|
|
|
1981
1988
|
}
|
|
1982
1989
|
automation.state = 'SOLVING';
|
|
1983
1990
|
updateAutomationUI();
|
|
1991
|
+
const requireClassQuizAgreement = location.origin === 'https://learning.ccbp.in'
|
|
1992
|
+
&& question.selectionType === 'single' && isClassQuizRoute(location.pathname);
|
|
1984
1993
|
let response;
|
|
1985
1994
|
try {
|
|
1986
1995
|
let requestText = question.text;
|
|
@@ -1993,7 +2002,8 @@ function mountJournalCountdown(signal) {
|
|
|
1993
2002
|
throw new Error(`Drag-and-drop needs backend 2.9.10 or newer. Backend ${backendVersion} is running. Restart it, then start automation again.`);
|
|
1994
2003
|
}
|
|
1995
2004
|
}
|
|
1996
|
-
if (location.origin === 'https://learning.ccbp.in'
|
|
2005
|
+
if (location.origin === 'https://learning.ccbp.in'
|
|
2006
|
+
&& (/^\/primitive-coding(?:-review)?\/practice\//.test(location.pathname) || isClassQuizRoute(location.pathname))
|
|
1997
2007
|
&& document.querySelector('.ace_editor,.monaco-editor,.CodeMirror')) {
|
|
1998
2008
|
const snapshot = await readMcqSnippetSnapshot(question, runId);
|
|
1999
2009
|
if (!snapshot?.ok)
|
|
@@ -2015,7 +2025,7 @@ function mountJournalCountdown(signal) {
|
|
|
2015
2025
|
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')}`,
|
|
2016
2026
|
...(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')}` } : {}),
|
|
2017
2027
|
url: window.location.href, practice_type: 'mcq', verify_answer: true,
|
|
2018
|
-
require_answer_agreement: question.selectionType === 'multiple' || question.type === 'short-answer',
|
|
2028
|
+
require_answer_agreement: requireClassQuizAgreement || question.selectionType === 'multiple' || question.type === 'short-answer',
|
|
2019
2029
|
};
|
|
2020
2030
|
const visuals = window.BrowserAssistantQuestionVisuals;
|
|
2021
2031
|
if (visuals?.nodes(question).length) {
|
|
@@ -2063,6 +2073,11 @@ function mountJournalCountdown(signal) {
|
|
|
2063
2073
|
stopAutomation('PAUSED');
|
|
2064
2074
|
break;
|
|
2065
2075
|
}
|
|
2076
|
+
if (requireClassQuizAgreement && response.data?.answer_agreement !== true) {
|
|
2077
|
+
automation.error = 'Classroom quiz answers require independent agreement before selection. Update the backend or review this question manually.';
|
|
2078
|
+
stopAutomation('PAUSED');
|
|
2079
|
+
break;
|
|
2080
|
+
}
|
|
2066
2081
|
if (question.selectionType === 'multiple' && response.data.selection_set_verified !== true) {
|
|
2067
2082
|
if (await continueAfterUnverifiedQuestion(question, runId, 'The complete checkbox answer could not be verified.'))
|
|
2068
2083
|
continue;
|
package/extension/manifest.json
CHANGED
package/package.json
CHANGED
package/server/code_contract.py
CHANGED
|
@@ -70,12 +70,51 @@ def function_header(node, data, language):
|
|
|
70
70
|
for start, stop in sorted(ignored, reverse=True):
|
|
71
71
|
header = header[:start-node.start_byte] + header[stop-node.start_byte:]
|
|
72
72
|
header = header.decode('utf-8')
|
|
73
|
+
elif language == 'python':
|
|
74
|
+
# Python comments between ':' and the first statement are not API.
|
|
75
|
+
spans = []
|
|
76
|
+
def comments(child):
|
|
77
|
+
if child.type == 'comment' and child.start_byte < end:
|
|
78
|
+
spans.append((child.start_byte, min(child.end_byte, end)))
|
|
79
|
+
for part in child.named_children:
|
|
80
|
+
comments(part)
|
|
81
|
+
comments(node)
|
|
82
|
+
for start, stop in sorted(spans, reverse=True):
|
|
83
|
+
header = header[:start-node.start_byte] + header[stop-node.start_byte:]
|
|
84
|
+
header = header.decode('utf-8')
|
|
73
85
|
else:
|
|
74
86
|
header = re.sub(r'/\*.*?\*/|//[^\n]*', '', header.decode('utf-8'), flags=re.DOTALL)
|
|
75
87
|
return re.sub(r'\s+', '', header)
|
|
76
88
|
|
|
77
89
|
|
|
78
|
-
def
|
|
90
|
+
def prepare_starter(source, language):
|
|
91
|
+
"""Recover a C++ portal scaffold without repairing generated output."""
|
|
92
|
+
if language != 'cpp':
|
|
93
|
+
return source
|
|
94
|
+
# An accidentally pasted Python program is not part of a C++ interface.
|
|
95
|
+
if re.search(r'\b(?:class|struct)\s+\w+\s*\{', source):
|
|
96
|
+
source = re.split(r'(?m)^def\s+\w+\s*\(', source, maxsplit=1)[0]
|
|
97
|
+
data = source.encode('utf-8')
|
|
98
|
+
root = get_parser('cpp').parse(data).root_node
|
|
99
|
+
balance = 0
|
|
100
|
+
def braces(node):
|
|
101
|
+
nonlocal balance
|
|
102
|
+
if node.type == '{' and not node.is_missing:
|
|
103
|
+
balance += 1
|
|
104
|
+
elif node.type == '}' and not node.is_missing:
|
|
105
|
+
balance -= 1
|
|
106
|
+
else:
|
|
107
|
+
for child in node.children:
|
|
108
|
+
braces(child)
|
|
109
|
+
braces(root)
|
|
110
|
+
if 0 < balance <= 8:
|
|
111
|
+
source += '\n' + '\n'.join('}' for _ in range(balance)) + ';\n'
|
|
112
|
+
return source
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def interface(source, language, *, starter=False):
|
|
116
|
+
if starter:
|
|
117
|
+
source = prepare_starter(source, language)
|
|
79
118
|
data = source.encode('utf-8')
|
|
80
119
|
root = get_parser(language).parse(data).root_node
|
|
81
120
|
classes, functions = set(), set()
|
|
@@ -114,7 +153,7 @@ def interface(source, language):
|
|
|
114
153
|
def validate_starter_interface(code, starter, language):
|
|
115
154
|
if not starter or language not in SUPPORTED:
|
|
116
155
|
return
|
|
117
|
-
classes, functions = interface(starter, language)
|
|
156
|
+
classes, functions = interface(starter, language, starter=True)
|
|
118
157
|
actual_classes, actual_functions = interface(code, language)
|
|
119
158
|
missing_classes = classes - actual_classes
|
|
120
159
|
if missing_classes:
|
|
@@ -139,7 +178,7 @@ def normalize_starter_code(code, starter, language):
|
|
|
139
178
|
"""Remove one added C++ driver only when the complete required interface remains."""
|
|
140
179
|
if language != 'cpp' or not starter:
|
|
141
180
|
return code
|
|
142
|
-
classes, functions = interface(starter, language)
|
|
181
|
+
classes, functions = interface(starter, language, starter=True)
|
|
143
182
|
if not (classes or functions) or any(not owner and re.search(r'^(?:int|signed(?:int)?|auto)main\(', header)
|
|
144
183
|
for owner, header, _access in functions):
|
|
145
184
|
return code
|
package/server/main.py
CHANGED
|
@@ -20,7 +20,7 @@ import sqlite3
|
|
|
20
20
|
from contextlib import asynccontextmanager, contextmanager
|
|
21
21
|
from datetime import datetime, timezone
|
|
22
22
|
from pathlib import Path
|
|
23
|
-
from code_contract import coding_samples, validate_starter_interface, normalize_starter_code
|
|
23
|
+
from code_contract import coding_samples, validate_starter_interface, normalize_starter_code, prepare_starter
|
|
24
24
|
from fastapi import Query, status
|
|
25
25
|
from fastapi.responses import FileResponse
|
|
26
26
|
from fastapi.exception_handlers import http_exception_handler
|
|
@@ -33,7 +33,7 @@ from vision_images import (compress_image_base64, unique_image_blocks, collect_i
|
|
|
33
33
|
solve_stack_push_order, solve_stack_pop_order, solve_next_greater_element_order,
|
|
34
34
|
multiple_choice_question, solve_linked_stack_choices, cross_check_multiple_choice, stack_reasoning_guidance,
|
|
35
35
|
reading_response_constraints, free_response_question,
|
|
36
|
-
VisionRateLimitError, VisionUnconfirmedError)
|
|
36
|
+
VisionRateLimitError, VisionUnconfirmedError, displayed_single_choices)
|
|
37
37
|
|
|
38
38
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
|
39
39
|
logger = logging.getLogger("browser-assistant")
|
|
@@ -201,7 +201,7 @@ async def lifespan(_app: FastAPI):
|
|
|
201
201
|
client.close()
|
|
202
202
|
|
|
203
203
|
|
|
204
|
-
app = FastAPI(title="Browser Assistant API", version="2.9.
|
|
204
|
+
app = FastAPI(title="Browser Assistant API", version="2.9.45", lifespan=lifespan)
|
|
205
205
|
install_local_guards(app)
|
|
206
206
|
|
|
207
207
|
@app.exception_handler(HTTPException)
|
|
@@ -998,7 +998,7 @@ def build_ollama_code_messages(text: str, url: str, language: str, *,
|
|
|
998
998
|
starter_code: str | None = None, repair_attempt: int = 0) -> list:
|
|
999
999
|
"""Keep all coding evidence intact within the local fallback's input budget."""
|
|
1000
1000
|
if starter_code:
|
|
1001
|
-
text += '\n\nOriginal portal starter interface:\n' + starter_code
|
|
1001
|
+
text += '\n\nOriginal portal starter interface:\n' + prepare_starter(starter_code, language)
|
|
1002
1002
|
if len(text) > 18_000:
|
|
1003
1003
|
raise ValueError(
|
|
1004
1004
|
'Local Ollama fallback needs the full problem, code and feedback within 18000 characters. '
|
|
@@ -1105,7 +1105,7 @@ def starter_interface_instructions(starter_code: str | None, language: str) -> s
|
|
|
1105
1105
|
return ''
|
|
1106
1106
|
instructions = ('\nORIGINAL PORTAL STARTER CODE (immutable interface; preserve exact class and function '
|
|
1107
1107
|
'names, case, return types, parameter types, reference qualifiers, parameter order and access):\n'
|
|
1108
|
-
+ starter_code)
|
|
1108
|
+
+ prepare_starter(starter_code, language))
|
|
1109
1109
|
if language == 'cpp':
|
|
1110
1110
|
instructions += ('\nFor C++: complete the supplied function body inside its original class. '
|
|
1111
1111
|
'Copy the original function declaration and access exactly. '
|
|
@@ -1441,6 +1441,7 @@ async def solve_questions(content: PageContent):
|
|
|
1441
1441
|
samples = coding_samples(trimmed_text) if strict_code_review and language != 'web' else ()
|
|
1442
1442
|
checkbox = multiple_choice is not None and not require_code
|
|
1443
1443
|
verify_answers = not require_code and (checkbox or content.verify_answer or content.require_answer_agreement or not FAST_SCAN_MODE)
|
|
1444
|
+
strict_single_choice = not require_code and content.require_answer_agreement and bool(displayed_single_choices(trimmed_text))
|
|
1444
1445
|
if checkbox:
|
|
1445
1446
|
if not multiple_choice[1]:
|
|
1446
1447
|
raise HTTPException(422, detail={'code': 'answer_unconfirmed',
|
|
@@ -1479,13 +1480,21 @@ async def solve_questions(content: PageContent):
|
|
|
1479
1480
|
|
|
1480
1481
|
async def independent_solve(prompt_messages):
|
|
1481
1482
|
if source_model is None:
|
|
1483
|
+
if strict_single_choice:
|
|
1484
|
+
if not TEXT_MODELS:
|
|
1485
|
+
raise VisionUnconfirmedError('An independent model was unavailable to confirm this quiz answer.')
|
|
1486
|
+
return await try_groq(prompt_messages, model=TEXT_MODELS[0], temperature=0.0)
|
|
1482
1487
|
return await try_ollama(prompt_messages, temperature=0.0)
|
|
1483
1488
|
alternate = next((model for model in TEXT_MODELS if model != source_model), None)
|
|
1484
1489
|
if alternate:
|
|
1485
1490
|
try:
|
|
1486
1491
|
return await try_groq(prompt_messages, model=alternate, temperature=0.0)
|
|
1487
1492
|
except Exception:
|
|
1493
|
+
if strict_single_choice:
|
|
1494
|
+
raise
|
|
1488
1495
|
logger.info("Alternate text verifier unavailable. Trying a fresh pass on %s.", source_model)
|
|
1496
|
+
if strict_single_choice:
|
|
1497
|
+
raise VisionUnconfirmedError('An independent model was unavailable to confirm this quiz answer.')
|
|
1489
1498
|
return await try_groq(prompt_messages, model=source_model, temperature=0.0)
|
|
1490
1499
|
|
|
1491
1500
|
try:
|
|
@@ -1661,10 +1670,11 @@ async def _solve_vision(content: VisionContent):
|
|
|
1661
1670
|
allow_overview = content.allow_overview and content.practice_type == 'auto' and not is_code_scan and not content.text.strip()
|
|
1662
1671
|
checkbox_question = None if is_code_scan else multiple_choice_question(content.text)
|
|
1663
1672
|
if ((checkbox_question is not None and not checkbox_question[1])
|
|
1664
|
-
or (content.require_answer_agreement and checkbox_question is None
|
|
1673
|
+
or (content.require_answer_agreement and checkbox_question is None
|
|
1674
|
+
and not displayed_single_choices(content.text) and not free_response_question(content.text))):
|
|
1665
1675
|
raise HTTPException(422, detail={'code': 'vision_unconfirmed',
|
|
1666
|
-
'message': '
|
|
1667
|
-
if not is_code_scan and checkbox_question is None and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1676
|
+
'message': 'The complete question and every displayed option are required for verification.'})
|
|
1677
|
+
if not is_code_scan and checkbox_question is None and not content.require_answer_agreement and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1668
1678
|
local_result = local_choice_result(content.text, content.language or CODE_DEFAULT_LANGUAGE)
|
|
1669
1679
|
if local_result is not None:
|
|
1670
1680
|
return local_result
|
|
@@ -1884,12 +1894,14 @@ async def _solve_vision(content: VisionContent):
|
|
|
1884
1894
|
elif has_mcq and not is_code_scan:
|
|
1885
1895
|
cleaned = await cross_check_visual_answers(
|
|
1886
1896
|
solution_messages, cleaned, vision_model, vision_verifier, comparison,
|
|
1887
|
-
require_agreement=content.verify_answer,
|
|
1897
|
+
require_agreement=content.verify_answer or content.require_answer_agreement,
|
|
1898
|
+
question_text=content.text,
|
|
1888
1899
|
)
|
|
1889
1900
|
return {
|
|
1890
1901
|
"results": cleaned,
|
|
1891
1902
|
"provider": f"groq-vision ({vision_model})" + (' [cross-checked]' if has_mcq and not is_code_scan else ''),
|
|
1892
1903
|
"answer_verified": has_mcq and not is_code_scan,
|
|
1904
|
+
"answer_agreement": has_mcq and not is_code_scan and content.require_answer_agreement,
|
|
1893
1905
|
"selection_set_verified": checkbox_question is not None,
|
|
1894
1906
|
"code_reviewed": code_reviewed,
|
|
1895
1907
|
"language": language,
|
package/server/vision_images.py
CHANGED
|
@@ -424,17 +424,26 @@ def rref_pivot_count(matrix):
|
|
|
424
424
|
|
|
425
425
|
|
|
426
426
|
def parse_labeled_choices(option_text):
|
|
427
|
+
"""Read sequential option labels without dropping multiline option bodies."""
|
|
427
428
|
lines = ('A.' + option_text).splitlines()
|
|
428
|
-
if not 2 <= len(lines) <= 26:
|
|
429
|
-
return {}
|
|
430
429
|
choices = {}
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
430
|
+
current = None
|
|
431
|
+
for line in lines:
|
|
432
|
+
# A label-like line must be the next uppercase label, never a
|
|
433
|
+
# duplicate, gap or lowercase option hidden in a preceding body.
|
|
434
|
+
option = re.fullmatch(r'([A-Za-z])\.[ \t]*(.*)', line)
|
|
435
|
+
if option:
|
|
436
|
+
letter, body = option.groups()
|
|
437
|
+
if (len(choices) >= 26 or letter != chr(ord('A') + len(choices))
|
|
438
|
+
or not body or body.isspace()):
|
|
439
|
+
return {}
|
|
440
|
+
choices[letter] = body
|
|
441
|
+
current = letter
|
|
442
|
+
elif current is not None:
|
|
443
|
+
choices[current] += '\n' + line
|
|
444
|
+
else:
|
|
435
445
|
return {}
|
|
436
|
-
|
|
437
|
-
return choices
|
|
446
|
+
return choices if len(choices) >= 2 else {}
|
|
438
447
|
|
|
439
448
|
|
|
440
449
|
def solve_matrix_choice(text):
|
|
@@ -704,7 +713,7 @@ def bind_displayed_choice(value, choices, *, matrix_math):
|
|
|
704
713
|
def key(text):
|
|
705
714
|
return normalize_checked_answer(text, matrix_math=matrix_math)
|
|
706
715
|
|
|
707
|
-
labeled = re.fullmatch(r'(?:Option\s+)?([A-Z])\s*[:.)]\s*(\S.*)', answer, re.I)
|
|
716
|
+
labeled = re.fullmatch(r'(?:Option\s+)?([A-Z])\s*[:.)]\s*(\S.*)', answer, re.I | re.S)
|
|
708
717
|
if labeled:
|
|
709
718
|
letter, body = labeled[1].upper(), labeled[2]
|
|
710
719
|
return letter if letter in choices and key(choices[letter]) == key(body) else None
|
|
@@ -871,6 +880,8 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
871
880
|
return keys if all(keys) else None
|
|
872
881
|
|
|
873
882
|
first = answer_key(items)
|
|
883
|
+
if require_agreement and choices and first is None:
|
|
884
|
+
raise VisionUnconfirmedError('The proposed quiz answer does not match one complete displayed option.')
|
|
874
885
|
previous = None
|
|
875
886
|
for attempt in range(2):
|
|
876
887
|
if step_count:
|
|
@@ -894,6 +905,8 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
894
905
|
current = answer_key(verified)
|
|
895
906
|
except ValueError:
|
|
896
907
|
current = None
|
|
908
|
+
if require_agreement and choices and current is not None and current != first:
|
|
909
|
+
raise VisionUnconfirmedError('The independent solves disagreed on the quiz answer. Review this question before submitting.')
|
|
897
910
|
if current is not None and (current == first or current == previous):
|
|
898
911
|
if step_count:
|
|
899
912
|
if current != first:
|
|
@@ -933,7 +946,7 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
933
946
|
else 'The independent solves could not agree on the displayed answer.')
|
|
934
947
|
|
|
935
948
|
|
|
936
|
-
async def cross_check_visual_answers(messages, results, model, complete, comparison=None, *, require_agreement=False):
|
|
949
|
+
async def cross_check_visual_answers(messages, results, model, complete, comparison=None, *, require_agreement=False, question_text=''):
|
|
937
950
|
"""Solve again from the original evidence without exposing proposed answers.
|
|
938
951
|
|
|
939
952
|
Agreement is an additional check, not a guarantee of factual correctness.
|
|
@@ -947,13 +960,19 @@ async def cross_check_visual_answers(messages, results, model, complete, compari
|
|
|
947
960
|
if comparison and len(items) != 1:
|
|
948
961
|
raise VisionUnconfirmedError('Expected one chart comparison for the supplied options.')
|
|
949
962
|
matrix_math = matrix_question(messages)
|
|
963
|
+
choices = displayed_single_choices(question_text) if len(items) == 1 and not comparison else {}
|
|
950
964
|
|
|
951
965
|
def agreement_key(entries):
|
|
952
966
|
if comparison:
|
|
953
967
|
return resolve_relative_percentage(entries[0], comparison)
|
|
968
|
+
if choices:
|
|
969
|
+
return bind_displayed_choice(entries[0].get('answer'), choices, matrix_math=matrix_math)
|
|
954
970
|
return tuple(normalize_checked_answer(entry.get('answer'), matrix_math=matrix_math) for entry in entries)
|
|
955
971
|
|
|
956
972
|
def agreed_result():
|
|
973
|
+
if choices:
|
|
974
|
+
items[0]['answer'] = f'Option {first}: {choices[first]}'
|
|
975
|
+
return json.dumps(items, ensure_ascii=False)
|
|
957
976
|
return json.dumps(items, ensure_ascii=False) if comparison else results
|
|
958
977
|
|
|
959
978
|
instruction = (
|
|
@@ -985,7 +1004,7 @@ async def cross_check_visual_answers(messages, results, model, complete, compari
|
|
|
985
1004
|
first = agreement_key(items)
|
|
986
1005
|
except ValueError:
|
|
987
1006
|
first = None
|
|
988
|
-
if not comparison and (not first or not all(first)):
|
|
1007
|
+
if not comparison and (not first or (not choices and not all(first))):
|
|
989
1008
|
raise VisionUnconfirmedError('The initial visual solve did not provide every answer.')
|
|
990
1009
|
raw = await complete(check_messages, model)
|
|
991
1010
|
try:
|
|
@@ -1010,10 +1029,16 @@ async def cross_check_visual_answers(messages, results, model, complete, compari
|
|
|
1010
1029
|
third = agreement_key(checked_items)
|
|
1011
1030
|
except ValueError as exc:
|
|
1012
1031
|
raise VisionUnconfirmedError(str(exc)) from exc
|
|
1032
|
+
if third is None:
|
|
1033
|
+
raise VisionUnconfirmedError('The final visual solve did not match a displayed option.')
|
|
1013
1034
|
if third == first:
|
|
1014
1035
|
return agreed_result()
|
|
1015
1036
|
if third != second:
|
|
1016
1037
|
raise VisionUnconfirmedError('Two visual solves could not agree on the exact answers.')
|
|
1038
|
+
if choices:
|
|
1039
|
+
items[0]['answer'] = f'Option {third}: {choices[third]}'
|
|
1040
|
+
items[0].pop('reasoning', None)
|
|
1041
|
+
return json.dumps(items, ensure_ascii=False)
|
|
1017
1042
|
if comparison:
|
|
1018
1043
|
items[0].update({key: checked_items[0][key] for key in ('answer', 'reasoning', 'comparison')})
|
|
1019
1044
|
return agreed_result()
|