mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 03:09:49 +08:00
* fix: keep sent runtime snapshots in mastery replay Mastery replay dropped every runtime snapshot from history and the loop re-appended them after it, so each follow-up request diverged from the previous one at message 1 and only tools + system hit the prompt cache. - project_mastery_replay(keep_snapshots=True) for the tutor request and its token accounting; memory material still drops snapshots - replay_group no longer blanks a tagged mastery_status_snapshot while removing the legacy fused suffix - status snapshot anchors are numbered from the start (occurrence), so a later snapshot never changes how an earlier turn is projected Refs #2922 * fix: keep runtime snapshots out of the mastery history budget Replayed snapshots stay in the request so follow-up turns extend the cached prefix, but counting them made a large mastery_status snapshot push the history over its 20k budget after two turns; the next turn then paid a memory rewrite and a full prefix miss. The budget now measures the learning history only, as before. Refs #2922 * fix: bound the runtime snapshots kept in mastery history Keeping sent snapshots out of the history budget entirely let many short exchanges accumulate them without limit (80 quiz-style turns: 5.4k counted, 62k sent). Dialogue still keeps to the plan; dialogue plus snapshots keep to twice the plan, and only as far as the model's window allows. Refs #2922 * fix: keep only this turn's state in the mastery status snapshot Every mastery turn sends a fresh mastery_status snapshot and, since the replay change, keeps earlier ones in history, so whatever a snapshot carries is paid for once per turn and then kept. A full status read repeats fixed guidance (open question, question group, working brief, intake, teaching guidance and focus) and every default value of every knowledge point. The snapshot now drops empty and default values and the fixed guidance. That guidance lives in named constants and is stated once in a new mastery_status_guide system block, which also explains the omitted defaults. Snapshots start with a one-line header; history sharing reads both the header and the longer notice older sessions stored. An explicit mastery_status call still returns the full payload. Measured over 54 recorded snapshots: working briefs 1,454 -> 645 tokens (median), full outline snapshots 6,352 -> 2,954. The guide adds 861 tokens (en) to the cached system prompt. Refs #2922 * fix: size the exact tail the way the plan does, and share full reads with compact snapshots Two gaps left by keeping snapshots in mastery replay (review on #2992): - Recent-history selection counted kept snapshots in full while the plan discounted them, so a session of short exchanges with large snapshots archived most of them as soon as selection ran. ContextBuilder now sizes the candidate tail through _recent_history_tokens(), and the mastery builder answers with the same _plan_tokens() measure. - Snapshots carry the compact form of map, learner_profile, learning_stages and visual_requirements, so a later full mastery_status result never matched them exactly. Sharing now also compares a full field's compact form and marks such references with "defaults_omitted": true, which the state reference notice explains. Also: rename _next to _compact_next_step, and say in the status guide that the omitted-default rules cover only what the snapshot includes. Refs #2922
180 lines
6.4 KiB
Python
180 lines
6.4 KiB
Python
"""The per-turn mastery_status snapshot, kept to what changes between turns.
|
|
|
|
Every mastery turn starts with a fresh ``mastery_status`` read placed in the
|
|
request as a runtime snapshot, and earlier turns' snapshots stay in the replayed
|
|
history so the cached prefix keeps growing. Whatever a snapshot carries is
|
|
therefore paid for once per turn and then kept. A full status read repeats
|
|
guidance that never changes (how to treat an open question, how to use the
|
|
learner profile, what a working brief is) and spells out every default value
|
|
of every knowledge point. The snapshot leaves both out: the fixed guidance is
|
|
stated once in the system prompt (:func:`status_guide`), and empty or default
|
|
values are simply omitted, which the same guide explains.
|
|
|
|
An explicit ``mastery_status`` tool call still returns the full payload.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from deeptutor.capabilities.mastery.history import SNAPSHOT_HEADER
|
|
from deeptutor.capabilities.mastery.tools import (
|
|
GROUP_REPLY_INSTRUCTION,
|
|
INTAKE_INSTRUCTION,
|
|
OPEN_QUESTION_INSTRUCTION,
|
|
WORKING_BRIEF_INSTRUCTION,
|
|
)
|
|
from deeptutor.learning.teaching import TEACHING_FOCUS_INSTRUCTION, TEACHING_GUIDANCE
|
|
|
|
# Knowledge-point fields that are left out while they hold their default.
|
|
_POINT_DEFAULTS: dict[str, Any] = {
|
|
"prerequisite_ids": [],
|
|
"topic_source_ids": [],
|
|
"status": "new",
|
|
"mastery": 0,
|
|
"mastery_source": "",
|
|
"override_note": "",
|
|
"deferred": False,
|
|
}
|
|
_FIXED_INSTRUCTIONS = frozenset({GROUP_REPLY_INSTRUCTION, OPEN_QUESTION_INSTRUCTION})
|
|
|
|
|
|
def _empty(value: Any) -> bool:
|
|
return value is None or value == "" or value == [] or value == {}
|
|
|
|
|
|
def _point(point: Any) -> Any:
|
|
if not isinstance(point, dict):
|
|
return point
|
|
return {
|
|
key: value
|
|
for key, value in point.items()
|
|
if not (key in _POINT_DEFAULTS and value == _POINT_DEFAULTS[key])
|
|
}
|
|
|
|
|
|
def _map(overview: Any) -> Any:
|
|
if not isinstance(overview, dict) or not isinstance(overview.get("modules"), list):
|
|
return overview
|
|
modules = []
|
|
for module in overview["modules"]:
|
|
if isinstance(module, dict) and isinstance(module.get("knowledge_points"), list):
|
|
module = {**module, "knowledge_points": [_point(p) for p in module["knowledge_points"]]}
|
|
modules.append(module)
|
|
return {**overview, "modules": modules}
|
|
|
|
|
|
def _compact_next_step(step: Any) -> Any:
|
|
if not isinstance(step, dict):
|
|
return step
|
|
step = dict(step)
|
|
question = step.get("pending_question")
|
|
if isinstance(question, dict) and step.get("pending_prompt") == question.get("prompt"):
|
|
step.pop("pending_prompt")
|
|
for key in ("pending_prompt", "pending_question", "session_id"):
|
|
if key in step and _empty(step[key]):
|
|
step.pop(key)
|
|
return step
|
|
|
|
|
|
def _profile(profile: Any) -> Any:
|
|
if not isinstance(profile, dict):
|
|
return profile
|
|
profile = {
|
|
key: value
|
|
for key, value in profile.items()
|
|
if key != "teaching_guidance" or value != TEACHING_GUIDANCE
|
|
}
|
|
focus = profile.get("teaching_focus")
|
|
if isinstance(focus, dict):
|
|
focus = {
|
|
key: value
|
|
for key, value in focus.items()
|
|
if key != "instruction" or value != TEACHING_FOCUS_INSTRUCTION
|
|
}
|
|
profile["teaching_focus"] = focus if focus.get("observations") else None
|
|
return {key: value for key, value in profile.items() if not _empty(value)}
|
|
|
|
|
|
def _stages(stages: Any) -> Any:
|
|
if not isinstance(stages, dict):
|
|
return stages
|
|
return {key: value for key, value in stages.items() if value != "not_yet_covered"}
|
|
|
|
|
|
def _visuals(requirements: Any) -> Any:
|
|
if not isinstance(requirements, dict):
|
|
return requirements
|
|
return {
|
|
key: value
|
|
for key, value in requirements.items()
|
|
if not (isinstance(value, dict) and all(_empty(item) for item in value.values()))
|
|
}
|
|
|
|
|
|
#: How the snapshot shortens each state field that history sharing tracks.
|
|
#: Sharing applies the same function to a full ``mastery_status`` result, so a
|
|
#: field the snapshot already carried is not sent again in its long form.
|
|
_FIELD_COMPACTORS = {
|
|
"map": _map,
|
|
"learner_profile": _profile,
|
|
"learning_stages": _stages,
|
|
"visual_requirements": _visuals,
|
|
}
|
|
|
|
|
|
def compact_field(field: str, value: Any) -> Any:
|
|
"""The snapshot form of one top-level ``mastery_status`` field."""
|
|
compactor = _FIELD_COMPACTORS.get(field)
|
|
return compactor(value) if compactor is not None else value
|
|
|
|
|
|
def _pending(interaction: Any) -> Any:
|
|
if not isinstance(interaction, dict):
|
|
return interaction
|
|
interaction = dict(interaction)
|
|
interaction.pop("session_id", None)
|
|
if interaction.get("instruction") in _FIXED_INSTRUCTIONS:
|
|
interaction.pop("instruction")
|
|
return interaction
|
|
|
|
|
|
def compact_status(payload: dict[str, Any]) -> dict[str, Any]:
|
|
"""Drop fixed guidance and default values from a ``mastery_status`` payload."""
|
|
result = dict(payload)
|
|
if result.get("inspection_instruction") == WORKING_BRIEF_INSTRUCTION:
|
|
result.pop("inspection_instruction")
|
|
if result.get("intake_instruction") == INTAKE_INSTRUCTION:
|
|
result.pop("intake_instruction")
|
|
if result.get("intake_needed") is False:
|
|
result.pop("intake_needed")
|
|
if "next" in result:
|
|
result["next"] = _compact_next_step(result["next"])
|
|
for field in _FIELD_COMPACTORS:
|
|
if field in result:
|
|
result[field] = compact_field(field, result[field])
|
|
if "pending_interaction" in result:
|
|
result["pending_interaction"] = _pending(result["pending_interaction"])
|
|
for key in ("goal", "sources", "due_review_ids", "learning_stages", "visual_requirements"):
|
|
if key in result and _empty(result[key]):
|
|
result.pop(key)
|
|
return result
|
|
|
|
|
|
def status_guide(template: str) -> str:
|
|
"""Fill the localized guide with the fixed guidance the snapshot leaves out."""
|
|
values = {
|
|
"{working_brief}": WORKING_BRIEF_INSTRUCTION,
|
|
"{intake}": INTAKE_INSTRUCTION,
|
|
"{open_question}": OPEN_QUESTION_INSTRUCTION,
|
|
"{group_reply}": GROUP_REPLY_INSTRUCTION,
|
|
"{teaching_guidance}": TEACHING_GUIDANCE,
|
|
"{teaching_focus}": TEACHING_FOCUS_INSTRUCTION,
|
|
}
|
|
for placeholder, value in values.items():
|
|
template = template.replace(placeholder, value)
|
|
return template
|
|
|
|
|
|
__all__ = ["SNAPSHOT_HEADER", "compact_field", "compact_status", "status_guide"]
|