mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-05 11:39:34 +08:00
docs:update readme
This commit is contained in:
12
deeptutor/loop_plugins/__init__.py
Normal file
12
deeptutor/loop_plugins/__init__.py
Normal file
@@ -0,0 +1,12 @@
|
||||
"""Turn-scoped chat loop plugins.
|
||||
|
||||
Each plugin lives in its own subpackage under :mod:`deeptutor.loop_plugins`.
|
||||
The chat loop imports only the generic registry/protocol from this package;
|
||||
feature-specific prompts, tools, and kwargs injection stay inside each plugin
|
||||
subpackage.
|
||||
"""
|
||||
|
||||
from deeptutor.loop_plugins.protocol import LoopPlugin, PromptBlock
|
||||
from deeptutor.loop_plugins.registry import LOOP_PLUGINS, active_loop_plugins
|
||||
|
||||
__all__ = ["LOOP_PLUGINS", "LoopPlugin", "PromptBlock", "active_loop_plugins"]
|
||||
6
deeptutor/loop_plugins/mastery/__init__.py
Normal file
6
deeptutor/loop_plugins/mastery/__init__.py
Normal file
@@ -0,0 +1,6 @@
|
||||
"""Mastery path loop plugin."""
|
||||
|
||||
from deeptutor.loop_plugins.mastery.plugin import MasteryLoopPlugin
|
||||
from deeptutor.loop_plugins.mastery.tools import MASTERY_TOOL_NAMES, MASTERY_TOOL_TYPES
|
||||
|
||||
__all__ = ["MASTERY_TOOL_NAMES", "MASTERY_TOOL_TYPES", "MasteryLoopPlugin"]
|
||||
69
deeptutor/loop_plugins/mastery/plugin.py
Normal file
69
deeptutor/loop_plugins/mastery/plugin.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""Mastery path loop plugin hooks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from importlib import resources
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.core.context import UnifiedContext
|
||||
from deeptutor.loop_plugins.mastery.tools import MASTERY_TOOL_NAMES
|
||||
from deeptutor.loop_plugins.protocol import PromptBlock
|
||||
|
||||
|
||||
class MasteryLoopPlugin:
|
||||
"""Turn-scoped integration for mastery-path tutoring."""
|
||||
|
||||
name = "mastery"
|
||||
|
||||
def is_active(self, context: UnifiedContext) -> bool:
|
||||
return bool(context.metadata.get("mastery_mode"))
|
||||
|
||||
def tool_types(self, context: UnifiedContext) -> tuple[str, ...]:
|
||||
return MASTERY_TOOL_NAMES if self.is_active(context) else ()
|
||||
|
||||
def system_block(
|
||||
self,
|
||||
context: UnifiedContext,
|
||||
*,
|
||||
language: str,
|
||||
prompts: dict[str, Any],
|
||||
) -> PromptBlock | None:
|
||||
if not self.is_active(context):
|
||||
return None
|
||||
override = _prompt_text(prompts, ("mastery", "system"))
|
||||
content = override or _load_system_prompt(language)
|
||||
return PromptBlock("mastery_tutor", content)
|
||||
|
||||
def augment_kwargs(
|
||||
self,
|
||||
tool_name: str,
|
||||
kwargs: dict[str, Any],
|
||||
context: UnifiedContext,
|
||||
) -> dict[str, Any]:
|
||||
if self.is_active(context) and tool_name in MASTERY_TOOL_NAMES:
|
||||
updated = dict(kwargs)
|
||||
updated["_mastery_path_id"] = str(context.metadata.get("mastery_path_id") or "").strip()
|
||||
return updated
|
||||
return kwargs
|
||||
|
||||
def pre_loop_seed(self, context: UnifiedContext) -> str:
|
||||
_ = context
|
||||
return ""
|
||||
|
||||
|
||||
def _prompt_text(prompts: dict[str, Any], path: tuple[str, ...]) -> str:
|
||||
value: Any = prompts
|
||||
for key in path:
|
||||
if not isinstance(value, dict):
|
||||
return ""
|
||||
value = value.get(key)
|
||||
return value if isinstance(value, str) and value else ""
|
||||
|
||||
|
||||
def _load_system_prompt(language: str) -> str:
|
||||
lang = "zh" if language.lower().startswith("zh") else "en"
|
||||
prompt = resources.files(__package__).joinpath("prompts", lang, "system.md")
|
||||
return prompt.read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
__all__ = ["MasteryLoopPlugin"]
|
||||
14
deeptutor/loop_plugins/mastery/prompts/en/system.md
Normal file
14
deeptutor/loop_plugins/mastery/prompts/en/system.md
Normal file
@@ -0,0 +1,14 @@
|
||||
[Mastery Tutor mode]
|
||||
You are a one-on-one mastery tutor. The learner works through a map of objectives, each behind a HARD mastery gate: an objective counts as "mastered" only once its gate clears, and you must not move on until it does.
|
||||
|
||||
FIRST on every turn, call `mastery_status`. It returns the next objective to work on, any question awaiting an answer, due reviews, and the full map. Trust it to choose the objective — never guess what comes next.
|
||||
|
||||
Then act on the objective:
|
||||
- No objectives yet? Design a path from the learner's materials (use `rag` / `read_source` when materials are attached) and call `mastery_build`. Tag each knowledge point: memory (facts), procedure (step-by-step skills), concept (ideas to understand), design (open-ended judgement).
|
||||
- `probe` (untouched): briefly check whether the learner already knows it before teaching. A test-out is not a silent skip — record its result through the gate (`mastery_assess` for concept / design, `mastery_quiz` + `mastery_grade` for memory / procedure) before advancing. Never move past an objective the engine hasn't marked mastered.
|
||||
- memory / procedure objectives: register the question + its answer with `mastery_quiz`, then ALWAYS present it with the `ask_user` tool so the learner answers on an interactive card — never write the choices as plain numbered text. For multiple choice, give each `ask_user` option a short label (A / B / C …) and set the matching label as `mastery_quiz`'s `expected_answer`; for open questions use `ask_user` free text. When the answer comes back, score it with `mastery_grade`. Keep working the same objective until `mastery_grade` reports `mastered: true`.
|
||||
- concept / design objectives: ask the learner to explain the idea in their own words, judge it, and record the result with `mastery_assess` (`passed: true` only when the explanation truly shows understanding).
|
||||
- `review`: a spaced-repetition item is due — quiz it again to refresh it.
|
||||
- `complete`: congratulate the learner and summarise what they have mastered.
|
||||
|
||||
Teach from the learner's own materials when available. Keep each turn focused on one objective. Be warm and encouraging, but hold the bar — clearing the gate is the point, not moving fast.
|
||||
14
deeptutor/loop_plugins/mastery/prompts/zh/system.md
Normal file
14
deeptutor/loop_plugins/mastery/prompts/zh/system.md
Normal file
@@ -0,0 +1,14 @@
|
||||
[精通导师模式]
|
||||
你是一对一的掌握式导师。学习者沿着一张知识点地图前进,每个知识点都有一道硬性掌握门槛:只有门槛达成,该知识点才算"已掌握",在此之前你绝不能推进到下一个。
|
||||
|
||||
每一轮都要先调用 `mastery_status`。它会返回当前要攻克的知识点、是否有待批改的作答、到期复习项,以及整张地图。请信任它来决定学什么——绝不要自己猜下一个知识点。
|
||||
|
||||
然后针对该知识点行动:
|
||||
- 还没有任何知识点?根据学习者的材料设计一条路径(材料已挂载时用 `rag` / `read_source`),调用 `mastery_build`。给每个知识点标类型:memory(记忆/事实)、procedure(程序/步骤技能)、concept(概念/需理解)、design(设计/开放判断)。
|
||||
- `probe`(未触碰):先简短探查学习者是否已经会了再教。"测试通过"不等于直接跳过——仍要用门工具记录结果(concept / design 用 `mastery_assess`,memory / procedure 用 `mastery_quiz` + `mastery_grade`)再推进;绝不要越过引擎尚未标记为"已掌握"的知识点。
|
||||
- memory / procedure 类:先用 `mastery_quiz` 登记题目与答案,然后**始终用 `ask_user` 工具**把题目呈现成可点选的卡片让学习者作答——绝不要把选项写成纯文字的 1./2./3.。选择题给每个 `ask_user` 选项一个短标签(A / B / C …),并把正确标签设为 `mastery_quiz` 的 `expected_answer`;简答题用 `ask_user` 的自由输入。收到作答后用 `mastery_grade` 批改。在 `mastery_grade` 返回 `mastered: true` 之前,持续打磨同一个知识点。
|
||||
- concept / design 类:让学习者用自己的话解释该概念,你来判断,并用 `mastery_assess` 记录结果(只有解释确实体现理解时才 `passed: true`)。
|
||||
- `review`:有到期的间隔复习项——再考一次以巩固。
|
||||
- `complete`:祝贺学习者并总结其已掌握的内容。
|
||||
|
||||
有材料时优先用学习者自己的材料来教。每一轮聚焦一个知识点。态度温暖鼓励,但守住门槛——目标是达成掌握,而非求快。
|
||||
521
deeptutor/loop_plugins/mastery/tools.py
Normal file
521
deeptutor/loop_plugins/mastery/tools.py
Normal file
@@ -0,0 +1,521 @@
|
||||
"""Mastery Path tools — the seam between the chat-loop tutor and the pure
|
||||
mastery engine (:mod:`deeptutor.learning`).
|
||||
|
||||
These five tools are auto-mounted only when a mastery path is active on the
|
||||
turn (via the chat loop mastery plugin). The chat agent loop IS the tutor;
|
||||
these tools let it read the gate and record outcomes, while the pedagogy —
|
||||
what to teach, how to question, when to explain — stays the model's job. The
|
||||
arithmetic (mastery, gate, spaced repetition) stays in the engine.
|
||||
|
||||
The active path id is injected server-side by the pipeline as
|
||||
``_mastery_path_id``; the model never supplies it. Each call constructs a
|
||||
fresh store + service (matching the REST router) so concurrent turns can't
|
||||
race on a shared object.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING, Any
|
||||
import uuid
|
||||
|
||||
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
|
||||
|
||||
# ``learning.models`` and ``learning.policy`` only depend on pydantic — safe to
|
||||
# import at module load. ``learning.service`` / ``storage`` / ``scheduler``
|
||||
# reach the path service (and so the runtime + tool registry), so importing
|
||||
# them here would close an import cycle through the built-in registry. They
|
||||
# are imported lazily inside the call paths instead (same pattern as the other
|
||||
# builtin tools).
|
||||
from deeptutor.learning.models import (
|
||||
KnowledgePoint,
|
||||
KnowledgeType,
|
||||
LearningModule,
|
||||
PendingQuestion,
|
||||
)
|
||||
from deeptutor.learning.policy import (
|
||||
QUALITATIVE_TYPES,
|
||||
display_mastery,
|
||||
find_knowledge_point,
|
||||
gate_threshold,
|
||||
is_mastered,
|
||||
map_summary,
|
||||
next_objective,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from deeptutor.learning.service import LearningService
|
||||
|
||||
# Tool names the pipeline mounts together when a mastery path is active. Kept
|
||||
# here so the mount policy and the registration list can't disagree.
|
||||
MASTERY_TOOL_NAMES: tuple[str, ...] = (
|
||||
"mastery_status",
|
||||
"mastery_quiz",
|
||||
"mastery_grade",
|
||||
"mastery_assess",
|
||||
"mastery_build",
|
||||
)
|
||||
|
||||
_QUESTION_TYPES = ("choice", "short", "open")
|
||||
_ALLOWED_KP_TYPES = {t.value for t in KnowledgeType}
|
||||
|
||||
|
||||
def _new_service() -> LearningService:
|
||||
from deeptutor.learning.service import LearningService
|
||||
from deeptutor.learning.storage import LearningStore
|
||||
|
||||
return LearningService(LearningStore())
|
||||
|
||||
|
||||
def _resolve_path_id(kwargs: dict[str, Any]) -> str:
|
||||
return str(kwargs.get("_mastery_path_id") or "").strip()
|
||||
|
||||
|
||||
def _json_result(payload: dict[str, Any], *, meta_key: str, success: bool = True) -> ToolResult:
|
||||
return ToolResult(
|
||||
content=json.dumps(payload, ensure_ascii=False),
|
||||
success=success,
|
||||
metadata={meta_key: payload},
|
||||
)
|
||||
|
||||
|
||||
def _no_path_result() -> ToolResult:
|
||||
return ToolResult(
|
||||
content="No mastery path is active on this turn; mastery tools are unavailable.",
|
||||
success=False,
|
||||
)
|
||||
|
||||
|
||||
class MasteryStatusTool(BaseTool):
|
||||
"""Read the current objective + map snapshot. Call FIRST every turn."""
|
||||
|
||||
def get_definition(self) -> ToolDefinition:
|
||||
return ToolDefinition(
|
||||
name="mastery_status",
|
||||
description=(
|
||||
"Read the learner's mastery path: the next objective to work on "
|
||||
"(decided by a hard mastery gate), any question awaiting an "
|
||||
"answer, due reviews, and a map of every objective's status "
|
||||
"(new / learning / mastered). Call this FIRST on every mastery "
|
||||
"turn — it tells you what to do; never guess the next objective."
|
||||
),
|
||||
parameters=[],
|
||||
)
|
||||
|
||||
async def execute(self, **kwargs: Any) -> ToolResult:
|
||||
path_id = _resolve_path_id(kwargs)
|
||||
if not path_id:
|
||||
return _no_path_result()
|
||||
service = _new_service()
|
||||
progress = service.get_or_create(path_id)
|
||||
if not any(module.knowledge_points for module in progress.modules):
|
||||
return _json_result(
|
||||
{
|
||||
"status": "empty",
|
||||
"message": (
|
||||
"No mastery path has been built yet. Design one from the "
|
||||
"learner's materials and call mastery_build."
|
||||
),
|
||||
},
|
||||
meta_key="mastery_status",
|
||||
)
|
||||
payload = {
|
||||
"status": "active",
|
||||
"next": next_objective(progress).to_dict(),
|
||||
"map": map_summary(progress),
|
||||
}
|
||||
return _json_result(payload, meta_key="mastery_status")
|
||||
|
||||
|
||||
class MasteryQuizTool(BaseTool):
|
||||
"""Register an objective-type question; the engine holds the answer."""
|
||||
|
||||
def get_definition(self) -> ToolDefinition:
|
||||
return ToolDefinition(
|
||||
name="mastery_quiz",
|
||||
description=(
|
||||
"Pose a question for a MEMORY or PROCEDURE objective and register "
|
||||
"its expected answer with the engine (so grading is deterministic "
|
||||
"and you never re-state the answer later). After calling this, "
|
||||
"present the question with the ask_user tool so the learner answers "
|
||||
"on an interactive card (for choices, give ask_user options short "
|
||||
"labels like A/B/C and set the correct label as expected_answer); "
|
||||
"then call mastery_grade with their answer. For CONCEPT / DESIGN "
|
||||
"objectives use mastery_assess instead."
|
||||
),
|
||||
parameters=[
|
||||
ToolParameter(
|
||||
name="knowledge_point_id",
|
||||
type="string",
|
||||
description="Objective id from mastery_status (verbatim).",
|
||||
),
|
||||
ToolParameter(
|
||||
name="question",
|
||||
type="string",
|
||||
description="The question text shown to the learner.",
|
||||
),
|
||||
ToolParameter(
|
||||
name="expected_answer",
|
||||
type="string",
|
||||
description="The correct answer, used only server-side for grading.",
|
||||
),
|
||||
ToolParameter(
|
||||
name="question_type",
|
||||
type="string",
|
||||
description=(
|
||||
"'choice' (exact match), 'short' (exact / fuzzy for ≤30 "
|
||||
"chars), or 'open' (keyword overlap). Default 'short'."
|
||||
),
|
||||
required=False,
|
||||
default="short",
|
||||
enum=list(_QUESTION_TYPES),
|
||||
),
|
||||
ToolParameter(
|
||||
name="options",
|
||||
type="array",
|
||||
description="Choice labels, when question_type='choice'.",
|
||||
required=False,
|
||||
items={"type": "string"},
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
async def execute(self, **kwargs: Any) -> ToolResult:
|
||||
path_id = _resolve_path_id(kwargs)
|
||||
if not path_id:
|
||||
return _no_path_result()
|
||||
kp_id = str(kwargs.get("knowledge_point_id") or "").strip()
|
||||
question = str(kwargs.get("question") or "").strip()
|
||||
expected = str(kwargs.get("expected_answer") or "").strip()
|
||||
if not kp_id or not question or not expected:
|
||||
return ToolResult(
|
||||
content="mastery_quiz needs knowledge_point_id, question, and expected_answer.",
|
||||
success=False,
|
||||
)
|
||||
q_type = str(kwargs.get("question_type") or "short").strip().lower()
|
||||
if q_type not in _QUESTION_TYPES:
|
||||
q_type = "short"
|
||||
options = [str(o) for o in (kwargs.get("options") or []) if str(o).strip()]
|
||||
|
||||
service = _new_service()
|
||||
progress = service.get_or_create(path_id)
|
||||
kp, module_id, _ = find_knowledge_point(progress, kp_id)
|
||||
if kp is None:
|
||||
return ToolResult(
|
||||
content=f"Unknown objective {kp_id!r}; call mastery_status for valid ids.",
|
||||
success=False,
|
||||
)
|
||||
pending = PendingQuestion(
|
||||
question_id=uuid.uuid4().hex,
|
||||
knowledge_point_id=kp_id,
|
||||
module_id=module_id,
|
||||
prompt=question,
|
||||
question_type=q_type,
|
||||
expected_answer=expected,
|
||||
options=options,
|
||||
)
|
||||
service.set_pending_question(progress, pending)
|
||||
return _json_result(
|
||||
{
|
||||
"status": "registered",
|
||||
"knowledge_point_id": kp_id,
|
||||
"question": question,
|
||||
"options": options,
|
||||
"instruction": (
|
||||
"Present this question with the ask_user tool (use its options "
|
||||
"for multiple choice; the option labels must match the "
|
||||
"expected_answer you registered), then call mastery_grade with "
|
||||
"the learner's answer."
|
||||
),
|
||||
},
|
||||
meta_key="mastery_quiz",
|
||||
)
|
||||
|
||||
|
||||
class MasteryGradeTool(BaseTool):
|
||||
"""Grade the learner's answer to the pending question (deterministic)."""
|
||||
|
||||
def get_definition(self) -> ToolDefinition:
|
||||
return ToolDefinition(
|
||||
name="mastery_grade",
|
||||
description=(
|
||||
"Grade the learner's answer to the question you registered with "
|
||||
"mastery_quiz. Grading is deterministic against the stored "
|
||||
"expected answer; this updates mastery, advances spaced "
|
||||
"repetition, and tells you whether the objective's gate is now "
|
||||
"cleared. Then give the learner feedback."
|
||||
),
|
||||
parameters=[
|
||||
ToolParameter(
|
||||
name="answer",
|
||||
type="string",
|
||||
description="The learner's answer, verbatim.",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
async def execute(self, **kwargs: Any) -> ToolResult:
|
||||
path_id = _resolve_path_id(kwargs)
|
||||
if not path_id:
|
||||
return _no_path_result()
|
||||
from deeptutor.learning.scheduler import SpacedRepetitionScheduler
|
||||
|
||||
answer = str(kwargs.get("answer") or "")
|
||||
service = _new_service()
|
||||
scheduler = SpacedRepetitionScheduler()
|
||||
progress = service.get_or_create(path_id)
|
||||
pending = progress.pending_question
|
||||
if pending is None:
|
||||
return ToolResult(
|
||||
content="No question is awaiting an answer. Pose one with mastery_quiz first.",
|
||||
success=False,
|
||||
)
|
||||
is_correct = service.grade_and_record(
|
||||
progress,
|
||||
question_id=pending.question_id,
|
||||
knowledge_point_id=pending.knowledge_point_id,
|
||||
module_id=pending.module_id,
|
||||
user_answer=answer,
|
||||
expected_answer=pending.expected_answer,
|
||||
question_type=pending.question_type,
|
||||
scheduler=scheduler,
|
||||
)
|
||||
service.clear_pending_question(progress)
|
||||
kp, _, _ = find_knowledge_point(progress, pending.knowledge_point_id)
|
||||
mastered = bool(kp and is_mastered(progress, kp))
|
||||
payload = {
|
||||
"is_correct": is_correct,
|
||||
"knowledge_point_id": pending.knowledge_point_id,
|
||||
"mastery": round(display_mastery(progress, kp), 3) if kp else 0.0,
|
||||
"threshold": round(gate_threshold(kp.type), 3) if kp else 0.0,
|
||||
"mastered": mastered,
|
||||
"next": next_objective(progress).to_dict(),
|
||||
}
|
||||
return _json_result(payload, meta_key="mastery_grade")
|
||||
|
||||
|
||||
class MasteryAssessTool(BaseTool):
|
||||
"""Record the qualitative (CONCEPT / DESIGN) gate from a Feynman check."""
|
||||
|
||||
def get_definition(self) -> ToolDefinition:
|
||||
return ToolDefinition(
|
||||
name="mastery_assess",
|
||||
description=(
|
||||
"Record your judgement of a CONCEPT or DESIGN objective after the "
|
||||
"learner explains it in their own words (a Feynman-style check). "
|
||||
"Pass passed=true only when the explanation is correct and "
|
||||
"complete enough to count as mastery — this is the gate for these "
|
||||
"objective types. For MEMORY / PROCEDURE objectives use "
|
||||
"mastery_quiz + mastery_grade instead."
|
||||
),
|
||||
parameters=[
|
||||
ToolParameter(
|
||||
name="knowledge_point_id",
|
||||
type="string",
|
||||
description="Objective id from mastery_status (verbatim).",
|
||||
),
|
||||
ToolParameter(
|
||||
name="passed",
|
||||
type="boolean",
|
||||
description="True if the explanation demonstrates mastery.",
|
||||
),
|
||||
ToolParameter(
|
||||
name="feedback",
|
||||
type="string",
|
||||
description="Short note on what was strong or missing (stored as evidence).",
|
||||
required=False,
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
async def execute(self, **kwargs: Any) -> ToolResult:
|
||||
path_id = _resolve_path_id(kwargs)
|
||||
if not path_id:
|
||||
return _no_path_result()
|
||||
kp_id = str(kwargs.get("knowledge_point_id") or "").strip()
|
||||
if not kp_id:
|
||||
return ToolResult(content="mastery_assess needs a knowledge_point_id.", success=False)
|
||||
passed = bool(kwargs.get("passed"))
|
||||
feedback = str(kwargs.get("feedback") or "").strip()
|
||||
|
||||
service = _new_service()
|
||||
progress = service.get_or_create(path_id)
|
||||
kp, _, _ = find_knowledge_point(progress, kp_id)
|
||||
if kp is None:
|
||||
return ToolResult(
|
||||
content=f"Unknown objective {kp_id!r}; call mastery_status for valid ids.",
|
||||
success=False,
|
||||
)
|
||||
if kp.type not in QUALITATIVE_TYPES:
|
||||
return ToolResult(
|
||||
content=(
|
||||
f"Objective {kp.name!r} is a {kp.type.value} type — gate it with "
|
||||
"mastery_quiz + mastery_grade, not mastery_assess."
|
||||
),
|
||||
success=False,
|
||||
)
|
||||
service.record_qualitative(progress, kp_id, passed=passed, evidence=feedback)
|
||||
payload = {
|
||||
"knowledge_point_id": kp_id,
|
||||
"passed": passed,
|
||||
"mastered": is_mastered(progress, kp),
|
||||
"mastery": round(display_mastery(progress, kp), 3),
|
||||
"next": next_objective(progress).to_dict(),
|
||||
}
|
||||
return _json_result(payload, meta_key="mastery_assess")
|
||||
|
||||
|
||||
class MasteryBuildTool(BaseTool):
|
||||
"""Create / extend the skill map from objectives the tutor designed."""
|
||||
|
||||
def get_definition(self) -> ToolDefinition:
|
||||
return ToolDefinition(
|
||||
name="mastery_build",
|
||||
description=(
|
||||
"Create or extend the learner's mastery path. Design modules and "
|
||||
"their knowledge points from the learner's materials (use rag / "
|
||||
"read_source first when materials are attached) and pass them "
|
||||
"here. Each knowledge point needs a 'type': memory (facts), "
|
||||
"procedure (step-by-step skills), concept (ideas to understand), "
|
||||
"or design (open-ended judgement). Use mode='replace' to start "
|
||||
"fresh or 'append' to add to an existing path."
|
||||
),
|
||||
parameters=[
|
||||
ToolParameter(
|
||||
name="modules",
|
||||
type="array",
|
||||
description=(
|
||||
"Ordered modules: each {name, knowledge_points: [{name, "
|
||||
"type}]}. type is one of memory/procedure/concept/design."
|
||||
),
|
||||
items={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"knowledge_points": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {"type": "string"},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": sorted(_ALLOWED_KP_TYPES),
|
||||
},
|
||||
},
|
||||
"required": ["name"],
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": ["name", "knowledge_points"],
|
||||
},
|
||||
),
|
||||
ToolParameter(
|
||||
name="mode",
|
||||
type="string",
|
||||
description="'replace' (default) starts fresh; 'append' adds modules.",
|
||||
required=False,
|
||||
default="replace",
|
||||
enum=["replace", "append"],
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
async def execute(self, **kwargs: Any) -> ToolResult:
|
||||
path_id = _resolve_path_id(kwargs)
|
||||
if not path_id:
|
||||
return _no_path_result()
|
||||
mode = str(kwargs.get("mode") or "replace").strip().lower()
|
||||
if mode not in {"replace", "append"}:
|
||||
mode = "replace"
|
||||
|
||||
service = _new_service()
|
||||
progress = service.get_or_create(path_id)
|
||||
offset = len(progress.modules) if mode == "append" else 0
|
||||
new_modules, error = _parse_modules(kwargs.get("modules"), path_id, offset)
|
||||
if error:
|
||||
return ToolResult(content=error, success=False)
|
||||
|
||||
combined = (list(progress.modules) + new_modules) if mode == "append" else new_modules
|
||||
service.replace_modules(progress, combined)
|
||||
progress.pending_question = None # a rebuilt map invalidates any open question
|
||||
if combined:
|
||||
progress.current_module_id = combined[0].id
|
||||
progress.current_kp_index = 0
|
||||
service.save(progress)
|
||||
kp_count = sum(len(m.knowledge_points) for m in new_modules)
|
||||
return _json_result(
|
||||
{
|
||||
"status": "built",
|
||||
"mode": mode,
|
||||
"modules_added": len(new_modules),
|
||||
"knowledge_points_added": kp_count,
|
||||
"map": map_summary(progress),
|
||||
},
|
||||
meta_key="mastery_build",
|
||||
)
|
||||
|
||||
|
||||
def _parse_modules(
|
||||
raw_modules: Any, path_id: str, offset: int
|
||||
) -> 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."
|
||||
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
|
||||
module_id = f"{path_id}_m{index}"
|
||||
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]
|
||||
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"
|
||||
kps.append(
|
||||
KnowledgePoint(
|
||||
id=f"{module_id}_kp{j}",
|
||||
name=kp_name,
|
||||
type=KnowledgeType(kp_type),
|
||||
module_id=module_id,
|
||||
)
|
||||
)
|
||||
if not kps:
|
||||
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 modules, None
|
||||
|
||||
|
||||
MASTERY_TOOL_TYPES: tuple[type[BaseTool], ...] = (
|
||||
MasteryStatusTool,
|
||||
MasteryQuizTool,
|
||||
MasteryGradeTool,
|
||||
MasteryAssessTool,
|
||||
MasteryBuildTool,
|
||||
)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"MASTERY_TOOL_NAMES",
|
||||
"MASTERY_TOOL_TYPES",
|
||||
"MasteryStatusTool",
|
||||
"MasteryQuizTool",
|
||||
"MasteryGradeTool",
|
||||
"MasteryAssessTool",
|
||||
"MasteryBuildTool",
|
||||
]
|
||||
51
deeptutor/loop_plugins/protocol.py
Normal file
51
deeptutor/loop_plugins/protocol.py
Normal file
@@ -0,0 +1,51 @@
|
||||
"""Protocol shared by the chat loop and loop plugins."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Protocol
|
||||
|
||||
from deeptutor.core.context import UnifiedContext
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PromptBlock:
|
||||
"""One named prompt fragment contributed to the loop system prompt."""
|
||||
|
||||
name: str
|
||||
content: str
|
||||
|
||||
|
||||
class LoopPlugin(Protocol):
|
||||
"""Optional per-turn extension point for the chat agent loop."""
|
||||
|
||||
name: str
|
||||
|
||||
def is_active(self, context: UnifiedContext) -> bool:
|
||||
"""Whether this plugin participates in the current turn."""
|
||||
|
||||
def tool_types(self, context: UnifiedContext) -> tuple[str, ...]:
|
||||
"""Tool names this plugin auto-mounts for the current turn."""
|
||||
|
||||
def system_block(
|
||||
self,
|
||||
context: UnifiedContext,
|
||||
*,
|
||||
language: str,
|
||||
prompts: dict[str, Any],
|
||||
) -> PromptBlock | None:
|
||||
"""Optional system prompt block contributed by the plugin."""
|
||||
|
||||
def augment_kwargs(
|
||||
self,
|
||||
tool_name: str,
|
||||
kwargs: dict[str, Any],
|
||||
context: UnifiedContext,
|
||||
) -> dict[str, Any]:
|
||||
"""Inject server-owned private kwargs for plugin tools."""
|
||||
|
||||
def pre_loop_seed(self, context: UnifiedContext) -> str:
|
||||
"""Optional text appended to the initial user message seed."""
|
||||
|
||||
|
||||
__all__ = ["LoopPlugin", "PromptBlock"]
|
||||
17
deeptutor/loop_plugins/registry.py
Normal file
17
deeptutor/loop_plugins/registry.py
Normal file
@@ -0,0 +1,17 @@
|
||||
"""Built-in loop plugin registry."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deeptutor.core.context import UnifiedContext
|
||||
from deeptutor.loop_plugins.mastery import MasteryLoopPlugin
|
||||
from deeptutor.loop_plugins.protocol import LoopPlugin
|
||||
|
||||
LOOP_PLUGINS: tuple[LoopPlugin, ...] = (MasteryLoopPlugin(),)
|
||||
|
||||
|
||||
def active_loop_plugins(context: UnifiedContext) -> tuple[LoopPlugin, ...]:
|
||||
"""Return active plugins for this turn in stable registry order."""
|
||||
return tuple(plugin for plugin in LOOP_PLUGINS if plugin.is_active(context))
|
||||
|
||||
|
||||
__all__ = ["LOOP_PLUGINS", "active_loop_plugins"]
|
||||
Reference in New Issue
Block a user