mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-04 15:59:59 +08:00
fix(mastery): tolerate preference strategy, normalize evidence quotes, and report path_revision (#3173)
This commit is contained in:
@@ -2983,7 +2983,7 @@ class MasteryProfileTool(BaseTool):
|
||||
)
|
||||
|
||||
service = _new_service()
|
||||
from deeptutor.learning.storage import LearningStoreError
|
||||
from deeptutor.learning.storage import LearningConflictError, LearningStoreError
|
||||
|
||||
try:
|
||||
progress, changed = service.record_learner_profile(
|
||||
@@ -2997,7 +2997,22 @@ class MasteryProfileTool(BaseTool):
|
||||
clear_fields=clear_fields,
|
||||
clear_request=kwargs.get("clear_request") or "",
|
||||
)
|
||||
except (ValueError, LearningStoreError) as exc:
|
||||
except LearningConflictError as exc:
|
||||
return ToolResult(
|
||||
content=f"{exc}. Current path_revision is {exc.actual}.",
|
||||
success=False,
|
||||
)
|
||||
except ValueError as exc:
|
||||
message = str(exc)
|
||||
if "requires the current path revision" in message:
|
||||
try:
|
||||
current = _load_path(service, path_id)
|
||||
except (ValueError, LearningStoreError):
|
||||
current = None
|
||||
if current is not None:
|
||||
message = f"{message}. Current path_revision is {current.version}."
|
||||
return ToolResult(content=message, success=False)
|
||||
except LearningStoreError as exc:
|
||||
return ToolResult(content=str(exc), success=False)
|
||||
except KeyError:
|
||||
return ToolResult(
|
||||
|
||||
@@ -5,11 +5,28 @@ scope and provenance; it never infers understanding or awards mastery.
|
||||
"""
|
||||
|
||||
from typing import Literal
|
||||
import unicodedata
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from deeptutor.learning.models import LearnerProfile, TeachingObservation, TeachingPreference
|
||||
|
||||
_FULLWIDTH_ASCII_TABLE = str.maketrans({cp: cp - 0xFEE0 for cp in range(0xFF01, 0xFF5F)})
|
||||
|
||||
|
||||
def _normalize_evidence_text(text: str) -> str:
|
||||
normalized = unicodedata.normalize("NFC", text).translate(_FULLWIDTH_ASCII_TABLE)
|
||||
return " ".join(normalized.split())
|
||||
|
||||
|
||||
def _evidence_matches(evidence: str, learner_message: str) -> bool:
|
||||
if evidence in learner_message:
|
||||
return True
|
||||
normalized_evidence = _normalize_evidence_text(evidence)
|
||||
return bool(normalized_evidence) and normalized_evidence in _normalize_evidence_text(
|
||||
learner_message
|
||||
)
|
||||
|
||||
|
||||
class TeachingUpdate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
@@ -53,8 +70,10 @@ class TeachingUpdate(BaseModel):
|
||||
if self.kind == "preference":
|
||||
if self.basis != "learner_report":
|
||||
raise ValueError("a preference requires an explicit learner request")
|
||||
if self.knowledge_point_id or self.strategy or self.outcome != "unknown":
|
||||
if self.knowledge_point_id or self.outcome != "unknown":
|
||||
raise ValueError("concepts and strategy outcomes belong in observations")
|
||||
if self.strategy:
|
||||
self.strategy = ""
|
||||
else:
|
||||
if not self.knowledge_point_id:
|
||||
raise ValueError("an observation needs a knowledge_point_id")
|
||||
@@ -68,7 +87,7 @@ def parse_teaching_updates(raw: list[dict], learner_message: str) -> list[Teachi
|
||||
raise ValueError("teaching_updates limit is 1 to 6 operations")
|
||||
updates = [TeachingUpdate.model_validate(item) for item in raw]
|
||||
for item in updates:
|
||||
if item.evidence and item.evidence not in learner_message:
|
||||
if item.evidence and not _evidence_matches(item.evidence, learner_message):
|
||||
raise ValueError("evidence must be a literal quote from the current learner message")
|
||||
keys = [(item.kind, item.key) for item in updates]
|
||||
if len(keys) != len(set(keys)):
|
||||
|
||||
@@ -392,3 +392,91 @@ def test_teaching_updates_schema_documents_observation_only_fields():
|
||||
for field in ("knowledge_point_id", "strategy", "outcome"):
|
||||
description = items["properties"][field].get("description", "")
|
||||
assert "observation" in description, field
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_preference_clears_redundant_strategy_and_rejects_observation_fields(
|
||||
monkeypatch, system
|
||||
):
|
||||
from deeptutor.learning.teaching import TeachingUpdate
|
||||
|
||||
store, service = system
|
||||
payload = {
|
||||
"kind": "preference",
|
||||
"op": "upsert",
|
||||
"key": "worked_examples",
|
||||
"text": "Use concrete examples before formalism",
|
||||
"basis": "learner_report",
|
||||
"strategy": "Concrete worked examples first",
|
||||
"outcome": "unknown",
|
||||
"evidence": "Please use concrete examples first.",
|
||||
}
|
||||
validated = TeachingUpdate.model_validate(payload)
|
||||
assert validated.strategy == ""
|
||||
|
||||
monkeypatch.setattr("deeptutor.capabilities.mastery.tools._new_service", lambda: service)
|
||||
result = await MasteryProfileTool().execute(
|
||||
_mastery_path_id="path",
|
||||
_learner_message="Please use concrete examples first.",
|
||||
teaching_updates=[payload],
|
||||
expected_revision=store.load("path").version,
|
||||
)
|
||||
assert result.success, result.content
|
||||
saved = store.load("path").learner_profile.teaching_preferences["worked_examples"]
|
||||
assert saved.text == "Use concrete examples before formalism"
|
||||
assert saved.evidence == "Please use concrete examples first."
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
TeachingUpdate.model_validate({**payload, "knowledge_point_id": "p1"})
|
||||
with pytest.raises(ValueError):
|
||||
TeachingUpdate.model_validate({**payload, "outcome": "helped"})
|
||||
|
||||
|
||||
def test_parse_teaching_updates_normalizes_whitespace_nfc_and_fullwidth_ascii():
|
||||
from deeptutor.learning.teaching import parse_teaching_updates
|
||||
|
||||
cases = [
|
||||
("Please explain in short steps.", "Please explain\nin\u3000short steps."),
|
||||
("Use résumé examples.", "Use re\u0301sume\u0301 examples."),
|
||||
("请用例子,先别讲公式?", "请用例子,先别讲公式?"),
|
||||
]
|
||||
for evidence, learner_message in cases:
|
||||
parsed = parse_teaching_updates(
|
||||
[{**preference(), "evidence": evidence}],
|
||||
learner_message,
|
||||
)
|
||||
assert len(parsed) == 1
|
||||
|
||||
with pytest.raises(ValueError, match="quote"):
|
||||
parse_teaching_updates(
|
||||
[{**preference(), "evidence": "Completely unrelated quote"}],
|
||||
"Please explain in short steps.",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mastery_profile_revision_errors_include_current_path_revision(monkeypatch, system):
|
||||
store, service = system
|
||||
monkeypatch.setattr("deeptutor.capabilities.mastery.tools._new_service", lambda: service)
|
||||
record(store, service, [preference()])
|
||||
current_rev = store.load("path").version
|
||||
assert current_rev > 0
|
||||
|
||||
missing_rev = await MasteryProfileTool().execute(
|
||||
_mastery_path_id="path",
|
||||
_learner_message=preference()["evidence"],
|
||||
teaching_updates=[preference(key="new_pref")],
|
||||
)
|
||||
assert not missing_rev.success
|
||||
assert "requires the current path revision" in missing_rev.content
|
||||
assert f"path_revision is {current_rev}" in missing_rev.content
|
||||
|
||||
stale_rev = await MasteryProfileTool().execute(
|
||||
_mastery_path_id="path",
|
||||
_learner_message=preference()["evidence"],
|
||||
teaching_updates=[preference(key="new_pref")],
|
||||
expected_revision=0,
|
||||
)
|
||||
assert not stale_rev.success
|
||||
assert "changed" in stale_rev.content.lower()
|
||||
assert f"path_revision is {current_rev}" in stale_rev.content
|
||||
|
||||
Reference in New Issue
Block a user