mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 09:19:30 +08:00
Merge pull request #1079 from HKUDS/fix/mastery-build-schema
This commit is contained in:
@@ -18,6 +18,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
import uuid
|
||||
|
||||
@@ -78,6 +79,12 @@ MASTERY_TOOL_NAMES: tuple[str, ...] = (
|
||||
|
||||
_QUESTION_TYPES = ("choice", "short", "open")
|
||||
_ALLOWED_KP_TYPES = {t.value for t in KnowledgeType}
|
||||
_BUILD_SHAPE_ERROR = (
|
||||
"mastery_build could not read any objective. Send modules as "
|
||||
'\'modules\': [{"name": "<module>", "knowledge_points": '
|
||||
'[{"name": "<objective>", "type": "memory|procedure|concept|design"}]}] '
|
||||
"— every knowledge point needs a name of at least two characters."
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -938,7 +945,12 @@ class MasteryBuildTool(BaseTool):
|
||||
mode = "replace"
|
||||
|
||||
service = _new_service()
|
||||
new_modules, error = _parse_modules(kwargs.get("modules"), path_id, 0)
|
||||
new_modules, error = _parse_modules(
|
||||
kwargs.get("modules"),
|
||||
path_id,
|
||||
0,
|
||||
fallback_module_name=str(kwargs.get("path_name") or "").strip()[:200],
|
||||
)
|
||||
if error:
|
||||
return ToolResult(content=error, success=False)
|
||||
|
||||
@@ -1115,38 +1127,115 @@ class MasteryLeaveTool(BaseTool):
|
||||
)
|
||||
|
||||
|
||||
# Ordered by how well each key names the thing for a learner: a real name
|
||||
# first, a description only when there is nothing better, the raw id last.
|
||||
_KP_NAME_KEYS = ("name", "title", "label", "objective", "topic", "description", "id")
|
||||
_MODULE_NAME_KEYS = ("name", "title", "label", "module", "id")
|
||||
_KP_LIST_KEYS = ("knowledge_points", "objectives", "points", "items")
|
||||
|
||||
|
||||
def _humanized(value: str) -> str:
|
||||
"""Turn an identifier-shaped name into a readable one.
|
||||
|
||||
Models that answer with ``{"id": "concept_framework"}`` mean the words,
|
||||
not the key. Only reshape when the value really looks like an ASCII
|
||||
identifier — CJK names carry no separators and must survive untouched.
|
||||
"""
|
||||
if " " in value or not value.isascii():
|
||||
return value
|
||||
if "_" not in value and "-" not in value:
|
||||
return value
|
||||
return re.sub(r"[_-]+", " ", value).strip().title()
|
||||
|
||||
|
||||
def _display_name(raw: Any, keys: tuple[str, ...]) -> str:
|
||||
"""First readable name *raw* offers under *keys*, or ``""``."""
|
||||
if isinstance(raw, str):
|
||||
return _humanized(raw.strip())[:200]
|
||||
if not isinstance(raw, dict):
|
||||
return ""
|
||||
for key in keys:
|
||||
value = raw.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return _humanized(value.strip())[:200]
|
||||
return ""
|
||||
|
||||
|
||||
def _raw_knowledge_points(raw: dict[str, Any]) -> list[Any] | None:
|
||||
"""The knowledge-point list *raw* declares, or ``None`` if it declares none."""
|
||||
for key in _KP_LIST_KEYS:
|
||||
value = raw.get(key)
|
||||
if isinstance(value, list):
|
||||
return value
|
||||
return None
|
||||
|
||||
|
||||
def _normalized_module_tree(
|
||||
raw_modules: Any, fallback_module_name: str
|
||||
) -> list[tuple[str, list[Any]]]:
|
||||
"""Reduce whatever the model emitted to ``[(module name, knowledge points)]``.
|
||||
|
||||
The tool schema asks for ``[{name, knowledge_points: [{name, type}]}]``, but
|
||||
DeepTutor runs on whatever model the learner brings, and smaller ones
|
||||
routinely answer with ``objectives`` instead of ``modules``, ``title``
|
||||
instead of ``name``, bare strings instead of knowledge-point objects, or a
|
||||
flat objective list with no module layer at all (#1019). Every one of those
|
||||
used to be dropped silently, leaving an empty path and no error the learner
|
||||
could see. Read the meaning instead of rejecting the shape.
|
||||
"""
|
||||
if isinstance(raw_modules, dict):
|
||||
for key in ("modules", *_KP_LIST_KEYS):
|
||||
value = raw_modules.get(key)
|
||||
if isinstance(value, list):
|
||||
raw_modules = value
|
||||
break
|
||||
if not isinstance(raw_modules, list):
|
||||
return []
|
||||
|
||||
entries: list[tuple[str, list[Any]]] = []
|
||||
flat: list[Any] = []
|
||||
for raw in raw_modules:
|
||||
nested = _raw_knowledge_points(raw) if isinstance(raw, dict) else None
|
||||
if nested:
|
||||
entries.append((_display_name(raw, _MODULE_NAME_KEYS), nested))
|
||||
elif nested is None:
|
||||
# No knowledge-point list at all: the model flattened the tree and
|
||||
# this entry is itself an objective.
|
||||
flat.append(raw)
|
||||
if flat:
|
||||
entries.append((fallback_module_name, flat))
|
||||
return entries
|
||||
|
||||
|
||||
def _parse_modules(
|
||||
raw_modules: Any, path_id: str, offset: int
|
||||
raw_modules: Any, path_id: str, offset: int, fallback_module_name: str = ""
|
||||
) -> tuple[list[LearningModule], str | None]:
|
||||
"""Validate the model-designed module tree into engine models.
|
||||
|
||||
Ids are generated server-side (``<path>_m<i>_kp<j>``) so the model never
|
||||
controls storage keys; unknown knowledge types fall back to 'concept'.
|
||||
"""
|
||||
if not isinstance(raw_modules, list) or not raw_modules:
|
||||
return [], "mastery_build needs a non-empty 'modules' array."
|
||||
entries = _normalized_module_tree(raw_modules, fallback_module_name or "Objectives")
|
||||
if not entries:
|
||||
return [], _BUILD_SHAPE_ERROR
|
||||
modules: list[LearningModule] = []
|
||||
for i, raw in enumerate(raw_modules):
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
index = offset + i
|
||||
name = str(raw.get("name") or "").strip()[:200]
|
||||
if not name:
|
||||
continue
|
||||
for i, (raw_name, raw_kps) in enumerate(entries):
|
||||
index = offset + len(modules)
|
||||
module_id = f"{path_id}_m{index}"
|
||||
name = raw_name or fallback_module_name or f"Module {index + 1}"
|
||||
kps: list[KnowledgePoint] = []
|
||||
for j, raw_kp in enumerate(raw.get("knowledge_points") or []):
|
||||
if not isinstance(raw_kp, dict):
|
||||
continue
|
||||
kp_name = str(raw_kp.get("name") or "").strip()[:200]
|
||||
for raw_kp in raw_kps:
|
||||
kp_name = _display_name(raw_kp, _KP_NAME_KEYS)
|
||||
if len(kp_name) < 2:
|
||||
continue
|
||||
kp_type = str(raw_kp.get("type") or "concept").strip().lower()
|
||||
if kp_type not in _ALLOWED_KP_TYPES:
|
||||
kp_type = "concept"
|
||||
kp_type = "concept"
|
||||
if isinstance(raw_kp, dict):
|
||||
kp_type = str(raw_kp.get("type") or "concept").strip().lower()
|
||||
if kp_type not in _ALLOWED_KP_TYPES:
|
||||
kp_type = "concept"
|
||||
kps.append(
|
||||
KnowledgePoint(
|
||||
id=f"{module_id}_kp{j}",
|
||||
id=f"{module_id}_kp{len(kps)}",
|
||||
name=kp_name,
|
||||
type=KnowledgeType(kp_type),
|
||||
module_id=module_id,
|
||||
@@ -1156,7 +1245,7 @@ def _parse_modules(
|
||||
continue
|
||||
modules.append(LearningModule(id=module_id, name=name, order=index, knowledge_points=kps))
|
||||
if not modules:
|
||||
return [], "No valid modules: each module needs a name and at least one knowledge point."
|
||||
return [], _BUILD_SHAPE_ERROR
|
||||
return modules, None
|
||||
|
||||
|
||||
|
||||
156
deeptutor/learning/tests/test_mastery_build_shapes.py
Normal file
156
deeptutor/learning/tests/test_mastery_build_shapes.py
Normal file
@@ -0,0 +1,156 @@
|
||||
"""``mastery_build`` must read the module tree real models actually emit.
|
||||
|
||||
The tool schema asks for ``[{name, knowledge_points: [{name, type}]}]``, but
|
||||
DeepTutor runs on whatever model the learner brings. The variants below were
|
||||
observed in the wild (#1019) on gemma4, qwen3.5 and gpt-oss; every one of them
|
||||
used to be dropped silently, leaving an empty path in Learning Space with no
|
||||
error the learner could see.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deeptutor.capabilities.mastery.tools import _parse_modules
|
||||
|
||||
|
||||
def _names(modules) -> list[tuple[str, list[str]]]:
|
||||
return [(m.name, [kp.name for kp in m.knowledge_points]) for m in modules]
|
||||
|
||||
|
||||
def test_canonical_shape_is_unchanged() -> None:
|
||||
modules, error = _parse_modules(
|
||||
[{"name": "Basics", "knowledge_points": [{"name": "Number bases", "type": "memory"}]}],
|
||||
"p1",
|
||||
0,
|
||||
)
|
||||
assert error is None
|
||||
assert _names(modules) == [("Basics", ["Number bases"])]
|
||||
assert modules[0].knowledge_points[0].type.value == "memory"
|
||||
|
||||
|
||||
def test_objectives_key_with_title_instead_of_name() -> None:
|
||||
"""Variant 1: wrong top-level key, ``title`` rather than ``name``."""
|
||||
modules, error = _parse_modules(
|
||||
{
|
||||
"objectives": [
|
||||
{
|
||||
"title": "Layer basics",
|
||||
"objectives": [{"id": "l1", "title": "Layer order", "type": "concept"}],
|
||||
}
|
||||
]
|
||||
},
|
||||
"p1",
|
||||
0,
|
||||
)
|
||||
assert error is None
|
||||
assert _names(modules) == [("Layer basics", ["Layer order"])]
|
||||
|
||||
|
||||
def test_knowledge_points_as_bare_strings() -> None:
|
||||
"""Variant 2: knowledge points arrive as plain strings."""
|
||||
modules, error = _parse_modules(
|
||||
[{"name": "Frames", "knowledge_points": ["concept_framework", "Data model"]}],
|
||||
"p1",
|
||||
0,
|
||||
)
|
||||
assert error is None
|
||||
assert _names(modules) == [("Frames", ["Concept Framework", "Data model"])]
|
||||
|
||||
|
||||
def test_knowledge_points_carrying_only_an_id() -> None:
|
||||
"""Variant 3: knowledge-point dicts with nothing but an id."""
|
||||
modules, error = _parse_modules(
|
||||
[{"name": "Selection", "knowledge_points": [{"id": "quick-mask"}]}],
|
||||
"p1",
|
||||
0,
|
||||
)
|
||||
assert error is None
|
||||
assert _names(modules) == [("Selection", ["Quick Mask"])]
|
||||
|
||||
|
||||
def test_flat_objective_list_without_a_module_layer() -> None:
|
||||
"""Variant 4: no module layer at all — one implicit module holds them."""
|
||||
modules, error = _parse_modules(
|
||||
[
|
||||
{"id": "kp1", "title": "Bit shifting", "type": "procedure"},
|
||||
{"id": "kp2", "title": "Two's complement", "type": "concept"},
|
||||
],
|
||||
"p1",
|
||||
0,
|
||||
fallback_module_name="Computer architecture",
|
||||
)
|
||||
assert error is None
|
||||
assert _names(modules) == [("Computer architecture", ["Bit shifting", "Two's complement"])]
|
||||
|
||||
|
||||
def test_cjk_names_are_never_reshaped() -> None:
|
||||
"""Humanising is for ASCII identifiers only; CJK names pass through."""
|
||||
modules, error = _parse_modules(
|
||||
[{"name": "数制转换", "knowledge_points": [{"name": "二进制转十六进制"}]}],
|
||||
"p1",
|
||||
0,
|
||||
)
|
||||
assert error is None
|
||||
assert _names(modules) == [("数制转换", ["二进制转十六进制"])]
|
||||
|
||||
|
||||
def test_ids_are_still_server_generated_and_sequential() -> None:
|
||||
modules, _ = _parse_modules(
|
||||
[
|
||||
{"name": "A", "knowledge_points": ["one", "two"]},
|
||||
{"name": "B", "knowledge_points": ["three"]},
|
||||
],
|
||||
"path",
|
||||
0,
|
||||
)
|
||||
assert [m.id for m in modules] == ["path_m0", "path_m1"]
|
||||
assert [kp.id for kp in modules[0].knowledge_points] == ["path_m0_kp0", "path_m0_kp1"]
|
||||
assert [kp.id for kp in modules[1].knowledge_points] == ["path_m1_kp0"]
|
||||
|
||||
|
||||
def test_unreadable_input_explains_the_expected_shape() -> None:
|
||||
"""The failure must name the schema, not just say 'no valid modules'."""
|
||||
modules, error = _parse_modules([], "p1", 0)
|
||||
assert modules == []
|
||||
assert error is not None
|
||||
assert "knowledge_points" in error and "memory|procedure|concept|design" in error
|
||||
|
||||
|
||||
def test_modules_without_any_readable_objective_are_rejected() -> None:
|
||||
modules, error = _parse_modules(
|
||||
[{"name": "Empty", "knowledge_points": [{"type": "memory"}]}], "p1", 0
|
||||
)
|
||||
assert modules == []
|
||||
assert error is not None
|
||||
|
||||
|
||||
def test_flat_objectives_named_only_by_description() -> None:
|
||||
"""Variant 4 exactly as reported: description + id + type, no name key."""
|
||||
modules, error = _parse_modules(
|
||||
[
|
||||
{"id": "kp1", "description": "Convert between number bases", "type": "procedure"},
|
||||
{"id": "kp2", "description": "Read a truth table", "type": "concept"},
|
||||
],
|
||||
"p1",
|
||||
0,
|
||||
fallback_module_name="Digital logic",
|
||||
)
|
||||
assert error is None
|
||||
assert _names(modules) == [
|
||||
("Digital logic", ["Convert between number bases", "Read a truth table"])
|
||||
]
|
||||
|
||||
|
||||
def test_a_real_name_always_beats_a_description_or_id() -> None:
|
||||
modules, _ = _parse_modules(
|
||||
[
|
||||
{
|
||||
"name": "Bases",
|
||||
"knowledge_points": [
|
||||
{"name": "Hex", "description": "a much longer explanation", "id": "kp_9"}
|
||||
],
|
||||
}
|
||||
],
|
||||
"p1",
|
||||
0,
|
||||
)
|
||||
assert _names(modules) == [("Bases", ["Hex"])]
|
||||
Reference in New Issue
Block a user