mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 05:19:30 +08:00
Merge commit '083a9c9b7202f0ee58b6f1c2a1df1b6d91f8b173' into codex/validate-reviewed-integration
This commit is contained in:
@@ -210,6 +210,79 @@ async def judge_answers(config, items):
|
||||
) from exc
|
||||
|
||||
|
||||
def _answer_body(question) -> str:
|
||||
"""The correct-answer text the learner had to produce, independent of label."""
|
||||
if question.choice_map:
|
||||
body = question.choice_map.get(question.expected_answer)
|
||||
if body:
|
||||
return body
|
||||
return question.expected_answer
|
||||
|
||||
|
||||
def _same_stem(left: str, right: str) -> bool:
|
||||
"""Only layout-normalized equality is safe for automatic rejection.
|
||||
|
||||
Punctuation and case can change mathematical meaning; lexical similarity
|
||||
and a matching answer are not evidence that two exercises are identical.
|
||||
"""
|
||||
return bool(_comparable(left)) and _comparable(left) == _comparable(right)
|
||||
|
||||
|
||||
def _source_identity(question) -> str:
|
||||
sources = question.source_evidence.get("sources") or []
|
||||
return json.dumps(sources, sort_keys=True, ensure_ascii=False) if sources else ""
|
||||
|
||||
|
||||
def _prior_correct_questions(store, path_id: str) -> list:
|
||||
"""Leaves the learner already answered correctly on this path.
|
||||
|
||||
A source-verifiable item can be the only one that binds, so the tutor tends
|
||||
to fall back on it instead of writing a new question. Reporting the ones
|
||||
already proven correct lets :func:`bind_questions` refuse a restatement by
|
||||
comparing the new stem and answer key against them.
|
||||
"""
|
||||
try:
|
||||
interactions = store.list_interactions(path_id)
|
||||
except Exception:
|
||||
return []
|
||||
correct = []
|
||||
for interaction in interactions:
|
||||
result = interaction.result or {}
|
||||
receipts = result.get("results")
|
||||
if not isinstance(receipts, list):
|
||||
receipts = [{"question_id": interaction.question.question_id, **result}]
|
||||
by_id = {
|
||||
receipt.get("question_id"): receipt for receipt in receipts if isinstance(receipt, dict)
|
||||
}
|
||||
for leaf in interaction.question.questions or [interaction.question]:
|
||||
receipt = by_id.get(leaf.question_id)
|
||||
if receipt is not None and receipt.get("is_correct") is True:
|
||||
correct.append(leaf)
|
||||
return correct
|
||||
|
||||
|
||||
def _refuse_restatement(question, prior_correct: list) -> None:
|
||||
body = _comparable(_answer_body(question))
|
||||
if not body:
|
||||
return
|
||||
source = _source_identity(question)
|
||||
if not source:
|
||||
return
|
||||
for answered in prior_correct:
|
||||
if answered.knowledge_point_id != question.knowledge_point_id:
|
||||
continue
|
||||
if _source_identity(answered) != source:
|
||||
continue
|
||||
if _comparable(_answer_body(answered)) != body:
|
||||
continue
|
||||
if _same_stem(question.prompt, answered.prompt):
|
||||
raise AssessmentUnavailable(
|
||||
"This question restates one the learner already answered correctly "
|
||||
"for this objective and source; it is not fresh evidence. Write a different question, "
|
||||
"or move on to another step."
|
||||
)
|
||||
|
||||
|
||||
async def bind_question(store, progress, question, config=None):
|
||||
await bind_questions(store, progress, [question], config)
|
||||
|
||||
@@ -221,6 +294,7 @@ async def bind_questions(store, progress, questions, config=None):
|
||||
if not 1 <= len(questions) <= 4:
|
||||
raise AssessmentUnavailable("Bind one to four questions at a time.")
|
||||
items, located = [], []
|
||||
prior_correct = None
|
||||
for question in questions:
|
||||
evidence = json.loads(
|
||||
json.dumps(progress.lesson_evidence.get(question.knowledge_point_id, {}))
|
||||
@@ -231,6 +305,12 @@ async def bind_questions(store, progress, questions, config=None):
|
||||
question.source_evidence = evidence
|
||||
if not evidence:
|
||||
continue
|
||||
# A source-grounded question that restates a correct answer is not fresh
|
||||
# evidence; refuse it before spending the source check on it.
|
||||
if prior_correct is None:
|
||||
prior_correct = _prior_correct_questions(store, progress.book_id)
|
||||
if progress.current_stage != "review":
|
||||
_refuse_restatement(question, prior_correct)
|
||||
sources = [
|
||||
{
|
||||
"index": i,
|
||||
|
||||
@@ -2020,3 +2020,56 @@ async def test_an_empty_profile_call_is_refused_with_the_fields_it_wanted(path_i
|
||||
result = await MasteryProfileTool().execute(_mastery_path_id=path_id)
|
||||
assert result.success is False
|
||||
assert "time_budget" in result.content
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_quiz_refuses_a_restatement_of_a_correctly_answered_question(path_id, monkeypatch):
|
||||
"""The tutor falls back on the one source-verifiable item; that fallback
|
||||
must not re-pose a question the learner already answered correctly (issue
|
||||
#2073). The refusal reaches the tutor as a failed, explanatory tool result.
|
||||
"""
|
||||
from deeptutor.learning import lesson_evidence, semantic_assessment
|
||||
|
||||
await _build_basic(path_id)
|
||||
status = json.loads((await MasteryStatusTool().execute(_mastery_path_id=path_id)).content)
|
||||
kp_id = status["next"]["knowledge_point_id"]
|
||||
|
||||
store = LearningStore()
|
||||
progress = store.load(path_id)
|
||||
progress.lesson_evidence[kp_id] = {
|
||||
"sources": [{"ref": {}, "text": "alpha is the first letter"}]
|
||||
}
|
||||
store.save(progress)
|
||||
monkeypatch.setattr(lesson_evidence, "validate_evidence", lambda *args, **kwargs: None)
|
||||
|
||||
async def support(*args, **kwargs):
|
||||
return {
|
||||
"supported": True,
|
||||
"citations": [{"index": 0, "quote": "alpha is the first letter"}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(semantic_assessment, "_request", support)
|
||||
first = tool_payload(
|
||||
(
|
||||
await MasteryQuizTool().execute(
|
||||
_mastery_path_id=path_id,
|
||||
knowledge_point_id=kp_id,
|
||||
question="Name this.",
|
||||
expected_answer="alpha",
|
||||
)
|
||||
)
|
||||
)
|
||||
await MasteryGradeTool().execute(
|
||||
_mastery_path_id=path_id, question_id=first["question_id"], answer="alpha"
|
||||
)
|
||||
assert store.load(path_id).quiz_attempts[0].is_correct is True
|
||||
|
||||
refused = await MasteryQuizTool().execute(
|
||||
_mastery_path_id=path_id,
|
||||
knowledge_point_id=kp_id,
|
||||
question="Name this.",
|
||||
expected_answer="alpha",
|
||||
)
|
||||
assert refused.success is False
|
||||
assert "already answered correctly" in refused.content
|
||||
assert store.load(path_id).pending_question is None
|
||||
|
||||
@@ -410,6 +410,98 @@ async def test_question_support_must_quote_real_evidence(service, monkeypatch):
|
||||
await semantic.bind_question(service.store, progress, leaf())
|
||||
|
||||
|
||||
def _source_packet(*texts):
|
||||
return {"sources": [{"ref": {}, "text": text} for text in texts]}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_restated_correct_question_is_refused_without_spending_a_request(
|
||||
service, monkeypatch
|
||||
):
|
||||
"""A question already answered correctly must not be re-registered.
|
||||
|
||||
When novel questions fail source verification the tutor falls back on the
|
||||
one item that always binds and re-poses what the learner already got right.
|
||||
That is not fresh evidence, so ``bind_questions`` refuses the restatement
|
||||
before the bounded source request is even attempted.
|
||||
"""
|
||||
from deeptutor.learning import lesson_evidence
|
||||
from deeptutor.learning import semantic_assessment as semantic
|
||||
|
||||
progress = service.store.load("p")
|
||||
progress.lesson_evidence["kp1"] = _source_packet("alpha is the first letter")
|
||||
monkeypatch.setattr(lesson_evidence, "validate_evidence", lambda *args, **kwargs: None)
|
||||
prior = leaf(expected="alpha")
|
||||
prior.source_evidence = _source_packet("alpha is the first letter")
|
||||
service.store.save(progress)
|
||||
service.register_question("p", prior)
|
||||
service.grade_interaction("p", answer="alpha", question_id="q1")
|
||||
assert service.store.load("p").quiz_attempts[0].is_correct
|
||||
|
||||
calls = []
|
||||
|
||||
async def request(*args, **kwargs):
|
||||
calls.append(args)
|
||||
return {
|
||||
"supported": True,
|
||||
"citations": [{"index": 0, "quote": "alpha is the first letter"}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(semantic, "_request", request)
|
||||
restated = leaf("q2")
|
||||
restated.prompt = prior.prompt # Exact source-backed exercise, not a fuzzy match.
|
||||
with pytest.raises(semantic.AssessmentUnavailable, match="already answered correctly"):
|
||||
await semantic.bind_question(service.store, progress, restated)
|
||||
assert not calls
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_distinct_question_on_the_same_objective_is_not_refused(service, monkeypatch):
|
||||
from deeptutor.learning import lesson_evidence
|
||||
from deeptutor.learning import semantic_assessment as semantic
|
||||
|
||||
progress = service.store.load("p")
|
||||
progress.lesson_evidence["kp1"] = _source_packet("alpha and beta are letters")
|
||||
monkeypatch.setattr(lesson_evidence, "validate_evidence", lambda *args, **kwargs: None)
|
||||
service.register_question("p", leaf(expected="alpha"))
|
||||
service.grade_interaction("p", answer="alpha", question_id="q1")
|
||||
|
||||
async def request(*args, **kwargs):
|
||||
return {
|
||||
"supported": True,
|
||||
"citations": [{"index": 0, "quote": "alpha and beta are letters"}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(semantic, "_request", request)
|
||||
distinct = leaf("q2", expected="beta")
|
||||
distinct.prompt = "How many distinct letters follow the open relationship?"
|
||||
await semantic.bind_question(service.store, progress, distinct)
|
||||
assert distinct.source_evidence["assessment_contract"]["provenance"] == "adapted"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_same_answer_key_with_a_different_stem_is_not_refused(service, monkeypatch):
|
||||
from deeptutor.learning import lesson_evidence
|
||||
from deeptutor.learning import semantic_assessment as semantic
|
||||
|
||||
progress = service.store.load("p")
|
||||
progress.lesson_evidence["kp1"] = _source_packet("alpha is the first letter")
|
||||
monkeypatch.setattr(lesson_evidence, "validate_evidence", lambda *args, **kwargs: None)
|
||||
service.register_question("p", leaf(expected="alpha"))
|
||||
service.grade_interaction("p", answer="alpha", question_id="q1")
|
||||
|
||||
async def request(*args, **kwargs):
|
||||
return {
|
||||
"supported": True,
|
||||
"citations": [{"index": 0, "quote": "alpha is the first letter"}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(semantic, "_request", request)
|
||||
same_key = leaf("q2", expected="alpha")
|
||||
same_key.prompt = "How many moons does Jupiter have?"
|
||||
await semantic.bind_question(service.store, progress, same_key)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(
|
||||
"source_text, quote",
|
||||
@@ -712,3 +804,51 @@ async def test_citation_normalization_does_not_accept_changed_math_or_words(
|
||||
monkeypatch.setattr(semantic, "_request", request)
|
||||
with pytest.raises(semantic.AssessmentUnavailable, match="absent"):
|
||||
await semantic.bind_question(service.store, progress, leaf())
|
||||
|
||||
|
||||
def test_same_answer_does_not_make_different_math_a_duplicate():
|
||||
from deeptutor.learning import semantic_assessment as semantic
|
||||
|
||||
prior = leaf(expected="4")
|
||||
prior.prompt = "What is 2+2?"
|
||||
prior.source_evidence = _source_packet("Exercise sheet")
|
||||
candidate = prior.model_copy(deep=True)
|
||||
candidate.prompt = "What is 2*2?"
|
||||
semantic._refuse_restatement(candidate, [prior])
|
||||
|
||||
|
||||
def test_repeated_prompt_on_another_objective_or_source_is_allowed():
|
||||
from deeptutor.learning import semantic_assessment as semantic
|
||||
|
||||
prior = leaf(expected="4")
|
||||
prior.source_evidence = _source_packet("First exercise")
|
||||
candidate = prior.model_copy(deep=True)
|
||||
candidate.knowledge_point_id = "another-objective"
|
||||
semantic._refuse_restatement(candidate, [prior])
|
||||
candidate.knowledge_point_id = prior.knowledge_point_id
|
||||
candidate.source_evidence = _source_packet("Another exercise")
|
||||
semantic._refuse_restatement(candidate, [prior])
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_review_stage_can_repeat_an_answered_question(service, monkeypatch):
|
||||
from deeptutor.learning import lesson_evidence
|
||||
from deeptutor.learning import semantic_assessment as semantic
|
||||
|
||||
progress = service.store.load("p")
|
||||
progress.current_stage = "review"
|
||||
progress.lesson_evidence["kp1"] = _source_packet("alpha is the first letter")
|
||||
prior = leaf(expected="alpha")
|
||||
prior.source_evidence = progress.lesson_evidence["kp1"]
|
||||
service.register_question("p", prior)
|
||||
service.grade_interaction("p", answer="alpha", question_id="q1")
|
||||
monkeypatch.setattr(lesson_evidence, "validate_evidence", lambda *a, **kw: None)
|
||||
|
||||
async def support(*a, **kw):
|
||||
return {
|
||||
"supported": True,
|
||||
"citations": [{"index": 0, "quote": "alpha is the first letter"}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(semantic, "_request", support)
|
||||
await semantic.bind_question(service.store, progress, leaf("review", expected="alpha"))
|
||||
|
||||
Reference in New Issue
Block a user