mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 03:29:23 +08:00
294 lines
10 KiB
Python
294 lines
10 KiB
Python
"""Per-turn data must not rewrite the system prompt.
|
|
|
|
The system prompt is the head of every cached prefix. Anything that changes
|
|
inside one session — the sidebar selection, the chosen persona, installed
|
|
skills, a creator draft, the notebook anchor, the requested visualizer type —
|
|
used to be rendered into it, so the very next request missed the provider
|
|
cache from byte zero. Those facts now travel as append-only
|
|
``[Runtime context: <name>]`` snapshots: the system prompt stays byte-identical
|
|
and each change shows up as one new snapshot message after the history.
|
|
|
|
With native tool calling, the tool schemas already describe every tool, so the
|
|
``[Runtime context: tools]`` text manifest is not sent at all.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
|
|
from deeptutor.core.context import TurnRuntimeContext, UnifiedContext, WorkspaceRuntimeContext
|
|
from deeptutor.core.tool_protocol import ToolResult
|
|
from deeptutor.services.session.model_history import normalize_model_turn, replay_history
|
|
from deeptutor.visualizers.protocol import REQUESTED_VISUALIZER_KEY, VISUALIZE_MODE_KEY
|
|
|
|
_MANIFEST = "- `web_search` — Search the web\n When to use: recent events"
|
|
|
|
|
|
class _Registry:
|
|
def deferred_tools(self):
|
|
return []
|
|
|
|
def build_prompt_text(self, _enabled, **_kwargs):
|
|
return _MANIFEST
|
|
|
|
async def execute(self, name: str, **kwargs):
|
|
return ToolResult(content="tool answer", success=True)
|
|
|
|
|
|
class _Draft:
|
|
def __init__(self, name: str) -> None:
|
|
self.name = name
|
|
self.status = "pending"
|
|
self.created_name = ""
|
|
|
|
|
|
@pytest.fixture
|
|
def turn_data(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict[str, Any]:
|
|
"""Session-scoped facts the test mutates between turns."""
|
|
from deeptutor.capabilities.setup.binding import mark_intro_shown
|
|
from deeptutor.services.path_service import PathService
|
|
|
|
monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))
|
|
paths = PathService(workspace_root=tmp_path / "data")
|
|
monkeypatch.setattr(PathService, "_instance", paths)
|
|
paths.ensure_all_directories()
|
|
mark_intro_shown()
|
|
monkeypatch.setattr(
|
|
"deeptutor.agents.loop.pipeline.get_llm_config",
|
|
lambda: SimpleNamespace(
|
|
binding="openai",
|
|
model="gpt-test",
|
|
api_key="k",
|
|
base_url="u",
|
|
api_version=None,
|
|
extra_headers={},
|
|
reasoning_effort=None,
|
|
),
|
|
)
|
|
|
|
data: dict[str, Any] = {"names": ["algebra-coach"], "draft": "draft-1", "anchor": "A"}
|
|
|
|
kind = SimpleNamespace(
|
|
key="skill",
|
|
label="skill",
|
|
list_names=lambda limit=60: list(data["names"])[:limit],
|
|
)
|
|
monkeypatch.setattr(
|
|
"deeptutor.services.creations.get_creation_kind",
|
|
lambda key: kind if key == "skill" else None,
|
|
)
|
|
|
|
class _DraftStore:
|
|
def latest_for_session(self, _session_id: str, _kind: str) -> _Draft:
|
|
return _Draft(data["draft"])
|
|
|
|
monkeypatch.setattr("deeptutor.services.creations.CreationDraftStore", _DraftStore)
|
|
monkeypatch.setattr(
|
|
"deeptutor.capabilities.notes.capability.get_co_writer_storage",
|
|
lambda: SimpleNamespace(load_document=lambda _doc_id: {"id": "doc-1"}),
|
|
)
|
|
monkeypatch.setattr(
|
|
"deeptutor.capabilities.notes.capability.thread_anchor_context",
|
|
lambda _storage, _doc, _session, *, zh: f"Held at block {data['anchor']}.",
|
|
)
|
|
return data
|
|
|
|
|
|
def _pipeline(language: str = "en") -> AgenticChatPipeline:
|
|
pipeline = AgenticChatPipeline(language=language)
|
|
pipeline.registry = _Registry()
|
|
return pipeline
|
|
|
|
|
|
def _context(
|
|
turn: int,
|
|
*,
|
|
history: list[dict[str, Any]] | None,
|
|
sidebar: str,
|
|
persona: str,
|
|
skills: str,
|
|
visualizer: str,
|
|
) -> UnifiedContext:
|
|
return UnifiedContext(
|
|
session_id="snap-session",
|
|
user_message=f"Question {turn}",
|
|
sidebar_context=sidebar,
|
|
persona_context=persona,
|
|
skills_manifest=skills,
|
|
metadata={
|
|
"create_target": "skill",
|
|
"note_document_id": "doc-1",
|
|
VISUALIZE_MODE_KEY: True,
|
|
REQUESTED_VISUALIZER_KEY: visualizer,
|
|
},
|
|
runtime=TurnRuntimeContext(
|
|
workspace=WorkspaceRuntimeContext(
|
|
workspace_id="ws_test",
|
|
root="/private/host/learning-files",
|
|
output_dir=f"/private/host/learning-files/outputs/chat/snap-session/t{turn}",
|
|
logical_output_dir=f"outputs/chat/snap-session/t{turn}",
|
|
),
|
|
model_history=history,
|
|
),
|
|
)
|
|
|
|
|
|
def _snapshots(messages: list[dict[str, Any]]) -> dict[str, list[str]]:
|
|
found: dict[str, list[str]] = {}
|
|
for message in messages:
|
|
name = message.get("_context_snapshot")
|
|
if name:
|
|
found.setdefault(name, []).append(message["content"])
|
|
return found
|
|
|
|
|
|
_TURNS = (
|
|
dict(
|
|
sidebar="Selection: the chain rule",
|
|
persona="Speak like a patient coach.",
|
|
skills="## Skills\n- **derivatives** — practise derivatives",
|
|
visualizer="svg",
|
|
names=["algebra-coach"],
|
|
draft="draft-1",
|
|
anchor="A",
|
|
),
|
|
dict(
|
|
sidebar="Selection: the product rule",
|
|
persona="Speak like a strict examiner.",
|
|
skills=(
|
|
"## Skills\n- **derivatives** — practise derivatives\n"
|
|
"- **integrals** — practise integrals"
|
|
),
|
|
visualizer="mermaid",
|
|
names=["algebra-coach", "draft-1"],
|
|
draft="draft-2",
|
|
anchor="B",
|
|
),
|
|
)
|
|
|
|
|
|
def test_system_prompt_is_byte_identical_while_turn_data_changes(
|
|
turn_data: dict[str, Any],
|
|
) -> None:
|
|
rows: list[dict[str, Any]] = []
|
|
requests: list[list[dict[str, Any]]] = []
|
|
seeds: list[str] = []
|
|
start = 1
|
|
for index, turn in enumerate(_TURNS, start=1):
|
|
turn_data.update(names=turn["names"], draft=turn["draft"], anchor=turn["anchor"])
|
|
pipeline = _pipeline()
|
|
context = _context(
|
|
index,
|
|
history=replay_history(rows) if rows else None,
|
|
sidebar=turn["sidebar"],
|
|
persona=turn["persona"],
|
|
skills=turn["skills"],
|
|
visualizer=turn["visualizer"],
|
|
)
|
|
messages = pipeline._build_loop_messages(context=context, enabled_tools=["web_search"])
|
|
# AgentLoop prepends this seed to the current user message.
|
|
seeds.append(pipeline._capability_pre_loop_seed(context))
|
|
system = messages[0]["content"]
|
|
# None of the changing values reach the system prompt.
|
|
for value in (
|
|
turn["sidebar"],
|
|
turn["persona"],
|
|
"practise derivatives",
|
|
turn["draft"],
|
|
f"block {turn['anchor']}",
|
|
f"`{turn['visualizer']}`",
|
|
):
|
|
assert value not in system
|
|
if requests:
|
|
# Byte-identical system, and the whole previous request is an
|
|
# exact prefix of this one.
|
|
assert system == requests[0][0]["content"]
|
|
assert messages[: len(requests[-1])] == requests[-1]
|
|
requests.append(messages)
|
|
record = normalize_model_turn(
|
|
{"version": 1, "messages": messages[start:], "system": system}
|
|
)
|
|
assert record is not None
|
|
rows.extend(
|
|
[
|
|
{"role": "user", "content": f"Question {index}"},
|
|
{"role": "assistant", "content": f"A{index}", "metadata": {"model_turn": record}},
|
|
]
|
|
)
|
|
start = 1 + len(replay_history(rows))
|
|
|
|
first, second = requests
|
|
appended = _snapshots(second[len(first) :])
|
|
# Each changed fact arrives as one new snapshot after the history...
|
|
assert "Selection: the product rule" in appended["sidebar_tutor_context"][0]
|
|
assert "strict examiner" in appended["persona_style"][0]
|
|
assert "practise integrals" in appended["skills"][0]
|
|
assert "draft-2" in appended["creator_state"][0]
|
|
assert "block B" in appended["notes_page"][0]
|
|
# ...and the requested visualizer type rides in the current user message.
|
|
assert "requested_type=svg" in seeds[0]
|
|
assert "requested_type=mermaid" in seeds[1]
|
|
|
|
|
|
def test_unchanged_turn_data_appends_no_snapshot(turn_data: dict[str, Any]) -> None:
|
|
_ = turn_data
|
|
turn = _TURNS[0]
|
|
first = _pipeline()._build_loop_messages(
|
|
context=_context(
|
|
1,
|
|
history=None,
|
|
sidebar=turn["sidebar"],
|
|
persona=turn["persona"],
|
|
skills=turn["skills"],
|
|
visualizer=turn["visualizer"],
|
|
),
|
|
enabled_tools=["web_search"],
|
|
)
|
|
record = normalize_model_turn(
|
|
{"version": 1, "messages": first[1:], "system": first[0]["content"]}
|
|
)
|
|
rows = [
|
|
{"role": "user", "content": "Question 1"},
|
|
{"role": "assistant", "content": "A1", "metadata": {"model_turn": record}},
|
|
]
|
|
second = _pipeline()._build_loop_messages(
|
|
context=_context(
|
|
2,
|
|
history=replay_history(rows),
|
|
sidebar=turn["sidebar"],
|
|
persona=turn["persona"],
|
|
skills=turn["skills"],
|
|
visualizer=turn["visualizer"],
|
|
),
|
|
enabled_tools=["web_search"],
|
|
)
|
|
assert second[: len(first)] == first
|
|
assert _snapshots(second[len(first) :]) == {}
|
|
|
|
|
|
def test_native_tool_calling_sends_no_tool_manifest(turn_data: dict[str, Any]) -> None:
|
|
_ = turn_data
|
|
pipeline = _pipeline()
|
|
context = UnifiedContext(session_id="s", user_message="hi")
|
|
messages = pipeline._build_loop_messages(context=context, enabled_tools=["web_search"])
|
|
assert pipeline._can_use_native_tool_calling()
|
|
assert "tools" not in _snapshots(messages)
|
|
assert all(_MANIFEST not in str(message.get("content")) for message in messages)
|
|
|
|
|
|
def test_text_tool_path_keeps_the_manifest(
|
|
turn_data: dict[str, Any], monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""Without native schemas the manifest is the only tool description."""
|
|
_ = turn_data
|
|
pipeline = _pipeline()
|
|
monkeypatch.setattr(pipeline, "_can_use_native_tool_calling", lambda: False)
|
|
context = UnifiedContext(session_id="s", user_message="hi")
|
|
messages = pipeline._build_loop_messages(context=context, enabled_tools=["web_search"])
|
|
assert _MANIFEST in _snapshots(messages)["tools"][0]
|