mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 14:29:48 +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
272 lines
12 KiB
Python
272 lines
12 KiB
Python
"""Lossless sharing of repeated mastery state inside one model request.
|
|
|
|
This is a request projection, not session compaction. Raw history stays intact.
|
|
Known state fields can be shared; prior exact-history reads become recall
|
|
references so an archive never embeds another archive's body.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections import Counter
|
|
from copy import deepcopy
|
|
import json
|
|
from typing import Any
|
|
|
|
from deeptutor.services.session.model_history import _MASTERY_SNAPSHOT_NOTICE
|
|
|
|
#: First line of the per-turn mastery_status snapshot; its JSON payload follows.
|
|
#: What the runtime used to repeat after it in every snapshot now sits once in
|
|
#: the system prompt (see :mod:`deeptutor.capabilities.mastery.snapshot`).
|
|
SNAPSHOT_HEADER = "[Current-turn mastery_status snapshot]\n"
|
|
|
|
|
|
def snapshot_payload_text(content: str) -> str | None:
|
|
"""The JSON text of a snapshot message, or ``None`` when it is not one.
|
|
|
|
Accepts the short header and the longer notice older sessions stored, which
|
|
begins with the same line.
|
|
"""
|
|
for prefix in (_MASTERY_SNAPSHOT_NOTICE, SNAPSHOT_HEADER):
|
|
if content.startswith(prefix):
|
|
return content[len(prefix) :]
|
|
return None
|
|
|
|
|
|
STATE_REFERENCE_NOTICE = (
|
|
"\n\n[Historical mastery state sharing]\n"
|
|
'A {"$mastery_same_value": {"tool_call_id": "...", "pointer": "/..."}} '
|
|
'or {"$mastery_same_value": {"snapshot": "mastery_status_snapshot", "pointer": "/..."}} '
|
|
"inside a tool result means EXACTLY the same JSON value at that "
|
|
"pointer in the named tool result or runtime snapshot's full payload. "
|
|
"For a mastery status snapshot, the payload is the JSON after its first line; "
|
|
'without "occurrence" it is the first such snapshot in this request, '
|
|
'with "occurrence": N the N-th one. '
|
|
'With "defaults_omitted": true the named value is the compact form a status '
|
|
"snapshot sends: this value is that one with the omitted empty values, "
|
|
"defaults and fixed guidance restored, as the status guide describes. "
|
|
"The referenced value is included in this request, not external memory. "
|
|
"Only repeated state is shared; unique past state and learner "
|
|
"exchanges are retained. Historical status is not current progress."
|
|
)
|
|
|
|
_FIELDS = {
|
|
"mastery_status": (
|
|
"map",
|
|
"learner_profile",
|
|
"learning_stages",
|
|
"visual_requirements",
|
|
"sources",
|
|
),
|
|
"mastery_build": ("map",),
|
|
"mastery_revise": ("map",),
|
|
"mastery_revise_batch": ("map", "proposed_map"),
|
|
"mastery_profile": ("learner_profile",),
|
|
}
|
|
|
|
|
|
def project_mastery_replay(
|
|
messages: list[dict[str, Any]], *, keep_snapshots: bool = False
|
|
) -> list[dict[str, Any]]:
|
|
"""Project past turns; the loop supplies fresh runtime state and evidence.
|
|
|
|
Never interpret an unmarked user quotation as runtime context. Tool pairs,
|
|
dialogue and unique historical state stay intact until successful condensing.
|
|
|
|
``keep_snapshots`` is for the tutor's own model request: runtime snapshots
|
|
already sent stay where they were, and the loop appends only the ones that
|
|
changed. Dropping them would move every later message up and make each
|
|
follow-up request diverge from the previous one at its first history
|
|
message, defeating the provider's prompt cache. Memory material and
|
|
archives drop them: there they are repeated state, not dialogue.
|
|
"""
|
|
projected = deepcopy(
|
|
[
|
|
m
|
|
for m in messages
|
|
if keep_snapshots
|
|
or not (m.get("role") == "user" and (isinstance(m.get("_context_snapshot"), str)))
|
|
]
|
|
)
|
|
reference_history_reads(projected)
|
|
share_mastery_history(projected, len(projected))
|
|
return projected
|
|
|
|
|
|
def reference_history_reads(messages: list[dict[str, Any]]) -> None:
|
|
"""Replace recalled archive bodies in an owned historical copy, not storage.
|
|
|
|
Resolve each result against its preceding call batch: providers may reuse
|
|
call IDs in later turns. Never inspect or recursively decode the recalled
|
|
body when the call already identifies the archive.
|
|
"""
|
|
sources: dict[str, str] = {}
|
|
for message in messages:
|
|
if message.get("role") == "assistant":
|
|
sources = {}
|
|
calls = message.get("tool_calls") or []
|
|
counts = Counter(call.get("id") for call in calls)
|
|
for call in calls:
|
|
function = call.get("function", {})
|
|
if (
|
|
function.get("name") not in {"read_source", "pdf"}
|
|
or counts[call.get("id")] != 1
|
|
):
|
|
continue
|
|
try:
|
|
args = json.loads(function.get("arguments", "{}"))
|
|
except (ValueError, TypeError):
|
|
continue
|
|
source_id = args.get("source_id") if isinstance(args, dict) else None
|
|
if isinstance(args, dict) and not source_id:
|
|
sources[call["id"]] = ""
|
|
elif isinstance(source_id, str) and source_id.strip().startswith("hs-tutor-"):
|
|
sources[call["id"]] = source_id.strip()
|
|
elif message.get("role") == "tool":
|
|
source_id = sources.pop(message.get("tool_call_id"), None)
|
|
content = message.get("content")
|
|
if source_id == "" and isinstance(content, str):
|
|
# The reader may infer the only source when its ID was omitted.
|
|
# Our archive/page envelope puts the ID first. Decode just that
|
|
# small header, never the potentially multi-megabyte JSON body.
|
|
prefix = '{"archive_id":'
|
|
if content.startswith(prefix):
|
|
try:
|
|
inferred, _ = json.JSONDecoder().raw_decode(
|
|
content[len(prefix) : 256].lstrip()
|
|
)
|
|
if isinstance(inferred, str) and inferred.startswith("hs-tutor-"):
|
|
source_id = inferred
|
|
except ValueError:
|
|
pass
|
|
if source_id and isinstance(content, str) and not content.startswith("Error:"):
|
|
message["content"] = json.dumps(
|
|
{
|
|
"archive_id": source_id,
|
|
"note": "Previously recalled tutoring history. Use read_source with this "
|
|
"archive_id as source_id to inspect the original exchange again.",
|
|
},
|
|
ensure_ascii=False,
|
|
separators=(",", ":"),
|
|
)
|
|
else:
|
|
sources = {}
|
|
|
|
|
|
def _compact_anchor(
|
|
anchors: dict[str, dict[str, Any]], field: str, value: Any
|
|
) -> dict[str, Any] | None:
|
|
"""An anchor holding ``value`` in the compact form a snapshot sends."""
|
|
from deeptutor.capabilities.mastery.snapshot import compact_field
|
|
|
|
compact = compact_field(field, value)
|
|
if compact == value:
|
|
return None
|
|
encoded = json.dumps(compact, ensure_ascii=False, sort_keys=True, allow_nan=False)
|
|
anchor = anchors.get(encoded) if len(encoded) >= 512 else None
|
|
return {**anchor, "defaults_omitted": True} if anchor is not None else None
|
|
|
|
|
|
def share_mastery_history(messages: list[dict[str, Any]], history_end: int) -> None:
|
|
"""Share exact repeated state in the owned historical request copy in-place.
|
|
|
|
References point back to the earliest full values, never to another reference.
|
|
Current messages are anchors only. No messages are added/removed, so turn
|
|
boundaries and tool protocol remain unchanged. Ambiguous call IDs are not eligible.
|
|
"""
|
|
calls = [call for m in messages for call in m.get("tool_calls", [])]
|
|
counts = Counter(call.get("id") for call in calls)
|
|
results = Counter(m.get("tool_call_id") for m in messages if m.get("role") == "tool")
|
|
names = {
|
|
call["id"]: call.get("function", {}).get("name")
|
|
for call in calls
|
|
if isinstance(call.get("id"), str) and counts[call["id"]] == 1 and results[call["id"]] == 1
|
|
}
|
|
# Snapshot locators count from the start, so replaying later turns never
|
|
# changes how an earlier message is projected (its cache prefix).
|
|
snapshot_seen = 0
|
|
anchors: dict[str, dict[str, Any]] = {}
|
|
|
|
def visit(
|
|
value: Any, locator: dict[str, Any], pointer: str, *, replace: bool
|
|
) -> tuple[Any, bool]:
|
|
if not isinstance(value, (dict, list)):
|
|
return value, False
|
|
encoded = json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False)
|
|
# Small values cost less verbatim than a locator plus its explanation.
|
|
candidate = anchors.get(encoded) if len(encoded) >= 512 else None
|
|
if replace and candidate is None and pointer[1:] in _FIELDS["mastery_status"]:
|
|
# Snapshots carry the compact form of each state field; a full
|
|
# mastery_status result repeats it with defaults and fixed guidance.
|
|
candidate = _compact_anchor(anchors, pointer[1:], value)
|
|
if replace and candidate is not None:
|
|
reference = {"$mastery_same_value": candidate}
|
|
if len(json.dumps(reference)) < len(encoded):
|
|
return reference, True
|
|
changed = False
|
|
result: Any = {} if isinstance(value, dict) else []
|
|
items = value.items() if isinstance(value, dict) else enumerate(value)
|
|
for key, child in items:
|
|
token = str(key).replace("~", "~0").replace("/", "~1")
|
|
projected, shared = visit(child, locator, f"{pointer}/{token}", replace=replace)
|
|
if isinstance(result, dict):
|
|
result[key] = projected
|
|
else:
|
|
result.append(projected)
|
|
changed |= shared
|
|
# A projected parent is not a full anchor. This excludes reference chains.
|
|
if not changed and len(encoded) >= 512:
|
|
anchors.setdefault(encoded, {**locator, "pointer": pointer})
|
|
return result, changed
|
|
|
|
# Appended state must not rewrite prefixes sent in earlier requests.
|
|
for index, message in enumerate(messages):
|
|
content = message.get("content")
|
|
if not isinstance(content, str):
|
|
continue
|
|
snapshot_text = (
|
|
snapshot_payload_text(content)
|
|
if message.get("role") == "user"
|
|
and message.get("_context_snapshot") == "mastery_status_snapshot"
|
|
else None
|
|
)
|
|
is_snapshot = snapshot_text is not None
|
|
if is_snapshot:
|
|
snapshot_seen += 1
|
|
name = names.get(message.get("tool_call_id")) if message.get("role") == "tool" else None
|
|
if not is_snapshot and name not in _FIELDS:
|
|
continue
|
|
try:
|
|
payload = json.loads(snapshot_text if is_snapshot else content)
|
|
if not isinstance(payload, dict):
|
|
continue
|
|
# Do not reinterpret non-standard numbers or pre-existing reference syntax.
|
|
encoded = json.dumps(payload, allow_nan=False)
|
|
if '"$mastery_same_value"' in encoded:
|
|
continue
|
|
except (ValueError, TypeError):
|
|
continue
|
|
if is_snapshot and not isinstance(payload.get("path_id"), str):
|
|
continue
|
|
fields = _FIELDS["mastery_status"] if is_snapshot else _FIELDS[name]
|
|
locator: dict[str, Any]
|
|
if is_snapshot:
|
|
locator = {"snapshot": "mastery_status_snapshot"}
|
|
if snapshot_seen > 1:
|
|
locator["occurrence"] = snapshot_seen
|
|
else:
|
|
locator = {"tool_call_id": message["tool_call_id"]}
|
|
changed = False
|
|
for field in fields:
|
|
if field not in payload:
|
|
continue
|
|
projected, shared = visit(
|
|
payload[field],
|
|
locator,
|
|
f"/{field}",
|
|
replace=index < history_end and not is_snapshot,
|
|
)
|
|
payload[field] = projected
|
|
changed |= shared
|
|
if changed:
|
|
message["content"] = json.dumps(payload, ensure_ascii=False)
|