diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py index c3cdec71e..7e2c092c3 100644 --- a/deeptutor/agents/question/pipeline.py +++ b/deeptutor/agents/question/pipeline.py @@ -649,9 +649,17 @@ class QuestionPipeline: tool_list=self._tool_list_text(context), num_questions=num_questions, ) - from deeptutor.agents._shared.workspace_prompt import workspace_system_note + from deeptutor.agents._shared.workspace_prompt import ( + workspace_system_note, + workspace_turn_note, + ) - workspace_note = workspace_system_note(context, language=self.language) + # Same split as the chat loop: the standing workspace rules stay in + # the system prompt (byte-stable across turns), the per-turn output + # folder travels at the end of the user message. + workspace_note = workspace_system_note( + context, language=self.language, state_turn_path=False + ) if workspace_note: system_prompt = f"{system_prompt}\n\n{workspace_note}" system_prompt = append_language_directive(system_prompt, self.language) @@ -666,6 +674,9 @@ class QuestionPipeline: conversation_context=conversation_context or self._t("empty.no_conversation"), quiz_history=self._render_quiz_history(quiz_history), ) + turn_note = workspace_turn_note(context, language=self.language) + if turn_note: + user_prompt = f"{user_prompt}\n\n{turn_note}" messages = self._build_system_user_messages( system_prompt, user_prompt, image_attachments=image_attachments ) @@ -888,16 +899,20 @@ class QuestionPipeline: stream: StreamBus, client: Any, ) -> QuizPair: + # The system prompt is identical for every question of a turn so the + # questions share one cached prefix; everything that differs per + # question (its number and template) lives in the user message, after + # the shared exploration trace and plan. system_prompt = self._t( "quiz_step.system", - question_number=question_number, - total_questions=total_questions, kb_note=self._kb_system_note(), tool_list=self._tool_list_text(context), ) system_prompt = append_language_directive(system_prompt, self.language) user_prompt = self._t( "quiz_step.user_template", + question_number=question_number, + total_questions=total_questions, question_id=template.question_id, topic=template.topic, question_type=template.question_type, diff --git a/deeptutor/agents/question/prompts/en/pipeline.yaml b/deeptutor/agents/question/prompts/en/pipeline.yaml index a6147569e..a29173d6c 100644 --- a/deeptutor/agents/question/prompts/en/pipeline.yaml +++ b/deeptutor/agents/question/prompts/en/pipeline.yaml @@ -192,7 +192,7 @@ plan: # --------------------------------------------------------------------------- quiz_step: system: |- - You are writing **one** quiz question (#{question_number} of {total_questions}) according to a template the planner has already fixed. The exploration trace (Phase 1's full reasoning + tool-call history with summarized results) and prior question texts are provided so you can ground the question and avoid duplicates. + You are writing **one** quiz question according to a template the planner has already fixed. The exploration trace (Phase 1's full reasoning + tool-call history with summarized results) and prior question texts are provided so you can ground the question and avoid duplicates. # Output protocol (mandatory — every reply must comply) @@ -244,12 +244,6 @@ quiz_step: Enabled tools: {tool_list} user_template: |- - ## Quiz template for this question - - question_id: {question_id} - - topic: {topic} - - question_type: {question_type} - - difficulty: {difficulty} - ## Exploration trace (Phase 1's full thought + tool-call history, with summarized tool results) {exploration_trace} @@ -259,6 +253,12 @@ quiz_step: ## Already-generated questions this turn (do NOT duplicate) {previous_questions} + ## Quiz template for this question (#{question_number} of {total_questions}) + - question_id: {question_id} + - topic: {topic} + - question_type: {question_type} + - difficulty: {difficulty} + ## Reference material (mimic mode only — paraphrase / shadow this question's style and difficulty rather than inventing a fresh stem) {reference_block} diff --git a/deeptutor/agents/question/prompts/zh/pipeline.yaml b/deeptutor/agents/question/prompts/zh/pipeline.yaml index 81fd8f8fe..a96ebc1d7 100644 --- a/deeptutor/agents/question/prompts/zh/pipeline.yaml +++ b/deeptutor/agents/question/prompts/zh/pipeline.yaml @@ -173,7 +173,7 @@ plan: # --------------------------------------------------------------------------- quiz_step: system: |- - 你正在写**一道**测验题(第 {question_number}/{total_questions} 道),依据规划器已经固定下来的 template。探索轨迹(阶段 1 完整推理 + 工具调用历史,工具结果已概括)和本轮已生成题目的列表都已提供,请据此做出有依据、不重复的题目。 + 你正在写**一道**测验题,依据规划器已经固定下来的 template。探索轨迹(阶段 1 完整推理 + 工具调用历史,工具结果已概括)和本轮已生成题目的列表都已提供,请据此做出有依据、不重复的题目。 # 输出协议(强制) @@ -225,12 +225,6 @@ quiz_step: 启用的工具: {tool_list} user_template: |- - ## 本题 template - - question_id: {question_id} - - topic: {topic} - - question_type: {question_type} - - difficulty: {difficulty} - ## 探索轨迹(阶段 1 完整思考 + 工具调用历史,工具结果已概括) {exploration_trace} @@ -240,6 +234,12 @@ quiz_step: ## 本轮已生成题目(**不要**重复) {previous_questions} + ## 本题 template(第 {question_number}/{total_questions} 道) + - question_id: {question_id} + - topic: {topic} + - question_type: {question_type} + - difficulty: {difficulty} + ## 参考素材(仅 mimic 模式使用——本题应**仿写 / 改编**该参考题的风格和难度,**不要**另起炉灶) {reference_block} diff --git a/tests/agents/question/test_prompt_cache_layout.py b/tests/agents/question/test_prompt_cache_layout.py new file mode 100644 index 000000000..c759abb3a --- /dev/null +++ b/tests/agents/question/test_prompt_cache_layout.py @@ -0,0 +1,170 @@ +"""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 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 + assert f"{number}" in user[own_at - 80 : own_at] # "#n of 3" / "第 n/3 道" + 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]