mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 00:29:37 +08:00
Two assertions could not fail: "report" in the research user message matched other words, and the question number check passed for any digit near the template heading. They now look for the rendered mode (``report``) and for "#n of 3" / "第 n/3 道". The research forced-finish docstring said tool_choice="none" while the test asserts "auto". Refs #2974
330 lines
12 KiB
Python
330 lines
12 KiB
Python
"""Deep Question prompts keep per-question state out of the cached prefix.
|
|
|
|
Every question of a turn runs its own ``quiz_step`` loop. Providers cache
|
|
the request prefix, so the system prompt must be byte-identical across the
|
|
questions of one turn, and the shared exploration trace + plan must come
|
|
before anything that differs per question. Likewise the explore system
|
|
prompt must not carry the per-turn output folder.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
|
|
import pytest
|
|
|
|
from deeptutor.agents.question.pipeline import QuestionPipeline, QuizPair, QuizPlan, QuizTemplate
|
|
from deeptutor.core.context import TurnRuntimeContext, UnifiedContext, WorkspaceRuntimeContext
|
|
from deeptutor.runtime.stream_bus import StreamBus
|
|
from deeptutor.services.llm.config import LLMConfig
|
|
|
|
pytestmark = pytest.mark.asyncio
|
|
|
|
|
|
class _Captured(Exception):
|
|
pass
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _stub_llm_config(monkeypatch) -> None:
|
|
monkeypatch.setattr(
|
|
"deeptutor.agents.question.pipeline.get_llm_config",
|
|
lambda: LLMConfig(model="test-model", api_key="test-key"),
|
|
)
|
|
|
|
|
|
def _capture_loop(monkeypatch) -> list[list[dict[str, Any]]]:
|
|
calls: list[list[dict[str, Any]]] = []
|
|
|
|
async def fake_loop(*, initial_messages, **_kwargs):
|
|
calls.append([dict(m) for m in initial_messages])
|
|
raise _Captured
|
|
|
|
monkeypatch.setattr("deeptutor.agents.question.pipeline.run_agentic_loop", fake_loop)
|
|
return calls
|
|
|
|
|
|
def _context(turn: str) -> UnifiedContext:
|
|
return UnifiedContext(
|
|
session_id="s1",
|
|
user_message="Quiz me on Newton's laws",
|
|
runtime=TurnRuntimeContext(
|
|
workspace=WorkspaceRuntimeContext(
|
|
workspace_id="ws",
|
|
root="/host/root",
|
|
output_dir=f"/host/root/outputs/deep_question/s1/{turn}",
|
|
logical_output_dir=f"outputs/deep_question/s1/{turn}",
|
|
)
|
|
),
|
|
)
|
|
|
|
|
|
_PLAN = QuizPlan(
|
|
analysis="three angles",
|
|
templates=[
|
|
QuizTemplate("q_1", "first law", "choice", "easy"),
|
|
QuizTemplate("q_2", "second law", "short_answer", "medium"),
|
|
QuizTemplate("q_3", "third law", "concept", "hard"),
|
|
],
|
|
)
|
|
|
|
|
|
async def _quiz_messages(pipeline: QuestionPipeline, monkeypatch) -> list[list[dict[str, Any]]]:
|
|
calls = _capture_loop(monkeypatch)
|
|
context = _context("t-1")
|
|
previous: list[QuizPair] = []
|
|
for index, template in enumerate(_PLAN.templates):
|
|
with pytest.raises(_Captured):
|
|
await pipeline._quiz_one(
|
|
template=template,
|
|
question_number=index + 1,
|
|
total_questions=len(_PLAN.templates),
|
|
exploration_trace="EXPLORATION TRACE BODY",
|
|
plan=_PLAN,
|
|
previous_pairs=list(previous),
|
|
image_attachments=[],
|
|
context=context,
|
|
stream=StreamBus(),
|
|
client=None,
|
|
)
|
|
previous.append(
|
|
QuizPair(
|
|
question_id=template.question_id,
|
|
question=f"generated question {index + 1}",
|
|
question_type=template.question_type,
|
|
correct_answer="A",
|
|
explanation="because",
|
|
)
|
|
)
|
|
return calls
|
|
|
|
|
|
@pytest.mark.parametrize("language", ["en", "zh"])
|
|
async def test_quiz_step_system_is_identical_across_questions(monkeypatch, language) -> None:
|
|
pipeline = QuestionPipeline(language=language)
|
|
calls = await _quiz_messages(pipeline, monkeypatch)
|
|
|
|
systems = {call[0]["content"] for call in calls}
|
|
assert len(calls) == 3
|
|
assert len(systems) == 1, "quiz_step system prompt must not vary per question"
|
|
system = systems.pop()
|
|
assert "{" + "question_number" not in system
|
|
assert "q_1" not in system and "first law" not in system
|
|
|
|
|
|
@pytest.mark.parametrize("language", ["en", "zh"])
|
|
async def test_quiz_step_user_puts_shared_context_first(monkeypatch, language) -> None:
|
|
pipeline = QuestionPipeline(language=language)
|
|
calls = await _quiz_messages(pipeline, monkeypatch)
|
|
users = [call[1]["content"] for call in calls]
|
|
|
|
for number, (user, template) in enumerate(zip(users, _PLAN.templates, strict=True), 1):
|
|
trace_at = user.index("EXPLORATION TRACE BODY")
|
|
plan_at = user.index("[q_3]")
|
|
own_at = user.index(f"- topic: {template.topic}")
|
|
assert trace_at < plan_at < own_at
|
|
position = f"#{number} of 3" if language == "en" else f"第 {number}/3 道"
|
|
assert position in user[own_at - 80 : own_at]
|
|
assert "{question_number}" not in user and "{exploration_trace}" not in user
|
|
|
|
# Everything before the "already generated" list is the same for every
|
|
# question, so consecutive questions share the trace + plan as prefix.
|
|
def shared(a: str, b: str) -> int:
|
|
n = 0
|
|
while n < min(len(a), len(b)) and a[n] == b[n]:
|
|
n += 1
|
|
return n
|
|
|
|
for a, b in zip(users, users[1:], strict=False):
|
|
assert shared(a, b) > a.index("[q_3]")
|
|
|
|
|
|
@pytest.mark.parametrize("language", ["en", "zh"])
|
|
async def test_explore_system_is_identical_across_turns(monkeypatch, language) -> None:
|
|
calls = _capture_loop(monkeypatch)
|
|
pipeline = QuestionPipeline(language=language)
|
|
for turn in ("t-1", "t-2"):
|
|
with pytest.raises(_Captured):
|
|
await pipeline._explore(
|
|
context=_context(turn),
|
|
user_message="Quiz me on Newton's laws",
|
|
num_questions=3,
|
|
difficulty="",
|
|
allowed_types=[],
|
|
per_type_counts={},
|
|
conversation_context="",
|
|
attachments=[],
|
|
image_attachments=[],
|
|
quiz_history=[],
|
|
stream=StreamBus(),
|
|
client=None,
|
|
)
|
|
|
|
(sys1, user1), (sys2, user2) = ((c[0]["content"], c[1]["content"]) for c in calls)
|
|
assert sys1 == sys2
|
|
assert "outputs/deep_question/s1" not in sys1
|
|
# The standing workspace rules are still in the system prompt ...
|
|
assert "workspace_read" in sys1
|
|
# ... and the exact per-turn folder rides at the end of the user message.
|
|
assert user1.rstrip().endswith("]")
|
|
assert "outputs/deep_question/s1/t-1/" in user1.rsplit("\n\n", 1)[-1]
|
|
assert "outputs/deep_question/s1/t-2/" in user2.rsplit("\n\n", 1)[-1]
|
|
|
|
|
|
_SCHEMAS = [{"type": "function", "function": {"name": "web_search", "parameters": {}}}]
|
|
|
|
|
|
def _delta(content: str | None, tool_calls: list | None = None) -> SimpleNamespace:
|
|
return SimpleNamespace(
|
|
choices=[
|
|
SimpleNamespace(
|
|
delta=SimpleNamespace(content=content, tool_calls=tool_calls),
|
|
finish_reason=None,
|
|
)
|
|
],
|
|
usage=None,
|
|
)
|
|
|
|
|
|
_TOOL_CALL = SimpleNamespace(
|
|
index=0,
|
|
id="call_1",
|
|
type="function",
|
|
function=SimpleNamespace(name="web_search", arguments='{"query": "x"}'),
|
|
)
|
|
|
|
|
|
class _RecordingClient:
|
|
"""Answers with ``FINISH`` (after ``tool_rounds`` tool-call replies) and
|
|
keeps the request kwargs."""
|
|
|
|
def __init__(self, *, tool_rounds: int = 0) -> None:
|
|
self.calls: list[dict[str, Any]] = []
|
|
parent = self
|
|
|
|
class _Completions:
|
|
async def create(self, **kwargs: Any):
|
|
parent.calls.append(dict(kwargs))
|
|
calls_tool = len(parent.calls) <= tool_rounds
|
|
|
|
async def _stream():
|
|
if calls_tool:
|
|
yield _delta(None, [_TOOL_CALL])
|
|
else:
|
|
yield _delta("``FINISH``\nDone.")
|
|
|
|
return _stream()
|
|
|
|
self.chat = SimpleNamespace(completions=_Completions())
|
|
|
|
|
|
def _capture_host(monkeypatch) -> dict[str, Any]:
|
|
seen: dict[str, Any] = {}
|
|
|
|
async def fake_loop(*, host, tool_schemas, **_kwargs):
|
|
seen["host"] = host
|
|
seen["tool_schemas"] = tool_schemas
|
|
raise _Captured
|
|
|
|
monkeypatch.setattr("deeptutor.agents.question.pipeline.run_agentic_loop", fake_loop)
|
|
return seen
|
|
|
|
|
|
async def _force_finish_request(seen: dict[str, Any]) -> dict[str, Any]:
|
|
client = _RecordingClient()
|
|
host = seen["host"]
|
|
host._client = client
|
|
text, completed, _calls = await host.force_finalize(
|
|
messages=[{"role": "system", "content": "s"}, {"role": "user", "content": "u"}],
|
|
start_iteration=3,
|
|
)
|
|
assert completed and text == "Done."
|
|
return client.calls[0]
|
|
|
|
|
|
def _native_tools(pipeline: QuestionPipeline, monkeypatch) -> None:
|
|
monkeypatch.setattr(pipeline, "_use_native_tools", lambda _context: True)
|
|
monkeypatch.setattr(pipeline, "_build_llm_tool_schemas", lambda _context: _SCHEMAS)
|
|
|
|
|
|
async def test_a_forced_explore_finish_keeps_the_explore_tools(monkeypatch) -> None:
|
|
"""Running out of explore rounds must not drop the tools from the forced
|
|
FINISH request; the request keeps the explore rounds' cached prefix."""
|
|
pipeline = QuestionPipeline(language="en")
|
|
_native_tools(pipeline, monkeypatch)
|
|
seen = _capture_host(monkeypatch)
|
|
with pytest.raises(_Captured):
|
|
await pipeline._explore(
|
|
context=_context("t-1"),
|
|
user_message="Quiz me on Newton's laws",
|
|
num_questions=3,
|
|
difficulty="",
|
|
allowed_types=[],
|
|
per_type_counts={},
|
|
conversation_context="",
|
|
attachments=[],
|
|
image_attachments=[],
|
|
quiz_history=[],
|
|
stream=StreamBus(),
|
|
client=None,
|
|
)
|
|
|
|
request = await _force_finish_request(seen)
|
|
assert request["tools"] == seen["tool_schemas"] == _SCHEMAS
|
|
assert request["tool_choice"] == "auto"
|
|
|
|
|
|
async def test_a_forced_quiz_finish_keeps_the_quiz_tools(monkeypatch) -> None:
|
|
pipeline = QuestionPipeline(language="en")
|
|
_native_tools(pipeline, monkeypatch)
|
|
seen = _capture_host(monkeypatch)
|
|
with pytest.raises(_Captured):
|
|
await pipeline._quiz_one(
|
|
template=_PLAN.templates[0],
|
|
question_number=1,
|
|
total_questions=len(_PLAN.templates),
|
|
exploration_trace="EXPLORATION TRACE BODY",
|
|
plan=_PLAN,
|
|
previous_pairs=[],
|
|
image_attachments=[],
|
|
context=_context("t-1"),
|
|
stream=StreamBus(),
|
|
client=None,
|
|
)
|
|
|
|
request = await _force_finish_request(seen)
|
|
assert request["tools"] == seen["tool_schemas"] == _SCHEMAS
|
|
assert request["tool_choice"] == "auto"
|
|
|
|
|
|
async def test_a_tool_call_in_the_forced_finish_is_repaired_not_run() -> None:
|
|
"""The tools are still offered, so the model may call one anyway. That
|
|
attempt is not dispatched; the repair note asks for FINISH again."""
|
|
pipeline = QuestionPipeline(language="en")
|
|
client = _RecordingClient(tool_rounds=1)
|
|
messages = [{"role": "system", "content": "s"}, {"role": "user", "content": "u"}]
|
|
|
|
text, completed, calls = await pipeline._force_finish(
|
|
client=client,
|
|
messages=messages,
|
|
stream=StreamBus(),
|
|
stage="generation",
|
|
trace_root="quiz-q_1",
|
|
trace_extras={},
|
|
stream_body_live=False,
|
|
tool_schemas=_SCHEMAS,
|
|
)
|
|
|
|
assert completed and text == "Done." and calls == 2
|
|
assert [c["tools"] for c in client.calls] == [_SCHEMAS, _SCHEMAS]
|
|
assert not any(m.get("role") == "tool" or m.get("tool_calls") for m in messages)
|
|
assert messages[-1] == {"role": "user", "content": pipeline._t("protocol.force_finish_repair")}
|
|
# Anthropic rejects an empty text block, so the skipped call leaves a
|
|
# short note instead of empty content.
|
|
assert messages[-2] == {
|
|
"role": "assistant",
|
|
"content": pipeline._t("protocol.force_finish_tool_call_skipped"),
|
|
}
|
|
assert messages[-2]["content"].strip()
|