DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
refactor(agents): rebuild Deep Research / Deep Solve / Question on agentic engine
Bingxi Zhao (Frank)23ca3024becf
diff --git a/deeptutor/agents/__init__.py b/deeptutor/agents/__init__.pyindex 72965381b..7b1fc78f9 100644--- a/deeptutor/agents/__init__.py+++ b/deeptutor/agents/__init__.py@@ -2,10 +2,10 @@Agents Module - Unified agent system for OpenTutor.This module provides a unified BaseAgent class and module-specific agents:-- solve: Question solving agents (MainSolver, SolveAgent, etc.)+- solve: Multi-step problem solving (``SolvePipeline`` on the agentic engine)- research: Deep research agents (DecomposeAgent, ResearchAgent, etc.)- question: Question generation agents (ReAct architecture, separate base)-- chat: Lightweight conversational agent with session management+- chat: ``AgenticChatPipeline`` — single-loop chat on the agentic engineNote: ``co_writer`` and ``book`` are independent top-level modules under``deeptutor/`` (e.g. ``deeptutor.co_writer``, ``deeptutor.book``). Theydiff --git a/deeptutor/agents/_shared/__init__.py b/deeptutor/agents/_shared/__init__.pynew file mode 100644index 000000000..458b9d0aa--- /dev/null+++ b/deeptutor/agents/_shared/__init__.py@@ -0,0 +1,7 @@+"""Helpers shared by capability pipelines (chat, solve, quiz, ...).++Cross-pipeline policy that doesn't belong on the generic ``core.agentic``+engine (which stays capability-agnostic) and doesn't belong on a single+pipeline either. Each module here documents the contract its consumers+must hold to.+"""diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.pynew file mode 100644index 000000000..b62e0a78d--- /dev/null+++ b/deeptutor/agents/_shared/tool_composition.py@@ -0,0 +1,167 @@+"""Per-turn tool composition policy shared by chat / quiz pipelines.++Owns the rule "given the user's composer toggles + the turn's context+flags, what tools should be enabled?". Lives outside any single pipeline+so chat and quiz can't disagree about which tools the user controls vs.+which the pipeline auto-mounts.++Two pieces:++* :data:`AUTO_MOUNTED_TOOLS` — tools whose mounting is owned by the+ pipeline (auto-on under specific conditions), not by user toggles.+ Membership here hides the tool from the user's composer / settings UI.+* :func:`compose_enabled_tools` — pure function that takes the user's+ toggled list + a :class:`ToolMountFlags` and returns the final, ordered+ enabled-tool list for one turn.++Callers resolve their own flags (chat checks selected KBs / source index+/ memory / notebooks; quiz reuses chat's policy verbatim).+"""++from __future__ import annotations++from collections.abc import Iterable+from dataclasses import dataclass+from typing import Any++from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES, USER_TOGGLEABLE_TOOL_NAMES+++# Tools whose mounting is owned by the pipeline (auto-on under specific+# context conditions), not by the user's composer toggles. Adding a tool+# here hides it from ``{tool_list}`` until its corresponding condition+# fires in :func:`compose_enabled_tools`.+AUTO_MOUNTED_TOOLS: frozenset[str] = frozenset(+ {+ "rag",+ "read_source",+ "read_memory",+ "write_memory",+ "list_notebook",+ "write_note",+ "ask_user",+ "web_fetch",+ "github",+ }+)+++def default_optional_tools(excluded: Iterable[str] = ()) -> list[str]:+ """Return the user-toggleable tool list (chat's default set).++ Sourced from :mod:`deeptutor.tools.builtin` so the /settings/tools UI+ and the pipelines can never disagree about which tools the user+ actually controls.+ """+ excluded_set = frozenset(excluded)+ return [+ name+ for name in USER_TOGGLEABLE_TOOL_NAMES+ if name in BUILTIN_TOOL_NAMES+ and name not in excluded_set+ and name not in AUTO_MOUNTED_TOOLS+ ]+++@dataclass(frozen=True)+class ToolMountFlags:+ """Per-turn flags that drive the auto-mount policy.++ Each capability resolves these from its own context (chat inspects+ ``UnifiedContext.knowledge_bases``, the source index, the memory+ service, the notebook manager; quiz reuses the same checks).+ """++ has_kb: bool = False+ has_sources: bool = False+ has_memory: bool = False+ has_notebooks: bool = False+++def compose_enabled_tools(+ *,+ registry: Any,+ requested_tools: list[str] | None,+ optional_whitelist: list[str],+ mount_flags: ToolMountFlags,+) -> list[str]:+ """Compose the per-turn enabled-tool list.++ Order:++ 1. User-toggled tools (filtered through the registry's ``get_enabled``+ so disabled tools never sneak in, and intersected with+ ``optional_whitelist`` so only legitimate composer toggles are+ respected).+ 2. Conditional auto-mounts (``rag`` if a KB is attached, ``read_source``+ if a source index exists, ``read_memory`` if memory has content,+ ``list_notebook`` + ``write_note`` if notebooks exist).+ 3. Always-on auto-mounts (``web_fetch``, ``github``, ``ask_user``).++ The result is ordered (no dedup is applied — caller's prerequisite is+ that ``optional_whitelist`` excludes ``AUTO_MOUNTED_TOOLS``, which+ :func:`default_optional_tools` guarantees).+ """+ composed: list[str] = [+ tool.name+ for tool in registry.get_enabled(requested_tools or [])+ if tool.name in optional_whitelist+ ]+ if mount_flags.has_kb:+ composed.append("rag")+ if mount_flags.has_sources:+ composed.append("read_source")+ if mount_flags.has_memory:+ composed.append("read_memory")+ if mount_flags.has_notebooks:+ composed.append("list_notebook")+ composed.append("write_note")+ composed.append("write_memory")+ composed.append("web_fetch")+ composed.append("github")+ composed.append("ask_user")+ return composed+++def user_has_memory() -> bool:+ """Whether the active user has any L3 memory content.++ Drives the auto-mount of ``read_memory``. Per-user paths resolve via+ the multi-user ContextVars the runtime sets up. Fails closed (returns+ ``False``) on any error so a broken memory directory doesn't surface+ a tool with no payload to read.+ """+ try:+ from deeptutor.services.memory import get_memory_store++ store = get_memory_store()+ return any(store.read_raw("L3", slot).strip() for slot in ("recent", "profile", "scope", "preferences"))+ except Exception:+ return False+++def user_has_notebooks() -> bool:+ """Whether the active user has at least one notebook.++ Auto-mount gate for ``list_notebook`` + ``write_note``. Same+ fail-closed posture as :func:`user_has_memory`.+ """+ try:+ from deeptutor.services.notebook import get_notebook_manager++ notebooks = get_notebook_manager().list_notebooks()+ return isinstance(notebooks, list) and any(+ nb for nb in notebooks if str(nb.get("id") or "").strip()+ )+ except Exception:+ return False+++__all__ = [+ "AUTO_MOUNTED_TOOLS",+ "ToolMountFlags",+ "compose_enabled_tools",+ "default_optional_tools",+ "user_has_memory",+ "user_has_notebooks",+]diff --git a/deeptutor/agents/question/__init__.py b/deeptutor/agents/question/__init__.pyindex 08efc594b..7e5927727 100644--- a/deeptutor/agents/question/__init__.py+++ b/deeptutor/agents/question/__init__.py@@ -1,31 +1,33 @@-"""-Question generation package.+"""Question generation package.-Exports are resolved lazily so lightweight imports such as-``deeptutor.agents.question.models`` do not eagerly pull in optional RAG dependencies.+The main entry point is :class:`~deeptutor.agents.question.pipeline.QuestionPipeline`.+Lightweight names (``FollowupAgent``, ``QuizTemplate``, ``QuizPair``, etc.)+are resolved lazily so callers that only need one symbol don't eagerly+import the full pipeline + its LLM dependencies."""from importlib import import_modulefrom typing import Any__all__ = [- "IdeaAgent",- "Generator",- "FollowupAgent",- "QuestionTemplate",- "QAPair","AgentCoordinator",+ "FollowupAgent",+ "QuestionPipeline",+ "QuizTemplate",+ "QuizPair",+ "QuizPlan",+ "QuizHistoryEntry",]def __getattr__(name: str) -> Any:- if name in {"IdeaAgent", "Generator", "FollowupAgent"}:- module = import_module("deeptutor.agents.question.agents")- return getattr(module, name)if name == "AgentCoordinator":module = import_module("deeptutor.agents.question.coordinator")return getattr(module, name)- if name in {"QuestionTemplate", "QAPair"}:- module = import_module("deeptutor.agents.question.models")+ if name == "FollowupAgent":+ module = import_module("deeptutor.agents.question.agents.followup_agent")+ return getattr(module, name)+ if name in {"QuestionPipeline", "QuizTemplate", "QuizPair", "QuizPlan", "QuizHistoryEntry"}:+ module = import_module("deeptutor.agents.question.pipeline")return getattr(module, name)raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/deeptutor/agents/question/agents/__init__.py b/deeptutor/agents/question/agents/__init__.pyindex 0a535fc19..b4430ad6c 100644--- a/deeptutor/agents/question/agents/__init__.py+++ b/deeptutor/agents/question/agents/__init__.py@@ -1,18 +1,18 @@-"""Question generation agents."""+"""Question generation sub-agents.++Currently only the standalone single-call ``FollowupAgent`` lives here —+the per-question / per-batch agents (idea_agent, generator) were+replaced by the single :mod:`deeptutor.agents.question.pipeline` module+during the Phase A → C refactor.+"""from importlib import import_modulefrom typing import Any-__all__ = ["IdeaAgent", "Generator", "FollowupAgent"]+__all__ = ["FollowupAgent"]def __getattr__(name: str) -> Any:- if name == "Generator":- module = import_module("deeptutor.agents.question.agents.generator")- return getattr(module, name)- if name == "IdeaAgent":- module = import_module("deeptutor.agents.question.agents.idea_agent")- return getattr(module, name)if name == "FollowupAgent":module = import_module("deeptutor.agents.question.agents.followup_agent")return getattr(module, name)diff --git a/deeptutor/agents/question/agents/generator.py b/deeptutor/agents/question/agents/generator.pydeleted file mode 100644index c9fd192e9..000000000--- a/deeptutor/agents/question/agents/generator.py+++ /dev/null@@ -1,492 +0,0 @@-#!/usr/bin/env python-"""-Generator - Generate Q-A pairs from QuestionTemplate in a single LLM call.-"""--from __future__ import annotations--import json-import re-from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.agents.question.models import QAPair, QuestionTemplate-from deeptutor.core.trace import build_trace_metadata, new_call_id-from deeptutor.runtime.registry.tool_registry import get_tool_registry-from deeptutor.services.prompt.language import append_language_directive---class Generator(BaseAgent):- """- Generate a question/answer pair from one template.-- The simplified pipeline injects the user's enabled tools as prompt guidance- and relies on the knowledge context already prepared upstream.- """-- def __init__(- self,- kb_name: str | None = None,- language: str = "en",- tool_flags: dict[str, bool] | None = None,- **kwargs: Any,- ) -> None:- super().__init__(- module_name="question",- agent_name="generator",- language=language,- **kwargs,- )- self.kb_name = kb_name- self.tool_flags = tool_flags or {}- self._tool_registry = get_tool_registry()-- MAX_PREVIOUS_QUESTIONS = 20-- async def process(- self,- template: QuestionTemplate,- user_topic: str = "",- preference: str = "",- history_context: str = "",- previous_questions: list[str] | None = None,- ) -> QAPair:- """- Generate one Q-A pair from a template in a single call.- """- available_tools = self._build_available_tools_text()- knowledge_context = str(template.metadata.get("knowledge_context", "")).strip()- prev_q_text = self._format_previous_questions(previous_questions)- payload = await self._generate_payload(- template=template,- user_topic=user_topic,- preference=preference,- history_context=history_context,- knowledge_context=knowledge_context,- available_tools=available_tools,- previous_questions=prev_q_text,- )- payload, validation = await self._validate_and_repair_payload(- template=template,- payload=payload,- user_topic=user_topic,- preference=preference,- history_context=history_context,- knowledge_context=knowledge_context,- available_tools=available_tools,- previous_questions=prev_q_text,- )-- return QAPair(- question_id=template.question_id,- question=payload.get("question", ""),- correct_answer=payload.get("correct_answer", ""),- explanation=payload.get("explanation", ""),- question_type=payload.get("question_type", template.question_type),- options=(payload.get("options") if isinstance(payload.get("options"), dict) else None),- concentration=template.concentration,- difficulty=template.difficulty,- validation=validation,- metadata={- "source": template.source,- "reference_question": template.reference_question,- "enabled_tools": self._enabled_tool_names(),- "available_tools": available_tools,- "knowledge_context": knowledge_context,- },- )-- def _build_available_tools_text(self) -> str:- enabled_tools = self._enabled_tool_names()- if not enabled_tools:- return "(no tools available)"- return self._tool_registry.build_prompt_text(- enabled_tools,- format="list",- language=self.language,- kb_name=self.kb_name or "",- )-- async def _generate_payload(- self,- template: QuestionTemplate,- user_topic: str,- preference: str,- history_context: str,- knowledge_context: str,- available_tools: str,- previous_questions: str = "",- ) -> dict[str, Any]:- system_prompt = append_language_directive(- self.get_prompt("system", ""),- self.language,- )- user_prompt_template = self.get_prompt("generate", "")- if not user_prompt_template:- user_prompt_template = (- "Template: {template}\n"- "User topic: {user_topic}\n"- "Preference: {preference}\n"- "Conversation context: {history_context}\n"- "Previously generated questions (do not repeat):\n{previous_questions}\n"- "Knowledge context: {knowledge_context}\n"- "Enabled tools: {available_tools}\n\n"- 'Return JSON {{"question_type":"","question":"","options":{{}},"correct_answer":"","explanation":""}}'- )-- template_dict = self._strip_template_knowledge_context(template)-- user_prompt = user_prompt_template.format(- template=json.dumps(template_dict, ensure_ascii=False, indent=2),- user_topic=user_topic,- preference=preference or "(none)",- history_context=history_context or "(none)",- previous_questions=previous_questions or "(none)",- knowledge_context=knowledge_context or "(none)",- available_tools=available_tools,- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- stage="generator_build_qa",- trace_meta=build_trace_metadata(- call_id=new_call_id(f"quiz-{template.question_id}"),- phase="generation",- label=f"Generate {template.question_id}",- call_kind="llm_generation",- trace_id=template.question_id,- question_id=template.question_id,- ),- ):- _chunks.append(_c)- response = "".join(_chunks)- payload = self._parse_json_like(response)-- if "question" not in payload or not str(payload.get("question", "")).strip():- payload["question"] = (- f"Based on {template.concentration}, answer this {template.difficulty} "- f"{template.question_type} question."- )- if "correct_answer" not in payload:- payload["correct_answer"] = "N/A"- if "explanation" not in payload:- payload["explanation"] = "N/A"- if "question_type" not in payload:- payload["question_type"] = template.question_type-- return payload-- async def _validate_and_repair_payload(- self,- template: QuestionTemplate,- payload: dict[str, Any],- user_topic: str,- preference: str,- history_context: str,- knowledge_context: str,- available_tools: str,- previous_questions: str = "",- ) -> tuple[dict[str, Any], dict[str, Any]]:- expected_type = self._normalize_question_type(template.question_type)- normalized = self._normalize_payload_shape(expected_type, payload)- issues = self._collect_payload_issues(expected_type, normalized)- repaired = False-- if issues:- repaired_payload = await self._repair_payload(- template=template,- payload=normalized,- issues=issues,- user_topic=user_topic,- preference=preference,- history_context=history_context,- knowledge_context=knowledge_context,- available_tools=available_tools,- previous_questions=previous_questions,- )- if repaired_payload:- candidate = self._normalize_payload_shape(expected_type, repaired_payload)- candidate_issues = self._collect_payload_issues(expected_type, candidate)- if not candidate_issues or len(candidate_issues) <= len(issues):- normalized = candidate- issues = candidate_issues- repaired = True-- validation = {- "requested_question_type": expected_type,- "schema_ok": not issues,- "repaired": repaired,- "issues": issues,- }- return normalized, validation-- async def _repair_payload(- self,- template: QuestionTemplate,- payload: dict[str, Any],- issues: list[str],- user_topic: str,- preference: str,- history_context: str,- knowledge_context: str,- available_tools: str,- previous_questions: str = "",- ) -> dict[str, Any]:- expected_type = self._normalize_question_type(template.question_type)- template_dict = self._strip_template_knowledge_context(template)- repair_prompt = (- "You are repairing an invalid quiz question JSON.\n\n"- f"QuestionTemplate:\n{json.dumps(template_dict, ensure_ascii=False, indent=2)}\n\n"- f"User topic:\n{user_topic or '(none)'}\n\n"- f"User preference:\n{preference or '(none)'}\n\n"- f"Conversation context:\n{history_context or '(none)'}\n\n"- f"Previously generated questions:\n{previous_questions or '(none)'}\n\n"- f"Knowledge context:\n{knowledge_context or '(none)'}\n\n"- f"Enabled tools:\n{available_tools}\n\n"- f"Invalid payload:\n{json.dumps(payload, ensure_ascii=False, indent=2)}\n\n"- f"Detected issues:\n{json.dumps(issues, ensure_ascii=False)}\n\n"- f"Rewrite the payload so it strictly matches question_type='{expected_type}'.\n"- "Hard rules:\n"- "- Keep the same concentration and difficulty intent.\n"- "- question_type must exactly match the template.\n"- "- If question_type is choice: provide exactly 4 options (A-D), and correct_answer must be the correct option key.\n"- "- If question_type is written: do not provide options, and the learner must write an explanation or short answer.\n"- "- If question_type is coding: do not provide options, and the learner must write code, pseudocode, or an algorithmic solution.\n"- "- For written/coding questions, never ask the learner to select, choose, or pick among options.\n"- "- Return JSON only with keys: question_type, question, options, correct_answer, explanation.\n"- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=repair_prompt,- system_prompt=append_language_directive(- "You fix malformed quiz payloads and return valid JSON only.",- self.language,- ),- response_format={"type": "json_object"},- stage="generator_repair_qa",- trace_meta=build_trace_metadata(- call_id=new_call_id(f"quiz-repair-{template.question_id}"),- phase="generation",- label=f"Repair question {self._humanize_question_id(template.question_id)} format",- call_kind="llm_generation",- trace_id=template.question_id,- question_id=template.question_id,- ),- ):- _chunks.append(_c)- response = "".join(_chunks)- return self._parse_json_like(response)-- @classmethod- def _normalize_question_type(cls, question_type: str) -> str:- normalized = str(question_type or "").strip().lower()- return normalized if normalized in {"choice", "written", "coding"} else "written"-- @staticmethod- def _normalize_markdown_paragraphs(text: str) -> str:- """Convert single newlines into paragraph breaks for markdown rendering.-- LLMs often emit single ``\n`` characters between logical paragraphs- (e.g. (1)… (2)…). In markdown a single newline is treated as a- soft-break / space, so the front-end renders everything as one dense- block. This helper turns isolated single newlines into ``\n\n`` so- that react-markdown creates separate ``<p>`` tags, while preserving- existing blank lines and structural markers (lists, code fences, etc.).- """- if not text:- return text- lines = text.split("\n")- result: list[str] = []- prev_blank = True- for line in lines:- stripped = line.rstrip()- if stripped == "":- result.append("")- prev_blank = True- continue- # Structural lines that should start a new paragraph- is_structural = (- stripped.startswith("```")- or stripped.startswith("|")- or stripped.startswith("#")- or stripped.startswith("-")- or stripped.startswith("*")- or stripped.startswith(">")- or re.match(r"^\s*\d+[.):]", stripped)- or re.match(r"^\s*[-*+]\s", stripped)- )- if not prev_blank and not is_structural:- # This line continues the previous paragraph in the raw text,- # but we want it as its own paragraph for display.- result.append("")- result.append(stripped)- prev_blank = False- return "\n".join(result)-- @classmethod- def _normalize_payload_shape(- cls,- expected_type: str,- payload: dict[str, Any],- ) -> dict[str, Any]:- normalized = dict(payload or {})- normalized["question_type"] = expected_type- normalized["question"] = cls._normalize_markdown_paragraphs(- str(normalized.get("question", "") or "").strip()- )- normalized["correct_answer"] = cls._normalize_markdown_paragraphs(- str(normalized.get("correct_answer", "") or "").strip()- )- normalized["explanation"] = cls._normalize_markdown_paragraphs(- str(normalized.get("explanation", "") or "").strip()- )-- raw_options = normalized.get("options")- if expected_type == "choice":- clean_options: dict[str, str] = {}- if isinstance(raw_options, dict):- for key, value in raw_options.items():- option_key = str(key or "").strip().upper()[:1]- option_value = str(value or "").strip()- if option_key in {"A", "B", "C", "D"} and option_value:- clean_options[option_key] = option_value- normalized["options"] = clean_options if clean_options else None- if normalized["correct_answer"] and clean_options:- answer_upper = normalized["correct_answer"].upper()- if answer_upper in clean_options:- normalized["correct_answer"] = answer_upper- else:- for key, value in clean_options.items():- if normalized["correct_answer"].strip().lower() == value.lower():- normalized["correct_answer"] = key- break- else:- normalized["options"] = None-- return normalized-- @classmethod- def _collect_payload_issues(- cls,- expected_type: str,- payload: dict[str, Any],- ) -> list[str]:- issues: list[str] = []- question = str(payload.get("question", "") or "")- correct_answer = str(payload.get("correct_answer", "") or "").strip()- options = payload.get("options")-- if expected_type == "choice":- option_keys = set(options.keys()) if isinstance(options, dict) else set()- if not option_keys:- issues.append("choice_missing_options")- elif option_keys != {"A", "B", "C", "D"}:- issues.append("choice_options_must_be_a_to_d")- if correct_answer.upper() not in {"A", "B", "C", "D"}:- issues.append("choice_correct_answer_must_be_option_key")- else:- if cls._payload_looks_like_choice(- question=question, correct_answer=correct_answer, options=options- ):- issues.append("non_choice_payload_looks_like_multiple_choice")-- if not question:- issues.append("missing_question")- if not correct_answer:- issues.append("missing_correct_answer")- if not str(payload.get("explanation", "") or "").strip():- issues.append("missing_explanation")- return issues-- @staticmethod- def _payload_looks_like_choice(- question: str,- correct_answer: str,- options: Any,- ) -> bool:- if isinstance(options, dict) and bool(options):- return True- lowered = question.lower()- if re.search(- r"\b(select|choose|pick|which of the following|which option|multiple[- ]choice)\b",- lowered,- ):- return True- if re.search(r"(^|\n)\s*[A-D][\.\):]\s+", question):- return True- return correct_answer.upper() in {"A", "B", "C", "D"}-- @staticmethod- def _humanize_question_id(question_id: str) -> str:- match = re.fullmatch(r"q_(\d+)", str(question_id or "").strip().lower())- if match:- return f"question {match.group(1)}"- return str(question_id or "question").strip() or "question"-- def _is_tool_enabled(self, tool_name: str) -> bool:- aliases = {- "rag": ["rag", "rag_tool"],- "web_search": ["web_search"],- "code_execution": ["code_execution", "write_code"],- }- keys = aliases.get(tool_name, [tool_name])- present = [key for key in keys if key in self.tool_flags]- if not present:- return True- return any(bool(self.tool_flags.get(key)) for key in present)-- def _enabled_tool_names(self) -> list[str]:- enabled_tools: list[str] = []- if self._is_tool_enabled("rag"):- enabled_tools.append("rag")- if self._is_tool_enabled("web_search"):- enabled_tools.append("web_search")- if self._is_tool_enabled("code_execution"):- enabled_tools.append("code_execution")- return enabled_tools-- @staticmethod- def _strip_template_knowledge_context(template: QuestionTemplate) -> dict[str, Any]:- """Strip knowledge_context from template metadata to avoid prompt duplication."""- template_dict = template.__dict__.copy()- if isinstance(template_dict.get("metadata"), dict):- template_dict["metadata"] = {- k: v for k, v in template_dict["metadata"].items() if k != "knowledge_context"- }- return template_dict-- @classmethod- def _format_previous_questions(cls, questions: list[str] | None) -> str:- if not questions:- return ""- capped = questions[-cls.MAX_PREVIOUS_QUESTIONS :]- return "\n".join(f"{i}. {q}" for i, q in enumerate(capped, 1))-- @staticmethod- def _parse_json_like(content: str) -> dict[str, Any]:- if not content or not content.strip():- return {}-- cleaned = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]", "", content.strip())- block_match = re.search(r"```(?:json)?\s*(.*?)```", cleaned, re.DOTALL)- if block_match:- cleaned = block_match.group(1).strip()-- try:- payload = json.loads(cleaned)- return payload if isinstance(payload, dict) else {}- except Exception:- pass-- obj_match = re.search(r"\{[\s\S]*\}", cleaned)- if obj_match:- try:- payload = json.loads(obj_match.group(0))- return payload if isinstance(payload, dict) else {}- except Exception:- return {}- return {}diff --git a/deeptutor/agents/question/agents/idea_agent.py b/deeptutor/agents/question/agents/idea_agent.pydeleted file mode 100644index 3535de639..000000000--- a/deeptutor/agents/question/agents/idea_agent.py+++ /dev/null@@ -1,310 +0,0 @@-#!/usr/bin/env python-"""-IdeaAgent - Generate candidate question directions from topic and preference.-"""--from __future__ import annotations--import json-from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.agents.question.models import QuestionTemplate-from deeptutor.core.trace import build_trace_metadata, new_call_id-from deeptutor.services.prompt.language import append_language_directive-from deeptutor.tools.rag_tool import rag_search-from deeptutor.utils.json_parser import parse_json_response--BATCH_SIZE = 5---class IdeaAgent(BaseAgent):- """- Generate candidate question ideas with knowledge grounding.- """-- def __init__(- self,- kb_name: str | None = None,- enable_rag: bool = True,- language: str = "en",- **kwargs: Any,- ) -> None:- super().__init__(- module_name="question",- agent_name="idea_agent",- language=language,- **kwargs,- )- self.kb_name = kb_name- self.enable_rag = enable_rag-- async def process(- self,- user_topic: str,- preference: str = "",- num_ideas: int = 5,- target_difficulty: str = "",- target_question_type: str = "",- existing_concentrations: list[str] | None = None,- batch_number: int | None = None,- attachments: list[Any] | None = None,- ) -> dict[str, Any]:- """- Build grounded question templates in a single pass.- """- batch_size = max(1, min(int(num_ideas or 1), BATCH_SIZE))- trace_id = f"batch-{batch_number}" if batch_number is not None else "ideation"- if self.enable_rag and self.kb_name:- retrievals = await self._retrieve_context(- user_topic,- trace_id=trace_id,- batch_number=batch_number,- )- knowledge_context = self._build_context(retrievals)- else:- retrievals = []- knowledge_context = "Retrieval disabled."-- templates = await self._generate_templates(- user_topic=user_topic,- preference=preference,- knowledge_context=knowledge_context,- num_ideas=batch_size,- target_difficulty=target_difficulty,- target_question_type=target_question_type,- existing_concentrations=existing_concentrations or [],- retrieval_queries=[- item.get("query", "") for item in retrievals if isinstance(item, dict)- ],- trace_id=trace_id,- batch_number=batch_number,- attachments=attachments,- )- return {- "templates": templates,- "retrievals": retrievals,- "knowledge_context": knowledge_context,- "batch_size": batch_size,- }-- async def _retrieve_context(- self,- user_topic: str,- trace_id: str,- batch_number: int | None = None,- ) -> list[dict[str, Any]]:- retrievals: list[dict[str, Any]] = []- call_id = new_call_id("quiz-rag")- trace_meta = build_trace_metadata(- call_id=call_id,- phase="ideation",- label=(- f"Retrieve knowledge (batch {batch_number})"- if batch_number is not None- else "Retrieve knowledge"- ),- call_kind="tool_lookup",- trace_id=trace_id,- batch=batch_number,- )- try:- await self._emit_trace_event(- {- "event": "tool_call",- "state": "running",- "tool_name": "rag",- "tool_args": {- "query": user_topic,- "kb_name": self.kb_name,- "only_need_context": True,- },- **trace_meta,- }- )- result = await rag_search(- query=user_topic,- kb_name=self.kb_name,- only_need_context=True,- )- await self._emit_trace_event(- {- "event": "tool_result",- "state": "complete",- "tool_name": "rag",- "result": result.get("answer", ""),- **trace_meta,- }- )- retrievals.append(- {- "query": user_topic,- "answer": result.get("answer", ""),- "provider": result.get("provider", ""),- }- )- except Exception as exc:- self.logger.warning(f"RAG retrieval failed for topic '{user_topic}': {exc}")- await self._emit_trace_event(- {- "event": "tool_result",- "state": "error",- "tool_name": "rag",- "result": str(exc),- **trace_meta,- }- )- retrievals.append({"query": user_topic, "answer": "", "error": str(exc)})- return retrievals-- def _build_context(self, retrievals: list[dict[str, Any]]) -> str:- sections: list[str] = []- for item in retrievals:- answer = item.get("answer", "")- if not answer:- continue- clipped = answer[:4000] + ("...[truncated]" if len(answer) > 4000 else "")- sections.append(f"=== Query: {item.get('query', '')} ===\n{clipped}")- return "\n\n".join(sections) if sections else "No retrieval context available."-- async def _generate_templates(- self,- user_topic: str,- preference: str,- knowledge_context: str,- num_ideas: int,- target_difficulty: str = "",- target_question_type: str = "",- existing_concentrations: list[str] | None = None,- retrieval_queries: list[str] | None = None,- trace_id: str = "ideation",- batch_number: int | None = None,- attachments: list[Any] | None = None,- ) -> list[QuestionTemplate]:- system_prompt = append_language_directive(- self.get_prompt("system", ""),- self.language,- )- idea_prompt = self.get_prompt("generate_ideas", "")- if not idea_prompt:- idea_prompt = (- "Topic: {user_topic}\n"- "Preference: {preference}\n"- "Existing concentrations:\n{existing_concentrations}\n"- "Knowledge context:\n{knowledge_context}\n\n"- "Generate {num_ideas} candidate question ideas.\n"- 'Return JSON {{"ideas":[{{"concentration":"","question_type":"","difficulty":"","rationale":""}}]}}'- )-- constraints: list[str] = []- if target_difficulty:- constraints.append(f"Target difficulty: {target_difficulty}")- if target_question_type:- constraints.append(f"Target question type: {target_question_type}")- effective_preference = preference or "(none)"- if constraints:- effective_preference = f"{effective_preference}\n" + "\n".join(constraints)-- user_prompt = idea_prompt.format(- user_topic=user_topic,- preference=effective_preference,- knowledge_context=knowledge_context,- num_ideas=num_ideas,- existing_concentrations=json.dumps(- existing_concentrations or [], ensure_ascii=False, indent=2- ),- )- try:- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- stage="idea_generate_templates",- attachments=attachments,- trace_meta=build_trace_metadata(- call_id=new_call_id("quiz-ideation"),- phase="ideation",- label=(- f"Generate templates (batch {batch_number})"- if batch_number is not None- else "Generate templates"- ),- call_kind="llm_generation",- trace_id=trace_id,- batch=batch_number,- ),- ):- _chunks.append(_c)- response = "".join(_chunks)- payload = parse_json_response(response, logger_instance=self.logger)- if isinstance(payload, list):- payload = {"ideas": payload}- elif not isinstance(payload, dict):- payload = {"ideas": []}- ideas_raw = payload.get("ideas", [])- if not isinstance(ideas_raw, list):- ideas_raw = []- except Exception as exc:- self.logger.warning(f"Idea generation failed, fallback used: {exc}")- ideas_raw = []-- seen = {item.strip().lower() for item in (existing_concentrations or []) if item}- retrieval_queries = retrieval_queries or []- templates: list[QuestionTemplate] = []- for idx, item in enumerate(ideas_raw, 1):- if not isinstance(item, dict):- continue- concentration = str(item.get("concentration", "")).strip()- normalized_concentration = concentration.lower()- if not concentration or normalized_concentration in seen:- continue- seen.add(normalized_concentration)- resolved_question_type = (- target_question_type- or str(item.get("question_type", "written")).strip()- or "written"- )- resolved_difficulty = (- target_difficulty or str(item.get("difficulty", "medium")).strip() or "medium"- )- templates.append(- QuestionTemplate(- question_id=f"q_{idx}",- concentration=concentration,- question_type=resolved_question_type,- difficulty=resolved_difficulty,- source="custom",- metadata={- "idea_id": item.get("idea_id", f"idea_{idx}"),- "rationale": str(item.get("rationale", "")).strip(),- "knowledge_context": knowledge_context[:6000],- "retrieval_queries": retrieval_queries,- "requested_question_type": target_question_type or None,- "requested_difficulty": target_difficulty or None,- },- )- )- if len(templates) >= num_ideas:- break-- if len(templates) < num_ideas:- for idx in range(len(templates) + 1, num_ideas + 1):- fallback_concentration = f"{user_topic} - aspect {idx}"- templates.append(- QuestionTemplate(- question_id=f"q_{idx}",- concentration=fallback_concentration,- question_type=target_question_type or "written",- difficulty=target_difficulty or "medium",- source="custom",- metadata={- "idea_id": f"idea_{idx}",- "rationale": "Fallback template generated due to parsing issues.",- "knowledge_context": knowledge_context[:6000],- "retrieval_queries": retrieval_queries,- },- )- )-- return templatesdiff --git a/deeptutor/agents/question/coordinator.py b/deeptutor/agents/question/coordinator.pyindex 8fb0eb90e..a61a39153 100644--- a/deeptutor/agents/question/coordinator.py+++ b/deeptutor/agents/question/coordinator.py@@ -1,468 +1,242 @@-#!/usr/bin/env python-"""-Question Coordinator+"""Compatibility adapter for legacy question-generation entry points.-Simplified architecture:-1) Template generation in batches (max 5 per batch)-2) Single-pass question generation per template+The old ``AgentCoordinator`` implementation was replaced by+``QuestionPipeline``. A few API/tool modules still import the coordinator+name, so this module preserves that surface while delegating all real work+to the new pipeline."""from __future__ import annotations-from collections.abc import Callable-from datetime import datetime-import json+import asyncio+from collections.abc import Awaitable, Callable+import inspectimport loggingfrom pathlib import Pathfrom typing import Any-from deeptutor.agents.question.agents.generator import Generator-from deeptutor.agents.question.agents.idea_agent import BATCH_SIZE, IdeaAgent-from deeptutor.agents.question.models import QAPair, QuestionTemplate-from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.agents.question.mimic_source import parse_exam_paper_to_templates+from deeptutor.agents.question.pipeline import QuestionPipeline+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEvent+from deeptutor.core.stream_bus import StreamBusfrom deeptutor.services.path_service import get_path_service-from deeptutor.tools.question.pdf_parser import parse_pdf_with_mineru-from deeptutor.tools.question.question_extractor import extract_questions_from_paper+from deeptutor.services.settings.interface_settings import get_ui_language++logger = logging.getLogger(__name__)++WsCallback = Callable[[dict[str, Any]], Awaitable[None] | None]class AgentCoordinator:- """Coordinate topic-driven and paper-driven quiz generation."""+ """Legacy facade backed by :class:`QuestionPipeline`.++ New code should prefer ``DeepQuestionCapability`` or ``QuestionPipeline``+ directly. This class exists so older WebSocket routes and the+ ``tools.question.exam_mimic`` helper keep importing and running.+ """def __init__(self,+ *,api_key: str | None = None,base_url: str | None = None,api_version: str | None = None,kb_name: str | None = None,+ language: str | None = None,output_dir: str | None = None,- language: str = "en",- tool_flags_override: dict[str, bool] | None = None,- enable_idea_rag: bool = True,+ enabled_tools: list[str] | None = None,+ enable_idea_rag: bool | None = None,) -> None:- self.kb_name = kb_name+ # The new pipeline reads provider settings from the shared config+ # service. Keep these attributes only for compatibility/debugging.+ self.api_key = api_key+ self.base_url = base_url+ self.api_version = api_version+ self.kb_name = (kb_name or "").strip() or None+ self.enable_idea_rag = True if enable_idea_rag is None else bool(enable_idea_rag)+ self.language = language or get_ui_language(default="en")self.output_dir = output_dir- self.language = language- self._api_key = api_key- self._base_url = base_url- self._api_version = api_version- self._ws_callback: Callable | None = None- self._trace_callback: Callable | None = None- self.enable_idea_rag = enable_idea_rag-- self.config = load_config_with_main("main.yaml", PROJECT_ROOT)- log_dir = self.config.get("paths", {}).get("user_log_dir") or self.config.get(- "logging", {}- ).get("log_dir")- self.logger = logging.getLogger(__name__)+ self.enabled_tools = list(enabled_tools or [])+ self._ws_callback: WsCallback | None = None- question_cfg = self.config.get("capabilities", {}).get("question", {})- generation_cfg = question_cfg.get("generation", {})- default_tool_flags = generation_cfg.get(- "tools",- {"web_search": True, "rag": True, "code_execution": True},- )- self.tool_flags = (- tool_flags_override if isinstance(tool_flags_override, dict) else default_tool_flags- )- self._current_batch_dir: Path | None = None-- def set_ws_callback(self, callback: Callable) -> None:+ def set_ws_callback(self, callback: WsCallback | None) -> None:self._ws_callback = callback- def set_trace_callback(self, callback: Callable | None) -> None:- self._trace_callback = callback-- async def _send_ws_update(self, update_type: str, data: dict[str, Any]) -> None:- if self._ws_callback:- try:- await self._ws_callback({"type": update_type, **data})- except Exception as exc:- self.logger.debug(f"WS update failed: {exc}")-- def _create_idea_agent(self) -> IdeaAgent:- agent = IdeaAgent(- kb_name=self.kb_name,- enable_rag=self.enable_idea_rag,- language=self.language,- api_key=self._api_key,- base_url=self._base_url,- api_version=self._api_version,- )- agent.set_trace_callback(self._trace_callback)- return agent-- def _create_generator(self) -> Generator:- agent = Generator(- kb_name=self.kb_name,- language=self.language,- tool_flags=self.tool_flags,- api_key=self._api_key,- base_url=self._base_url,- api_version=self._api_version,- )- agent.set_trace_callback(self._trace_callback)- return agent-async def generate_from_topic(self,+ *,user_topic: str,- preference: str,- num_questions: int,+ num_questions: int = 1,difficulty: str = "",- question_type: str = "",- history_context: str = "",- attachments: list[Any] | None = None,+ question_types: list[str] | None = None,+ per_type_counts: dict[str, int] | None = None,) -> dict[str, Any]:- self._current_batch_dir = self._create_batch_dir("custom")- requested = max(1, int(num_questions or 1))- idea_agent = self._create_idea_agent()- templates: list[QuestionTemplate] = []- batch_trace: list[dict[str, Any]] = []- existing_concentrations: list[str] = []-- normalized_difficulty = difficulty.strip().lower()- normalized_question_type = question_type.strip().lower()- target_difficulty = (- normalized_difficulty- if normalized_difficulty and normalized_difficulty != "auto"- else ""- )- target_question_type = (- normalized_question_type- if normalized_question_type and normalized_question_type != "auto"- else ""- )-- batch_number = 0- while len(templates) < requested:- batch_number += 1- batch_size = min(BATCH_SIZE, requested - len(templates))- await self._send_ws_update(- "progress",- {- "stage": "ideation",- "status": "running",- "batch": batch_number,- "current": len(templates),- "total": requested,- "batch_size": batch_size,- },- )-- idea_result = await idea_agent.process(- user_topic=user_topic,- preference=preference,- num_ideas=batch_size,- target_difficulty=target_difficulty,- target_question_type=target_question_type,- existing_concentrations=existing_concentrations,- batch_number=batch_number,- attachments=attachments,- )- batch_templates = idea_result.get("templates", [])- if not isinstance(batch_templates, list):- batch_templates = []-- for template in batch_templates:- if not isinstance(template, QuestionTemplate):- continue- template.question_id = f"q_{len(templates) + 1}"- templates.append(template)- existing_concentrations.append(template.concentration)-- batch_trace.append(- {- "batch": batch_number,- "requested": batch_size,- "generated": len(batch_templates),- "knowledge_context": idea_result.get("knowledge_context", ""),- }- )- await self._send_ws_update(- "templates_ready",- {- "stage": "ideation",- "batch": batch_number,- "count": len(batch_templates),- "generated_total": len(templates),- "requested_total": requested,- "templates": [t.__dict__ for t in batch_templates],- },- )-- if not batch_templates:- self.logger.warning("Template generation returned an empty batch; stopping early.")- break-- await self._send_ws_update(- "progress",- {- "stage": "ideation",- "status": "complete",- "current": len(templates),- "total": requested,- "batches": batch_number,- },- )-- qa_pairs = await self._generation_loop(- templates=templates[:requested],- user_topic=user_topic,- preference=preference,- history_context=history_context,- )- return self._build_summary(- source="topic",- requested=requested,- templates=templates[:requested],- qa_pairs=qa_pairs,- trace={"batches": batch_trace},- )+ """Generate a quiz from a topic using the new pipeline."""++ context = self._build_context(user_message=user_topic)+ pipeline = self._build_pipeline()+ stream = self._new_stream_bus()+ result = await self._run_with_forwarding(+ stream,+ pipeline.run(+ context=context,+ user_message=user_topic,+ num_questions=max(1, int(num_questions or 1)),+ difficulty=difficulty,+ question_types=question_types or [],+ per_type_counts=per_type_counts or {},+ stream=stream,+ ),+ )+ return self._legacy_summary(result)async def generate_from_exam(self,+ *,exam_paper_path: str,- max_questions: int,+ max_questions: int = 10,paper_mode: str = "upload",- history_context: str = "",) -> dict[str, Any]:- if self._current_batch_dir is None:- self._current_batch_dir = self._create_batch_dir("mimic")- templates, parse_trace = await self._parse_exam_to_templates(- exam_paper_path=exam_paper_path,- max_questions=max_questions,- paper_mode=paper_mode,- )- for idx, template in enumerate(templates, 1):- template.question_id = f"q_{idx}"-- await self._send_ws_update(- "templates_ready",- {- "stage": "ideation",- "count": len(templates),- "generated_total": len(templates),- "requested_total": max_questions,- "templates": [t.__dict__ for t in templates],- },- )-- qa_pairs = await self._generation_loop(- templates=templates,- user_topic="",- preference="",- history_context=history_context,- )- return self._build_summary(- source="exam",- requested=max_questions,- templates=templates,- qa_pairs=qa_pairs,- trace=parse_trace,- )+ """Generate mimic questions from an uploaded PDF or parsed paper dir."""- async def _generation_loop(- self,- templates: list[QuestionTemplate],- user_topic: str,- preference: str,- history_context: str = "",- ) -> list[dict[str, Any]]:- generator = self._create_generator()- results: list[dict[str, Any]] = []- total = len(templates)- generated_questions: list[str] = []+ paper_path = str(exam_paper_path or "").strip()+ if not paper_path:+ return {"success": False, "error": "exam_paper_path is required."}- for idx, template in enumerate(templates, 1):- await self._send_ws_update(- "question_update",+ try:+ await self._emit_callback({- "question_id": template.question_id,- "status": "generating",- "current": idx,- "total": total,- },- )-- success = True- try:- qa_pair = await generator.process(- template=template,- user_topic=user_topic,- preference=preference,- history_context=history_context,- previous_questions=generated_questions or None,- )- except Exception as exc:- success = False- self.logger.warning(f"Generation failed for {template.question_id}: {exc}")- qa_pair = QAPair(- question_id=template.question_id,- question=f"[Generation failed] {template.concentration}",- correct_answer="N/A",- explanation=str(exc),- question_type=template.question_type,- concentration=template.concentration,- difficulty=template.difficulty,- metadata={"error": str(exc)},- )-- result = {- "template": template.__dict__,- "qa_pair": qa_pair.__dict__,- "success": success,- }- results.append(result)-- # Track successfully generated question text for diversity enforcement- if success and qa_pair.question:- generated_questions.append(qa_pair.question)-- await self._send_ws_update(- "result",- {- "question_id": template.question_id,- "index": idx - 1,- "question": qa_pair.__dict__,- "success": success,- },+ "type": "status",+ "stage": "parsing",+ "content": "Extracting question templates from exam paper...",+ })- await self._send_ws_update(- "progress",- {- "stage": "generation",- "status": "running",- "current": idx,- "total": total,- "question_id": template.question_id,- },+ output_dir = self._resolve_output_dir()+ templates, trace = await parse_exam_paper_to_templates(+ paper_path,+ max_questions=max(1, int(max_questions or 1)),+ paper_mode=paper_mode,+ output_dir=output_dir,)+ if not templates:+ return {+ "success": False,+ "error": "No questions could be extracted from the exam paper.",+ "template_count": 0,+ "results": [],+ "trace": trace,+ }- await self._send_ws_update(- "progress",- {"stage": "complete", "completed": len(results), "total": total},- )- return results-- async def _parse_exam_to_templates(- self,- exam_paper_path: str,- max_questions: int,- paper_mode: str,- ) -> tuple[list[QuestionTemplate], dict[str, Any]]:- await self._send_ws_update("progress", {"stage": "parsing", "status": "running"})-- paper_path = Path(exam_paper_path)- output_base = (- self._current_batch_dir- or (Path(self.output_dir) if self.output_dir else None)- or get_path_service().get_question_dir()- )- output_base.mkdir(parents=True, exist_ok=True)-- if paper_mode == "parsed":- working_dir = paper_path- else:- parse_success = parse_pdf_with_mineru(str(paper_path), str(output_base))- if not parse_success:- raise RuntimeError("Failed to parse exam paper with MinerU")- subdirs = sorted(- [d for d in output_base.iterdir() if d.is_dir()],- key=lambda d: d.stat().st_mtime,- reverse=True,+ context = self._build_context(user_message="Mimic this exam paper")+ pipeline = self._build_pipeline()+ stream = self._new_stream_bus()+ result = await self._run_with_forwarding(+ stream,+ pipeline.run(+ context=context,+ user_message=context.user_message,+ num_questions=len(templates),+ templates_override=templates,+ stream=stream,+ ),)- if not subdirs:- raise RuntimeError("No parsed exam directory found after MinerU parsing")- working_dir = subdirs[0]-- await self._send_ws_update(- "progress",- {"stage": "extracting", "status": "running", "paper_dir": str(working_dir)},+ summary = self._legacy_summary(result)+ summary["trace"] = trace+ return summary+ except Exception as exc:+ logger.exception("Legacy AgentCoordinator.generate_from_exam failed: %s", exc)+ return {"success": False, "error": str(exc), "results": []}++ def _build_context(self, *, user_message: str) -> UnifiedContext:+ kb_name = self._active_kb_name()+ return UnifiedContext(+ session_id=self._session_id(),+ user_message=user_message,+ enabled_tools=self.enabled_tools,+ active_capability="deep_question",+ knowledge_bases=[kb_name] if kb_name else [],+ language=self.language,)- json_files = list(working_dir.glob("*_questions.json"))- if not json_files:- extract_success = extract_questions_from_paper(str(working_dir), output_dir=None)- if not extract_success:- raise RuntimeError("Failed to extract questions from parsed exam")- json_files = list(working_dir.glob("*_questions.json"))- if not json_files:- raise RuntimeError("Question extraction output not found")+ def _build_pipeline(self) -> QuestionPipeline:+ return QuestionPipeline(+ language=self.language,+ kb_name=self._active_kb_name(),+ enabled_tools=self.enabled_tools,+ )- with open(json_files[0], encoding="utf-8") as f:- payload = json.load(f)- questions = payload.get("questions", [])- if max_questions > 0:- questions = questions[:max_questions]+ def _active_kb_name(self) -> str | None:+ return self.kb_name if self.enable_idea_rag else None- templates: list[QuestionTemplate] = []- for i, item in enumerate(questions, 1):- if not isinstance(item, dict):- continue- q_text = str(item.get("question_text", "")).strip()- if not q_text:- continue- templates.append(- QuestionTemplate(- question_id=f"q_{i}",- concentration=q_text[:240],- question_type=str(item.get("question_type", "written")).lower(),- difficulty="medium",- source="mimic",- reference_question=q_text,- reference_answer=str(item.get("answer", "")).strip() or None,- metadata={- "question_number": item.get("question_number", str(i)),- "images": item.get("images", []),- },- )- )-- await self._send_ws_update(- "progress",- {"stage": "extracting", "status": "complete", "templates": len(templates)},- )- return templates, {- "paper_dir": str(working_dir),- "question_file": str(json_files[0]),- "template_count": len(templates),- }+ def _new_stream_bus(self) -> StreamBus:+ return StreamBus()- def _build_summary(+ async def _run_with_forwarding(self,- source: str,- requested: int,- templates: list[QuestionTemplate],- qa_pairs: list[dict[str, Any]],- trace: dict[str, Any],+ stream: StreamBus,+ pipeline_call: Awaitable[dict[str, Any]],) -> dict[str, Any]:- completed = sum(1 for item in qa_pairs if item.get("success"))- failed = len(qa_pairs) - completed- summary = {- "success": completed > 0 and failed == 0,- "source": source,- "requested": requested,- "template_count": len(templates),- "completed": completed,- "failed": failed,- "templates": [t.__dict__ for t in templates],- "results": qa_pairs,- "trace": trace,- "batch_dir": str(self._current_batch_dir) if self._current_batch_dir else None,- }- self._persist_summary(summary)+ """Run a pipeline coroutine and forward its stream events if possible."""++ forwarder = asyncio.create_task(self._forward_stream(stream))+ try:+ return await pipeline_call+ finally:+ await stream.close()+ try:+ await forwarder+ except Exception:+ logger.debug("Question stream forwarding task failed", exc_info=True)++ async def _forward_stream(self, stream: StreamBus) -> None:+ async for event in stream.subscribe():+ await self._emit_callback(self._event_payload(event))++ @staticmethod+ def _event_payload(event: StreamEvent) -> dict[str, Any]:+ payload = event.to_dict()+ if event.type.value == "result":+ payload.setdefault("content", event.metadata.get("response", ""))+ return payload++ async def _emit_callback(self, payload: dict[str, Any]) -> None:+ if self._ws_callback is None:+ return+ maybe_awaitable = self._ws_callback(payload)+ if inspect.isawaitable(maybe_awaitable):+ await maybe_awaitable++ def _resolve_output_dir(self) -> Path:+ if self.output_dir:+ return Path(self.output_dir)+ return get_path_service().get_question_dir() / "mimic_papers"++ def _session_id(self) -> str:+ if self.output_dir:+ return Path(self.output_dir).name or "legacy-question"+ return "legacy-question"++ @staticmethod+ def _legacy_summary(result: dict[str, Any]) -> dict[str, Any]:+ summary = dict(result.get("summary") or {})+ if not summary:+ summary["success"] = False+ summary["results"] = []+ summary.setdefault("response", result.get("response", ""))+ summary.setdefault("mode", result.get("mode", "custom"))+ if "metadata" in result:+ summary.setdefault("metadata", result["metadata"])+ summary.setdefault("results", [])+ for item in summary["results"]:+ if isinstance(item, dict) and "success" not in item:+ metadata = item.get("metadata") if isinstance(item.get("metadata"), dict) else {}+ item["success"] = not bool(metadata.get("error"))+ summary.setdefault("requested", summary.get("template_count", 0))+ summary.setdefault("completed", 0)+ summary.setdefault("failed", 0)+ summary.setdefault("success", bool(summary.get("completed")))return summary- def _create_batch_dir(self, prefix: str) -> Path:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- base = Path(self.output_dir) if self.output_dir else get_path_service().get_question_dir()- batch_dir = base / f"{prefix}_{timestamp}"- batch_dir.mkdir(parents=True, exist_ok=True)- return batch_dir- def _persist_summary(self, summary: dict[str, Any]) -> None:- if self._current_batch_dir is None:- return- summary_file = self._current_batch_dir / "summary.json"- with open(summary_file, "w", encoding="utf-8") as f:- json.dump(summary, f, ensure_ascii=False, indent=2)+__all__ = ["AgentCoordinator"]diff --git a/deeptutor/agents/question/example.py b/deeptutor/agents/question/example.pydeleted file mode 100644index 6fbdd26e7..000000000--- a/deeptutor/agents/question/example.py+++ /dev/null@@ -1,98 +0,0 @@-#!/usr/bin/env python-"""-Example script that demonstrates how to use the Agent coordinator.-"""--import asyncio-import json-import logging-from pathlib import Path--from deeptutor.agents.question import AgentCoordinator--logging.basicConfig(level=logging.WARNING, force=True)-for logger_name in ["openai", "httpx", "httpcore"]:- logger = logging.getLogger(logger_name)- logger.setLevel(logging.WARNING)- logger.propagate = False--project_root = Path(__file__).resolve().parents[3]---async def run_single_example(coordinator: AgentCoordinator):- """Generate a single question."""- requirement = {- "knowledge_point": "Lagrange multipliers",- "difficulty": "medium",- "question_type": "written",- "additional_requirements": "Focus on a computational exercise that demonstrates how to apply Lagrange multipliers.",- }-- result = await coordinator.generate_question(requirement)-- print("\n" + "=" * 80)- print("📊 Single-question result")- print("=" * 80)-- if result.get("success"):- question = result["question"]- validation = result["validation"]-- print(f"\n✓ Success in {result['rounds']} round(s)")- print(f"\nType: {question.get('question_type')}")- print(f"\nQuestion:\n{question.get('question')}")-- if question.get("options"):- print("\nOptions:")- for key, value in question["options"].items():- print(f" {key}. {value}")-- print(f"\nCorrect answer: {question.get('correct_answer')}")- print(f"\nExplanation:\n{question.get('explanation')}")-- print(f"\nValidation decision: {validation.get('decision')}")- print(f"Validation reasoning: {validation.get('reasoning')}")- else:- error_type = result.get("error")- if error_type == "task_rejected":- print("\n🚫 Task rejected")- print(f"Reason: {result.get('reason')}")- print(- "\n💡 Tip: try a different knowledge point or ensure the knowledge base contains supporting material."- )- else:- print(f"\n✗ Failed: {error_type}")- if result.get("last_question"):- print("\nLast attempted question:")- print(json.dumps(result["last_question"], ensure_ascii=False, indent=2))- if result.get("last_validation"):- print("\nLast validation result:")- print(json.dumps(result["last_validation"], ensure_ascii=False, indent=2))---async def run_batch_example(coordinator: AgentCoordinator):- """Generate multiple questions from a natural-language prompt."""- prompt = (- "Medium questions on Multivariable Functions, Limits and Continuity, and Differentiation"- )-- batch_result = await coordinator.generate_questions_from_prompt(- requirement_text=prompt, num_questions=3- )-- print("\n" + "=" * 80)- print("📦 Batch generation result")- print("=" * 80)- print(json.dumps(batch_result, ensure_ascii=False, indent=2))---async def main():- """Entry point for the example script."""- coordinator = AgentCoordinator(max_rounds=10, kb_name="math2211", output_dir="./output")-- # await run_single_example(coordinator)- await run_batch_example(coordinator)---if __name__ == "__main__":- asyncio.run(main())diff --git a/deeptutor/agents/question/history.py b/deeptutor/agents/question/history.pynew file mode 100644index 000000000..ec569bd6d--- /dev/null+++ b/deeptutor/agents/question/history.py@@ -0,0 +1,105 @@+"""Quiz history loader — surfaces prior quiz items in the same session.++Used by :class:`QuestionPipeline` so the Explore phase can articulate+which topics have already been tested, which the learner got wrong, and+how the next round should avoid duplication / optionally target weak+spots.++Single public entry point:++* :func:`load_session_quiz_history` — async, takes ``session_id`` and an+ upper bound, returns a chronological list of+ :class:`~deeptutor.agents.question.pipeline.QuizHistoryEntry`.++Source of truth: the ``notebook_entries`` table (populated by+``POST /sessions/{id}/quiz-results``). Messages are *not* consulted —+they're free-text and would require fragile parsing.++Fails closed: any error returns an empty list (so the pipeline simply+treats the session as if no quizzes had been asked before).+"""++from __future__ import annotations++import logging+from typing import Any++from deeptutor.agents.question.pipeline import QuizHistoryEntry++logger = logging.getLogger(__name__)++DEFAULT_MAX_ENTRIES = 30+++async def load_session_quiz_history(+ session_id: str,+ *,+ max_entries: int = DEFAULT_MAX_ENTRIES,+) -> list[QuizHistoryEntry]:+ """Return prior quiz items for ``session_id`` in chronological order.++ "Chronological" means oldest-first in the returned list, even though+ the underlying table sorts DESC for pagination — the order matters+ for the LLM prompt (which reads top-to-bottom as "this is what we've+ covered so far").++ The boolean ``is_correct`` field on notebook entries defaults to 0+ even when no answer was submitted; we treat an empty ``user_answer``+ as "unanswered" and surface ``is_correct=None`` for it so the explore+ prompt can render "unknown" instead of misleading "incorrect".+ """+ if not session_id or max_entries <= 0:+ return []+ try:+ from deeptutor.services.session.sqlite_store import get_sqlite_session_store++ store = get_sqlite_session_store()+ result = await store.list_notebook_entries(+ session_id=session_id,+ limit=max(1, int(max_entries)),+ offset=0,+ )+ except Exception:+ logger.warning(+ "Failed to load quiz history for session %s", session_id, exc_info=True+ )+ return []++ items: list[dict[str, Any]] = list(result.get("items") or [])+ # Store returns DESC, but rows with identical ``created_at`` (a single+ # upsert call writes all rows at the same timestamp) come back in+ # insertion order — so a plain reverse() would still flip them. Sort+ # explicitly by (created_at ASC, id ASC) so the prompt reads earliest+ # → latest, deterministically.+ items.sort(key=lambda r: (float(r.get("created_at") or 0.0), int(r.get("id") or 0)))++ entries: list[QuizHistoryEntry] = []+ for raw in items:+ if not isinstance(raw, dict):+ continue+ question = str(raw.get("question") or "").strip()+ if not question:+ continue+ user_answer = str(raw.get("user_answer") or "").strip()+ correct_answer = str(raw.get("correct_answer") or "").strip()+ # The DB column is a 0/1 INTEGER with default 0 — we can't tell+ # "answered wrong" from "not answered yet" purely from is_correct.+ # The user_answer field is authoritative for "did they attempt this".+ if not user_answer:+ is_correct: bool | None = None+ else:+ is_correct = bool(raw.get("is_correct"))+ entries.append(+ QuizHistoryEntry(+ question=question,+ question_type=str(raw.get("question_type") or "").strip(),+ correct_answer=correct_answer,+ user_answer=user_answer,+ is_correct=is_correct,+ turn_id=str(raw.get("turn_id") or "").strip(),+ )+ )+ return entries+++__all__ = ["DEFAULT_MAX_ENTRIES", "load_session_quiz_history"]diff --git a/deeptutor/agents/question/mimic_source.py b/deeptutor/agents/question/mimic_source.pynew file mode 100644index 000000000..25c0fdd04--- /dev/null+++ b/deeptutor/agents/question/mimic_source.py@@ -0,0 +1,127 @@+"""Exam-paper → QuizTemplate adapter for mimic mode.++Wraps the (sync, IO-heavy) MinerU PDF parser + the rule-based question+extractor so the capability layer can hand mimic templates to+:class:`QuestionPipeline` via its ``templates_override`` entry.++This module is intentionally narrow: it ONLY converts a PDF (or a+previously-parsed working directory) into a list of+:class:`QuizTemplate`. Streaming progress, prompt assembly, LLM calls,+and result emission all stay in the pipeline / capability layers.+"""++from __future__ import annotations++import asyncio+import json+import logging+from pathlib import Path++from deeptutor.agents.question.pipeline import QuizTemplate+from deeptutor.tools.question.pdf_parser import parse_pdf_with_mineru+from deeptutor.tools.question.question_extractor import extract_questions_from_paper++logger = logging.getLogger(__name__)+++_DEFAULT_DIFFICULTY = "medium"+_DEFAULT_QUESTION_TYPE = "written"+_TOPIC_CLIP_CHARS = 240+++async def parse_exam_paper_to_templates(+ paper_path: str | Path,+ *,+ max_questions: int,+ paper_mode: str,+ output_dir: str | Path,+) -> tuple[list[QuizTemplate], dict[str, str]]:+ """Resolve an exam paper into a list of mimic-mode ``QuizTemplate``\\ s.++ ``paper_mode``:++ * ``"upload"`` — ``paper_path`` is a freshly-uploaded PDF; MinerU+ parses it under ``output_dir`` and we pick the newest subdir.+ * ``"parsed"`` — ``paper_path`` is a previously-parsed working dir+ (already contains the MinerU output); skip the parse step.++ Returns ``(templates, trace)``. ``trace`` carries paths + counts for+ inclusion in the final ``stream.result`` envelope. Raises+ ``RuntimeError`` when parsing or extraction fails — the caller emits+ a user-facing error.+ """+ return await asyncio.to_thread(+ _parse_sync,+ Path(paper_path),+ int(max_questions),+ str(paper_mode),+ Path(output_dir),+ )+++def _parse_sync(+ paper_path: Path,+ max_questions: int,+ paper_mode: str,+ output_base: Path,+) -> tuple[list[QuizTemplate], dict[str, str]]:+ output_base.mkdir(parents=True, exist_ok=True)++ if paper_mode == "parsed":+ working_dir = paper_path+ else:+ ok = parse_pdf_with_mineru(str(paper_path), str(output_base))+ if not ok:+ raise RuntimeError("Failed to parse exam paper with MinerU")+ subdirs = sorted(+ [d for d in output_base.iterdir() if d.is_dir()],+ key=lambda d: d.stat().st_mtime,+ reverse=True,+ )+ if not subdirs:+ raise RuntimeError("No parsed exam directory found after MinerU parsing")+ working_dir = subdirs[0]++ json_files = list(working_dir.glob("*_questions.json"))+ if not json_files:+ ok = extract_questions_from_paper(str(working_dir), output_dir=None)+ if not ok:+ raise RuntimeError("Failed to extract questions from parsed exam")+ json_files = list(working_dir.glob("*_questions.json"))+ if not json_files:+ raise RuntimeError("Question extraction output not found")++ with json_files[0].open(encoding="utf-8") as fh:+ payload = json.load(fh)+ questions = payload.get("questions") or []+ if max_questions > 0:+ questions = questions[:max_questions]++ templates: list[QuizTemplate] = []+ for idx, item in enumerate(questions, 1):+ if not isinstance(item, dict):+ continue+ q_text = str(item.get("question_text") or "").strip()+ if not q_text:+ continue+ templates.append(+ QuizTemplate(+ question_id=f"q_{idx}",+ topic=q_text[:_TOPIC_CLIP_CHARS],+ question_type=str(item.get("question_type") or _DEFAULT_QUESTION_TYPE).lower(),+ difficulty=_DEFAULT_DIFFICULTY,+ source="mimic",+ reference_question=q_text,+ reference_answer=str(item.get("answer") or "").strip() or None,+ )+ )++ trace = {+ "paper_dir": str(working_dir),+ "question_file": str(json_files[0]),+ "template_count": str(len(templates)),+ }+ return templates, trace+++__all__ = ["parse_exam_paper_to_templates"]diff --git a/deeptutor/agents/question/models.py b/deeptutor/agents/question/models.pydeleted file mode 100644index 124a4b1cd..000000000--- a/deeptutor/agents/question/models.py+++ /dev/null@@ -1,41 +0,0 @@-#!/usr/bin/env python-"""-Data models for the refactored question pipeline.-"""--from dataclasses import dataclass, field-from typing import Any---@dataclass-class QuestionTemplate:- """- Standardized intermediate template shared by all input paths.- """-- question_id: str- concentration: str- question_type: str- difficulty: str- source: str = "custom"- reference_question: str | None = None- reference_answer: str | None = None- metadata: dict[str, Any] = field(default_factory=dict)---@dataclass-class QAPair:- """- Final generated Q-A payload.- """-- question_id: str- question: str- correct_answer: str- explanation: str- question_type: str- options: dict[str, str] | None = None- concentration: str = ""- difficulty: str = ""- validation: dict[str, Any] = field(default_factory=dict)- metadata: dict[str, Any] = field(default_factory=dict)diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.pynew file mode 100644index 000000000..08406705d--- /dev/null+++ b/deeptutor/agents/question/pipeline.py@@ -0,0 +1,2197 @@+"""QuestionPipeline — agentic-engine-based replacement for ``AgentCoordinator``.++Phase shape:++* **Phase 1 (Explore)** — one agentic loop over ``THINK`` / ``TOOL`` /+ ``FINISH``, using the same tool composition as chat. The ``FINISH``+ text streams live into the chat bubble as a brief, user-facing preface+ (e.g., "I researched X; now let me generate N questions"). Prior quiz+ history (if any) is fed in so the model articulates avoidance and+ weak-spot coverage.+* **Phase 2 (Plan)** — one ``PLAN`` labeled step emits a JSON plan with+ per-question templates ``[{question_id, topic, question_type,+ difficulty}, ...]``. No tools, no loop. Streams into the trace panel.+* **Phase 3 (Quiz)** — for each template, one agentic loop over the+ three ``THINK`` / ``TOOL`` / ``FINISH`` labels. ``FINISH`` is a strict+ JSON payload describing one question; the pipeline parses it (with+ one-shot repair on schema violation) and emits a structured+ ``quiz_question_emitted`` event so the frontend can render the+ question card the moment it's ready.++The orchestrator owns control flow (per-question iteration, repair pass,+incremental emission) and prompt assembly; everything else is delegated+to :mod:`deeptutor.core.agentic` and the shared tool-composition policy.+"""++from __future__ import annotations++import json+import logging+import re+from collections.abc import Awaitable+from dataclasses import dataclass, field+from enum import StrEnum+from typing import Any++from deeptutor.capabilities._shared import emit_capability_result+from deeptutor.agents._shared.tool_composition import (+ ToolMountFlags,+ compose_enabled_tools,+ default_optional_tools,+ user_has_memory,+ user_has_notebooks,+)+from deeptutor.core.agentic import (+ DispatchOutcome,+ LLMClientConfig,+ LabeledStepResult,+ LabelProtocol,+ LoopOutcome,+ UsageTracker,+ build_completion_kwargs,+ build_openai_client,+ can_use_native_tool_calling,+ dispatch_tool_calls,+ run_agentic_loop,+ run_labeled_step,+)+from deeptutor.core.agentic.labels import find_inline_labels+from deeptutor.core.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS+from deeptutor.core.context import Attachment, UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import (+ build_trace_metadata,+ derive_trace_metadata,+ merge_trace_metadata,+ new_call_id,+)+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.config import parse_language+from deeptutor.services.llm import get_llm_config, prepare_multimodal_messages+from deeptutor.services.path_service import get_path_service+from deeptutor.services.prompt import get_prompt_manager+from deeptutor.services.prompt.language import append_language_directive+from deeptutor.utils.json_parser import parse_json_response++logger = logging.getLogger(__name__)+++SOURCE = "deep_question"+FEATURE = "deep_question"++STAGE_EXPLORING = "exploring"+STAGE_PLANNING = "planning"+STAGE_QUIZZING = "quizzing"++LABEL_THINK = "THINK"+LABEL_TOOL = "TOOL"+LABEL_FINISH = "FINISH"+LABEL_PLAN = "PLAN"++# Sub-trace metadata that the frontend renders as a "Question" card.+# Pairs with TracePanels.tsx's getTraceHeader extension (call_kind/role).+CALL_KIND_QUIZ_QUESTION = "quiz_question_emitted"+TRACE_ROLE_QUIZ_QUESTION = "quiz_question"+TRACE_GROUP_QUIZ = "quiz"++_PROTOCOL_EXPLORE = LabelProtocol(+ allowed=(LABEL_THINK, LABEL_TOOL, LABEL_FINISH),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset({LABEL_THINK}),+ final=frozenset({LABEL_FINISH}),+ tool_label=LABEL_TOOL,+)+_PROTOCOL_PLAN = LabelProtocol(+ allowed=(LABEL_PLAN,),+ terminal=frozenset({LABEL_PLAN}),+ intermediate=frozenset(),+ final=frozenset(),+ tool_label=None,+)+_PROTOCOL_QUIZ = LabelProtocol(+ allowed=(LABEL_THINK, LABEL_TOOL, LABEL_FINISH),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset({LABEL_THINK}),+ final=frozenset({LABEL_FINISH}),+ tool_label=LABEL_TOOL,+)+_PROTOCOL_REPAIR = LabelProtocol(+ allowed=(LABEL_FINISH,),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset(),+ final=frozenset({LABEL_FINISH}),+ tool_label=None,+)++DEFAULT_MAX_EXPLORE_ITERATIONS = 8+DEFAULT_MAX_QUIZ_ITERATIONS_PER_QUESTION = 5+DEFAULT_MAX_TOKENS = 4000+EXPLORE_FINISH_MAX_TOKENS = 3000+PLAN_MAX_TOKENS = 2000+QUIZ_FINISH_MAX_TOKENS = 3000+REPAIR_MAX_TOKENS = 2500+FINALIZATION_REPAIR_ATTEMPTS = 2+# Tool-result summarizer (Phase 1 reflection step). The summarizer runs+# after every tool_result returned during Explore; its compressed output+# replaces the raw tool message in the loop's buffer so subsequent+# iterations — and the exploration_trace passed downstream — see only the+# distilled version. Cost: one extra main-model LLM call per tool result.+DEFAULT_TOOL_SUMMARIZER_MAX_TOKENS = 800+TOOL_SUMMARIZER_TEMPERATURE = 0.2++class QuestionType(StrEnum):+ """Canonical question-type taxonomy. Source of truth for the planner,+ quiz-step prompt schema, and the normalizer / validator below."""++ CHOICE = "choice"+ CONCEPT = "concept"+ FILL_IN_BLANK = "fill_in_blank"+ SHORT_ANSWER = "short_answer"+ WRITTEN = "written"+ CODING = "coding"+++_VALID_QUESTION_TYPES: frozenset[str] = frozenset(qt.value for qt in QuestionType)+_TYPES_WITH_OPTIONS: frozenset[str] = frozenset({QuestionType.CHOICE.value})+_VALID_DIFFICULTIES = ("easy", "medium", "hard")+_CHOICE_KEYS = ("A", "B", "C", "D")+_FILL_IN_BLANK_TOKEN = "____"+_CONCEPT_ANSWERS: frozenset[str] = frozenset({"true", "false"})+++# ---------------------------------------------------------------------------+# Question-type whitelist helpers (used by ``run`` / ``_explore`` / ``_plan``).+#+# The pipeline accepts an optional ``question_types`` allow-list and an+# optional ``per_type_counts`` distribution so callers can constrain the+# planner to a subset of the canonical taxonomy (or fix the per-type+# breakdown). Both inputs are tolerant: anything outside the canonical set+# is silently dropped; non-positive counts are removed.+# ---------------------------------------------------------------------------+++def _normalize_type_list(types: list[str] | None) -> list[str]:+ """Filter / dedup a caller-supplied ``question_types`` list.++ Returns an ordered list of canonical type names. Unknown entries are+ dropped silently; ``None`` and ``[]`` both yield ``[]`` which downstream+ treats as "any canonical type is fair game".+ """+ if not types:+ return []+ seen: set[str] = set()+ out: list[str] = []+ for raw in types:+ if not isinstance(raw, str):+ continue+ normalized = raw.strip().lower()+ if normalized in _VALID_QUESTION_TYPES and normalized not in seen:+ seen.add(normalized)+ out.append(normalized)+ return out+++def _normalize_per_type_counts(+ counts: dict[str, int] | None, allowed: list[str]+) -> dict[str, int]:+ """Validate and clamp a per-type count map.++ Keys outside the canonical taxonomy — or outside ``allowed`` when+ non-empty — are dropped. Non-positive values are dropped. Returns an+ empty dict when there's nothing usable, in which case the planner is+ free to distribute the requested total however it sees fit.+ """+ if not counts:+ return {}+ allowed_set = frozenset(allowed) if allowed else _VALID_QUESTION_TYPES+ cleaned: dict[str, int] = {}+ for key, value in counts.items():+ if not isinstance(key, str):+ continue+ normalized = key.strip().lower()+ if normalized not in allowed_set:+ continue+ try:+ count = int(value)+ except (TypeError, ValueError):+ continue+ if count > 0:+ cleaned[normalized] = count+ return cleaned+++def _format_allowed_types(types: list[str]) -> str:+ """Render ``allowed_types`` for prompt injection. ``[]`` collapses to+ ``"auto"`` so the model knows it can pick freely."""+ return ", ".join(types) if types else "auto"+++def _format_per_type_counts(counts: dict[str, int]) -> str:+ """Render ``per_type_counts`` for prompt injection. ``{}`` collapses to+ ``"auto"`` so the model knows the breakdown is its call."""+ if not counts:+ return "auto"+ return ", ".join(f"{key}={value}" for key, value in counts.items())+++def _normalize_type_list(raw: list[str] | None) -> list[str]:+ """Coerce a user-supplied type list into the canonical taxonomy.++ Unknown values are dropped; duplicates collapse; order preserved+ relative to first appearance. Empty list means "any type".+ """+ if not raw:+ return []+ seen: set[str] = set()+ out: list[str] = []+ for item in raw:+ value = str(item or "").strip().lower()+ if value in _VALID_QUESTION_TYPES and value not in seen:+ seen.add(value)+ out.append(value)+ return out+++def _normalize_per_type_counts(+ raw: dict[str, int] | None,+ allowed_types: list[str],+) -> dict[str, int]:+ """Coerce per-type quantity targets into the canonical taxonomy.++ Drops counts for types not in ``allowed_types`` (when non-empty) or+ not in the canonical taxonomy (when allowed_types is empty). Negative+ or non-integer values become 0. Empty dict means "let the planner+ distribute".+ """+ if not raw:+ return {}+ accepted: frozenset[str] = (+ frozenset(allowed_types) if allowed_types else _VALID_QUESTION_TYPES+ )+ out: dict[str, int] = {}+ for key, value in raw.items():+ canonical = str(key or "").strip().lower()+ if canonical not in accepted:+ continue+ try:+ count = int(value)+ except (TypeError, ValueError):+ continue+ if count > 0:+ out[canonical] = count+ return out+++def _format_allowed_types(allowed_types: list[str]) -> str:+ """Prompt-side rendering of the allowed-types directive."""+ if not allowed_types:+ return "any (planner picks per question)"+ return ", ".join(f"``{t}``" for t in allowed_types)+++def _format_per_type_counts(per_type_counts: dict[str, int]) -> str:+ """Prompt-side rendering of the per-type quantity directive."""+ if not per_type_counts:+ return "no per-type targets (planner distributes freely)"+ return ", ".join(f"{t}={n}" for t, n in per_type_counts.items())+++# ---------------------------------------------------------------------------+# Data shapes+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class QuizTemplate:+ question_id: str+ topic: str+ question_type: str+ difficulty: str+ # ``source`` distinguishes templates the planner invents from templates+ # lifted out of an exam paper. ``mimic`` templates carry the original+ # text so the quiz step can shadow / paraphrase rather than invent.+ source: str = "custom"+ reference_question: str | None = None+ reference_answer: str | None = None+++@dataclass(frozen=True)+class QuizPlan:+ analysis: str+ templates: list[QuizTemplate] = field(default_factory=list)+++@dataclass(frozen=True)+class QuizHistoryEntry:+ """One prior quiz item the learner attempted in this session."""++ question: str+ question_type: str+ correct_answer: str+ user_answer: str+ is_correct: bool | None+ turn_id: str = ""+++@dataclass+class QuizPair:+ """Final shape one question takes when emitted to the frontend.++ Mirrors the legacy ``QAPair`` shape so ``QuizViewer`` keeps rendering.+ """++ question_id: str+ question: str+ question_type: str+ correct_answer: str+ explanation: str+ options: dict[str, str] | None = None+ topic: str = ""+ difficulty: str = ""+ metadata: dict[str, Any] = field(default_factory=dict)+++# ---------------------------------------------------------------------------+# QuestionPipeline+# ---------------------------------------------------------------------------+++class QuestionPipeline:+ """One-shot orchestrator: instantiate per turn, call :meth:`run` once."""++ def __init__(+ self,+ *,+ language: str = "en",+ kb_name: str | None = None,+ enabled_tools: list[str] | None = None,+ max_explore_iterations: int = DEFAULT_MAX_EXPLORE_ITERATIONS,+ max_quiz_iterations_per_question: int = DEFAULT_MAX_QUIZ_ITERATIONS_PER_QUESTION,+ runtime_config: dict[str, Any] | None = None,+ ) -> None:+ self.language = parse_language(language)+ self.kb_name = (kb_name or "").strip() or None+ self.enabled_tools = list(enabled_tools or [])+ self.runtime_config: dict[str, Any] = dict(runtime_config or {})++ # Pull the exploring sub-config. Direct kwargs win for callers that+ # don't go through ``build_question_runtime_config``; runtime_config+ # is the path the capability wires up.+ exploring_cfg = (+ self.runtime_config.get("exploring")+ if isinstance(self.runtime_config.get("exploring"), dict)+ else {}+ )+ cfg_max_iter = exploring_cfg.get("max_iterations")+ if isinstance(cfg_max_iter, int) and cfg_max_iter > 0:+ self.max_explore_iterations = max(1, int(cfg_max_iter))+ else:+ self.max_explore_iterations = max(1, int(max_explore_iterations))++ summarizer_cfg = (+ exploring_cfg.get("tool_summarizer")+ if isinstance(exploring_cfg.get("tool_summarizer"), dict)+ else {}+ )+ summarizer_tokens = summarizer_cfg.get("max_tokens")+ if isinstance(summarizer_tokens, int) and summarizer_tokens > 0:+ self.tool_summarizer_max_tokens = int(summarizer_tokens)+ else:+ self.tool_summarizer_max_tokens = DEFAULT_TOOL_SUMMARIZER_MAX_TOKENS+ self.tool_summarizer_enabled = bool(summarizer_cfg.get("enabled", True))++ self.max_quiz_iterations_per_question = max(1, int(max_quiz_iterations_per_question))++ self.llm_config = get_llm_config()+ self.binding = getattr(self.llm_config, "binding", None) or "openai"+ self.model = getattr(self.llm_config, "model", None)+ self.client_config = LLMClientConfig(+ binding=self.binding,+ model=self.model,+ api_key=getattr(self.llm_config, "api_key", None),+ base_url=getattr(self.llm_config, "base_url", None),+ api_version=getattr(self.llm_config, "api_version", None),+ extra_headers=getattr(self.llm_config, "extra_headers", None) or None,+ )++ self.registry = get_tool_registry()+ self.usage = UsageTracker(model=self.model)+ self._optional_tools = default_optional_tools()+ self._temperature = 0.4++ try:+ self._prompts: dict[str, Any] = (+ get_prompt_manager().load_prompts(+ module_name="question",+ agent_name="pipeline",+ language=self.language,+ )+ or {}+ )+ except Exception as exc:+ logger.warning("Failed to load question pipeline prompts: %s", exc)+ self._prompts = {}++ # ------------------------------------------------------------------+ # Public entry point+ # ------------------------------------------------------------------+ async def run(+ self,+ *,+ context: UnifiedContext,+ user_message: str,+ num_questions: int,+ difficulty: str = "",+ question_types: list[str] | None = None,+ per_type_counts: dict[str, int] | None = None,+ conversation_context: str = "",+ attachments: list[Attachment] | None = None,+ quiz_history: list[QuizHistoryEntry] | None = None,+ templates_override: list[QuizTemplate] | None = None,+ stream: StreamBus,+ ) -> dict[str, Any]:+ """Drive the pipeline. ``templates_override`` is the mimic-mode hook:+ when caller supplies pre-built templates (e.g., extracted from an+ uploaded exam paper), Phase 1 (Explore) and Phase 2 (Plan) are+ skipped — we jump straight to per-question quizzing with the+ provided templates.++ ``question_types`` is the allowed-types whitelist (empty = any+ type). ``per_type_counts`` optionally pins how many questions of+ each type to produce; when supplied, it must sum to+ ``num_questions`` (caller's responsibility).+ """+ attachments = list(attachments or [])+ image_attachments = [a for a in attachments if getattr(a, "type", "") == "image"]+ quiz_history = list(quiz_history or [])+ requested = max(1, int(num_questions or 1))++ allowed_types = _normalize_type_list(question_types)+ counts = _normalize_per_type_counts(per_type_counts, allowed_types)++ client = build_openai_client(self.client_config)++ try:+ return await self._run_inner(+ context=context,+ user_message=user_message,+ num_questions=requested,+ difficulty=str(difficulty or "").strip().lower(),+ allowed_types=allowed_types,+ per_type_counts=counts,+ conversation_context=conversation_context.strip(),+ attachments=attachments,+ image_attachments=image_attachments,+ quiz_history=quiz_history,+ templates_override=list(templates_override) if templates_override else None,+ stream=stream,+ client=client,+ )+ except Exception as exc:+ logger.exception("QuestionPipeline.run failed: %s", exc)+ await self._emit_visible_failure(stream, exc)+ raise++ async def _run_inner(+ self,+ *,+ context: UnifiedContext,+ user_message: str,+ num_questions: int,+ difficulty: str,+ allowed_types: list[str],+ per_type_counts: dict[str, int],+ conversation_context: str,+ attachments: list[Attachment],+ image_attachments: list[Attachment],+ quiz_history: list[QuizHistoryEntry],+ templates_override: list[QuizTemplate] | None,+ stream: StreamBus,+ client: Any,+ ) -> dict[str, Any]:+ is_mimic = templates_override is not None+ logger.info(+ "QuestionPipeline.run: lang=%s kb=%s tools=%s requested=%d "+ "explore_iter=%d quiz_iter/q=%d history=%d mode=%s",+ self.language,+ self.kb_name,+ self.enabled_tools,+ num_questions,+ self.max_explore_iterations,+ self.max_quiz_iterations_per_question,+ len(quiz_history),+ "mimic" if is_mimic else "custom",+ )++ finish_text = ""+ if is_mimic:+ # Mimic mode: templates come from an exam paper. We skip explore+ # + plan and synthesize a minimal Plan envelope so downstream+ # rendering / result code paths stay identical. ``exploration_trace``+ # is the empty marker so quiz prompts render a coherent section.+ exploration_trace = self._t("empty.no_exploration_trace")+ plan = QuizPlan(analysis="", templates=list(templates_override or []))+ else:+ # ----- Phase 1: Explore -----+ async with stream.stage(STAGE_EXPLORING, source=SOURCE):+ finish_text, exploration_trace = await self._explore(+ context=context,+ user_message=user_message,+ num_questions=num_questions,+ difficulty=difficulty,+ allowed_types=allowed_types,+ per_type_counts=per_type_counts,+ conversation_context=conversation_context,+ attachments=attachments,+ image_attachments=image_attachments,+ quiz_history=quiz_history,+ stream=stream,+ client=client,+ )++ # ----- Phase 2: Plan -----+ async with stream.stage(STAGE_PLANNING, source=SOURCE):+ plan = await self._plan(+ user_message=user_message,+ exploration_trace=exploration_trace,+ num_questions=num_questions,+ difficulty=difficulty,+ allowed_types=allowed_types,+ per_type_counts=per_type_counts,+ stream=stream,+ client=client,+ )++ if not plan.templates:+ await stream.progress(+ self._t("notices.plan_count_mismatch", got=0, requested=num_questions),+ source=SOURCE,+ stage=STAGE_PLANNING,+ metadata={"trace_kind": "warning"},+ )++ # ----- Phase 3: Quiz (per-question) -----+ qa_pairs: list[QuizPair] = []+ async with stream.stage(STAGE_QUIZZING, source=SOURCE):+ for index, template in enumerate(plan.templates):+ qa_pair = await self._quiz_one(+ template=template,+ question_number=index + 1,+ total_questions=len(plan.templates),+ exploration_trace=exploration_trace,+ plan=plan,+ previous_pairs=qa_pairs,+ image_attachments=image_attachments,+ context=context,+ stream=stream,+ client=client,+ )+ await self._emit_quiz_question(+ stream=stream,+ qa_pair=qa_pair,+ index=index,+ total=len(plan.templates),+ )+ qa_pairs.append(qa_pair)++ # ----- Result envelope -----+ result_payload = self._build_result_payload(+ plan, qa_pairs, is_mimic=is_mimic, finish_text=finish_text+ )+ await emit_capability_result(+ stream, result_payload, source=SOURCE, usage=self.usage+ )+ return result_payload++ # ------------------------------------------------------------------+ # Phase 1: Explore+ # ------------------------------------------------------------------+ async def _explore(+ self,+ *,+ context: UnifiedContext,+ user_message: str,+ num_questions: int,+ difficulty: str,+ allowed_types: list[str],+ per_type_counts: dict[str, int],+ conversation_context: str,+ attachments: list[Attachment],+ image_attachments: list[Attachment],+ quiz_history: list[QuizHistoryEntry],+ stream: StreamBus,+ client: Any,+ ) -> tuple[str, str]:+ """Drive Phase 1 and return a ``(finish_text, exploration_trace)`` pair.++ ``finish_text`` is the user-facing exploration preface (already+ streamed to ``stream.content`` during the loop via+ ``stream_body_live=True``). It is **not** consumed by downstream+ phases. ``exploration_trace`` is the full reasoning + tool-call+ history serialized for the plan / quiz prompts; tool results+ embedded in it have already been replaced by the Tool Summarizer+ step's compressed output.+ """+ system_prompt = self._t(+ "explore.system",+ kb_note=self._kb_system_note(),+ tool_list=self._tool_list_text(context),+ num_questions=num_questions,+ )+ system_prompt = append_language_directive(system_prompt, self.language)+ user_prompt = self._t(+ "explore.user_template",+ user_message=user_message,+ num_questions=num_questions,+ allowed_types=_format_allowed_types(allowed_types),+ per_type_counts=_format_per_type_counts(per_type_counts),+ difficulty=difficulty or "auto",+ attachments_summary=self._render_attachments_summary(attachments),+ conversation_context=conversation_context+ or self._t("empty.no_conversation"),+ quiz_history=self._render_quiz_history(quiz_history),+ )+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )+ # Capture the initial-message count so the trace renderer can skip+ # them: only post-system+user iteration messages constitute the+ # exploration trace passed downstream.+ initial_message_count = len(messages)++ tool_schemas = (+ self._build_llm_tool_schemas(context)+ if self._use_native_tools(context)+ else None+ )++ host = _ExploreLoopHost(pipeline=self, stream=stream, context=context, client=client)+ outcome = await run_agentic_loop(+ initial_messages=messages,+ protocol=_PROTOCOL_EXPLORE,+ client=client,+ model=self.model,+ completion_kwargs=self._completion_kwargs(DEFAULT_MAX_TOKENS),+ binding=self.binding,+ tool_schemas=tool_schemas,+ stream=stream,+ source=SOURCE,+ stage=STAGE_EXPLORING,+ max_iterations=self.max_explore_iterations,+ host=host,+ usage=self.usage,+ stream_body_live=True,+ eager_sub_trace=True,+ )+ finish_text = (outcome.final_text or "").strip()+ exploration_trace = self._render_exploration_trace(+ outcome.messages[initial_message_count:],+ finish_text=finish_text,+ )+ return finish_text, exploration_trace++ # ------------------------------------------------------------------+ # Phase 2: Plan+ # ------------------------------------------------------------------+ async def _plan(+ self,+ *,+ user_message: str,+ exploration_trace: str,+ num_questions: int,+ difficulty: str,+ allowed_types: list[str],+ per_type_counts: dict[str, int],+ stream: StreamBus,+ client: Any,+ ) -> QuizPlan:+ system_prompt = self._t("plan.system", num_questions=num_questions)+ system_prompt = append_language_directive(system_prompt, self.language)+ user_prompt = self._t(+ "plan.user_template",+ user_message=user_message,+ exploration_trace=exploration_trace or self._t("empty.no_exploration_trace"),+ num_questions=num_questions,+ allowed_types=_format_allowed_types(allowed_types),+ per_type_counts=_format_per_type_counts(per_type_counts),+ difficulty=difficulty or "auto",+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ iter_meta = self._build_simple_trace_meta(+ call_id_root="quiz-plan",+ label=self._t("labels.plan", default="Plan"),+ stage=STAGE_PLANNING,+ call_kind="llm_planning",+ trace_role="plan",+ trace_group="plan",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_PLAN,+ stream=stream,+ stage=STAGE_PLANNING,+ iter_meta=iter_meta,+ max_tokens=PLAN_MAX_TOKENS,+ )+ plan = self._parse_plan(+ step.text,+ requested=num_questions,+ allowed_types=allowed_types,+ target_difficulty=difficulty,+ )+ if len(plan.templates) != num_questions:+ await stream.progress(+ self._t(+ "notices.plan_count_mismatch",+ got=len(plan.templates),+ requested=num_questions,+ ),+ source=SOURCE,+ stage=STAGE_PLANNING,+ metadata={"trace_kind": "warning"},+ )+ return plan++ def _parse_plan(+ self,+ raw: str,+ *,+ requested: int,+ allowed_types: list[str],+ target_difficulty: str,+ ) -> QuizPlan:+ data = parse_json_response(raw, logger_instance=logger, fallback={})+ if not isinstance(data, dict) or not data:+ return QuizPlan(analysis="", templates=[])+ analysis = str(data.get("analysis", "") or "")++ raw_items: list[Any]+ if isinstance(data.get("templates"), list):+ raw_items = list(data["templates"])+ elif isinstance(data.get("ideas"), list):+ raw_items = list(data["ideas"])+ else:+ raw_items = []++ # If the caller restricted types, the plan must only use that set.+ # Otherwise fall back to the full canonical taxonomy.+ allowed_set: frozenset[str] = (+ frozenset(allowed_types) if allowed_types else _VALID_QUESTION_TYPES+ )+ # The chosen fallback when the planner emits an out-of-set type:+ # prefer SHORT_ANSWER (concept-style Q&A) when allowed, else first+ # allowed type, else WRITTEN as a global default.+ if QuestionType.SHORT_ANSWER.value in allowed_set:+ fallback_type = QuestionType.SHORT_ANSWER.value+ elif allowed_set:+ fallback_type = next(iter(allowed_set))+ else:+ fallback_type = QuestionType.WRITTEN.value++ templates: list[QuizTemplate] = []+ seen_topics: set[str] = set()+ for idx, item in enumerate(raw_items, 1):+ if not isinstance(item, dict):+ continue+ topic = str(item.get("topic") or item.get("concentration") or "").strip()+ if not topic or topic.lower() in seen_topics:+ continue+ seen_topics.add(topic.lower())++ qtype_raw = str(item.get("question_type", "")).strip().lower()+ qtype = qtype_raw if qtype_raw in allowed_set else fallback_type++ diff_raw = str(item.get("difficulty", "")).strip().lower()+ diff = target_difficulty or diff_raw+ diff = diff if diff in _VALID_DIFFICULTIES else "medium"++ templates.append(+ QuizTemplate(+ question_id=f"q_{len(templates) + 1}",+ topic=topic,+ question_type=qtype,+ difficulty=diff,+ )+ )+ if len(templates) >= requested:+ break+ return QuizPlan(analysis=analysis, templates=templates)++ # ------------------------------------------------------------------+ # Phase 3: Quiz (one question)+ # ------------------------------------------------------------------+ async def _quiz_one(+ self,+ *,+ template: QuizTemplate,+ question_number: int,+ total_questions: int,+ exploration_trace: str,+ plan: QuizPlan,+ previous_pairs: list[QuizPair],+ image_attachments: list[Attachment],+ context: UnifiedContext,+ stream: StreamBus,+ client: Any,+ ) -> QuizPair:+ 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_id=template.question_id,+ topic=template.topic,+ question_type=template.question_type,+ difficulty=template.difficulty,+ exploration_trace=exploration_trace or self._t("empty.no_exploration_trace"),+ plan_summary=self._render_plan_summary(plan),+ previous_questions=self._render_previous_questions(previous_pairs),+ reference_block=self._render_reference_block(template),+ )+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )++ tool_schemas = (+ self._build_llm_tool_schemas(context)+ if self._use_native_tools(context)+ else None+ )+ host = _QuizLoopHost(+ pipeline=self,+ template=template,+ stream=stream,+ context=context,+ client=client,+ )+ outcome = await run_agentic_loop(+ initial_messages=messages,+ protocol=_PROTOCOL_QUIZ,+ client=client,+ model=self.model,+ completion_kwargs=self._completion_kwargs(QUIZ_FINISH_MAX_TOKENS),+ binding=self.binding,+ tool_schemas=tool_schemas,+ stream=stream,+ source=SOURCE,+ stage=STAGE_QUIZZING,+ max_iterations=self.max_quiz_iterations_per_question,+ host=host,+ usage=self.usage,+ stream_body_live=False,+ eager_sub_trace=True,+ )+ payload = self._parse_quiz_payload(outcome.final_text)+ normalized = self._normalize_quiz_payload(template, payload)+ issues = self._collect_quiz_issues(template, normalized)+ if issues:+ await stream.progress(+ self._t("notices.repair_attempted"),+ source=SOURCE,+ stage=STAGE_QUIZZING,+ metadata={"trace_kind": "warning"},+ )+ repaired = await self._repair_quiz_payload(+ template=template,+ payload=normalized,+ issues=issues,+ stream=stream,+ client=client,+ )+ if repaired:+ normalized = self._normalize_quiz_payload(template, repaired)+ issues = self._collect_quiz_issues(template, normalized)+ if issues:+ await stream.progress(+ self._t("notices.repair_failed"),+ source=SOURCE,+ stage=STAGE_QUIZZING,+ metadata={"trace_kind": "warning"},+ )+ return self._payload_to_qa_pair(template, normalized, issues=issues)++ async def _repair_quiz_payload(+ self,+ *,+ template: QuizTemplate,+ payload: dict[str, Any],+ issues: list[str],+ stream: StreamBus,+ client: Any,+ ) -> dict[str, Any] | None:+ system_prompt = append_language_directive(+ self._t("repair.system"),+ self.language,+ )+ user_prompt = self._t(+ "repair.user_template",+ question_id=template.question_id,+ topic=template.topic,+ question_type=template.question_type,+ difficulty=template.difficulty,+ invalid_payload=json.dumps(payload, ensure_ascii=False, indent=2),+ issues=json.dumps(issues, ensure_ascii=False),+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ iter_meta = self._build_simple_trace_meta(+ call_id_root=f"quiz-repair-{template.question_id}",+ label=self._t("labels.repair", default="Repair question format"),+ stage=STAGE_QUIZZING,+ call_kind="llm_reasoning",+ trace_role="thought",+ trace_group=TRACE_GROUP_QUIZ,+ question_id=template.question_id,+ )+ # Repair uses a FINISH-only protocol so the host's existing parser+ # path can re-use ``_parse_quiz_payload`` on the buffered text.+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_REPAIR,+ stream=stream,+ stage=STAGE_QUIZZING,+ iter_meta=iter_meta,+ max_tokens=REPAIR_MAX_TOKENS,+ )+ return self._parse_quiz_payload(step.text)++ # ------------------------------------------------------------------+ # Tool Summarizer (Phase 1 reflection over a single tool_result)+ # ------------------------------------------------------------------+ async def _summarize_tool_result(+ self,+ *,+ tool_name: str,+ tool_result: str,+ iteration: int,+ stream: StreamBus,+ client: Any,+ ) -> str | None:+ """Run one main-model LLM call that compresses ``tool_result`` into a+ lossless summary. The summary is streamed live to the trace panel+ under a "Reflecting..." sub-trace node and returned to the caller,+ which then substitutes it for the raw result in the loop's message+ buffer.++ Returns ``None`` on failure / empty input so the caller can keep the+ raw result instead.+ """+ text = (tool_result or "").strip()+ if not text:+ return None++ system_prompt = self._t("tool_summarizer.system")+ system_prompt = append_language_directive(system_prompt, self.language)+ user_prompt = self._t("tool_summarizer.user_template", tool_result=text)+ messages = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ]++ call_id = new_call_id(f"quiz-reflect-iter-{iteration}-{tool_name or 'tool'}")+ meta = build_trace_metadata(+ call_id=call_id,+ phase=STAGE_EXPLORING,+ label=self._t("labels.reflecting", default="DeepTutor Reflecting..."),+ call_kind="tool_result_reflection",+ trace_id=call_id,+ trace_role="reflection",+ trace_group="reflection",+ tool=tool_name,+ iteration=iteration,+ )+ # Open the sub-trace card before the LLM stream starts so the panel+ # registers the "Reflecting..." node immediately.+ await stream.progress(+ self._t("labels.reflecting", default="DeepTutor Reflecting..."),+ source=SOURCE,+ stage=STAGE_EXPLORING,+ metadata=merge_trace_metadata(+ meta, {"trace_kind": "call_status", "call_state": "running"}+ ),+ )++ # ``build_completion_kwargs`` only returns temperature + token-limit+ # kwargs; ``model``/``messages``/``stream`` must be added explicitly+ # (mirrors how ``run_labeled_step`` composes its create call).+ kwargs: dict[str, Any] = {+ "model": self.model,+ "messages": messages,+ "stream": True,+ **build_completion_kwargs(+ temperature=TOOL_SUMMARIZER_TEMPERATURE,+ model=self.model,+ max_tokens=self.tool_summarizer_max_tokens,+ ),+ }+ try:+ kwargs["stream_options"] = {"include_usage": True}+ except Exception:+ pass++ chunks: list[str] = []+ try:+ response_stream = await client.chat.completions.create(**kwargs)+ async for chunk in response_stream:+ # Usage frames have no choices; surface them to the usage+ # tracker so the cost summary reflects the summarizer too.+ usage_frame = getattr(chunk, "usage", None)+ if usage_frame and self.usage is not None:+ try:+ self.usage.add_from_response(usage_frame)+ except Exception:+ logger.debug("usage recording failed for summarizer", exc_info=True)+ if not getattr(chunk, "choices", None):+ continue+ delta = chunk.choices[0].delta+ if delta is None:+ continue+ text_chunk = getattr(delta, "content", None) or ""+ if not text_chunk:+ continue+ chunks.append(text_chunk)+ await stream.thinking(+ text_chunk,+ source=SOURCE,+ stage=STAGE_EXPLORING,+ metadata=merge_trace_metadata(meta, {"trace_kind": "llm_chunk"}),+ )+ except Exception as exc:+ logger.warning("Tool summarizer failed for %s: %s", tool_name, exc)+ await stream.progress(+ self._t("notices.tool_summarizer_failed"),+ source=SOURCE,+ stage=STAGE_EXPLORING,+ metadata=merge_trace_metadata(+ meta, {"trace_kind": "warning", "call_state": "error"}+ ),+ )+ return None+ finally:+ await stream.progress(+ "",+ source=SOURCE,+ stage=STAGE_EXPLORING,+ metadata=merge_trace_metadata(+ meta, {"trace_kind": "call_status", "call_state": "complete"}+ ),+ )++ summary = "".join(chunks).strip()+ return summary or None++ # ------------------------------------------------------------------+ # Exploration trace serialization (Phase 1 → Phase 2/3 hand-off)+ # ------------------------------------------------------------------+ def _render_exploration_trace(+ self,+ loop_messages: list[dict[str, Any]],+ *,+ finish_text: str,+ ) -> str:+ """Serialize the explore loop's post-initial messages into a+ markdown blob consumed by the plan + quiz prompts.++ Tool results in ``loop_messages`` have already been replaced by the+ Tool Summarizer's output (the explore host substitutes them inside+ ``dispatch_tools``), so this renderer never has to compress anything+ — it just lays the buffer out in a readable form.++ The final FINISH assistant message is included as a labeled "final+ exploration preface" block so the planner can read the same closing+ synthesis the user saw, while still having every preceding tool+ result + thought to draw on.+ """+ if not loop_messages and not finish_text:+ return self._t("empty.no_exploration_trace")++ blocks: list[str] = []+ iteration = 0+ # Map tool_call_id → invoked function name so tool messages can+ # surface a human-readable label even though the role=tool message+ # itself only carries the id.+ tool_call_names: dict[str, str] = {}++ for message in loop_messages:+ role = message.get("role")+ content = (message.get("content") or "").strip()++ if role == "assistant":+ tool_calls = message.get("tool_calls") or []+ if tool_calls:+ iteration += 1+ for tc in tool_calls:+ function = tc.get("function") or {}+ name = function.get("name") or "tool"+ tc_id = tc.get("id") or ""+ if tc_id:+ tool_call_names[tc_id] = name+ raw_args = function.get("arguments") or "{}"+ try:+ parsed_args = json.loads(raw_args)+ args_display = json.dumps(+ parsed_args, ensure_ascii=False, indent=2+ )+ except Exception:+ args_display = str(raw_args)+ header = self._t(+ "trace.iteration_tool_call",+ n=iteration,+ tool=name,+ default=f"Iteration {iteration} — Tool call: {name}",+ )+ body_parts: list[str] = []+ if content:+ body_parts.append(content)+ body_parts.append(f"Arguments:\n```json\n{args_display}\n```")+ blocks.append(f"### {header}\n\n" + "\n\n".join(body_parts))+ continue++ # Plain assistant content = a THINK iteration. Strip the+ # leading protocol label so downstream consumers don't have+ # to.+ if not content:+ continue+ iteration += 1+ stripped = self._strip_protocol_label(content)+ header = self._t(+ "trace.iteration_thought",+ n=iteration,+ default=f"Iteration {iteration} — Thought",+ )+ blocks.append(f"### {header}\n\n{stripped}")++ elif role == "tool":+ tc_id = message.get("tool_call_id") or ""+ name = tool_call_names.get(tc_id, "tool")+ header = self._t(+ "trace.iteration_tool_result",+ n=iteration,+ tool=name,+ default=f"Iteration {iteration} — Tool result (summarized): {name}",+ )+ blocks.append(f"### {header}\n\n{content or '(empty)'}")++ elif role == "user":+ # User-role messages inside the loop are protocol-repair+ # nudges or force-finish prompts injected by the host —+ # noise that downstream readers don't need.+ continue++ finish_label = self._t(+ "trace.finish_note", default="Final exploration preface (also shown to the user)"+ )+ if finish_text:+ blocks.append(f"### {finish_label}\n\n{finish_text.strip()}")++ return "\n\n".join(blocks) if blocks else self._t("empty.no_exploration_trace")++ @staticmethod+ def _strip_protocol_label(text: str) -> str:+ """Drop a leading ``THINK`` / ``TOOL`` / ``FINISH`` label so the trace+ rendering doesn't double up on protocol noise."""+ stripped = text.lstrip()+ for label in ("``THINK``", "``TOOL``", "``FINISH``"):+ if stripped.startswith(label):+ return stripped[len(label):].lstrip("\n").lstrip()+ return text++ # ------------------------------------------------------------------+ # Incremental emission (per question)+ # ------------------------------------------------------------------+ async def _emit_quiz_question(+ self,+ *,+ stream: StreamBus,+ qa_pair: QuizPair,+ index: int,+ total: int,+ ) -> None:+ meta = build_trace_metadata(+ call_id=new_call_id(f"quiz-question-{index + 1}"),+ phase=STAGE_QUIZZING,+ label=f"{self._t('labels.quiz_step', default='Question')} {index + 1}",+ call_kind=CALL_KIND_QUIZ_QUESTION,+ trace_id=qa_pair.question_id,+ trace_role=TRACE_ROLE_QUIZ_QUESTION,+ trace_group=TRACE_GROUP_QUIZ,+ question_index=index,+ total_questions=total,+ qa_pair=self._qa_pair_to_dict(qa_pair),+ )+ await stream.content(+ self._render_question_markdown(qa_pair, index + 1),+ source=SOURCE,+ stage=STAGE_QUIZZING,+ metadata=merge_trace_metadata(meta, {"trace_kind": "llm_output"}),+ )++ # ------------------------------------------------------------------+ # Final result envelope+ # ------------------------------------------------------------------+ def _build_result_payload(+ self,+ plan: QuizPlan,+ qa_pairs: list[QuizPair],+ *,+ is_mimic: bool = False,+ finish_text: str = "",+ ) -> dict[str, Any]:+ """Compose the terminal envelope.++ On result-event arrival the frontend overwrites the chat bubble's+ body with ``response``. The QuizViewer renders the per-question+ cards from ``summary.results`` independently, **above** which it+ now stacks the response body — so we put ONLY the explore FINISH+ preface in ``response`` (no per-question markdown). Mimic mode+ has no Phase 1, so ``finish_text`` is empty and ``response``+ falls back to the rendered question summary so something still+ shows in the bubble even though the QuizViewer carries the same+ content.+ """+ results = [+ {+ "qa_pair": self._qa_pair_to_dict(qa_pair),+ "metadata": dict(qa_pair.metadata),+ }+ for qa_pair in qa_pairs+ ]+ successful = sum(1 for qa in qa_pairs if not qa.metadata.get("error"))+ markdown = self._render_summary_markdown(qa_pairs)+ finish_block = finish_text.strip()+ if finish_block:+ # Custom mode: the user already watched FINISH stream into the+ # bubble. Keep that as the bubble's body so it doesn't disappear+ # when QuizViewer mounts. Question markdown lives in QuizViewer+ # — duplicating it here would render every question twice.+ response_body = finish_block+ else:+ # Mimic mode: no Phase 1 ran, so there's no streamed preface+ # to preserve. Fall back to the legacy summary markdown.+ response_body = markdown or "No questions generated."+ payload: dict[str, Any] = {+ "response": response_body,+ "summary": {+ "success": successful == len(qa_pairs) and bool(qa_pairs),+ "source": "exam" if is_mimic else "topic",+ "requested": len(plan.templates),+ "template_count": len(plan.templates),+ "completed": successful,+ "failed": len(qa_pairs) - successful,+ "templates": [self._template_to_dict(t) for t in plan.templates],+ "results": results,+ "analysis": plan.analysis,+ },+ "mode": "mimic" if is_mimic else "custom",+ }+ return payload++ # ------------------------------------------------------------------+ # Quiz payload parsing / validation / normalization+ # ------------------------------------------------------------------+ @staticmethod+ def _parse_quiz_payload(raw: str) -> dict[str, Any]:+ text = (raw or "").strip()+ if not text:+ return {}+ # Strip a single fenced block if the model wrapped the JSON+ fence = re.search(r"```(?:json)?\s*(.*?)```", text, re.DOTALL)+ if fence:+ text = fence.group(1).strip()+ try:+ parsed = json.loads(text)+ except json.JSONDecodeError:+ obj = re.search(r"\{[\s\S]*\}", text)+ if obj is None:+ return {}+ try:+ parsed = json.loads(obj.group(0))+ except json.JSONDecodeError:+ return {}+ return parsed if isinstance(parsed, dict) else {}++ @classmethod+ def _normalize_quiz_payload(+ cls, template: QuizTemplate, payload: dict[str, Any]+ ) -> dict[str, Any]:+ normalized = dict(payload or {})+ expected_type = template.question_type+ normalized["question_type"] = expected_type+ normalized["question"] = str(normalized.get("question", "") or "").strip()+ normalized["correct_answer"] = str(normalized.get("correct_answer", "") or "").strip()+ normalized["explanation"] = str(normalized.get("explanation", "") or "").strip()++ raw_options = normalized.get("options")+ if expected_type == QuestionType.CHOICE.value:+ clean: dict[str, str] = {}+ if isinstance(raw_options, dict):+ for key, value in raw_options.items():+ k = str(key or "").strip().upper()[:1]+ v = str(value or "").strip()+ if k in _CHOICE_KEYS and v:+ clean[k] = v+ normalized["options"] = clean or None+ if clean and normalized["correct_answer"]:+ ans = normalized["correct_answer"].upper().strip()+ if ans in clean:+ normalized["correct_answer"] = ans+ else:+ for key, value in clean.items():+ if normalized["correct_answer"].lower() == value.lower():+ normalized["correct_answer"] = key+ break+ elif expected_type == QuestionType.CONCEPT.value:+ # Concept (T/F) answers ride through correct_answer as the lowercase+ # literal "true"/"false". Coerce any Chinese / casing variants the+ # model might emit before the rest of the pipeline sees them.+ normalized["options"] = None+ raw_ans = normalized["correct_answer"].lower()+ if raw_ans in {"true", "t", "对", "正确", "yes", "y", "1"}:+ normalized["correct_answer"] = "true"+ elif raw_ans in {"false", "f", "错", "错误", "no", "n", "0"}:+ normalized["correct_answer"] = "false"+ else:+ normalized["options"] = None+ return normalized++ @classmethod+ def _collect_quiz_issues(+ cls, template: QuizTemplate, payload: dict[str, Any]+ ) -> list[str]:+ issues: list[str] = []+ question = str(payload.get("question") or "").strip()+ correct = str(payload.get("correct_answer") or "").strip()+ explanation = str(payload.get("explanation") or "").strip()+ options = payload.get("options")++ if not question:+ issues.append("missing_question")+ if not correct:+ issues.append("missing_correct_answer")+ if not explanation:+ issues.append("missing_explanation")++ qtype = template.question_type+ if qtype == QuestionType.CHOICE.value:+ if not isinstance(options, dict) or set(options.keys()) != set(_CHOICE_KEYS):+ issues.append("choice_options_must_be_a_to_d")+ if correct.upper() not in _CHOICE_KEYS:+ issues.append("choice_correct_answer_must_be_option_key")+ elif qtype == QuestionType.CONCEPT.value:+ if isinstance(options, dict) and options:+ issues.append("concept_must_not_have_options")+ if correct.lower() not in _CONCEPT_ANSWERS:+ issues.append("concept_correct_answer_must_be_true_or_false")+ elif qtype == QuestionType.FILL_IN_BLANK.value:+ if isinstance(options, dict) and options:+ issues.append("fill_in_blank_must_not_have_options")+ if question and _FILL_IN_BLANK_TOKEN not in question:+ issues.append("fill_in_blank_question_must_contain_blank_token")+ else:+ if isinstance(options, dict) and options:+ issues.append("non_choice_must_not_have_options")+ if correct.upper() in _CHOICE_KEYS and len(correct) == 1:+ issues.append("non_choice_correct_answer_looks_like_option_key")+ return issues++ def _payload_to_qa_pair(+ self,+ template: QuizTemplate,+ payload: dict[str, Any],+ *,+ issues: list[str],+ ) -> QuizPair:+ question = str(payload.get("question") or "").strip()+ if not question:+ question = f"[Generation failed] {template.topic}"+ return QuizPair(+ question_id=template.question_id,+ question=question,+ question_type=template.question_type,+ correct_answer=str(payload.get("correct_answer") or "").strip() or "N/A",+ explanation=str(payload.get("explanation") or "").strip() or "N/A",+ options=payload.get("options") if isinstance(payload.get("options"), dict) else None,+ topic=template.topic,+ difficulty=template.difficulty,+ metadata={"issues": issues} if issues else {},+ )++ # ------------------------------------------------------------------+ # Forced-finish (max-iter recovery) — shared by explore + quiz+ # ------------------------------------------------------------------+ async def _force_finish(+ self,+ *,+ client: Any,+ messages: list[dict[str, Any]],+ stream: StreamBus,+ stage: str,+ trace_root: str,+ trace_extras: dict[str, Any],+ stream_body_live: bool,+ ) -> tuple[str, bool, int]:+ messages.append({"role": "user", "content": self._t("protocol.force_finish")})+ await stream.progress(+ self._t("notices.max_iterations_reached"),+ source=SOURCE,+ stage=stage,+ metadata={"trace_kind": "warning"},+ )+ calls = 0+ for attempt in range(FINALIZATION_REPAIR_ATTEMPTS):+ iter_meta = self._build_simple_trace_meta(+ call_id_root=f"{trace_root}-force-{attempt}",+ label=self._t("labels.reasoning", default="Reasoning"),+ stage=stage,+ **trace_extras,+ )+ final_meta = None+ if stream_body_live:+ final_call_id = new_call_id(f"{trace_root}-force-final-{attempt}")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase=stage,+ label=self._t("labels.explore", default="Explore"),+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_REPAIR,+ stream=stream,+ stage=stage,+ iter_meta=iter_meta,+ max_tokens=DEFAULT_MAX_TOKENS,+ final_meta=final_meta,+ )+ calls += 1+ if step.label == LABEL_FINISH and not find_inline_labels(+ step.text, allowed_labels=_PROTOCOL_EXPLORE.allowed+ ):+ return step.text, True, calls+ messages.append({"role": "assistant", "content": step.text[:500]})+ messages.append(+ {"role": "user", "content": self._t("protocol.force_finish_repair")}+ )+ return self._t("protocol.fallback_final"), False, calls++ # ------------------------------------------------------------------+ # Tool integration (mirrors chat's policy)+ # ------------------------------------------------------------------+ def _mount_flags(self, context: UnifiedContext) -> ToolMountFlags:+ return ToolMountFlags(+ has_kb=bool(self.kb_name),+ has_sources=bool(self._source_index(context)),+ has_memory=user_has_memory(),+ has_notebooks=user_has_notebooks(),+ )++ def _resolved_tools(self, context: UnifiedContext) -> list[str]:+ return compose_enabled_tools(+ registry=self.registry,+ requested_tools=self.enabled_tools,+ optional_whitelist=self._optional_tools,+ mount_flags=self._mount_flags(context),+ )++ def _use_native_tools(self, context: UnifiedContext) -> bool:+ """Native tool calling is only worth enabling when (a) the binding /+ model actually supports it and (b) we have at least one tool to+ mount. Returning True with no tools would make the model improvise+ text-based "tool calls" since the prompt still mentions tools."""+ return bool(self._resolved_tools(context)) and can_use_native_tool_calling(+ binding=self.binding, model=self.model+ )++ def _build_llm_tool_schemas(self, context: UnifiedContext) -> list[dict[str, Any]]:+ schemas = self.registry.build_openai_schemas(self._resolved_tools(context))+ kb_choices = [self.kb_name] if self.kb_name else []+ source_ids = sorted((self._source_index(context) or {}).keys())+ for schema in schemas:+ function = schema.get("function") if isinstance(schema, dict) else None+ if not isinstance(function, dict):+ continue+ parameters = function.get("parameters") or {}+ if not isinstance(parameters, dict):+ continue+ properties = parameters.get("properties") or {}+ name = function.get("name")+ if name == "rag" and isinstance(properties, dict):+ query_schema = properties.get("query")+ if isinstance(query_schema, dict):+ query_schema.setdefault("minLength", 1)+ kb_schema = properties.get("kb_name")+ if isinstance(kb_schema, dict) and kb_choices:+ kb_schema["enum"] = kb_choices+ if name == "read_source" and isinstance(properties, dict):+ sid_schema = properties.get("source_id")+ if isinstance(sid_schema, dict) and source_ids:+ sid_schema["enum"] = source_ids+ parameters["additionalProperties"] = False+ return schemas++ def _augment_tool_kwargs(+ self,+ tool_name: str,+ args: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ kwargs = dict(args)+ turn_id = str(context.metadata.get("turn_id", "") or "").strip()+ task_dir = None+ if turn_id:+ task_dir = get_path_service().get_task_workspace(FEATURE, turn_id)+ if tool_name == "rag":+ kwargs.setdefault("mode", "hybrid")+ if self.kb_name:+ kwargs.setdefault("kb_name", self.kb_name)+ elif tool_name == "code_execution":+ kwargs.setdefault("intent", context.user_message)+ kwargs.setdefault("timeout", 30)+ kwargs.setdefault("feature", FEATURE)+ kwargs.setdefault("session_id", context.session_id)+ kwargs.setdefault("turn_id", turn_id)+ if task_dir is not None:+ kwargs.setdefault("workspace_dir", str(task_dir / "code_runs"))+ elif tool_name in {"reason", "brainstorm"}:+ kwargs.setdefault("context", context.user_message)+ elif tool_name == "web_search":+ kwargs.setdefault("query", context.user_message)+ if task_dir is not None:+ kwargs.setdefault("output_dir", str(task_dir / "web_search"))+ elif tool_name == "paper_search":+ kwargs.setdefault("max_results", 3)+ kwargs.setdefault("years_limit", 3)+ kwargs.setdefault("sort_by", "relevance")+ elif tool_name == "read_source":+ kwargs["source_index"] = self._source_index(context)+ elif tool_name == "write_note":+ kwargs["conversation_history"] = list(context.conversation_history or [])+ kwargs["current_user_message"] = context.user_message or ""+ return kwargs++ def _retrieve_trace_metadata(+ self,+ tool_meta: dict[str, Any],+ *,+ tool_name: str,+ tool_args: dict[str, Any],+ ) -> dict[str, Any] | None:+ if tool_name != "rag":+ return None+ return derive_trace_metadata(+ tool_meta,+ label=self._t("labels.retrieve", default="Retrieve"),+ call_kind="rag_retrieval",+ trace_role="retrieve",+ trace_group="retrieve",+ query=str(tool_args.get("query", "") or ""),+ )++ @staticmethod+ def _source_index(context: UnifiedContext) -> dict[str, str]:+ idx = context.metadata.get("source_index")+ return idx if isinstance(idx, dict) and idx else {}++ def _tool_list_text(self, context: UnifiedContext) -> str:+ text = self.registry.build_prompt_text(+ self._resolved_tools(context),+ format="list_with_usage",+ language=self.language,+ )+ return text or self._fallback_empty_tool_list()++ def _fallback_empty_tool_list(self) -> str:+ return "- 无" if self.language == "zh" else "- none"++ def _kb_system_note(self) -> str:+ if not self.kb_name:+ return ""+ if self.language == "zh":+ return f"用户已挂载知识库:{self.kb_name}。调用 rag 时,kb_name 必须填这个名称。"+ return (+ f"Attached knowledge bases: {self.kb_name}. When calling rag, kb_name "+ f"must be {self.kb_name!r}."+ )++ # ------------------------------------------------------------------+ # LLM call helpers+ # ------------------------------------------------------------------+ def _completion_kwargs(self, max_tokens: int) -> dict[str, Any]:+ return build_completion_kwargs(+ temperature=self._temperature,+ model=self.model,+ max_tokens=max_tokens,+ )++ async def _run_labeled_step(+ self,+ *,+ client: Any,+ messages: list[dict[str, Any]],+ tool_schemas: list[dict[str, Any]] | None,+ protocol: LabelProtocol,+ stream: StreamBus,+ stage: str,+ iter_meta: dict[str, Any],+ max_tokens: int = DEFAULT_MAX_TOKENS,+ final_meta: dict[str, Any] | None = None,+ eager_sub_trace: bool = True,+ ) -> LabeledStepResult:+ return await run_labeled_step(+ client=client,+ model=self.model,+ messages=messages,+ completion_kwargs=self._completion_kwargs(max_tokens),+ tool_schemas=tool_schemas,+ allowed_labels=protocol.allowed,+ final_labels=protocol.final,+ tool_label=protocol.tool_label,+ stream=stream,+ source=SOURCE,+ stage=stage,+ iter_meta=iter_meta,+ binding=self.binding,+ usage=self.usage,+ final_meta=final_meta,+ eager_sub_trace=eager_sub_trace,+ )++ # ------------------------------------------------------------------+ # Message + trace assembly+ # ------------------------------------------------------------------+ def _build_system_user_messages(+ self,+ system_prompt: str,+ user_prompt: str,+ *,+ image_attachments: list[Attachment] | None = None,+ ) -> list[dict[str, Any]]:+ messages: list[dict[str, Any]] = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ]+ if image_attachments:+ mm_result = prepare_multimodal_messages(+ messages, image_attachments, binding=self.binding, model=self.model+ )+ return mm_result.messages+ return messages++ def _build_simple_trace_meta(+ self,+ *,+ call_id_root: str,+ label: str,+ stage: str,+ call_kind: str = "llm_reasoning",+ trace_role: str = "thought",+ trace_group: str = "stage",+ **extra: Any,+ ) -> dict[str, Any]:+ call_id = new_call_id(call_id_root)+ return build_trace_metadata(+ call_id=call_id,+ phase=stage,+ label=label,+ call_kind=call_kind,+ trace_id=call_id,+ trace_role=trace_role,+ trace_group=trace_group,+ **extra,+ )++ # ------------------------------------------------------------------+ # Rendering helpers+ # ------------------------------------------------------------------+ def _render_attachments_summary(self, attachments: list[Attachment]) -> str:+ if not attachments:+ return self._t("empty.no_attachments")+ lines = []+ for att in attachments:+ name = getattr(att, "filename", "") or getattr(att, "type", "attachment")+ kind = getattr(att, "type", "")+ lines.append(f"- {name} ({kind})")+ return "\n".join(lines)++ def _render_quiz_history(self, history: list[QuizHistoryEntry]) -> str:+ if not history:+ return self._t("empty.no_quiz_history")+ lines = [+ (+ f"- ({entry.turn_id or '?'}) [{self._correctness_label(entry.is_correct)}] "+ f"{entry.question[:160]}"+ + (+ f" — learner answer: {entry.user_answer[:80]}; "+ f"reference: {entry.correct_answer[:80]}"+ if entry.user_answer or entry.correct_answer+ else ""+ )+ )+ for entry in history+ ]+ return "\n".join(lines)++ def _correctness_label(self, is_correct: bool | None) -> str:+ if is_correct is True:+ return "correct" if self.language != "zh" else "做对"+ if is_correct is False:+ return "incorrect" if self.language != "zh" else "做错"+ return "unknown" if self.language != "zh" else "未知"++ def _render_plan_summary(self, plan: QuizPlan) -> str:+ if not plan.templates:+ return "(empty plan)"+ lines = []+ if plan.analysis:+ lines.append(f"Analysis: {plan.analysis}")+ for template in plan.templates:+ lines.append(+ f" - [{template.question_id}] ({template.question_type}/"+ f"{template.difficulty}) {template.topic}"+ )+ return "\n".join(lines)++ def _render_previous_questions(self, qa_pairs: list[QuizPair]) -> str:+ if not qa_pairs:+ return self._t("empty.no_previous_questions")+ return "\n".join(f"{i}. {qa.question}" for i, qa in enumerate(qa_pairs, 1))++ def _render_reference_block(self, template: QuizTemplate) -> str:+ """Mimic-mode reference block injected into ``quiz_step.user_template``.++ For ``custom`` templates this is the YAML-supplied empty marker so+ the LLM treats this as a generative task; for ``mimic`` templates+ we surface the original exam-paper question (and reference answer+ when present) so the LLM shadows the source's style and difficulty+ rather than inventing a fresh stem.+ """+ if template.source != "mimic":+ return self._t("empty.no_reference")+ reference_q = (template.reference_question or "").strip()+ reference_a = (template.reference_answer or "").strip()+ if not reference_q and not reference_a:+ return self._t("empty.no_reference")+ lines: list[str] = []+ if reference_q:+ lines.append(f"Reference question:\n{reference_q}")+ if reference_a:+ lines.append(f"Reference answer:\n{reference_a}")+ return "\n\n".join(lines)++ def _render_question_markdown(self, qa: QuizPair, ordinal: int) -> str:+ header = "题目" if self.language == "zh" else "Question"+ lines = [f"### {header} {ordinal}\n", qa.question]+ if isinstance(qa.options, dict) and qa.options:+ for key in _CHOICE_KEYS:+ if key in qa.options:+ lines.append(f"- {key}. {qa.options[key]}")+ if qa.correct_answer:+ answer_label = "答案" if self.language == "zh" else "Answer"+ lines.append(f"\n**{answer_label}:** {qa.correct_answer}")+ if qa.explanation:+ expl_label = "解析" if self.language == "zh" else "Explanation"+ lines.append(f"\n**{expl_label}:** {qa.explanation}")+ return "\n".join(lines).strip()++ def _render_summary_markdown(self, qa_pairs: list[QuizPair]) -> str:+ return "\n\n".join(+ self._render_question_markdown(qa, i + 1) for i, qa in enumerate(qa_pairs)+ )++ @staticmethod+ def _qa_pair_to_dict(qa: QuizPair) -> dict[str, Any]:+ return {+ "question_id": qa.question_id,+ "question": qa.question,+ "question_type": qa.question_type,+ "options": qa.options,+ "correct_answer": qa.correct_answer,+ "explanation": qa.explanation,+ "difficulty": qa.difficulty,+ "concentration": qa.topic,+ }++ @staticmethod+ def _template_to_dict(template: QuizTemplate) -> dict[str, Any]:+ return {+ "question_id": template.question_id,+ "topic": template.topic,+ "question_type": template.question_type,+ "difficulty": template.difficulty,+ "source": template.source,+ "reference_question": template.reference_question,+ "reference_answer": template.reference_answer,+ }++ # ------------------------------------------------------------------+ # Visible failure+ # ------------------------------------------------------------------+ async def _emit_visible_failure(self, stream: StreamBus, exc: BaseException) -> None:+ call_id = new_call_id("quiz-failure")+ meta = build_trace_metadata(+ call_id=call_id,+ phase=STAGE_QUIZZING,+ label=self._t("labels.quiz_step", default="Question"),+ call_kind="llm_final_response",+ trace_id=call_id,+ trace_role="response",+ trace_group="stage",+ )+ message = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__+ await stream.error(+ message,+ source=SOURCE,+ stage=STAGE_QUIZZING,+ metadata=merge_trace_metadata(meta, {"trace_kind": "error"}),+ )+ prefix = "⚠️ " if self.language == "zh" else "⚠ "+ await stream.content(+ f"{prefix}{message}",+ source=SOURCE,+ stage=STAGE_QUIZZING,+ metadata=merge_trace_metadata(meta, {"trace_kind": "llm_output"}),+ )++ # ------------------------------------------------------------------+ # YAML lookup+ # ------------------------------------------------------------------+ def _t(self, key: str, default: str = "", **kwargs: Any) -> str:+ value: Any = self._prompts+ for part in key.split("."):+ if not isinstance(value, dict) or part not in value:+ return default+ value = value[part]+ if not isinstance(value, str):+ return default+ if kwargs:+ try:+ return value.format(**kwargs)+ except (KeyError, IndexError, ValueError):+ return value+ return value+++# ---------------------------------------------------------------------------+# LoopHosts+# ---------------------------------------------------------------------------+++class _BaseLoopHost:+ """Common LoopHost wiring shared by explore + quiz hosts.++ Subclasses customize the iteration trace metadata, the final-emission+ behavior, and the force-finalize copy.+ """++ def __init__(+ self,+ *,+ pipeline: QuestionPipeline,+ stream: StreamBus,+ context: UnifiedContext,+ client: Any,+ ) -> None:+ self._pipeline = pipeline+ self._stream = stream+ self._context = context+ self._client = client++ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:+ # v1 doesn't run an in-loop trimmer for the quiz pipeline. Per-phase+ # message buffers are bounded by max_iterations × per-call size.+ return++ async def dispatch_tools(+ self,+ *,+ iteration: int,+ tool_calls: list[dict[str, Any]],+ ) -> DispatchOutcome:+ too_many = None+ if len(tool_calls) > MAX_PARALLEL_TOOL_CALLS:+ too_many = self._pipeline._t(+ "notices.too_many_tool_calls",+ requested=len(tool_calls),+ limit=MAX_PARALLEL_TOOL_CALLS,+ )+ return await dispatch_tool_calls(+ tool_calls=tool_calls,+ context=self._context,+ stream=self._stream,+ source=SOURCE,+ stage=self._stage,+ iteration_index=iteration,+ registry=self._pipeline.registry,+ kwarg_augmenter=self._pipeline._augment_tool_kwargs,+ retrieve_meta_factory=lambda meta, tn, ta: self._pipeline._retrieve_trace_metadata(+ meta, tool_name=tn, tool_args=ta+ ),+ tool_call_label=self._pipeline._t("labels.tool_call", default="Tool call"),+ retrieve_label=self._pipeline._t("labels.retrieve", default="Retrieve"),+ empty_tool_result_message=self._pipeline._t("notices.empty_tool_result"),+ start_retrieval_message=self._pipeline._t(+ "notices.start_retrieval", default="Starting retrieval"+ ),+ too_many_tool_calls_message=too_many,+ unknown_error_message_factory=lambda tn: self._pipeline._t(+ "notices.tool_unknown_error",+ tool=tn,+ default=f"Error executing {tn}.",+ ),+ trace_id_prefix=self._trace_id_prefix,+ )++ async def resolve_pause(self, dispatch: DispatchOutcome) -> bool:+ # ``ask_user`` would pause the turn — quiz pipeline v1 doesn't wire up+ # the wait/resume path. Terminate the loop so the turn closes cleanly.+ return False++ async def emit_terminator(self, payload: dict[str, Any] | None) -> None:+ # No quiz tool is wired to terminate the loop with content.+ return++ def assistant_message_with_tool_calls(+ self,+ *,+ content: str,+ tool_calls: list[dict[str, Any]],+ ) -> dict[str, Any]:+ return {+ "role": "assistant",+ "content": content or None,+ "tool_calls": [+ {+ "id": tc["id"],+ "type": "function",+ "function": {+ "name": tc["name"],+ "arguments": tc.get("arguments") or "{}",+ },+ }+ for tc in tool_calls+ ],+ }++ def protocol_retry_notice(self) -> str:+ return self._pipeline._t(+ "notices.protocol_retry",+ default="The model violated the action-label protocol; retrying.",+ )++ def protocol_repair_message(self, violation: str) -> str:+ return self._pipeline._t(+ f"protocol.{violation}",+ default=f"Protocol violation: {violation}.",+ )++ # The two attributes below are set by each subclass.+ _stage: str = ""+ _trace_id_prefix: str = "iter"+++class _ExploreLoopHost(_BaseLoopHost):+ """Drives the Explore phase. FINISH streams live to the chat bubble.++ Layers a Tool Summarizer over the base ``dispatch_tools``: after the+ parent dispatch returns, this host fires one main-model LLM call per+ ``role=tool`` message to compress the raw result into a concise summary,+ streams that summary to a "Reflecting..." trace node, and substitutes it+ back into the loop's message buffer. Downstream phases see only the+ summarized version via the exploration_trace.+ """++ _stage = STAGE_EXPLORING+ _trace_id_prefix = "quiz-explore-iter"++ async def dispatch_tools(+ self,+ *,+ iteration: int,+ tool_calls: list[dict[str, Any]],+ ) -> DispatchOutcome:+ outcome = await super().dispatch_tools(+ iteration=iteration, tool_calls=tool_calls+ )+ if not self._pipeline.tool_summarizer_enabled or not outcome.tool_messages:+ return outcome++ # Build a tool_call_id → name map so the reflection node carries a+ # human-readable tool label.+ name_by_id: dict[str, str] = {}+ for tc in tool_calls:+ tc_id = tc.get("id") or ""+ if tc_id:+ name_by_id[tc_id] = str(tc.get("name") or "tool")++ summarized: list[dict[str, Any]] = []+ for message in outcome.tool_messages:+ new_message = dict(message)+ content = str(message.get("content") or "")+ tc_id = str(message.get("tool_call_id") or "")+ tool_name = name_by_id.get(tc_id, "tool")+ summary = await self._pipeline._summarize_tool_result(+ tool_name=tool_name,+ tool_result=content,+ iteration=iteration,+ stream=self._stream,+ client=self._client,+ )+ if summary:+ new_message["content"] = summary+ summarized.append(new_message)++ return DispatchOutcome(+ sources=outcome.sources,+ tool_messages=summarized,+ terminate=outcome.terminate,+ terminate_payload=outcome.terminate_payload,+ pause=outcome.pause,+ pause_payload=outcome.pause_payload,+ pause_tool_call_id=outcome.pause_tool_call_id,+ )++ def build_iteration_trace_meta(+ self, iteration: int+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ iter_call_id = new_call_id(f"quiz-explore-iter-{iteration}")+ iter_meta = build_trace_metadata(+ call_id=iter_call_id,+ phase=STAGE_EXPLORING,+ label=self._pipeline._t("labels.reasoning", default="Reasoning"),+ call_kind="llm_reasoning",+ trace_id=iter_call_id,+ trace_role="thought",+ trace_group="stage",+ )+ final_call_id = new_call_id("quiz-explore-final")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase=STAGE_EXPLORING,+ label=self._pipeline._t("labels.explore", default="Explore"),+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ )+ return iter_meta, final_meta++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ # Reached when ``stream_body_live=False`` would have been set; the+ # explore loop runs with ``stream_body_live=True`` so the+ # ``run_agentic_loop`` skips this. Kept for protocol compliance.+ if not text:+ return+ await self._stream.content(+ text,+ source=SOURCE,+ stage=STAGE_EXPLORING,+ metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_output"}),+ )++ async def force_finalize(+ self,+ *,+ messages: list[dict[str, Any]],+ start_iteration: int,+ ) -> tuple[str, bool, int]:+ return await self._pipeline._force_finish(+ client=self._client,+ messages=messages,+ stream=self._stream,+ stage=STAGE_EXPLORING,+ trace_root="quiz-explore",+ trace_extras={+ "call_kind": "llm_reasoning",+ "trace_role": "thought",+ "trace_group": "stage",+ },+ stream_body_live=True,+ )+++class _QuizLoopHost(_BaseLoopHost):+ """Drives one quiz question's loop.++ FINISH text is buffered (``stream_body_live=False``); the pipeline+ parses + repairs + emits a structured ``quiz_question_emitted`` event+ after the loop returns. This host's ``emit_final`` is a deliberate+ no-op so the loop doesn't drop the raw JSON into the chat bubble.+ """++ _stage = STAGE_QUIZZING++ def __init__(+ self,+ *,+ pipeline: QuestionPipeline,+ template: QuizTemplate,+ stream: StreamBus,+ context: UnifiedContext,+ client: Any,+ ) -> None:+ super().__init__(pipeline=pipeline, stream=stream, context=context, client=client)+ self._template = template+ self._trace_id_prefix = f"quiz-{template.question_id}-iter"++ def build_iteration_trace_meta(+ self, iteration: int+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ iter_call_id = new_call_id(f"quiz-{self._template.question_id}-iter-{iteration}")+ iter_meta = build_trace_metadata(+ call_id=iter_call_id,+ phase=STAGE_QUIZZING,+ label=self._pipeline._t("labels.reasoning", default="Reasoning"),+ call_kind="llm_reasoning",+ trace_id=iter_call_id,+ trace_role="thought",+ trace_group=TRACE_GROUP_QUIZ,+ question_id=self._template.question_id,+ )+ # The visible "Question" card is emitted by the pipeline after the+ # loop returns (with the structured qa_pair). ``final_meta`` is+ # never consumed because ``stream_body_live=False`` AND+ # ``emit_final`` is a no-op for this host.+ return iter_meta, iter_meta++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ # Intentional no-op. See class docstring.+ return++ async def force_finalize(+ self,+ *,+ messages: list[dict[str, Any]],+ start_iteration: int,+ ) -> tuple[str, bool, int]:+ return await self._pipeline._force_finish(+ client=self._client,+ messages=messages,+ stream=self._stream,+ stage=STAGE_QUIZZING,+ trace_root=f"quiz-{self._template.question_id}",+ trace_extras={+ "call_kind": "llm_reasoning",+ "trace_role": "thought",+ "trace_group": TRACE_GROUP_QUIZ,+ "question_id": self._template.question_id,+ },+ stream_body_live=False,+ )+++# Awaitable re-export so host return types resolve cleanly when callers+# type-check this module in isolation (mirrors solve/pipeline.py).+_ = Awaitable # type: ignore[assignment]diff --git a/deeptutor/agents/question/prompts/en/answer_now.yaml b/deeptutor/agents/question/prompts/en/answer_now.yamldeleted file mode 100644index cd17ab3f8..000000000--- a/deeptutor/agents/question/prompts/en/answer_now.yaml+++ /dev/null@@ -1,21 +0,0 @@-system: |- You are DeepTutor's question generator. The user is waiting, so produce- a complete question set in one shot using the context already gathered.- Output strictly the JSON schema {"questions": [{"question_id": "q_1",- "question": "...", "question_type": "choice|written|coding", "options":- {"A": "..."}, "correct_answer": "...", "explanation": "...", "difficulty":- "...", "concentration": "..."}, ...]}. Omit ``options`` when the type is- not ``choice``.--user_template: |- Topic: {topic}-- Number of questions requested: {num_questions}- Preferred type: {question_type} (auto = free choice)- Preferred difficulty: {difficulty}-- {current_draft}-- {execution_trace}-- Emit the JSON object now, no surrounding prose.diff --git a/deeptutor/agents/question/prompts/en/generator.yaml b/deeptutor/agents/question/prompts/en/generator.yamldeleted file mode 100644index 8a5daadd6..000000000--- a/deeptutor/agents/question/prompts/en/generator.yaml+++ /dev/null@@ -1,51 +0,0 @@-system: |- You are the Generator in a question pipeline.- Produce high-quality Q-A pairs from a structured QuestionTemplate.- You can leverage upstream knowledge context and the user's enabled tool set as guidance.--generate: |- QuestionTemplate:- {template}-- User topic:- {user_topic}-- User preference:- {preference}-- Knowledge context prepared upstream:- {knowledge_context}-- Tools enabled by the user:- {available_tools}-- Conversation context:- {history_context}-- Previously generated questions in this session (your new question MUST be different from all of these):- {previous_questions}-- Requirements:- - Keep strict alignment with template.concentration and template.difficulty.- - Respect template.question_type exactly. Do not silently change it.- - If question_type is choice, provide exactly 4 options and one correct answer.- - For choice questions, ensure options are well-differentiated and balanced in length.- Do NOT make the correct answer noticeably longer or more detailed than distractors.- All options should be plausible and similar in style/length to avoid test-taking shortcuts.- - If question_type is written, do not provide options. The learner must write a short answer or explanation.- - If question_type is coding, do not provide options. The learner must write code, pseudocode, or an algorithmic solution.- - For written/coding questions, never ask the learner to select, choose, or pick among options.- - If you include options for a non-choice question, the output is invalid.- - Provide a clear explanation.- - Use the knowledge context when it helps ground the question.- - Treat the enabled tools list as capability guidance only; do not mention tool names in the final output.- - Do NOT generate a question that is identical or nearly identical to any of the previously generated questions listed above.-- Return JSON only:- {{- "question_type": "choice or written or coding",- "question": "question content",- "options": {{"A":"...","B":"...","C":"...","D":"..."}} or null,- "correct_answer": "choice questions use the correct option key; written/coding questions use the reference answer itself",- "explanation": "detailed explanation"- }}diff --git a/deeptutor/agents/question/prompts/en/idea_agent.yaml b/deeptutor/agents/question/prompts/en/idea_agent.yamldeleted file mode 100644index 419930f07..000000000--- a/deeptutor/agents/question/prompts/en/idea_agent.yaml+++ /dev/null@@ -1,40 +0,0 @@-system: |- You are an Idea Agent for exam question design.- Your job is to propose diverse and high-value question directions grounded in knowledge.--generate_ideas: |- Topic:- {user_topic}-- User preference:- {preference}-- Grounding knowledge:- {knowledge_context}-- Existing concentrations already used in previous batches:- {existing_concentrations}-- Generate exactly {num_ideas} candidate question ideas.- Focus on diversity, relevance, alignment with user preference, and avoid overlap- with the existing concentrations list.-- IMPORTANT — question_type must be exactly one of these three values:- - "choice" (multiple-choice, 4 options, one correct)- - "written" (short-answer / essay, no options)- - "coding" (the learner must write code / pseudocode / an algorithm, no options)- Do NOT invent other types (e.g. visual, diagram, matching, etc.).- If the task is about comparing or choosing among snippets/options, classify it as "choice", not "coding".-- Return only JSON in this format:- {{- "ideas": [- {{- "idea_id": "idea_1",- "concentration": "what this question should focus on",- "question_type": "choice | written | coding",- "difficulty": "easy or medium or hard",- "rationale": "why this idea is valuable"- }}- ]- }}diff --git a/deeptutor/agents/question/prompts/en/pipeline.yaml b/deeptutor/agents/question/prompts/en/pipeline.yamlnew file mode 100644index 000000000..81e48f4bd--- /dev/null+++ b/deeptutor/agents/question/prompts/en/pipeline.yaml@@ -0,0 +1,353 @@+# QuestionPipeline prompts (English)+#+# One YAML file owns the protocol for every LLM call quiz generation makes:+# * explore.step — agentic loop with ``THINK`` / ``TOOL`` /+# ``FINISH``; FINISH is the user-facing+# "what I learned, now let me make N questions"+# announcement (NOT used downstream)+# * tool_summarizer — single-shot reflection over one raw tool+# result, replaces the tool message in the+# explore buffer so subsequent iterations+# read a tight, lossless summary+# * plan — emit ``PLAN`` + JSON {analysis, templates[]}+# * quiz_step — agentic loop with ``THINK`` / ``TOOL`` /+# ``FINISH``; FINISH is a strict JSON payload+# for one question+# * repair — single-shot post-loop schema fixup when+# FINISH JSON is invalid+#+# Loaded via PromptManager as module="question", agent_name="pipeline".++# ---------------------------------------------------------------------------+# Trace labels (UI rows in CallTracePanel)+# ---------------------------------------------------------------------------+labels:+ explore: "Explore"+ plan: "Plan"+ quiz_step: "Question"+ reasoning: "Reasoning"+ tool_call: "Tool call"+ retrieve: "Retrieve"+ repair: "Repair question format"+ reflecting: "Reflecting"++# ---------------------------------------------------------------------------+# Phase 1: Explore (agentic loop — chat-style tools)+# ---------------------------------------------------------------------------+explore:+ system: |-+ You are the Exploration Agent for a tutor-style quiz generator. Your job in this phase is to investigate the user's request and collect the material the downstream planner / question writer will need. You are NOT writing the questions yet.++ # Output protocol (mandatory — every reply must comply)++ Every reply MUST begin with exactly one of these three labels on the very first line, all-caps, wrapped with two backticks on each side:++ ``FINISH`` → Exploration is done. The body is the user-facing exploration preface (see "Writing the FINISH content" below). No tools.+ ``TOOL`` → This reply will call tools. The body may contain one short sentence stating intent (optional). The tools themselves come through as native ``tool_calls`` in the same reply — the standard OpenAI function-calling channel. Do not type the call as JSON text in the body.+ ``THINK`` → This reply is intermediate reasoning — **no tools, and not the final summary either**. The body is your thinking; the next iteration continues from here and eventually closes with ``FINISH``.++ The runtime treats **only** ``FINISH`` as terminal. ``THINK``, ``TOOL``, and tool results keep the loop alive.++ Each reply is **one action**, not a sequence of actions. The first line tells the runtime which action this reply is. The body fills in the substance of that one action and nothing else.++ Hard rules:+ - Nothing — no prose, quotes, zero-width chars — comes before the label on the first line.+ - The label uses double backticks. Single backticks, square brackets, asterisks, or any alternate wrapper does not register.+ - Only one protocol label per reply. A reply cannot "first think, then call a tool". If you want to think, choose ``THINK`` and stop after thinking; the next iteration is where the tool gets called.+ - ``THINK`` and ``FINISH`` replies must not emit any ``tool_calls``. Conversely, ``TOOL`` must emit real native ``tool_calls`` — a ``TOOL`` reply whose body merely *describes* a call is a protocol violation.+ - Writing a JSON ``tool_calls`` array (or any equivalent shape like ``{{"name": ..., "arguments": ...}}``) as text in the body of any reply has no effect: that text is processed as reasoning prose, no tool runs, the loop just consumes an iteration. The only way to actually invoke a tool is ``TOOL`` + a real native ``tool_calls`` field on the same response.++ # How to make each iteration count++ Before you decide what this reply will be, review the conversation so far — your earlier ``THINK`` notes, the tool calls you already made, and the summarized tool results that came back. Then ask:++ 1. What do I now know that I didn't at the start of this turn?+ 2. What is still missing or uncertain for producing {num_questions} grounded questions at the requested type / difficulty?+ 3. What is the smallest next action that closes the biggest remaining gap — another retrieval, reading a specific source, looking up an external reference, more reflection, or finishing?++ Pick the action that follows from that analysis. Do **not** repeat a retrieval you already ran with the same arguments; do not call a tool whose result you already have summarized in the conversation.++ # Available capabilities (objective inventory — use only what helps)++ The runtime mounts whichever of the following are appropriate for this turn. Their presence below is not an instruction to invoke them; it is a list of what you *may* invoke when prior iterations show you still need information.++ {kb_note}+ Enabled tools:+ {tool_list}++ Notes on grounding:+ - When attachments, knowledge bases, or sources are present, prefer them over external sources if the question topic overlaps with them — the user expects questions tied to their own materials.+ - When you cite retrieved material in the FINISH preface, mark it inline with [source-id] using the exact id surfaced by the tool result.+ - Copy tool names, parameter names, and KB names verbatim from the lists above. Do not invent.++ # Prior quiz history (when present)++ If the user message context includes a "Prior quiz history" section, treat your earliest iterations as a diagnosis pass: read the entries, look for patterns in which questions were answered incorrectly (which sub-topics, which difficulty, which question type), and decide where the learner's weak spots actually live. Subsequent retrievals should bias toward material that targets those weak spots, **without** repeating prior question stems.++ If no prior quiz history is present, this diagnosis pass is unnecessary — go straight to grounding the requested topic.++ # Writing the FINISH content++ The ``FINISH`` text is shown to the user as a brief preface before questions appear. **It is not seen by the downstream planner or question writer** — they read the structured exploration trace separately. So the FINISH body's job is purely to introduce the upcoming quiz to the learner.++ Write a coherent paragraph in the user's language, covering in order:++ 1. One sentence acknowledging what they asked for.+ 2. 2–4 sentences summarizing the material the questions will draw on (cite source-ids inline when you used retrieved passages).+ 3. If you ran a diagnosis pass on prior quiz history, one sentence stating how this round will avoid prior questions and (when applicable) target weak areas.+ 4. One closing sentence transitioning into the question set, e.g., "Now let me generate {num_questions} questions for you."++ Use Markdown. Math in LaTeX: inline $...$, block $$...$$. Keep the whole FINISH under ~400 words.+ user_template: |-+ ## User request+ {user_message}++ ## Quiz parameters+ - Number of questions: {num_questions}+ - Allowed question types: {allowed_types}+ - Per-type quantity targets: {per_type_counts}+ - Requested difficulty: {difficulty}++ ## Attachments+ {attachments_summary}++ ## Conversation context+ {conversation_context}++ ## Prior quiz history (only present if the learner already did quizzes earlier in this session)+ {quiz_history}++ Begin exploring.++# ---------------------------------------------------------------------------+# Tool Summarizer (single-shot, runs after every tool result in Phase 1)+# ---------------------------------------------------------------------------+# Used by the explore loop to compress raw tool results before they go back+# to the model. The summary replaces the original tool message in the loop's+# message buffer, and is what eventually rides downstream as part of the+# exploration trace passed to plan + quiz.+tool_summarizer:+ system: |-+ You compress a single raw tool result into a concise, lossless summary so the next iteration of an exploration agent can read it cheaply. You do not see the user's request and you do not see what the tool was asked — only the raw result content.++ Rules:+ - Preserve any source-id tags, citation markers, URLs, file paths, page numbers, and section identifiers verbatim.+ - Preserve numerical facts, dates, named entities, formulas, and definitions exactly as written. Never paraphrase a quantity.+ - Drop boilerplate, navigation hints, repeated headers, fluff prose, ads, and provenance metadata that doesn't add information.+ - If the result is already short (under ~300 characters) and information-dense, restate it verbatim.+ - If the result is an error / empty / refusal, surface that fact in one line — do not invent content.+ - Output plain text. No protocol labels, no JSON, no Markdown headings. Multi-paragraph plain text is fine when warranted.+ - Hard maximum 600 words.+ user_template: |-+ Raw tool result to summarize:++ {tool_result}++# ---------------------------------------------------------------------------+# Phase 2: Plan (single LLM call — emits the per-question templates)+# ---------------------------------------------------------------------------+plan:+ system: |-+ You are the Quiz Planner. Given the exploration trace (Phase 1's full reasoning + tool-call history with summarized results) and the user's parameters, lay out exactly the questions to generate.++ Reply MUST begin with ``PLAN`` on the very first line. After the label, output exactly one JSON object of the form:++ {{"analysis": "one short paragraph explaining the question mix", "templates": [{{"question_id": "q_1", "topic": "what this question focuses on", "question_type": "choice|concept|fill_in_blank|short_answer|written|coding", "difficulty": "easy|medium|hard"}}, ...]}}++ Rules:++ 1. Produce **exactly {num_questions}** templates. If you cannot justify that many distinct topics, still output {num_questions} and make them as diverse as the material allows.+ 2. ``question_id`` must follow the pattern ``q_1``, ``q_2``, ``q_3``, ... starting at 1.+ 3. ``question_type`` must be one of:+ - ``choice`` — 4-option multiple choice (A/B/C/D), one correct.+ - ``concept`` — true/false judgement of a single proposition.+ - ``fill_in_blank`` — single-blank completion (one missing word / phrase).+ - ``short_answer`` — concept-style Q&A (a few sentences expected).+ - ``written`` — longer essay-style explanation / discussion.+ - ``coding`` — write code / pseudocode / algorithm.+ Constraints:+ - Restrict the type to those listed in "Allowed question types" (see user input). If the list is "any", pick the type that best fits each question's topic.+ - When "Per-type quantity targets" specifies counts (e.g., ``choice=3, short_answer=2``), the plan's distribution of types must match those counts exactly.+ 4. ``difficulty`` must be one of: ``easy``, ``medium``, ``hard``.+ - If the user requested a specific difficulty, every template uses it.+ - If empty / "auto", pick per template.+ 5. ``topic`` is a concise sentence describing what knowledge the question will test. **No two templates may have the same topic.** Reference concrete material from the exploration trace.+ 6. If the exploration trace shows the agent diagnosed prior quiz history, do not repeat prior topics; if learner weak areas were identified, bias coverage toward them where consistent with the user's request.+ 7. Do NOT write the question text or answer in this phase — only the template fields.+ user_template: |-+ ## Exploration trace (Phase 1's full thought + tool-call history, with summarized tool results)+ {exploration_trace}++ ## User request (original)+ {user_message}++ ## Quiz parameters+ - Number of questions: {num_questions}+ - Allowed question types: {allowed_types}+ - Per-type quantity targets: {per_type_counts}+ - Requested difficulty: {difficulty}++# ---------------------------------------------------------------------------+# Phase 3: Quiz step (one agentic loop per question)+# ---------------------------------------------------------------------------+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.++ # Output protocol (mandatory — every reply must comply)++ Every reply MUST begin with exactly one of these three labels on the very first line, all-caps, wrapped with two backticks on each side:++ ``FINISH`` → The question is ready. The body is a single JSON object matching the schema below — nothing else, no surrounding prose, no code fences, no heading. No tools.+ ``TOOL`` → This reply will call tools (to verify a fact, fetch an example, look something up). The body may contain one short sentence stating intent (optional). The tools themselves come through as native ``tool_calls`` in the same reply — the standard OpenAI function-calling channel. Do not type the call as JSON text in the body.+ ``THINK`` → This reply is intermediate reasoning — **no tools, and not the final JSON either**. The body is your thinking; the next iteration continues from here.++ The runtime treats **only** ``FINISH`` as terminal. ``THINK``, ``TOOL``, and tool results keep the loop alive.++ Each reply is **one action**, not a sequence of actions. The first line tells the runtime which action this reply is. The body fills in the substance of that one action and nothing else.++ Hard rules:+ - Nothing — no prose, quotes, zero-width chars — comes before the label on the first line.+ - The label uses double backticks. Single backticks, square brackets, asterisks, or any alternate wrapper does not register.+ - Only one protocol label per reply. A reply cannot "first think, then call a tool". If you want to think, choose ``THINK`` and stop after thinking; the next iteration is where the tool gets called.+ - ``THINK`` and ``FINISH`` replies must not emit any ``tool_calls``. Conversely, ``TOOL`` must emit real native ``tool_calls`` — a ``TOOL`` reply whose body merely *describes* a call is a protocol violation.+ - Writing a JSON ``tool_calls`` array (or any equivalent shape like ``{{"name": ..., "arguments": ...}}``) as text in the body of any reply has no effect: that text is processed as reasoning prose, no tool runs, the loop just consumes an iteration. The only way to actually invoke a tool is ``TOOL`` + a real native ``tool_calls`` field on the same response.+ - A ``FINISH`` reply's body is exactly one JSON object. No code fence wrappers, no leading heading, no text after the closing brace.++ # FINISH JSON schema (strict)++ {{+ "question_type": "choice" | "concept" | "fill_in_blank" | "short_answer" | "written" | "coding",+ "question": "the question text shown to the learner (Markdown, math in LaTeX)",+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}},+ "correct_answer": "see per-type rules below",+ "explanation": "why the correct answer is correct — a clear, learner-facing explanation"+ }}++ Hard schema rules:+ - ``question_type`` must equal the template's question_type exactly.+ - If ``question_type`` is ``choice``: ``options`` MUST contain exactly the four keys A, B, C, D, each non-empty; ``correct_answer`` MUST be one of "A", "B", "C", "D". Options should be plausible and similar in length / style — do not make the correct option noticeably longer or more detailed.+ - If ``question_type`` is ``concept``: the question is a single proposition the learner judges true or false. Omit ``options`` (or null). ``correct_answer`` MUST be exactly the lowercase string ``"true"`` or ``"false"``. Do not phrase the question as a choice.+ - If ``question_type`` is ``fill_in_blank``: the question text MUST contain exactly one occurrence of the literal blank token ``____`` (four underscores) marking the missing word or phrase. Omit ``options`` (or null). ``correct_answer`` is the string that fills the blank (a single word or short phrase). Do not pluralize alternates — pick one canonical answer.+ - If ``question_type`` is ``short_answer``: a concept-style Q&A — expected answer is a few sentences. Omit ``options`` (or null). ``correct_answer`` is the reference answer text.+ - If ``question_type`` is ``written``: a longer essay-style answer (a paragraph or more of discussion). Omit ``options`` (or null). ``correct_answer`` is the reference answer text.+ - If ``question_type`` is ``coding``: omit ``options`` (or null). ``correct_answer`` is the reference code / pseudocode / algorithm.+ - The question must align tightly with the template's ``topic`` and respect the template's ``difficulty``.+ - The question must NOT duplicate or near-duplicate any entry in "Already-generated questions this turn".+ - Cite sources inline as [source-id] when you used retrieved passages.++ Hard rules for tool calls:+ - Copy tool names, parameter names, and KB names verbatim from the "Enabled tools" / "Knowledge bases" blocks. Never invent.+ - Arguments must be concrete and executable; empty queries are invalid.++ {kb_note}+ 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}++ ## Full plan (all questions in this turn)+ {plan_summary}++ ## Already-generated questions this turn (do NOT duplicate)+ {previous_questions}++ ## Reference material (mimic mode only — paraphrase / shadow this question's style and difficulty rather than inventing a fresh stem)+ {reference_block}++ Begin work on question {question_id}.++# ---------------------------------------------------------------------------+# Repair (single shot, called only when the FINISH JSON is schema-invalid)+# ---------------------------------------------------------------------------+repair:+ system: |-+ You fix malformed quiz question JSON. Read the invalid payload and the detected issues, then output a corrected JSON object — only the JSON, nothing else.++ Hard rules:+ - Keep the same ``question_type`` as the template (do not change it).+ - If ``question_type`` is ``choice``: provide exactly four options A/B/C/D; ``correct_answer`` must be one of "A", "B", "C", "D".+ - If ``question_type`` is ``concept``: omit ``options`` (or null); ``correct_answer`` must be exactly ``"true"`` or ``"false"`` (lowercase).+ - If ``question_type`` is ``fill_in_blank``: omit ``options`` (or null); ``question`` must contain exactly one ``____`` (four underscores) marking the blank; ``correct_answer`` is the string that fills it.+ - If ``question_type`` is ``short_answer``, ``written``, or ``coding``: omit ``options`` (or null); ``correct_answer`` is the reference answer text.+ - Preserve the topic and difficulty intent.+ - Return JSON only with keys: question_type, question, options, correct_answer, explanation.+ user_template: |-+ ## Template+ - question_id: {question_id}+ - topic: {topic}+ - question_type: {question_type}+ - difficulty: {difficulty}++ ## Invalid payload+ {invalid_payload}++ ## Detected issues+ {issues}++# ---------------------------------------------------------------------------+# Protocol violation repair messages (host returns these to the loop)+# ---------------------------------------------------------------------------+protocol:+ missing_label: |-+ Protocol correction: your previous reply did not begin with a protocol label, so this iteration is not complete. Your next reply must choose exactly one action label, written once on the first line only: ``THINK``, ``TOOL``, or ``FINISH``. Do not include a second protocol label anywhere in the body.+ multiple_labels: |-+ Protocol correction: your previous reply contained multiple protocol labels. Your next reply must use exactly one action label on the first line. Do not put a second label inside the body.+ tool_without_calls: |-+ Protocol correction: you chose ``TOOL`` but emitted no real tool_calls. Use ``TOOL`` only when you emit native tool_calls in that same reply; otherwise use ``THINK`` or ``FINISH``.+ think_with_tools: |-+ Protocol correction: you chose ``THINK`` while emitting tool_calls. ``THINK`` is reasoning-only. Use ``TOOL`` if you need a tool, or ``THINK`` without tool_calls.+ finish_with_tools: |-+ Protocol correction: you chose ``FINISH`` while emitting tool_calls. ``FINISH`` is the terminal output — no tools. Use ``TOOL`` first if you still need information.+ label_with_tools: |-+ Protocol correction: you emitted tool_calls under a label that does not allow them. Use ``TOOL`` for tool calls; ``THINK`` for reasoning; ``FINISH`` for the terminal output (no tools).+ force_finish: |-+ The iteration budget is exhausted. Now produce the terminal output: the first line must be ``FINISH``. Do not call tools, do not use ``THINK``. If material is still incomplete, state the uncertainty briefly while still producing the most useful output you can.+ force_finish_repair: |-+ Finalization protocol correction: the previous reply did not produce a valid ``FINISH``. Now output only the terminal payload: first line ``FINISH``, then the required content. Do not write ``THINK`` or ``TOOL``; do not call tools.+ fallback_final: |-+ I reached the iteration limit without a valid ``FINISH``. The output may be incomplete.++# ---------------------------------------------------------------------------+# Notices (warnings emitted into the trace stream)+# ---------------------------------------------------------------------------+notices:+ start_retrieval: "Starting retrieval"+ empty_tool_result: "The tool completed without returning text output."+ too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one iteration, so the list was truncated."+ tool_unknown_error: "An unknown error occurred while executing {tool}."+ protocol_retry: "The model violated the action-label protocol; retrying this iteration."+ max_iterations_reached: "Reached the iteration ceiling. Producing the best output I can with what I have."+ context_window_guard: "Trimmed older tool results to keep within the model's context window."+ final_protocol_failed: "The model still did not produce a valid FINISH reply after the finalization prompt."+ plan_count_mismatch: "Plan returned {got} templates instead of {requested}; proceeding with what we have."+ repair_attempted: "The previous question payload was invalid; repairing the schema once."+ repair_failed: "Repair did not fully fix the question; emitting the best-effort version."+ tool_summarizer_failed: "Tool summarizer could not produce a summary; passing raw tool result forward."++empty:+ no_quiz_history: "(no prior quiz turns in this session)"+ no_attachments: "(no attachments)"+ no_conversation: "(no prior conversation)"+ no_kb: "(no knowledge base attached)"+ no_previous_questions: "(this is the first question of this turn)"+ no_explore_summary: "(exploration summary unavailable — proceed using only the user's request)"+ no_exploration_trace: "(no exploration trace — mimic mode skipped Phase 1; rely on the reference material and template fields)"+ no_reference: "(no reference material — this is a generative custom question)"++# ---------------------------------------------------------------------------+# Exploration trace rendering (markdown headings used when serializing the+# explore message buffer for downstream consumption)+# ---------------------------------------------------------------------------+trace:+ iteration_thought: "Iteration {n} — Thought"+ iteration_tool_call: "Iteration {n} — Tool call: {tool}"+ iteration_tool_result: "Iteration {n} — Tool result (summarized): {tool}"+ finish_note: "Final exploration preface (also shown to the user)"diff --git a/deeptutor/agents/question/prompts/zh/answer_now.yaml b/deeptutor/agents/question/prompts/zh/answer_now.yamldeleted file mode 100644index 9cd0bdbbe..000000000--- a/deeptutor/agents/question/prompts/zh/answer_now.yaml+++ /dev/null@@ -1,21 +0,0 @@-system: |- 你是 DeepTutor 的题目生成器。用户已经在等待,请基于现有信息直接输出一组题目。- 严格输出 JSON:{"questions": [{"question_id": "q_1",- "question": "...", "question_type": "choice|written|coding",- "options": {"A": "..."}, "correct_answer": "...",- "explanation": "...", "difficulty": "...",- "concentration": "..."}, ...]}。- 若不是 choice 题,options 字段可省略。所有字符串使用 UTF-8。--user_template: |- 用户原始问题/主题:{topic}-- 题量要求:{num_questions}- 题型偏好:{question_type}(auto 表示自由选择)- 难度偏好:{difficulty}-- {current_draft}-- {execution_trace}-- 立即输出符合上述 JSON schema 的题目集合,不要包含其他文字。diff --git a/deeptutor/agents/question/prompts/zh/generator.yaml b/deeptutor/agents/question/prompts/zh/generator.yamldeleted file mode 100644index 8a1af8c09..000000000--- a/deeptutor/agents/question/prompts/zh/generator.yaml+++ /dev/null@@ -1,50 +0,0 @@-system: |- 你是出题流程中的 Generator。- 你需要基于结构化的 QuestionTemplate 产出高质量 Q-A 对。- 当上游提供了知识上下文和可用工具信息时,可将其作为出题依据。--generate: |- QuestionTemplate:- {template}-- 用户主题:- {user_topic}-- 用户偏好:- {preference}-- 上游准备好的知识上下文:- {knowledge_context}-- 用户当前启用的工具:- {available_tools}-- 对话上下文:- {history_context}-- 本次会话中已生成的题目(你的新题目必须与以下所有题目不同):- {previous_questions}-- 要求:- - 严格对齐 template.concentration 与 template.difficulty。- - 必须严格遵循 template.question_type,不要私自改题型。- - 若为选择题,必须提供恰好 4 个选项且仅 1 个正确答案。- - 选择题的各选项长度应大致均衡,不要让正确选项明显比干扰项更长或更详细。- 所有选项应具有合理的迷惑性,风格和长度相近,避免考生通过选项长度猜出答案。- - 若为 written 题,不要提供选项,作答方式应为简答、解释或分析。- - 若为 coding 题,不要提供选项,作答方式应为编写代码、伪代码或算法步骤。- - 对于 written/coding 题,禁止要求学习者在若干选项中选择答案。- - 如果非选择题仍然给出 A/B/C/D 选项,则该输出视为无效。- - 给出清晰解释。- - 在有帮助时使用知识上下文增强题目质量。- - 可将启用工具列表视为能力提示,但不要在最终题目中直接提及工具名称。- - 不要生成与上面已生成题目相同或高度相似的题目。-- 仅返回 JSON:- {{- "question_type": "choice 或 written 或 coding",- "question": "题目内容",- "options": {{"A":"...","B":"...","C":"...","D":"..."}} 或 null,- "correct_answer": "选择题填写正确选项键;written/coding 题填写参考答案本身",- "explanation": "详细解释"- }}diff --git a/deeptutor/agents/question/prompts/zh/idea_agent.yaml b/deeptutor/agents/question/prompts/zh/idea_agent.yamldeleted file mode 100644index 2554375e7..000000000--- a/deeptutor/agents/question/prompts/zh/idea_agent.yaml+++ /dev/null@@ -1,39 +0,0 @@-system: |- 你是考试题目设计流程中的 Idea Agent。- 你的职责是基于知识内容提出多样、有效、可执行的出题方向。--generate_ideas: |- 主题:- {user_topic}-- 用户偏好:- {preference}-- 知识依据:- {knowledge_context}-- 前几批已经使用过的考察点:- {existing_concentrations}-- 请生成恰好 {num_ideas} 个候选出题创意。- 重点关注:多样性、相关性、与用户偏好的一致性,并尽量避免与已有考察点重复。-- 重要 — question_type 只允许以下三个值之一:- - "choice" (选择题,4 选 1)- - "written" (简答 / 论述题,不带选项)- - "coding" (要求学习者自己写代码、伪代码或算法步骤,不带选项)- 不要使用其他类型(如 visual、diagram、matching 等)。- 如果题目本质上是在若干代码片段/选项中做判断或选择,应归类为 "choice",而不是 "coding"。-- 仅返回 JSON,格式如下:- {{- "ideas": [- {{- "idea_id": "idea_1",- "concentration": "该题主要考察点",- "question_type": "choice | written | coding",- "difficulty": "easy 或 medium 或 hard",- "rationale": "该创意的价值"- }}- ]- }}diff --git a/deeptutor/agents/question/prompts/zh/pipeline.yaml b/deeptutor/agents/question/prompts/zh/pipeline.yamlnew file mode 100644index 000000000..29bb89a7e--- /dev/null+++ b/deeptutor/agents/question/prompts/zh/pipeline.yaml@@ -0,0 +1,333 @@+# QuestionPipeline 提示词(中文)+# 参见 en/pipeline.yaml 了解协议总览。++# ---------------------------------------------------------------------------+# Trace 标签(CallTracePanel 行标题)+# ---------------------------------------------------------------------------+labels:+ explore: "探索"+ plan: "规划"+ quiz_step: "题目"+ reasoning: "推理"+ tool_call: "工具调用"+ retrieve: "检索"+ repair: "修复题目格式"+ reflecting: "反思"++# ---------------------------------------------------------------------------+# 阶段 1:探索(agentic loop —— 沿用 chat 风格工具集)+# ---------------------------------------------------------------------------+explore:+ system: |-+ 你是 tutor 风格出题流程中的「探索代理」。本阶段的任务是在出题之前**调研用户请求并为下游规划器 / 出题器收集素材**——本阶段**不写题**。++ # 输出协议(强制)++ 每次回复**必须**以以下三个标签之一开头,全大写,第一行用两个反引号包裹:++ ``FINISH`` → 探索完成。正文是**面向用户的探索前言**(写法见下方「写 FINISH 内容」)。**不**调工具。+ ``TOOL`` → 本次回复要调工具。正文里可以写**一句**简短意图(可选)。工具本身通过**原生 ``tool_calls`` 字段**在同一次回复里发出——这是标准的 OpenAI function-calling 通道。**不要**把工具调用以 JSON 文字形式写在正文里。+ ``THINK`` → 本次回复只是中间推理——**不调工具,也不是最终前言**。正文是你的思路;下一轮迭代接着想,最终用 ``FINISH`` 收尾。++ 运行时**只**把 ``FINISH`` 视为终止信号;``THINK``、``TOOL``、工具结果都让循环继续。++ **每次回复是一个动作,不是动作序列。** 第一行告诉运行时本次回复是哪个动作,正文是该动作的具体内容,**仅此而已**。++ 硬性规则:+ - 第一行的标签前面**绝对不能**有任何东西——前导文字、引号、不可见字符都不行。+ - 标签必须用**两个**反引号包裹。单反引号、方括号、星号、或任何其他包裹方式**不会被识别**。+ - **一次回复只能有一个协议标签。** 一次回复**不能**"先 think 然后调工具"——如果你想思考,就用 ``THINK`` 然后停在思考;调工具留给下一轮迭代。+ - ``THINK`` 和 ``FINISH`` 回复**绝不**带任何 ``tool_calls``。反过来,``TOOL`` **必须**发出真实的原生 ``tool_calls``——只在正文里**描述**工具调用的 ``TOOL`` 回复属于协议违规。+ - 在任何回复的正文里写 JSON 形式的 ``tool_calls`` 数组(或类似形状如 ``{{"name": ..., "arguments": ...}}``)**完全没用**:那段文字会被当作思考文字处理,**工具不会被执行**,本轮迭代白费。**唯一能真正触发工具的方式**:用 ``TOOL`` 开头 + 在同一次回复里通过原生 ``tool_calls`` 字段发出。++ # 让每次迭代都有价值++ 在决定本次回复要做什么之前,先复盘到目前为止的对话——你之前的 ``THINK`` 笔记、已经发起的工具调用、以及返回的「已概括的工具结果」。然后问自己:++ 1. 我现在比本轮开始时多知道了什么?+ 2. 为了产出 {num_questions} 道符合指定类型 / 难度且**有依据**的题目,我还缺什么、还有哪些不确定?+ 3. 让最大的剩余信息缺口收窄的「最小下一步」是什么——再做一次检索、读一个具体的 source、查一下外部资料、再多思考一轮、还是直接收尾?++ 依据这一分析选择动作。**不要**在同一参数下重复已经做过的检索;**不要**调用结果已经在对话历史里被概括过的工具。++ # 可用能力(客观清单——按需使用)++ 运行时会根据本轮上下文挂载下述能力。它们出现在列表里**不是**让你必须调用的指示,而是**当之前的迭代显示你确实还缺信息时,你可以调用的备选**。++ {kb_note}+ 启用的工具:+ {tool_list}++ 依据原则:+ - 当有附件、知识库或 source 文档存在、且话题与之重叠时,**优先**使用它们而不是外部检索——用户希望题目扣住他自己的素材。+ - 在 FINISH 前言里引用检索内容时,以 [source-id] 行内引用,使用工具结果给出的精确 id。+ - 工具名、参数名、知识库名必须**逐字**抄自上方列表,**不要**编造。++ # 历史出题记录(仅当上下文中存在时)++ 如果用户上下文里含「Prior quiz history / 历史出题记录」段落,把最早的几次迭代当作**诊断阶段**:读条目,找出错题模式(哪些子主题、哪些难度、哪些题型容易错),判断学习者真正的薄弱点。后续检索应**偏向**针对这些薄弱点的素材,**不要**重复旧题面。++ 如果**没有**历史出题记录,这个诊断阶段不需要——直接为指定主题取材即可。++ # 写 FINISH 内容++ ``FINISH`` 文本会作为出题前的简短前言**展示给用户**。**它不会传给下游的规划器或出题器**——后者会单独读到一份结构化的探索轨迹。所以 FINISH 正文的唯一职责是**向学习者介绍本轮即将出现的题目**。++ 请用**用户的语言**写一段连贯的话,按以下顺序:++ 1. 一句话确认用户的请求。+ 2. 2–4 句概述题目将依据的素材 / 知识(用到检索内容时以 [source-id] 行内引用)。+ 3. 如果你针对历史出题记录做了诊断,用一句话说明本次将如何避开旧题目(如适用,覆盖薄弱点)。+ 4. 一句过渡到出题,例如「现在为你出 {num_questions} 道题。」++ 使用 Markdown,数学用 LaTeX:行内 $...$,行间 $$...$$。整段 FINISH 控制在约 400 字以内。+ user_template: |-+ ## 用户请求+ {user_message}++ ## 出题参数+ - 题目数量:{num_questions}+ - 允许的题型:{allowed_types}+ - 各题型数量分配:{per_type_counts}+ - 指定难度:{difficulty}++ ## 附件+ {attachments_summary}++ ## 对话上下文+ {conversation_context}++ ## 历史出题记录(仅当本 session 之前出过题时存在)+ {quiz_history}++ 开始探索。++# ---------------------------------------------------------------------------+# 工具结果概括(单次调用,每个工具结果返回后都跑一次)+# ---------------------------------------------------------------------------+# 由 explore loop 在每次拿到工具结果后调用。概括后的文本会**替换**原始工具+# 消息进入 loop 的 message buffer,并最终随 exploration_trace 传给下游。+tool_summarizer:+ system: |-+ 你的任务是把**一条原始工具结果**压成一段精炼、**不丢信息**的概括,让下一轮探索代理能以更低成本读到它。你**看不到**用户请求、也**看不到**当时的工具调用参数——只有结果内容本身。++ 规则:+ - **完整保留** source-id 标签、引用标记、URL、文件路径、页码、章节编号等。+ - **完整保留**数值、日期、专有名词、公式、定义——**绝不**改写数量。+ - 删除模板化文本、导航提示、重复标题、废话、广告、与下游无关的元信息。+ - 如果结果本来就很短(约 300 字符以内)且信息密度高,**原样照抄**。+ - 如果结果是错误 / 空 / 拒绝,用一句话指出这个事实——**不要**编造内容。+ - 输出纯文本:不写协议标签、不写 JSON、不写 Markdown 标题。可分段,按需即可。+ - 硬上限 600 字。+ user_template: |-+ 待概括的原始工具结果:++ {tool_result}++# ---------------------------------------------------------------------------+# 阶段 2:规划(单次 LLM 调用——输出每道题的 template)+# ---------------------------------------------------------------------------+plan:+ system: |-+ 你是「出题规划器」。基于探索轨迹(阶段 1 的完整推理 + 工具调用历史,工具结果已概括)和用户参数,给出本次要生成的所有题目蓝图。++ 回复**必须**以 ``PLAN`` 开头,第一行用两个反引号包裹。标签之后输出**恰好一个** JSON 对象:++ {{"analysis": "一段简短的题型/难度搭配说明", "templates": [{{"question_id": "q_1", "topic": "本题考查的具体内容", "question_type": "choice|concept|fill_in_blank|short_answer|written|coding", "difficulty": "easy|medium|hard"}}, ...]}}++ 规则:++ 1. **恰好输出 {num_questions} 个** template。即使你觉得很难找出这么多不同主题,也要尽力让它们在素材范围内最大化差异。+ 2. ``question_id`` 遵循 ``q_1``、``q_2``、``q_3`` … 的格式,从 1 开始。+ 3. ``question_type`` 必须是以下之一:+ - ``choice``——4 选 1 选择题(A/B/C/D),一个正确答案。+ - ``concept``——单一命题的「判断对错」题。+ - ``fill_in_blank``——单空填空(一个缺失的词或短语)。+ - ``short_answer``——概念性简答(预期几句话)。+ - ``written``——更长的论述 / 解答(一段甚至多段)。+ - ``coding``——写代码 / 伪代码 / 算法。+ 约束:+ - 类型必须在「允许的题型」列表中(参见用户输入)。若列表为 "any",按每道题最合适的类型选择。+ - 若「各题型数量分配」给出了配比(例如 ``choice=3, short_answer=2``),plan 中的类型分布必须严格符合该配比。+ 4. ``difficulty`` 必须是以下之一:``easy``、``medium``、``hard``。+ - 如果用户指定了难度,所有 template 使用该难度。+ - 如果为空 / "auto",按 template 选择。+ 5. ``topic`` 是一句话描述本题考查什么知识点。**两个 template 不允许有相同的 topic。** 直接引用探索轨迹中的具体素材。+ 6. 如果探索轨迹显示代理诊断过历史出题记录,**不要**重复旧主题;若识别出学习者薄弱点,且与用户请求一致,可优先围绕这些点。+ 7. 本阶段**不要**写题面或答案——只输出 template 字段。+ user_template: |-+ ## 探索轨迹(阶段 1 完整思考 + 工具调用历史,工具结果已概括)+ {exploration_trace}++ ## 用户原请求+ {user_message}++ ## 出题参数+ - 题目数量:{num_questions}+ - 允许的题型:{allowed_types}+ - 各题型数量分配:{per_type_counts}+ - 指定难度:{difficulty}++# ---------------------------------------------------------------------------+# 阶段 3:出题(每道题一个 agentic loop)+# ---------------------------------------------------------------------------+quiz_step:+ system: |-+ 你正在写**一道**测验题(第 {question_number}/{total_questions} 道),依据规划器已经固定下来的 template。探索轨迹(阶段 1 完整推理 + 工具调用历史,工具结果已概括)和本轮已生成题目的列表都已提供,请据此做出有依据、不重复的题目。++ # 输出协议(强制)++ 每次回复**必须**以以下三个标签之一开头,全大写,第一行用两个反引号包裹:++ ``FINISH`` → 题目已就绪。正文是**恰好一个**符合下方 schema 的 JSON 对象——没有其他文字、没有代码块包裹、没有标题、闭合括号之后也不能再写任何东西。**不**调工具。+ ``TOOL`` → 本次回复要调工具(核实事实、拉取例子、查询资料等)。正文里可以写**一句**简短意图(可选)。工具本身通过**原生 ``tool_calls`` 字段**在同一次回复里发出——这是标准的 OpenAI function-calling 通道。**不要**把工具调用以 JSON 文字形式写在正文里。+ ``THINK`` → 本次回复只是中间推理——**不调工具,也不是最终 JSON**。正文是你的思路;下一轮迭代接着想。++ 运行时**只**把 ``FINISH`` 视为终止信号;``THINK``、``TOOL``、工具结果都让循环继续。++ **每次回复是一个动作,不是动作序列。** 第一行告诉运行时本次回复是哪个动作,正文是该动作的具体内容,**仅此而已**。++ 硬性规则:+ - 第一行的标签前面**绝对不能**有任何东西。+ - 标签必须用**两个**反引号包裹。单反引号、方括号、星号、或其他包裹方式**不会被识别**。+ - **一次回复只能有一个协议标签。** 一次回复**不能**"先 think 然后调工具"。+ - ``THINK`` 和 ``FINISH`` 回复**绝不**带任何 ``tool_calls``。反过来,``TOOL`` **必须**发出真实的原生 ``tool_calls``——只在正文里**描述**工具调用的 ``TOOL`` 回复属于协议违规。+ - 在任何回复的正文里写 JSON 形式的 ``tool_calls`` 数组(或类似形状如 ``{{"name": ..., "arguments": ...}}``)**完全没用**:那段文字会被当作思考文字处理,**工具不会被执行**。**唯一能真正触发工具的方式**:用 ``TOOL`` 开头 + 在同一次回复里通过原生 ``tool_calls`` 字段发出。+ - ``FINISH`` 回复的正文**就是一个 JSON 对象**,不要包代码块、不要加标题、闭合括号之后不要再写任何文字。++ # FINISH 的 JSON schema(严格)++ {{+ "question_type": "choice" | "concept" | "fill_in_blank" | "short_answer" | "written" | "coding",+ "question": "向学习者展示的题面(Markdown,数学用 LaTeX)",+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}},+ "correct_answer": "见下方各题型规则",+ "explanation": "为什么正确答案是正确的——面向学习者的清晰解释"+ }}++ 硬性 schema 规则:+ - ``question_type`` 必须**完全等于** template 的 question_type。+ - 如果 ``question_type`` 是 ``choice``:``options`` 必须**恰好**包含 A、B、C、D 四个 key,每个非空;``correct_answer`` 必须是 "A"、"B"、"C"、"D" 之一。选项要可信且**长度 / 风格相近**——**不要**把正确选项写得明显比干扰项更长或更详细。+ - 如果 ``question_type`` 是 ``concept``:题面是**一个命题**,由学习者判断对错。省略 ``options``(或 null);``correct_answer`` 必须是小写字符串 ``"true"`` 或 ``"false"``。**不要**把题目写成「以下哪项…」式的选择。+ - 如果 ``question_type`` 是 ``fill_in_blank``:题面中**必须**包含**恰好一处** ``____``(四个下划线),用于标记缺失的词或短语。省略 ``options``(或 null);``correct_answer`` 是填入空白处的字符串(一个词或短语)。**不要**列多个并列答案——选一个最规范的。+ - 如果 ``question_type`` 是 ``short_answer``:概念性简答,期望答案是几句话。省略 ``options``(或 null);``correct_answer`` 是参考答案文本。+ - 如果 ``question_type`` 是 ``written``:更长的论述 / 解答(一段甚至多段)。省略 ``options``(或 null);``correct_answer`` 是参考答案文本。+ - 如果 ``question_type`` 是 ``coding``:省略 ``options``(或 null);``correct_answer`` 是参考代码 / 伪代码 / 算法。+ - 题目必须严格扣住 template 的 ``topic``,并符合 ``difficulty``。+ - 题目**不允许**重复 / 近似重复「本轮已生成题目」中的任何一项。+ - 如用到检索内容,以 [source-id] 行内引用。++ 工具调用的硬规则:+ - 工具名、参数名、知识库名必须**逐字**抄自下方「启用的工具」/「知识库」块。**不要**编造。+ - 参数必须具体可执行;空查询无效。++ {kb_note}+ 启用的工具:+ {tool_list}+ user_template: |-+ ## 本题 template+ - question_id: {question_id}+ - topic: {topic}+ - question_type: {question_type}+ - difficulty: {difficulty}++ ## 探索轨迹(阶段 1 完整思考 + 工具调用历史,工具结果已概括)+ {exploration_trace}++ ## 完整规划(本轮所有题目)+ {plan_summary}++ ## 本轮已生成题目(**不要**重复)+ {previous_questions}++ ## 参考素材(仅 mimic 模式使用——本题应**仿写 / 改编**该参考题的风格和难度,**不要**另起炉灶)+ {reference_block}++ 开始为 {question_id} 出题。++# ---------------------------------------------------------------------------+# 修复(仅在 FINISH JSON schema 不合法时一次性调用)+# ---------------------------------------------------------------------------+repair:+ system: |-+ 你来修复一个不合法的题目 JSON。读 invalid payload 和检测到的问题,然后输出修正后的 JSON 对象——**只**输出 JSON,不要其他内容。++ 硬性规则:+ - ``question_type`` 与 template 一致(**不要**改)。+ - 如果是 ``choice``:提供恰好四个选项 A/B/C/D;``correct_answer`` 必须是 "A"/"B"/"C"/"D" 之一。+ - 如果是 ``concept``:省略 ``options``(或 null);``correct_answer`` 必须是小写的 ``"true"`` 或 ``"false"``。+ - 如果是 ``fill_in_blank``:省略 ``options``(或 null);``question`` 中必须包含**恰好一处** ``____``(四个下划线);``correct_answer`` 是填入空白处的字符串。+ - 如果是 ``short_answer``、``written`` 或 ``coding``:省略 ``options``(或 null);``correct_answer`` 是参考答案文本。+ - 保留原 topic 和 difficulty 意图。+ - 返回 JSON 只包含字段:question_type, question, options, correct_answer, explanation。+ user_template: |-+ ## Template+ - question_id: {question_id}+ - topic: {topic}+ - question_type: {question_type}+ - difficulty: {difficulty}++ ## 无效载荷+ {invalid_payload}++ ## 检测到的问题+ {issues}++# ---------------------------------------------------------------------------+# 协议违规修复提示(host 返回给 loop 用)+# ---------------------------------------------------------------------------+protocol:+ missing_label: |-+ 协议修正:你上一轮回复没有以协议标签开头,本轮还不算完成。下一次回复**必须**在第一行写**且仅写**一个动作标签:``THINK``、``TOOL`` 或 ``FINISH``。正文里**不要**再出现第二个协议标签。+ multiple_labels: |-+ 协议修正:上一轮回复出现了多个协议标签。下一次回复在第一行**只**写一个动作标签,正文里**不要**再放第二个标签。+ tool_without_calls: |-+ 协议修正:你选择了 ``TOOL`` 但没有发出真实的 tool_calls。``TOOL`` 必须在同一次回复里发出 tool_calls;否则改用 ``THINK`` 或 ``FINISH``。+ think_with_tools: |-+ 协议修正:你选择了 ``THINK`` 同时发起了工具调用。``THINK`` 只用于思考。需要工具就用 ``TOOL``;只想思考就用 ``THINK`` 且**不要**调工具。+ finish_with_tools: |-+ 协议修正:你选择了 ``FINISH`` 同时发起了工具调用。``FINISH`` 是终止输出——**不要**调工具。如果还需要信息,先用 ``TOOL``。+ label_with_tools: |-+ 协议修正:你在不允许带 tool_calls 的标签下发起了工具调用。需要工具用 ``TOOL``,需要思考用 ``THINK``,需要终止输出用 ``FINISH``(**不**带工具)。+ force_finish: |-+ 迭代预算已用完。现在必须给出终止输出:第一行必须是 ``FINISH``,**不要**再调用工具、**不要**用 ``THINK``。即使素材不完整,也请简短说明不确定性,并仍输出当前最有用的内容。+ force_finish_repair: |-+ 最终化协议修正:上一轮没有按 ``FINISH`` 协议输出。现在只输出终止载荷:第一行 ``FINISH``,后面直接写要求的内容。**不要**写 ``THINK`` / ``TOOL``,**不要**调工具。+ fallback_final: |-+ 已达迭代上限但模型未给出有效的 ``FINISH``。输出可能不完整。++# ---------------------------------------------------------------------------+# Notices(流式到 trace 框的提示)+# ---------------------------------------------------------------------------+notices:+ start_retrieval: "开始检索"+ empty_tool_result: "工具完成但未返回文本输出。"+ too_many_tool_calls: "模型请求了 {requested} 个工具。一次最多并行 {limit} 个,已截断。"+ tool_unknown_error: "执行 {tool} 时出现未知错误。"+ protocol_retry: "模型违反了动作标签协议;本轮重试。"+ max_iterations_reached: "已达迭代上限。基于当前已有内容产出输出。"+ context_window_guard: "为了保持在模型上下文窗口内,裁剪了较早的工具结果。"+ final_protocol_failed: "最终化提示之后模型仍未给出有效的 FINISH 回复。"+ plan_count_mismatch: "规划返回了 {got} 个 template(要求 {requested} 个),按实际数量继续。"+ repair_attempted: "上一轮题目载荷不合法;做一次 schema 修复。"+ repair_failed: "修复未能完全修正题目;使用尽力版本输出。"+ tool_summarizer_failed: "工具结果概括失败;将把原始工具结果传给下一轮。"++empty:+ no_quiz_history: "(本 session 之前没有出过题)"+ no_attachments: "(无附件)"+ no_conversation: "(无对话上下文)"+ no_kb: "(未挂载知识库)"+ no_previous_questions: "(这是本轮第一题)"+ no_explore_summary: "(探索总结不可用——仅基于用户请求出题)"+ no_exploration_trace: "(无探索轨迹——mimic 模式跳过了阶段 1;请依赖参考素材和 template 字段)"+ no_reference: "(无参考素材——这是从零生成的自定义题)"++# ---------------------------------------------------------------------------+# 探索轨迹渲染(把 explore 阶段的 message buffer 序列化给下游时用的标题)+# ---------------------------------------------------------------------------+trace:+ iteration_thought: "迭代 {n} —— 思考"+ iteration_tool_call: "迭代 {n} —— 工具调用:{tool}"+ iteration_tool_result: "迭代 {n} —— 工具结果(已概括):{tool}"+ finish_note: "最终探索前言(同时展示给用户)"diff --git a/deeptutor/agents/question/request_config.py b/deeptutor/agents/question/request_config.pynew file mode 100644index 000000000..8a552ca0e--- /dev/null+++ b/deeptutor/agents/question/request_config.py@@ -0,0 +1,81 @@+"""Runtime config builder for ``QuestionPipeline``.++Mirrors the shape used by :mod:`deeptutor.agents.research.request_config`,+but with a much smaller surface — the question pipeline only needs a+handful of knobs out of the service config:++* ``exploring.max_iterations`` (int, default 8) — agentic-loop cap for the+ Explore phase.+* ``exploring.tool_summarizer.enabled`` (bool, default True) — toggle the+ per-tool-result LLM reflection step that compresses raw tool output+ before downstream phases see it.+* ``exploring.tool_summarizer.max_tokens`` (int, default 800) — token cap+ on each summarizer call.++The helper is intentionally tolerant: missing keys / wrong types collapse+to defaults so callers can pass any base config (e.g. ``main.yaml``)+without first defining a ``capabilities.deep_question`` section.+"""++from __future__ import annotations++from typing import Any+++def _read_int(source: dict[str, Any], key: str, default: int) -> int:+ value = source.get(key)+ if isinstance(value, int) and value > 0:+ return value+ return default+++def _read_bool(source: dict[str, Any], key: str, default: bool) -> bool:+ value = source.get(key)+ if isinstance(value, bool):+ return value+ return default+++def build_question_runtime_config(+ *,+ base_config: dict[str, Any] | None,+) -> dict[str, Any]:+ """Build the runtime_config dict passed to :class:`QuestionPipeline`.++ The pipeline reads its knobs from ``runtime_config["exploring"]`` —+ everything else in ``base_config`` is currently ignored by question.+ """+ base = base_config if isinstance(base_config, dict) else {}+ capabilities = (+ base.get("capabilities") if isinstance(base.get("capabilities"), dict) else {}+ )+ question_root = (+ capabilities.get("deep_question")+ if isinstance(capabilities.get("deep_question"), dict)+ else {}+ )+ exploring_root = (+ question_root.get("exploring")+ if isinstance(question_root.get("exploring"), dict)+ else {}+ )+ summarizer_root = (+ exploring_root.get("tool_summarizer")+ if isinstance(exploring_root.get("tool_summarizer"), dict)+ else {}+ )++ exploring = {+ "max_iterations": _read_int(exploring_root, "max_iterations", 8),+ "tool_summarizer": {+ "enabled": _read_bool(summarizer_root, "enabled", True),+ "max_tokens": _read_int(summarizer_root, "max_tokens", 800),+ },+ }++ runtime_config = dict(base)+ runtime_config["exploring"] = exploring+ return runtime_config+++__all__ = ["build_question_runtime_config"]diff --git a/deeptutor/agents/research/agents/__init__.py b/deeptutor/agents/research/agents/__init__.pydeleted file mode 100644index e1f7b4838..000000000--- a/deeptutor/agents/research/agents/__init__.py+++ /dev/null@@ -1,20 +0,0 @@-#!/usr/bin/env python-"""-DR-in-KG 2.0 Agents Module-"""--from .decompose_agent import DecomposeAgent-from .manager_agent import ManagerAgent-from .note_agent import NoteAgent-from .rephrase_agent import RephraseAgent-from .reporting_agent import ReportingAgent-from .research_agent import ResearchAgent--__all__ = [- "DecomposeAgent",- "ManagerAgent",- "NoteAgent",- "RephraseAgent",- "ReportingAgent",- "ResearchAgent",-]diff --git a/deeptutor/agents/research/agents/decompose_agent.py b/deeptutor/agents/research/agents/decompose_agent.pydeleted file mode 100644index 364cc8560..000000000--- a/deeptutor/agents/research/agents/decompose_agent.py+++ /dev/null@@ -1,482 +0,0 @@-#!/usr/bin/env python-"""-DecomposeAgent - Topic decomposition Agent-Responsible for decomposing topics into multiple subtopics and generating overviews for each subtopic-"""--import json-from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.agents.research.data_structures import ToolTrace-from deeptutor.core.trace import build_trace_metadata, new_call_id-from deeptutor.tools.rag_tool import rag_search--from ..utils.json_utils import extract_json_from_text---class DecomposeAgent(BaseAgent):- """Topic decomposition Agent"""-- _MODE_TO_STYLE = {- "notes": "study_notes",- "report": "report",- "comparison": "comparison",- "learning_path": "learning_path",- }-- @staticmethod- def _build_trace_meta(mode: str) -> dict[str, Any]:- return build_trace_metadata(- call_id=new_call_id("research-decompose"),- phase="decomposing",- label="Decompose topic",- call_kind="llm_generation",- trace_role="plan",- trace_kind="llm_generation",- mode=mode,- )-- def __init__(- self,- config: dict[str, Any],- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- kb_name: str | None = None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="research",- agent_name="decompose_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- )- rag_cfg = config.get("rag", {}) or {}- self.kb_name = rag_cfg.get("kb_name") or kb_name or None-- researching_cfg = config.get("researching", {})- self.enable_rag = researching_cfg.get("enable_rag", True)- # Defensive: never attempt RAG without a real KB name. The- # capability/runtime config layer is responsible for stripping- # ``kb`` from sources when no KB is attached, but this guard keeps- # the agent safe even when called directly.- if not self.kb_name:- self.enable_rag = False-- self.conversation_history: list[dict[str, Any]] = config.get("conversation_history", [])-- self.citation_manager = None- intent_mode = str(config.get("intent", {}).get("mode", "") or "")- reporting_style = str(config.get("reporting", {}).get("style", "") or "")- self._research_style = reporting_style or self._MODE_TO_STYLE.get(intent_mode, "report")-- def set_citation_manager(self, citation_manager):- """Set citation manager"""- self.citation_manager = citation_manager-- def _format_conversation_context(self) -> str:- """Format conversation history into a context block for the LLM."""- if not self.conversation_history:- return ""- parts: list[str] = []- for msg in self.conversation_history:- role = msg.get("role", "user")- content = str(msg.get("content", "")).strip()- if not content:- continue- parts.append(f"[{role}]: {content}")- if not parts:- return ""- return (- "\n<conversation_history>\n"- "The following is the conversation history of this session. "- "If the user's current request references or modifies a previous outline, "- "use this history as context.\n\n" + "\n\n".join(parts) + "\n</conversation_history>\n"- )-- def _get_mode_contract(self, stage: str) -> str:- return (- self.get_prompt("mode_contracts", f"{self._research_style}_{stage}", "") or ""- ).strip()-- async def process(- self,- topic: str,- num_subtopics: int = 5,- mode: str = "manual",- attachments: list[Any] | None = None,- ) -> dict[str, Any]:- """- Decompose topic into subtopics and generate overview for each subtopic-- Args:- topic: Main topic- num_subtopics: Expected number of subtopics in manual mode, or maximum limit in auto mode- mode: Mode, "manual" (manually specify count) or "auto" (auto-generate)-- Returns:- Dictionary containing decomposition results- {- "main_topic": str,- "sub_topics": [- {- "title": str,- "overview": str- },- ...- ],- "total_subtopics": int,- "mode": str- }- """- print(f"\n{'=' * 70}")- print("🔀 DecomposeAgent - Topic Decomposition")- print(f"{'=' * 70}")- print(f"Main Topic: {topic}")- print(f"Mode: {mode}")- print(f"RAG Enabled: {self.enable_rag}")- if mode == "auto":- print(f"Max Subtopic Limit: {num_subtopics}\n")- else:- print(f"Expected Subtopic Count: {num_subtopics}\n")-- # If RAG is disabled, use direct LLM generation without RAG context- if not self.enable_rag:- print("⚠️ RAG is disabled, generating subtopics directly from LLM...")- return await self._process_without_rag(topic, num_subtopics, mode, attachments)-- print("\n🔍 Step 1: Executing RAG retrieval to get background knowledge...")- rag_context, source_query = await self._retrieve_background_knowledge(topic)-- print("\n🎯 Step 2: Generating subtopics...")- if mode == "auto":- sub_topics = await self._generate_sub_topics_auto(- topic=topic,- rag_context=rag_context,- max_subtopics=num_subtopics,- attachments=attachments,- )- else:- sub_topics = await self._generate_sub_topics(- topic=topic,- rag_context=rag_context,- num_subtopics=num_subtopics,- attachments=attachments,- )-- print(f"✓ Generated {len(sub_topics)} subtopics")-- return {- "main_topic": topic,- "sub_queries": [source_query] if source_query else [],- "rag_context": rag_context,- "sub_topics": sub_topics,- "total_subtopics": len(sub_topics),- "mode": mode,- "rag_context_summary": "RAG background based on topic",- }-- async def _retrieve_background_knowledge(self, topic: str) -> tuple[str, str]:- """Retrieve one background context for lightweight decomposition."""- source_query = (topic or "").strip()- if not source_query:- return "", ""- if not self.kb_name:- print(" ⚠️ No knowledge base configured; skipping RAG retrieval.")- return "", source_query-- try:- result = await rag_search(query=source_query, kb_name=self.kb_name)- rag_context = result.get("answer", "")- print(f" ✓ Retrieved background knowledge ({len(rag_context)} characters)")-- if self.citation_manager:- citation_id = self.citation_manager.get_next_citation_id(stage="planning")- tool_type = "rag"-- import time-- tool_id = f"plan_tool_{int(time.time() * 1000)}"- raw_answer_json = json.dumps(result, ensure_ascii=False)- trace = ToolTrace(- tool_id=tool_id,- citation_id=citation_id,- tool_type=tool_type,- query=source_query,- raw_answer=raw_answer_json,- summary=rag_context[:500] if rag_context else "",- )- self.citation_manager.add_citation(- citation_id=citation_id,- tool_type=tool_type,- tool_trace=trace,- raw_answer=raw_answer_json,- )-- return rag_context, source_query- except Exception as e:- print(f" ✗ RAG retrieval failed: {e!s}")- return "", source_query-- async def _process_without_rag(- self,- topic: str,- num_subtopics: int,- mode: str = "manual",- attachments: list[Any] | None = None,- ) -> dict[str, Any]:- """- Process without RAG: directly generate subtopics from LLM based on topic.- Used when RAG is disabled by user.-- Args:- topic: Main topic- num_subtopics: Number of subtopics to generate (exact for manual, max for auto)- mode: "manual" or "auto"-- Returns:- Dictionary containing decomposition results- """- print("\n🎯 Generating subtopics directly (no RAG)...")-- system_prompt = self.get_prompt(- "system",- "role",- "You are a research planning expert. Your task is to decompose complex topics into clear subtopics.",- )- system_prompt += self._format_conversation_context()-- user_prompt_template = self.get_prompt("process", "decompose_without_rag")- if not user_prompt_template:- raise ValueError(- "DecomposeAgent missing decompose_without_rag prompt, please configure process.decompose_without_rag in prompts/{lang}/decompose_agent.yaml"- )-- # Build requirement based on mode- if mode == "auto":- decompose_requirement = f"""-Quantity Requirements:-Generate between 3 and {num_subtopics} subtopics based on the complexity of the topic.-- For simple topics, generate fewer subtopics (3-4)-- For complex topics, generate more subtopics (up to {num_subtopics})-- Prioritize the most important and distinctive aspects of the topic-"""- else:- decompose_requirement = f"""-Quantity Requirements:-Generate exactly {num_subtopics} subtopics. Please ensure exactly {num_subtopics} subtopics are generated, no more, no less.-"""-- user_prompt = user_prompt_template.format(- topic=topic,- decompose_requirement=decompose_requirement,- mode_instruction=self._get_mode_contract("decompose"),- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="decompose_no_rag",- attachments=attachments,- trace_meta=self._build_trace_meta(mode),- ):- _chunks.append(_c)- response = "".join(_chunks)-- # Parse JSON output- from ..utils.json_utils import ensure_json_dict, ensure_keys-- data = extract_json_from_text(response)- try:- obj = ensure_json_dict(data)- ensure_keys(obj, ["sub_topics"])- subs = obj.get("sub_topics", [])- if not isinstance(subs, list):- raise ValueError("sub_topics must be an array")- # Clean and limit subtopics- cleaned = []- for it in subs[:num_subtopics]:- if isinstance(it, dict):- cleaned.append(- {"title": it.get("title", ""), "overview": it.get("overview", "")}- )- sub_topics = cleaned- except Exception:- sub_topics = []-- print(f"✓ Generated {len(sub_topics)} subtopics (without RAG)")-- return {- "main_topic": topic,- "sub_queries": [], # No sub-queries when RAG is disabled- "rag_context": "", # No RAG context- "sub_topics": sub_topics,- "total_subtopics": len(sub_topics),- "mode": f"{mode}_no_rag",- "rag_context_summary": "RAG disabled - subtopics generated directly from LLM",- }-- async def _generate_sub_topics_auto(- self,- topic: str,- rag_context: str,- max_subtopics: int,- attachments: list[Any] | None = None,- ) -> list[dict[str, str]]:- """- Auto mode: Autonomously generate subtopics based on RAG background-- Args:- topic: Main topic- rag_context: RAG background knowledge- max_subtopics: Maximum subtopic count limit-- Returns:- Subtopics list- """- system_prompt = self.get_prompt("system", "role")- if not system_prompt:- raise ValueError(- "DecomposeAgent missing system prompt, please configure system.role in prompts/{lang}/decompose_agent.yaml"- )- system_prompt += self._format_conversation_context()-- user_prompt_template = self.get_prompt("process", "decompose")- if not user_prompt_template:- raise ValueError(- "DecomposeAgent missing decompose prompt, please configure process.decompose in prompts/{lang}/decompose_agent.yaml"- )-- # Auto mode: Dynamically generate subtopics not exceeding the limit- decompose_requirement = f"""-Quantity Requirements:-Dynamically generate no more than {max_subtopics} subtopics. Please carefully analyze the background knowledge, identify core content areas related to the topic, and independently generate subtopics around the topic-related book content.-- The number of subtopics should be reasonable, not exceeding {max_subtopics}-- Prioritize subtopics most relevant and important to the topic-- Ensure subtopics do not duplicate and cover different dimensions of the topic-"""-- user_prompt = user_prompt_template.format(- topic=topic,- rag_context=rag_context,- decompose_requirement=decompose_requirement,- mode_instruction=self._get_mode_contract("decompose"),- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="decompose",- attachments=attachments,- trace_meta=self._build_trace_meta("auto"),- ):- _chunks.append(_c)- response = "".join(_chunks)-- # Parse JSON output (strict validation)- from ..utils.json_utils import ensure_json_dict, ensure_keys-- data = extract_json_from_text(response)- try:- obj = ensure_json_dict(data)- ensure_keys(obj, ["sub_topics"])- subs = obj.get("sub_topics", [])- if not isinstance(subs, list):- raise ValueError("sub_topics must be an array")- # Limit count not exceeding max_subtopics- cleaned = []- for it in subs[:max_subtopics]:- if isinstance(it, dict):- cleaned.append(- {"title": it.get("title", ""), "overview": it.get("overview", "")}- )- return cleaned- except Exception:- # Fallback: return empty list- return []-- async def _generate_sub_topics(- self,- topic: str,- rag_context: str,- num_subtopics: int,- attachments: list[Any] | None = None,- ) -> list[dict[str, str]]:- """- Generate subtopics based on RAG background-- Args:- topic: Main topic- rag_context: RAG background knowledge- num_subtopics: Expected number of subtopics-- Returns:- Subtopics list- """- system_prompt = self.get_prompt("system", "role")- if not system_prompt:- raise ValueError(- "DecomposeAgent missing system prompt, please configure system.role in prompts/{lang}/decompose_agent.yaml"- )- system_prompt += self._format_conversation_context()-- user_prompt_template = self.get_prompt("process", "decompose")- if not user_prompt_template:- raise ValueError(- "DecomposeAgent missing decompose prompt, please configure process.decompose in prompts/{lang}/decompose_agent.yaml"- )-- # Manual mode: Explicitly generate specified number of subtopics- decompose_requirement = f"""-Quantity Requirements:-Explicitly generate {num_subtopics} subtopics. Please ensure exactly {num_subtopics} subtopics are generated, no more, no less.-"""-- user_prompt = user_prompt_template.format(- topic=topic,- rag_context=rag_context,- decompose_requirement=decompose_requirement,- mode_instruction=self._get_mode_contract("decompose"),- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="decompose",- attachments=attachments,- trace_meta=self._build_trace_meta("manual"),- ):- _chunks.append(_c)- response = "".join(_chunks)-- # Parse JSON output (strict validation)- from ..utils.json_utils import ensure_json_dict, ensure_keys-- data = extract_json_from_text(response)- try:- obj = ensure_json_dict(data)- ensure_keys(obj, ["sub_topics"])- subs = obj.get("sub_topics", [])- if not isinstance(subs, list):- raise ValueError("sub_topics must be an array")- # Only select required fields- cleaned = []- for it in subs[:num_subtopics]:- if isinstance(it, dict):- cleaned.append(- {"title": it.get("title", ""), "overview": it.get("overview", "")}- )- return cleaned- except Exception:- # Fallback: return empty list- return []---__all__ = ["DecomposeAgent"]diff --git a/deeptutor/agents/research/agents/manager_agent.py b/deeptutor/agents/research/agents/manager_agent.pydeleted file mode 100644index a546683c6..000000000--- a/deeptutor/agents/research/agents/manager_agent.py+++ /dev/null@@ -1,211 +0,0 @@-#!/usr/bin/env python-"""-ManagerAgent - Queue management Agent-Responsible for managing DynamicTopicQueue state and task distribution-"""--import asyncio-from typing import Any--from deeptutor.agents.research.data_structures import DynamicTopicQueue, TopicBlock---class ManagerAgent:- """Queue management Agent"""-- def __init__(- self,- config: dict[str, Any],- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- ):- self.queue: DynamicTopicQueue | None = None- self.primary_topic: str | None = None- self._lock = asyncio.Lock() # Lock for thread-safe operations in parallel mode-- def set_queue(self, queue: DynamicTopicQueue) -> None:- """Set queue to manage"""- self.queue = queue-- def set_primary_topic(self, topic: str | None) -> None:- """Update primary research topic for subsequent topic consistency judgment"""- self.primary_topic = (topic or "").strip() or None-- def get_next_task(self) -> TopicBlock | None:- """- Get next task to research-- Returns:- Next TopicBlock with PENDING status, returns None if none available- """- if not self.queue:- return None-- block = self.queue.get_pending_block()- if block:- # Mark as researching- self.queue.mark_researching(block.block_id)- print(f"\n📋 ManagerAgent: Assigned task {block.block_id}")- print(f" Topic: {block.sub_topic}")-- return block-- def complete_task(self, block_id: str) -> bool:- """- Mark task as completed-- Args:- block_id: Topic block ID-- Returns:- Whether successfully marked- """- if not self.queue:- return False-- success = self.queue.mark_completed(block_id)- if success:- print(f"✓ ManagerAgent: Task {block_id} completed")-- return success-- async def get_next_task_async(self) -> TopicBlock | None:- """- Thread-safe async version of get_next_task for parallel mode-- Returns:- Next TopicBlock with PENDING status, returns None if none available- """- async with self._lock:- return self.get_next_task()-- async def complete_task_async(self, block_id: str) -> bool:- """- Thread-safe async version of complete_task for parallel mode-- Args:- block_id: Topic block ID-- Returns:- Whether successfully marked- """- async with self._lock:- return self.complete_task(block_id)-- async def fail_task_async(self, block_id: str, reason: str = "") -> bool:- """- Thread-safe async version of fail_task for parallel mode-- Args:- block_id: Topic block ID- reason: Failure reason-- Returns:- Whether successfully marked- """- async with self._lock:- return self.fail_task(block_id, reason)-- async def add_new_topic_async(self, sub_topic: str, overview: str) -> TopicBlock:- """- Thread-safe async version of add_new_topic for parallel mode-- Args:- sub_topic: Sub-topic name- overview: Topic overview-- Returns:- Newly created TopicBlock- """- async with self._lock:- return self.add_new_topic(sub_topic, overview)-- def fail_task(self, block_id: str, reason: str = "") -> bool:- """- Mark task as failed-- Args:- block_id: Topic block ID- reason: Failure reason-- Returns:- Whether successfully marked- """- if not self.queue:- return False-- success = self.queue.mark_failed(block_id)- if success:- print(f"✗ ManagerAgent: Task {block_id} failed")- if reason:- print(f" Reason: {reason}")-- return success-- def add_new_topic(self, sub_topic: str, overview: str) -> TopicBlock:- """- Add new topic to queue-- Args:- sub_topic: Sub-topic name- overview: Topic overview-- Returns:- Newly created TopicBlock- """- if not self.queue:- raise RuntimeError("Queue not initialized")-- normalized = (sub_topic or "").strip()- if not normalized:- raise ValueError("New topic title cannot be empty")- if self.queue.has_topic(normalized):- print(f"⚠️ ManagerAgent: Topic《{normalized}》already exists, skipping addition")- return None-- block = self.queue.add_block(normalized, overview)- print(f"✓ ManagerAgent: Added new topic {block.block_id}")- print(f" Topic: {sub_topic}")-- return block-- def is_research_complete(self) -> bool:- """- Check if research is complete (all tasks are completed)-- Returns:- Whether all tasks are completed- """- if not self.queue:- return False-- return self.queue.is_all_completed()-- def get_queue_status(self) -> dict[str, Any]:- """- Get queue status-- Returns:- Queue statistics- """- if not self.queue:- return {}-- stats = self.queue.get_statistics()- print("\n📊 Queue Status:")- print(f" Total Topics: {stats['total_blocks']}")- print(f" Pending: {stats['pending']}")- print(f" Researching: {stats['researching']}")- print(f" Completed: {stats['completed']}")- print(f" Failed: {stats['failed']}")- print(f" Total Tool Calls: {stats['total_tool_calls']}")-- return stats-- async def process(self, *args, **kwargs) -> Any:- """Main processing logic of Manager Agent"""- # Manager Agent is mainly called through other methods, no independent process method needed---__all__ = ["ManagerAgent"]diff --git a/deeptutor/agents/research/agents/note_agent.py b/deeptutor/agents/research/agents/note_agent.pydeleted file mode 100644index 5c5c0aeb2..000000000--- a/deeptutor/agents/research/agents/note_agent.py+++ /dev/null@@ -1,319 +0,0 @@-#!/usr/bin/env python-"""-NoteAgent - Recording Agent-Responsible for information compression and summary generation, converting raw data returned by tools into usable knowledge summaries-"""--from string import Template-from typing import Any, Optional--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.agents.research.data_structures import ToolTrace-from deeptutor.core.trace import build_trace_metadata, new_call_id-from deeptutor.utils.json_parser import parse_json_response--from ..utils.json_utils import extract_json_from_text---class NoteAgent(BaseAgent):- """Recording Agent"""-- _MODE_TO_STYLE = {- "notes": "study_notes",- "report": "report",- "comparison": "comparison",- "learning_path": "learning_path",- }-- @staticmethod- def _build_trace_meta(tool_type: str, query: str) -> dict[str, Any]:- return build_trace_metadata(- call_id=new_call_id("research-note"),- phase="researching",- label="Summarize evidence",- call_kind="llm_observation",- trace_role="observe",- trace_kind="llm_generation",- tool_name=tool_type,- query=query,- )-- def __init__(- self,- config: dict[str, Any],- api_key: Optional[str] = None,- base_url: Optional[str] = None,- api_version: Optional[str] = None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="research",- agent_name="note_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- )- researching_cfg = config.get("researching", {})- self.summary_mode = researching_cfg.get("note_agent_mode", "auto")- intent_mode = str(config.get("intent", {}).get("mode", "") or "")- reporting_style = str(config.get("reporting", {}).get("style", "") or "")- self._research_style = reporting_style or self._MODE_TO_STYLE.get(intent_mode, "report")-- async def process(- self,- tool_type: str,- query: str,- raw_answer: str,- citation_id: str,- topic: str = "",- context: str = "",- ) -> ToolTrace:- """- Process raw data returned by tool, generate summary and create ToolTrace-- Args:- tool_type: Tool type- query: Query statement- raw_answer: Raw answer returned by tool- citation_id: Citation ID (REQUIRED, must be obtained from CitationManager)- topic: Topic (for context)- context: Additional context-- Returns:- ToolTrace object-- Note:- citation_id must be obtained from CitationManager before calling this method.- Use CitationManager.get_next_citation_id() or its async variant.- """- print(f"\n{'=' * 70}")- print("📝 NoteAgent - Information Recording and Summary")- print(f"{'=' * 70}")- print(f"Tool: {tool_type}")- print(f"Query: {query}")- print(f"Citation ID: {citation_id}")- print(f"Raw Answer Length: {len(raw_answer)} characters\n")-- summary = ""- use_rule = self.summary_mode in ("rule", "auto")- use_llm_fallback = self.summary_mode in ("llm", "auto")-- if use_rule:- summary = self._extract_summary_by_rule(tool_type=tool_type, raw_answer=raw_answer)-- if (not summary or len(summary) < 50) and use_llm_fallback:- summary = await self._generate_summary(- tool_type=tool_type,- query=query,- raw_answer=raw_answer,- topic=topic,- context=context,- )- elif not summary:- summary = raw_answer[:1000]-- print(f"✓ Summary generation completed ({len(summary)} characters)")-- # Create ToolTrace with the provided citation ID- tool_id = self._generate_tool_id()- trace = ToolTrace(- tool_id=tool_id,- citation_id=citation_id,- tool_type=tool_type,- query=query,- raw_answer=raw_answer,- summary=summary,- )-- return trace-- @staticmethod- def _convert_to_template_format(template_str: str) -> str:- """- Convert {var} style placeholders to $var style for string.Template.- This avoids conflicts with LaTeX braces like {\rho}.- """- import re-- # Only convert simple {var_name} patterns, not nested or complex ones- return re.sub(r"\{(\w+)\}", r"$\1", template_str)-- @staticmethod- def _truncate_text(text: str, limit: int = 800) -> str:- """Keep summaries compact for iterative accumulation."""- text = (text or "").strip()- if len(text) <= limit:- return text- return text[: limit - 3].rstrip() + "..."-- def _get_mode_contract(self, stage: str) -> str:- return (- self.get_prompt("mode_contracts", f"{self._research_style}_{stage}", "") or ""- ).strip()-- def _get_mode_instruction_text(self, stage: str) -> str:- instruction = self._get_mode_contract(stage)- if not instruction:- return ""- return f"Mode-specific note focus:\n{instruction}\n"-- def _extract_summary_by_rule(self, tool_type: str, raw_answer: str) -> str:- """Extract a concise summary from structured tool output without LLM."""- data = parse_json_response(raw_answer, fallback=None)- if data is None:- return ""- # Some tools (notably ``paper_search``) return a JSON list at the top- # level rather than an object. Wrap it in a sensible envelope so the- # downstream ``data.get(...)`` calls don't blow up with an- # ``AttributeError: 'list' object has no attribute 'get'``.- if isinstance(data, list):- data = {"results": data, "papers": data, "search_results": data}- if not isinstance(data, dict):- # Truly unparseable shape (number, string, etc.) — just truncate- # the raw answer and bail.- return self._truncate_text(raw_answer)-- tool_type = (tool_type or "").lower()-- if tool_type in {"rag_hybrid", "rag_naive", "rag"}: # aliases kept for backward compat- answer = data.get("answer") or data.get("content") or ""- return self._truncate_text(answer)-- if tool_type == "web_search":- answer = data.get("answer") or ""- snippets: list[str] = []- for item in (data.get("search_results") or data.get("results") or [])[:3]:- if not isinstance(item, dict):- continue- title = (item.get("title") or "").strip()- snippet = (item.get("snippet") or item.get("content") or "").strip()- piece = " - ".join(part for part in [title, snippet] if part)- if piece:- snippets.append(piece)- combined = "\n".join(part for part in [answer.strip(), *snippets] if part)- return self._truncate_text(combined)-- if tool_type == "paper_search":- papers = data.get("papers") or []- formatted: list[str] = []- for paper in papers[:3]:- if not isinstance(paper, dict):- continue- title = (paper.get("title") or "").strip()- authors = paper.get("authors") or []- if isinstance(authors, list):- authors_text = ", ".join(authors[:3])- else:- authors_text = str(authors)- year = paper.get("year")- abstract = (paper.get("abstract") or "").strip()- parts = [title]- if authors_text:- parts.append(authors_text)- if year:- parts.append(str(year))- header = " | ".join(part for part in parts if part)- body = "\n".join(part for part in [header, abstract] if part)- if body:- formatted.append(body)- return self._truncate_text("\n\n".join(formatted))-- if tool_type in {"run_code", "code_execution", "code_execute"}:- stdout = (data.get("stdout") or "").strip()- stderr = (data.get("stderr") or "").strip()- artifacts = data.get("artifacts") or []- parts = []- if stdout:- parts.append(f"stdout:\n{stdout}")- if stderr:- parts.append(f"stderr:\n{stderr}")- if artifacts:- parts.append(f"artifacts: {', '.join(str(item) for item in artifacts)}")- return self._truncate_text("\n\n".join(parts))-- if isinstance(data, dict):- for key in ("answer", "content", "summary", "message"):- value = data.get(key)- if isinstance(value, str) and value.strip():- return self._truncate_text(value)-- return ""-- async def _generate_summary(- self, tool_type: str, query: str, raw_answer: str, topic: str = "", context: str = ""- ) -> str:- """- Generate summary-- Args:- tool_type: Tool type- query: Query statement- raw_answer: Raw answer- topic: Topic- context: Additional context-- Returns:- Generated summary- """- system_prompt = self.get_prompt("system", "role")- if not system_prompt:- raise ValueError(- "NoteAgent missing system prompt, please configure system.role in prompts/{lang}/note_agent.yaml"- )-- user_prompt_template = self.get_prompt("process", "generate_summary")- if not user_prompt_template:- raise ValueError(- "NoteAgent missing generate_summary prompt, please configure process.generate_summary in prompts/{lang}/note_agent.yaml"- )-- # Use string.Template to avoid conflicts with LaTeX braces like {\rho}- # Convert {var} to $var format, then use safe_substitute- template_str = self._convert_to_template_format(user_prompt_template)- template = Template(template_str)- user_prompt = template.safe_substitute(- tool_type=tool_type,- query=query,- raw_answer=raw_answer,- topic=topic,- context=context,- mode_instruction=self._get_mode_instruction_text("note"),- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="generate_summary",- trace_meta=self._build_trace_meta(tool_type, query),- ):- _chunks.append(_c)- response = "".join(_chunks)-- # Parse JSON output (strict validation)- from ..utils.json_utils import ensure_json_dict, ensure_keys-- data = extract_json_from_text(response)- try:- obj = ensure_json_dict(data)- ensure_keys(obj, ["summary"])- summary = obj.get("summary", "")- # Ensure summary is string type- if not isinstance(summary, str):- summary = str(summary) if summary else ""- return summary- except Exception:- # Fallback: directly use text prefix- return (response or "")[:1000]-- def _generate_tool_id(self) -> str:- """Generate tool ID"""- import time-- timestamp = int(time.time() * 1000)- return f"tool_{timestamp}"---__all__ = ["NoteAgent"]diff --git a/deeptutor/agents/research/agents/rephrase_agent.py b/deeptutor/agents/research/agents/rephrase_agent.pydeleted file mode 100644index e90814701..000000000--- a/deeptutor/agents/research/agents/rephrase_agent.py+++ /dev/null@@ -1,221 +0,0 @@-#!/usr/bin/env python-"""-RephraseAgent - Topic rephrasing Agent-Responsible for rephrasing and optimizing user input-"""--from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.core.trace import build_trace_metadata, new_call_id--from ..utils.json_utils import extract_json_from_text---class RephraseAgent(BaseAgent):- """Topic rephrasing Agent"""-- _MODE_TO_STYLE = {- "notes": "study_notes",- "report": "report",- "comparison": "comparison",- "learning_path": "learning_path",- }-- @staticmethod- def _build_trace_meta(iteration: int) -> dict[str, Any]:- return build_trace_metadata(- call_id=new_call_id("research-rephrase"),- phase="rephrasing",- label="Rephrase topic",- call_kind="llm_generation",- trace_role="thought",- trace_kind="llm_generation",- iteration=iteration,- )-- def __init__(- self,- config: dict[str, Any],- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="research",- agent_name="rephrase_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- )- self.conversation_history: list[dict[str, Any]] = []- self.session_history: list[dict[str, Any]] = config.get("conversation_history", [])- intent_mode = str(config.get("intent", {}).get("mode", "") or "")- reporting_style = str(config.get("reporting", {}).get("style", "") or "")- self._research_style = reporting_style or self._MODE_TO_STYLE.get(intent_mode, "report")-- def reset_history(self):- """Reset conversation history for a new research session"""- self.conversation_history = []-- def _get_mode_contract(self, stage: str) -> str:- return (- self.get_prompt("mode_contracts", f"{self._research_style}_{stage}", "") or ""- ).strip()-- def _format_conversation_history(self) -> str:- """Format conversation history for prompt"""- if not self.conversation_history:- return ""-- history_parts = []- for entry in self.conversation_history:- role = entry.get("role", "unknown")- iteration = entry.get("iteration", 0)- content = entry.get("content", "")-- if role == "user":- if iteration == 0:- history_parts.append(f"[User - Initial Input]\n{content}")- else:- history_parts.append(f"[User - Feedback (Round {iteration})]\n{content}")- elif role == "assistant":- topic = content.get("topic", "") if isinstance(content, dict) else str(content)- history_parts.append(f"[Assistant - Rephrased Topic (Round {iteration})]\n{topic}")-- return "\n\n".join(history_parts)-- async def process(- self,- user_input: str,- iteration: int = 0,- previous_result: dict[str, Any] = None,- attachments: list[Any] | None = None,- ) -> dict[str, Any]:- """- Rephrase and optimize user input using the accumulated planning context.-- Args:- user_input: Research topic or the latest rephrased topic- iteration: Iteration count (for tracking rephrasing rounds)- previous_result: Previous rephrasing result- attachments: Optional chat attachments for multimodal topic analysis-- Returns:- Dictionary containing rephrasing results- {- "topic": str, # Optimized research topic (a clear, explicit statement)- "iteration": int, # Iteration count- }- """- print(f"\n{'=' * 70}")- print(f"🔄 RephraseAgent - Topic Rephrasing (Iteration {iteration})")- print(f"{'=' * 70}")-- # Reset history for new session (iteration 0)- if iteration == 0:- self.reset_history()- print(f"Original Input: {user_input}\n")- else:- print(f"User Feedback: {user_input}\n")- print(f"Conversation History: {len(self.conversation_history)} entries\n")-- # Add current user input to history- self.conversation_history.append(- {- "role": "user",- "content": user_input,- "iteration": iteration,- }- )-- system_prompt = self.get_prompt("system", "role")- if not system_prompt:- raise ValueError(- "RephraseAgent missing system prompt, please configure system.role in prompts/{lang}/rephrase_agent.yaml"- )- if self.session_history:- ctx_parts = []- for msg in self.session_history:- role = msg.get("role", "user")- content = str(msg.get("content", "")).strip()- if content:- ctx_parts.append(f"[{role}]: {content}")- if ctx_parts:- system_prompt += (- "\n\n<session_history>\n"- "The following is the earlier conversation in this session. "- "Use it to understand what the user previously discussed or planned.\n\n"- + "\n\n".join(ctx_parts)- + "\n</session_history>"- )-- # Get user prompt template- user_prompt_template = self.get_prompt("process", "rephrase")- if not user_prompt_template:- raise ValueError(- "RephraseAgent missing rephrase prompt, please configure process.rephrase in prompts/{lang}/rephrase_agent.yaml"- )-- # Format conversation history for prompt- history_text = self._format_conversation_history()-- # Format user prompt with full history- user_prompt = user_prompt_template.format(- user_input=user_input,- iteration=iteration,- conversation_history=history_text,- previous_result=history_text,- mode_instruction=self._get_mode_contract("rephrase"),- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="rephrase",- attachments=attachments,- trace_meta=self._build_trace_meta(iteration),- ):- _chunks.append(_c)- response = "".join(_chunks)-- # Parse JSON output- data = extract_json_from_text(response)- from ..utils.json_utils import ensure_json_dict, ensure_keys-- try:- result = ensure_json_dict(data)- ensure_keys(result, ["topic"])- except Exception:- # Fallback: use user input or last assistant topic- fallback_topic = user_input- for entry in reversed(self.conversation_history):- if entry.get("role") == "assistant":- content = entry.get("content", {})- if isinstance(content, dict) and content.get("topic"):- fallback_topic = content["topic"]- break- result = {"topic": fallback_topic}-- result["iteration"] = iteration-- # Add assistant response to history- self.conversation_history.append(- {- "role": "assistant",- "content": result,- "iteration": iteration,- }- )-- print("\n✓ Rephrasing Completed:")- print(f" Optimized Research Topic: {result.get('topic', '')}")-- return result---__all__ = ["RephraseAgent"]diff --git a/deeptutor/agents/research/agents/reporting_agent.py b/deeptutor/agents/research/agents/reporting_agent.pydeleted file mode 100644index 1dcb47b18..000000000--- a/deeptutor/agents/research/agents/reporting_agent.py+++ /dev/null@@ -1,1661 +0,0 @@-#!/usr/bin/env python-"""-ReportingAgent - Report generation Agent (DR-in-KG 2.0)-- Deduplication and cleaning-- Generate linear outline (introduction → sections → conclusion)-- Write final report (prefer LLM JSON return markdown, fallback to local assembly on failure)-- Inline citations and References anchors (based on citation_id)-"""--from __future__ import annotations--from collections.abc import Callable-import re-from string import Template-from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.agents.research.data_structures import DynamicTopicQueue, TopicBlock-from deeptutor.core.trace import build_trace_metadata, new_call_id--from ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_text---class ReportingAgent(BaseAgent):- """Report generation Agent"""-- @staticmethod- def _build_trace_meta(label: str, trace_kind: str = "llm_generation") -> dict[str, Any]:- return build_trace_metadata(- call_id=new_call_id("research-report"),- phase="reporting",- label=label,- call_kind=trace_kind,- trace_role="response",- trace_kind=trace_kind,- )-- @staticmethod- def _escape_braces(text: str) -> str:- """- Escape curly braces in text to prevent str.format() from interpreting them.- This is needed because JSON data may contain LaTeX formulas with braces like {L}, {x}.-- Args:- text: Input text that may contain curly braces-- Returns:- Text with braces escaped ({{ and }})- """- return text.replace("{", "{{").replace("}", "}}")-- @staticmethod- def _convert_to_template_format(template_str: str) -> str:- """- Convert {var} style placeholders to $var style for string.Template.- This avoids conflicts with LaTeX braces like {\rho}, {L}.- """- return re.sub(r"\{(\w+)\}", r"$\1", template_str)-- def _safe_format(self, template_str: str, **kwargs) -> str:- """- Safe string formatting using string.Template to avoid LaTeX brace conflicts.- Converts {var} to $var format, then uses safe_substitute.- """- converted = self._convert_to_template_format(template_str)- return Template(converted).safe_substitute(**kwargs)-- def __init__(- self,- config: dict[str, Any],- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="research",- agent_name="reporting_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- )- self.reporting_config = config.get("reporting", {})- self.citation_manager = None # Will be set during process-- # Citation configuration: read from config, default off- self.enable_citation_list = self.reporting_config.get("enable_citation_list", False)- self.enable_inline_citations = self.reporting_config.get("enable_inline_citations", False)- self.deduplicate_enabled = self.reporting_config.get("deduplicate_enabled", False)- self.single_pass_threshold = int(- self.reporting_config.get("report_single_pass_threshold", 0)- )- self.report_style = str(self.reporting_config.get("style", "report") or "report")-- def set_citation_manager(self, citation_manager):- """Set citation manager"""- self.citation_manager = citation_manager-- @staticmethod- def _append_contract(prompt: str, heading: str, contract: str) -> str:- contract = str(contract or "").strip()- if not contract:- return prompt- return f"{prompt}\n\n{heading}:\n{contract}\n"-- def _get_mode_contract(self, stage: str) -> str:- return (self.get_prompt("mode_contracts", f"{self.report_style}_{stage}", "") or "").strip()-- def _get_mode_process_prompt(self, base_key: str, default: str = "") -> str:- """Select mode-specific process template, falling back to the generic one.-- Tries ``process.{base_key}_{report_style}`` first (e.g.- ``generate_outline_study_notes``). If the YAML has no such key the- generic ``process.{base_key}`` is returned instead.- """- if self.report_style and self.report_style != "report":- mode_key = f"{base_key}_{self.report_style}"- mode_prompt = self.get_prompt("process", mode_key, "")- if mode_prompt:- return mode_prompt- return self.get_prompt("process", base_key, default)-- async def process(- self,- queue: DynamicTopicQueue,- topic: str,- progress_callback: Callable[[dict[str, Any]], None] | None = None,- ) -> dict[str, Any]:- """- Generate final report- Returns:- {- "report": str,- "word_count": int,- "sections": int,- "citations": int- }- """- print(f"\n{'=' * 70}")- print("📄 ReportingAgent - Report Generation")- print(f"{'=' * 70}")- print(f"Topic: {topic}")- print(f"Topic Blocks: {len(queue.blocks)}\n")-- # Store progress_callback for use in _write_report- self._progress_callback = progress_callback-- self._notify_progress(- progress_callback, "reporting_started", topic=topic, total_blocks=len(queue.blocks)- )-- candidate_blocks = queue.get_all_completed_blocks() or queue.blocks-- # 1) Optional deduplication- print("🔄 Step 1: Preparing topic blocks...")- if self.deduplicate_enabled:- cleaned_blocks = await self._deduplicate_blocks(candidate_blocks)- else:- cleaned_blocks = candidate_blocks- print(f"✓ Preparation completed: {len(cleaned_blocks)} topic blocks")- self._notify_progress(- progress_callback, "deduplicate_completed", kept_blocks=len(cleaned_blocks)- )-- # 2) Outline- print("\n📋 Step 2: Generating outline...")- outline = await self._generate_outline(topic, cleaned_blocks)- print("✓ Outline generation completed")- self._notify_progress(- progress_callback, "outline_completed", sections=len(outline.get("sections", []))- )-- # Save outline for later use- self._current_outline = outline-- # 3) Writing- print("\n✍️ Step 3: Writing report...")- report_markdown = await self._write_report(topic, cleaned_blocks, outline)- print("✓ Report writing completed")- self._notify_progress(progress_callback, "writing_completed")-- word_count = len(report_markdown)- sections = len(cleaned_blocks)- citations = sum(len(b.tool_traces) for b in cleaned_blocks)-- print("\n📊 Report Statistics:")- print(f" Word Count: {word_count}")- print(f" Sections: {sections}")- print(f" Citations: {citations}")- self._notify_progress(- progress_callback,- "reporting_completed",- word_count=word_count,- sections=sections,- citations=citations,- )-- result = {- "report": report_markdown,- "word_count": word_count,- "sections": sections,- "citations": citations,- }-- # If outline has been generated, add it to result- if hasattr(self, "_current_outline"):- result["outline"] = self._current_outline- delattr(self, "_current_outline")-- return result-- async def _deduplicate_blocks(self, blocks: list[TopicBlock]) -> list[TopicBlock]:- if len(blocks) <= 1:- return blocks- system_prompt = self.get_prompt("system", "role")- if not system_prompt:- raise ValueError(- "ReportingAgent missing system prompt, please configure system.role in prompts/{lang}/reporting_agent.yaml"- )- user_prompt = self.get_prompt("process", "deduplicate")- if not user_prompt:- raise ValueError(- "ReportingAgent missing deduplicate prompt, please configure process.deduplicate in prompts/{lang}/reporting_agent.yaml"- )- topics_text = "\n".join(- [f"{i + 1}. {b.sub_topic}: {b.overview[:200]}" for i, b in enumerate(blocks)]- )- filled = self._safe_format(user_prompt, topics=topics_text, total_topics=len(blocks))- _chunks: list[str] = []- async for _c in self.stream_llm(- filled,- system_prompt,- stage="deduplicate",- trace_meta=self._build_trace_meta("Deduplicate topics"),- ):- _chunks.append(_c)- resp = "".join(_chunks)- data = extract_json_from_text(resp)- try:- obj = ensure_json_dict(data)- ensure_keys(obj, ["keep_indices"])- keep_indices = obj.get("keep_indices", [])- return [blocks[i] for i in keep_indices if isinstance(i, int) and i < len(blocks)]- except Exception:- return blocks-- async def _generate_outline(self, topic: str, blocks: list[TopicBlock]) -> dict[str, Any]:- """Generate report outline based on complete subtopic, overview and all tool_trace summaries-- Supports three-level heading system:- - Level 1 (#): Report main title- - Level 2 (##): Main sections (Introduction, Core Sections, Conclusion)- - Level 3 (###): Subsections within each section- """- system_prompt = self.get_prompt("system", "role")- if not system_prompt:- raise ValueError(- "ReportingAgent missing system prompt, please configure system.role in prompts/{lang}/reporting_agent.yaml"- )- user_prompt = self._get_mode_process_prompt("generate_outline")- if not user_prompt:- raise ValueError(- "ReportingAgent missing generate_outline prompt, please configure process.generate_outline in prompts/{lang}/reporting_agent.yaml"- )-- # Build complete topic information, including subtopic, overview and all tool_trace summaries- topics_data = []- for i, block in enumerate(blocks, 1):- topic_info = {- "index": i,- "block_id": block.block_id,- "sub_topic": block.sub_topic,- "overview": block.overview,- "tool_summaries": (- [trace.summary for trace in block.tool_traces] if block.tool_traces else []- ),- }- topics_data.append(topic_info)-- import json as _json-- topics_json = _json.dumps(topics_data, ensure_ascii=False, indent=2)- # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}- filled = self._safe_format(- user_prompt, topic=topic, topics_json=topics_json, total_topics=len(blocks)- )- filled = self._append_contract(- filled,- "Mode-specific outline contract",- self._get_mode_contract("outline"),- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- filled,- system_prompt,- stage="generate_outline",- trace_meta=self._build_trace_meta("Generate outline"),- ):- _chunks.append(_c)- resp = "".join(_chunks)- data = extract_json_from_text(resp)- try:- obj = ensure_json_dict(data)- ensure_keys(obj, ["title", "introduction", "sections", "conclusion"])- # Ensure title uses markdown format (# prefix)- if not obj.get("title", "").startswith("#"):- obj["title"] = f"# {obj.get('title', topic)}"- # Ensure introduction and conclusion use markdown format (## prefix)- if obj.get("introduction") and not obj["introduction"].startswith("##"):- obj["introduction"] = f"## {obj['introduction']}"- if obj.get("conclusion") and not obj["conclusion"].startswith("##"):- obj["conclusion"] = f"## {obj['conclusion']}"-- # Process sections to ensure proper formatting- for section in obj.get("sections", []):- # Ensure section title has ## prefix- if section.get("title") and not section["title"].startswith("##"):- section["title"] = f"## {section['title']}"- # Process subsections if present- for subsection in section.get("subsections", []):- if subsection.get("title") and not subsection["title"].startswith("###"):- subsection["title"] = f"### {subsection['title']}"-- return obj- except Exception:- # Fallback to default outline with subsections- return self._create_default_outline(topic, blocks)-- def _create_default_outline(self, topic: str, blocks: list[TopicBlock]) -> dict[str, Any]:- """Create a default outline with three-level heading structure"""- intro_title = "## Introduction"- intro_instruction = (- "Present the research background, motivation, objectives, and report structure"- )- conclusion_title = "## Conclusion and Future Directions"- conclusion_instruction = (- "Summarize core findings, research contributions, limitations, and future directions"- )-- if self.report_style == "study_notes":- intro_title = "## Study Overview"- intro_instruction = (- "Orient the learner, define the scope, and state the main learning goals"- )- conclusion_title = "## Key Takeaways"- conclusion_instruction = (- "Summarize the most important concepts, mechanisms, and memory anchors"- )- elif self.report_style == "comparison":- intro_title = "## Comparison Setup"- intro_instruction = "Define the comparison target, criteria, and evaluation lens"- conclusion_title = "## Recommendation by Scenario"- conclusion_instruction = (- "Summarize the trade-offs and recommend which option fits which scenario"- )- elif self.report_style == "learning_path":- intro_title = "## Learning Goal and Scope"- intro_instruction = (- "Clarify the learner profile, expected progression, and prerequisite assumptions"- )- conclusion_title = "## Milestones and Next Steps"- conclusion_instruction = (- "Summarize stage milestones, practice checkpoints, and how to keep progressing"- )-- sections = []- for i, b in enumerate(blocks, 1):- section_instruction = f"Provide detailed introduction to {b.sub_topic}, including core concepts, key mechanisms, and practical applications"- section_title = f"## {i}. {b.sub_topic}"- subsections = [- {- "title": f"### {i}.1 Core Concepts and Definitions",- "instruction": f"Explain the fundamental concepts and definitions related to {b.sub_topic}",- },- {- "title": f"### {i}.2 Key Mechanisms and Principles",- "instruction": f"Analyze the underlying mechanisms and theoretical principles of {b.sub_topic}",- },- ]- if self.report_style == "study_notes":- section_title = f"## Note {i}. {b.sub_topic}"- section_instruction = f"Write compact study notes for {b.sub_topic}, focusing on definitions, mechanisms, examples, and takeaways"- subsections = [- {- "title": f"### {i}.1 What It Means",- "instruction": f"State the definition, intuition, and key idea of {b.sub_topic}",- },- {- "title": f"### {i}.2 Why It Matters",- "instruction": f"Explain the mechanism, a quick example, and the main takeaway for {b.sub_topic}",- },- {- "title": f"### {i}.3 Common Pitfalls",- "instruction": f"List typical misunderstandings or mistakes related to {b.sub_topic}",- },- ]- elif self.report_style == "comparison":- section_title = f"## Dimension {i}. {b.sub_topic}"- section_instruction = f"Compare {b.sub_topic} across key dimensions, trade-offs, strengths, weaknesses, and best-fit scenarios"- subsections = [- {- "title": f"### {i}.1 Side-by-Side Contrast",- "instruction": f"Compare the relevant options under the dimension of {b.sub_topic}",- },- {- "title": f"### {i}.2 Trade-offs",- "instruction": f"Explain strengths, weaknesses, and trade-offs under {b.sub_topic}",- },- {- "title": f"### {i}.3 Best-Fit Scenarios",- "instruction": f"Recommend which option fits which scenario for the dimension {b.sub_topic}",- },- ]- elif self.report_style == "learning_path":- section_title = f"## Stage {i}. {b.sub_topic}"- section_instruction = f"Explain how {b.sub_topic} fits into a learning roadmap, including prerequisites, what to practice, and what comes next"- subsections = [- {- "title": f"### {i}.1 Learn First",- "instruction": f"Explain the prerequisite ideas and what the learner should understand before tackling {b.sub_topic}",- },- {- "title": f"### {i}.2 Practice Plan",- "instruction": f"Describe how to practice {b.sub_topic}, including exercise focus and progression",- },- {- "title": f"### {i}.3 Checkpoint",- "instruction": f"Define what counts as finishing this stage and what should come next after {b.sub_topic}",- },- ]- section = {- "title": section_title,- "instruction": section_instruction,- "block_id": b.block_id,- "subsections": subsections,- }- sections.append(section)-- return {- "title": f"# {topic}",- "introduction": intro_title,- "introduction_instruction": intro_instruction,- "sections": sections,- "conclusion": conclusion_title,- "conclusion_instruction": conclusion_instruction,- }-- def _ser_block(self, b: TopicBlock) -> dict[str, Any]:- """Serialize TopicBlock to dictionary, including complete tool traces-- If self._citation_map is available (built by _build_citation_number_map),- each trace will include a ref_number field for inline citation use.- """- traces = []- for t in b.tool_traces:- cid = getattr(t, "citation_id", None) or f"CIT-{b.block_id.split('_')[-1]}-01"- trace_data = {- "citation_id": cid,- "tool_type": t.tool_type,- "query": t.query,- "raw_answer": t.raw_answer, # Include complete original response- "summary": t.summary,- }- # Add ref_number if citation map is available- if hasattr(self, "_citation_map") and self._citation_map:- ref_num = self._citation_map.get(cid, 0)- if ref_num > 0:- trace_data["ref_number"] = ref_num- traces.append(trace_data)- return {- "block_id": b.block_id,- "sub_topic": b.sub_topic,- "overview": b.overview,- "traces": traces,- }-- def _build_citation_table(self, block: TopicBlock) -> str:- """Build a clear citation reference table for LLM to understand the mapping-- This creates an easy-to-read table showing:- - Reference number to use in text (use [N] format)- - Tool type- - Query summary (truncated)-- Args:- block: TopicBlock containing tool traces-- Returns:- Formatted citation table string- """- if not block.tool_traces:- return " (No citations available for this section)"-- lines = []- for trace in block.tool_traces:- cid = getattr(trace, "citation_id", None)- if not cid:- continue-- ref_num = self._citation_map.get(cid, 0) if hasattr(self, "_citation_map") else 0- if ref_num <= 0:- continue-- # Truncate query for readability- query_preview = trace.query[:60] + "..." if len(trace.query) > 60 else trace.query- tool_display = {- "rag": "RAG",- "paper_search": "Paper",- "web_search": "Web",- "run_code": "Code",- }.get(trace.tool_type.lower(), trace.tool_type)-- # Use clear format: cite as [N] -> source description- lines.append(f" - Cite as [{ref_num}] → ({tool_display}) {query_preview}")-- if not lines:- return " (No citations available for this section)"-- return "\n".join(lines)-- async def _call_llm_json(- self,- prompt: str,- system_prompt: str,- stage: str,- trace_label: str,- required_keys: list[str],- max_retries: int = 1,- ) -> dict[str, Any]:- """Call LLM and extract JSON with retry logic."""- last_error = None- for attempt in range(max_retries + 1):- if attempt > 0:- self.logger.info(f"Retrying {stage} (attempt {attempt}/{max_retries})...")-- _chunks: list[str] = []- async for _c in self.stream_llm(- prompt,- system_prompt,- stage=stage,- trace_meta=self._build_trace_meta(trace_label),- ):- _chunks.append(_c)- resp = "".join(_chunks)- data = extract_json_from_text(resp)-- try:- obj = ensure_json_dict(data)- ensure_keys(obj, required_keys)- return obj- except (ValueError, KeyError) as e:- last_error = e- self.logger.warning(f"JSON parsing failed for {stage} (attempt {attempt}): {e}")-- raise ValueError(- f"Failed to get valid JSON from LLM after {max_retries} retries for {stage}. "- f"Required keys: {required_keys}. Last error: {last_error}"- )-- async def _write_introduction(- self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]- ) -> str:- """Write report introduction section"""- system_prompt = self.get_prompt(- "system",- "role",- "You are an academic writing expert specializing in writing the introduction section of research reports.",- )- tmpl = self._get_mode_process_prompt("write_introduction")- if not tmpl:- raise ValueError(- "Cannot get introduction writing prompt template, report generation failed"- )-- import json as _json-- # Prepare context for introduction: overview information of all topics- topics_summary = []- for b in blocks:- topics_summary.append(- {"sub_topic": b.sub_topic, "overview": b.overview, "tool_count": len(b.tool_traces)}- )-- # Use introduction_instruction if available, otherwise fall back to introduction title- intro_instruction = outline.get("introduction_instruction", "") or outline.get(- "introduction", ""- )-- # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}- topics_summary_json = _json.dumps(topics_summary, ensure_ascii=False, indent=2)- filled = self._safe_format(- tmpl,- topic=topic,- introduction_instruction=intro_instruction,- topics_summary=topics_summary_json,- total_topics=len(blocks),- )- filled = self._append_contract(- filled,- "Mode-specific introduction contract",- self._get_mode_contract("introduction"),- )-- data = await self._call_llm_json(- prompt=filled,- system_prompt=system_prompt,- stage="write_introduction",- trace_label="Write introduction",- required_keys=["introduction"],- )- return data["introduction"]-- async def _write_section_body(- self, topic: str, block: TopicBlock, section_outline: dict[str, Any]- ) -> str:- """Write main content of a single section"""- system_prompt = self.get_prompt(- "system",- "role",- "You are an academic writing expert specializing in writing chapter content for research reports.",- )- tmpl = self._get_mode_process_prompt("write_section_body")- if not tmpl:- raise ValueError("Cannot get section writing prompt template, report generation failed")-- import json as _json-- block_data = self._ser_block(block)-- # Dynamically build citation instructions based on configuration- if self.enable_inline_citations:- # Build clear citation reference table for this block- citation_table = self._build_citation_table(block)-- citation_instruction_template = self.get_prompt("citation", "enabled_instruction")- if citation_instruction_template:- citation_instruction = citation_instruction_template.format(- citation_table=citation_table- )- else:- # Fallback if YAML not configured- citation_instruction = f"**Citation Reference Table**:\n{citation_table}"- citation_output_hint = ", citations"- else:- citation_instruction = self.get_prompt("citation", "disabled_instruction") or ""- citation_output_hint = ""-- # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}- block_data_json = _json.dumps(block_data, ensure_ascii=False, indent=2)- filled = self._safe_format(- tmpl,- topic=topic,- section_title=section_outline.get("title", block.sub_topic),- section_instruction=section_outline.get("instruction", ""),- block_data=block_data_json,- min_section_length=self.reporting_config.get("min_section_length", 500),- citation_instruction=citation_instruction,- citation_output_hint=citation_output_hint,- )- filled = self._append_contract(- filled,- "Mode-specific section contract",- self._get_mode_contract("section"),- )-- data = await self._call_llm_json(- prompt=filled,- system_prompt=system_prompt,- stage="write_section_body",- trace_label="Write section",- required_keys=["section_content"],- )- return data["section_content"]-- async def _write_conclusion(- self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]- ) -> str:- """Write report conclusion section"""- system_prompt = self.get_prompt(- "system",- "role",- "You are an academic writing expert specializing in writing the conclusion section of research reports.",- )- tmpl = self._get_mode_process_prompt("write_conclusion")- if not tmpl:- raise ValueError(- "Cannot get conclusion writing prompt template, report generation failed"- )-- import json as _json-- # Prepare context for conclusion: key findings of all topics- topics_findings = []- for b in blocks:- findings = {- "sub_topic": b.sub_topic,- "overview": b.overview,- "key_findings": [- t.summary for t in b.tool_traces[:3]- ], # Top 3 key findings for each topic- }- topics_findings.append(findings)-- # Use conclusion_instruction if available, otherwise fall back to conclusion title- conclusion_instruction = outline.get("conclusion_instruction", "") or outline.get(- "conclusion", ""- )-- # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}- topics_findings_json = _json.dumps(topics_findings, ensure_ascii=False, indent=2)- filled = self._safe_format(- tmpl,- topic=topic,- conclusion_instruction=conclusion_instruction,- topics_findings=topics_findings_json,- total_topics=len(blocks),- )- filled = self._append_contract(- filled,- "Mode-specific conclusion contract",- self._get_mode_contract("conclusion"),- )-- data = await self._call_llm_json(- prompt=filled,- system_prompt=system_prompt,- stage="write_conclusion",- trace_label="Write conclusion",- required_keys=["conclusion"],- )- return data["conclusion"]-- def _build_citation_number_map(self, blocks: list[TopicBlock]) -> dict[str, int]:- """Build citation_id to reference number mapping with deduplication-- This method delegates to CitationManager for unified mapping logic.- The mapping is built once and cached in CitationManager.-- Returns:- Dictionary mapping citation_id (e.g., "CIT-1-01") to reference number (e.g., 1)- """- if self.citation_manager:- # Use CitationManager's unified mapping (single source of truth)- return self.citation_manager.build_ref_number_map()-- # Fallback: build from blocks when no CitationManager available- citation_map = {}-- def extract_citation_number(cit_id):- try:- if cit_id.startswith("PLAN-"):- num = int(cit_id.replace("PLAN-", ""))- return (0, 0, num)- parts_list = cit_id.replace("CIT-", "").split("-")- if len(parts_list) == 2:- return (1, int(parts_list[0]), int(parts_list[1]))- except:- pass- return (999, 999, 999)-- all_citations = []- for block in blocks:- if block.tool_traces:- for trace in block.tool_traces:- citation_id = getattr(trace, "citation_id", None)- if citation_id and citation_id not in [c["citation_id"] for c in all_citations]:- all_citations.append({"citation_id": citation_id})-- all_citations.sort(key=lambda x: extract_citation_number(x["citation_id"]))-- for idx, cit in enumerate(all_citations, 1):- citation_map[cit["citation_id"]] = idx-- return citation_map-- def _generate_references(self, blocks: list[TopicBlock]) -> str:- """Generate References section"""- parts = ["## References\n"]-- # If using CitationManager, generate from JSON file- if self.citation_manager:- return self._generate_references_from_manager(blocks)-- # Otherwise use original method of extracting from blocks (backward compatible)- return self._generate_references_from_blocks(blocks)-- def _get_citation_dedup_key(self, citation: dict, paper: dict = None) -> str:- """Generate unique key for citation deduplication-- Args:- citation: The citation dict- paper: Optional paper dict for paper_search citations-- Returns:- Unique string key for deduplication- """- tool_type = citation.get("tool_type", "").lower()-- if tool_type == "paper_search" and paper:- # For papers: use title + first author (normalized)- title = paper.get("title", "").lower().strip()- authors = paper.get("authors", "").lower().strip()- # Extract first author if multiple- first_author = authors.split(",")[0].strip() if authors else ""- return f"paper:{title}|{first_author}"- elif tool_type == "paper_search":- # Fallback for paper_search without paper dict- title = citation.get("title", "").lower().strip()- authors = citation.get("authors", "").lower().strip()- first_author = authors.split(",")[0].strip() if authors else ""- return f"paper:{title}|{first_author}"- else:- # For RAG/web_search/etc: use tool_type + query (normalized)- query = citation.get("query", "").lower().strip()- # Use first 100 chars of query for dedup- return f"{tool_type}:{query[:100]}"-- def _generate_references_from_manager(self, blocks: list[TopicBlock]) -> str:- """Generate References section from CitationManager in academic paper style-- Uses CitationManager's ref_number_map to ensure consistency between- in-text citations and the References section.-- Format:- - Ordered by reference number (consistent with in-text citations)- - Paper citations: APA format- - RAG/Query citations: Tool name, query, summary- - Web search: Tool name, query, summary + collapsible links- """- parts = ["## References\n\n"]-- # Get all citations and the ref_number_map- all_citations = self.citation_manager.get_all_citations()-- if not all_citations:- return "## References\n\n*No citations available.*\n"-- # Get the ref_number_map from CitationManager (single source of truth)- ref_map = self.citation_manager.get_ref_number_map()-- # Build reverse map: ref_number -> (citation_id, paper_idx or None)- # This groups citations by their ref_number for consistent output- ref_to_citations: dict[int, list[tuple[str, dict, dict | None]]] = {}-- for citation_id, citation in all_citations.items():- tool_type = citation.get("tool_type", "").lower()-- if tool_type == "paper_search":- papers = citation.get("papers", [])- if papers:- for paper_idx, paper in enumerate(papers):- # Check if this paper has a ref_number- paper_ref_key = f"{citation_id}-{paper_idx + 1}"- ref_num = ref_map.get(paper_ref_key) or ref_map.get(citation_id, 0)- if ref_num > 0:- if ref_num not in ref_to_citations:- ref_to_citations[ref_num] = []- ref_to_citations[ref_num].append((citation_id, citation, paper))- else:- ref_num = ref_map.get(citation_id, 0)- if ref_num > 0:- if ref_num not in ref_to_citations:- ref_to_citations[ref_num] = []- ref_to_citations[ref_num].append((citation_id, citation, None))- else:- ref_num = ref_map.get(citation_id, 0)- if ref_num > 0:- if ref_num not in ref_to_citations:- ref_to_citations[ref_num] = []- ref_to_citations[ref_num].append((citation_id, citation, None))-- # Generate references in order of ref_number- for ref_num in sorted(ref_to_citations.keys()):- entries = ref_to_citations[ref_num]- if not entries:- continue-- # Use the first entry for this ref_number (others are duplicates)- citation_id, citation, paper = entries[0]- tool_type = citation.get("tool_type", "").lower()-- anchor = f"ref-{ref_num}"- parts.append(f'<a id="{anchor}"></a>**[{ref_num}]** ')-- if tool_type == "paper_search":- if paper:- formatted = self._format_single_paper_apa(paper)- else:- formatted = self._format_paper_citation_apa(citation)- parts.append(formatted)- elif tool_type == "web_search":- formatted = self._format_web_search_citation(citation)- parts.append(formatted)- elif tool_type in ("rag", "rag_naive", "rag_hybrid"):- formatted = self._format_rag_citation(citation)- parts.append(formatted)- elif tool_type == "run_code":- formatted = self._format_code_citation(citation)- parts.append(formatted)- else:- # Generic format- query = citation.get("query", "")- summary = citation.get("summary", "")- parts.append(f"**{tool_type}**\n\n")- parts.append(f"- **Query**: {query}\n")- if summary:- clean_summary = self._strip_markdown(summary)- parts.append(- f"- **Summary**: {clean_summary[:300]}{'...' if len(clean_summary) > 300 else ''}\n"- )-- parts.append("\n\n")-- return "".join(parts)-- def _format_single_paper_apa(self, paper: dict) -> str:- """Format a single paper in APA style-- Format: Authors (Year). *Title*. Venue. arXiv:ID. URL- """- authors = paper.get("authors", "Unknown Author")- year = paper.get("year", "n.d.")- title = paper.get("title", "Untitled")- url = paper.get("url", "")- arxiv_id = paper.get("arxiv_id", "")- venue = paper.get("venue", "")- doi = paper.get("doi", "")-- # APA format- result = f"{authors} ({year}). *{title}*."- if venue:- result += f" {venue}."- if arxiv_id:- result += f" arXiv:{arxiv_id}."- if doi:- result += f" https://doi.org/{doi}"- elif url:- result += f" {url}"-- return result-- def _format_paper_citation_apa(self, citation: dict) -> str:- """Format paper citation in APA style (fallback for citations without papers array)-- Format: Authors (Year). *Title*. Venue. arXiv:ID. URL- """- authors = citation.get("authors", "Unknown Author")- year = citation.get("year", "n.d.")- title = citation.get("title", "Untitled")- url = citation.get("url", "")- arxiv_id = citation.get("arxiv_id", "")- venue = citation.get("venue", "")- doi = citation.get("doi", "")-- result = f"{authors} ({year}). *{title}*."- if venue:- result += f" {venue}."- if arxiv_id:- result += f" arXiv:{arxiv_id}."- if doi:- result += f" https://doi.org/{doi}"- elif url:- result += f" {url}"- return result-- def _format_web_search_citation(self, citation: dict) -> str:- """Format web search citation with collapsible links"""- query = citation.get("query", "")- summary = citation.get("summary", "")- web_sources = citation.get("web_sources", [])-- result = "**Web Search**\n\n"- result += f"- **Query**: {query}\n"- if summary:- # Clean summary to avoid markdown rendering issues- clean_summary = self._strip_markdown(summary)- summary_text = clean_summary[:300] + ("..." if len(clean_summary) > 300 else "")- result += f"- **Summary**: {summary_text}\n"-- # Add collapsible links section- if web_sources:- result += "\n<details>\n<summary>📎 Retrieved Sources ({} links)</summary>\n\n".format(- len(web_sources)- )- for i, source in enumerate(web_sources, 1):- title = source.get("title", "Untitled")- url = source.get("url", "")- snippet = source.get("snippet", "")- if url:- result += f"{i}. [{title}]({url})"- if snippet:- clean_snippet = self._strip_markdown(snippet)- result += f"\n > {clean_snippet[:150]}{'...' if len(clean_snippet) > 150 else ''}"- result += "\n\n"- result += "</details>"-- return result-- def _format_rag_citation(self, citation: dict) -> str:- """Format RAG/Query citation"""- tool_type = citation.get("tool_type", "")- query = citation.get("query", "")- summary = citation.get("summary", "")- kb_name = citation.get("kb_name", "")- sources = citation.get("sources", [])-- # Tool name display- result = "**RAG**"- if kb_name:- result += f" (KB: {kb_name})"- result += "\n\n"- result += f"- **Query**: {query}\n"- if summary:- # Clean summary: remove markdown formatting to avoid rendering issues- clean_summary = self._strip_markdown(summary)- summary_text = clean_summary[:300] + ("..." if len(clean_summary) > 300 else "")- result += f"- **Summary**: {summary_text}\n"-- # Add source documents if available- if sources:- result += "\n<details>\n<summary>📄 Source Documents ({} docs)</summary>\n\n".format(- len(sources)- )- for i, source in enumerate(sources, 1):- title = source.get("title", "") or source.get("source_file", f"Document {i}")- content = source.get("content_preview", "")- page = source.get("page", "")- result += f"{i}. **{title}**"- if page:- result += f" (Page {page})"- if content:- clean_content = self._strip_markdown(content)- result += (- f"\n > {clean_content[:150]}{'...' if len(clean_content) > 150 else ''}"- )- result += "\n\n"- result += "</details>"-- return result-- def _strip_markdown(self, text: str) -> str:- """Strip markdown formatting from text to get plain text"""- import re-- if not text:- return ""-- # Remove bold/italic markers- text = re.sub(r"\*\*([^*]+)\*\*", r"\1", text) # **bold**- text = re.sub(r"\*([^*]+)\*", r"\1", text) # *italic*- text = re.sub(r"__([^_]+)__", r"\1", text) # __bold__- text = re.sub(r"_([^_]+)_", r"\1", text) # _italic_-- # Remove headers- text = re.sub(r"^#{1,6}\s+", "", text, flags=re.MULTILINE)-- # Remove links but keep text- text = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", text)-- # Remove inline code- text = re.sub(r"`([^`]+)`", r"\1", text)-- # Remove bullet points- text = re.sub(r"^[\s]*[-*+]\s+", "", text, flags=re.MULTILINE)-- # Remove numbered lists- text = re.sub(r"^[\s]*\d+\.\s+", "", text, flags=re.MULTILINE)-- # Remove blockquotes- text = re.sub(r"^>\s*", "", text, flags=re.MULTILINE)-- # Normalize whitespace- text = re.sub(r"\n{3,}", "\n\n", text)- text = re.sub(r" +", " ", text)-- return text.strip()-- def _format_code_citation(self, citation: dict) -> str:- """Format code execution citation"""- query = citation.get("query", "") # This is usually the code- summary = citation.get("summary", "")-- result = "**Code Execution**\n\n"- if query:- # Truncate long code- code_preview = query[:300] + ("..." if len(query) > 300 else "")- result += f"- **Code**: `{code_preview}`\n"- if summary:- summary_text = summary[:300] + ("..." if len(summary) > 300 else "")- result += f"- **Result**: {summary_text}\n"-- return result-- def _generate_references_from_blocks(self, blocks: list[TopicBlock]) -> str:- """Generate References section from blocks (backward compatible, academic paper style)"""- parts = ["## References\n\n"]-- # Collect all citations- all_citations = []- for block in blocks:- if block.tool_traces:- for trace in block.tool_traces:- citation_id = (- getattr(trace, "citation_id", None)- or f"CIT-{block.block_id.split('_')[-1]}-01"- )- all_citations.append(- {"citation_id": citation_id, "block": block, "trace": trace}- )-- if not all_citations:- return "## References\n\n*No citations available.*\n"-- # Sort by citation_id (extract numeric parts for sorting)- def extract_citation_number(cit_id):- try:- if cit_id.startswith("PLAN-"):- num = int(cit_id.replace("PLAN-", ""))- return (0, 0, num)- # CIT-X-XX format- parts_list = cit_id.replace("CIT-", "").split("-")- if len(parts_list) == 2:- return (1, int(parts_list[0]), int(parts_list[1]))- except:- pass- return (999, 999, 999)-- all_citations.sort(key=lambda x: extract_citation_number(x["citation_id"]))-- # Generate numbered references in academic paper style- # Using simple ref-N anchor format for clickable inline citations- for idx, cit in enumerate(all_citations, 1):- trace = cit["trace"]- citation_id = cit["citation_id"]-- # Use simple ref-N anchor format (consistent with _generate_references_from_manager)- anchor = f"ref-{idx}"- tool_type = trace.tool_type.lower() if trace.tool_type else ""-- # Tool name display- tool_display = {- "rag": "RAG",- "paper_search": "Paper Search",- "web_search": "Web Search",- "run_code": "Code Execution",- }.get(tool_type, tool_type)-- parts.append(f'<a id="{anchor}"></a>**[{idx}]** **{tool_display}**\n\n')- parts.append(f"- **Query**: {trace.query}\n")- if trace.summary:- summary_text = trace.summary[:500] + ("..." if len(trace.summary) > 500 else "")- parts.append(f"- **Summary**: {summary_text}\n")- parts.append("\n")-- return "".join(parts)-- def _convert_citation_format(self, text: str) -> str:- """- Convert various citation formats to clickable [[N]](#ref-N) format.-- Handles:- - [N] format (simple number in brackets)- - [ref=N] format (from citation table)-- Args:- text: Text with citations in various formats-- Returns:- Text with [[N]](#ref-N) clickable citations- """- import re-- # Get valid ref_numbers from the citation map- valid_refs = set()- if hasattr(self, "_citation_map") and self._citation_map:- valid_refs = set(self._citation_map.values())-- def replace_citation(match):- # Get the number from the match- ref_num = match.group(1)-- # Only convert if it's a valid ref_number- try:- num = int(ref_num)- if num in valid_refs:- return f"[[{ref_num}]](#ref-{ref_num})"- except ValueError:- pass-- # Return unchanged if not a valid reference- return match.group(0)-- # First, convert [ref=N] format to clickable format- # Pattern: [ref=N] where N is a number- ref_pattern = r"\[ref=(\d+)\]"- text = re.sub(ref_pattern, replace_citation, text)-- # Then, convert simple [N] format (but NOT already converted [[N]])- # Pattern to match [N] where N is a number, but NOT already in [[N]] format- # Use negative lookbehind and lookahead to avoid matching [[N]] or [N](#ref-N)- simple_pattern = r"(?<!\[)\[(\d+)\](?!\(#ref-)"- text = re.sub(simple_pattern, replace_citation, text)-- return text-- def _validate_and_fix_citations(self, text: str) -> tuple[str, dict]:- """- Validate citations in text and fix invalid ones.-- Args:- text: Text with citations-- Returns:- Tuple of (fixed_text, validation_result)- """- import re-- # Get valid ref_numbers- valid_refs = set()- if hasattr(self, "_citation_map") and self._citation_map:- valid_refs = set(self._citation_map.values())-- # Find all citations in [[N]](#ref-N) format- pattern = r"\[\[(\d+)\]\]\(#ref-\d+\)"- found_citations = re.findall(pattern, text)-- valid = []- invalid = []-- for ref in found_citations:- try:- num = int(ref)- if num in valid_refs:- valid.append(num)- else:- invalid.append(num)- except ValueError:- invalid.append(ref)-- # Remove invalid citations- if invalid:-- def remove_invalid(match):- ref_num = match.group(1)- try:- num = int(ref_num)- if num not in valid_refs:- return "" # Remove invalid citation- except ValueError:- return ""- return match.group(0)-- text = re.sub(pattern, remove_invalid, text)-- validation_result = {- "valid_citations": valid,- "invalid_citations": invalid,- "is_valid": len(invalid) == 0,- "total_found": len(found_citations),- }-- return text, validation_result-- async def _write_report(- self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]- ) -> str:- """Write complete report using step-by-step method with three-level heading support"""- # Build citation number map before writing (for consistent ref_number in traces)- if self.enable_inline_citations:- self._citation_map = self._build_citation_number_map(blocks)- print(f" 📋 Built citation map with {len(self._citation_map)} entries")- else:- self._citation_map = {}-- if self.single_pass_threshold > 0 and len(blocks) <= self.single_pass_threshold:- print(" ⚡ Using single-pass report writing mode...")- report = await self._write_report_single_pass(topic, blocks, outline)- else:- report = await self._write_report_step_by_step(topic, blocks, outline)-- # 6. Post-process citations (convert [N] to [[N]](#ref-N) format)- if self.enable_inline_citations:- print(" 🔗 Converting citation format...")- report = self._convert_citation_format(report)-- # Validate and fix invalid citations- print(" ✓ Validating citations...")- report, validation = self._validate_and_fix_citations(report)-- if not validation["is_valid"]:- print(- f" ⚠️ Removed {len(validation['invalid_citations'])} invalid citations: {validation['invalid_citations']}"- )- else:- print(f" ✓ All {validation['total_found']} citations are valid")-- return report-- async def _write_report_step_by_step(- self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]- ) -> str:- """Write complete report using the original multi-call chapter flow."""- parts = []-- # 1. Add main title (from outline, or use topic if not available)- title = outline.get("title", f"# {topic}")- if not title.startswith("#"):- title = f"# {title}"- parts.append(f"{title}\n\n")-- # 2. Write introduction- print(" 📝 Writing introduction...")- self._notify_progress(- getattr(self, "_progress_callback", None),- "writing_section",- current_section="Introduction",- section_index=0,- total_sections=len(outline.get("sections", [])) + 2, # +2 for intro and conclusion- )- introduction = await self._write_introduction(topic, blocks, outline)- # Get introduction title from outline, or use default if not available- intro_title = outline.get("introduction", "## Introduction")- if not intro_title.startswith("##"):- intro_title = f"## {intro_title}"- parts.append(f"{intro_title}\n\n")- parts.append(introduction)- parts.append("\n\n")-- # 3. Write each section with subsection support- sections = outline.get("sections", [])- for i, section in enumerate(sections, 1):- block_id = section.get("block_id")- block = next((b for b in blocks if b.block_id == block_id), None)- if not block:- print(- f" ⚠️ Warning: Cannot find topic block with block_id={block_id}, skipping this section"- )- continue-- section_title = section.get("title", block.sub_topic)- # Clean section title for display (remove markdown markers)- display_title = section_title.replace("##", "").strip()- print(f" 📝 Writing section {i}/{len(sections)}: {section_title}...")- self._notify_progress(- getattr(self, "_progress_callback", None),- "writing_section",- current_section=display_title,- section_index=i, # 1-based, after introduction- total_sections=len(sections) + 2, # +2 for intro and conclusion- )-- # Check if section has subsections defined in outline- subsections = section.get("subsections", [])-- if subsections:- # Write section with explicit subsection structure- section_content = await self._write_section_with_subsections(- topic, block, section, subsections- )- else:- # Write section normally (LLM will generate its own subsection structure)- section_content = await self._write_section_body(topic, block, section)-- # Section content already includes ## level title, append directly- parts.append(section_content)- parts.append("\n\n")-- # 4. Write conclusion- print(" 📝 Writing conclusion...")- total_sections = len(sections) + 2- self._notify_progress(- getattr(self, "_progress_callback", None),- "writing_section",- current_section="Conclusion",- section_index=total_sections - 1, # Last section- total_sections=total_sections,- )- conclusion = await self._write_conclusion(topic, blocks, outline)- # Get conclusion title from outline, or use default if not available- conclusion_title = outline.get("conclusion", "## Conclusion")- if not conclusion_title.startswith("##"):- conclusion_title = f"## {conclusion_title}"- parts.append(f"{conclusion_title}\n\n")- parts.append(conclusion)- parts.append("\n\n")-- # 5. Generate References based on configuration- if self.enable_citation_list:- print(" 📝 Generating citation list...")- references = self._generate_references(blocks)- parts.append(references)- else:- print(" ℹ️ Citation list disabled, skipping generation")-- # Combine all parts- return "".join(parts)-- async def _write_report_single_pass(- self, topic: str, blocks: list[TopicBlock], outline: dict[str, Any]- ) -> str:- """Write the full report in one LLM call for lightweight runs."""- import json as _json-- system_prompt = self.get_prompt(- "system",- "role",- "You are an academic writing expert specializing in concise, high-quality research reports.",- )- tmpl = self._get_mode_process_prompt("write_full_report")- if not tmpl:- raise ValueError(- "Cannot get single-pass report prompt template, report generation failed"- )-- blocks_data = [self._ser_block(block) for block in blocks]- outline_json = _json.dumps(outline, ensure_ascii=False, indent=2)- blocks_json = _json.dumps(blocks_data, ensure_ascii=False, indent=2)-- if self.enable_inline_citations:- citation_instruction = (- "Use inline citations in [N] format whenever a trace provides a ref_number. "- "Do not invent citation numbers and do not add a References section."- )- else:- citation_instruction = (- "Do not add inline citations and do not add a References section."- )-- filled = self._safe_format(- tmpl,- topic=topic,- outline_json=outline_json,- blocks_json=blocks_json,- total_topics=len(blocks),- citation_instruction=citation_instruction,- )- filled = self._append_contract(- filled,- "Mode-specific full-report contract",- self._get_mode_contract("single_pass"),- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- filled,- system_prompt,- stage="write_full_report",- trace_meta=self._build_trace_meta("Write full report"),- ):- _chunks.append(_c)- resp = "".join(_chunks)- data = extract_json_from_text(resp)-- try:- obj = ensure_json_dict(data)- ensure_keys(obj, ["report"])- report = obj.get("report", "")- if not isinstance(report, str) or not report.strip():- raise ValueError("LLM returned empty report field")- except Exception:- if isinstance(data, dict) and ("sections" in data or "title" in data):- report = self._assemble_markdown_from_structured(data)- else:- stripped = resp.strip()- if stripped and stripped.startswith("#"):- report = stripped- else:- report = self._strip_json_wrapper(resp)-- if self.enable_citation_list:- report = report.rstrip() + "\n\n" + self._generate_references(blocks)-- return report-- @staticmethod- def _assemble_markdown_from_structured(obj: dict[str, Any]) -> str:- """Reconstruct markdown from a structured JSON report the LLM returned- instead of the expected {report: "..."} wrapper."""- parts: list[str] = []- if obj.get("title"):- parts.append(str(obj["title"]))- if obj.get("introduction"):- parts.append(str(obj["introduction"]))- for section in obj.get("sections", []):- if isinstance(section, str):- parts.append(section)- continue- if not isinstance(section, dict):- continue- if section.get("title"):- parts.append(str(section["title"]))- if section.get("content"):- parts.append(str(section["content"]))- for sub in section.get("subsections", []):- if isinstance(sub, str):- parts.append(sub)- elif isinstance(sub, dict):- if sub.get("title"):- parts.append(str(sub["title"]))- if sub.get("content"):- parts.append(str(sub["content"]))- if obj.get("conclusion"):- parts.append(str(obj["conclusion"]))- return "\n\n".join(parts)-- @staticmethod- def _strip_json_wrapper(resp: str) -> str:- """Best-effort extraction of readable text from a JSON response."""- from deeptutor.utils.json_parser import parse_json_response-- obj = parse_json_response(resp.strip(), fallback=None)- if isinstance(obj, dict):- for key in ("report", "content", "text", "markdown", "output"):- if key in obj and isinstance(obj[key], str):- return obj[key]- stripped = resp.strip()- if stripped.startswith("{") or stripped.startswith("["):- for line in stripped.split("\\n"):- if line.strip().startswith("#"):- return stripped.replace("\\n", "\n")- return stripped-- async def _write_section_with_subsections(- self,- topic: str,- block: TopicBlock,- section: dict[str, Any],- subsections: list[dict[str, Any]],- ) -> str:- """Write a section that has explicitly defined subsections in the outline-- This method writes the section as a whole, passing subsection structure to the LLM- to guide the content organization while maintaining coherence.- """- import json as _json-- # Enhance section instruction with subsection information- subsection_info = []- for j, sub in enumerate(subsections, 1):- subsection_info.append(- {- "title": sub.get("title", f"### Subsection {j}"),- "instruction": sub.get("instruction", ""),- }- )-- # Create enhanced section data with subsection guidance- enhanced_section = {- "title": section.get("title", block.sub_topic),- "instruction": section.get("instruction", ""),- "subsection_structure": subsection_info,- }-- # Prepare block data with subsection hints- block_data = self._ser_block(block)- block_data["expected_subsections"] = subsection_info-- system_prompt = self.get_prompt(- "system",- "role",- "You are an academic writing expert specializing in writing comprehensive research report sections with structured subsections.",- )- tmpl = self._get_mode_process_prompt("write_section_body")- if not tmpl:- raise ValueError("Cannot get section writing prompt template, report generation failed")-- # Build enhanced instruction including subsection structure- section_instruction = section.get("instruction", "")- if subsection_info:- subsection_guide = "\n\n**Expected subsection structure:**\n"- for sub in subsection_info:- subsection_guide += f"- {sub['title']}: {sub['instruction']}\n"- section_instruction += subsection_guide-- # Dynamically build citation instructions based on configuration- if self.enable_inline_citations:- # Build clear citation reference table for this block- citation_table = self._build_citation_table(block)-- citation_instruction_template = self.get_prompt("citation", "enabled_instruction")- if citation_instruction_template:- citation_instruction = citation_instruction_template.format(- citation_table=citation_table- )- else:- # Fallback if YAML not configured- citation_instruction = f"**Citation Reference Table**:\n{citation_table}"- citation_output_hint = ", citations"- else:- citation_instruction = self.get_prompt("citation", "disabled_instruction") or ""- citation_output_hint = ""-- # Use safe_format to avoid conflicts with LaTeX braces like {\rho}, {L}- block_data_json = _json.dumps(block_data, ensure_ascii=False, indent=2)- filled = self._safe_format(- tmpl,- topic=topic,- section_title=section.get("title", block.sub_topic),- section_instruction=section_instruction,- block_data=block_data_json,- min_section_length=self.reporting_config.get("min_section_length", 800),- citation_instruction=citation_instruction,- citation_output_hint=citation_output_hint,- )- filled = self._append_contract(- filled,- "Mode-specific section contract",- self._get_mode_contract("section"),- )-- try:- data = await self._call_llm_json(- prompt=filled,- system_prompt=system_prompt,- stage="write_section_with_subsections",- trace_label="Write section",- required_keys=["section_content"],- )- content = data["section_content"]- if isinstance(content, str) and content.strip():- return content- raise ValueError("LLM returned empty or invalid section_content field")- except ValueError:- self.logger.warning(- f"JSON parsing failed for section '{section.get('title', 'unknown')}', "- "falling back to raw LLM output"- )- # Fallback: call LLM again without strict JSON requirement and use raw text- _chunks: list[str] = []- async for _c in self.stream_llm(- filled,- system_prompt,- stage="write_section_with_subsections_fallback",- trace_meta=self._build_trace_meta("Write section (fallback)"),- ):- _chunks.append(_c)- resp = "".join(_chunks).strip()- if not resp:- raise ValueError(- f"Unable to generate section content for '{section.get('title', 'unknown')}'. "- "Report generation failed."- )- return self._strip_json_wrapper(resp)-- def _notify_progress(- self, callback: Callable[[dict[str, Any]], None] | None, status: str, **payload: Any- ) -> None:- if not callback:- return- event = {"status": status}- event.update({k: v for k, v in payload.items() if v is not None})- try:- callback(event)- except Exception:- pass---__all__ = ["ReportingAgent"]diff --git a/deeptutor/agents/research/agents/research_agent.py b/deeptutor/agents/research/agents/research_agent.pydeleted file mode 100644index 2365975b7..000000000--- a/deeptutor/agents/research/agents/research_agent.py+++ /dev/null@@ -1,746 +0,0 @@-#!/usr/bin/env python-"""-ResearchAgent - Research Agent-Responsible for executing research logic and tool call decisions-"""--from collections.abc import Awaitable, Callable-import json-import re-from string import Template-from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.agents.research.data_structures import DynamicTopicQueue, TopicBlock-from deeptutor.core.trace import build_trace_metadata, new_call_id-from deeptutor.runtime.registry.tool_registry import get_tool_registry--from ..utils.json_utils import extract_json_from_text---class ResearchAgent(BaseAgent):- """Research Agent"""-- _MODE_TO_STYLE = {- "notes": "study_notes",- "report": "report",- "comparison": "comparison",- "learning_path": "learning_path",- }-- @staticmethod- def _build_trace_meta(- *,- label: str,- iteration: int,- block_id: str = "",- trace_role: str = "thought",- ) -> dict[str, Any]:- return build_trace_metadata(- call_id=new_call_id("research-step"),- phase="researching",- label=label,- call_kind="llm_reasoning",- trace_role=trace_role,- trace_kind="llm_reasoning",- iteration=iteration,- block_id=block_id or None,- trace_group="research_round" if block_id else None,- )-- def __init__(- self,- config: dict[str, Any],- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- ):- language = config.get("system", {}).get("language", "zh")- super().__init__(- module_name="research",- agent_name="research_agent",- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=language,- config=config,- )- self.researching_config = config.get("researching", {})- self.max_iterations = self.researching_config.get("max_iterations", 5)- # Iteration mode: "fixed" (must explore all iterations) or "flexible" (can stop early)- # In "fixed" mode, agent should be more conservative about declaring knowledge sufficient- # In "flexible" mode (auto), agent can stop early when knowledge is truly sufficient- self.iteration_mode = self.researching_config.get("iteration_mode", "fixed")- self.enable_rag = self.researching_config.get("enable_rag", True)- # Web search: global switch (tools.web_search.enabled) has higher priority- # Only enabled when both global switch and module switch are True- tools_web_search_enabled = (- config.get("tools", {}).get("web_search", {}).get("enabled", True)- )- research_web_search_enabled = self.researching_config.get("enable_web_search", False)- self.enable_web_search = tools_web_search_enabled and research_web_search_enabled- self.enable_paper_search = self.researching_config.get("enable_paper_search", False)- self.enable_run_code = self.researching_config.get("enable_run_code", True)- # Store enabled tools list for prompt generation- self.enabled_tools = self.researching_config.get("enabled_tools", ["RAG"])- self._tool_registry = get_tool_registry()- intent_mode = str(config.get("intent", {}).get("mode", "") or "")- reporting_style = str(config.get("reporting", {}).get("style", "") or "")- self._research_style = reporting_style or self._MODE_TO_STYLE.get(intent_mode, "report")-- @staticmethod- def _convert_to_template_format(template_str: str) -> str:- """- Convert {var} style placeholders to $var style for string.Template.- This avoids conflicts with LaTeX braces like {\rho}.- """- # Only convert simple {var_name} patterns, not nested or complex ones- return re.sub(r"\{(\w+)\}", r"$\1", template_str)-- def _safe_format(self, template_str: str, **kwargs) -> str:- """- Safe string formatting using string.Template to avoid LaTeX brace conflicts.- """- converted = self._convert_to_template_format(template_str)- return Template(converted).safe_substitute(**kwargs)-- def _get_mode_contract(self, stage: str) -> str:- return (- self.get_prompt("mode_contracts", f"{self._research_style}_{stage}", "") or ""- ).strip()-- def _generate_available_tools_text(self) -> str:- """Generate available tools list based on enabled tool configuration."""- tool_names = self._get_enabled_prompt_tools()- if not tool_names:- return "(no tools available)"- return self._tool_registry.build_prompt_text(- tool_names,- format="aliases",- language=self.language,- )-- def _generate_tool_phase_guidance(self) -> str:- """Generate phased tool guidance based on enabled tools."""- tool_names = self._get_enabled_prompt_tools()- guidance = self._tool_registry.build_prompt_text(- tool_names,- format="phased",- language=self.language,- )- if guidance:- return guidance- if self.language == "zh":- return "当前没有额外工具可用,请围绕现有知识继续分析。"- return "No extra tools are currently enabled; continue reasoning with the knowledge already gathered."-- def _get_enabled_prompt_tools(self) -> list[str]:- tool_names: list[str] = []- if self.enable_rag:- tool_names.append("rag")- if self.enable_paper_search:- tool_names.append("paper_search")- if self.enable_web_search:- tool_names.append("web_search")- if self.enable_run_code:- tool_names.append("code_execution")- deduped: list[str] = []- for name in tool_names:- if name not in deduped:- deduped.append(name)- return deduped-- def _is_llm_only_mode(self) -> bool:- return not self._get_enabled_prompt_tools()-- async def _run_llm_self_research(- self,- *,- topic: str,- overview: str,- query: str,- current_knowledge: str,- iteration: int,- block_id: str,- ) -> str:- """Research internally with the model when no external tool is enabled."""- if self.language == "zh":- system_prompt = (- "你是一个深度研究助理。在没有任何外部工具可用时,你需要只基于模型已有知识,"- "围绕给定查询做谨慎、结构化的内部研究。不要假装访问了网页、论文或知识库。"- "如果某些内容是常识性推断或可能存在不确定性,请明确说明。"- )- user_prompt = self._safe_format(- """-请对下面的研究查询进行一次“纯 LLM 内部研究”。--主话题:{topic}-话题概览:{overview}-当前研究轮次:{iteration}-本轮查询:{query}-已有知识:-{current_knowledge}--模式聚焦:-{mode_instruction}--要求:-1. 只能基于模型已有知识进行分析,不要声称使用了外部来源。-2. 直接产出可被后续笔记/报告阶段吸收的研究内容。-3. 优先回答本轮查询对应的知识缺口,并保持结构化、信息密度高。-4. 如果存在不确定点,单独列出“Known Uncertainties”。--仅输出 JSON:-{{- "content": "结构化研究内容",- "confidence": "high/medium/low",- "limitations": ["不确定点1", "不确定点2"]-}}-""",- topic=topic,- overview=overview or "(无)",- iteration=iteration,- query=query,- current_knowledge=current_knowledge[:3000] if current_knowledge else "(无)",- mode_instruction=self._get_mode_contract("research") or "(无额外模式指令)",- )- else:- system_prompt = (- "You are a deep-research assistant. When no external tools are enabled, "- "you must research using only the model's internal knowledge. Do not claim "- "to have searched the web, papers, or a knowledge base. Explicitly note uncertainty "- "when needed."- )- user_prompt = self._safe_format(- """-Perform one round of LLM-only internal research for the following query.--Main Topic: {topic}-Topic Overview: {overview}-Current Iteration: {iteration}-This Round's Query: {query}-Current Knowledge:-{current_knowledge}--Mode-Specific Focus:-{mode_instruction}--Requirements:-1. Use only the model's internal knowledge; do not pretend to access outside sources.-2. Produce content that can be directly absorbed by the later note/report stages.-3. Focus on the specific knowledge gap behind this query and keep the result structured and information-dense.-4. If anything is uncertain, list it under "Known Uncertainties".--Only output JSON:-{{- "content": "Structured research content",- "confidence": "high/medium/low",- "limitations": ["uncertainty 1", "uncertainty 2"]-}}-""",- topic=topic,- overview=overview or "(none)",- iteration=iteration,- query=query,- current_knowledge=current_knowledge[:3000] if current_knowledge else "(none)",- mode_instruction=self._get_mode_contract("research")- or "(no extra mode instruction)",- )-- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="llm_self_research",- trace_meta=self._build_trace_meta(- label="LLM self research",- iteration=iteration,- block_id=block_id,- ),- ):- _chunks.append(_c)- response = "".join(_chunks)-- try:- data = extract_json_from_text(response)- except Exception:- data = None- if isinstance(data, dict):- return json.dumps(data, ensure_ascii=False)- return json.dumps({"content": response}, ensure_ascii=False)-- def _generate_research_depth_guidance(self, iteration: int, used_tools: list[str]) -> str:- """- Generate research depth guidance based on iteration, used tools, and iteration_mode-- Args:- iteration: Current iteration number- used_tools: List of tools already used-- Returns:- Research depth guidance text- """- # Determine research phase based on max_iterations- early_threshold = max(2, self.max_iterations // 3)- middle_threshold = max(4, self.max_iterations * 2 // 3)-- if iteration <= early_threshold:- phase = "early"- phase_desc = f"Early Stage (Iteration 1-{early_threshold})"- guidance = "Focus on building foundational knowledge using RAG/knowledge base tools."- elif iteration <= middle_threshold:- phase = "middle"- phase_desc = f"Middle Stage (Iteration {early_threshold + 1}-{middle_threshold})"- if self.enable_paper_search or self.enable_web_search:- guidance = "Consider using Paper/Web search to add academic depth and real-time information."- else:- guidance = "Deepen knowledge coverage, explore different angles of the topic."- else:- phase = "late"- phase_desc = f"Late Stage (Iteration {middle_threshold + 1}+)"- guidance = "Fill knowledge gaps, ensure completeness before concluding."-- # Tool diversity analysis- unique_tools = set(used_tools)- available_tools = []- if self.enable_rag and "rag" not in unique_tools:- available_tools.append("rag")- if self.enable_paper_search and "paper_search" not in unique_tools:- available_tools.append("paper_search")- if self.enable_web_search and "web_search" not in unique_tools:- available_tools.append("web_search")-- diversity_hint = ""- if available_tools and phase != "early":- diversity_hint = f"\n**Tool Diversity Suggestion**: Consider using unexplored tools: {', '.join(available_tools)}"-- # Iteration mode specific guidance- if self.iteration_mode == "flexible":- # Auto/flexible mode: agent can decide when to stop- mode_guidance = """-**Iteration Mode: FLEXIBLE (Auto)**-You have autonomy to decide when knowledge is sufficient. You may stop early if:-- Core concepts are well covered from multiple angles-- Key questions about the topic have been addressed-- Further iterations would only add marginal value-However, ensure you have made meaningful exploration before concluding."""- else:- # Fixed mode: more conservative about stopping- mode_guidance = """-**Iteration Mode: FIXED**-This mode requires thorough exploration. Be CONSERVATIVE about declaring knowledge sufficient:-- In early iterations (first third), rarely conclude sufficiency-- In middle iterations, require strong evidence of comprehensive coverage-- Only in late iterations, conclude if truly comprehensive"""-- return f"""-**Research Phase Guidance** ({phase_desc}):-{guidance}--Current iteration: {iteration}/{self.max_iterations}-Tools already used: {", ".join(used_tools) if used_tools else "None"}-{diversity_hint}-{mode_guidance}-"""-- def _generate_online_search_instruction(self) -> str:- """- Generate online search guidance instructions from YAML config-- Returns:- Online search guidance text, returns empty string if not enabled- """- if not self.enable_web_search and not self.enable_paper_search:- return ""-- if self.enable_web_search and self.enable_paper_search:- instruction = self.get_prompt("guidance", "online_search_both")- if instruction:- return instruction- elif self.enable_web_search:- instruction = self.get_prompt("guidance", "online_search_web_only")- if instruction:- return instruction- elif self.enable_paper_search:- instruction = self.get_prompt("guidance", "online_search_paper_only")- if instruction:- return instruction-- return ""-- def _generate_iteration_mode_criteria(self, iteration: int) -> str:- """- Generate iteration mode specific criteria for sufficiency check from YAML config-- Args:- iteration: Current iteration number-- Returns:- Iteration mode criteria text- """- # Calculate early threshold- early_threshold = max(2, self.max_iterations // 3)-- if self.iteration_mode == "flexible":- criteria = self.get_prompt("guidance", "iteration_mode_flexible")- if criteria:- return criteria- # Fallback if YAML not configured- return "- **FLEXIBLE mode (Auto)**: You have autonomy to decide sufficiency."- else:- criteria = self.get_prompt("guidance", "iteration_mode_fixed")- if criteria:- return criteria.format(early_threshold=early_threshold)- # Fallback if YAML not configured- return f"- **FIXED mode**: Be CONSERVATIVE about declaring sufficiency. Early threshold: {early_threshold}"-- async def plan_next_step(- self,- topic: str,- overview: str,- current_knowledge: str,- iteration: int,- existing_topics: list[str] | None = None,- used_tools: list[str] | None = None,- ) -> dict[str, Any]:- """Evaluate sufficiency and plan the next tool call in one LLM round."""- system_prompt = self.get_prompt("system", "role")- if not system_prompt:- raise ValueError(- "ResearchAgent missing system prompt, please configure system.role in prompts/{lang}/research_agent.yaml"- )- user_prompt_template = self.get_prompt("process", "plan_next_step")- if not user_prompt_template:- raise ValueError(- "ResearchAgent missing plan_next_step prompt, please configure process.plan_next_step in prompts/{lang}/research_agent.yaml"- )-- topics_text = "(No other topics)"- if existing_topics:- topics_text = "\n".join([f"- {t}" for t in existing_topics])-- online_search_instruction = self._generate_online_search_instruction()- research_depth_guidance = self._generate_research_depth_guidance(- iteration, used_tools or []- )- iteration_mode_criteria = self._generate_iteration_mode_criteria(iteration)- available_tools_text = self._generate_available_tools_text()- tool_phase_guidance = self._generate_tool_phase_guidance()-- user_prompt = self._safe_format(- user_prompt_template,- topic=topic,- overview=overview,- current_knowledge=current_knowledge[:3000] if current_knowledge else "(None)",- iteration=iteration,- max_iterations=self.max_iterations,- existing_topics=topics_text,- available_tools=available_tools_text,- tool_phase_guidance=tool_phase_guidance,- research_depth_guidance=research_depth_guidance,- online_search_instruction=online_search_instruction,- iteration_mode_criteria=iteration_mode_criteria,- mode_instruction=self._get_mode_contract("research"),- )- _chunks: list[str] = []- async for _c in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="plan_next_step",- trace_meta=self._build_trace_meta(- label="Plan next step",- iteration=iteration,- trace_role="plan",- ),- ):- _chunks.append(_c)- response = "".join(_chunks)-- from ..utils.json_utils import ensure_json_dict, ensure_keys-- data = extract_json_from_text(response)- obj = ensure_json_dict(data)- ensure_keys(obj, ["is_sufficient", "sufficiency_reason"])- return obj-- async def process(- self,- topic_block: TopicBlock,- call_tool_callback: Callable[[str, str], Awaitable[str]],- note_agent,- citation_manager,- queue: DynamicTopicQueue,- manager_agent,- config: dict[str, Any],- progress_callback: Callable[[str, Any], None] | None = None,- ) -> dict[str, Any]:- """- Execute research for a single topic block (complete multi-round retrieval loop)-- Args:- topic_block: Topic block to research- call_tool_callback: Tool call callback function (tool_type, query) -> raw_answer- note_agent: NoteAgent instance for generating summaries- citation_manager: CitationManager instance for managing citations- queue: DynamicTopicQueue instance for getting existing topic list- manager_agent: ManagerAgent instance for adding new topics- config: Configuration dictionary for getting parameters- progress_callback: Optional callback for iteration progress (event_type, **data)-- Returns:- Research result- {- "block_id": str,- "iterations": int,- "final_knowledge": str,- "tools_used": List[str],- "queries_used": List[dict],- "status": str- }- """- block_id_prefix = f"[{topic_block.block_id}]"- print(f"\n{block_id_prefix} {'=' * 70}")- print(f"{block_id_prefix} 🔬 ResearchAgent - Executing Research")- print(f"{block_id_prefix} {'=' * 70}")- print(f"{block_id_prefix} Topic: {topic_block.sub_topic}")- print(f"{block_id_prefix} Overview: {topic_block.overview}")- print(- f"{block_id_prefix} Max iterations: {self.max_iterations}, Mode: {self.iteration_mode}\n"- )-- iteration = 0- current_knowledge = ""- tools_used = []- queries_used = [] # Track all queries for progress display- llm_only_mode = self._is_llm_only_mode()-- # Helper to send progress updates- def send_progress(event_type: str, **data):- if progress_callback:- try:- progress_callback(event_type, **data)- except Exception:- pass # Ignore callback errors-- while iteration < self.max_iterations:- iteration += 1- print(f"{block_id_prefix} \n【Iteration {iteration}/{self.max_iterations}】")-- # Send iteration started progress- send_progress(- "iteration_started",- iteration=iteration,- max_iterations=self.max_iterations,- tools_used=tools_used.copy(),- )-- # Step 1: Check if knowledge is sufficient- send_progress(- "checking_sufficiency", iteration=iteration, max_iterations=self.max_iterations- )- plan = await self.plan_next_step(- topic=topic_block.sub_topic,- overview=topic_block.overview,- current_knowledge=current_knowledge,- iteration=iteration,- existing_topics=queue.list_topics(),- used_tools=tools_used,- )-- if plan.get("is_sufficient", False):- print(- f"{block_id_prefix} ✓ Current topic is sufficient, ending research for this topic"- )- send_progress(- "knowledge_sufficient",- iteration=iteration,- max_iterations=self.max_iterations,- reason=plan.get("sufficiency_reason", plan.get("reason", "")),- )- break-- send_progress(- "generating_query",- iteration=iteration,- max_iterations=self.max_iterations,- merged_planning=True,- )-- # Dynamic splitting: if new topic is discovered, add to queue tail- new_topic = plan.get("new_sub_topic")- new_overview = plan.get("new_overview")- new_topic_score = float(plan.get("new_topic_score") or 0)- should_add_new_topic = plan.get("should_add_new_topic")- min_score = config.get("researching", {}).get("new_topic_min_score", 0.75)- new_topic_reason = plan.get("new_topic_reason")-- if isinstance(new_topic, str) and new_topic.strip():- trimmed_topic = new_topic.strip()- if should_add_new_topic is False:- print(- f"{block_id_prefix} ↩️ LLM determined not to add new topic《{trimmed_topic}》, skipping"- )- elif new_topic_score < min_score:- print(- f"{block_id_prefix} ↩️ New topic《{trimmed_topic}》score {new_topic_score:.2f} below threshold {min_score:.2f}, skipping"- )- else:- # Support both sync and async manager_agent- import inspect-- add_topic_method = getattr(manager_agent, "add_new_topic")- if inspect.iscoroutinefunction(add_topic_method):- added = await add_topic_method(trimmed_topic, new_overview or "")- else:- added = manager_agent.add_new_topic(trimmed_topic, new_overview or "")- if added:- print(f"{block_id_prefix} ✓ Added new topic《{trimmed_topic}》to queue")- send_progress(- "new_topic_added",- iteration=iteration,- max_iterations=self.max_iterations,- new_topic=trimmed_topic,- new_overview=new_overview or "",- )- if new_topic_reason:- print(f"{block_id_prefix} Reason: {new_topic_reason}")-- query = plan.get("query", "").strip()- tool_type = "llm_self_research" if llm_only_mode else plan.get("tool_type", "rag")- rationale = plan.get("rationale", "")-- if not query:- print(f"{block_id_prefix} ⚠️ Generated query is empty, skipping this iteration")- send_progress(- "query_empty", iteration=iteration, max_iterations=self.max_iterations- )- continue-- # Track this query- query_info = {- "query": query,- "tool_type": tool_type,- "rationale": rationale,- "iteration": iteration,- }- queries_used.append(query_info)-- # Send progress before tool call- send_progress(- "tool_calling",- iteration=iteration,- max_iterations=self.max_iterations,- tool_type=tool_type,- query=query,- rationale=rationale,- )-- # Step 3: Call tool- if llm_only_mode:- raw_answer = await self._run_llm_self_research(- topic=topic_block.sub_topic,- overview=topic_block.overview,- query=query,- current_knowledge=current_knowledge,- iteration=iteration,- block_id=topic_block.block_id,- )- else:- raw_answer = await call_tool_callback(tool_type, query)-- # Send progress after tool call- send_progress(- "tool_completed",- iteration=iteration,- max_iterations=self.max_iterations,- tool_type=tool_type,- query=query,- )-- # Step 4: Get citation ID from CitationManager (unified ID generation)- send_progress(- "processing_notes", iteration=iteration, max_iterations=self.max_iterations- )-- # Get citation_id from CitationManager - support both sync and async- import inspect-- if hasattr(- citation_manager, "get_next_citation_id_async"- ) and inspect.iscoroutinefunction(- getattr(citation_manager, "get_next_citation_id_async", None)- ):- citation_id = await citation_manager.get_next_citation_id_async(- stage="research", block_id=topic_block.block_id- )- else:- citation_id = citation_manager.get_next_citation_id(- stage="research", block_id=topic_block.block_id- )-- # Step 5: NoteAgent records summary with the citation ID- trace = await note_agent.process(- tool_type=tool_type,- query=query,- raw_answer=raw_answer,- citation_id=citation_id,- topic=topic_block.sub_topic,- context=current_knowledge,- )- topic_block.add_tool_trace(trace)-- # Step 6: Add citation information to citation manager- # Support both sync and async citation_manager- if hasattr(citation_manager, "add_citation") and callable(- getattr(citation_manager, "add_citation", None)- ):- add_citation_method = getattr(citation_manager, "add_citation")- if inspect.iscoroutinefunction(add_citation_method):- await add_citation_method(- citation_id=citation_id,- tool_type=tool_type,- tool_trace=trace,- raw_answer=raw_answer,- )- else:- citation_manager.add_citation(- citation_id=citation_id,- tool_type=tool_type,- tool_trace=trace,- raw_answer=raw_answer,- )- else:- # Fallback to sync version- citation_manager.add_citation(- citation_id=citation_id,- tool_type=tool_type,- tool_trace=trace,- raw_answer=raw_answer,- )-- # Step 7: Update knowledge (accumulate summaries)- current_knowledge = (current_knowledge + "\n" + trace.summary).strip()- topic_block.iteration_count = iteration- tools_used.append(tool_type)-- # Send iteration completed progress- send_progress(- "iteration_completed",- iteration=iteration,- max_iterations=self.max_iterations,- tool_type=tool_type,- query=query,- tools_used=tools_used.copy(),- )-- return {- "block_id": topic_block.block_id,- "iterations": iteration,- "final_knowledge": current_knowledge,- "tools_used": tools_used,- "queries_used": queries_used,- "status": "completed" if iteration < self.max_iterations else "max_iterations_reached",- }---__all__ = ["ResearchAgent"]diff --git a/deeptutor/agents/research/data_structures.py b/deeptutor/agents/research/data_structures.pyindex 8977622fd..98253ad90 100644--- a/deeptutor/agents/research/data_structures.py+++ b/deeptutor/agents/research/data_structures.py@@ -6,13 +6,40 @@ Includes: TopicBlock, ToolTrace, DynamicTopicQueuefrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime+import difflibfrom enum import Enumimport jsonfrom pathlib import Path+import refrom typing import Anyfrom deeptutor.utils.json_parser import parse_json_response+# Default fuzzy-match threshold used by :meth:`DynamicTopicQueue.find_similar`.+# 0.85 reliably catches near-duplicate titles (case / punctuation / one-word+# reorderings) while letting genuinely distinct sub-topics through.+DEFAULT_TOPIC_SIMILARITY_THRESHOLD = 0.85+_TOPIC_TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE)+_TOPIC_STOPWORDS = {+ "a",+ "an",+ "and",+ "as",+ "at",+ "by",+ "for",+ "from",+ "in",+ "into",+ "of",+ "on",+ "or",+ "the",+ "to",+ "vs",+ "with",+}+class TopicStatus(Enum):"""Topic block status enumeration"""@@ -240,7 +267,46 @@ class DynamicTopicQueue:@staticmethoddef _normalize_topic(text: str) -> str:- return (text or "").strip().lower()+ return re.sub(r"\s+", " ", (text or "").strip().lower())++ @classmethod+ def _topic_tokens(cls, text: str) -> set[str]:+ tokens: set[str] = set()+ for raw in _TOPIC_TOKEN_RE.findall(cls._normalize_topic(text)):+ token = raw.strip()+ if not token or token in _TOPIC_STOPWORDS:+ continue+ # Tiny English stemmer: enough to align "basics" and "basic"+ # without adding a heavyweight NLP dependency.+ if len(token) > 4 and token.endswith("ies"):+ token = token[:-3] + "y"+ elif len(token) > 3 and token.endswith("s"):+ token = token[:-1]+ tokens.add(token)+ return tokens++ @classmethod+ def _topic_similarity(cls, left: str, right: str) -> float:+ left_norm = cls._normalize_topic(left)+ right_norm = cls._normalize_topic(right)+ if not left_norm or not right_norm:+ return 0.0+ if left_norm == right_norm:+ return 1.0++ sequence_score = difflib.SequenceMatcher(None, left_norm, right_norm).ratio()+ left_tokens = cls._topic_tokens(left_norm)+ right_tokens = cls._topic_tokens(right_norm)+ if not left_tokens or not right_tokens:+ return sequence_score++ overlap = left_tokens & right_tokens+ jaccard = len(overlap) / max(1, len(left_tokens | right_tokens))+ containment = len(overlap) / max(1, min(len(left_tokens), len(right_tokens)))+ token_score = jaccard+ if len(left_tokens) >= 2 and len(right_tokens) >= 2 and jaccard >= 0.5:+ token_score = max(token_score, containment * 0.95)+ return max(sequence_score, token_score)def add_block(self, sub_topic: str, overview: str) -> TopicBlock:"""@@ -271,6 +337,72 @@ class DynamicTopicQueue:return Falsereturn any(self._normalize_topic(b.sub_topic) == target for b in self.blocks)+ def is_full(self) -> bool:+ """Return ``True`` when the queue has reached its configured cap."""+ return self.max_length is not None and len(self.blocks) >= self.max_length++ def find_similar(+ self,+ sub_topic: str,+ *,+ threshold: float = DEFAULT_TOPIC_SIMILARITY_THRESHOLD,+ ) -> TopicBlock | None:+ """Return an existing block whose title is fuzzily similar to+ ``sub_topic``, or ``None`` when no match exceeds ``threshold``.++ Used to dedup ``APPEND`` requests so the LLM can't reliably keep+ proposing the same topic in slightly different words. Exact+ normalised matches always win; otherwise the highest-scoring+ block above ``threshold`` is returned.+ """+ target = self._normalize_topic(sub_topic)+ if not target:+ return None++ best: tuple[float, TopicBlock] | None = None+ for block in self.blocks:+ candidate = self._normalize_topic(block.sub_topic)+ if not candidate:+ continue+ if candidate == target:+ return block+ score = self._topic_similarity(target, candidate)+ if score >= threshold and (best is None or score > best[0]):+ best = (score, block)+ return best[1] if best else None++ def append_child(+ self,+ *,+ parent: TopicBlock | None,+ sub_topic: str,+ overview: str = "",+ ) -> TopicBlock | None:+ """Append a new block to the queue tail, optionally tagging the+ parent block's id in metadata so reporting can reconstruct the+ topic tree.++ Returns the new block on success, or ``None`` when the queue is+ already full. Duplicate detection is the caller's responsibility+ (use :meth:`find_similar` first when needed).+ """+ if self.is_full():+ return None+ self.block_counter += 1+ block_id = f"block_{self.block_counter}"+ metadata: dict[str, Any] = {}+ if parent is not None:+ metadata["parent_block_id"] = parent.block_id+ block = TopicBlock(+ block_id=block_id,+ sub_topic=sub_topic,+ overview=overview,+ metadata=metadata,+ )+ self.blocks.append(block)+ self._auto_save()+ return block+def list_topics(self) -> list[str]:"""List all current topic titles"""return [b.sub_topic for b in self.blocks]diff --git a/deeptutor/agents/research/mode_strategy.py b/deeptutor/agents/research/mode_strategy.pyindex 767b81026..e9993d7ab 100644--- a/deeptutor/agents/research/mode_strategy.py+++ b/deeptutor/agents/research/mode_strategy.py@@ -99,7 +99,7 @@ STRATEGIES: dict[ResearchMode, ModeStrategy] = {"notes": ModeStrategy(name="notes",style="study_notes",- rephrase_enabled=False,+ rephrase_enabled=True,decompose_mode="manual",single_pass_threshold=99,min_section_length=260,@@ -107,7 +107,7 @@ STRATEGIES: dict[ResearchMode, ModeStrategy] = {"report": ModeStrategy(name="report",style="report",- rephrase_enabled=False,+ rephrase_enabled=True,decompose_mode="auto",single_pass_threshold=2,min_section_length=650,diff --git a/deeptutor/agents/research/pipeline.py b/deeptutor/agents/research/pipeline.pynew file mode 100644index 000000000..0e2dfd211--- /dev/null+++ b/deeptutor/agents/research/pipeline.py@@ -0,0 +1,2870 @@+"""ResearchPipeline — agentic-engine-based replacement for the legacy+multi-agent ``ResearchPipeline``.++Phase shape:++* **Phase 1 (Rephrase)** — a mini agentic loop over ``THINK`` / ``TOOL``+ / ``FINISH`` whose only available tool is ``ask_user``. Up to 3+ ask_user rounds (each with 1-3 questions on one card). FINISH text+ is the refined research topic. May FINISH early when the user is+ unambiguous.+* **Phase 2 (Decompose)** — one ``OUTLINE`` labeled step turning the+ refined topic into N sub-topics. When ``confirmed_outline=None``+ ResearchPipeline returns the outline and exits so the capability can+ surface it as a preview; the same pipeline is invoked again with+ ``confirmed_outline`` once the user confirms.+* **Phase 3 (Research blocks)** — for each ``TopicBlock`` in the+ dynamic queue, one ``run_agentic_loop`` over ``THINK`` / ``TOOL`` /+ ``APPEND`` / ``FINISH``. ``APPEND`` is an intermediate label that+ mutates the queue (via ``_BlockLoopHost.on_intermediate``). The outer+ scheduler drains the queue in series or parallel; APPEND-added+ blocks naturally get picked up by subsequent batches.+* **Phase 4 (Reporting)** — sequence of one-shot labeled steps:+ ``OUTLINE`` (report structure) → ``INTRO`` → for each section+ ``SECTION`` → ``CONCLUSION`` → assemble. Each emits its own trace+ card and pulls evidence from :class:`CitationManager` for anchor+ injection.++Citations and the dynamic topic queue — the two features that make+deep research distinct — are preserved.+"""++from __future__ import annotations++import asyncio+import html+import logging+import re+from collections.abc import Awaitable, Callable+from dataclasses import dataclass, field+from typing import Any++from deeptutor.agents.research.data_structures import (+ DynamicTopicQueue,+ TopicBlock,+ TopicStatus,+ ToolTrace,+)+from deeptutor.agents.research.utils.citation_manager import CitationManager+from deeptutor.capabilities._shared import emit_capability_result+from deeptutor.core.agentic import (+ DispatchOutcome,+ LLMClientConfig,+ LabeledStepResult,+ LabelProtocol,+ LoopOutcome,+ UsageTracker,+ build_completion_kwargs,+ build_openai_client,+ can_use_native_tool_calling,+ classify_label,+ dispatch_tool_calls,+ run_agentic_loop,+ run_labeled_step,+)+from deeptutor.core.agentic.tool_dispatch import (+ MAX_PARALLEL_TOOL_CALLS,+ execute_tool_call,+)+from deeptutor.core.context import Attachment, UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import (+ build_trace_metadata,+ derive_trace_metadata,+ merge_trace_metadata,+ new_call_id,+)+from deeptutor.agents._shared.tool_composition import (+ ToolMountFlags,+ compose_enabled_tools,+ default_optional_tools,+ user_has_memory,+ user_has_notebooks,+)+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.config import parse_language+from deeptutor.services.llm import get_llm_config, prepare_multimodal_messages+from deeptutor.services.path_service import get_path_service+from deeptutor.services.prompt import get_prompt_manager+from deeptutor.services.prompt.language import append_language_directive+from deeptutor.utils.json_parser import parse_json_response++logger = logging.getLogger(__name__)+++SOURCE = "deep_research"++# Per-block research uses the same shared composition policy as chat+# (``compose_enabled_tools``), then narrows the result to tools that can+# produce evidence for a block-level research summary.+RESEARCH_OPTIONAL_TOOLS: list[str] = default_optional_tools()+RESEARCH_BLOCK_TOOL_ALLOWLIST: frozenset[str] = frozenset(+ {"rag", "web_search", "paper_search", "code_execution"}+)++# ---------------------------------------------------------------------------+# Label vocabulary+# ---------------------------------------------------------------------------+LABEL_THINK = "THINK"+LABEL_TOOL = "TOOL"+LABEL_APPEND = "APPEND"+LABEL_FINISH = "FINISH"+LABEL_OUTLINE = "OUTLINE"+LABEL_INTRO = "INTRO"+LABEL_SECTION = "SECTION"+LABEL_CONCLUSION = "CONCLUSION"++# Rephrase loop: agent talks to the user through ``ask_user`` and then+# FINISHes with a refined topic statement.+_PROTOCOL_REPHRASE = LabelProtocol(+ allowed=(LABEL_THINK, LABEL_TOOL, LABEL_FINISH),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset({LABEL_THINK}),+ final=frozenset({LABEL_FINISH}),+ tool_label=LABEL_TOOL,+)++# Decompose: one-shot ``OUTLINE`` payload (JSON list of sub-topics).+_PROTOCOL_DECOMPOSE = LabelProtocol(+ allowed=(LABEL_OUTLINE,),+ terminal=frozenset({LABEL_OUTLINE}),+ intermediate=frozenset(),+ final=frozenset({LABEL_OUTLINE}),+ tool_label=None,+)++# Per-block research: the headline agentic loop. ``APPEND`` is the+# intermediate label that extends the dynamic queue (handled by the+# host's ``on_intermediate`` hook).+_PROTOCOL_BLOCK = LabelProtocol(+ allowed=(LABEL_THINK, LABEL_TOOL, LABEL_APPEND, LABEL_FINISH),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset({LABEL_THINK, LABEL_APPEND}),+ final=frozenset({LABEL_FINISH}),+ tool_label=LABEL_TOOL,+)++# Reporting sub-phases — each is one labeled step with one terminal+# label. Distinct names so the LLM and the trace UI both recognise+# which phase the call belongs to.+_PROTOCOL_REPORT_OUTLINE = LabelProtocol(+ allowed=(LABEL_OUTLINE,),+ terminal=frozenset({LABEL_OUTLINE}),+ intermediate=frozenset(),+ final=frozenset({LABEL_OUTLINE}),+ tool_label=None,+)+_PROTOCOL_REPORT_INTRO = LabelProtocol(+ allowed=(LABEL_INTRO,),+ terminal=frozenset({LABEL_INTRO}),+ intermediate=frozenset(),+ final=frozenset({LABEL_INTRO}),+ tool_label=None,+)+_PROTOCOL_REPORT_SECTION = LabelProtocol(+ allowed=(LABEL_SECTION,),+ terminal=frozenset({LABEL_SECTION}),+ intermediate=frozenset(),+ final=frozenset({LABEL_SECTION}),+ tool_label=None,+)+_PROTOCOL_REPORT_CONCLUSION = LabelProtocol(+ allowed=(LABEL_CONCLUSION,),+ terminal=frozenset({LABEL_CONCLUSION}),+ intermediate=frozenset(),+ final=frozenset({LABEL_CONCLUSION}),+ tool_label=None,+)+_PROTOCOL_ANSWER_NOW = LabelProtocol(+ allowed=(LABEL_FINISH,),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset(),+ final=frozenset({LABEL_FINISH}),+ tool_label=None,+)++# Note Agent — single ``FINISH`` labeled step that compresses a raw tool+# result into a short dense summary for the citation sidecar.+_PROTOCOL_NOTE = LabelProtocol(+ allowed=(LABEL_FINISH,),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset(),+ final=frozenset({LABEL_FINISH}),+ tool_label=None,+)++# Tools whose results get summarised + recorded in the citation manager.+# Any tool whose results carry source documents / external evidence+# should be added here.+CITABLE_TOOLS: frozenset[str] = frozenset(+ {"rag", "web_search", "paper_search", "code_execution"}+)++# Token budget for the note summarization sidecar.+DEFAULT_NOTE_MAX_TOKENS = 1500+# How much of the raw tool output we feed into the note summarizer.+NOTE_RAW_INPUT_TRUNCATE_CHARS = 8000++# ---------------------------------------------------------------------------+# Defaults — preserved from the legacy presets so refactor is config-stable.+# ---------------------------------------------------------------------------+DEFAULT_REPHRASE_MAX_ITERATIONS = 8 # Inner loop iter cap; ask_user round cap is enforced separately.+DEFAULT_REPHRASE_MAX_ROUNDS = 3+DEFAULT_REPHRASE_MAX_QUESTIONS_PER_ROUND = 3+DEFAULT_BLOCK_MAX_ITERATIONS = 5+DEFAULT_BLOCK_MAX_TOKENS = 6000+DEFAULT_OUTLINE_MAX_TOKENS = 2000+DEFAULT_REPORT_OUTLINE_MAX_TOKENS = 2000+DEFAULT_REPORT_INTRO_MAX_TOKENS = 3000+DEFAULT_REPORT_SECTION_MAX_TOKENS = 6000+DEFAULT_REPORT_CONCLUSION_MAX_TOKENS = 3000+DEFAULT_INITIAL_SUBTOPICS = 5+DEFAULT_MAX_PARALLEL_TOPICS = 3+DEFAULT_QUEUE_MAX_LENGTH = 8+++# ---------------------------------------------------------------------------+# Data shapes+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class SubTopicItem:+ """One entry in the decompose / outline preview output."""++ title: str+ overview: str = ""+++@dataclass+class ResearchedBlock:+ """A finished topic block ready for reporting."""++ block: TopicBlock+ knowledge: str # accumulated FINISH text from the block's agentic loop+++@dataclass(frozen=True)+class ReportSectionPlan:+ """Per-section instruction in the report outline."""++ id: str+ title: str+ intent: str # what this section should cover+ block_ids: tuple[str, ...] # which TopicBlocks supply evidence+++@dataclass(frozen=True)+class ReportOutline:+ title: str+ sections: tuple[ReportSectionPlan, ...]+++# ---------------------------------------------------------------------------+# ResearchPipeline+# ---------------------------------------------------------------------------+++class ResearchPipeline:+ """One-shot orchestrator: instantiate per turn, call :meth:`run` once.++ The pipeline owns control flow and per-phase prompt assembly; every+ LLM call goes through :mod:`deeptutor.core.agentic` primitives. The+ legacy ``DynamicTopicQueue`` + :class:`CitationManager` are reused+ verbatim as the in-flight scratchpad and citation registry.+ """++ def __init__(+ self,+ *,+ language: str = "en",+ runtime_config: dict[str, Any] | None = None,+ kb_name: str | None = None,+ enabled_tools: list[str] | None = None,+ ) -> None:+ self.language = parse_language(language)+ self.kb_name = (kb_name or "").strip() or None+ self.enabled_tools = list(enabled_tools or [])+ self.runtime_config: dict[str, Any] = dict(runtime_config or {})++ # Read structured policy sub-dicts produced by+ # :func:`build_research_runtime_config`. All keys are best-effort —+ # missing values fall back to module-level defaults so the pipeline+ # also runs against a minimal direct-instantiation in unit tests.+ researching = (+ self.runtime_config.get("researching")+ if isinstance(self.runtime_config.get("researching"), dict)+ else {}+ )+ planning = (+ self.runtime_config.get("planning")+ if isinstance(self.runtime_config.get("planning"), dict)+ else {}+ )+ reporting = (+ self.runtime_config.get("reporting")+ if isinstance(self.runtime_config.get("reporting"), dict)+ else {}+ )+ queue_cfg = (+ self.runtime_config.get("queue")+ if isinstance(self.runtime_config.get("queue"), dict)+ else {}+ )++ self.rephrase_max_iterations = _read_int(+ planning.get("rephrase"),+ key="max_iterations",+ default=DEFAULT_REPHRASE_MAX_ITERATIONS,+ )+ self.rephrase_max_rounds = DEFAULT_REPHRASE_MAX_ROUNDS+ self.rephrase_max_questions_per_round = DEFAULT_REPHRASE_MAX_QUESTIONS_PER_ROUND+ self.rephrase_enabled = bool(+ planning.get("rephrase", {}).get("enabled", True)+ if isinstance(planning.get("rephrase"), dict)+ else True+ )+ self.initial_subtopics = _read_int(+ planning.get("decompose"),+ key="initial_subtopics",+ default=DEFAULT_INITIAL_SUBTOPICS,+ )++ self.block_max_iterations = _read_int(+ researching,+ key="max_iterations",+ default=DEFAULT_BLOCK_MAX_ITERATIONS,+ )+ self.max_parallel_topics = max(+ 1,+ _read_int(+ researching,+ key="max_parallel_topics",+ default=DEFAULT_MAX_PARALLEL_TOPICS,+ ),+ )+ self.execution_mode = str(researching.get("execution_mode", "parallel"))+ self.research_mode = str(reporting.get("mode", "report"))++ self.queue_max_length = _read_int(+ queue_cfg, key="max_length", default=DEFAULT_QUEUE_MAX_LENGTH+ )++ # Block-loop tool composition runs through the same shared policy+ # chat uses (``compose_enabled_tools``) — see :meth:`_block_tool_names`.+ # There is no per-source enable_* gating here: the per-block loop+ # sees exactly the user-toggled tools plus auto-mounts (``rag``+ # when a KB is attached). Citations, ``ask_user`` is excluded by+ # the block prompt itself.++ # LLM client setup mirrors solve's pattern so the same engine+ # primitives behave identically across capabilities.+ self.llm_config = get_llm_config()+ self.binding = getattr(self.llm_config, "binding", None) or "openai"+ self.model = getattr(self.llm_config, "model", None)+ self.api_key = getattr(self.llm_config, "api_key", None)+ self.base_url = getattr(self.llm_config, "base_url", None)+ self.api_version = getattr(self.llm_config, "api_version", None)+ self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}+ self.client_config = LLMClientConfig(+ binding=self.binding,+ model=self.model,+ api_key=self.api_key,+ base_url=self.base_url,+ api_version=self.api_version,+ extra_headers=self.extra_headers or None,+ )++ self.registry = get_tool_registry()+ self.usage = UsageTracker(model=self.model)++ # Default sampling temperature — slightly higher than solve so+ # the research loop can take initiative on APPEND decisions.+ self._temperature = 0.3++ try:+ self._prompts: dict[str, Any] = (+ get_prompt_manager().load_prompts(+ module_name="research",+ agent_name="pipeline",+ language=self.language,+ )+ or {}+ )+ except Exception as exc:+ logger.warning("Failed to load research pipeline prompts: %s", exc)+ self._prompts = {}++ # ------------------------------------------------------------------+ # Public entry points+ # ------------------------------------------------------------------+ async def run(+ self,+ *,+ context: UnifiedContext,+ topic: str,+ confirmed_outline: list[SubTopicItem] | None = None,+ attachments: list[Attachment] | None = None,+ stream: StreamBus,+ ) -> dict[str, Any]:+ """Drive the four phases.++ When ``confirmed_outline`` is ``None`` and rephrase + decompose+ complete, the pipeline emits an ``outline_preview`` result and+ returns so the capability can surface the outline for the user+ to edit / confirm. A subsequent call with ``confirmed_outline``+ skips Phase 1+2 (the user already saw the questions and approved+ a structure) and runs Phase 3+4 directly.+ """+ attachments = list(attachments or [])+ image_attachments = [+ a for a in attachments if getattr(a, "type", "") == "image"+ ]+ client = self._build_client()++ try:+ return await self._run_inner(+ context=context,+ topic=topic,+ image_attachments=image_attachments,+ confirmed_outline=confirmed_outline,+ stream=stream,+ client=client,+ )+ except Exception as exc:+ logger.exception("ResearchPipeline.run failed: %s", exc)+ await self._emit_visible_failure(stream, exc)+ raise++ async def _run_inner(+ self,+ *,+ context: UnifiedContext,+ topic: str,+ image_attachments: list[Attachment],+ confirmed_outline: list[SubTopicItem] | None,+ stream: StreamBus,+ client: Any,+ ) -> dict[str, Any]:+ logger.info(+ "ResearchPipeline.run start: lang=%s kb=%s requested_tools=%s "+ "max_iter/block=%d max_parallel=%d",+ self.language,+ self.kb_name,+ self.enabled_tools,+ self.block_max_iterations,+ self.max_parallel_topics,+ )++ # ----- Phase 1 + Phase 2 (planning) — skipped when an outline is+ # already confirmed so the user isn't asked clarifying questions a+ # second time on the same logical research task.+ if confirmed_outline is None:+ async with stream.stage("rephrasing", source=SOURCE):+ refined_topic = (+ await self._rephrase(+ topic=topic,+ context=context,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )+ if self.rephrase_enabled+ else topic.strip()+ )++ async with stream.stage(+ "decomposing",+ source=SOURCE,+ metadata={"research_status_key": "decompose_target"},+ ):+ outline = await self._decompose(+ topic=refined_topic,+ context=context,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )++ # Flat top-level keys: ``stream.result(data)`` merges ``data``+ # into the event's ``metadata`` field, and the frontend reads+ # ``event.metadata.outline_preview`` (not ``…metadata.metadata.…``).+ #+ # No ``stream.result`` here — the capability emits a single+ # result event after augmenting this payload with+ # ``research_config`` (which the frontend needs to send back+ # on confirm). Emitting here too would land first and the+ # frontend's ``find(type="result")`` would pick this one,+ # leaving ``research_config`` undefined.+ preview_payload: dict[str, Any] = {+ "response": "",+ "output_dir": "",+ "outline_preview": True,+ "topic": refined_topic,+ "sub_topics": [+ {"title": st.title, "overview": st.overview} for st in outline+ ],+ }+ return preview_payload++ # ----- Phase 3 (research blocks) -----+ refined_topic = topic.strip()+ queue = DynamicTopicQueue(+ f"research_{context.session_id or 'adhoc'}",+ max_length=self.queue_max_length,+ )+ citations = CitationManager(queue.research_id, cache_dir=None)+ for sub in confirmed_outline:+ queue.add_block(sub.title, sub.overview)++ async with stream.stage("researching", source=SOURCE):+ researched = await self._drive_queue(+ queue=queue,+ citations=citations,+ topic=refined_topic,+ context=context,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )++ # ----- Phase 4 (iterative reporting) -----+ async with stream.stage(+ "reporting",+ source=SOURCE,+ metadata={+ "research_status_key": "report_outline",+ "report_part": "outline",+ },+ ):+ report_text = await self._write_report(+ topic=refined_topic,+ blocks=researched,+ citations=citations,+ stream=stream,+ client=client,+ )++ result_payload: dict[str, Any] = {+ "response": report_text,+ "output_dir": "",+ "metadata": {+ "mode": "agentic_research",+ "topic": refined_topic,+ "block_count": len(researched),+ "citation_count": len(citations.get_all_citations()),+ },+ }+ await emit_capability_result(+ stream, result_payload, source=SOURCE, usage=self.usage+ )+ return result_payload++ async def _emit_visible_failure(self, stream: StreamBus, exc: BaseException) -> None:+ """Surface a runtime exception as a labelled error trace card so the+ user sees what went wrong instead of an empty assistant message."""+ call_id = new_call_id("research-failure")+ meta = build_trace_metadata(+ call_id=call_id,+ phase="researching",+ label=self._t("labels.research_step", default="Research step"),+ call_kind="llm_final_response",+ trace_id=call_id,+ trace_role="response",+ trace_group="stage",+ )+ message = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__+ await stream.error(+ message,+ source=SOURCE,+ stage="researching",+ metadata=merge_trace_metadata(meta, {"trace_kind": "error"}),+ )+ prefix = self._t("system.warning_prefix", default="⚠ ")+ await stream.content(+ f"{prefix}{message}",+ source=SOURCE,+ stage="researching",+ metadata=merge_trace_metadata(meta, {"trace_kind": "llm_output"}),+ )++ # ------------------------------------------------------------------+ # Phase 1: rephrase+ # ------------------------------------------------------------------+ async def _rephrase(+ self,+ *,+ topic: str,+ context: UnifiedContext,+ image_attachments: list[Attachment] | None = None,+ stream: StreamBus,+ client: Any,+ ) -> str:+ """Mini agentic loop over ``THINK / TOOL / FINISH`` with only+ ``ask_user`` exposed.++ The host (``_RephraseLoopHost``) enforces the round cap, rejects+ any non-``ask_user`` tool call inline, and routes pause/resume+ through the runtime-supplied ``wait_for_user_reply``. When the+ LLM emits ``FINISH`` the post-label text is the refined topic.+ If the loop exits without a valid FINISH (e.g. ``ask_user`` is+ not available, or the LLM bails early) the original topic is+ returned unchanged so the rest of the pipeline can proceed.+ """+ if not self._tool_in_registry("ask_user"):+ return topic.strip()++ system_prompt = self._t(+ "rephrase.system",+ max_rounds=self.rephrase_max_rounds,+ max_questions_per_round=self.rephrase_max_questions_per_round,+ topic=topic,+ )+ user_prompt = self._t("rephrase.user_template", topic=topic)+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )++ tool_names = ["ask_user"]+ tool_schemas = (+ self.registry.build_openai_schemas(tool_names)+ if can_use_native_tool_calling(binding=self.binding, model=self.model)+ else None+ )++ host = _RephraseLoopHost(+ pipeline=self,+ stream=stream,+ context=context,+ client=client,+ max_rounds=self.rephrase_max_rounds,+ )+ try:+ outcome = await run_agentic_loop(+ initial_messages=messages,+ protocol=_PROTOCOL_REPHRASE,+ client=client,+ model=self.model,+ completion_kwargs=self._completion_kwargs(DEFAULT_BLOCK_MAX_TOKENS),+ binding=self.binding,+ tool_schemas=tool_schemas,+ stream=stream,+ source=SOURCE,+ stage="rephrasing",+ max_iterations=self.rephrase_max_iterations,+ host=host,+ usage=self.usage,+ # FINISH text is the model's brief user-facing confirmation+ # of what it's about to research — stream it live to the+ # chat bubble body so the user sees the summary forming+ # before the outline editor appears. It also doubles as+ # the refined topic input for the decompose phase.+ stream_body_live=True,+ # Lazy sub-trace open so the FINISH iteration (which+ # streams to the chat body, not into a reasoning card)+ # doesn't leave a near-empty "Reasoning" card behind.+ # THINK iters still get a card the moment their first+ # thinking chunk arrives.+ eager_sub_trace=False,+ )+ except Exception as exc:+ logger.warning("Rephrase loop failed; falling back to raw topic: %s", exc)+ return topic.strip()++ refined = (outcome.final_text or "").strip()+ return refined or topic.strip()++ # ------------------------------------------------------------------+ # Phase 2: decompose+ # ------------------------------------------------------------------+ async def _decompose(+ self,+ *,+ topic: str,+ context: UnifiedContext,+ image_attachments: list[Attachment] | None = None,+ stream: StreamBus,+ client: Any,+ ) -> list[SubTopicItem]:+ """One-shot ``OUTLINE`` labeled step.++ The LLM is asked to emit a JSON array of ``{title, overview}``+ objects (any object with a ``title`` field is accepted). Parsing+ is lenient — if JSON parse fails, the topic itself becomes the+ single fallback sub-topic so the pipeline can still drive the+ outline-preview UX.+ """+ system_prompt = self._t("decompose.system")+ user_prompt = self._t(+ "decompose.user_template",+ topic=topic,+ num_subtopics=self.initial_subtopics,+ )+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )+ iter_meta = self._build_simple_trace_meta(+ call_id_root="research-decompose",+ label=self._t("labels.decompose", default="Decompose"),+ stage="decomposing",+ call_kind="llm_planning",+ trace_role="plan",+ trace_group="plan",+ research_status_key="decompose_target",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_DECOMPOSE,+ stream=stream,+ stage="decomposing",+ iter_meta=iter_meta,+ max_tokens=DEFAULT_OUTLINE_MAX_TOKENS,+ eager_sub_trace=False,+ )+ return self._parse_outline(topic, step.text)++ def _parse_outline(self, topic: str, raw: str) -> list[SubTopicItem]:+ data = parse_json_response(raw, logger_instance=logger, fallback={})+ if isinstance(data, list):+ iterable: list[Any] = data+ elif isinstance(data, dict):+ iterable = list(data.get("sub_topics") or data.get("subtopics") or [])+ else:+ iterable = []++ items: list[SubTopicItem] = []+ for entry in iterable:+ if isinstance(entry, dict):+ title = str(entry.get("title") or entry.get("topic") or "").strip()+ overview = str(entry.get("overview") or entry.get("description") or "").strip()+ elif isinstance(entry, str):+ title = entry.strip()+ overview = ""+ else:+ continue+ if title:+ items.append(SubTopicItem(title=title, overview=overview))+ if len(items) >= self.initial_subtopics:+ break+ if not items:+ items = [SubTopicItem(title=topic, overview="")]+ return items++ # ------------------------------------------------------------------+ # Phase 3: research one block+ # ------------------------------------------------------------------+ async def _research_block(+ self,+ *,+ block: TopicBlock,+ queue: DynamicTopicQueue,+ citations: CitationManager,+ topic: str,+ context: UnifiedContext,+ stream: StreamBus,+ client: Any,+ ) -> ResearchedBlock:+ """Run one block of the dynamic research queue through an agentic+ loop with the ``THINK`` / ``TOOL`` / ``APPEND`` / ``FINISH``+ protocol. ``FINISH``'s post-label text becomes the block's+ consolidated knowledge for the report layer; ``APPEND`` triggers+ a queue mutation via :meth:`_BlockLoopHost.on_intermediate`.+ """+ queue.mark_researching(block.block_id)++ block_tool_names = self._block_tool_names()+ native_block_tools = self._use_native_block_tools(block_tool_names)+ prompt_tool_names = block_tool_names if native_block_tools else []+ effective_max_iterations = (+ max(self.block_max_iterations, 4)+ if prompt_tool_names+ else self.block_max_iterations+ )+ tool_schemas = (+ self._build_block_tool_schemas(prompt_tool_names)+ if native_block_tools+ else None+ )+ tool_list = self.registry.build_prompt_text(+ prompt_tool_names,+ format="list_with_usage",+ language=self.language,+ ) or self._fallback_empty_tool_list()+ kb_note = self._kb_system_note()++ system_prompt = self._t(+ "research_step.system",+ topic=topic,+ block_title=block.sub_topic,+ block_overview=block.overview or "(no overview)",+ mode=self.research_mode,+ max_iterations=effective_max_iterations,+ kb_note=kb_note,+ tool_list=tool_list,+ )+ system_prompt = append_language_directive(system_prompt, self.language)++ sibling_topics = self._render_sibling_topics(queue, block)+ user_prompt = self._t(+ "research_step.user_template",+ accumulated_knowledge=self._t(+ "empty.no_evidence", default="(no evidence collected yet)"+ ),+ sibling_topics=sibling_topics,+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)++ host = _BlockLoopHost(+ pipeline=self,+ block=block,+ queue=queue,+ citations=citations,+ topic=topic,+ stream=stream,+ context=context,+ client=client,+ )+ try:+ outcome = await run_agentic_loop(+ initial_messages=messages,+ protocol=_PROTOCOL_BLOCK,+ client=client,+ model=self.model,+ completion_kwargs=self._completion_kwargs(DEFAULT_BLOCK_MAX_TOKENS),+ binding=self.binding,+ tool_schemas=tool_schemas,+ stream=stream,+ source=SOURCE,+ stage="researching",+ max_iterations=effective_max_iterations,+ host=host,+ usage=self.usage,+ stream_body_live=False,+ eager_sub_trace=True,+ # Reasoning models may emit a native ``<think>...</think>``+ # planning pass without the requested ``THINK`` label. Treat+ # that as a real THINK iteration so the next round can perform+ # the tool call instead of burning the budget on label repair.+ implicit_think_label=LABEL_THINK,+ )+ except Exception as exc:+ logger.exception(+ "Research block %s failed: %s", block.block_id, exc+ )+ queue.mark_failed(block.block_id)+ return ResearchedBlock(block=block, knowledge="")++ knowledge = (outcome.final_text or "").strip()+ if outcome.completed:+ queue.mark_completed(block.block_id)+ else:+ queue.mark_failed(block.block_id)+ block.iteration_count = outcome.iterations+ return ResearchedBlock(block=block, knowledge=knowledge)++ async def _force_finish_block(+ self,+ *,+ client: Any,+ messages: list[dict[str, Any]],+ stream: StreamBus,+ start_iteration: int,+ block: TopicBlock,+ ) -> tuple[str, bool, int]:+ """Per-block ``LoopHost.force_finalize`` recovery: prompt the model+ to emit a final ``FINISH`` consolidating what was learned so far,+ with a small retry budget for protocol-repair attempts."""+ calls = 0+ messages.append({"role": "user", "content": self._t("protocol.force_finish")})+ await stream.progress(+ self._t("notices.max_iterations_reached", default="Max iterations reached."),+ source=SOURCE,+ stage="researching",+ metadata={"trace_kind": "warning"},+ )+ for attempt in range(3):+ iter_meta = self._build_simple_trace_meta(+ call_id_root=f"research-{block.block_id}-force-{start_iteration + attempt}",+ label=self._t("labels.reasoning", default="Reasoning"),+ stage="researching",+ block_id=block.block_id,+ **_research_topic_status_meta(block),+ )+ result = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=LabelProtocol(+ allowed=(LABEL_FINISH,),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset(),+ final=frozenset({LABEL_FINISH}),+ tool_label=None,+ ),+ stream=stream,+ stage="researching",+ iter_meta=iter_meta,+ )+ calls += 1+ if result.label == LABEL_FINISH and result.text.strip():+ return result.text, True, calls+ messages.append({"role": "assistant", "content": result.text[:500]})+ messages.append(+ {"role": "user", "content": self._t("protocol.force_finish_repair")}+ )+ return self._t("protocol.fallback_final"), False, calls++ # ------------------------------------------------------------------+ # Per-block rendering helpers+ # ------------------------------------------------------------------+ def _render_sibling_topics(+ self, queue: DynamicTopicQueue, current_block: TopicBlock+ ) -> str:+ """Compact list of other topics in the queue so APPEND can dedup+ against them at prompt-time (in addition to the runtime check)."""+ siblings = [+ f" - [{b.block_id}] {b.sub_topic}"+ for b in queue.blocks+ if b.block_id != current_block.block_id+ ]+ if not siblings:+ return self._t("empty.no_subtopics", default="(none)")+ return "\n".join(siblings)++ def _kb_system_note(self) -> str:+ if not self.kb_name:+ return ""+ return self._t(+ "system.kb_system_note",+ default=(+ f"Attached knowledge bases: {self.kb_name}. When calling rag, "+ f"kb_name must be {self.kb_name!r}."+ ),+ kb_name=self.kb_name,+ kb_name_repr=repr(self.kb_name),+ )++ def _fallback_empty_tool_list(self) -> str:+ return self._t("empty.no_tools", default="- none")++ # ------------------------------------------------------------------+ # Phase 4: reporting+ # ------------------------------------------------------------------+ # ------------------------------------------------------------------+ # Queue scheduler — drains the dynamic topic queue. Series vs.+ # parallel selected from ``researching.execution_mode``.+ # ------------------------------------------------------------------+ async def _drive_queue(+ self,+ *,+ queue: DynamicTopicQueue,+ citations: CitationManager,+ topic: str,+ context: UnifiedContext,+ image_attachments: list[Attachment] | None,+ stream: StreamBus,+ client: Any,+ ) -> list[ResearchedBlock]:+ researched_by_id: dict[str, ResearchedBlock] = {}+ rounds = 0+ safety_cap = max(20, (self.queue_max_length or 0) * 4)++ while True:+ pending = queue.get_all_pending_blocks()+ if not pending:+ break+ batch_size = (+ 1+ if str(self.execution_mode).lower() == "series"+ else self.max_parallel_topics+ )+ batch = pending[:batch_size]+ results = await asyncio.gather(+ *[+ self._research_block(+ block=block,+ queue=queue,+ citations=citations,+ topic=topic,+ context=context,+ stream=stream,+ client=client,+ )+ for block in batch+ ],+ return_exceptions=True,+ )+ for block, result in zip(batch, results, strict=True):+ if isinstance(result, BaseException):+ logger.exception(+ "Block %s research failed: %s", block.block_id, result+ )+ if block.status == TopicStatus.RESEARCHING:+ queue.mark_failed(block.block_id)+ researched_by_id[block.block_id] = ResearchedBlock(+ block=block, knowledge=""+ )+ continue+ researched_by_id[block.block_id] = result++ rounds += 1+ if rounds > safety_cap:+ logger.warning(+ "Research scheduler aborted after %d rounds — queue size %d",+ rounds,+ len(queue.blocks),+ )+ break++ # Preserve queue order so parents come before APPENDed children.+ ordered: list[ResearchedBlock] = []+ for block in queue.blocks:+ ordered.append(+ researched_by_id.get(block.block_id)+ or ResearchedBlock(block=block, knowledge="")+ )+ return ordered++ # ------------------------------------------------------------------+ # Note-agent sidecar — summarise + record citation for one tool call.+ # ------------------------------------------------------------------+ async def _summarise_tool_result(+ self,+ *,+ tool_name: str,+ query: str,+ raw_answer: str,+ client: Any,+ ) -> str:+ """One LLM call per citable tool result: condense long retrievals+ into a short, citation-ready summary. Failures fall back to a+ leading slice of the raw answer so the loop never stalls on a+ flaky summariser call.+ """+ cleaned = (raw_answer or "").strip()+ if not cleaned:+ return ""+ system_prompt = self._t("note.system")+ user_prompt = self._t(+ "note.user_template",+ tool_name=tool_name,+ query=query,+ raw_answer=cleaned[:NOTE_RAW_INPUT_TRUNCATE_CHARS],+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ try:+ kwargs = self._completion_kwargs(DEFAULT_NOTE_MAX_TOKENS)+ response = await client.chat.completions.create(+ model=self.model, messages=messages, stream=False, **kwargs+ )+ content = (+ response.choices[0].message.content if response.choices else ""+ ) or ""+ parsed = classify_label(+ content,+ allowed_labels=(LABEL_FINISH,),+ final=True,+ )+ if parsed is not None:+ _label, content = parsed+ return content.strip() or cleaned[:600]+ except Exception as exc:+ logger.warning("Note summarisation failed (%s): %s", tool_name, exc)+ return cleaned[:600]++ # ------------------------------------------------------------------+ # Phase 4: iterative reporting+ #+ # Each sub-phase is one labeled step:+ # _gen_report_outline → _write_intro → for sec: _write_section →+ # _write_conclusion. Bodies stream live (``stream_body_live``)+ # chunk-by-chunk for the section-level steps so the user sees the+ # report assemble in real time.+ # ------------------------------------------------------------------+ async def _write_report(+ self,+ *,+ topic: str,+ blocks: list[ResearchedBlock],+ citations: CitationManager,+ stream: StreamBus,+ client: Any,+ ) -> str:+ outline = await self._gen_report_outline(+ topic=topic, blocks=blocks, citations=citations,+ stream=stream, client=client,+ )++ # Global numbering: introduction is 1, sub-topic sections are 2..N+1,+ # conclusion is N+2 (where N == len(outline.sections)). Both the+ # rendered ``##`` heading and any ``### N.x`` subsection prefixes the+ # LLM emits reference these numbers, so we resolve them here and pass+ # them into every report-writing step.+ section_count = len(outline.sections)+ conclusion_number = section_count + 2++ section_texts: list[str] = []++ # Emit the report's H1 title before the introduction so the rendered+ # markdown opens with the report name, then the numbered ``## 1.``+ # Introduction heading. The LLM is not asked to write the title — we+ # already have it on the outline.+ title_block = self._render_report_title_block(outline.title)+ if title_block:+ await stream.content(+ title_block,+ source=SOURCE,+ stage="reporting",+ metadata={"trace_kind": "report_title"},+ )+ section_texts.append(title_block)++ intro = await self._write_intro(+ topic=topic, outline=outline, stream=stream, client=client+ )+ if intro:+ if section_texts:+ await self._stream_report_separator(stream)+ section_texts.append(intro)++ section_bodies: list[str] = []+ for section_index, section in enumerate(outline.sections, start=1):+ if section_texts:+ await self._stream_report_separator(stream)+ body = await self._write_section(+ section=section,+ section_index=section_index,+ section_count=section_count,+ section_number=section_index + 1,+ topic=topic,+ outline=outline,+ blocks=blocks,+ citations=citations,+ stream=stream,+ client=client,+ )+ if body:+ section_texts.append(body)+ section_bodies.append(body)++ if section_texts:+ await self._stream_report_separator(stream)+ conclusion = await self._write_conclusion(+ topic=topic,+ outline=outline,+ section_bodies=section_bodies,+ section_number=conclusion_number,+ stream=stream,+ client=client,+ )+ if conclusion:+ section_texts.append(conclusion)++ body = self._normalise_report_markdown(+ "\n\n".join(part for part in section_texts if part.strip()),+ citations,+ )+ used_citation_ids = _citation_ids_in_first_appearance(body, citations)+ citation_numbers = {+ citation_id: index+ for index, citation_id in enumerate(used_citation_ids, start=1)+ }+ body = self._linkify_report_citations(+ body, citations, citation_numbers=citation_numbers+ )+ references = self._render_reference_list(+ citations,+ citation_ids=used_citation_ids,+ citation_numbers=citation_numbers,+ )+ if references:+ await self._stream_report_separator(stream)+ await stream.content(+ references,+ source=SOURCE,+ stage="reporting",+ metadata={"trace_kind": "reference_list"},+ )+ return "\n\n".join(part for part in (body, references) if part.strip())++ def _render_reference_list(+ self,+ citations: CitationManager,+ *,+ citation_ids: list[str] | None = None,+ citation_numbers: dict[str, int] | None = None,+ ) -> str:+ """Append a collapsible reference appendix with stable anchors.++ Numbering follows first appearance in the final report body. That+ keeps body links and the appendix compact even when research collected+ additional tool traces that did not survive synthesis.+ """+ entries = []+ ordered_ids = citation_ids if citation_ids is not None else _sorted_citation_ids(citations)+ numbers = citation_numbers or {+ citation_id: index for index, citation_id in enumerate(ordered_ids, start=1)+ }+ for citation_id in ordered_ids:+ formatted = self._format_reference_entry(citations, citation_id)+ if formatted:+ anchor = _citation_anchor_id(citation_id)+ ref_number = numbers.get(citation_id, len(entries) + 1)+ entries.append(+ f'<li id="{anchor}" data-citation-id="{html.escape(citation_id)}">'+ f'<span data-ref-number="{ref_number}">{formatted}</span>'+ "</li>"+ )+ if not entries:+ return ""+ heading = self._t("labels.references_heading", default="References")+ return (+ '<details id="references" open>\n'+ f"<summary>{heading}</summary>\n"+ "<ol>\n"+ + "\n".join(entries)+ + "\n</ol>\n"+ "</details>"+ )++ def _linkify_report_citations(+ self,+ text: str,+ citations: CitationManager,+ *,+ citation_numbers: dict[str, int] | None = None,+ ) -> str:+ """Turn generated ``[CIT-...]`` markers into same-page anchor links.++ The section writer is intentionally instructed to copy plain markers,+ because that is easier for models to follow. This renderer pass makes+ the final persisted Markdown navigable without asking the model to+ manufacture link syntax.+ """+ numbers = citation_numbers or _citation_number_map(citations)+ if not text or not numbers:+ return text++ def _replace(match: re.Match[str]) -> str:+ citation_id = match.group("id")+ ref_number = numbers.get(citation_id)+ if ref_number is None:+ return ""+ return _citation_markdown_link(citation_id, ref_number)++ return _REPORT_CITATION_MARKER_RE.sub(_replace, text)++ def _normalise_report_markdown(+ self,+ text: str,+ citations: CitationManager,+ ) -> str:+ """Clean model-authored report markdown before persistence.++ The report writer is instructed to copy raw ``[CIT-...]`` markers,+ but models sometimes pre-link them or repeat heading markers. This+ pass converts pre-linked markers back to canonical form, strips+ unknown citation ids, and normalises duplicate headings like+ ``## ## Title``.+ """+ if not text:+ return ""+ known = set(citations.get_all_citations())++ def _replace_link(match: re.Match[str]) -> str:+ citation_id = match.group("id")+ return f"[{citation_id}]" if citation_id in known else ""++ cleaned = _REPORT_CITATION_LINK_RE.sub(_replace_link, text)++ def _replace_bare(match: re.Match[str]) -> str:+ citation_id = match.group("id")+ return match.group(0) if citation_id in known else ""++ cleaned = _REPORT_CITATION_MARKER_RE.sub(_replace_bare, cleaned)+ return _normalise_markdown_headings(cleaned).strip()++ def _format_reference_entry(+ self,+ citations: CitationManager,+ citation_id: str,+ ) -> str | None:+ """Return a reference-list entry as HTML-safe HTML.++ ``CitationManager.format_citation_for_report`` already produces escaped+ HTML for known tool types; the fallback path below also escapes+ user-controlled fields so the caller can drop the result into the page+ without re-escaping.+ """+ formatted = citations.format_citation_for_report(citation_id)+ if formatted:+ return formatted+ citation = citations.get_citation(citation_id)+ if not citation:+ return None+ tool = str(citation.get("tool_type") or "tool")+ query = str(citation.get("query") or "").strip()+ summary = str(citation.get("summary") or "").strip()+ parts = [html.escape(tool.replace("_", " ").title())]+ if query:+ parts.append(f"query: {html.escape(query)}")+ if summary:+ parts.append(f"note: {html.escape(summary[:180])}")+ return " — ".join(parts)++ async def _stream_report_separator(self, stream: StreamBus) -> None:+ await stream.content("\n\n", source=SOURCE, stage="reporting")++ def _render_report_title_block(self, title: str) -> str:+ """Build the ``# <title>`` H1 block emitted before the introduction.++ Strips any leading ``#`` the model may have left on the outline title+ so the rendered output is always a single H1 line.+ """+ clean = _clean_report_heading_text(title or "").strip()+ if not clean:+ return ""+ return f"# {clean}"++ async def _gen_report_outline(+ self,+ *,+ topic: str,+ blocks: list[ResearchedBlock],+ citations: CitationManager,+ stream: StreamBus,+ client: Any,+ ) -> ReportOutline:+ """One ``OUTLINE`` labeled step that proposes the report sections.++ The model sees the topic + each researched block's title and a+ short knowledge snippet, then emits a JSON ``{title, sections:+ [{id, title, intent, block_ids}]}`` payload mapping each+ section to one or more blocks that supply its evidence.+ """+ block_summaries = []+ for rb in blocks:+ preview = (rb.knowledge or "").strip().split("\n\n")[0][:400]+ block_summaries.append(+ f"- [{rb.block.block_id}] {rb.block.sub_topic}\n {preview}"+ )+ system_prompt = self._t("report.outline.system")+ user_prompt = self._t(+ "report.outline.user_template",+ topic=topic,+ block_summaries="\n".join(block_summaries) or "(no researched blocks)",+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ iter_meta = self._build_simple_trace_meta(+ call_id_root="research-report-outline",+ label=self._t("labels.report_outline", default="Report outline"),+ stage="reporting",+ call_kind="llm_planning",+ trace_role="plan",+ trace_group="plan",+ research_status_key="report_outline",+ report_part="outline",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_REPORT_OUTLINE,+ stream=stream,+ stage="reporting",+ iter_meta=iter_meta,+ max_tokens=DEFAULT_REPORT_OUTLINE_MAX_TOKENS,+ eager_sub_trace=False,+ )+ return self._parse_report_outline(topic, step.text, blocks)++ def _parse_report_outline(+ self, topic: str, raw: str, blocks: list[ResearchedBlock]+ ) -> ReportOutline:+ data = parse_json_response(raw, logger_instance=logger, fallback={})+ valid_ids = {rb.block.block_id for rb in blocks}+ title_to_id = {rb.block.sub_topic.lower(): rb.block.block_id for rb in blocks}++ if isinstance(data, dict):+ title = _clean_report_heading_text(str(data.get("title") or topic)) or topic+ raw_sections = data.get("sections") or []+ elif isinstance(data, list):+ title = _clean_report_heading_text(topic) or topic+ raw_sections = data+ else:+ title = _clean_report_heading_text(topic) or topic+ raw_sections = []++ sections: list[ReportSectionPlan] = []+ for i, item in enumerate(raw_sections if isinstance(raw_sections, list) else []):+ if not isinstance(item, dict):+ continue+ sec_title = _clean_report_heading_text(str(item.get("title") or ""))+ if not sec_title:+ continue+ sec_id = str(item.get("id") or f"R{i + 1}").strip() or f"R{i + 1}"+ intent = str(item.get("intent") or item.get("summary") or "").strip()+ raw_block_ids = item.get("block_ids") or item.get("blocks") or []+ resolved_ids: list[str] = []+ if isinstance(raw_block_ids, list):+ for entry in raw_block_ids:+ if not isinstance(entry, str):+ continue+ if entry in valid_ids:+ resolved_ids.append(entry)+ else:+ bid = title_to_id.get(entry.strip().lower())+ if bid:+ resolved_ids.append(bid)+ sections.append(+ ReportSectionPlan(+ id=sec_id,+ title=sec_title,+ intent=intent,+ block_ids=tuple(resolved_ids),+ )+ )+ if not sections:+ # Fallback: one section per researched block in queue order.+ for rb in blocks:+ sections.append(+ ReportSectionPlan(+ id=rb.block.block_id,+ title=rb.block.sub_topic,+ intent=rb.block.overview or "",+ block_ids=(rb.block.block_id,),+ )+ )+ sections = self._repair_report_section_coverage(sections, blocks)+ return ReportOutline(title=title, sections=tuple(sections))++ def _repair_report_section_coverage(+ self,+ sections: list[ReportSectionPlan],+ blocks: list[ResearchedBlock],+ ) -> list[ReportSectionPlan]:+ """Make report planning robust to partial / invalid block maps.++ The prompt asks the model to map every researched block into at+ least one report section, but outline JSON is still model output.+ This deterministic pass keeps the report from silently dropping a+ block when the LLM omits its id, misspells it, or leaves a section+ with an empty ``block_ids`` list.+ """+ if not sections or not blocks:+ return sections++ valid_ids = {rb.block.block_id for rb in blocks}+ covered: set[str] = set()+ repaired: list[ReportSectionPlan] = []++ for section in sections:+ ids = tuple(+ dict.fromkeys(bid for bid in section.block_ids if bid in valid_ids)+ )+ if not ids:+ best = _best_block_for_section(section, blocks, exclude=covered)+ if best is not None:+ ids = (best.block.block_id,)+ covered.update(ids)+ repaired.append(_section_with_block_ids(section, ids))++ missing = [rb for rb in blocks if rb.block.block_id not in covered]+ if not missing:+ return repaired++ addendum: list[str] = []+ for rb in missing:+ section_index = _best_section_for_block(rb, repaired)+ if section_index is None:+ addendum.append(rb.block.block_id)+ continue+ section = repaired[section_index]+ repaired[section_index] = _section_with_block_ids(+ section,+ tuple(dict.fromkeys((*section.block_ids, rb.block.block_id))),+ )++ if addendum:+ addendum_title = self._t(+ "labels.addendum_title", default="Additional findings"+ )+ addendum_intent = self._t(+ "labels.addendum_intent",+ default=(+ "Covers researched blocks that did not fit cleanly "+ "into the earlier sections."+ ),+ )+ repaired.append(+ ReportSectionPlan(+ id=f"S{len(repaired) + 1}",+ title=addendum_title,+ intent=addendum_intent,+ block_ids=tuple(addendum),+ )+ )+ return repaired++ async def _write_intro(+ self,+ *,+ topic: str,+ outline: ReportOutline,+ stream: StreamBus,+ client: Any,+ ) -> str:+ system_prompt = self._t("report.intro.system", section_number=1)+ user_prompt = self._t(+ "report.intro.user_template",+ topic=topic,+ title=outline.title,+ section_number=1,+ sections_overview="\n".join(+ f"- {s.title}: {s.intent}".rstrip(": ") for s in outline.sections+ ),+ )+ return await self._stream_report_step(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ protocol=_PROTOCOL_REPORT_INTRO,+ stream=stream,+ client=client,+ label=self._t("labels.report_intro", default="Introduction"),+ call_id_root="research-report-intro",+ max_tokens=DEFAULT_REPORT_INTRO_MAX_TOKENS,+ extra_meta={+ "research_status_key": "report_intro",+ "report_part": "intro",+ },+ )++ async def _write_section(+ self,+ *,+ section: ReportSectionPlan,+ section_index: int,+ section_count: int,+ section_number: int,+ topic: str,+ outline: ReportOutline,+ blocks: list[ResearchedBlock],+ citations: CitationManager,+ stream: StreamBus,+ client: Any,+ ) -> str:+ evidence = self._render_section_evidence(+ section=section, blocks=blocks, citations=citations+ )+ system_prompt = self._t(+ "report.section.system", section_number=section_number+ )+ user_prompt = self._t(+ "report.section.user_template",+ topic=topic,+ report_title=outline.title,+ section_id=section.id,+ section_title=section.title,+ section_intent=section.intent or "(no extra guidance)",+ section_number=section_number,+ evidence=evidence,+ )+ return await self._stream_report_step(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ protocol=_PROTOCOL_REPORT_SECTION,+ stream=stream,+ client=client,+ label=(+ f"{self._t('labels.report_section', default='Section')}: "+ f"{section.title}"+ ),+ call_id_root=f"research-report-section-{section.id}",+ max_tokens=DEFAULT_REPORT_SECTION_MAX_TOKENS,+ extra_meta={+ "research_status_key": "report_section",+ "report_part": "section",+ "section_index": section_index,+ "section_count": section_count,+ "section_title": section.title,+ },+ )++ async def _write_conclusion(+ self,+ *,+ topic: str,+ outline: ReportOutline,+ section_bodies: list[str],+ section_number: int,+ stream: StreamBus,+ client: Any,+ ) -> str:+ # Recap: first paragraph of each rendered sub-topic section so the+ # conclusion writer can land the answer without re-reading the full+ # raw evidence. ``section_bodies`` contains only the middle sections+ # (title block and intro are intentionally excluded).+ recap_chunks: list[str] = []+ for sec, body in zip(outline.sections, section_bodies, strict=False):+ snippet = (body or "").strip().split("\n\n", 1)[0]+ recap_chunks.append(f"### {sec.title}\n{snippet[:300]}")+ system_prompt = self._t(+ "report.conclusion.system", section_number=section_number+ )+ user_prompt = self._t(+ "report.conclusion.user_template",+ topic=topic,+ title=outline.title,+ section_number=section_number,+ sections_recap="\n\n".join(recap_chunks) or "(no section bodies)",+ )+ return await self._stream_report_step(+ system_prompt=system_prompt,+ user_prompt=user_prompt,+ protocol=_PROTOCOL_REPORT_CONCLUSION,+ stream=stream,+ client=client,+ label=self._t("labels.report_conclusion", default="Conclusion"),+ call_id_root="research-report-conclusion",+ max_tokens=DEFAULT_REPORT_CONCLUSION_MAX_TOKENS,+ extra_meta={+ "research_status_key": "report_conclusion",+ "report_part": "conclusion",+ },+ )++ async def _stream_report_step(+ self,+ *,+ system_prompt: str,+ user_prompt: str,+ protocol: LabelProtocol,+ stream: StreamBus,+ client: Any,+ label: str,+ call_id_root: str,+ max_tokens: int,+ extra_meta: dict[str, Any] | None = None,+ ) -> str:+ """Common runner for the four report sub-phases: one labeled step+ with body streaming live to the chat bubble + a sub-trace card."""+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ trace_extra = dict(extra_meta or {})+ iter_meta = self._build_simple_trace_meta(+ call_id_root=call_id_root,+ label=label,+ stage="reporting",+ call_kind="llm_final_response",+ trace_role="response",+ trace_group="stage",+ **trace_extra,+ )+ final_call_id = new_call_id(f"{call_id_root}-final")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase="reporting",+ label=label,+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ **trace_extra,+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=protocol,+ stream=stream,+ stage="reporting",+ iter_meta=iter_meta,+ max_tokens=max_tokens,+ final_meta=final_meta,+ )+ return (step.text or "").strip()++ def _render_section_evidence(+ self,+ *,+ section: ReportSectionPlan,+ blocks: list[ResearchedBlock],+ citations: CitationManager,+ ) -> str:+ block_ids = section.block_ids or tuple(rb.block.block_id for rb in blocks)+ by_id = {rb.block.block_id: rb for rb in blocks}+ chunks: list[str] = []+ total = 0+ cap_per_block = 4000+ cap_total = 12000++ for bid in block_ids:+ rb = by_id.get(bid)+ if rb is None:+ continue+ title = _clean_report_heading_text(rb.block.sub_topic) or rb.block.sub_topic+ lines = [f"### Block [{rb.block.block_id}] {title}"]+ block_chars = 0+ for trace in rb.block.tool_traces:+ cid = trace.citation_id or trace.tool_id+ summary = (trace.summary or "").strip()+ if not summary:+ continue+ citation = citations.get_citation(cid) or {}+ source_preview = _citation_source_preview(citation)+ line_parts = [+ f"#### Evidence [{cid}]",+ f"- tool: {trace.tool_type}",+ f"- query: {trace.query}",+ ]+ if source_preview:+ line_parts.append(f"- source hints: {source_preview}")+ line_parts.append(f"- note: {summary}")+ line = "\n".join(line_parts)+ line = line[: cap_per_block - block_chars]+ if not line:+ break+ lines.append(line)+ block_chars += len(line)+ if block_chars >= cap_per_block:+ break+ if rb.knowledge:+ lines.append(f"#### Block FINISH\n{rb.knowledge[:1500]}")+ chunk = "\n\n".join(lines)+ if total + len(chunk) > cap_total:+ chunk = chunk[: max(0, cap_total - total)]+ if chunk:+ chunks.append(chunk)+ total += len(chunk)+ if total >= cap_total:+ break+ return "\n\n".join(chunks) or "(no evidence available)"++ # ------------------------------------------------------------------+ # Tool composition for the block loop+ # ------------------------------------------------------------------+ def _block_tool_names(self) -> list[str]:+ """Tools available inside the per-block research loop.++ Uses the same shared composition policy chat uses+ (:func:`compose_enabled_tools`): user-toggled tools first, then+ the conditional and always-on auto-mounts. Two block-phase-only+ adjustments:++ * Only evidence-producing research tools are surfaced. Chat's+ always-on convenience tools (``write_memory``, ``web_fetch``,+ ``github``, ``ask_user``) are deliberately not part of the+ block loop because they do not provide broad citable retrieval+ for an arbitrary sub-topic.+ * Each name is filtered through the registry so an inactive tool+ (mis-configured backend, missing dep) doesn't end up in the+ prompt.+ """+ composed = compose_enabled_tools(+ registry=self.registry,+ requested_tools=self.enabled_tools,+ optional_whitelist=RESEARCH_OPTIONAL_TOOLS,+ mount_flags=ToolMountFlags(+ has_kb=bool(self.kb_name),+ has_sources=False,+ has_memory=user_has_memory(),+ has_notebooks=user_has_notebooks(),+ ),+ )+ return [+ name+ for name in composed+ if name in RESEARCH_BLOCK_TOOL_ALLOWLIST+ and self._tool_in_registry(name)+ ]++ def _build_block_tool_schemas(+ self,+ tool_names: list[str] | None = None,+ ) -> list[dict[str, Any]]:+ names = self._block_tool_names() if tool_names is None else tool_names+ schemas = self.registry.build_openai_schemas(names)+ kb_choices = [self.kb_name] if self.kb_name else []+ for schema in schemas:+ function = schema.get("function") if isinstance(schema, dict) else None+ if not isinstance(function, dict):+ continue+ parameters = function.get("parameters")+ if not isinstance(parameters, dict):+ continue+ properties = parameters.get("properties") or {}+ if function.get("name") == "rag" and isinstance(properties, dict):+ if isinstance(properties.get("query"), dict):+ properties["query"].setdefault("minLength", 1)+ kb_schema = properties.get("kb_name")+ if isinstance(kb_schema, dict) and kb_choices:+ kb_schema["enum"] = kb_choices+ parameters["additionalProperties"] = False+ return schemas++ def _augment_tool_kwargs(+ self,+ tool_name: str,+ args: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ kwargs = dict(args)+ turn_id = str(context.metadata.get("turn_id", "") or "").strip()+ task_dir = None+ if turn_id:+ task_dir = get_path_service().get_task_workspace("deep_research", turn_id)+ if tool_name == "rag":+ kwargs.setdefault("mode", "hybrid")+ if self.kb_name:+ kwargs.setdefault("kb_name", self.kb_name)+ elif tool_name == "code_execution":+ kwargs.setdefault("intent", context.user_message)+ kwargs.setdefault("timeout", 30)+ kwargs.setdefault("feature", "deep_research")+ kwargs.setdefault("session_id", context.session_id)+ kwargs.setdefault("turn_id", turn_id)+ if task_dir is not None:+ kwargs.setdefault("workspace_dir", str(task_dir / "code_runs"))+ elif tool_name == "web_search":+ kwargs.setdefault("query", context.user_message)+ if task_dir is not None:+ kwargs.setdefault("output_dir", str(task_dir / "web_search"))+ return kwargs++ def _retrieve_trace_metadata(+ self,+ tool_meta: dict[str, Any],+ *,+ tool_name: str,+ tool_args: dict[str, Any],+ ) -> dict[str, Any] | None:+ if tool_name != "rag":+ return None+ return derive_trace_metadata(+ tool_meta,+ label=self._t("labels.retrieve", default="Retrieve"),+ call_kind="rag_retrieval",+ trace_role="retrieve",+ trace_group="retrieve",+ query=str(tool_args.get("query", "") or ""),+ )++ def _use_native_block_tools(self, tool_names: list[str] | None = None) -> bool:+ names = self._block_tool_names() if tool_names is None else tool_names+ return bool(names) and can_use_native_tool_calling(+ binding=self.binding, model=self.model+ )++ def _tool_in_registry(self, name: str) -> bool:+ try:+ return self.registry.get(name) is not None+ except Exception:+ return False++ # ------------------------------------------------------------------+ # LLM call helpers+ # ------------------------------------------------------------------+ def _build_client(self) -> Any:+ return build_openai_client(self.client_config)++ def _completion_kwargs(self, max_tokens: int) -> dict[str, Any]:+ return build_completion_kwargs(+ temperature=self._temperature,+ model=self.model,+ max_tokens=max_tokens,+ )++ async def _run_labeled_step(+ self,+ *,+ client: Any,+ messages: list[dict[str, Any]],+ tool_schemas: list[dict[str, Any]] | None,+ protocol: LabelProtocol,+ stream: StreamBus,+ stage: str,+ iter_meta: dict[str, Any],+ max_tokens: int = DEFAULT_BLOCK_MAX_TOKENS,+ final_meta: dict[str, Any] | None = None,+ eager_sub_trace: bool = True,+ ) -> LabeledStepResult:+ """Research-flavoured thin wrapper over :func:`run_labeled_step`."""+ return await run_labeled_step(+ client=client,+ model=self.model,+ messages=messages,+ completion_kwargs=self._completion_kwargs(max_tokens),+ tool_schemas=tool_schemas,+ allowed_labels=protocol.allowed,+ final_labels=protocol.final,+ tool_label=protocol.tool_label,+ stream=stream,+ source=SOURCE,+ stage=stage,+ iter_meta=iter_meta,+ binding=self.binding,+ usage=self.usage,+ final_meta=final_meta,+ eager_sub_trace=eager_sub_trace,+ )++ # ------------------------------------------------------------------+ # Message + trace assembly+ # ------------------------------------------------------------------+ def _build_system_user_messages(+ self,+ system_prompt: str,+ user_prompt: str,+ *,+ image_attachments: list[Attachment] | None = None,+ ) -> list[dict[str, Any]]:+ messages: list[dict[str, Any]] = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ]+ if image_attachments:+ mm_result = prepare_multimodal_messages(+ messages, image_attachments, binding=self.binding, model=self.model+ )+ return mm_result.messages+ return messages++ def _build_simple_trace_meta(+ self,+ *,+ call_id_root: str,+ label: str,+ stage: str,+ call_kind: str = "llm_reasoning",+ trace_role: str = "thought",+ trace_group: str = "stage",+ **extra: Any,+ ) -> dict[str, Any]:+ call_id = new_call_id(call_id_root)+ return build_trace_metadata(+ call_id=call_id,+ phase=stage,+ label=label,+ call_kind=call_kind,+ trace_id=call_id,+ trace_role=trace_role,+ trace_group=trace_group,+ **extra,+ )++ # ------------------------------------------------------------------+ # YAML lookup+ # ------------------------------------------------------------------+ def _t(self, key: str, default: str = "", **kwargs: Any) -> str:+ value: Any = self._prompts+ for part in key.split("."):+ if not isinstance(value, dict) or part not in value:+ return default+ value = value[part]+ if not isinstance(value, str):+ return default+ if kwargs:+ try:+ return value.format(**kwargs)+ except (KeyError, IndexError, ValueError):+ return value+ return value+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++_REPORT_TOKEN_RE = re.compile(r"[^\W_]+", re.UNICODE)+_REPORT_STOPWORDS = {+ "a",+ "an",+ "and",+ "as",+ "at",+ "by",+ "for",+ "from",+ "in",+ "into",+ "of",+ "on",+ "or",+ "the",+ "to",+ "vs",+ "with",+}+++_REPORT_CITATION_MARKER_RE = re.compile(+ r"`?\[(?P<id>CIT-\d+-\d+|PLAN-\d+)\]`?(?!\s*\()"+)+_REPORT_CITATION_LINK_RE = re.compile(+ r"`?\[(?P<id>CIT-\d+-\d+|PLAN-\d+)\]`?\([^)]*\)"+)+_MARKDOWN_HEADING_RE = re.compile(r"^(?P<hashes>#{1,6})\s+(?P<title>.+?)\s*$")+_LEADING_HEADING_MARKERS_RE = re.compile(r"^(?:#{1,6}\s+)+")+_LEADING_SECTION_ID_RE = re.compile(r"^(?:[\[\(]?S\d+[\]\)]?\s*[::\-]\s*)+", re.I)+++def _clean_report_heading_text(text: str) -> str:+ cleaned = _LEADING_HEADING_MARKERS_RE.sub("", (text or "").strip())+ cleaned = _LEADING_SECTION_ID_RE.sub("", cleaned).strip()+ return cleaned+++def _normalise_markdown_headings(text: str) -> str:+ lines: list[str] = []+ for line in (text or "").splitlines():+ match = _MARKDOWN_HEADING_RE.match(line)+ if not match:+ lines.append(line.rstrip())+ continue+ title = _clean_report_heading_text(match.group("title"))+ hashes = match.group("hashes")+ lines.append(f"{hashes} {title}" if title else hashes)+ return "\n".join(lines)+++def _citation_ids_in_first_appearance(+ text: str,+ citations: CitationManager,+) -> list[str]:+ known = set(citations.get_all_citations())+ ordered: list[str] = []+ seen: set[str] = set()+ for match in _REPORT_CITATION_MARKER_RE.finditer(text or ""):+ citation_id = match.group("id")+ if citation_id not in known or citation_id in seen:+ continue+ seen.add(citation_id)+ ordered.append(citation_id)+ return ordered+++def _citation_source_preview(citation: dict[str, Any]) -> str:+ if not citation:+ return ""+ tool_type = str(citation.get("tool_type") or "").lower()+ if tool_type == "web_search":+ sources = citation.get("web_sources")+ if isinstance(sources, list):+ hints = []+ for source in sources[:3]:+ if not isinstance(source, dict):+ continue+ title = str(source.get("title") or source.get("domain") or "").strip()+ url = str(source.get("url") or "").strip()+ if title and url:+ hints.append(f"{title} <{url}>")+ elif url:+ hints.append(url)+ return "; ".join(hints)+ if tool_type == "paper_search":+ papers = citation.get("papers")+ if isinstance(papers, list):+ hints = []+ for paper in papers[:3]:+ if not isinstance(paper, dict):+ continue+ title = str(paper.get("title") or "").strip()+ year = str(paper.get("year") or "").strip()+ if title:+ hints.append(f"{title} ({year})" if year else title)+ return "; ".join(hints)+ if tool_type in {"rag", "rag_naive", "rag_hybrid"}:+ sources = citation.get("sources")+ if isinstance(sources, list):+ hints = []+ for source in sources[:3]:+ if not isinstance(source, dict):+ continue+ title = str(+ source.get("title") or source.get("source_file") or ""+ ).strip()+ page = str(source.get("page") or "").strip()+ if title:+ hints.append(f"{title} p.{page}" if page else title)+ return "; ".join(hints)+ return ""+++def _section_with_block_ids(+ section: ReportSectionPlan,+ block_ids: tuple[str, ...],+) -> ReportSectionPlan:+ return ReportSectionPlan(+ id=section.id,+ title=section.title,+ intent=section.intent,+ block_ids=block_ids,+ )+++def _report_tokens(text: str) -> set[str]:+ tokens: set[str] = set()+ for raw in _REPORT_TOKEN_RE.findall((text or "").lower()):+ token = raw.strip()+ if not token or token in _REPORT_STOPWORDS:+ continue+ if len(token) > 4 and token.endswith("ies"):+ token = token[:-3] + "y"+ elif len(token) > 3 and token.endswith("s"):+ token = token[:-1]+ tokens.add(token)+ return tokens+++def _report_overlap_score(left: str, right: str) -> float:+ left_tokens = _report_tokens(left)+ right_tokens = _report_tokens(right)+ if not left_tokens or not right_tokens:+ return 0.0+ overlap = left_tokens & right_tokens+ if not overlap:+ return 0.0+ return len(overlap) / max(1, min(len(left_tokens), len(right_tokens)))+++def _best_block_for_section(+ section: ReportSectionPlan,+ blocks: list[ResearchedBlock],+ *,+ exclude: set[str],+) -> ResearchedBlock | None:+ candidates = [rb for rb in blocks if rb.block.block_id not in exclude] or blocks+ section_text = f"{section.title} {section.intent}"+ best: tuple[float, ResearchedBlock] | None = None+ for rb in candidates:+ block_text = f"{rb.block.sub_topic} {rb.block.overview} {rb.knowledge[:500]}"+ score = _report_overlap_score(section_text, block_text)+ if best is None or score > best[0]:+ best = (score, rb)+ return best[1] if best is not None else None+++def _best_section_for_block(+ block: ResearchedBlock,+ sections: list[ReportSectionPlan],+) -> int | None:+ block_text = f"{block.block.sub_topic} {block.block.overview} {block.knowledge[:500]}"+ best: tuple[float, int] | None = None+ for idx, section in enumerate(sections):+ section_text = f"{section.title} {section.intent}"+ score = _report_overlap_score(block_text, section_text)+ if best is None or score > best[0]:+ best = (score, idx)+ if best is None or best[0] <= 0:+ return None+ return best[1]+++def _citation_anchor_id(citation_id: str) -> str:+ return "ref-" + re.sub(r"[^a-z0-9_-]+", "-", citation_id.lower()).strip("-")+++def _citation_markdown_link(citation_id: str, ref_number: int) -> str:+ return f'[{ref_number}](#{_citation_anchor_id(citation_id)} "citation")'+++def _sorted_citation_ids(citations: CitationManager) -> list[str]:+ return sorted(citations.get_all_citations(), key=_citation_sort_key)+++def _citation_number_map(citations: CitationManager) -> dict[str, int]:+ return {+ citation_id: index+ for index, citation_id in enumerate(_sorted_citation_ids(citations), start=1)+ }+++def _citation_sort_key(citation_id: str) -> tuple[int, int, int]:+ """Sort PLAN and per-block CIT ids in the same order users see them."""+ try:+ if citation_id.startswith("PLAN-"):+ return (0, 0, int(citation_id.replace("PLAN-", "", 1)))+ if citation_id.startswith("CIT-"):+ block_num, seq_num = citation_id.replace("CIT-", "", 1).split("-", 1)+ return (1, int(block_num), int(seq_num))+ except (IndexError, ValueError):+ pass+ return (999, 999, 999)+++def _topic_index_from_block_id(block_id: str) -> int | None:+ match = re.search(r"block_(\d+)", block_id or "")+ if match is None:+ return None+ try:+ return int(match.group(1))+ except ValueError:+ return None+++def _research_topic_status_meta(block: TopicBlock) -> dict[str, Any]:+ return {+ "research_status_key": "research_topic",+ "topic_index": _topic_index_from_block_id(block.block_id),+ "topic_title": block.sub_topic,+ }+++def _read_int(cfg: Any, *, key: str, default: int) -> int:+ if isinstance(cfg, dict):+ value = cfg.get(key, default)+ else:+ value = default+ try:+ return int(value)+ except (TypeError, ValueError):+ return default++# ---------------------------------------------------------------------------+# _BlockLoopHost — per-block research loop callbacks+# ---------------------------------------------------------------------------+++class _BlockLoopHost:+ """Binds a ``ResearchPipeline`` + one ``TopicBlock`` + queue + citation+ store so the generic agentic loop can call back for per-block side+ effects.++ Three loop hooks are implemented beyond the default protocol:+ * :meth:`dispatch_tools` — wraps the standard parallel dispatch with+ a note-agent sidecar that summarises citable tool results and+ records them in :class:`CitationManager`. The summary then+ replaces the raw tool message content sent back to the model so+ long retrievals don't blow the context budget.+ * :meth:`on_intermediate` — handles the ``APPEND`` label. Parses+ ``<title>\n<overview?>`` out of the post-label text, runs dedup+ + capacity checks, appends a child block to the queue, and+ returns a confirmation / rejection message that the loop injects+ as the next iteration's user feedback.+ * :meth:`force_finalize` — drives the per-block force-finish+ recovery when the iteration budget is exhausted before a+ terminal label fires.+ """++ def __init__(+ self,+ *,+ pipeline: "ResearchPipeline",+ block: TopicBlock,+ queue: DynamicTopicQueue,+ citations: CitationManager,+ topic: str,+ stream: StreamBus,+ context: UnifiedContext,+ client: Any,+ ) -> None:+ self._pipeline = pipeline+ self._block = block+ self._queue = queue+ self._citations = citations+ self._topic = topic+ self._stream = stream+ self._context = context+ self._client = client+ self._tool_rounds_used = 0++ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:+ # Per-block budgets keep messages bounded; no trimming for v1.+ return None++ def build_iteration_trace_meta(+ self, iteration: int+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ status_meta = _research_topic_status_meta(self._block)+ iter_call_id = new_call_id(+ f"research-{self._block.block_id}-iter-{iteration}"+ )+ iter_meta = build_trace_metadata(+ call_id=iter_call_id,+ phase="researching",+ label=self._pipeline._t("labels.reasoning", default="Reasoning"),+ call_kind="llm_reasoning",+ trace_id=iter_call_id,+ trace_role="thought",+ trace_group="stage",+ block_id=self._block.block_id,+ **status_meta,+ )+ final_call_id = new_call_id(f"research-{self._block.block_id}-final")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase="researching",+ label=(+ f"{self._pipeline._t('labels.research_step', default='Research step')}: "+ f"{self._block.sub_topic}"+ ),+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ block_id=self._block.block_id,+ **status_meta,+ )+ return iter_meta, final_meta++ async def dispatch_tools(+ self,+ *,+ iteration: int,+ tool_calls: list[dict[str, Any]],+ ) -> DispatchOutcome:+ too_many = None+ if len(tool_calls) > MAX_PARALLEL_TOOL_CALLS:+ too_many = self._pipeline._t(+ "notices.too_many_tool_calls",+ requested=len(tool_calls),+ limit=MAX_PARALLEL_TOOL_CALLS,+ )+ outcome = await dispatch_tool_calls(+ tool_calls=tool_calls,+ context=self._context,+ stream=self._stream,+ source=SOURCE,+ stage="researching",+ iteration_index=iteration,+ registry=self._pipeline.registry,+ kwarg_augmenter=self._pipeline._augment_tool_kwargs,+ retrieve_meta_factory=lambda meta, tn, ta: self._pipeline._retrieve_trace_metadata(+ meta, tool_name=tn, tool_args=ta+ ),+ tool_call_label=self._pipeline._t("labels.tool_call", default="Tool call"),+ retrieve_label=self._pipeline._t("labels.retrieve", default="Retrieve"),+ empty_tool_result_message=self._pipeline._t("notices.empty_tool_result"),+ start_retrieval_message=self._pipeline._t(+ "notices.start_retrieval", default="Starting retrieval"+ ),+ too_many_tool_calls_message=too_many,+ unknown_error_message_factory=lambda tn: self._pipeline._t(+ "notices.tool_unknown_error",+ tool=tn,+ default=f"Error executing {tn}.",+ ),+ trace_id_prefix=f"research-{self._block.block_id}-iter",+ )+ if tool_calls:+ self._tool_rounds_used += 1+ await self._summarise_and_record(tool_calls, outcome)+ return outcome++ async def validate_terminal(self, label: str, text: str) -> str | None:+ """Reject a first-turn FINISH when native evidence tools are callable.++ The prompt tells the model to call a tool before FINISH, but some+ models still jump straight to synthesis. This hook makes that rule+ executable instead of prompt-only.+ """+ if (+ label == LABEL_FINISH+ and self._tool_rounds_used <= 0+ and self._pipeline._use_native_block_tools()+ ):+ return "finish_without_tool"+ return None++ async def _summarise_and_record(+ self,+ tool_calls: list[dict[str, Any]],+ outcome: DispatchOutcome,+ ) -> None:+ """Walk every emitted tool message; for citable tools, summarise+ the raw answer through ``_summarise_tool_result``, register the+ result in :class:`CitationManager`, and substitute the summary+ back into the tool message body the LLM sees."""+ if not outcome.tool_messages:+ return+ call_meta_by_id: dict[str, tuple[str, dict[str, Any]]] = {}+ for tc in tool_calls:+ cid = tc.get("id") or ""+ name = str(tc.get("name") or "")+ raw_args = tc.get("arguments") or {}+ if isinstance(raw_args, str):+ parsed = parse_json_response(raw_args, fallback={})+ args = parsed if isinstance(parsed, dict) else {}+ elif isinstance(raw_args, dict):+ args = raw_args+ else:+ args = {}+ call_meta_by_id[cid] = (name, args)++ for tm in outcome.tool_messages:+ tool_call_id = str(tm.get("tool_call_id") or "")+ tool_name, tool_args = call_meta_by_id.get(tool_call_id, ("", {}))+ if tool_name not in CITABLE_TOOLS:+ continue+ raw_answer = str(tm.get("content") or "")+ if not raw_answer.strip():+ continue+ try:+ query = str(tool_args.get("query") or "")+ summary = await self._pipeline._summarise_tool_result(+ tool_name=tool_name,+ query=query,+ raw_answer=raw_answer,+ client=self._client,+ )+ citation_id = await self._citations.generate_research_citation_id_async(+ self._block.block_id+ )+ trace = ToolTrace.create_with_size_limit(+ tool_id=f"{self._block.block_id}-tool-{citation_id}",+ citation_id=citation_id,+ tool_type=tool_name,+ query=query,+ raw_answer=raw_answer,+ summary=summary,+ )+ self._block.add_tool_trace(trace)+ tool_metadata = outcome.tool_metadata_by_id.get(tool_call_id)+ await self._citations.add_citation_async(+ citation_id, tool_name, trace, raw_answer, tool_metadata+ )+ tm["content"] = f"[{citation_id}] {summary}"+ except Exception:+ logger.exception(+ "Failed to record research citation for %s in %s",+ tool_name,+ self._block.block_id,+ )++ async def resolve_pause(self, dispatch: DispatchOutcome) -> bool:+ # Per-block research never surfaces ask_user; clarification only+ # happens in the rephrase phase.+ return False++ async def emit_terminator(self, payload: dict[str, Any] | None) -> None:+ return None++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ # Block FINISH text is consumed by the reporting phase, not+ # streamed live as user-facing content — streaming it here would+ # dump raw per-block findings into the chat bubble before the+ # actual report begins.+ return None++ def assistant_message_with_tool_calls(+ self,+ *,+ content: str,+ tool_calls: list[dict[str, Any]],+ ) -> dict[str, Any]:+ return {+ "role": "assistant",+ "content": content or None,+ "tool_calls": [+ {+ "id": tc["id"],+ "type": "function",+ "function": {+ "name": tc["name"],+ "arguments": tc.get("arguments") or "{}",+ },+ }+ for tc in tool_calls+ ],+ }++ def protocol_retry_notice(self) -> str:+ return self._pipeline._t(+ "notices.protocol_retry",+ default="The model violated the action-label protocol; retrying.",+ )++ def protocol_repair_message(self, violation: str) -> str:+ return self._pipeline._t(+ f"protocol.{violation}",+ default=f"Protocol violation: {violation}.",+ )++ async def force_finalize(+ self,+ *,+ messages: list[dict[str, Any]],+ start_iteration: int,+ ) -> tuple[str, bool, int]:+ return await self._pipeline._force_finish_block(+ client=self._client,+ messages=messages,+ stream=self._stream,+ block=self._block,+ start_iteration=start_iteration,+ )++ async def on_intermediate(self, label: str, text: str) -> str | None:+ """Parse ``APPEND`` payload and extend the queue.++ Format: first line = title, remainder (optional) = overview.+ Empty / duplicate / over-capacity proposals get a rejection note+ the loop injects as the next iteration's user message so the LLM+ can adapt rather than spam the same proposal.+ """+ if label != LABEL_APPEND:+ return None+ first_line, _, rest = (text or "").strip().partition("\n")+ # Strip leading markdown heading markers (``#``, ``##``, …) so the+ # queue stores a clean title even if the LLM rendered the new+ # sub-topic as a markdown header.+ title = first_line.strip().lstrip("#").strip()+ overview = rest.strip()+ if not title:+ return self._pipeline._t(+ "notices.append_rejected_empty",+ default="APPEND rejected: missing title.",+ )++ if self._queue.is_full():+ await self._stream.progress(+ self._pipeline._t(+ "notices.append_rejected_full_progress",+ title=title,+ default=f"Queue is full; rejected append: {title}",+ ),+ source=SOURCE,+ stage="researching",+ metadata={+ "trace_kind": "queue_append_rejected",+ "block_id": self._block.block_id,+ "reason": "full",+ "title": title,+ },+ )+ return self._pipeline._t(+ "notices.append_rejected_full",+ default=(+ "APPEND rejected: the topic queue is at capacity. Continue "+ "researching the current block and emit FINISH when done."+ ),+ )++ dup = self._queue.find_similar(title)+ if dup is not None:+ await self._stream.progress(+ self._pipeline._t(+ "notices.append_rejected_dup_progress",+ title=title,+ existing=dup.block_id,+ default=(+ f"APPEND rejected: '{title}' is too similar to "+ f"existing block {dup.block_id}"+ ),+ ),+ source=SOURCE,+ stage="researching",+ metadata={+ "trace_kind": "queue_append_rejected",+ "block_id": self._block.block_id,+ "reason": "duplicate",+ "title": title,+ "existing_id": dup.block_id,+ },+ )+ return self._pipeline._t(+ "notices.append_rejected_duplicate",+ existing_id=dup.block_id,+ existing_title=dup.sub_topic,+ default=(+ f"APPEND rejected: too similar to existing block "+ f"{dup.block_id} ({dup.sub_topic!r})."+ ),+ )++ new_block = self._queue.append_child(+ parent=self._block, sub_topic=title, overview=overview+ )+ if new_block is None:+ return self._pipeline._t(+ "notices.append_rejected_full",+ default="APPEND rejected: queue is full.",+ )++ await self._stream.progress(+ self._pipeline._t(+ "notices.append_accepted_progress",+ title=title,+ new_block_id=new_block.block_id,+ default=f"Sub-topic queued: {title}",+ ),+ source=SOURCE,+ stage="researching",+ metadata={+ "trace_kind": "queue_append",+ "block_id": self._block.block_id,+ "parent_block_id": self._block.block_id,+ "new_block_id": new_block.block_id,+ "title": title,+ },+ )+ return self._pipeline._t(+ "notices.append_accepted",+ new_block_id=new_block.block_id,+ title=title,+ default=f"Appended block {new_block.block_id}: {title}",+ )+++# ---------------------------------------------------------------------------+# _RephraseLoopHost — ask_user-only mini loop+# ---------------------------------------------------------------------------+++class _RephraseLoopHost:+ """Drives the rephrase mini-loop. Only ``ask_user`` is allowed as a+ tool; the round cap (``rephrase_max_rounds``) is enforced here. When+ exhausted, any further ``ask_user`` call is replied to with a tool+ message instructing the model to FINISH with the best refined topic+ it has."""++ def __init__(+ self,+ *,+ pipeline: "ResearchPipeline",+ stream: StreamBus,+ context: UnifiedContext,+ client: Any,+ max_rounds: int,+ ) -> None:+ self._pipeline = pipeline+ self._stream = stream+ self._context = context+ self._client = client+ self._max_rounds = max(0, int(max_rounds))+ self._rounds_used = 0+ # Reuse one call_id across all rephrase iterations so the FE+ # groups every THINK trace from before *and* after ``ask_user``+ # into a single "Rephrasing" reasoning card. Without this each+ # iter would get its own card and the post-answer reasoning+ # would appear as a brand-new box below the user's reply.+ self._shared_iter_call_id = new_call_id("research-rephrase-iter")++ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:+ return None++ def build_iteration_trace_meta(+ self, iteration: int+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ iter_meta = build_trace_metadata(+ call_id=self._shared_iter_call_id,+ phase="rephrasing",+ label=self._pipeline._t("labels.rephrase", default="Rephrase"),+ call_kind="llm_reasoning",+ trace_id=self._shared_iter_call_id,+ trace_role="thought",+ trace_group="stage",+ )+ final_call_id = new_call_id(f"research-rephrase-final-{iteration}")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase="rephrasing",+ label=self._pipeline._t("labels.rephrase", default="Rephrase"),+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ )+ return iter_meta, final_meta++ async def dispatch_tools(+ self,+ *,+ iteration: int,+ tool_calls: list[dict[str, Any]],+ ) -> DispatchOutcome:+ allowed: list[dict[str, Any]] = []+ rejected: list[dict[str, Any]] = []+ for tc in tool_calls:+ if tc.get("name") == "ask_user":+ allowed.append(tc)+ else:+ rejected.append(+ {+ "role": "tool",+ "tool_call_id": tc.get("id"),+ "name": tc.get("name", ""),+ "content": self._pipeline._t(+ "notices.rephrase_only_ask_user",+ tool=tc.get("name", ""),+ default=(+ "Only `ask_user` is available in this phase. "+ "Use it or emit FINISH with the refined topic."+ ),+ ),+ }+ )++ if self._rounds_used >= self._max_rounds and allowed:+ cap_messages = [+ {+ "role": "tool",+ "tool_call_id": tc.get("id"),+ "name": "ask_user",+ "content": self._pipeline._t(+ "notices.rephrase_cap_reached",+ max_rounds=self._max_rounds,+ default=(+ f"ask_user limit reached ({self._max_rounds} "+ "rounds). Emit FINISH now with the best refined "+ "topic you can produce from prior answers."+ ),+ ),+ }+ for tc in allowed+ ]+ return DispatchOutcome(+ sources=[], tool_messages=cap_messages + rejected+ )++ if not allowed:+ return DispatchOutcome(sources=[], tool_messages=rejected)++ too_many = None+ if len(allowed) > MAX_PARALLEL_TOOL_CALLS:+ too_many = self._pipeline._t(+ "notices.too_many_tool_calls",+ requested=len(allowed),+ limit=MAX_PARALLEL_TOOL_CALLS,+ )+ outcome = await dispatch_tool_calls(+ tool_calls=allowed,+ context=self._context,+ stream=self._stream,+ source=SOURCE,+ stage="rephrasing",+ iteration_index=iteration,+ registry=self._pipeline.registry,+ kwarg_augmenter=self._pipeline._augment_tool_kwargs,+ retrieve_meta_factory=lambda meta, tn, ta: None,+ tool_call_label=self._pipeline._t("labels.tool_call", default="Tool call"),+ retrieve_label=self._pipeline._t("labels.retrieve", default="Retrieve"),+ empty_tool_result_message=self._pipeline._t("notices.empty_tool_result"),+ start_retrieval_message=self._pipeline._t(+ "notices.start_retrieval", default="Starting retrieval"+ ),+ too_many_tool_calls_message=too_many,+ unknown_error_message_factory=lambda tn: self._pipeline._t(+ "notices.tool_unknown_error",+ tool=tn,+ default=f"Error executing {tn}.",+ ),+ trace_id_prefix="research-rephrase-iter",+ )+ if rejected:+ outcome.tool_messages.extend(rejected)+ self._rounds_used += 1+ return outcome++ async def resolve_pause(self, dispatch: DispatchOutcome) -> bool:+ from deeptutor.agents.chat.agentic_pipeline import (+ _format_user_reply_body,+ _normalise_user_reply,+ )++ ask_user = (dispatch.pause_payload or {}).get("ask_user") or {}+ waiter = self._context.metadata.get("wait_for_user_reply")+ if not callable(waiter):+ return False+ raw_reply = await waiter()+ if raw_reply is None:+ return False+ reply_text, answers = _normalise_user_reply(raw_reply)+ body_text = _format_user_reply_body(reply_text, answers, ask_user)+ for tm in dispatch.tool_messages:+ if tm.get("tool_call_id") == dispatch.pause_tool_call_id:+ tm["content"] = (+ f"{body_text}\n\n[ask_user resolved. Continue to FINISH "+ "with the refined research topic when you have enough "+ "information.]"+ )+ break+ progress_meta: dict[str, Any] = {+ "trace_kind": "user_reply",+ "ask_user_resolved": True,+ "ask_user_tool_call_id": dispatch.pause_tool_call_id,+ "reply_preview": (reply_text or "")[:200],+ }+ if answers:+ progress_meta["answers"] = list(answers)+ await self._stream.progress(+ "", source=SOURCE, stage="rephrasing", metadata=progress_meta+ )+ return True++ async def emit_terminator(self, payload: dict[str, Any] | None) -> None:+ return None++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ # The refined topic is internal; not streamed as user content.+ return None++ def assistant_message_with_tool_calls(+ self,+ *,+ content: str,+ tool_calls: list[dict[str, Any]],+ ) -> dict[str, Any]:+ return {+ "role": "assistant",+ "content": content or None,+ "tool_calls": [+ {+ "id": tc["id"],+ "type": "function",+ "function": {+ "name": tc["name"],+ "arguments": tc.get("arguments") or "{}",+ },+ }+ for tc in tool_calls+ ],+ }++ def protocol_retry_notice(self) -> str:+ return self._pipeline._t(+ "notices.protocol_retry",+ default="The model violated the action-label protocol; retrying.",+ )++ def protocol_repair_message(self, violation: str) -> str:+ return self._pipeline._t(+ f"protocol.{violation}",+ default=f"Protocol violation: {violation}.",+ )++ async def force_finalize(+ self,+ *,+ messages: list[dict[str, Any]],+ start_iteration: int,+ ) -> tuple[str, bool, int]:+ # Rephrase exhaustion falls back to the raw topic (handled by+ # the caller); we report no extra calls and "not completed" so+ # the loop returns with an empty final_text.+ return ("", False, 0)+++# Re-export ``Awaitable`` so host implementations can type their+# coroutine return values without an extra import (mirrors solve).+_ = Awaitable # type: ignore[assignment]+++__all__ = [+ "CITABLE_TOOLS",+ "LABEL_APPEND",+ "LABEL_CONCLUSION",+ "LABEL_FINISH",+ "LABEL_INTRO",+ "LABEL_OUTLINE",+ "LABEL_SECTION",+ "LABEL_THINK",+ "LABEL_TOOL",+ "ResearchPipeline",+ "ResearchedBlock",+ "ReportOutline",+ "ReportSectionPlan",+ "SOURCE",+ "SubTopicItem",+]diff --git a/deeptutor/agents/research/prompts/en/answer_now.yaml b/deeptutor/agents/research/prompts/en/answer_now.yamldeleted file mode 100644index be475d6f1..000000000--- a/deeptutor/agents/research/prompts/en/answer_now.yaml+++ /dev/null@@ -1,16 +0,0 @@-system: |- You are DeepTutor's research-report writer. The user is waiting, so- produce a structured research report right now from whatever evidence- has streamed so far (rephrase, decompose, search hits, notes/outline,- ...). Do not retrieve more evidence and do not call tools. If coverage- is thin, say so explicitly in the report. Use Markdown with: 1) intro,- 2) body sections (one per identifiable subtopic), 3) conclusion.--user_template: |- Research topic: {original}-- {current_draft}-- {research_trace}-- Produce the final research report from this material now.diff --git a/deeptutor/agents/research/prompts/en/decompose_agent.yaml b/deeptutor/agents/research/prompts/en/decompose_agent.yamldeleted file mode 100644index 340180332..000000000--- a/deeptutor/agents/research/prompts/en/decompose_agent.yaml+++ /dev/null@@ -1,119 +0,0 @@-# DecomposeAgent Prompt Configuration (English)--system:- role: |- You are a research planning expert, responsible for decomposing complex topics into logically clear, non-overlapping subtopic systems.--mode_contracts:- study_notes_decompose: |- YOU MUST decompose into **learner-friendly study units**, NOT report chapters.- - Subtopics should be: core concepts, key mechanisms, worked examples, common pitfalls, recap blocks.- - NEVER produce subtopics like "Background", "Methodology", "Analysis", "Discussion" — those are report sections.- - Each subtopic title should be short and memory-oriented (e.g. "How X Works", "Key Formula", "Watch Out For").- - The decomposition must make later output feel like revision notes, not an essay.- report_decompose: |- YOU MUST decompose into **analytical report sections** with clear scope and logical progression.- - Prefer: context/background, major themes, methods/issues, synthesis/implications.- - Subtopics should read like report chapters. NEVER produce flashcard-style or stage-style subtopics.- comparison_decompose: |- YOU MUST decompose by **comparison dimensions**, NOT by option.- - Each subtopic = one evaluation dimension that applies to ALL alternatives (e.g. "Performance", "Cost", "Ease of Use").- - NEVER create subtopics like "About Option A", "About Option B" — that defeats comparison.- - Include space for trade-offs, strengths, weaknesses, and scenario-fit judgment.- - Example good subtopics: "Dimension: Scalability — comparing A, B, C", "Dimension: Cost-Efficiency — comparing A, B, C".- learning_path_decompose: |- YOU MUST decompose into **prerequisite-aware sequential learning stages**.- - Subtopics must reflect progression: what to learn first → next → after that.- - NEVER produce flat topical sections. The order MUST matter — earlier stages are prerequisites for later ones.- - Each subtopic should imply a stage with objectives, practice, and a checkpoint.- - Example good subtopics: "Stage 1: Math Foundations (prerequisites for everything)", "Stage 2: Core Algorithms (builds on Stage 1)".--process:- generate_queries: |- Generate {num_queries} search queries for the following topic. Only output JSON object:-- Topic: {topic}-- Requirements:- 1. Each query 1-3 keywords, concise and representative- 2. Cover different dimensions of the topic to ensure diversity- 3. Avoid duplication between queries-- Output JSON:- {{- "queries": ["Query 1", "Query 2", ...]- }}-- decompose: |- Decompose the topic into subtopics based on the following information. Only output JSON object:-- Main Topic: {topic}-- Background Knowledge (from RAG retrieval):- {rag_context}-- {decompose_requirement}-- **Mode-Specific Focus**:- {mode_instruction}-- **Decomposition Steps:**-- 1. **Analyze Background Knowledge**: Identify core concepts, key theories, and important content-- 2. **Identify Research Dimensions**: Determine research focus for each dimension, ensure dimensions are complementary-- 3. **Generate Subtopics**:- - Based on actual content in background knowledge- - Subtopics are logically related but not duplicated- - Cover main aspects of the theme-- 4. **Refine Descriptions**:- - title: Concise and clear, expressing the core of the subtopic- - overview: 2-3 sentences, explaining content, importance, and research value-- Output JSON:- {{- "sub_topics": [- {{- "title": "Subtopic Title",- "overview": "Detailed overview, explaining content, focus, and research value"- }}- ]- }}-- decompose_without_rag: |- Decompose the following research topic into clear, well-structured subtopics. Only output JSON object:-- Main Topic: {topic}-- {decompose_requirement}-- **Mode-Specific Focus**:- {mode_instruction}-- **Decomposition Steps (Without RAG Context):**-- 1. **Identify Key Aspects**: Based on your knowledge, identify the key aspects and dimensions of this topic-- 2. **Generate Subtopics**:- - Each subtopic should cover a distinct aspect of the main topic- - Subtopics should have logical relationships but not overlap or duplicate- - Ensure subtopics together form a comprehensive research framework-- 3. **Refine Descriptions**:- - title: Concise and clear, expressing the core focus of the subtopic- - overview: 2-3 sentences explaining:- - What this subtopic covers- - Why it's important for understanding the main topic- - Key concepts or areas to explore-- Output JSON:- {{- "sub_topics": [- {{- "title": "Subtopic title (concise and clear)",- "overview": "Detailed overview (2-3 sentences explaining importance, scope, and key areas)"- }}- ]- }}diff --git a/deeptutor/agents/research/prompts/en/manager_agent.yaml b/deeptutor/agents/research/prompts/en/manager_agent.yamldeleted file mode 100644index 40895525e..000000000--- a/deeptutor/agents/research/prompts/en/manager_agent.yaml+++ /dev/null@@ -1,24 +0,0 @@-# ManagerAgent Prompt Configuration (English)--system:- role: |- You are a task scheduling expert, responsible for managing the state of dynamic topic queues and task dispatching.--process:- decide_next: |- Decide the next operation based on queue status. Only output JSON object:-- Queue Statistics:- total={total}, pending={pending}, researching={researching}, completed={completed}, failed={failed}-- **Decision Rules:**- - If there are pending → action: "dispatch", select the head block_id- - If no pending and researching=0 → action: "finish"- - Otherwise → action: "wait"-- Output JSON:- {{- "action": "dispatch|finish|wait",- "block_id": "(required when dispatch)",- "reason": "Brief reason"- }}diff --git a/deeptutor/agents/research/prompts/en/note_agent.yaml b/deeptutor/agents/research/prompts/en/note_agent.yamldeleted file mode 100644index 75052a009..000000000--- a/deeptutor/agents/research/prompts/en/note_agent.yaml+++ /dev/null@@ -1,145 +0,0 @@-# NoteAgent Prompt Configuration - Deep Information Extraction and Structured Summary-# Design Goal: Extract rich structured information from tool outputs to provide materials for high-quality report generation--system:- role: |- You are an information extraction and knowledge organization expert, responsible for extracting key information from various tool outputs and generating structured, reusable high-quality summaries.-- **Core Capabilities**:- 1. **Multimodal Information Recognition**: Ability to identify and preserve formulas, tables, code, data, and other structured elements- 2. **Hierarchical Extraction**: Distinguish core information, supporting information, and background information- 3. **Knowledge Association**: Identify relationships and dependencies between concepts- 4. **Academic Standards**: Maintain terminology accuracy and citation completeness-- **Important Format Requirements**:- - All outputs must strictly follow JSON format- - Only output valid JSON objects, do not include any additional text, explanations, or code block markers- - JSON must be directly parseable, cannot contain comments or format errors- - If the output contains text content, include it as a JSON string value and properly escape special characters--mode_contracts:- study_notes_note: |- YOU MUST produce summaries that already look like **reusable study-note material**.- - Extract and highlight: definitions (with `> **Definition — Term**: ...` format), core mechanisms, representative examples, memory cues, common pitfalls.- - Use bullet lists, short paragraphs, and callout blocks. NEVER produce long analytical prose.- - Every summary should be directly usable as a revision-note section without further editing.- report_note: |- YOU MUST produce summaries that look like **reusable evidence blocks for a formal report**.- - Prioritize claims, supporting evidence, implications, limitations, and connections to the broader topic.- - Preserve material that helps later synthesis and argumentation.- comparison_note: |- YOU MUST produce summaries that look like **reusable comparison cards**.- - For EVERY piece of information, tag which option/alternative it relates to and which comparison dimension it belongs to.- - Extract: dimension-specific evidence, strengths, weaknesses, trade-offs, scenario-fit judgments.- - NEVER produce a summary that only describes one option without positioning it against alternatives.- - Format preference: use structured labels like `**Option A — Dimension X**: ...` for easy side-by-side assembly later.- learning_path_note: |- YOU MUST produce summaries that look like **reusable stage cards for a learning roadmap**.- - For EVERY piece of information, tag where it fits in the learning sequence (foundation / intermediate / advanced).- - Extract: prerequisites, stage goals, must-know concepts, practice suggestions, completion signals, "learn X before Y" dependencies.- - NEVER produce flat encyclopedic summaries. Every extracted fact must be positioned on the learning timeline.--process:- generate_summary: |- Extract key information from the following tool output and generate a structured summary.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Tool Type: {tool_type}- Query: {query}- Topic: {topic}- Context: {context}-- {mode_instruction}-- Raw Output:- {raw_answer}-- **Deep Extraction Framework**:-- ## Step 1: Content Type Identification-- Identify information types contained in the raw output:- - □ Concept Definitions (terms, definitions, explanations)- - □ Mathematical Formulas (equations, theorems, derivations)- - □ Data Tables (comparisons, parameters, statistics)- - □ Algorithms/Code (pseudocode, implementations, examples)- - □ Processes/Architectures (steps, workflows, system structures)- - □ Cases/Examples (application scenarios, experimental results)- - □ Citations/Sources (papers, authors, references)-- ## Step 2: Hierarchical Information Extraction-- 1. **Core Layer** (Must Extract):- - Key information directly answering the query- - Important definitions, formulas, conclusions- - Core data and key findings-- 2. **Supporting Layer** (Selective Extraction):- - Derivation processes and argumentation logic- - Experimental methods and validation data- - Comparative analysis and pros/cons-- 3. **Background Layer** (Brief Mention):- - Historical evolution and development trajectory- - Related work and references- - Applicable conditions and limitations-- ## Step 3: Structured Information Preservation-- **Elements that MUST preserve original format**:-- 1. **Mathematical Formulas**:- - Inline formulas: preserve as `$...$` format- - Block formulas: preserve as `$$...$$` format- - Example: `$E = mc^2$` or `$$\\nabla \\cdot E = \\frac{\\rho}{\\epsilon_0}$$`-- 2. **Table Data**:- - Convert to Markdown table format- - Preserve headers and key data rows- - Example: `| Method | Accuracy | Efficiency |\\n|---|---|---|\\n| A | 95% | Fast |`-- 3. **Code Snippets**:- - Preserve key algorithms or example code- - Use code block format with language annotation- - Example: `\\`\\`\\`python\\ndef func():\\n pass\\n\\`\\`\\``-- 4. **List Structures**:- - Preserve steps, key points, and other lists- - Use `1. 2. 3.` or `- - -` format-- ## Step 4: Generate Structured Summary-- **Summary Requirements**:- - Length: 300-600 words (adjust based on information density)- - Structure: Organize by logical themes, not original text order- - Completeness: Summary should be independently readable without referring to raw output- - Accuracy: Maintain accuracy of terminology and numerical values-- **Output Format Requirements (Strictly Follow):**- - Only output JSON object, do not use ```json code block wrapper- - Do not add any explanatory text- - Special characters in JSON strings (such as quotes, newlines, backslashes) must be properly escaped- - Ensure JSON format is completely valid and can be directly parsed by json.loads()-- Output Example (for format reference only, do not copy content):- {{- "summary": "Structured summary content (including preserved formulas, tables, and other elements)",- "key_elements": {{- "definitions": ["definition1", "definition2"],- "formulas": ["$formula1$", "$$formula2$$"],- "data_points": ["data1", "data2"],- "methods": ["method1", "method2"]- }},- "content_type": ["concept", "formula", "data"],- "confidence": 0.85,- "source_quality": "high/medium/low"- }}-- **Key Principles**:- 1. Prioritize quantifiable, verifiable information- 2. Formulas and code must be preserved completely, do not simplify- 3. Convert table data to Markdown format- 4. Annotate credibility of information sources-- **Now directly output the JSON object, do not include any other content.**diff --git a/deeptutor/agents/research/prompts/en/pipeline.yaml b/deeptutor/agents/research/prompts/en/pipeline.yamlnew file mode 100644index 000000000..c758ebaf2--- /dev/null+++ b/deeptutor/agents/research/prompts/en/pipeline.yaml@@ -0,0 +1,317 @@+# Unified prompt manifest for the new ResearchPipeline.+#+# Loaded via ``get_prompt_manager().load_prompts("research", "pipeline",+# language=lang)``. The pipeline reads strings by dotted key (e.g.+# ``rephrase.system``) and renders them with ``str.format(**kwargs)``.+# Placeholders use ``{name}``; literal ``{`` / ``}`` must be doubled.++# ----------------------- UI labels (trace cards) -----------------------+labels:+ rephrase: "Clarify topic"+ decompose: "Outline sub-topics"+ research_step: "Research block"+ reasoning: "Reasoning"+ tool_call: "Tool call"+ retrieve: "Retrieve"+ note: "Summarize evidence"+ report_outline: "Plan report structure"+ report_intro: "Write introduction"+ report_section: "Write section"+ report_conclusion: "Write conclusion"+ queue_append: "Sub-topic added"+ references_heading: "References"+ addendum_title: "Additional findings"+ addendum_intent: "Covers researched blocks that did not fit cleanly into the earlier sections."++# ----------------------- Empty / fallback fillers ----------------------+empty:+ no_evidence: "(no evidence collected yet)"+ no_subtopics: "(no sub-topics)"+ no_blocks_completed: "(no completed research blocks)"+ no_conversation: "(no prior conversation)"+ no_memory: "(no relevant memory)"+ no_tools: "- none"++# ----------------------- Misc system fragments -------------------------+system:+ warning_prefix: "⚠ "+ kb_system_note: "Attached knowledge bases: {kb_name}. When calling rag, kb_name must be {kb_name_repr}."++# --------------------- Notices (stream.progress) -----------------------+notices:+ protocol_retry: "The model violated the action-label protocol; retrying."+ empty_tool_result: "Tool returned no result."+ start_retrieval: "Starting retrieval"+ tool_unknown_error: "Error executing {tool}."+ too_many_tool_calls: "Requested {requested} tool calls; capped at {limit}."+ max_iterations_reached: "Reached the iteration ceiling for this block; forcing FINISH."+ rephrase_cap_reached: "ask_user limit reached ({max_rounds} rounds). Emit FINISH now with the best refined topic you can produce from prior answers."+ rephrase_only_ask_user: "Inside rephrase you may only call `ask_user`; `{tool}` is ignored."+ append_rejected_empty: "APPEND rejected: provide a title on the first line after the label."+ append_rejected_full: "APPEND rejected: the topic queue is at capacity. Continue researching the current block and emit FINISH when done."+ append_rejected_full_progress: "Queue is full; rejected append: {title}"+ append_rejected_duplicate: "APPEND rejected: too similar to existing block {existing_id} ({existing_title!r})."+ append_rejected_dup_progress: "APPEND rejected: {title} is too similar to existing block {existing}"+ append_accepted: "Appended block {new_block_id}: {title}"+ append_accepted_progress: "Sub-topic queued: {title} (new block {new_block_id})"++# ------------------------ Protocol repair copy -------------------------+protocol:+ missing_label: |+ Your previous reply did not start with an action label. Reply with exactly one allowed label on the first line, wrapped in double backticks (e.g. ``THINK``), followed by the post-label content.+ multiple_labels: |+ Your previous reply contained more than one action label. Emit exactly one label on the first line.+ tool_without_calls: |+ You used ``TOOL`` but produced no tool calls. Either emit real tool calls or switch to ``THINK`` / ``FINISH`` / ``APPEND``.+ think_with_tools: |+ ``THINK`` is reasoning-only — no tool calls. Drop the tool calls or use ``TOOL`` instead.+ finish_with_tools: |+ ``FINISH`` is terminal — no tool calls. Finish without tools, or emit ``TOOL`` and FINISH on the next turn.+ finish_without_tool: |+ You tried to ``FINISH`` before collecting evidence. The block has research tools available, so your next turn MUST be ``TOOL`` with at least one evidence-gathering call. Do not answer from memory.+ label_with_tools: |+ Tool calls are only allowed on a ``TOOL`` turn. Switch the label or drop the tool calls.+ unknown_action: |+ Unrecognised label. Use one of the allowed labels exactly as written.+ force_finish: |+ You have reached the maximum number of iterations for this block. Stop calling tools and produce a single ``FINISH`` response consolidating what you have learned.+ force_finish_repair: |+ The previous forced-finish reply still violated the protocol. Reply with exactly one ``FINISH`` label on the first line; no tool calls, no other labels.+ fallback_final: |+ Unable to produce a clean FINISH; falling back to a minimal closing note for this block.++# =======================================================================+# Phase 1 — Rephrase (mini agentic loop with ask_user)+# =======================================================================+rephrase:+ system: |+ You are the planning host for a deep-research workflow. Your job in this phase is to make sure the research topic is precise enough for the downstream research and reporting agents — but with as few questions to the user as possible.++ Emit exactly one of these labels per reply on the first line, wrapped in double backticks (``LABEL``):++ - ``THINK`` — reflect privately on what is still ambiguous. The post-label text is internal scratchpad and not shown to the user.+ - ``TOOL`` — call the ``ask_user`` tool to ask 1-{max_questions_per_round} questions in one card. The only tool available in this phase is ``ask_user``.+ - ``FINISH`` — terminate the rephrase phase. **The post-label text streams live into the chat bubble body — the user sees it.** Write a brief, user-facing confirmation of what you'll research (e.g. "Got it — I'll focus on X, covering …"). It also serves as the topic input for the decompose phase, so it must be concrete, well-scoped, and directly decomposable.++ Hard rules:+ - You may call ``ask_user`` at most {max_rounds} times.+ - Each ``ask_user`` call carries at most {max_questions_per_round} questions.+ - Each question should offer 3-5 suggested options as quick-pick chips.+ - If the user's original topic is already clear, FINISH immediately without asking anything. Do not invent ambiguity to justify questions.+ - If the user skips a question (``(skipped)``), respect their preference and either ask follow-ups in a later round or FINISH.+ - Do not paste the user's original topic verbatim into FINISH — restate it as a sharper, more specific research target.+ - Keep the FINISH body short (3-6 sentences). The decompose and report phases do the heavy lifting later.++ Original topic to refine: "{topic}"+ user_template: |+ Original topic from user:++ {topic}++ Decide whether you need any clarifying question. If yes, emit ``TOOL`` with an ``ask_user`` call. Otherwise emit ``FINISH`` with the refined research target.++# =======================================================================+# Phase 2 — Decompose+# =======================================================================+decompose:+ system: |+ Decompose the refined research topic into sub-topics. Each sub-topic is one focused angle that downstream research blocks will investigate independently and (when configured) in parallel. Sub-topics must be:+ - **Disjoint** — no overlap with each other.+ - **Collectively exhaustive** — together they cover the topic.+ - **Actionable** — a researcher can immediately know what to look for.++ **Output protocol (strict)**: the very first line of your reply must be the literal label ``OUTLINE`` (wrapped in double backticks). Do NOT prepend any preamble, heading, explanation, or markdown decoration. The next line begins the JSON payload with this exact shape:++ {{+ "sub_topics": [+ {{"title": "concise heading", "overview": "1-2 sentences on what this sub-topic covers"}}+ ]+ }}++ Order the sub-topics so a reader can follow the natural flow (background → core → extensions / implications). Emit nothing outside the OUTLINE label and the JSON.+ user_template: |+ Refined research topic:++ {topic}++ Produce a JSON outline with approximately {num_subtopics} sub-topics now.++# =======================================================================+# Phase 3 — Per-block research (agentic loop)+# =======================================================================+research_step:+ system: |+ You are researching one sub-topic of a larger investigation.++ Overall research topic:+ > {topic}++ Your specific sub-topic:+ > **{block_title}** — {block_overview}++ Output mode for the eventual report: ``{mode}``. Match its tone and granularity.++ On each turn emit exactly one of these labels on the first line, wrapped in double backticks (``LABEL``):++ - ``THINK`` — reflect on what you know, what is still missing, what to look up next. No tool calls. The post-label text is private scratch.+ - ``TOOL`` — call one or more tools (see the tool list below). On a TOOL turn emit only tool calls; no prose final answer.+ - ``APPEND`` — propose a NEW, distinct sub-topic worth its own block. The first line after the label is the new block's title; subsequent lines (optional) are a short overview. Use this when you discover a tangent that deserves dedicated research rather than being a detail inside this block. Do NOT use APPEND for sub-questions of THIS block; investigate those with TOOL.+ - ``FINISH`` — terminate this block. The post-label text is the consolidated knowledge summary for this sub-topic: short paragraphs, concrete facts, and inline ``[CIT-...]`` markers referring to evidence (the report layer resolves them). **Every ``[CIT-...]`` MUST map to an actual tool result you obtained in this block. Never fabricate citation IDs or use them when no tool call backs them up.**++ Hard rules:+ - One label per reply, always on the first line.+ - Inside this block you may emit at most {max_iterations} turns.+ - Do not call ``ask_user`` in this phase; clarifications happened earlier. Pick the most useful tool, or APPEND, or FINISH.+ - **When the "Tools available" list below is non-empty, you MUST issue at least one ``TOOL`` call to collect evidence before you FINISH.** Answering straight from training data is a protocol violation: this block exists to retrieve citable evidence.+ - If you decide the next action is search/retrieval/code, do not merely say "I will use TOOL"; actually choose ``TOOL`` and emit native tool calls.+ - Once a tool result already covers the sub-topic, the next turn can be FINISH — do not run extra calls just to fill the iteration budget.+ - If the "Tools available" list is empty, you may FINISH directly, but state plainly in the body that no external evidence was retrieved and DO NOT invent ``[CIT-...]`` markers.++ {kb_note}++ Tools available to you on this block:+ {tool_list}+ user_template: |+ Existing knowledge gathered for this block so far:++ {accumulated_knowledge}++ Already-queued sibling sub-topics (do NOT duplicate these in APPEND):+ {sibling_topics}++ Decide your next move now. Reply with one labeled turn.++# =======================================================================+# Note Agent — post-tool summarisation (citation sidecar)+# =======================================================================+note:+ system: |+ You are summarising a single tool result into a short, dense note that the research agent will see in subsequent turns INSTEAD of the raw tool output. The note must:++ - faithfully preserve facts, numbers, and named entities,+ - drop boilerplate, navigation chrome, and unrelated content,+ - be 4-10 sentences (shorter if the source is thin).++ Emit exactly one ``FINISH`` label on the first line; everything below is the summary body.+ user_template: |+ Tool: `{tool_name}`+ Query: {query}++ Raw tool result:++ {raw_answer}++# =======================================================================+# Phase 4 — Reporting (sequence of one-shot labeled steps)+# =======================================================================+report:+ outline:+ system: |+ You are planning the final report's structure from a pile of finished research blocks. Each block has an id, a sub-topic title, and a short knowledge preview.++ Emit exactly one ``OUTLINE`` label on the first line, then a JSON object below with this exact shape:++ {{+ "title": "concise report title",+ "sections": [+ {{+ "id": "S1",+ "title": "section heading",+ "intent": "1-2 sentences on what this section covers",+ "block_ids": ["block_1", "block_3"]+ }}+ ]+ }}++ Rules:+ - Every research block must appear in at least one section's ``block_ids`` — do not silently drop blocks. A single block MAY feed multiple sections when its evidence is cross-cutting.+ - Sections should read in a coherent order (background → core → implications / comparisons).+ - Use plain text titles only. Do not include ``##``, ``[S1]``, ``1.``, or other numbering / markdown markers in ``title`` fields.+ - Aim for 3-6 sections.+ user_template: |+ Topic: {topic}++ Research blocks available:++ {block_summaries}++ Plan the report outline now.+ intro:+ system: |+ Write the introduction of the report. This is not throat-clearing: it should establish the motivating problem, boundaries, and reading path for the whole report.++ Writing requirements:+ - Be substantial: use 3-5 focused paragraphs to explain why the question matters, what definitions or tensions shape it, and how the report will decompose it.+ - Do not merely restate the outline. Extract a clear central claim or analytical frame so the reader knows what the report will answer.+ - You may use a few bullet points to preview the dimensions covered, but do not turn the introduction into a mechanical list.+ - If the topic involves technical, business, or quantitative relationships, introduce the key terms, variables, or evaluation dimensions naturally; do not invent specific facts that are not grounded in the provided context.+ - **The introduction body MUST start with a single H2 heading**: ``## {section_number}. Introduction`` (i.e. section number {section_number}, title "Introduction"). Emit the heading exactly once. Never produce ``## ## ...`` and never drop the leading ``{section_number}.`` number.+ - **Do NOT use any H3 sub-headings inside the introduction** (no ``### {section_number}.1 ...``, no ``### ...``). Write the introduction as flowing paragraphs; a few bullet points are fine, but do not slice it into numbered sub-sections.++ Emit exactly one ``INTRO`` label on the first line; everything below is the introduction body in markdown.+ user_template: |+ Topic: {topic}+ Report title: {title}++ Introduction number: {section_number} (i.e. section {section_number} of the report).++ Section outline (titles + intent):++ {sections_overview}++ Write the introduction now.+ section:+ system: |+ Write ONE section of the final report.++ Rules:+ - Make the section as substantial as the evidence allows: develop definitions, background, mechanisms, boundary conditions, examples / counterexamples, implementation paths, risks, trade-offs, and unresolved questions. Do not stop after a few generic sentences.+ - Write a dense analytical section: lead with a claim or definition, then develop the reasoning chain. Do not make every section a generic ``1. 2. 3.`` list.+ - Use coherent paragraphs as the backbone, and use Markdown rich formats when they genuinely clarify the content: tables for comparisons / trade-offs, bullets for taxonomies / checklists, numbered lists for true sequences, Mermaid for workflows / architectures / causal chains, and LaTeX equations for meaningful quantitative relationships.+ - Rich formatting must serve comprehension, not decoration. Usually 1-2 structured elements per section is enough; if evidence is thin, explain uncertainty rather than padding or fabricating detail.+ - Use the consolidated knowledge in the evidence block as your only source of facts. Each ``#### Evidence [CIT-...]`` item is a citeable source. Inline citations as ``[CIT-...]`` markers — **copy them verbatim** from the evidence; never invent IDs.+ - Attach citations precisely to the sentence they support. Do not dump a long citation cluster at the end of a paragraph.+ - If the evidence contains NO ``[CIT-...]`` markers (research phase retrieved nothing for this section), write the section without any ``[CIT-...]`` at all, and append a short final note: "No external evidence was retrieved for this section; the conclusions reflect the model's prior knowledge."+ - Preserve concrete facts, numbers, and named entities — do not smudge them into vague claims.+ - Do not duplicate content already covered by sibling sections.+ - **The section body MUST start with a single H2 heading**: ``## {section_number}. <section title>`` (i.e. this section is number {section_number}). Emit the heading exactly once. Never produce ``## ## ...``; never keep ``[S1]``-style internal IDs; never drop the leading ``{section_number}.`` number.+ - For sub-sections within this section, use H3 headings prefixed with this section's number: ``### {section_number}.1 <sub-title>``, ``### {section_number}.2 <sub-title>`` — do NOT restart sub-numbering at 1 across sections.++ Emit exactly one ``SECTION`` label on the first line; everything below is the section body in markdown.+ user_template: |+ Topic: {topic}+ Report title: {report_title}++ Section [{section_id}]: {section_title}+ Section number: {section_number} (i.e. section {section_number} of the report)+ Intent: {section_intent}++ Evidence for THIS section:++ {evidence}++ Write the section now.+ conclusion:+ system: |+ Write the conclusion of the report. It should read like a synthesis and judgement, not a simple recap.++ Writing requirements:+ - Use 4-6 focused paragraphs to integrate the core conclusions across sections and show how they reinforce or constrain each other.+ - Answer the most important question posed by the research topic. If evidence is incomplete, distinguish reliable conclusions from claims that still need validation.+ - When useful, add follow-up research directions, decision criteria, implementation recommendations, or a risk checklist. Use sparse bullets when they improve scanability; avoid a templated ending.+ - You may include a compact table such as "Known conclusion / evidence strength / still to validate", but only if it genuinely improves readability.+ - **The conclusion body MUST start with a single H2 heading**: ``## {section_number}. Conclusion`` (i.e. this is the last section, number {section_number}). Emit the heading exactly once.+ - **Do NOT use any H3 sub-headings inside the conclusion** (no ``### {section_number}.1 ...``, no ``### ...``). Write the conclusion as flowing paragraphs; a few bullets or one compact table are fine, but do not slice it into numbered sub-sections.++ Emit exactly one ``CONCLUSION`` label on the first line; everything below is the conclusion body in markdown.+ user_template: |+ Topic: {topic}+ Report title: {title}++ Conclusion number: {section_number} (i.e. the final section, section {section_number} of the report).++ Section recap:++ {sections_recap}++ Write the conclusion now.diff --git a/deeptutor/agents/research/prompts/en/rephrase_agent.yaml b/deeptutor/agents/research/prompts/en/rephrase_agent.yamldeleted file mode 100644index 46be71116..000000000--- a/deeptutor/agents/research/prompts/en/rephrase_agent.yaml+++ /dev/null@@ -1,85 +0,0 @@-# RephraseAgent Prompt Configuration (English)--system:- role: |- You are a research topic optimization expert, responsible for transforming user research needs into clear, specific, and executable research topics.--mode_contracts:- study_notes_rephrase: |- YOU MUST reframe the request as a **learning goal**, NOT a research thesis.- - The rephrased topic MUST answer: "After studying this, the learner should be able to explain/do X."- - Focus on teachability, memorability, and core understanding.- - Surface likely confusion points and core ideas worth clarifying.- - NEVER produce a topic that sounds like a report title (e.g. "A Comprehensive Analysis of…").- - Example good output: "Understand how gradient descent works: the intuition, the math, common pitfalls, and when to use variants."- report_rephrase: |- YOU MUST reframe the request as a **formal research/analysis topic** with explicit scope.- - Clarify the central question, boundary of investigation, and analytical angle.- - The result must naturally lead to a structured synthesis report.- - NEVER produce a topic that sounds like a study guide or learning path.- comparison_rephrase: |- YOU MUST reframe the request as a **comparison task** with explicit structure.- - The rephrased topic MUST name: (a) the alternatives being compared, (b) the evaluation criteria, (c) the decision scenario.- - Example good output: "Compare PyTorch vs TensorFlow vs JAX for production ML: ease of use, performance, ecosystem, and deployment."- - NEVER produce a topic that would lead to separate summaries of each option.- learning_path_rephrase: |- YOU MUST reframe the request as a **learning-path design task**.- - The rephrased topic MUST specify: (a) the target learner profile, (b) the end-goal competency, (c) the expected progression direction.- - Example good output: "Design a learning path for a Python developer to become proficient in machine learning: from math foundations through core algorithms to real-world projects."- - NEVER produce a topic that sounds like a report or static overview.--process:- rephrase: |- Analyze and optimize the following user input. Only output JSON object:-- User Input: {user_input}- Iteration Count: {iteration}- {previous_result}-- **Mode-Specific Focus**:- {mode_instruction}-- **Optimization Dimensions:**-- 1. **Research Topic**: Transform into a clear, specific, researchable topic- 2. **Research Focus**: Identify core issues and key elements- 3. **Research Scope**: Clarify boundaries, define depth and breadth- 4. **Optimization Rationale**: Explain optimization basis and logic-- Based on the above considerations, generate a research objective with prominent theme, clear focus, and well-defined scope, with length not exceeding twice the user input.-- Output JSON:- {{- "topic": "A clear, complete research topic description"- }}-- Requirements:- 1. topic must be coherent text that can independently express complete information- 2. When iteration = 0, provide reasonable focus and optimization- 3. When iteration > 0, adjust based on user feedback-- check_satisfaction: |- Analyze user feedback on the rephrasing result. Only output JSON object:-- Current Result:- - Topic: {topic}-- User Feedback: {user_feedback}-- **Judgment Dimensions:**- 1. Whether the user explicitly expresses satisfaction/dissatisfaction- 2. Whether specific modification requirements are proposed- 3. Whether feedback is positive or negative-- Output JSON:- {{- "user_satisfied": true/false,- "should_continue": true/false,- "interpretation": "Interpretation of user intent",- "suggested_action": "Suggested next action"- }}-- Judgment Criteria:- - Satisfied, agree, okay, good → user_satisfied = true, should_continue = false- - Request modification or raise opinions → user_satisfied = false, should_continue = true- - Ambiguous feedback → tend to continue optimizationdiff --git a/deeptutor/agents/research/prompts/en/reporting_agent.yaml b/deeptutor/agents/research/prompts/en/reporting_agent.yamldeleted file mode 100644index c8f14c565..000000000--- a/deeptutor/agents/research/prompts/en/reporting_agent.yaml+++ /dev/null@@ -1,1064 +0,0 @@-# ReportingAgent Prompt Configuration - Deep Research Report Generation-# Design Goal: Generate rich, coherent, and comprehensive academic-level deep research reports--# Citation instruction templates-citation:- enabled_instruction: |- **Citation Requirements (CRITICAL)**:- - Format: Use `[N]` format where N is the reference number from the table below- - ONLY use reference numbers from the Citation Reference Table - do NOT invent numbers!- - Place citations at the end of sentences or claims that use information from that source- - DO NOT add a References section - it will be generated automatically-- **Citation Reference Table** (use these exact numbers):- {citation_table}-- **Examples**:- - "According to recent research [5], the method achieves..."- - "This approach has been validated in multiple studies [3][7]."-- disabled_instruction: |- **Citation Requirements**:- - DO NOT add any inline citations like [1], [[1]], or [N] in the text- - DO NOT add a References section at the end - references will be handled separately- - Focus on content synthesis without citation markers--system:- role: |- You are a top-tier academic writing and content integration expert, skilled at transforming complex research findings into well-structured, insightful professional reports. Your reports should exhibit the following qualities:-- **Core Writing Philosophy**:- 1. **Depth over Breadth**: Better to deeply analyze a few key points than to superficially cover many- 2. **Argumentation over Statement**: Every point should be supported by evidence, reasoning, or examples- 3. **Structured Presentation**: Use formulas, tables, flowcharts, code, and other elements to enhance expression- 4. **Academic Rigor**: Accurately cite sources, distinguish facts from inferences, acknowledge limitations-- **Important Format Requirements**:- - All outputs must strictly follow JSON format- - Only output valid JSON objects, do not include any additional text, explanations, or code block markers- - JSON must be directly parseable, cannot contain comments or format errors- - If the output contains Markdown content, include it as a JSON string value and properly escape special characters--mode_contracts:- study_notes_outline: |- - This mode must produce a revision-notes artifact, not a formal report.- - Use note-style sectioning such as key ideas, mechanisms, examples, pitfalls, and recap.- - Keep section titles short, direct, and memory-oriented.- - Do NOT structure the outline as background-method-analysis-conclusion.- study_notes_introduction: |- - Keep the opening short and orientation-first.- - State what the learner should understand after reading the notes.- - Avoid report-style scene setting or long motivation.- study_notes_section: |- - Write like a high-quality study sheet.- - Prefer bullets, short explanation bursts, worked mini-examples, pitfall lists, and key-takeaway blocks.- - Never let the section read like a long formal essay.- - For every major concept, include a definition box: `> **Definition — <Term>**: <concise definition>`- - End each section with a "Test Yourself" micro-question: `> 💡 **Test Yourself**: Can you explain <concept> without looking at the notes?`- - Where appropriate, add a memory anchor: `> 🧠 **Memory Anchor**: <mnemonic, analogy, or visual cue to aid recall>`- study_notes_conclusion: |- - End with a recap checklist or takeaway block.- - Include key takeaways and optional common mistakes.- - Add a **Self-Test Checklist**: a numbered list of core claims/concepts the learner should be able to explain from memory.- - Do not write a formal conclusion with limitations or future work.- study_notes_single_pass: |- - The full output must read like revision notes prepared for a learner.- - It should be compact, scannable, memorable, and clearly segmented for review.- - Include definition boxes, "Test Yourself" micro-questions, and memory anchors throughout.- - End with a Self-Test Checklist of core concepts to verify recall.- - The finished artifact should feel optimized for understanding, recall, and quick revision.-- report_outline: |- - This mode must produce a formal synthesis report.- - Use a conventional analytical structure: context, major themes, analysis, synthesis, conclusion.- - Do not turn it into a notes sheet, comparison matrix, or staged roadmap.- report_introduction: |- - Write a formal introduction covering motivation, scope, and report organization.- - The tone should be analytical and report-like.- report_section: |- - Write sustained analytical prose with clear transitions and synthesized evidence.- - Sections should feel like chapters of a report, not note fragments or stage instructions.- report_conclusion: |- - End with a proper synthesis-style conclusion.- - Summarize findings, implications, limitations, and the final analytical takeaway.- report_single_pass: |- - The final output must read like a proper report with consistent analytical prose and report structure.- - The finished artifact should feel optimized for analysis, synthesis, and evidence-based explanation.-- comparison_outline: |- - This mode must produce a comparison deliverable, not a generic report.- - Organize the outline by comparison dimensions or evaluation criteria.- - Include explicit space for trade-offs, strengths, weaknesses, and scenario fit.- - A comparison matrix or table should be naturally expected in the structure.- comparison_introduction: |- - Clearly define what is being compared, why it matters, and which comparison criteria will be used.- comparison_section: |- - Every main section must compare alternatives side by side.- - Use dimension-based analysis, explicit contrasts, tables, and scenario-based judgments.- - Do not drift into isolated topic summaries.- - For each comparison dimension, assign a quantitative score (1-5) to every option. Present scores in a mini table.- - Format: `| Criterion | Option A | Option B | ... |` with numeric scores.- comparison_conclusion: |- - End with a verdict and recommendation by scenario, constraint, or priority.- - Make selection guidance explicit.- - Include a **Scoring Summary Table** that aggregates all per-dimension scores into one table:- `| Dimension | Option A | Option B | ... | (with numeric 1-5 scores)`- - Below the table, state overall weighted impressions and scenario-based recommendations.- comparison_single_pass: |- - The whole output must be dimension-first, trade-off-heavy, and recommendation-oriented.- - It should feel unmistakably like a comparison document.- - Include quantitative 1-5 scores per dimension per option, and a scoring summary table in the conclusion.- - The finished artifact should help a reader make a decision under explicit scenarios or constraints.-- learning_path_outline: |- - This mode must produce a staged learning roadmap.- - Organize the outline by progression: prerequisites, stage 1, stage 2, stage 3, practice, milestones, next steps.- - Do not use generic topical report chapters as the primary structure.- learning_path_introduction: |- - Define the learner profile, prerequisite assumptions, and expected progression.- - Make the roadmap intent obvious from the start.- learning_path_section: |- - Write as a study roadmap, not a report.- - Make sequence, prerequisites, exercises, checkpoints, milestones, and what-to-study-next explicit.- - Every section should help the learner act, not just understand.- - Start each stage with metadata: `> ⏱️ **Estimated Time**: X hours` and `> 📊 **Difficulty**: Foundation / Intermediate / Advanced`- - Include a **Recommended Resources** block: `> 📚 **Resources**: [books, courses, tools, or links]`- learning_path_conclusion: |- - End with milestone checks, next-step advice, and how to continue after completing the path.- - Include a Mermaid roadmap diagram showing the stage progression:- ```mermaid- graph LR- A[Stage 1: ...] --> B[Stage 2: ...]- B --> C[Stage 3: ...]- ```- - Below the diagram, summarize total estimated time and a final competency checklist.- learning_path_single_pass: |- - The final output must read like a staged study plan with progression logic, checkpoints, exercises, and sequence.- - Each stage must include estimated time, difficulty label, and recommended resources.- - End with a Mermaid roadmap diagram and total time estimate.- - The finished artifact should help a learner decide what to do first, next, and how to judge progress.--process:- deduplicate: |- Analyze the following topic list and identify duplicate or highly similar topics.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Topic List:- {topics}-- Total Topics: {total_topics}-- **Analysis Steps:**- 1. Understand the core content and research perspective of each topic- 2. Identify semantically duplicate or highly similar topics (Note: same concept with different perspectives is NOT duplication)- 3. Keep the most representative and content-rich topics-- **Output Format Requirements (Strictly Follow):**- - Only output JSON object, do not use ```json code block wrapper- - Do not add any explanatory text- - Ensure JSON format is completely valid and can be directly parsed-- Output Example (for format reference only, do not copy content):- {{- "duplicates": [{{"indices": [0, 3], "reason": "Semantic duplication: both discuss basic principles of XX"}}],- "keep_indices": [0, 1, 2, 4],- "summary": "Kept 4 complementary topics covering theoretical foundations, technical implementation, application scenarios, and frontier developments"- }}-- **Now directly output the JSON object, do not include any other content.**-- generate_outline: |- Generate a structured three-level heading system outline for the following research.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Research Topic: {topic}-- Research Topics (including subtopic, overview, and tool_summaries):- {topics_json}-- Total Topics: {total_topics}-- **Outline Design Principles**:-- 1. **Three-Level Heading System**:- - Level 1 (#): Report main title- - Level 2 (##): Major sections (Introduction, Core Sections 1-N, Conclusion)- - Level 3 (###): Subsections within each section- - Level 4 (####): Further subdivisions (optional, for complex sections)-- 2. **Logical Structure Design**:- - Identify logical relationships between topics: hierarchy, dependency, parallel, progression, comparison- - Order by cognitive flow: Concept → Principles → Methods → Applications → Evaluation → Outlook- - Ensure clear transition logic between sections-- 3. **Section Design Guidelines**:- - Each main section should have a clear research question or objective- - Subsections should cover core dimensions of the topic- - Instructions should specify key elements to include and presentation approach-- **Output Format Requirements (Strictly Follow):**- - Only output JSON object, do not use ```json code block wrapper- - Do not add any explanatory text-- Output Example (for format reference only, do not copy content):- {{- "title": "# Report Main Title: Precisely Express Research Topic",- "introduction": "## Introduction",- "introduction_instruction": "Present research background, problem motivation, research objectives, and report structure",- "sections": [- {{- "title": "## 1. First Main Section Title",- "instruction": "This section focuses on... should include principle derivation and key formulas",- "block_id": "block_1",- "subsections": [- {{- "title": "### 1.1 Subsection Title",- "instruction": "Explain in detail... recommend using comparison tables"- }},- {{- "title": "### 1.2 Subsection Title",- "instruction": "Analyze... recommend using flowcharts"- }}- ]- }}- ],- "conclusion": "## Conclusion and Future Directions",- "conclusion_instruction": "Summarize core findings, research contributions, limitations, and future directions"- }}-- **Now directly output the JSON object, do not include any other content.**-- write_introduction: |- Write the introduction section of the research report.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Research Topic: {topic}- Introduction Guidance: {introduction_instruction}- Research Topics Overview: {topics_summary}- Total Topics: {total_topics}-- **Introduction Writing Framework** (400-600 words):-- 1. **Opening Statement** (Paragraph 1):- - Start from macro background or important trends- - Introduce core challenges or opportunities in the research field- - Highlight the necessity and urgency of the research-- 2. **Problem Focus** (Paragraph 2):- - Clearly state the specific problems this research addresses- - Explain limitations of existing methods or understanding- - Introduce core research objectives-- 3. **Research Scope** (Paragraph 3):- - Outline the main dimensions covered by the research- - Explain the logical relationships between different parts- - Preview core findings or contributions (optional)-- 4. **Structure Guide** (Paragraph 4):- - Briefly introduce the organization of report sections- - Help readers build reading expectations-- **Writing Requirements**:- - Use academic but accessible language- - Each paragraph should have a clear topic sentence- - Natural transitions between paragraphs- - Do not use section headings, write body content directly-- **Output Format Requirements (Strictly Follow):**- - Only output JSON object, do not use ```json code block wrapper- - Special characters in JSON strings (such as quotes, newlines) must be properly escaped-- Output Example:- {{- "introduction": "Complete introduction content (Markdown format, without heading, 400-600 words)"- }}-- **Now directly output the JSON object, do not include any other content.**-- write_section_body: |- Write in-depth section content based on research data.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Research Topic: {topic}- Section Title: {section_title}- Writing Guidance: {section_instruction}- Data Source: {block_data}-- **Deep Writing Framework**:-- ## Step 1: In-Depth Material Analysis-- 1. **Information Classification**:- - **Core Layer**: Key definitions, core formulas, main conclusions → Must present completely- - **Supporting Layer**: Derivation processes, experimental data, case analyses → Selectively elaborate- - **Background Layer**: Historical evolution, related work → Briefly mention-- 2. **Information Credibility Assessment**:- - Priority: peer-reviewed papers > authoritative textbooks > technical documentation > web resources- - Conflict handling: Note different viewpoints, or choose most recent/authoritative source-- ## Step 2: Structured Organization-- **Three-Level Heading System** (Must Follow):- - Use `##` as the main section heading- - Use `###` to organize sub-topics (2-4 is ideal)- - Complex sub-topics can use `####` for further subdivision-- **Logical Architecture Patterns** (Choose the most suitable one):- - **Deductive**: Principles → Corollaries → Applications → Validation- - **Inductive**: Phenomena → Analysis → Patterns → Theory- - **Comparative**: Method A vs Method B → Pros/Cons Analysis → Applicable Scenarios- - **Problem-Oriented**: Problem → Existing Solutions → Limitations → Improvement Ideas-- ## Step 3: Multi-Modal Element Usage-- **Must selectively use the following elements based on content characteristics**:-- 1. **Mathematical Formulas** (LaTeX format):- - Inline formula: `$E = mc^2$`- - Block formula:- ```- $$- \mathcal{L} = \sum_{i=1}^{n} \ell(y_i, f(x_i)) + \lambda \Omega(f)- $$- ```- - Applicable: definitions, theorems, derivations, optimization objectives, etc.-- 2. **Tables** (Markdown format):- - Applicable: multi-dimensional comparisons, parameter configurations, experimental results, classification summaries- - Format example:- ```- | Method | Accuracy | Efficiency | Use Case |- |--------|----------|------------|----------|- | A | 95% | Fast | Real-time systems |- | B | 98% | Slow | Offline analysis |- ```-- 3. **Flowcharts** (Mermaid format):- - Applicable: algorithm flows, system architectures, decision logic, data flows- - Format example:- ```mermaid- graph TD- A[Input] --> B{{Processing}}- B --> C[Output]- ```-- 4. **Code Blocks**:- - Applicable: algorithm implementations, configuration examples, API calls- - Must specify language type (python/javascript/sql, etc.)-- 5. **Lists and Hierarchy**:- - Ordered lists: steps, rankings, priorities- - Unordered lists: features, elements, options- - Nested lists: hierarchical relationships, classification systems-- ## Step 4: Academic Writing Standards- {citation_instruction}-- 1. **Deep Paraphrasing**:- - Avoid direct copying, reorganize with academic language- - Example transformation:- - Original: "Method X works well"- - Revised: "Experimental results demonstrate that Method X achieves significant improvement in metric Y, with a Z% increase over the baseline approach"-- 2. **Argument Completeness**:- - Each core point should have: Claim → Evidence → Analysis → Summary- - Use appropriate transition sentences to connect paragraphs-- 3. **Technical Terminology Handling**:- - Provide definition or explanation when first mentioned- - Can use "term (original English)" format-- **Output Format Requirements (Strictly Follow):**- - Only output JSON object, do not use ```json code block wrapper- - Newlines in JSON strings should use \n escape- - Ensure JSON format is completely valid-- Output Example:- {{- "section_content": "## Section Title\n\nOpening paragraph...\n\n### 1.1 Subsection Title\n\nContent...\n\n### 1.2 Subsection Title\n\nContent...{citation_output_hint}"- }}-- **Word Count Requirement**: Each section should be at least 800 words, with comprehensive and thorough discussion-- **Now directly output the JSON object, do not include any other content.**-- write_conclusion: |- Write the conclusion section of the research report.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Research Topic: {topic}- Conclusion Guidance: {conclusion_instruction}- Key Findings: {topics_findings}- Total Topics: {total_topics}-- **Conclusion Writing Framework** (500-700 words):-- 1. **Research Review and Core Findings** (Paragraphs 1-2):- - Briefly review research questions and methods- - Systematically summarize core findings from each chapter- - Synthesize into overall conclusions-- 2. **Research Contributions and Value** (Paragraph 3):- - **Theoretical Contributions**: Advances in domain understanding- - **Methodological Contributions**: New methods, frameworks, or tools- - **Practical Value**: Guidance for real-world applications-- 3. **Limitations and Reflections** (Paragraph 4):- - Honestly point out research limitations- - Explain constraints of data, methods, or scope- - Indicate boundaries of conclusion applicability-- 4. **Future Outlook** (Paragraph 5):- - Identify open problems to be solved- - Propose valuable research directions- - Outlook on field development trends-- **Writing Requirements**:- - Conclusion should be highly summarized, avoid repeating text details- - Demonstrate critical thinking, do not avoid limitations- - Outlook should be specific and feasible, not generic- - Do not use section headings, write body content directly-- **Output Format Requirements (Strictly Follow):**- - Only output JSON object, do not use ```json code block wrapper- - Special characters in JSON strings must be properly escaped-- Output Example:- {{- "conclusion": "Complete conclusion content (Markdown format, without heading, 500-700 words)"- }}-- **Now directly output the JSON object, do not include any other content.**-- write_full_report: |- Write the complete research report in one pass.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Research Topic: {topic}- Outline JSON:- {outline_json}-- Block Data:- {blocks_json}-- Total Topics: {total_topics}-- Citation Instruction:- {citation_instruction}-- **Requirements**:- 1. Follow the outline structure closely:- - Keep the main title- - Include introduction, main sections, and conclusion- - Preserve section hierarchy (`#`, `##`, `###`) where appropriate- 2. Synthesize the block summaries into a coherent report- 3. Keep the report concise but substantial; do not add a References section- 4. If citation numbers are present in traces, use them in `[N]` format only- 5. Return the full Markdown report as one string-- Output Example:- {{- "report": "# Title\n\n## Introduction\n\n...\n\n## Section\n\n...\n\n## Conclusion\n\n..."- }}-- **Now directly output the JSON object, do not include any other content.**-- # New: Subsection writing prompt (for Level 3 heading content)- write_subsection: |- Write subsection content based on parent section context.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Research Topic: {topic}- Parent Section Title: {parent_section_title}- Subsection Title: {subsection_title}- Writing Guidance: {subsection_instruction}- Related Data: {subsection_data}-- **Writing Requirements**:-- 1. **Content Positioning**:- - Focus on the specific topic of the subsection- - Maintain logical coherence with the parent section- - Avoid content overlap with other subsections-- 2. **Depth Requirements**:- - Provide specific technical details or case analyses- - Appropriately use formulas, tables, charts, and other elements- - Arguments should be well-reasoned and evidence-based-- 3. **Format Standards**:- - Use `###` as subsection heading- - Can use `####` for further subdivision (optional)- - Clear paragraphs with distinct logic-- **Output Format Requirements (Strictly Follow):**- - Only output JSON object- - Newlines in JSON strings should use \n escape-- Output Example:- {{- "subsection_content": "### Subsection Title\n\nContent...\n\n#### Sub-topic (optional)\n\nContent..."- }}-- **Word Count Requirement**: Each subsection should be 300-500 words-- **Now directly output the JSON object, do not include any other content.**-- # ============================================================- # STUDY NOTES — mode-specific process templates- # ============================================================-- generate_outline_study_notes: |- Create a study-notes outline for the following topic.-- **Important: You must only output a valid JSON object, do not include any other text, explanations, or code block markers.**-- Topic: {topic}-- Research Topics (including subtopic, overview, and tool_summaries):- {topics_json}-- Total Topics: {total_topics}-- **STUDY NOTES Outline Rules** (follow strictly):-- 1. **DO NOT** use a report-style structure (Introduction → Analysis → Conclusion).- 2. Organize by **learning units**: group content around concepts, mechanisms, examples, and pitfalls.- 3. Section titles must be **short, direct, and memory-oriented** — e.g. "Key Idea: X", "How It Works", "Watch Out", "Quick Reference".- 4. Include a **Quick Reference / Cheat Sheet** section at the end.- 5. Sections should feel like a well-organized notebook, not chapters of an essay.-- Output JSON (match this shape exactly):- {{- "title": "# Study Notes: Topic Title",- "introduction": "## What These Notes Cover",- "introduction_instruction": "In 2-3 sentences state what the learner will understand after reading these notes. No formal introduction.",- "sections": [- {{- "title": "## Note 1. Section Title",- "instruction": "Cover the key idea, definition, mechanism, and a concrete mini-example for this concept.",- "block_id": "block_1",- "subsections": [- {{ "title": "### What It Means", "instruction": "Definition and intuition" }},- {{ "title": "### How It Works", "instruction": "Core mechanism with a mini-example" }},- {{ "title": "### Common Mistakes", "instruction": "Pitfalls and misconceptions" }}- ]- }}- ],- "conclusion": "## Quick Reference",- "conclusion_instruction": "Provide a scannable summary: key terms with one-line definitions, the 3-5 most important takeaways, and a list of common pitfalls to avoid."- }}-- **Now directly output the JSON object, do not include any other content.**-- write_introduction_study_notes: |- Write a short orientation for study notes.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Orientation Guidance: {introduction_instruction}- Topics Overview: {topics_summary}- Total Topics: {total_topics}-- **Rules**:- - Write **2-4 sentences only**. No formal introduction.- - State what the notes cover and what the reader should be able to do/explain after reading.- - Optionally mention prerequisites.- - Tone: friendly, direct, like a tutor speaking to a student.-- Output:- {{- "introduction": "Short orientation text (2-4 sentences, no heading)"- }}-- **Now directly output the JSON object.**-- write_section_body_study_notes: |- Write a study-note section. The output must look and feel like high-quality revision notes — NOT an essay or report chapter.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Section Title: {section_title}- Writing Guidance: {section_instruction}- Data Source: {block_data}-- **Study Notes Writing Rules** (MANDATORY):-- 1. **Structure**: Use short paragraphs, bullet lists, numbered steps, and callout blocks. NEVER write long unbroken prose.- 2. **Definition Boxes**: For every key term, use:- ```- > **Definition — Term**: One-sentence explanation.- ```- 3. **Mini-Examples**: Include at least one concrete worked example per section. Use code blocks, math, or step-by-step walkthroughs as appropriate.- 4. **Pitfall Alerts**: Mark common mistakes with:- ```- > ⚠️ **Common Mistake**: Description of the mistake and how to avoid it.- ```- 5. **Key Takeaway Block**: End each section with:- ```- > 🔑 **Key Takeaway**: The one thing to remember from this section.- ```- 6. **Tables**: Use comparison tables for contrasting concepts, parameter summaries, or method comparisons.- 7. **Formulas**: Preserve LaTeX. Inline: `$...$`. Block: `$$...$$`.- 8. **Test Yourself**: End with a micro-question that tests recall:- ```- > 💡 **Test Yourself**: Can you explain <concept> without looking at the notes?- ```- 9. **Memory Anchor**: Where helpful, provide a mnemonic, analogy, or visual cue:- ```- > 🧠 **Memory Anchor**: <mnemonic or analogy to aid recall>- ```- 10. **NEVER** write like a report: no "In this section, we examine…", no lengthy analytical prose, no formal transitions.-- {citation_instruction}-- Output:- {{- "section_content": "## Section Title\n\n> **Definition — X**: ...\n\n- Point 1\n- Point 2\n\n**Example**:\n...\n\n> ⚠️ **Common Mistake**: ...\n\n> 🧠 **Memory Anchor**: ...\n\n> 🔑 **Key Takeaway**: ...\n\n> 💡 **Test Yourself**: ...{citation_output_hint}"- }}-- **Word Count**: 400-700 words. Prioritize clarity over length.-- **Now directly output the JSON object.**-- write_conclusion_study_notes: |- Write a Quick Reference / Cheat Sheet ending for study notes.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Conclusion Guidance: {conclusion_instruction}- Key Findings: {topics_findings}- Total Topics: {total_topics}-- **Rules** (MANDATORY):- - **DO NOT** write a formal conclusion with "limitations" or "future work".- - Output a scannable reference block containing:- 1. **Key Terms Table**: Term | Definition (one row per key concept)- 2. **Top Takeaways**: Numbered list of the 3-5 most important points- 3. **Common Pitfalls**: Bullet list of mistakes to avoid- 4. **Self-Test Checklist**: Numbered list of core claims/concepts the learner should be able to explain from memory. Format: `✅ 1. Can you explain ...?`- - Keep it compact and scannable — this is a cheat sheet, not a summary essay.-- Output:- {{- "conclusion": "| Term | Definition |\n|---|---|\n| ... | ... |\n\n**Top Takeaways**\n1. ...\n2. ...\n\n**Pitfalls to Avoid**\n- ...\n\n**Self-Test Checklist**\n✅ 1. Can you explain ...?\n✅ 2. ..."- }}-- **Now directly output the JSON object.**-- write_full_report_study_notes: |- Write complete study notes in one pass.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Outline JSON:- {outline_json}-- Block Data:- {blocks_json}-- Total Topics: {total_topics}-- Citation Instruction:- {citation_instruction}-- **CRITICAL**: The output MUST read like well-organized revision notes, NOT a report.-- **Mandatory formatting elements**:- - Definition boxes: `> **Definition — Term**: ...`- - Mini-examples with code/math/steps- - Pitfall alerts: `> ⚠️ **Common Mistake**: ...`- - Key takeaway blocks: `> 🔑 **Key Takeaway**: ...`- - Test Yourself micro-questions: `> 💡 **Test Yourself**: Can you explain ...?`- - Memory anchors: `> 🧠 **Memory Anchor**: <mnemonic or analogy>`- - Comparison tables where relevant- - A Quick Reference section at the end with a terms table + top takeaways + pitfalls list + Self-Test Checklist- - Short paragraphs and bullet lists — NO long prose-- Output:- {{- "report": "# Study Notes: Title\n\n## What These Notes Cover\n...\n\n## Note 1. ...\n\n> **Definition — X**: ...\n\n...\n\n## Quick Reference\n\n| Term | Definition |\n|---|---|\n..."- }}-- **Now directly output the JSON object.**-- # ============================================================- # COMPARISON — mode-specific process templates- # ============================================================-- generate_outline_comparison: |- Create a comparison-document outline for the following topic.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}-- Research Topics (including subtopic, overview, and tool_summaries):- {topics_json}-- Total Topics: {total_topics}-- **COMPARISON Outline Rules** (follow strictly):-- 1. **Structure MUST be dimension-first**, NOT object-first. Each main section compares ALL alternatives along ONE dimension.- 2. Start with a Comparison Setup section (what is compared, why, criteria).- 3. Middle sections = one per comparison dimension or evaluation criterion.- 4. Every dimension section MUST have space for a comparison table.- 5. End with a Trade-off Summary + Recommendation by Scenario section.- 6. **NEVER** organize by describing Option A, then Option B separately.-- Output JSON:- {{- "title": "# Comparison: Topic Title",- "introduction": "## Comparison Setup",- "introduction_instruction": "Define what is being compared, why it matters, the evaluation criteria, and the target decision scenario. Keep it focused.",- "sections": [- {{- "title": "## Dimension 1. Dimension Name",- "instruction": "Compare all alternatives along this dimension. MUST include a side-by-side table, strengths/weaknesses, and scenario-fit judgment.",- "block_id": "block_1",- "subsections": [- {{ "title": "### Side-by-Side Contrast", "instruction": "Comparison table + key differences" }},- {{ "title": "### Trade-offs", "instruction": "Strengths, weaknesses, constraints" }},- {{ "title": "### Best Fit", "instruction": "Which option is best for which scenario under this dimension" }}- ]- }}- ],- "conclusion": "## Verdict & Recommendation",- "conclusion_instruction": "Provide a decision matrix table (Scenario x Option → Recommendation) and clear per-scenario recommendations."- }}-- **Now directly output the JSON object.**-- write_introduction_comparison: |- Write the Comparison Setup section.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Setup Guidance: {introduction_instruction}- Topics Overview: {topics_summary}- Total Topics: {total_topics}-- **Rules**:- - Clearly state: (a) what alternatives are compared, (b) why the comparison matters, (c) the evaluation criteria/dimensions, (d) the intended decision scenario.- - Use a bulleted criteria list.- - Keep it under 300 words. No generic scene-setting.-- Output:- {{- "introduction": "Comparison setup text (no heading)"- }}-- **Now directly output the JSON object.**-- write_section_body_comparison: |- Write a comparison-dimension section. Every section MUST compare alternatives side by side — NEVER describe one option in isolation.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Section Title: {section_title}- Writing Guidance: {section_instruction}- Data Source: {block_data}-- **Comparison Writing Rules** (MANDATORY):-- 1. **Comparison Table**: Every section MUST start with or prominently include a Markdown table comparing options:- ```- | Criterion | Option A | Option B | Option C |- |-----------|----------|----------|----------|- | ... | ... | ... | ... |- ```- 2. **Dimension Analysis**: After the table, discuss the key trade-offs, nuances, and edge cases for this dimension.- 3. **Strengths & Weaknesses**: Use explicit `**Strengths**:` and `**Weaknesses**:` sub-blocks for each option.- 4. **Quantitative Score**: For this dimension, assign each option a score from 1-5 (1=poor, 5=excellent).- 5. **Scenario-Fit Judgment**: End with a clear statement: "For scenario X, Option Y is preferable because…"- 6. **NEVER** write isolated option profiles. Every paragraph must compare.- 7. Use bold labels, tables, and structured lists. Minimize long prose.-- {citation_instruction}-- Output:- {{- "section_content": "## Dimension Title\n\n| Criterion | A | B | Score A | Score B |\n|---|---|---|---|---|\n| ... | ... | ... | 4 | 3 |\n\n**Analysis**: ...\n\n**Strengths & Weaknesses**:\n- Option A: ...\n- Option B: ...\n\n**Best fit**: For scenario X, prefer ...{citation_output_hint}"- }}-- **Word Count**: 500-800 words per dimension section.-- **Now directly output the JSON object.**-- write_conclusion_comparison: |- Write the Verdict & Recommendation section.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Verdict Guidance: {conclusion_instruction}- Key Findings: {topics_findings}- Total Topics: {total_topics}-- **Rules** (MANDATORY):- - **Scoring Summary Table**: MUST include an aggregate scoring table with 1-5 scores per dimension per option:- ```- | Dimension | Option A | Option B | Option C |- |-------------|----------|----------|----------|- | Dim 1 | 4 | 3 | 5 |- | Dim 2 | 3 | 5 | 2 |- | **Average** | **3.5** | **4.0** | **3.5** |- ```- - **Decision Matrix Table**: Include a table mapping scenarios/priorities to recommended options:- ```- | If you prioritize… | Recommended | Why |- |---------------------|-------------|-----|- | Performance | Option A | ... |- | Cost | Option B | ... |- ```- - **Per-Scenario Recommendations**: After the tables, write 2-3 sentences per scenario explaining the recommendation.- - **NEVER** write a vague "it depends" conclusion. Be specific and opinionated.- - No formal "limitations and future work" section.-- Output:- {{- "conclusion": "**Scoring Summary**\n\n| Dimension | A | B |\n|---|---|---|\n| ... | 4 | 3 |\n| **Average** | **3.5** | **4.0** |\n\n**Recommendation by Scenario**\n\n| If you prioritize… | Recommended | Why |\n|---|---|---|\n| ... | ... | ... |\n\n**Scenario 1**: ...\n\n**Scenario 2**: ..."- }}-- **Now directly output the JSON object.**-- write_full_report_comparison: |- Write a complete comparison document in one pass.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Outline JSON:- {outline_json}-- Block Data:- {blocks_json}-- Total Topics: {total_topics}-- Citation Instruction:- {citation_instruction}-- **CRITICAL**: The output MUST read like a dimension-first comparison document, NOT a generic report.-- **Mandatory elements**:- - Comparison Setup section defining what/why/criteria- - Every main section = one comparison dimension with a comparison table- - Strengths/weaknesses for each option per dimension- - Scenario-fit judgments in each section- - Verdict section with a decision matrix table + per-scenario recommendations- - NEVER describe options in isolation-- Output:- {{- "report": "# Comparison: Title\n\n## Comparison Setup\n...\n\n## Dimension 1. ...\n\n| ... | A | B |\n...\n\n## Verdict & Recommendation\n\n| If you prioritize… | Recommended | Why |\n..."- }}-- **Now directly output the JSON object.**-- # ============================================================- # LEARNING PATH — mode-specific process templates- # ============================================================-- generate_outline_learning_path: |- Create a learning-path roadmap outline for the following topic.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}-- Research Topics (including subtopic, overview, and tool_summaries):- {topics_json}-- Total Topics: {total_topics}-- **LEARNING PATH Outline Rules** (follow strictly):-- 1. **Structure MUST be stage-first and progressive**. The reader should feel a clear trajectory from beginner to competent.- 2. Start with a "Who This Path Is For" section (learner profile, prerequisites, end goal).- 3. Middle sections = sequential stages (Stage 1 → Stage 2 → Stage 3 → …). Order by prerequisite dependency — what MUST be learned before what.- 4. Each stage MUST include: learning objectives, core content, practice suggestions, and a checkpoint (how to know you're ready for the next stage).- 5. End with "Milestones & What's Next" — progress markers and continuation advice.- 6. **NEVER** organize as a flat topical report. The progression must be obvious.-- Output JSON:- {{- "title": "# Learning Path: Topic Title",- "introduction": "## Who This Path Is For",- "introduction_instruction": "Define the target learner (background, level), prerequisites, what they will be able to do after completing the path, and estimated effort.",- "sections": [- {{- "title": "## Stage 1. Stage Name",- "instruction": "Cover the foundational concepts for this stage. Include learning objectives, core content, practice plan, and a checkpoint.",- "block_id": "block_1",- "subsections": [- {{ "title": "### Learning Objectives", "instruction": "What the learner should be able to do after this stage" }},- {{ "title": "### Core Content", "instruction": "The key concepts and material for this stage" }},- {{ "title": "### Practice & Exercises", "instruction": "Hands-on activities, exercises, or projects" }},- {{ "title": "### Checkpoint", "instruction": "How to verify readiness for the next stage" }}- ]- }}- ],- "conclusion": "## Milestones & What's Next",- "conclusion_instruction": "Provide a milestone checklist covering all stages, self-assessment criteria, and guidance on where to go after completing the path."- }}-- **Now directly output the JSON object.**-- write_introduction_learning_path: |- Write the "Who This Path Is For" section of a learning path.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Learner Guidance: {introduction_instruction}- Topics Overview: {topics_summary}- Total Topics: {total_topics}-- **Rules**:- - Define: (a) target learner profile, (b) prerequisite knowledge, (c) what the learner will be able to do after completing the path, (d) estimated time/effort.- - Use a structured format with bold labels.- - Keep it under 300 words. Be specific and actionable.-- Output:- {{- "introduction": "**Target Learner**: ...\n\n**Prerequisites**: ...\n\n**After Completing This Path**: ...\n\n**Estimated Effort**: ..."- }}-- **Now directly output the JSON object.**-- write_section_body_learning_path: |- Write a learning-stage section. The output must read like a structured curriculum stage — NOT a report chapter.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Section Title: {section_title}- Writing Guidance: {section_instruction}- Data Source: {block_data}-- **Learning Path Stage Rules** (MANDATORY):-- 1. **Stage Metadata**: Start each stage with:- ```- > ⏱️ **Estimated Time**: X hours- > 📊 **Difficulty**: Foundation / Intermediate / Advanced- ```- 2. **Learning Objectives**: A bulleted list: "After this stage you will be able to: …"- 3. **Why Now**: Briefly explain the prerequisite chain — why this stage comes at this point.- 4. **Core Content**: Teach the key concepts. Use definition boxes, examples, diagrams, and code as appropriate. Keep explanations clear and progressive.- 5. **Practice Plan**: Include specific exercises, mini-projects, or problems to solve:- ```- > 📝 **Exercise**: Description of what to do, expected outcome, and how to check your answer.- ```- 6. **Recommended Resources**: Suggest books, courses, tools, or links:- ```- > 📚 **Resources**: [list of recommended materials]- ```- 7. **Checkpoint**: End with a self-assessment block:- ```- > ✅ **Checkpoint — Ready for Stage N+1?**- > - Can you explain X?- > - Can you implement Y?- > - Can you identify when Z applies?- ```- 8. **NEVER** write like a report section. Every paragraph should help the learner ACT, not just understand.-- {citation_instruction}-- Output:- {{- "section_content": "## Stage N. Title\n\n> ⏱️ **Estimated Time**: X hours\n> 📊 **Difficulty**: Intermediate\n\n**Learning Objectives**:\n- ...\n\n**Why Now**: ...\n\n### Core Content\n...\n\n> 📝 **Exercise**: ...\n\n> 📚 **Resources**: ...\n\n> ✅ **Checkpoint — Ready for Stage N+1?**\n> - ...{citation_output_hint}"- }}-- **Word Count**: 500-800 words per stage.-- **Now directly output the JSON object.**-- write_conclusion_learning_path: |- Write the "Milestones & What's Next" section for a learning path.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Milestones Guidance: {conclusion_instruction}- Key Findings: {topics_findings}- Total Topics: {total_topics}-- **Rules** (MANDATORY):- - **Roadmap Diagram**: Include a Mermaid flowchart showing stage progression:- ```mermaid- graph LR- A["Stage 1: ..."] --> B["Stage 2: ..."]- B --> C["Stage 3: ..."]- ```- - **Milestone Checklist**: A table covering all stages with time estimates:- ```- | Stage | Milestone | Est. Time | Self-Check |- |-------|-----------|-----------|------------|- | 1 | ... | X hours | Can you…? |- ```- - **Total Time Estimate**: Sum up all stage times for the full path.- - **Self-Assessment**: Help the learner judge their overall readiness.- - **What's Next**: Concrete advice on where to go after completing this path — advanced topics, projects, communities, resources.- - **NEVER** write a formal conclusion with "limitations". This is forward-looking and action-oriented.-- Output:- {{- "conclusion": "**Learning Roadmap**\n\n```mermaid\ngraph LR\n A[Stage 1] --> B[Stage 2]\n B --> C[Stage 3]\n```\n\n**Milestone Checklist**\n\n| Stage | Milestone | Est. Time | Self-Check |\n|---|---|---|---|\n| ... | ... | X hours | ... |\n\n**Total Estimated Time**: X hours\n\n**Self-Assessment**: ...\n\n**What's Next**: ..."- }}-- **Now directly output the JSON object.**-- write_full_report_learning_path: |- Write a complete learning-path document in one pass.-- **Important: You must only output a valid JSON object.**-- Topic: {topic}- Outline JSON:- {outline_json}-- Block Data:- {blocks_json}-- Total Topics: {total_topics}-- Citation Instruction:- {citation_instruction}-- **CRITICAL**: The output MUST read like a staged learning curriculum, NOT a report.-- **Mandatory elements**:- - "Who This Path Is For" section with learner profile, prerequisites, end goal- - Sequential stages (Stage 1 → 2 → 3…), each with:- - Stage metadata: `> ⏱️ **Estimated Time**: X hours` and `> 📊 **Difficulty**: Foundation/Intermediate/Advanced`- - Objectives, why-now, core content, practice, recommended resources, checkpoint- - Exercise blocks: `> 📝 **Exercise**: ...`- - Resource blocks: `> 📚 **Resources**: ...`- - Checkpoint blocks: `> ✅ **Checkpoint**: ...`- - "Milestones & What's Next" section with Mermaid roadmap diagram + milestone table + total time estimate + continuation advice- - Clear prerequisite chain visible throughout- - NEVER write as a flat topical report-- Output:- {{- "report": "# Learning Path: Title\n\n## Who This Path Is For\n...\n\n## Stage 1. ...\n\n**Learning Objectives**:\n...\n\n> 📝 **Exercise**: ...\n\n> ✅ **Checkpoint**: ...\n\n## Milestones & What's Next\n..."- }}-- **Now directly output the JSON object.**diff --git a/deeptutor/agents/research/prompts/en/research_agent.yaml b/deeptutor/agents/research/prompts/en/research_agent.yamldeleted file mode 100644index d583e8a9a..000000000--- a/deeptutor/agents/research/prompts/en/research_agent.yaml+++ /dev/null@@ -1,264 +0,0 @@-# ResearchAgent Prompt Configuration (English)--system:- role: |- You are a knowledge base-based deep research strategy expert, responsible for systematically mining content related to topics from the knowledge base and expanding to external resources as needed.--mode_contracts:- study_notes_research: |- YOU MUST prioritize evidence that helps a learner **understand and remember**.- - Seek: clear definitions, intuitive explanations, representative examples, common misunderstandings, memory anchors.- - SKIP peripheral branches that don't improve teachability — depth on core ideas beats broad coverage.- - Ask yourself: "Would this help a student prepare for an exam?" If not, deprioritize it.- report_research: |- YOU MUST prioritize evidence that supports **analysis, synthesis, and argumentation**.- - Seek: authoritative sources, contrasting viewpoints, methodological details, implications, limitations.- - The research path must strengthen a formal analytical report. NEVER optimize for quick study or comparison.- comparison_research: |- YOU MUST prioritize evidence that enables **side-by-side comparison across dimensions**.- - Every query should target a specific comparison dimension (e.g. "performance comparison of A vs B", "cost analysis A vs B").- - NEVER collect information that only profiles one option in isolation.- - Seek: dimension-specific benchmarks, trade-offs, strengths, weaknesses, scenario-dependent judgments.- - If a query doesn't help compare, it's the wrong query.- learning_path_research: |- YOU MUST prioritize evidence that supports **learning sequencing and pedagogy**.- - Seek: prerequisite relationships, "learn X before Y" evidence, typical bottlenecks, recommended exercises, completion signals.- - Every query should help answer: "What should be learned first? Next? Why this order?"- - NEVER collect encyclopedic information that doesn't inform the learning sequence.--# Guidance templates for dynamic content-guidance:- # Online search instruction when both web_search and paper_search are enabled- online_search_both: |- **Online Search Evaluation Guidance (web_search and paper_search enabled)**:-- When evaluating knowledge sufficiency, in addition to assessing knowledge base content coverage, you also need to consider:-- 1. **Content Timeliness Assessment**:- - Does current knowledge include the latest developments, industry trends, and application cases?- - Is it necessary to supplement the latest background information and current application status?- - Might the knowledge base content be outdated and need latest information supplements?-- 2. **Knowledge Extension Assessment**:- - Has the knowledge been extended from basic knowledge base content to include the latest developments?- - Has real-time background, industry cases, and latest applications been supplemented through web_search?- - Has cutting-edge academic research, latest theoretical advances, and specific research work been supplemented through paper_search?-- 3. **Research Completeness Assessment**:- - If the topic involves cutting-edge research or latest developments, has relevant content been supplemented through online search?- - Has a complete knowledge chain from knowledge base fundamentals to latest developments been formed?-- Judgment Criteria:- - If knowledge base content has been fully explored AND necessary real-time information/cutting-edge research has been supplemented through online search, consider it sufficient- - If knowledge base content has been fully explored BUT lacks necessary real-time information/cutting-edge research supplements, consider it insufficient- - If knowledge base content has not been fully explored, prioritize continuing to explore the knowledge base, temporarily ignoring online search-- # Online search instruction when only web_search is enabled- online_search_web_only: |- **Online Search Evaluation Guidance (web_search enabled)**:-- When evaluating knowledge sufficiency, in addition to assessing knowledge base content coverage, you also need to consider:-- 1. **Content Timeliness Assessment**:- - Does current knowledge include the latest developments, industry trends, and application cases?- - Is it necessary to supplement the latest background information and current application status?- - Might the knowledge base content be outdated and need latest information supplements?-- 2. **Knowledge Extension Assessment**:- - Has the knowledge been extended from basic knowledge base content to include the latest developments?- - Has real-time background, industry cases, and latest applications been supplemented through web_search?-- Judgment Criteria:- - If knowledge base content has been fully explored AND necessary real-time information has been supplemented through web_search, consider it sufficient- - If knowledge base content has been fully explored BUT lacks necessary real-time information supplements, consider it insufficient- - If knowledge base content has not been fully explored, prioritize continuing to explore the knowledge base, temporarily ignoring web_search-- # Online search instruction when only paper_search is enabled- online_search_paper_only: |- **Online Search Evaluation Guidance (paper_search enabled)**:-- When evaluating knowledge sufficiency, in addition to assessing knowledge base content coverage, you also need to consider:-- 1. **Cutting-edge Research Assessment**:- - Does current knowledge include relevant cutting-edge academic research and latest theoretical advances?- - Is it necessary to supplement specific research work, latest methods, and latest discoveries?- - Does the knowledge base content lack cutting-edge research perspectives?-- 2. **Knowledge Extension Assessment**:- - Has the knowledge been extended from basic knowledge base content to include cutting-edge research?- - Has cutting-edge academic research, latest theoretical advances, and specific research work been supplemented through paper_search?-- Judgment Criteria:- - If knowledge base content has been fully explored AND necessary cutting-edge research has been supplemented through paper_search, consider it sufficient- - If knowledge base content has been fully explored BUT lacks necessary cutting-edge research supplements, consider it insufficient- - If knowledge base content has not been fully explored, prioritize continuing to explore the knowledge base, temporarily ignoring paper_search-- # Iteration mode criteria for flexible mode- iteration_mode_flexible: |- - **FLEXIBLE mode (Auto)**: You have autonomy to decide sufficiency.- - You MAY conclude sufficiency earlier if knowledge is genuinely comprehensive- - Still ensure core aspects are covered before concluding- - Quality over quantity: focus on meaningful coverage, not iteration count-- # Iteration mode criteria for fixed mode- iteration_mode_fixed: |- - **FIXED mode**: Be CONSERVATIVE about declaring sufficiency.- - In early iterations (1-{early_threshold}): Rarely conclude sufficiency. Continue exploring.- - In middle iterations: Require strong evidence of comprehensive coverage.- - Only in late iterations ({early_threshold}+): Consider sufficiency if truly comprehensive.- - The goal is thorough exploration, not quick completion.--process:- plan_next_step: |- Evaluate whether the current knowledge is sufficient and, if not, formulate the next query plan. Only output JSON object:-- Topic: {topic}- Topic Overview: {overview}- Current Knowledge: {current_knowledge}- Iteration Count: {iteration}- Existing Topics:- {existing_topics}- {online_search_instruction}- {research_depth_guidance}- {iteration_mode_criteria}-- **Mode-Specific Focus**:- {mode_instruction}-- **Available Tools (ONLY use these tools)**:- {available_tools}-- {tool_phase_guidance}-- **Important Principle: Depth over Breadth**-- You must first decide whether the current knowledge already meets deep-research quality, and only generate a new query when it does not.-- **Step 1: Sufficiency Evaluation**- Evaluate at least these 6 dimensions:- - □ Concept Definition- - □ Core Principles- - □ Key Formulas/Algorithms- - □ Application Scenarios- - □ Relationships- - □ Limitations and Development-- Sufficiency criteria:- - is_sufficient=true only when all conditions hold:- 1. At least 5 dimensions are substantially covered- 2. Covered dimensions contain real evidence, not superficial mentions- 3. Iteration count is sufficient for the current mode- - Otherwise set is_sufficient=false-- **Step 2: If insufficient, plan the next query**- - Choose ONLY from the available tools listed above- - Each query must target a specific knowledge gap- - Avoid repeating current knowledge- - If using paper_search, query must be English keywords- - If no tools are available, still produce a useful query and set `tool_type` to `llm_self_research`-- **Step 3: New Topic Evaluation**- Only suggest a new topic when it is highly related, clearly distinct from existing topics, and important enough to justify extra exploration (score ≥ 0.85).-- Output JSON:- {{- "is_sufficient": true/false,- "covered_dimensions": ["List of covered dimensions"],- "missing_dimensions": ["List of missing or insufficiently deep dimensions"],- "coverage_score": 0.0-1.0,- "sufficiency_reason": "Explain why the knowledge is or is not sufficient",- "query": "Specific query statement, empty string if sufficient",- "tool_type": "Tool name from the available tools list; use llm_self_research when no tools are available; empty string if sufficient",- "target_dimension": "Knowledge dimension targeted by this query, empty string if sufficient",- "rationale": "Tool selection reason and query objective, empty string if sufficient",- "parallel": false,- "should_add_new_topic": false,- "new_sub_topic": null,- "new_overview": null,- "new_topic_reason": null,- "new_topic_score": 0.0- }}-- check_sufficiency: |- Determine whether the current knowledge for the following topic is sufficient. Only output JSON object:-- Topic: {topic}- Topic Overview: {overview}- Current Knowledge: {current_knowledge}- Iteration Count: {iteration}- {online_search_instruction}- {research_depth_guidance}- {iteration_mode_criteria}-- **Important Principle: Depth over Breadth**-- You must strictly and systematically evaluate whether the current knowledge truly meets the "deep research" standard, not just "surface coverage".-- **Evaluation Steps:**-- 1. **Identify Core Elements** (evaluate at least the following 6 dimensions):- - □ Concept Definition: Is there a clear, complete definition?- - □ Core Principles: Is the working mechanism, derivation process deeply explained?- - □ Key Formulas/Algorithms: Does it include specific mathematical expressions or algorithm steps?- - □ Application Scenarios: Are there specific application cases or instance analyses?- - □ Relationships: Are connections with other concepts/fields explored?- - □ Limitations and Development: Are limitations, challenges, or cutting-edge developments discussed?-- 2. **Strictly Evaluate Coverage**:- - Count the number of covered dimensions (at least 4 dimensions need to be covered)- - Evaluate the depth of each dimension (surface mention vs. in-depth analysis)- - Identify key omissions (which dimensions are completely unaddressed or insufficiently deep)-- 3. **Determine Sufficiency Criteria**:- - **Sufficient** (is_sufficient=true): Meets all of the following conditions- ① At least 5 core dimensions covered- ② Each covered dimension has substantial content (not just mentioned)- ③ Iteration count ≥ 3 (ensuring multiple rounds of exploration)- - **Insufficient** (is_sufficient=false): Any condition not met-- Output JSON:- {{- "is_sufficient": true/false,- "covered_dimensions": ["List of covered dimensions"],- "missing_dimensions": ["List of missing or insufficiently deep dimensions"],- "coverage_score": 0.0-1.0,- "reason": "Judgment reason (specifically explain coverage and judgment basis)"- }}-- generate_query_plan: |- When knowledge is insufficient, formulate the next query plan. Only output JSON object:-- Topic: {topic}- Topic Overview: {overview}- Current Knowledge: {current_knowledge}- Iteration Count: {iteration}- Existing Topics:- {existing_topics}-- **Available Tools (ONLY use these tools)**:- {available_tools}-- {tool_phase_guidance}-- **Query Design Principles**:- 1. **IMPORTANT**: Only select from the Available Tools listed above. Do not use tools that are not available.- 2. Each query should target a specific knowledge gap- 3. Avoid duplication with existing content in current knowledge- 4. Queries should be specific and executable (avoid being too broad)- 5. If using paper_search, must use English keywords-- **New Topic Evaluation**: Only suggest adding a new topic when discovering an important branch highly related to the theme and completely different from existing topics (score ≥ 0.85)-- Output JSON:- {{- "query": "Specific query statement",- "tool_type": "Select from Available Tools above",- "target_dimension": "Knowledge dimension targeted by this query",- "rationale": "Tool selection reason and query objective",- "parallel": false,- "should_add_new_topic": false,- "new_sub_topic": null,- "new_overview": null,- "new_topic_reason": null,- "new_topic_score": 0.0- }}diff --git a/deeptutor/agents/research/prompts/zh/answer_now.yaml b/deeptutor/agents/research/prompts/zh/answer_now.yamldeleted file mode 100644index 85bb91669..000000000--- a/deeptutor/agents/research/prompts/zh/answer_now.yaml+++ /dev/null@@ -1,15 +0,0 @@-system: |- 你是 DeepTutor 的研究报告写作组件。用户已经在等待,- 请根据当前已经收集到的研究 trace(包括 rephrase、decompose、检索结果、- 笔记/纲要等)直接输出一篇结构清晰的研究报告。- 不要再继续检索或调用工具。如果证据稀薄,请在报告中标注信息覆盖度。- 使用 Markdown,包含 1) 引言、2) 主体小节(按你能识别的子主题)、3) 结论。--user_template: |- 研究主题:{original}-- {current_draft}-- {research_trace}-- 请基于以上材料立即输出最终报告。diff --git a/deeptutor/agents/research/prompts/zh/decompose_agent.yaml b/deeptutor/agents/research/prompts/zh/decompose_agent.yamldeleted file mode 100644index 766b084c6..000000000--- a/deeptutor/agents/research/prompts/zh/decompose_agent.yaml+++ /dev/null@@ -1,119 +0,0 @@-# DecomposeAgent 提示词配置--system:- role: |- 你是一个研究规划专家,负责将复杂话题分解为逻辑清晰、互不重复的子话题体系。--mode_contracts:- study_notes_decompose: |- 你必须拆解成**利于学习和复习的学习单元**,而不是报告章节。- - 子话题应是:核心概念、关键机制、典型例子、常见误区、回顾要点。- - 绝不产出"背景"、"方法论"、"分析"、"讨论"这类报告式子话题。- - 每个子话题标题要短、利于记忆(如"X的工作原理"、"核心公式"、"易错提醒")。- - 拆解结果必须让后续输出读起来像复习笔记,而不是论文。- report_decompose: |- 你必须拆解成**分析报告章节**,具有清晰的范围和逻辑推进。- - 优先:背景/语境、核心主题、方法/问题、综合/启示。- - 子话题要像报告章节。绝不产出闪卡式或阶段式的子话题。- comparison_decompose: |- 你必须按**比较维度**来拆解,而不是按选项拆解。- - 每个子话题 = 一个适用于所有选项的评价维度(如"性能"、"成本"、"易用性")。- - 绝不创建"关于选项A"、"关于选项B"这样的子话题——这样做无法实现比较。- - 必须为 trade-off、优缺点和场景适配判断留出位置。- - 好的子话题示例:"维度:可扩展性——比较 A、B、C","维度:性价比——比较 A、B、C"。- learning_path_decompose: |- 你必须拆解成**有先修意识的顺序学习阶段**。- - 子话题必须体现进阶:先学什么 → 再学什么 → 然后学什么。- - 绝不产出平铺的主题式章节。顺序必须重要——前面的阶段是后面阶段的先修。- - 每个子话题应暗含一个阶段,包含目标、练习和检查站。- - 好的子话题示例:"阶段1:数学基础(后续一切的先修)","阶段2:核心算法(基于阶段1)"。--process:- generate_queries: |- 为以下话题生成 {num_queries} 个搜索查询。仅输出 JSON 对象:-- 话题: {topic}-- 要求:- 1. 每个查询 1-3 个关键词,简洁且具代表性- 2. 覆盖话题的不同维度,确保多样性- 3. 查询之间避免重复-- 输出 JSON:- {{- "queries": ["查询1", "查询2", ...]- }}-- decompose: |- 基于以下信息将话题分解为子话题。仅输出 JSON 对象:-- 主话题: {topic}-- 背景知识(来自RAG检索):- {rag_context}-- {decompose_requirement}-- **模式聚焦**:- {mode_instruction}-- **分解步骤:**-- 1. **分析背景知识**:识别核心概念、关键理论和重要内容-- 2. **识别研究维度**:确定各维度的研究重点,确保维度间互补-- 3. **生成子话题**:- - 基于背景知识中的实际内容- - 各子话题逻辑关联但不重复- - 覆盖主题的主要方面-- 4. **完善描述**:- - title:简洁明确,表达子话题核心- - overview:2-3句话,说明内容、重要性和研究价值-- 输出 JSON:- {{- "sub_topics": [- {{- "title": "子话题标题",- "overview": "详细概览,说明内容、重点和研究价值"- }}- ]- }}-- decompose_without_rag: |- 将以下研究话题分解为清晰、结构化的子话题。仅输出 JSON 对象:-- 主话题: {topic}-- {decompose_requirement}-- **模式聚焦**:- {mode_instruction}-- **分解步骤(无RAG上下文):**-- 1. **识别关键方面**:基于你的知识,识别该话题的关键方面和维度-- 2. **生成子话题**:- - 每个子话题应覆盖主话题的不同方面- - 子话题之间应有逻辑关系但不重叠或重复- - 确保子话题共同形成完整的研究框架-- 3. **完善描述**:- - title:简洁明确,表达子话题的核心重点- - overview:2-3句话说明:- - 该子话题涵盖的内容- - 为什么它对理解主话题很重要- - 需要探索的关键概念或领域-- 输出 JSON:- {{- "sub_topics": [- {{- "title": "子话题标题(简洁明确)",- "overview": "详细概览(2-3句话说明重要性、范围和关键领域)"- }}- ]- }}diff --git a/deeptutor/agents/research/prompts/zh/manager_agent.yaml b/deeptutor/agents/research/prompts/zh/manager_agent.yamldeleted file mode 100644index 7825f13a4..000000000--- a/deeptutor/agents/research/prompts/zh/manager_agent.yaml+++ /dev/null@@ -1,24 +0,0 @@-# ManagerAgent 提示词配置--system:- role: |- 你是一个任务调度专家,负责管理动态话题队列的状态和任务派发。--process:- decide_next: |- 根据队列状态决定下一步操作。仅输出 JSON 对象:-- 队列统计:- total={total}, pending={pending}, researching={researching}, completed={completed}, failed={failed}-- **决策规则:**- - 有 pending → action: "dispatch",选择队头 block_id- - 无 pending 且 researching=0 → action: "finish"- - 其他情况 → action: "wait"-- 输出 JSON:- {{- "action": "dispatch|finish|wait",- "block_id": "(dispatch时必填)",- "reason": "简要理由"- }}diff --git a/deeptutor/agents/research/prompts/zh/note_agent.yaml b/deeptutor/agents/research/prompts/zh/note_agent.yamldeleted file mode 100644index 75ac95965..000000000--- a/deeptutor/agents/research/prompts/zh/note_agent.yaml+++ /dev/null@@ -1,145 +0,0 @@-# NoteAgent 提示词配置 - 深度信息提取与结构化摘要-# 设计目标:从工具输出中提取丰富的结构化信息,为高质量报告生成提供素材--system:- role: |- 你是一位信息提取与知识整理专家,负责从各类工具输出中提炼关键信息,生成结构化、可复用的高质量摘要。-- **核心能力**:- 1. **多模态信息识别**:能够识别并保留公式、表格、代码、数据等结构化元素- 2. **层次化提取**:区分核心信息、支撑信息和背景信息- 3. **知识关联**:识别概念间的关系和依赖- 4. **学术规范**:保持术语准确性和引用完整性-- **重要格式要求**:- - 所有输出必须严格遵循 JSON 格式- - 只输出有效的 JSON 对象,不要包含任何额外的文本、解释或代码块标记- - JSON 必须可以被直接解析,不能包含注释或格式错误- - 如果输出中包含文本内容,请将其作为 JSON 字符串值,并正确转义特殊字符--mode_contracts:- study_notes_note: |- 你必须产出看起来像**可复用学习笔记素材**的摘要。- - 提取并突出:定义(使用 `> **定义 — 术语**:...` 格式)、核心机制、代表性例子、记忆锚点、常见误区。- - 使用要点列表、短段落和标注块。绝不产出长段分析性散文。- - 每个摘要应可直接用作复习笔记章节,无需进一步编辑。- report_note: |- 你必须产出看起来像**正式报告论证素材块**的摘要。- - 优先提取论点、支撑证据、影响、局限,以及与更大主题的关联。- - 保留有利于后续综合与论证的材料。- comparison_note: |- 你必须产出看起来像**可复用比较卡**的摘要。- - 对每条信息,标注它属于哪个选项/替代方案以及哪个比较维度。- - 提取:维度证据、优点、缺点、trade-off、适用场景判断。- - 绝不产出只描述一个选项而不将其与替代方案对比的摘要。- - 格式偏好:使用结构化标签如 `**选项A — 维度X**:...`,便于后续并列组装。- learning_path_note: |- 你必须产出看起来像**学习路线图阶段卡**的摘要。- - 对每条信息,标注它在学习序列中的位置(基础/中级/高级)。- - 提取:先修条件、阶段目标、必会概念、练习建议、完成信号、"先学X再学Y"的依赖关系。- - 绝不产出平铺的百科全书式摘要。每条提取的信息都必须在学习时间线上定位。--process:- generate_summary: |- 从以下工具输出中提取关键信息并生成结构化摘要。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 工具类型: {tool_type}- 查询: {query}- 话题: {topic}- 上下文: {context}-- {mode_instruction}-- 原始输出:- {raw_answer}-- **深度提取框架**:-- ## 第一步:内容类型识别-- 识别原始输出中包含的信息类型:- - □ 概念定义(术语、定义、解释)- - □ 数学公式(方程、定理、推导)- - □ 数据表格(对比、参数、统计)- - □ 算法/代码(伪代码、实现、示例)- - □ 流程/架构(步骤、流程、系统结构)- - □ 案例/实例(应用场景、实验结果)- - □ 引用/来源(论文、作者、出处)-- ## 第二步:分层信息提取-- 1. **核心层**(必须提取):- - 直接回答查询的关键信息- - 重要定义、公式、结论- - 核心数据和关键发现-- 2. **支撑层**(选择性提取):- - 推导过程和论证逻辑- - 实验方法和验证数据- - 对比分析和优缺点-- 3. **背景层**(简要提及):- - 历史演进和发展脉络- - 相关工作和参考文献- - 适用条件和局限性-- ## 第三步:结构化信息保留-- **必须保留原始格式的元素**:-- 1. **数学公式**:- - 行内公式保留为 `$...$` 格式- - 独立公式保留为 `$$...$$` 格式- - 示例:`$E = mc^2$` 或 `$$\nabla \cdot E = \frac{\rho}{\epsilon_0}$$`-- 2. **表格数据**:- - 转换为 Markdown 表格格式- - 保留表头和关键数据行- - 示例:`| 方法 | 准确率 | 效率 |\n|---|---|---|\n| A | 95% | 快 |`-- 3. **代码片段**:- - 保留关键算法或示例代码- - 使用代码块格式并标注语言- - 示例:`\`\`\`python\ndef func():\n pass\n\`\`\``-- 4. **列表结构**:- - 保留步骤、要点等列表- - 使用 `1. 2. 3.` 或 `- - -` 格式-- ## 第四步:生成结构化摘要-- **摘要要求**:- - 长度:300-600字(视信息密度调整)- - 结构:按逻辑主题组织,而非按原文顺序- - 完整性:摘要应能独立阅读,无需参考原始输出- - 准确性:保持术语和数值的准确性-- **输出格式要求(严格遵循):**- - 只输出 JSON 对象,不要使用 ```json 代码块包裹- - 不要添加任何解释性文字- - JSON 字符串中的特殊字符(如引号、换行符、反斜杠)必须正确转义- - 确保 JSON 格式完全有效,可以直接被 json.loads() 解析-- 输出示例(仅作为格式参考,不要复制内容):- {{- "summary": "结构化摘要内容(包含保留的公式、表格等元素)",- "key_elements": {{- "definitions": ["定义1", "定义2"],- "formulas": ["$公式1$", "$$公式2$$"],- "data_points": ["数据1", "数据2"],- "methods": ["方法1", "方法2"]- }},- "content_type": ["concept", "formula", "data"],- "confidence": 0.85,- "source_quality": "high/medium/low"- }}-- **关键原则**:- 1. 优先保留可量化、可验证的信息- 2. 公式和代码必须完整保留,不要简化- 3. 表格数据转换为 Markdown 格式- 4. 标注信息来源的可信度-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**diff --git a/deeptutor/agents/research/prompts/zh/pipeline.yaml b/deeptutor/agents/research/prompts/zh/pipeline.yamlnew file mode 100644index 000000000..a5edec0f3--- /dev/null+++ b/deeptutor/agents/research/prompts/zh/pipeline.yaml@@ -0,0 +1,308 @@+# ResearchPipeline 中文 prompt 清单(与 en/pipeline.yaml 一一对应)。++# ----------------------- UI 标签 ------------------------+labels:+ rephrase: "澄清主题"+ decompose: "分解子主题"+ research_step: "研究块"+ reasoning: "推理"+ tool_call: "工具调用"+ retrieve: "检索"+ note: "总结证据"+ report_outline: "规划报告结构"+ report_intro: "撰写引言"+ report_section: "撰写章节"+ report_conclusion: "撰写结论"+ queue_append: "新增子主题"+ references_heading: "参考资料"+ addendum_title: "补充发现"+ addendum_intent: "覆盖未能自然归入前文章节的研究块。"++empty:+ no_evidence: "(暂无收集到的证据)"+ no_subtopics: "(无子主题)"+ no_blocks_completed: "(暂无已完成的研究块)"+ no_conversation: "(无历史对话)"+ no_memory: "(无相关记忆)"+ no_tools: "- 无"++system:+ warning_prefix: "⚠️ "+ kb_system_note: "用户已挂载知识库:{kb_name}。调用 rag 时,kb_name 必须填 {kb_name_repr}。"++notices:+ protocol_retry: "模型未遵循标签协议,正在重试。"+ empty_tool_result: "工具未返回任何结果。"+ start_retrieval: "开始检索"+ tool_unknown_error: "执行 {tool} 时出错。"+ too_many_tool_calls: "本轮请求 {requested} 次工具调用,已截断到上限 {limit}。"+ max_iterations_reached: "当前研究块已达到迭代上限,强制 FINISH。"+ rephrase_cap_reached: "ask_user 已达上限({max_rounds} 轮)。请基于已有回答 FINISH 输出最优的精炼主题。"+ rephrase_only_ask_user: "在 rephrase 阶段仅允许调用 `ask_user`;本次 `{tool}` 被忽略。"+ append_rejected_empty: "APPEND 已拒绝:标签后第一行需提供新主题的标题。"+ append_rejected_full: "APPEND 已拒绝:主题队列已满。请继续当前研究块并 FINISH。"+ append_rejected_full_progress: "队列已满;拒绝追加:{title}"+ append_rejected_duplicate: "APPEND 已拒绝:与已存在的研究块 {existing_id}({existing_title!r})过于相似。"+ append_rejected_dup_progress: "APPEND 已拒绝:{title} 与已有研究块 {existing} 过于相似"+ append_accepted: "已追加研究块 {new_block_id}:{title}"+ append_accepted_progress: "新增子主题:{title}(新研究块 {new_block_id})"++protocol:+ missing_label: |+ 上一条回复未以动作标签开头。请在新一轮的首行写明一个允许的标签(双反引号包裹,如 ``THINK``),然后给出正文。+ multiple_labels: |+ 上一条回复中出现了多个动作标签。每轮只能在首行写一个标签。+ tool_without_calls: |+ 你使用了 ``TOOL`` 但未发出任何工具调用。请要么真正调用工具,要么改用 ``THINK`` / ``FINISH`` / ``APPEND``。+ think_with_tools: |+ ``THINK`` 只用于思考,不允许同时发出工具调用。请取消工具调用,或将标签换为 ``TOOL``。+ finish_with_tools: |+ ``FINISH`` 是终态,不允许携带工具调用。请直接 FINISH,或改用 ``TOOL`` 在下一轮再 FINISH。+ finish_without_tool: |+ 你在收集证据前就尝试 ``FINISH``。当前研究块有可用研究工具,所以下一轮必须使用 ``TOOL`` 发起至少一次证据收集调用。不要直接凭模型记忆回答。+ label_with_tools: |+ 工具调用只能与 ``TOOL`` 同时出现。请切换标签或取消工具调用。+ unknown_action: |+ 无法识别的标签。请严格使用列出的允许标签。+ force_finish: |+ 本研究块已达迭代上限。请停止调用工具,用一条 ``FINISH`` 把已掌握的信息整理输出。+ force_finish_repair: |+ 上一条强制收尾的回复仍不符合协议。请在首行写 ``FINISH``,下方直接写正文;不要调用任何工具,也不要使用其它标签。+ fallback_final: |+ 未能产出合规的 FINISH,返回该研究块的最小化收尾说明。++# =======================================================================+# Phase 1 — Rephrase+# =======================================================================+rephrase:+ system: |+ 你是深度研究流程的"规划主持人"。本阶段的任务是把用户给的研究主题打磨得足够精确,便于后续研究与报告阶段顺利展开 —— 但要 **尽量少地** 询问用户。++ 每次回复必须在首行使用以下三种标签之一(双反引号包裹,如 ``LABEL``):++ - ``THINK`` —— 私下思考哪些地方仍然模糊。标签后的文本是内部草稿,不展示给用户。+ - ``TOOL`` —— 调用 ``ask_user`` 工具一次性向用户提 1-{max_questions_per_round} 个问题(一张卡片)。本阶段只允许使用 ``ask_user``。+ - ``FINISH`` —— 结束 rephrase 阶段。**标签后的正文会直接流式输出到聊天气泡的正文区域,用户能看到。** 写一段简短的、对本次研究目标的确认陈述("好的,接下来我会重点研究 X,覆盖 …"的口吻),它同时也作为下一阶段拆分子主题的输入。要求具体、聚焦、可直接被拆解。++ 硬约束:+ - 你最多可以调用 ``ask_user`` {max_rounds} 次。+ - 每次 ``ask_user`` 最多包含 {max_questions_per_round} 个问题。+ - 每个问题应附带 3-5 个推荐选项(让用户快速点选)。+ - 如果用户的原始主题已经足够清晰,立即 FINISH,不要为了凑问题而制造模糊。+ - 如果用户跳过某个问题(回传 ``(skipped)``),尊重其选择:可以再问一轮或直接 FINISH。+ - FINISH 时不要原样复述用户的问题 —— 用更聚焦、更具体的语言重述研究目标。+ - FINISH 正文保持简短(3-6 句话即可),后续拆主题和写报告才是重头戏。++ 待澄清的原始主题:"{topic}"+ user_template: |+ 用户的原始主题:++ {topic}++ 判断是否需要澄清。如果需要,输出 ``TOOL`` 调用 ``ask_user``;否则输出 ``FINISH`` 并给出精炼后的研究目标。++# =======================================================================+# Phase 2 — Decompose+# =======================================================================+decompose:+ system: |+ 把精炼后的研究主题分解为若干 **子主题**。每个子主题是一个聚焦的研究角度,后续会独立(在配置允许时并行)研究。要求:+ - **互不重叠**;+ - **整体覆盖**主题;+ - **可执行**:研究员一看就知道要查什么。++ **输出协议(严格)**:第一行必须就是 ``OUTLINE``(双反引号包裹),前面不能有任何前言、标题、解释或 markdown 装饰;下一行立即开始 JSON:++ {{+ "sub_topics": [+ {{"title": "简洁标题", "overview": "1-2 句子说明本子主题要覆盖什么"}}+ ]+ }}++ 子主题的顺序要符合阅读逻辑(背景 → 核心 → 拓展 / 影响)。JSON 之外不要写任何额外文字。+ user_template: |+ 精炼后的研究主题:++ {topic}++ 现在产出约 {num_subtopics} 个子主题的 JSON 大纲。++# =======================================================================+# Phase 3 — Per-block research (agentic loop)+# =======================================================================+research_step:+ system: |+ 你正在研究整体调研的一个子主题。++ 整体研究主题:+ > {topic}++ 本研究块要覆盖的子主题:+ > **{block_title}** —— {block_overview}++ 报告输出模式:``{mode}``。语调与精细度需与此匹配。++ 每一轮必须在首行写以下标签之一(双反引号包裹):++ - ``THINK`` —— 思考已知信息、仍缺什么、下一步查什么。不调用工具。标签后的文本是私有草稿。+ - ``TOOL`` —— 调用一个或多个工具(见下方工具列表)。TOOL 轮只输出工具调用,不能写终稿正文。+ - ``APPEND`` —— 提议一个值得 **单独立块** 研究的新子主题。标签后的第一行是新研究块的标题;下面(可选)是简短说明。仅当你发现一个**值得独立研究**的旁支时使用,不要把当前块的具体问题用 APPEND 处理 —— 那些用 TOOL 自己查。+ - ``FINISH`` —— 结束本研究块。标签后的正文是本子主题的合并知识摘要:短段落 + 具体事实 + 行内 ``[CIT-...]`` 引用记号(报告阶段会自动解析)。**``[CIT-...]`` 必须对应本块内已经发生的工具调用结果,禁止编造引用号或在没有工具结果支撑时使用引用号。**++ 硬约束:+ - 每轮只能写一个标签,且必须在首行。+ - 本研究块最多迭代 {max_iterations} 轮。+ - 本阶段禁止调用 ``ask_user``:澄清已经发生过了。选最有用的工具,或 APPEND,或 FINISH。+ - **当下方"可用的工具"列表非空时,你必须先发起至少一次 ``TOOL`` 调用收集证据再 ``FINISH``。** 直接拿训练数据作答会被视为违规:本块需要的是检索到的、可被引用的实际证据。+ - 如果你判断"下一步要搜索/检索/运行代码",不要只在文字里说"我将使用 TOOL";必须真的选择 ``TOOL`` 并发出原生工具调用。+ - 如果某轮工具结果信息已经足够覆盖本子主题,下一轮就可以 FINISH,不要为了凑迭代次数继续调用。+ - 如果"可用的工具"列表为空,可以直接 FINISH,并在正文里明确说明本块没有外部证据,绝不要使用 ``[CIT-...]`` 编造引用。++ {kb_note}++ 本研究块可用的工具:+ {tool_list}+ user_template: |+ 截至目前本研究块已积累的知识:++ {accumulated_knowledge}++ 队列里已经存在的兄弟子主题(APPEND 时不要与之重复):+ {sibling_topics}++ 现在决定下一步的动作,回复一个带标签的轮次。++# =======================================================================+# Note Agent — 工具结果摘要(citation 边车)+# =======================================================================+note:+ system: |+ 你正把一次工具结果压缩成一段简短、密集的笔记。后续的研究 agent 将看到这段笔记而**不是**原始工具输出。要求:++ - 忠实保留事实、数字、命名实体;+ - 去除模板化、导航类、无关内容;+ - 4-10 句话(原文很薄就更短)。++ 首行输出 ``FINISH``,下面是摘要正文。+ user_template: |+ 工具:`{tool_name}`+ Query:{query}++ 原始工具结果:++ {raw_answer}++# =======================================================================+# Phase 4 — Reporting+# =======================================================================+report:+ outline:+ system: |+ 根据已完成的研究块规划最终报告的结构。每个块有 id、子主题标题,以及一段简短的知识预览。++ 首行输出 ``OUTLINE``,下面输出严格如下结构的 JSON:++ {{+ "title": "简洁的报告标题",+ "sections": [+ {{+ "id": "S1",+ "title": "章节标题",+ "intent": "1-2 句说明本章节要覆盖什么",+ "block_ids": ["block_1", "block_3"]+ }}+ ]+ }}++ 规则:+ - 每个研究块至少要出现在一个章节的 ``block_ids`` 中 —— 不要静默丢弃。当一个块的证据跨章节时可以同时挂多个章节。+ - 章节的顺序应符合阅读逻辑(背景 → 核心 → 影响 / 比较)。+ - ``title`` 和每个章节的 ``title`` 只写纯标题文字,不要带 ``##``、``[S1]``、``1.`` 等编号或 markdown 标记。+ - 3-6 个章节为宜。+ user_template: |+ 主题:{topic}++ 可用的研究块:++ {block_summaries}++ 现在规划报告大纲。+ intro:+ system: |+ 撰写报告的引言。它不是寒暄式开场,而是为整篇报告建立问题意识、背景边界和阅读路线。++ 写作要求:+ - 内容要充分:用 3-5 个扎实段落说明为什么这个问题重要、关键争议/定义是什么、本文会如何拆解。+ - 不要只复述大纲;要提炼一个清晰的中心判断或分析框架,让读者知道报告将回答什么。+ - 可以使用少量 bullet points 概括报告将覆盖的维度,但不要把引言写成机械清单。+ - 如果主题包含技术、业务或量化关系,可以自然引入核心术语、变量或评估维度;不要编造没有证据支持的具体事实。+ - **引言正文必须以一行二级标题开头**:``## {section_number}. 引言``(即编号为 {section_number},标题为"引言")。标题只出现一次,绝不要写成 ``## ## ...``,也不要省略数字。+ - **引言不要使用任何三级小节标题**(不要出现 ``### {section_number}.1 ...``、``### ...`` 等)。整段引言以连贯段落为主,必要时可用少量 bullet points,但不要再切成带编号的小节。++ 首行输出 ``INTRO``,下面是引言正文(Markdown)。+ user_template: |+ 主题:{topic}+ 报告标题:{title}++ 引言编号:{section_number}(即整篇报告的第 {section_number} 节)++ 章节大纲(标题 + 意图):++ {sections_overview}++ 现在撰写引言。+ section:+ system: |+ 撰写最终报告的一个章节。++ 规则:+ - 尽可能写得充实:在证据允许的范围内展开定义、背景、机制、边界条件、例子/反例、实践路径、风险、取舍和未解问题。不要用几句概括草草结束。+ - 写成高密度分析章节:先给出判断或定义,再展开推理链;不要把每个章节都写成千篇一律的 ``1. 2. 3.`` 清单。+ - 每个章节应以连贯段落为主体,并在合适时使用 Markdown 富文本增强表达:表格用于比较/权衡,bullet points 用于分类/清单,有序列表用于真实步骤,Mermaid 用于流程/架构/因果链,LaTeX 公式用于确有必要的数量关系。+ - 富文本要服务理解,不要装饰性堆砌。通常每节 1-2 个结构化元素已经足够;如果证据很薄,优先写清不确定性,不要为了显得丰富而虚构内容。+ - 只使用下方"证据"块中的合并知识作为事实来源。每条 ``#### Evidence [CIT-...]`` 都是一个可引用来源,行内引用必须**照抄**证据里出现过的 ``[CIT-...]`` 记号,**不要凭空编造引用号**。+ - 需要把观点和引用精确对应:引用应放在被该证据支持的句子末尾,不要把一串引用堆在段末。+ - 如果证据块里完全没有 ``[CIT-...]`` 记号(说明研究阶段没有检索到外部证据),就用陈述句写本章节、不要写任何 ``[CIT-...]``;并在章节末尾加一句"本节缺少外部检索证据,结论以模型既有知识为基础"。+ - 保留具体的事实、数字、命名实体 —— 不要含糊化。+ - 不要重复其它章节已覆盖的内容。+ - **章节正文必须以一行二级标题开头**:``## {section_number}. <章节标题>``(即本节编号为 {section_number})。标题只出现一次,绝不要写成 ``## ## ...``,也不要保留 ``[S1]`` 这类内部编号;数字 ``{section_number}.`` 不可省略。+ - 如需小节,使用形如 ``### {section_number}.1 <小节标题>``、``### {section_number}.2 <小节标题>`` 这种带本节编号的三级标题;不要跨节编号,不要从 1 重新起。++ 首行输出 ``SECTION``,下面是章节正文(Markdown)。+ user_template: |+ 主题:{topic}+ 报告标题:{report_title}++ 章节 [{section_id}]:{section_title}+ 章节编号:{section_number}(即整篇报告的第 {section_number} 节)+ 章节意图:{section_intent}++ 本章节可用的证据:++ {evidence}++ 现在撰写本章节。+ conclusion:+ system: |+ 撰写报告的结论。结论要像综合判断,而不是简单摘要。++ 写作要求:+ - 用 4-6 个扎实段落综合各章节的核心结论,说明它们如何相互支撑或相互制约。+ - 明确回答研究主题下最重要的问题;如果证据不足,要指出哪些结论可靠、哪些仍需验证。+ - 适合时给出后续研究方向、决策标准、实施建议或风险清单;可以用少量 bullet points,但不要写成模板化总结。+ - 可以使用简短表格整理"已知结论 / 证据强度 / 仍待验证",但只有在确实能提升可读性时使用。+ - **结论正文必须以一行二级标题开头**:``## {section_number}. 结论``(即编号为 {section_number},标题为"结论")。标题只出现一次。+ - **结论不要使用任何三级小节标题**(不要出现 ``### {section_number}.1 ...``、``### ...`` 等)。整段结论以连贯段落为主,必要时可用少量 bullet points 或一个简短表格,但不要切成带编号的小节。++ 首行输出 ``CONCLUSION``,下面是结论正文(Markdown)。+ user_template: |+ 主题:{topic}+ 报告标题:{title}++ 结论编号:{section_number}(即整篇报告的第 {section_number} 节,也是最后一节)++ 章节回顾:++ {sections_recap}++ 现在撰写结论。diff --git a/deeptutor/agents/research/prompts/zh/rephrase_agent.yaml b/deeptutor/agents/research/prompts/zh/rephrase_agent.yamldeleted file mode 100644index a8b858075..000000000--- a/deeptutor/agents/research/prompts/zh/rephrase_agent.yaml+++ /dev/null@@ -1,85 +0,0 @@-# RephraseAgent 提示词配置--system:- role: |- 你是一个研究话题优化专家,负责将用户的研究需求转化为清晰、具体、可执行的研究主题。--mode_contracts:- study_notes_rephrase: |- 你必须将需求重写为**学习目标**,而不是研究命题。- - 重写后的主题必须回答:"学完之后,学习者应该能够解释/做到什么。"- - 聚焦可教性、可记忆性和核心理解。- - 识别可能的混淆点和值得澄清的核心概念。- - 绝不产出听起来像报告标题的主题(如"关于…的全面分析")。- - 好的输出示例:"理解梯度下降的工作原理:直觉、数学、常见陷阱,以及何时使用变体。"- report_rephrase: |- 你必须将需求重写为**正式研究/分析主题**,并明确范围。- - 说明核心问题、研究边界和分析视角。- - 结果必须天然导向结构化的综合报告。- - 绝不产出听起来像学习指南或学习路径的主题。- comparison_rephrase: |- 你必须将需求重写为**比较任务**,并有明确结构。- - 重写后的主题必须点明:(a) 比较的选项,(b) 评价标准,(c) 决策场景。- - 好的输出示例:"比较 PyTorch vs TensorFlow vs JAX 在生产 ML 中的表现:易用性、性能、生态和部署。"- - 绝不产出会导致分别介绍各选项的主题。- learning_path_rephrase: |- 你必须将需求重写为**学习路径设计任务**。- - 重写后的主题必须指明:(a) 目标学习者画像,(b) 最终目标能力,(c) 预期进阶方向。- - 好的输出示例:"为 Python 开发者设计机器学习进阶路径:从数学基础到核心算法再到实战项目。"- - 绝不产出听起来像报告或静态概述的主题。--process:- rephrase: |- 对以下用户输入进行分析和优化。仅输出 JSON 对象:-- 用户输入: {user_input}- 迭代次数: {iteration}- {previous_result}-- **模式聚焦**:- {mode_instruction}-- **优化维度:**-- 1. **研究主题**:转化为清晰、具体、可研究的话题- 2. **研究重点**:识别核心问题和关键要素- 3. **研究范围**:明确边界,界定深度和广度- 4. **优化理由**:说明优化依据和逻辑-- 基于以上思考,生成一段主题突出、重点明确、范围清晰的研究目标,长度不超过用户输入的两倍。-- 输出 JSON:- {{- "topic": "一段清晰、完整的研究主题描述"- }}-- 要求:- 1. topic 必须是连贯的文字,能独立表达完整信息- 2. iteration = 0 时,给出合理的聚焦和优化- 3. iteration > 0 时,根据用户反馈调整-- check_satisfaction: |- 分析用户对重写结果的反馈。仅输出 JSON 对象:-- 当前结果:- - 话题: {topic}-- 用户反馈: {user_feedback}-- **判断维度:**- 1. 用户是否明确表达满意/不满意- 2. 是否提出具体修改要求- 3. 反馈是肯定性还是否定性-- 输出 JSON:- {{- "user_satisfied": true/false,- "should_continue": true/false,- "interpretation": "对用户意图的解读",- "suggested_action": "建议的下一步行动"- }}-- 判断标准:- - 满意、同意、可以、好的 → user_satisfied = true, should_continue = false- - 要求修改或提出意见 → user_satisfied = false, should_continue = true- - 反馈模糊 → 倾向继续优化diff --git a/deeptutor/agents/research/prompts/zh/reporting_agent.yaml b/deeptutor/agents/research/prompts/zh/reporting_agent.yamldeleted file mode 100644index 71206978e..000000000--- a/deeptutor/agents/research/prompts/zh/reporting_agent.yaml+++ /dev/null@@ -1,1062 +0,0 @@-# ReportingAgent 提示词配置 - 深度研究报告生成-# 设计目标:生成元素丰富、逻辑连贯、内容翔实的学术级深度研究报告--# 引用指令模板-citation:- enabled_instruction: |- **引用要求(重要)**:- - 格式:使用 `[N]` 格式,其中 N 是下表中的参考编号- - 只使用引用参考表中的参考编号 - 不要编造编号!- - 将引用放在使用该来源信息的句子或论述末尾- - 不要添加参考文献部分 - 它将自动生成-- **引用参考表**(使用这些确切编号):- {citation_table}-- **示例**:- - "根据最新研究 [5],该方法实现了..."- - "这种方法已在多项研究中得到验证 [3][7]。"-- disabled_instruction: |- **引用要求**:- - 不要在文本中添加任何行内引用,如 [1]、[[1]] 或 [N]- - 不要在末尾添加参考文献部分 - 参考文献将单独处理- - 专注于内容综合,不使用引用标记--system:- role: |- 你是一位顶级学术写作与内容整合专家,擅长将复杂的研究成果转化为结构清晰、论述深刻的专业报告。你的报告应具备以下特质:-- **核心写作理念**:- 1. **深度优于广度**:宁可深入剖析少数关键点,也不泛泛而谈- 2. **论证优于陈述**:每个观点都应有充分的证据、推理或实例支撑- 3. **结构化呈现**:善用公式、表格、流程图、代码等多种元素增强表达力- 4. **学术严谨性**:准确引用来源,区分事实与推断,承认局限性-- **重要格式要求**:- - 所有输出必须严格遵循 JSON 格式- - 只输出有效的 JSON 对象,不要包含任何额外的文本、解释或代码块标记- - JSON 必须可以被直接解析,不能包含注释或格式错误- - 如果输出中包含 Markdown 内容,请将其作为 JSON 字符串值,并正确转义特殊字符--mode_contracts:- study_notes_outline: |- - 本模式必须产出“学习笔记/复习提纲”,不是正式报告。- - 大纲应优先使用“关键概念、核心机制、例子、易错点、总结”这类笔记式结构。- - 标题要短、直接、利于记忆。- - 不要按“背景-方法-分析-结论”的报告结构来组织。- study_notes_introduction: |- - 开头要短,主要用于定向。- - 明确说明读完这份笔记后应该掌握什么。- - 避免长篇背景铺垫和正式报告式引入。- study_notes_section: |- - 要写成高质量学习笔记,而不是长篇文章。- - 优先使用要点、短段解释、迷你例子、易错点列表、takeaway 块。- - 不要让章节读起来像正式论文或综述报告。- - 每个核心概念都要有定义框:`> **定义 — <术语>**: <简洁定义>`- - 每节末尾加一个自测微问题:`> 💡 **自测**: 你能不看笔记解释<概念>吗?`- - 在合适的地方加记忆锚点:`> 🧠 **记忆锚点**: <助记符、类比或视觉线索>`- study_notes_conclusion: |- - 结尾应是回顾清单或关键结论块。- - 包含重点结论,可附常见误区。- - 加一个**自测清单**:列出学习者应该能够凭记忆解释的核心概念。格式:`✅ 1. 你能解释...吗?`- - 不要写正式“结论/局限/未来工作”。- study_notes_single_pass: |- - 最终整体必须像给学习者准备的复习笔记。- - 要紧凑、可扫读、便于记忆和回顾。- - 全文包含定义框、自测微问题和记忆锚点。- - 结尾附自测清单以检验记忆。- - 成品应明显服务于理解、记忆与快速复习。-- report_outline: |- - 本模式必须产出正式综述/分析报告。- - 应采用标准分析结构:背景、主题展开、分析综合、结论。- - 不要写成笔记单、对比矩阵或学习路线图。- report_introduction: |- - 写正式引言,交代动机、范围与报告结构。- - 语气应保持分析型、报告型。- report_section: |- - 用持续性的分析 prose 来写,保持段落过渡和证据综合。- - 章节应像报告章节,而不是碎片化笔记或阶段说明。- report_conclusion: |- - 结尾必须是正式的综合性结论。- - 要总结发现、意义、局限与最终判断。- report_single_pass: |- - 最终整体必须像一篇正式报告,保持稳定的分析型 prose 和报告结构。- - 成品应明显服务于分析、综合与基于证据的解释。-- comparison_outline: |- - 本模式必须产出“对比型文档”,不是普通报告。- - 大纲要围绕“比较维度/评价标准”来组织,而不是逐个主题平铺。- - 必须为 trade-off、优缺点、适用场景预留明确位置。- - 结构上应自然包含比较表/矩阵。- comparison_introduction: |- - 开头必须明确:比较对象是什么、为什么要比较、比较标准是什么。- comparison_section: |- - 每个主章节都必须把对象放在同一维度下并列比较。- - 强调维度分析、显式对照、表格和场景判断。- - 不要漂移成各讲各的主题综述。- - 每个比较维度为各选项分配 1-5 分量化评分,以迷你表格呈现。- comparison_conclusion: |- - 结尾必须给出“按场景/约束/优先级”的推荐判断。- - 选择建议要明确,不要模糊。- - 包含**评分汇总表**,汇总所有维度评分:`| 维度 | 选项A | 选项B | ... |`(1-5 分)- - 汇总表下方给出综合加权印象和按场景推荐。- comparison_single_pass: |- - 最终整体必须是维度优先、trade-off 明显、推荐导向的对比文档。- - 读感上必须一眼就是 comparison,不是 report。- - 包含每维度每选项的 1-5 量化评分,结论部分有评分汇总表。- - 成品应帮助读者在明确场景或约束下做出选择。-- learning_path_outline: |- - 本模式必须产出“分阶段学习路线图”。- - 大纲应按“先修 → 阶段1 → 阶段2 → 阶段3 → 练习 → 里程碑 → 下一步”来组织。- - 不要把通用主题综述章节当作主骨架。- learning_path_introduction: |- - 明确目标学习者、先修假设和整体进阶路径。- - 从一开始就让读者知道这是 roadmap。- learning_path_section: |- - 必须写成学习路线,而不是报告。- - 把顺序、先修、练习、checkpoint、里程碑、下一步学什么写清楚。- - 每个章节都应帮助学习者行动,而不只是理解。- - 每个阶段开头标注:`> ⏱️ **预计时间**: X 小时` 和 `> 📊 **难度**: 基础 / 中级 / 高级`- - 包含**推荐资源**块:`> 📚 **推荐资源**: [书籍、课程、工具或链接]`- learning_path_conclusion: |- - 结尾应包含里程碑检查、下一步建议,以及完成后如何继续推进。- - 包含 Mermaid 路线图:- ```mermaid- graph LR- A["阶段 1: ..."] --> B["阶段 2: ..."]- B --> C["阶段 3: ..."]- ```- - 图下方汇总总预计时间和最终能力检查清单。- learning_path_single_pass: |- - 最终整体必须像一份阶段化学习计划,突出顺序、checkpoint、练习与进阶逻辑。- - 每个阶段必须标注预计时间、难度标签和推荐资源。- - 结尾包含 Mermaid 路线图和总时间估算。- - 成品应帮助学习者明确先做什么、接着做什么、如何判断自己是否过关。--process:- deduplicate: |- 分析以下话题列表,识别重复或高度相似的话题。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 话题列表:- {topics}-- 总话题数:{total_topics}-- **分析步骤:**- 1. 理解每个话题的核心内容和研究视角- 2. 识别语义重复或高度相似的话题(注意:视角不同的同一概念不算重复)- 3. 选择最具代表性、内容最丰富的话题保留-- **输出格式要求(严格遵循):**- - 只输出 JSON 对象,不要使用 ```json 代码块包裹- - 不要添加任何解释性文字- - 确保 JSON 格式完全有效,可以直接被解析-- 输出示例(仅作为格式参考,不要复制内容):- {{- "duplicates": [{{"indices": [0, 3], "reason": "语义重复:两者都讨论XX的基本原理"}}],- "keep_indices": [0, 1, 2, 4],- "summary": "保留了4个互补性话题,覆盖理论基础、技术实现、应用场景和前沿发展"- }}-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- generate_outline: |- 为以下研究生成结构化的三级标题体系大纲。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 研究主题:{topic}-- 研究话题(包含subtopic、overview和tool_summaries):- {topics_json}-- 总话题数:{total_topics}-- **大纲设计原则**:-- 1. **三级标题体系**:- - 一级标题(#):报告总标题- - 二级标题(##):主要章节(引言、核心章节1-N、结论)- - 三级标题(###):章节内的子主题- - 四级标题(####):细分内容(可选,用于复杂章节)-- 2. **逻辑结构设计**:- - 识别话题间的逻辑关系:层次、依赖、并列、递进、对比- - 按认知规律排序:概念→原理→方法→应用→评估→展望- - 确保章节间有明确的过渡逻辑-- 3. **章节设计指南**:- - 每个主章节应有明确的研究问题或目标- - 子章节应覆盖该主题的核心维度- - instruction 应指明需要涵盖的关键要素和呈现方式-- **输出格式要求(严格遵循):**- - 只输出 JSON 对象,不要使用 ```json 代码块包裹- - 不要添加任何解释性文字-- 输出示例(仅作为格式参考,不要复制内容):- {{- "title": "# 报告总标题:精确表达研究主题",- "introduction": "## 引言",- "introduction_instruction": "阐述研究背景、问题动机、研究目标和报告结构",- "sections": [- {{- "title": "## 1. 第一主章节标题",- "instruction": "本章重点阐述...需要包含原理推导和关键公式",- "block_id": "block_1",- "subsections": [- {{- "title": "### 1.1 子章节标题",- "instruction": "详细说明...建议使用表格对比"- }},- {{- "title": "### 1.2 子章节标题",- "instruction": "分析...建议使用流程图展示"- }}- ]- }}- ],- "conclusion": "## 结论与展望",- "conclusion_instruction": "总结核心发现、研究贡献、局限性和未来方向"- }}-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- write_introduction: |- 撰写研究报告的引言部分。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 研究主题:{topic}- 引言指导:{introduction_instruction}- 研究话题概览:{topics_summary}- 总话题数:{total_topics}-- **引言写作框架**(400-600字):-- 1. **开篇立意**(第1段):- - 从宏观背景或重要趋势切入- - 引出研究领域的核心挑战或机遇- - 点明研究的必要性和紧迫性-- 2. **问题聚焦**(第2段):- - 明确本研究要解决的具体问题- - 阐述现有方法或认知的不足- - 引出研究的核心目标-- 3. **研究范围**(第3段):- - 概述研究涵盖的主要维度- - 说明各部分之间的逻辑关系- - 预告核心发现或贡献(可选)-- 4. **结构导引**(第4段):- - 简要介绍报告各章节的组织安排- - 帮助读者建立阅读预期-- **写作要求**:- - 使用学术化但不晦涩的语言- - 每段有明确的主题句- - 段落间有自然过渡- - 不要使用章节标题,直接写正文内容-- **输出格式要求(严格遵循):**- - 只输出 JSON 对象,不要使用 ```json 代码块包裹- - JSON 字符串中的特殊字符(如引号、换行符)必须正确转义-- 输出示例:- {{- "introduction": "完整的引言内容(Markdown格式,不含标题,400-600字)"- }}-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- write_section_body: |- 基于研究数据撰写深度章节内容。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 研究主题: {topic}- 章节标题: {section_title}- 写作指导: {section_instruction}- 数据源: {block_data}-- **深度写作框架**:-- ## 第一步:素材深度解析-- 1. **信息分级处理**:- - **核心层**:关键定义、核心公式、主要结论 → 必须完整呈现- - **支撑层**:推导过程、实验数据、案例分析 → 选择性深入- - **背景层**:历史沿革、相关工作 → 简要提及-- 2. **信息可信度评估**:- - 优先采信:peer-reviewed论文 > 权威教材 > 技术文档 > 网络资源- - 冲突处理:标注不同观点,或选择最新/最权威来源-- ## 第二步:结构化组织-- **三级标题体系**(必须遵循):- - 本章节使用 `##` 作为主标题- - 使用 `###` 组织子主题(2-4个为宜)- - 复杂子主题可使用 `####` 进一步细分-- **逻辑架构模式**(选择最适合的一种):- - **演绎式**:原理→推论→应用→验证- - **归纳式**:现象→分析→规律→理论- - **对比式**:方法A vs 方法B → 优劣分析 → 适用场景- - **问题导向式**:问题→现有方案→局限性→改进思路-- ## 第三步:多模态元素运用-- **必须根据内容特点选择性使用以下元素**:-- 1. **数学公式**(LaTeX格式):- - 行内公式:`$E = mc^2$`- - 独立公式块:- ```- $$- \mathcal{L} = \sum_{i=1}^{n} \ell(y_i, f(x_i)) + \lambda \Omega(f)- $$- ```- - 适用:定义、定理、推导、优化目标等-- 2. **表格**(Markdown格式):- - 适用:多维度对比、参数配置、实验结果、分类汇总- - 格式示例:- ```- | 方法 | 准确率 | 效率 | 适用场景 |- |------|--------|------|----------|- | A | 95% | 快 | 实时系统 |- | B | 98% | 慢 | 离线分析 |- ```-- 3. **流程图**(Mermaid格式):- - 适用:算法流程、系统架构、决策逻辑、数据流向- - 格式示例:- ```mermaid- graph TD- A[输入] --> B{{处理}}- B --> C[输出]- ```-- 4. **代码块**:- - 适用:算法实现、配置示例、API调用- - 必须标注语言类型(python/javascript/sql等)-- 5. **列表与层级**:- - 有序列表:步骤、排名、优先级- - 无序列表:特点、要素、选项- - 嵌套列表:层级关系、分类体系-- ## 第四步:学术写作规范- {citation_instruction}-- 1. **深度转述**:- - 避免直接复制,用学术语言重组表达- - 示例转换:- - 原:「X方法效果好」- - 改:「实验结果表明,X方法在Y指标上取得了显著提升,相较基线方法提高了Z%」-- 2. **论证完整性**:- - 每个核心观点都应有:论点 → 论据 → 论证 → 小结- - 适当使用过渡句连接段落-- 3. **专业术语处理**:- - 首次出现时给出定义或解释- - 可使用「术语(英文原文)」格式-- **输出格式要求(严格遵循):**- - 只输出 JSON 对象,不要使用 ```json 代码块包裹- - JSON 字符串中的换行符应使用 \n 转义- - 确保 JSON 格式完全有效-- 输出示例:- {{- "section_content": "## 章节标题\n\n开篇段落...\n\n### 1.1 子章节标题\n\n内容...\n\n### 1.2 子章节标题\n\n内容...{citation_output_hint}"- }}-- **字数要求**:每个章节至少800字,内容翔实、论述充分-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- write_conclusion: |- 撰写研究报告的结论部分。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 研究主题:{topic}- 结论指导:{conclusion_instruction}- 关键发现:{topics_findings}- 总话题数:{total_topics}-- **结论写作框架**(500-700字):-- 1. **研究回顾与核心发现**(第1-2段):- - 简要回顾研究问题和方法- - 系统总结各章节的核心发现- - 归纳形成整体性结论-- 2. **研究贡献与价值**(第3段):- - **理论贡献**:对领域认知的推进- - **方法贡献**:新方法、新框架、新工具- - **实践价值**:对实际应用的指导意义-- 3. **局限性与反思**(第4段):- - 诚实指出研究的局限性- - 说明数据、方法或范围的约束- - 提示结论的适用边界-- 4. **未来展望**(第5段):- - 指出待解决的开放问题- - 提出有价值的研究方向- - 展望领域发展趋势-- **写作要求**:- - 结论应有高度概括性,避免重复正文细节- - 体现批判性思维,不回避局限性- - 展望应具体可行,不泛泛而谈- - 不要使用章节标题,直接写正文内容-- **输出格式要求(严格遵循):**- - 只输出 JSON 对象,不要使用 ```json 代码块包裹- - JSON 字符串中的特殊字符必须正确转义-- 输出示例:- {{- "conclusion": "完整的结论内容(Markdown格式,不含标题,500-700字)"- }}-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- write_full_report: |- 一次性撰写完整研究报告。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 研究主题:{topic}- 大纲 JSON:- {outline_json}-- 主题块数据:- {blocks_json}-- 总话题数:{total_topics}-- 引用要求:- {citation_instruction}-- **要求**:- 1. 严格遵循给定大纲结构:- - 保留总标题- - 包含引言、主体章节和结论- - 合理保留 `#`、`##`、`###` 层级- 2. 将各主题块摘要整合成一份连贯、完整的 Markdown 报告- 3. 报告保持精炼但信息充分,不要添加 References / 参考文献章节- 4. 如果 trace 中提供了引用编号,只能使用 `[N]` 格式,不要虚构编号- 5. 返回完整 Markdown 报告字符串-- 输出示例:- {{- "report": "# 标题\n\n## 引言\n\n...\n\n## 主体章节\n\n...\n\n## 结论\n\n..."- }}-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- # 新增:子章节写作提示词(用于三级标题内容)- write_subsection: |- 基于父章节上下文,撰写子章节内容。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 研究主题: {topic}- 父章节标题: {parent_section_title}- 子章节标题: {subsection_title}- 写作指导: {subsection_instruction}- 相关数据: {subsection_data}-- **写作要求**:-- 1. **内容定位**:- - 聚焦子章节的具体主题- - 与父章节保持逻辑连贯- - 避免与其他子章节内容重复-- 2. **深度要求**:- - 提供具体的技术细节或案例分析- - 适当使用公式、表格、图表等元素- - 论述要有理有据-- 3. **格式规范**:- - 使用 `###` 作为子章节标题- - 可使用 `####` 进一步细分(可选)- - 段落清晰,逻辑分明-- **输出格式要求(严格遵循):**- - 只输出 JSON 对象- - JSON 字符串中的换行符应使用 \n 转义-- 输出示例:- {{- "subsection_content": "### 子章节标题\n\n内容...\n\n#### 细分主题(可选)\n\n内容..."- }}-- **字数要求**:每个子章节300-500字-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- # ============================================================- # 学习笔记 (STUDY NOTES) — 模式专属 process 模板- # ============================================================-- generate_outline_study_notes: |- 为以下主题创建一份学习笔记大纲。-- **重要:你必须只输出一个有效的 JSON 对象,不要包含任何其他文本、解释或代码块标记。**-- 研究主题:{topic}-- 研究话题(包含subtopic、overview和tool_summaries):- {topics_json}-- 总话题数:{total_topics}-- **学习笔记大纲规则**(严格遵循):-- 1. **禁止**使用报告式结构(引言→分析→结论)。- 2. 按**学习单元**组织:围绕概念、机制、例子、易错点来分块。- 3. 标题必须**简短、直接、利于记忆**——如"核心概念:X"、"工作原理"、"易错提醒"、"速查表"。- 4. 末尾必须包含**速查表 / 备忘录**章节。- 5. 整体应像一本组织良好的笔记本,而不是论文的章节。-- 输出 JSON(严格匹配以下结构):- {{- "title": "# 学习笔记:主题标题",- "introduction": "## 本笔记涵盖内容",- "introduction_instruction": "用2-3句话说明读完这份笔记后学习者应掌握什么。不要写正式引言。",- "sections": [- {{- "title": "## 笔记 1. 章节标题",- "instruction": "涵盖该概念的核心定义、机制和一个具体的迷你例子。",- "block_id": "block_1",- "subsections": [- {{ "title": "### 它是什么", "instruction": "定义和直觉理解" }},- {{ "title": "### 工作原理", "instruction": "核心机制配合迷你例子" }},- {{ "title": "### 常见误区", "instruction": "易错点和常见误解" }}- ]- }}- ],- "conclusion": "## 速查表",- "conclusion_instruction": "提供可快速扫读的总结:关键术语及一句话定义、3-5条最重要的要点、常见易错点清单。"- }}-- **现在请直接输出 JSON 对象,不要包含任何其他内容。**-- write_introduction_study_notes: |- 为学习笔记写一段简短的导读。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 导读指导:{introduction_instruction}- 话题概览:{topics_summary}- 总话题数:{total_topics}-- **规则**:- - 只写**2-4句话**。不要写正式引言。- - 说明笔记涵盖什么、读完后读者应该能做/解释什么。- - 可选提及前置知识。- - 语气:友好、直接,像导师对学生说话。-- 输出:- {{- "introduction": "简短的导读文字(2-4句话,不含标题)"- }}-- **现在请直接输出 JSON 对象。**-- write_section_body_study_notes: |- 撰写一个学习笔记章节。输出必须看起来像高质量复习笔记——不是论文或报告章节。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 章节标题:{section_title}- 写作指导:{section_instruction}- 数据源:{block_data}-- **学习笔记写作规则**(强制):-- 1. **结构**:使用短段落、要点列表、编号步骤和标注块。绝不写长段连续散文。- 2. **定义框**:每个关键术语使用:- ```- > **定义 — 术语**:一句话解释。- ```- 3. **迷你例子**:每个章节至少包含一个具体的演算/解题例子。适当使用代码块、数学公式或分步推导。- 4. **易错提醒**:标注常见错误:- ```- > ⚠️ **常见误区**:错误描述及如何避免。- ```- 5. **要点总结块**:每个章节末尾:- ```- > 🔑 **核心要点**:本章节最重要的一件事。- ```- 6. **表格**:对比性概念、参数汇总或方法比较时使用对照表。- 7. **公式**:保留 LaTeX。行内:`$...$`。独立块:`$$...$$`。- 8. **自测微问题**:每节末尾加一个自测题:- ```- > 💡 **自测**:你能不看笔记解释<概念>吗?- ```- 9. **记忆锚点**:在适当位置加入助记或类比:- ```- > 🧠 **记忆锚点**:<助记符或类比>- ```- 10. **绝不**写成报告风格:不要"在本节中,我们将…",不要长段分析性散文,不要正式过渡句。-- {citation_instruction}-- 输出:- {{- "section_content": "## 章节标题\n\n> **定义 — X**:...\n\n- 要点 1\n- 要点 2\n\n**例子**:\n...\n\n> ⚠️ **常见误区**:...\n\n> 🧠 **记忆锚点**:...\n\n> 🔑 **核心要点**:...\n\n> 💡 **自测**:...{citation_output_hint}"- }}-- **字数要求**:400-700字。优先保证清晰度,而非长度。-- **现在请直接输出 JSON 对象。**-- write_conclusion_study_notes: |- 为学习笔记写一份速查表/备忘录结尾。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 结尾指导:{conclusion_instruction}- 关键发现:{topics_findings}- 总话题数:{total_topics}-- **规则**(强制):- - **禁止**写正式结论(不要"局限性"或"未来工作")。- - 输出一个可快速扫读的参考块,包含:- 1. **关键术语表**:术语 | 定义(每个核心概念一行)- 2. **重点提炼**:3-5条最重要的编号要点- 3. **易错清单**:要避免的错误的要点列表- 4. **自测清单**:列出学习者应凭记忆解释的核心概念。格式:`✅ 1. 你能解释...吗?`- - 保持紧凑、可扫读——这是备忘录,不是总结性文章。-- 输出:- {{- "conclusion": "| 术语 | 定义 |\n|---|---|\n| ... | ... |\n\n**重点提炼**\n1. ...\n2. ...\n\n**易错清单**\n- ...\n\n**自测清单**\n✅ 1. 你能解释...吗?\n✅ 2. ..."- }}-- **现在请直接输出 JSON 对象。**-- write_full_report_study_notes: |- 一次性撰写完整的学习笔记。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 大纲 JSON:- {outline_json}-- 主题块数据:- {blocks_json}-- 总话题数:{total_topics}-- 引用要求:- {citation_instruction}-- **关键要求**:输出必须读起来像组织良好的复习笔记,不是报告。-- **强制格式元素**:- - 定义框:`> **定义 — 术语**:...`- - 迷你例子(代码/数学/步骤)- - 易错提醒:`> ⚠️ **常见误区**:...`- - 核心要点块:`> 🔑 **核心要点**:...`- - 自测微问题:`> 💡 **自测**:你能不看笔记解释...吗?`- - 记忆锚点:`> 🧠 **记忆锚点**:<助记符或类比>`- - 适当使用对照表- - 结尾的速查表(术语表 + 重点提炼 + 易错清单 + 自测清单)- - 短段落和要点列表——绝不要长段散文-- 输出:- {{- "report": "# 学习笔记:标题\n\n## 本笔记涵盖内容\n...\n\n## 笔记 1. ...\n\n> **定义 — X**:...\n\n...\n\n## 速查表\n\n| 术语 | 定义 |\n|---|---|\n..."- }}-- **现在请直接输出 JSON 对象。**-- # ============================================================- # 对比分析 (COMPARISON) — 模式专属 process 模板- # ============================================================-- generate_outline_comparison: |- 为以下主题创建一份对比分析文档大纲。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}-- 研究话题(包含subtopic、overview和tool_summaries):- {topics_json}-- 总话题数:{total_topics}-- **对比分析大纲规则**(严格遵循):-- 1. **结构必须是维度优先**,而不是对象优先。每个主章节沿一个维度比较所有选项。- 2. 以"比较设定"章节开头(比较什么、为什么、评价标准)。- 3. 中间章节 = 每个比较维度或评价标准一个章节。- 4. 每个维度章节必须有对照表的位置。- 5. 以"权衡总结 + 按场景推荐"章节结尾。- 6. **绝不**按选项A、选项B分别描述来组织。-- 输出 JSON:- {{- "title": "# 对比分析:主题标题",- "introduction": "## 比较设定",- "introduction_instruction": "明确比较对象、比较原因、评价标准和目标决策场景。保持聚焦。",- "sections": [- {{- "title": "## 维度 1. 维度名称",- "instruction": "沿该维度比较所有选项。必须包含对照表、优缺点分析和适用场景判断。",- "block_id": "block_1",- "subsections": [- {{ "title": "### 并列对照", "instruction": "对照表 + 关键差异" }},- {{ "title": "### 权衡取舍", "instruction": "优点、缺点、约束条件" }},- {{ "title": "### 最佳适用", "instruction": "在该维度下,哪个选项最适合哪种场景" }}- ]- }}- ],- "conclusion": "## 结论与推荐",- "conclusion_instruction": "提供决策矩阵表(场景 x 选项 → 推荐)和明确的按场景推荐。"- }}-- **现在请直接输出 JSON 对象。**-- write_introduction_comparison: |- 撰写"比较设定"章节。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 设定指导:{introduction_instruction}- 话题概览:{topics_summary}- 总话题数:{total_topics}-- **规则**:- - 明确说明:(a) 比较哪些选项,(b) 为什么要比较,(c) 评价维度/标准,(d) 目标决策场景。- - 使用要点列表列出评价标准。- - 控制在300字以内。不要泛泛的背景铺垫。-- 输出:- {{- "introduction": "比较设定文字(不含标题)"- }}-- **现在请直接输出 JSON 对象。**-- write_section_body_comparison: |- 撰写对比维度章节。每个章节必须并列比较各选项——绝不单独描述某个选项。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 章节标题:{section_title}- 写作指导:{section_instruction}- 数据源:{block_data}-- **对比写作规则**(强制):-- 1. **对照表**:每个章节必须以 Markdown 表格开头或突出包含:- ```- | 评价指标 | 选项 A | 选项 B | 选项 C |- |----------|--------|--------|--------|- | ... | ... | ... | ... |- ```- 2. **维度分析**:表格之后,讨论该维度的关键权衡、细微差别和边缘情况。- 3. **优缺点**:使用明确的 `**优点**:` 和 `**缺点**:` 子块来分析每个选项。- 4. **量化评分**:为该维度下每个选项给出 1-5 分评分(1=差,5=优秀)。- 5. **适用场景判断**:以明确声明结尾:"对于场景X,选项Y更合适,因为…"- 6. **绝不**写孤立的选项介绍。每个段落都必须在比较。- 7. 使用加粗标签、表格和结构化列表。减少长段散文。-- {citation_instruction}-- 输出:- {{- "section_content": "## 维度标题\n\n| 指标 | A | B | 评分A | 评分B |\n|---|---|---|---|---|\n| ... | ... | ... | 4 | 3 |\n\n**分析**:...\n\n**优缺点**:\n- 选项A:...\n- 选项B:...\n\n**最佳适用**:对于场景X,推荐...{citation_output_hint}"- }}-- **字数要求**:每个维度章节500-800字。-- **现在请直接输出 JSON 对象。**-- write_conclusion_comparison: |- 撰写"结论与推荐"章节。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 结论指导:{conclusion_instruction}- 关键发现:{topics_findings}- 总话题数:{total_topics}-- **规则**(强制):- - **评分汇总表**:必须包含汇总所有维度评分的表格(1-5分):- ```- | 维度 | 选项 A | 选项 B | 选项 C |- |----------|--------|--------|--------|- | 维度 1 | 4 | 3 | 5 |- | 维度 2 | 3 | 5 | 2 |- | **平均** | **3.5**| **4.0**| **3.5**|- ```- - **决策矩阵表**:包含将场景/优先级映射到推荐选项的表格:- ```- | 如果你优先考虑… | 推荐选项 | 原因 |- |------------------|----------|------|- | 性能 | 选项 A | ... |- | 成本 | 选项 B | ... |- ```- - **按场景推荐**:表格之后,每个场景写2-3句话解释推荐理由。- - **绝不**写模糊的"视情况而定"结论。要明确、有立场。- - 不要写正式的"局限性和未来工作"。-- 输出:- {{- "conclusion": "**评分汇总**\n\n| 维度 | A | B |\n|---|---|---|\n| ... | 4 | 3 |\n| **平均** | **3.5** | **4.0** |\n\n**按场景推荐**\n\n| 如果你优先考虑… | 推荐选项 | 原因 |\n|---|---|---|\n| ... | ... | ... |\n\n**场景 1**:...\n\n**场景 2**:..."- }}-- **现在请直接输出 JSON 对象。**-- write_full_report_comparison: |- 一次性撰写完整的对比分析文档。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 大纲 JSON:- {outline_json}-- 主题块数据:- {blocks_json}-- 总话题数:{total_topics}-- 引用要求:- {citation_instruction}-- **关键要求**:输出必须读起来像一份维度优先的对比文档,不是普通报告。-- **强制元素**:- - 比较设定章节(定义比较什么/为什么/标准)- - 每个主章节 = 一个比较维度 + 对照表 + 每选项 1-5 量化评分- - 每个维度的优缺点分析- - 每个章节的适用场景判断- - 结论章节包含评分汇总表 + 决策矩阵表 + 按场景推荐- - 绝不孤立地描述各选项-- 输出:- {{- "report": "# 对比分析:标题\n\n## 比较设定\n...\n\n## 维度 1. ...\n\n| ... | A | B |\n...\n\n## 结论与推荐\n\n| 如果你优先考虑… | 推荐选项 | 原因 |\n..."- }}-- **现在请直接输出 JSON 对象。**-- # ============================================================- # 学习路径 (LEARNING PATH) — 模式专属 process 模板- # ============================================================-- generate_outline_learning_path: |- 为以下主题创建一份学习路径路线图大纲。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}-- 研究话题(包含subtopic、overview和tool_summaries):- {topics_json}-- 总话题数:{total_topics}-- **学习路径大纲规则**(严格遵循):-- 1. **结构必须是阶段优先且渐进式**。读者应能感受到从入门到精通的清晰进阶。- 2. 以"适用人群"章节开头(学习者画像、前置知识、最终目标)。- 3. 中间章节 = 顺序阶段(阶段1 → 阶段2 → 阶段3 → …)。按先修依赖排序——什么必须在什么之前学。- 4. 每个阶段必须包含:学习目标、核心内容、练习建议、检查站(如何判断准备好进入下一阶段)。- 5. 以"里程碑与下一步"结尾——进度标记和后续建议。- 6. **绝不**组织成平铺的主题报告。进阶感必须显而易见。-- 输出 JSON:- {{- "title": "# 学习路径:主题标题",- "introduction": "## 适用人群",- "introduction_instruction": "定义目标学习者(背景、水平)、前置知识、完成路径后能做什么、预计所需投入。",- "sections": [- {{- "title": "## 阶段 1. 阶段名称",- "instruction": "涵盖该阶段的基础概念。包含学习目标、核心内容、练习计划和检查站。",- "block_id": "block_1",- "subsections": [- {{ "title": "### 学习目标", "instruction": "完成该阶段后学习者应能做到什么" }},- {{ "title": "### 核心内容", "instruction": "该阶段的关键概念和材料" }},- {{ "title": "### 练习与实操", "instruction": "动手活动、练习题或项目" }},- {{ "title": "### 检查站", "instruction": "如何验证是否准备好进入下一阶段" }}- ]- }}- ],- "conclusion": "## 里程碑与下一步",- "conclusion_instruction": "提供覆盖所有阶段的里程碑检查表、自评标准,以及完成路径后的后续指导。"- }}-- **现在请直接输出 JSON 对象。**-- write_introduction_learning_path: |- 撰写学习路径的"适用人群"章节。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 学习者指导:{introduction_instruction}- 话题概览:{topics_summary}- 总话题数:{total_topics}-- **规则**:- - 明确定义:(a) 目标学习者画像,(b) 前置知识,(c) 完成后能做什么,(d) 预计时间/投入。- - 使用加粗标签的结构化格式。- - 控制在300字以内。要具体、可操作。-- 输出:- {{- "introduction": "**目标学习者**:...\n\n**前置知识**:...\n\n**完成后你将能够**:...\n\n**预计投入**:..."- }}-- **现在请直接输出 JSON 对象。**-- write_section_body_learning_path: |- 撰写一个学习阶段章节。输出必须读起来像结构化的课程阶段——不是报告章节。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 章节标题:{section_title}- 写作指导:{section_instruction}- 数据源:{block_data}-- **学习路径阶段规则**(强制):-- 1. **阶段元数据**:每个阶段开头标注:- ```- > ⏱️ **预计时间**:X 小时- > 📊 **难度**:基础 / 中级 / 高级- ```- 2. **学习目标**:以要点列表开头:"完成本阶段后你将能够:…"- 3. **为什么是现在**:简要解释先修链——为什么这个阶段在这个位置。- 4. **核心内容**:教授关键概念。适当使用定义框、例子、图表和代码。保持解释清晰、渐进。- 5. **练习计划**:包含具体的练习题、小项目或待解决的问题:- ```- > 📝 **练习**:做什么、预期结果、如何检验答案。- ```- 6. **推荐资源**:建议相关书籍、课程、工具或链接:- ```- > 📚 **推荐资源**:[推荐材料列表]- ```- 7. **检查站**:以自评块结尾:- ```- > ✅ **检查站 — 准备好进入阶段 N+1 了吗?**- > - 你能解释 X 吗?- > - 你能实现 Y 吗?- > - 你能判断 Z 什么时候适用吗?- ```- 8. **绝不**写成报告章节。每个段落都应帮助学习者**行动**,而不只是理解。-- {citation_instruction}-- 输出:- {{- "section_content": "## 阶段 N. 标题\n\n> ⏱️ **预计时间**:X 小时\n> 📊 **难度**:中级\n\n**学习目标**:\n- ...\n\n**为什么是现在**:...\n\n### 核心内容\n...\n\n> 📝 **练习**:...\n\n> 📚 **推荐资源**:...\n\n> ✅ **检查站 — 准备好进入阶段 N+1 了吗?**\n> - ...{citation_output_hint}"- }}-- **字数要求**:每个阶段500-800字。-- **现在请直接输出 JSON 对象。**-- write_conclusion_learning_path: |- 为学习路径撰写"里程碑与下一步"章节。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 里程碑指导:{conclusion_instruction}- 关键发现:{topics_findings}- 总话题数:{total_topics}-- **规则**(强制):- - **路线图**:包含 Mermaid 流程图展示阶段进阶:- ```mermaid- graph LR- A["阶段 1: ..."] --> B["阶段 2: ..."]- B --> C["阶段 3: ..."]- ```- - **里程碑检查表**:覆盖所有阶段的表格(含时间估算):- ```- | 阶段 | 里程碑 | 预计时间 | 自检 |- |------|--------|----------|------|- | 1 | ... | X 小时 | 你能…? |- ```- - **总时间估算**:汇总所有阶段时间。- - **自我评估**:帮助学习者判断整体准备度。- - **下一步**:完成路径后的具体建议——进阶主题、项目、社区、资源。- - **绝不**写正式结论(不要"局限性")。这是面向未来的、行动导向的。-- 输出:- {{- "conclusion": "**学习路线图**\n\n```mermaid\ngraph LR\n A[阶段 1] --> B[阶段 2]\n B --> C[阶段 3]\n```\n\n**里程碑检查表**\n\n| 阶段 | 里程碑 | 预计时间 | 自检 |\n|---|---|---|---|\n| ... | ... | X 小时 | ... |\n\n**总预计时间**:X 小时\n\n**自我评估**:...\n\n**下一步**:..."- }}-- **现在请直接输出 JSON 对象。**-- write_full_report_learning_path: |- 一次性撰写完整的学习路径文档。-- **重要:你必须只输出一个有效的 JSON 对象。**-- 研究主题:{topic}- 大纲 JSON:- {outline_json}-- 主题块数据:- {blocks_json}-- 总话题数:{total_topics}-- 引用要求:- {citation_instruction}-- **关键要求**:输出必须读起来像一份阶段化的学习课程,不是报告。-- **强制元素**:- - "适用人群"章节(学习者画像、前置知识、最终目标)- - 顺序阶段(阶段1 → 2 → 3…),每个包含:- - 阶段元数据:`> ⏱️ **预计时间**:X 小时` 和 `> 📊 **难度**:基础/中级/高级`- - 目标、为什么现在、核心内容、练习、推荐资源、检查站- - 练习块:`> 📝 **练习**:...`- - 推荐资源块:`> 📚 **推荐资源**:...`- - 检查站块:`> ✅ **检查站**:...`- - "里程碑与下一步"章节(Mermaid 路线图 + 里程碑表 + 总时间估算 + 后续建议)- - 全文可见的先修依赖链- - 绝不写成平铺的主题报告-- 输出:- {{- "report": "# 学习路径:标题\n\n## 适用人群\n...\n\n## 阶段 1. ...\n\n**学习目标**:\n...\n\n> 📝 **练习**:...\n\n> ✅ **检查站**:...\n\n## 里程碑与下一步\n..."- }}-- **现在请直接输出 JSON 对象。**diff --git a/deeptutor/agents/research/prompts/zh/research_agent.yaml b/deeptutor/agents/research/prompts/zh/research_agent.yamldeleted file mode 100644index 6de706045..000000000--- a/deeptutor/agents/research/prompts/zh/research_agent.yaml+++ /dev/null@@ -1,264 +0,0 @@-# ResearchAgent 提示词配置--system:- role: |- 你是一个基于知识库的深度研究策略专家,负责系统性地从知识库中挖掘与话题相关的内容,并根据需要拓展到外部资源。--mode_contracts:- study_notes_research: |- 你必须优先寻找有助于学习者**理解和记忆**的证据。- - 寻找:清晰定义、直觉解释、代表性例子、常见误解、记忆锚点。- - 跳过不能提升可教性的外围分支——核心概念的深度优于广覆盖。- - 问自己:"这能帮学生备考吗?"如果不能,降低优先级。- report_research: |- 你必须优先寻找能够支撑**分析、综合和论证**的证据。- - 寻找:权威来源、不同观点、方法细节、影响和局限。- - 研究路径必须服务于正式分析报告。绝不为速记提纲或比较分析优化。- comparison_research: |- 你必须优先寻找能够实现**维度间并列比较**的证据。- - 每个查询应针对一个具体的比较维度(如"A vs B 性能比较"、"A vs B 成本分析")。- - 绝不收集只介绍单个选项而不支持比较的信息。- - 寻找:维度基准、trade-off、优缺点、场景化判断。- - 如果一个查询不能帮助比较,那就是错误的查询。- learning_path_research: |- 你必须优先寻找支撑**学习顺序和教学推进**的证据。- - 寻找:先修关系、"先学X再学Y"的依据、典型瓶颈、练习建议、完成信号。- - 每个查询应帮助回答:"应该先学什么?接着学什么?为什么这个顺序?"- - 绝不收集无助于确定学习顺序的百科全书式信息。--# 动态内容的指导模板-guidance:- # 当 web_search 和 paper_search 都启用时的在线搜索指导- online_search_both: |- **在线搜索评估指导(web_search 和 paper_search 已启用)**:-- 在评估知识充足性时,除了评估知识库内容覆盖度外,还需要考虑:-- 1. **内容时效性评估**:- - 当前知识是否包含最新发展、行业趋势和应用案例?- - 是否需要补充最新背景信息和当前应用状态?- - 知识库内容是否可能过时,需要最新信息补充?-- 2. **知识扩展评估**:- - 知识是否已从基础知识库内容扩展到最新发展?- - 是否通过 web_search 补充了实时背景、行业案例和最新应用?- - 是否通过 paper_search 补充了前沿学术研究、最新理论进展和具体研究工作?-- 3. **研究完整性评估**:- - 如果话题涉及前沿研究或最新发展,是否通过在线搜索补充了相关内容?- - 是否形成了从知识库基础到最新发展的完整知识链?-- 判断标准:- - 如果知识库内容已充分探索 且 已通过在线搜索补充必要的实时信息/前沿研究,则视为充足- - 如果知识库内容已充分探索 但 缺少必要的实时信息/前沿研究补充,则视为不充足- - 如果知识库内容尚未充分探索,优先继续探索知识库,暂时忽略在线搜索-- # 当只启用 web_search 时的在线搜索指导- online_search_web_only: |- **在线搜索评估指导(web_search 已启用)**:-- 在评估知识充足性时,除了评估知识库内容覆盖度外,还需要考虑:-- 1. **内容时效性评估**:- - 当前知识是否包含最新发展、行业趋势和应用案例?- - 是否需要补充最新背景信息和当前应用状态?- - 知识库内容是否可能过时,需要最新信息补充?-- 2. **知识扩展评估**:- - 知识是否已从基础知识库内容扩展到最新发展?- - 是否通过 web_search 补充了实时背景、行业案例和最新应用?-- 判断标准:- - 如果知识库内容已充分探索 且 已通过 web_search 补充必要的实时信息,则视为充足- - 如果知识库内容已充分探索 但 缺少必要的实时信息补充,则视为不充足- - 如果知识库内容尚未充分探索,优先继续探索知识库,暂时忽略 web_search-- # 当只启用 paper_search 时的在线搜索指导- online_search_paper_only: |- **在线搜索评估指导(paper_search 已启用)**:-- 在评估知识充足性时,除了评估知识库内容覆盖度外,还需要考虑:-- 1. **前沿研究评估**:- - 当前知识是否包含相关前沿学术研究和最新理论进展?- - 是否需要补充具体研究工作、最新方法和最新发现?- - 知识库内容是否缺乏前沿研究视角?-- 2. **知识扩展评估**:- - 知识是否已从基础知识库内容扩展到前沿研究?- - 是否通过 paper_search 补充了前沿学术研究、最新理论进展和具体研究工作?-- 判断标准:- - 如果知识库内容已充分探索 且 已通过 paper_search 补充必要的前沿研究,则视为充足- - 如果知识库内容已充分探索 但 缺少必要的前沿研究补充,则视为不充足- - 如果知识库内容尚未充分探索,优先继续探索知识库,暂时忽略 paper_search-- # 灵活模式的迭代模式标准- iteration_mode_flexible: |- - **灵活模式(自动)**:你有自主权决定充足性。- - 如果知识确实全面,你可以提前得出充足结论- - 但仍需确保在得出结论前核心方面已被覆盖- - 质量优于数量:关注有意义的覆盖,而非迭代次数-- # 固定模式的迭代模式标准- iteration_mode_fixed: |- - **固定模式**:在宣布充足性时要保守。- - 在早期迭代(1-{early_threshold}):很少得出充足结论,继续探索- - 在中期迭代:需要有力证据证明全面覆盖- - 仅在后期迭代({early_threshold}+):如果确实全面,才考虑充足- - 目标是彻底探索,而非快速完成--process:- plan_next_step: |- 评估当前知识是否已经充足;如果不充足,再制定下一步查询计划。仅输出 JSON 对象:-- 话题: {topic}- 话题概览: {overview}- 当前知识: {current_knowledge}- 迭代次数: {iteration}- 已存在话题:- {existing_topics}- {online_search_instruction}- {research_depth_guidance}- {iteration_mode_criteria}-- **模式聚焦**:- {mode_instruction}-- **可用工具列表(只能使用以下工具)**:- {available_tools}-- {tool_phase_guidance}-- **重要原则:深度优先于广度**-- 你必须先判断当前知识是否已经达到"深度研究"标准,只有在不充分时才生成新的查询。-- **步骤1:充足性评估**- 至少评估以下 6 个维度:- - □ 概念定义- - □ 核心原理- - □ 关键公式/算法- - □ 应用场景- - □ 关联关系- - □ 局限与发展-- 充足性标准:- - 只有在以下条件全部满足时,才能设置 is_sufficient=true:- 1. 至少 5 个维度被实质覆盖- 2. 已覆盖维度有真实内容支撑,而非表面提及- 3. 当前迭代轮次对所选模式而言已经足够- - 否则设置 is_sufficient=false-- **步骤2:如果不充足,制定下一步查询**- - 只能从上面的可用工具中选择- - 每次查询必须针对一个具体知识缺口- - 避免重复当前知识- - 如果使用 paper_search,查询必须是英文关键词- - 如果当前没有任何工具可用,仍然要产出一个有价值的查询,并将 `tool_type` 设置为 `llm_self_research`-- **步骤3:新话题评估**- 只有在新话题与主线高度相关、与已有话题明确不同,并且足够重要时,才建议添加(score ≥ 0.85)。-- 输出 JSON:- {{- "is_sufficient": true/false,- "covered_dimensions": ["已覆盖的维度列表"],- "missing_dimensions": ["缺失或深度不足的维度列表"],- "coverage_score": 0.0-1.0,- "sufficiency_reason": "说明当前知识为什么充足或不充足",- "query": "具体查询语句;如果已充足则为空字符串",- "tool_type": "从可用工具列表中选择;如果当前无工具可用则填 llm_self_research;如果已充足则为空字符串",- "target_dimension": "本次查询针对的知识维度;如果已充足则为空字符串",- "rationale": "工具选择理由与查询目标;如果已充足则为空字符串",- "parallel": false,- "should_add_new_topic": false,- "new_sub_topic": null,- "new_overview": null,- "new_topic_reason": null,- "new_topic_score": 0.0- }}-- check_sufficiency: |- 判断以下话题的当前知识是否充足。仅输出 JSON 对象:-- 话题: {topic}- 话题概览: {overview}- 当前知识: {current_knowledge}- 迭代次数: {iteration}- {online_search_instruction}- {research_depth_guidance}- {iteration_mode_criteria}-- **重要原则:深度优先于广度**-- 你必须严格、系统地评估当前知识是否真正达到了"深度研究"的标准,而非仅仅"表面覆盖"。-- **评估步骤:**-- 1. **明确核心要素**(至少评估以下6个维度):- - □ 概念定义:是否有清晰、完整的定义?- - □ 核心原理:是否深入解释了工作机制、推导过程?- - □ 关键公式/算法:是否包含具体的数学表达或算法步骤?- - □ 应用场景:是否有具体的应用案例或实例分析?- - □ 关联关系:是否探索了与其他概念/领域的联系?- - □ 局限与发展:是否讨论了局限性、挑战或前沿发展?-- 2. **严格评估覆盖情况**:- - 统计已覆盖维度数量(至少需要覆盖4个以上维度)- - 评估每个维度的深度(表面提及 vs 深入分析)- - 识别关键遗漏(哪些维度完全未涉及或深度不足)-- 3. **判断充足性标准**:- - **充足**(is_sufficient=true):满足以下**全部**条件- ① 至少覆盖5个核心维度- ② 每个已覆盖维度都有实质内容(非仅提及)- ③ 迭代次数 ≥ 3(确保已进行多轮探索)- - **不充足**(is_sufficient=false):任一条件不满足-- 输出 JSON:- {{- "is_sufficient": true/false,- "covered_dimensions": ["已覆盖的维度列表"],- "missing_dimensions": ["缺失或深度不足的维度列表"],- "coverage_score": 0.0-1.0,- "reason": "判断理由(具体说明覆盖情况和判断依据)"- }}-- generate_query_plan: |- 知识不充分时,制定下一步查询计划。仅输出 JSON 对象:-- 话题: {topic}- 话题概览: {overview}- 当前知识: {current_knowledge}- 迭代次数: {iteration}- 已存在话题:- {existing_topics}-- **可用工具列表(只能使用以下工具)**:- {available_tools}-- {tool_phase_guidance}-- **查询设计原则**:- 1. **重要**:只能从上方"可用工具列表"中选择工具,不要使用未列出的工具- 2. 每次查询应针对一个具体的知识缺口- 3. 避免与当前知识中已有内容重复- 4. 查询应具体、可执行(避免过于宽泛)- 5. 如果使用 paper_search,必须使用英文关键词-- **新话题评估**:仅当发现与主题高度相关且与现有话题完全不同的重要分支时,才建议添加新话题(score ≥ 0.85)-- 输出 JSON:- {{- "query": "具体查询语句",- "tool_type": "从可用工具列表中选择",- "target_dimension": "本次查询针对的知识维度",- "rationale": "工具选择理由和查询目标",- "parallel": false,- "should_add_new_topic": false,- "new_sub_topic": null,- "new_overview": null,- "new_topic_reason": null,- "new_topic_score": 0.0- }}diff --git a/deeptutor/agents/research/request_config.py b/deeptutor/agents/research/request_config.pyindex 588e837cb..2aad565d1 100644--- a/deeptutor/agents/research/request_config.py+++ b/deeptutor/agents/research/request_config.py@@ -1,4 +1,11 @@-"""Validated request config and intent-to-policy mapping for deep research."""+"""Validated request config and intent-to-policy mapping for deep research.++Tool composition lives in :mod:`deeptutor.agents._shared.tool_composition`+— the same shim chat uses. Research has no separate ``sources`` knob:+whatever tools the user enables in the composer become available to the+per-block research loop, with ``rag`` auto-mounted when a KB is attached+(again, identical to chat).+"""from __future__ import annotations@@ -8,7 +15,6 @@ from pydantic import BaseModel, ConfigDict, ValidationError, field_validatorResearchMode = Literal["notes", "report", "comparison", "learning_path"]ResearchDepth = Literal["quick", "standard", "deep", "manual"]-ResearchSource = Literal["kb", "web", "papers"]class OutlineItem(BaseModel):@@ -21,19 +27,12 @@ class DeepResearchRequestConfig(BaseModel):mode: ResearchModedepth: ResearchDepth- sources: list[ResearchSource]manual_subtopics: int | None = Nonemanual_max_iterations: int | None = Noneconfirmed_outline: list[OutlineItem] | None = None- @field_validator("sources")- @classmethod- def validate_sources(cls, value: list[ResearchSource]) -> list[ResearchSource]:- deduped = list(dict.fromkeys(value))- return deduped-@field_validator("manual_subtopics")@classmethoddef validate_manual_subtopics(cls, value: int | None) -> int | None:@@ -67,7 +66,6 @@ def validate_research_request_config(def build_research_execution_policy(*,request_config: DeepResearchRequestConfig,- enabled_tools: set[str],) -> dict[str, Any]:depth_policy = _build_depth_policy(request_config.depth,@@ -83,22 +81,6 @@ def build_research_execution_policy(else:mode_policy["initial_subtopics"] = n- source_tools: set[str] = set()- if "kb" in request_config.sources:- source_tools.add("rag")- if "web" in request_config.sources:- source_tools.add("web_search")- if "papers" in request_config.sources:- source_tools.add("paper_search")-- allow_code_execution = (- bool(request_config.sources)- and "code_execution" in enabled_tools- and request_config.mode == "comparison"- and request_config.depth == "deep"- )- effective_tools = sorted(source_tools | ({"code_execution"} if allow_code_execution else set()))-planning = {"rephrase": {"enabled": mode_policy["rephrase_enabled"],@@ -115,12 +97,6 @@ def build_research_execution_policy("iteration_mode": depth_policy["iteration_mode"],"execution_mode": depth_policy["execution_mode"],"max_parallel_topics": depth_policy["max_parallel_topics"],- "new_topic_min_score": depth_policy["new_topic_min_score"],- "enable_rag": "rag" in source_tools,- "enable_web_search": "web_search" in source_tools,- "enable_paper_search": "paper_search" in source_tools,- "enable_run_code": allow_code_execution,- "enabled_tools": effective_tools,}reporting = {"min_section_length": mode_policy["min_section_length"],@@ -147,7 +123,6 @@ def build_research_runtime_config(*,base_config: dict[str, Any],request_config: DeepResearchRequestConfig,- enabled_tools: set[str],kb_name: str | None,) -> dict[str, Any]:capabilities = (@@ -169,10 +144,7 @@ def build_research_runtime_config(else {})rag_root: dict = {}- policy = build_research_execution_policy(- request_config=request_config,- enabled_tools=enabled_tools,- )+ policy = build_research_execution_policy(request_config=request_config)runtime_config = dict(base_config)runtime_config["planning"] = policy["planning"]@@ -212,12 +184,6 @@ def build_research_runtime_config()runtime_config["system"] = system_cfg- tools_cfg = dict(runtime_config.get("tools", {}) or {})- web_cfg = dict(tools_cfg.get("web_search", {}) or {})- web_cfg["enabled"] = bool(runtime_config["researching"].get("enable_web_search"))- tools_cfg["web_search"] = web_cfg- runtime_config["tools"] = tools_cfg-return runtime_config@@ -233,7 +199,6 @@ def _build_depth_policy("iteration_mode": "fixed","execution_mode": "series","max_parallel_topics": 1,- "new_topic_min_score": 0.95,"queue_max_length": 2,},"standard": {@@ -241,7 +206,6 @@ def _build_depth_policy("iteration_mode": "fixed","execution_mode": "series","max_parallel_topics": 1,- "new_topic_min_score": 0.88,"queue_max_length": 5,},"deep": {@@ -249,7 +213,6 @@ def _build_depth_policy("iteration_mode": "flexible","execution_mode": "parallel","max_parallel_topics": 3,- "new_topic_min_score": 0.78,"queue_max_length": 8,},}@@ -262,7 +225,6 @@ def _build_depth_policy("iteration_mode": "fixed","execution_mode": "series" if subtopics <= 3 else "parallel","max_parallel_topics": min(subtopics, 3),- "new_topic_min_score": 0.88,"queue_max_length": subtopics + 2,}@@ -278,6 +240,9 @@ def _build_mode_policy(mode: ResearchMode, depth: ResearchDepth) -> dict[str, An__all__ = ["DeepResearchRequestConfig",+ "OutlineItem",+ "ResearchDepth",+ "ResearchMode","build_research_execution_policy","build_research_runtime_config","validate_research_request_config",diff --git a/deeptutor/agents/research/research_pipeline.py b/deeptutor/agents/research/research_pipeline.pydeleted file mode 100644index e8033506e..000000000--- a/deeptutor/agents/research/research_pipeline.py+++ /dev/null@@ -1,1342 +0,0 @@-#!/usr/bin/env python-"""-ResearchPipeline 2.0 - Research workflow based on dynamic topic queue-Coordinates three stages: Planning -> Researching -> Reporting-"""--import asyncio-from datetime import datetime-import inspect-import json-import logging-from pathlib import Path-import sys-from typing import Any, Callable--from deeptutor.agents.research.agents import (- DecomposeAgent,- ManagerAgent,- NoteAgent,- RephraseAgent,- ReportingAgent,- ResearchAgent,-)-from deeptutor.agents.research.data_structures import DynamicTopicQueue-from deeptutor.agents.research.utils.citation_manager import CitationManager-from deeptutor.core.trace import new_call_id-from deeptutor.runtime.registry.tool_registry import get_tool_registry-from deeptutor.services.config import PROJECT_ROOT---class ResearchPipeline:- """DR-in-KG 2.0 Research workflow"""-- def __init__(- self,- config: dict[str, Any],- api_key: str,- base_url: str,- api_version: str | None = None,- research_id: str | None = None,- kb_name: str | None = None,- progress_callback: Callable | None = None,- trace_callback: Callable[[dict[str, Any]], Any] | None = None,- pre_confirmed_outline: list[dict[str, str]] | None = None,- attachments: list[Any] | None = None,- ):- """- Initialize research workflow-- Args:- config: Configuration dictionary- api_key: API key- base_url: API endpoint- api_version: API version (for Azure OpenAI)- research_id: Research task ID (optional)- kb_name: Knowledge base name (optional, if provided overrides config file setting)- progress_callback: Progress callback function (optional), signature: callback(event: Dict[str, Any])- pre_confirmed_outline: Pre-confirmed sub-topics from outline preview (skips decompose)- attachments: Optional chat attachments for the planning LLMs.- """- self.config = config- self.progress_callback = progress_callback- self.trace_callback = trace_callback- self.pre_confirmed_outline = pre_confirmed_outline- self.attachments = list(attachments or [])-- # If kb_name is provided, override config- if kb_name is not None:- if "rag" not in self.config:- self.config["rag"] = {}- self.config["rag"]["kb_name"] = kb_name- self.api_key = api_key- self.base_url = base_url- self.api_version = api_version or config.get("llm", {}).get("api_version")- self.input_topic: str | None = None- self.optimized_topic: str | None = None-- # Generate research ID- if research_id is None:- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- self.research_id = f"research_{timestamp}"- else:- self.research_id = research_id-- # Set directories- system_config = config.get("system", {})- self.cache_dir = (- Path(- system_config.get(- "output_base_dir",- "./data/user/workspace/chat/deep_research",- )- )- / self.research_id- )- self.reports_dir = Path(- system_config.get(- "reports_dir",- "./data/user/workspace/chat/deep_research/reports",- )- )-- # Create directories- self.cache_dir.mkdir(parents=True, exist_ok=True)- self.reports_dir.mkdir(parents=True, exist_ok=True)- self.plan_progress_file = self.cache_dir / "planning_progress.json"- self.report_progress_file = self.cache_dir / "reporting_progress.json"- self.queue_progress_file = self.cache_dir / "queue_progress.json"- self._stage_events: dict[str, list[dict[str, Any]]] = {- "planning": [],- "reporting": [],- }-- # Initialize queue- queue_cfg = config.get("queue", {})- self.queue = DynamicTopicQueue(- self.research_id,- max_length=queue_cfg.get("max_length"),- state_file=str(self.queue_progress_file),- )-- # Initialize unified logging system (must be before _init_agents)- self._init_logger()-- # Initialize Agents- self.agents = {}- self._init_agents()-- # Tool instances- self._tool_registry = get_tool_registry()-- # Citation manager- self.citation_manager = CitationManager(self.research_id, self.cache_dir)-- # Lock for thread-safe progress file writing in parallel mode- import threading-- self._progress_file_lock = threading.Lock()-- def _init_logger(self):- """Initialize unified logging system"""- # Get log_dir from config paths (user_log_dir from main.yaml)- log_dir = self.config.get("paths", {}).get("user_log_dir") or self.config.get(- "logging", {}- ).get("log_dir")-- self.logger = logging.getLogger(__name__)- self.logger.info("Logger initialized")-- def _init_agents(self):- """Initialize all Agents"""- if self.logger:- self.logger.info("Initializing Agents...")-- self.agents = {- "rephrase": RephraseAgent(- self.config, self.api_key, self.base_url, api_version=self.api_version- ),- "decompose": DecomposeAgent(- self.config, self.api_key, self.base_url, api_version=self.api_version- ),- "manager": ManagerAgent(- self.config, self.api_key, self.base_url, api_version=self.api_version- ),- "research": ResearchAgent(- self.config, self.api_key, self.base_url, api_version=self.api_version- ),- "note": NoteAgent(- self.config, self.api_key, self.base_url, api_version=self.api_version- ),- "reporting": ReportingAgent(- self.config, self.api_key, self.base_url, api_version=self.api_version- ),- }-- if self.trace_callback is not None:- for agent in self.agents.values():- if hasattr(agent, "set_trace_callback"):- agent.set_trace_callback(self.trace_callback)-- # Set Manager's queue- self.agents["manager"].set_queue(self.queue)-- if self.logger:- self.logger.info(f"Initialized {len(self.agents)} Agents")-- async def _emit_trace_event(self, payload: dict[str, Any]) -> None:- callback = self.trace_callback- if callback is None:- return- result = callback(payload)- if inspect.isawaitable(result):- await result-- async def _call_tool_with_timeout(- self, coro, timeout: float = 60.0, tool_name: str = "tool"- ) -> Any:- """- Execute a coroutine with timeout support-- Args:- coro: Coroutine to execute- timeout: Timeout in seconds (default 60s)- tool_name: Name of the tool for logging-- Returns:- Result of the coroutine-- Raises:- asyncio.TimeoutError: If timeout exceeded- """- try:- return await asyncio.wait_for(coro, timeout=timeout)- except asyncio.TimeoutError:- self.logger.warning(f"Tool {tool_name} timed out after {timeout}s")- raise-- async def _call_tool_with_retry(- self,- tool_func,- *args,- max_retries: int = 2,- timeout: float = 60.0,- tool_name: str = "tool",- **kwargs,- ) -> Any:- """- Call a tool function with retry and timeout support-- Args:- tool_func: Tool function to call- *args: Positional arguments for the function- max_retries: Maximum number of retries (default 2)- timeout: Timeout per attempt in seconds (default 60s)- tool_name: Name of the tool for logging- **kwargs: Keyword arguments for the function-- Returns:- Result of the tool function- """- last_error = None-- for attempt in range(max_retries + 1):- try:- if asyncio.iscoroutinefunction(tool_func):- result = await self._call_tool_with_timeout(- tool_func(*args, **kwargs), timeout=timeout, tool_name=tool_name- )- else:- # For sync functions, run in executor- import functools-- loop = asyncio.get_running_loop()- result = await asyncio.wait_for(- loop.run_in_executor(None, functools.partial(tool_func, *args, **kwargs)),- timeout=timeout,- )- return result- except asyncio.TimeoutError as e:- last_error = e- if attempt < max_retries:- self.logger.warning(- f"Tool {tool_name} attempt {attempt + 1} timed out, retrying..."- )- await asyncio.sleep(1) # Brief pause before retry- except Exception as e:- last_error = e- if attempt < max_retries:- self.logger.warning(- f"Tool {tool_name} attempt {attempt + 1} failed: {e}, retrying..."- )- await asyncio.sleep(1)-- # All retries exhausted- self.logger.error(f"Tool {tool_name} failed after {max_retries + 1} attempts: {last_error}")- raise last_error if last_error else RuntimeError(f"{tool_name} failed")-- async def _call_tool(self, tool_type: str, query: str) -> str:- """Call tool and return raw string answer (JSON string or text)"""- tool_type = (tool_type or "").lower()- call_id = new_call_id("research-tool")- await self._emit_trace_event(- {- "event": "tool_call",- "phase": "researching",- "call_id": call_id,- "label": f"Use {tool_type or 'tool'}",- "call_kind": "tool_execution",- "tool_name": tool_type or "tool",- "tool_args": {"query": query},- "query": query,- }- )-- # Get timeout and retry settings from config- tool_config = self.config.get("researching", {})- default_timeout = tool_config.get("tool_timeout", 60)- max_retries = tool_config.get("tool_max_retries", 2)-- try:- if tool_type in ("rag_hybrid", "rag_naive", "rag"):- rag_cfg = self.config.get("rag", {}) or {}- kb_name = rag_cfg.get("kb_name")- if not kb_name:- skipped = json.dumps(- {- "status": "skipped",- "reason": "no_kb_selected",- "message": (- "RAG retrieval was requested but no "- "knowledge base is configured for this "- "research run."- ),- "tool": "rag",- "query": query,- },- ensure_ascii=False,- )- await self._emit_trace_event(- {- "event": "tool_result",- "phase": "researching",- "call_id": call_id,- "label": "Use rag",- "call_kind": "tool_execution",- "tool_name": "rag",- "result": skipped,- "state": "skipped",- "query": query,- }- )- return skipped- result = await self._call_tool_with_retry(- self._tool_registry.execute,- "rag",- query=query,- kb_name=kb_name,- max_retries=max_retries,- timeout=default_timeout,- tool_name="rag",- )- elif tool_type == "web_search":- result = await self._call_tool_with_retry(- self._tool_registry.execute,- tool_type,- query=query,- output_dir=str(self.cache_dir),- max_retries=max_retries,- timeout=default_timeout,- tool_name="web_search",- )- elif tool_type == "paper_search":- years_limit = self.config.get("researching", {}).get("paper_search_years_limit", 3)- result = await self._call_tool_with_retry(- self._tool_registry.execute,- tool_type,- query=query,- max_results=3,- years_limit=years_limit,- max_retries=max_retries,- timeout=default_timeout,- tool_name="paper_search",- )- elif tool_type in {"run_code", "code_execution", "code_execute"}:- result = await self._call_tool_with_retry(- self._tool_registry.execute,- tool_type,- intent=query,- feature="deep_research",- task_id=self.research_id,- max_retries=1,- timeout=30,- tool_name="run_code",- )- else:- unknown = json.dumps(- {- "status": "failed",- "reason": "unknown_tool",- "tool": tool_type,- "query": query,- },- ensure_ascii=False,- )- await self._emit_trace_event(- {- "event": "tool_result",- "phase": "researching",- "call_id": call_id,- "label": f"Use {tool_type or 'tool'}",- "call_kind": "tool_execution",- "tool_name": tool_type or "tool",- "result": unknown,- "state": "error",- "query": query,- }- )- return unknown- except Exception as e:- failure = json.dumps(- {"status": "failed", "error": str(e), "tool": tool_type, "query": query},- ensure_ascii=False,- )- await self._emit_trace_event(- {- "event": "tool_result",- "phase": "researching",- "call_id": call_id,- "label": f"Use {tool_type or 'tool'}",- "call_kind": "tool_execution",- "tool_name": tool_type or "tool",- "result": failure,- "state": "error",- "query": query,- }- )- return failure-- serialized = self._serialise_tool_result(result)- await self._emit_trace_event(- {- "event": "tool_result",- "phase": "researching",- "call_id": call_id,- "label": f"Use {tool_type or 'tool'}",- "call_kind": "tool_execution",- "tool_name": tool_type or "tool",- "result": serialized,- "state": "complete",- "query": query,- }- )- return serialized-- @staticmethod- def _serialise_tool_result(result) -> str:- payload = dict(result.metadata or {})- if "content" not in payload:- payload["content"] = result.content- if result.sources:- if "sources" not in payload:- payload["sources"] = result.sources- else:- payload["tool_sources"] = result.sources- payload.setdefault("success", result.success)- return json.dumps(payload, ensure_ascii=False)-- async def run(self, topic: str) -> dict[str, Any]:- """- Execute complete research workflow-- Args:- topic: Research topic-- Returns:- Research result- """- if self.logger:- self.logger.info("DR-in-KG 2.0 - Deep Research System Based on Dynamic Topic Queue")- self.logger.info(f"Research Topic: {topic}")- self.logger.info(f"Research ID: {self.research_id}")- self.input_topic = topic-- try:- # ========== Phase 1: Planning (Planning and Initialization) ==========- self.logger.info("\n" + "═" * 70)- self.logger.info("▶ Phase 1: Planning - Planning and Initialization")- self.logger.info("═" * 70)-- optimized_topic = await self._phase1_planning(topic)-- # ========== Phase 2: Researching (Dynamic Research Loop) ==========- self.logger.info("\n" + "═" * 70)- self.logger.info("▶ Phase 2: Researching - Dynamic Research Loop")- self.logger.info("═" * 70)-- await self._phase2_researching()-- # ========== Phase 3: Reporting (Report Generation) ==========- self.logger.info("\n" + "═" * 70)- self.logger.info("▶ Phase 3: Reporting - Report Generation")- self.logger.info("═" * 70)-- report_result = await self._phase3_reporting(optimized_topic)-- # ========== Save Results ==========- self.logger.info("\n" + "═" * 70)- self.logger.info("▶ Save Results")- self.logger.info("═" * 70 + "\n")-- report_file = self.reports_dir / f"{self.research_id}.md"- with open(report_file, "w", encoding="utf-8") as f:- f.write(report_result["report"])- self.logger.info(f"Final Report: {report_file}")-- # Save queue- queue_file = self.cache_dir / "queue.json"- self.queue.save_to_json(str(queue_file))- self.logger.info(f"Queue Data: {queue_file}")-- # Save outline (if exists)- if "outline" in report_result:- outline_file = self.cache_dir / "outline.json"- with open(outline_file, "w", encoding="utf-8") as f:- json.dump(report_result["outline"], f, ensure_ascii=False, indent=2)- self.logger.info(f"Report Outline: {outline_file}")-- # Save metadata- metadata = {- "research_id": self.research_id,- "topic": topic,- "optimized_topic": optimized_topic,- "statistics": self.queue.get_statistics(),- "report_word_count": report_result["word_count"],- "completed_at": datetime.now().isoformat(),- }-- metadata_file = self.reports_dir / f"{self.research_id}_metadata.json"- with open(metadata_file, "w", encoding="utf-8") as f:- json.dump(metadata, f, ensure_ascii=False, indent=2)- self.logger.info(f"Metadata: {metadata_file}")-- # ===== Token Cost Statistics =====- try:- from deeptutor.agents.research.utils.token_tracker import get_token_tracker-- tracker = get_token_tracker()- cost_summary_text = tracker.format_summary()- self.logger.info(cost_summary_text)- cost_file = self.cache_dir / "token_cost_summary.json"- tracker.save(str(cost_file))- self.logger.info(f"Cost statistics saved: {cost_file}")- t_summary = tracker.get_summary()- if t_summary.get("total_calls", 0) > 0:- metadata["cost_summary"] = {- "total_cost_usd": t_summary.get("total_cost_usd", 0),- "total_tokens": t_summary.get("total_tokens", 0),- "total_calls": t_summary.get("total_calls", 0),- }- except Exception as _e:- self.logger.warning(f"Cost statistics failed: {_e}")-- self.logger.info("\n" + "=" * 70)- self.logger.info("Research Completed!")- self.logger.info("=" * 70)- self.logger.info(f"Research ID: {self.research_id}")- self.logger.info(f"Topic: {topic}")- self.logger.info(f"Final Report: {report_file}")- self.logger.info(f"Report Word Count: {report_result['word_count']}")- self.logger.info(f"Topic Blocks: {len(self.queue.blocks)}")- self.logger.info("=" * 70 + "\n")-- return {- "research_id": self.research_id,- "topic": topic,- "report": report_result["report"],- "final_report_path": str(report_file),- "metadata": metadata,- }-- except KeyboardInterrupt:- self.logger.warning("\n\n⚠️ Research interrupted by user")- sys.exit(0)- except Exception as e:- self.logger.error(f"\n\n✗ Research failed: {e!s}")- import traceback-- self.logger.error(traceback.format_exc())- raise-- async def _phase1_planning(self, topic: str) -> str:- """- Phase 1: Planning and Initialization-- Args:- topic: User input topic-- Returns:- Optimized topic- """- self._log_progress("planning", "planning_started", user_topic=topic)-- if self.pre_confirmed_outline:- self.logger.info(- "\n【Step 1-2】Using pre-confirmed outline (skipping rephrase + decompose)..."- )- optimized_topic = topic- self.optimized_topic = optimized_topic- self._log_progress(- "planning",- "rephrase_skipped",- optimized_topic=optimized_topic,- reason="pre-confirmed outline provided",- )-- self.logger.info("\n【Step 3】Initializing Queue from confirmed outline...")- for item in self.pre_confirmed_outline:- title = (item.get("title") or "").strip()- overview = item.get("overview", "")- if not title:- continue- try:- block = self.queue.add_block(sub_topic=title, overview=overview)- self._log_progress(- "planning",- "queue_seeded",- block_id=block.block_id,- sub_topic=block.sub_topic,- total_blocks=len(self.queue.blocks),- )- except RuntimeError as err:- self.logger.warning(f"Queue reached capacity limit: {err}")- break-- stats = self.queue.get_statistics()- self._log_progress("planning", "planning_completed", total_blocks=stats["total_blocks"])- self.logger.info("\nPhase 1 Completed (from confirmed outline):")- self.logger.info(f" - Topic: {optimized_topic}")- self.logger.info(f" - Subtopic Count: {stats['total_blocks']}")- self.agents["manager"].set_primary_topic(optimized_topic)- return optimized_topic-- rephrase_config = self.config.get("planning", {}).get("rephrase", {})- rephrase_enabled = rephrase_config.get("enabled", True)-- if rephrase_enabled:- self.logger.info("\n【Step 1】Topic Rephrasing...")- max_iterations = rephrase_config.get("max_iterations", 3)- rephrase_result = {"topic": topic}- current_topic = topic- iteration = 0- planning_attachments_used = False-- while iteration < max_iterations:- first_rephrase_turn = iteration == 0- rephrase_result = await self.agents["rephrase"].process(- current_topic,- iteration=iteration,- previous_result=rephrase_result,- attachments=self.attachments if first_rephrase_turn else None,- )- if first_rephrase_turn:- planning_attachments_used = True- iteration += 1- next_topic = str(rephrase_result.get("topic", "") or "").strip()- if not next_topic:- break- if next_topic == current_topic.strip():- current_topic = next_topic- break- current_topic = next_topic-- optimized_topic = current_topic or topic- self._log_progress(- "planning",- "rephrase_completed",- optimized_topic=optimized_topic,- iterations=iteration,- )- else:- self.logger.info("\n【Step 1】Topic Rephrasing (disabled, skipping)...")- optimized_topic = topic- planning_attachments_used = False- self._log_progress(- "planning",- "rephrase_skipped",- optimized_topic=optimized_topic,- reason="rephrase feature disabled",- )-- self.optimized_topic = optimized_topic-- self.logger.info("\n【Step 2】Topic Decomposition...")-- decompose_config = self.config.get("planning", {}).get("decompose", {})- mode = decompose_config.get("mode", "manual")-- if mode == "auto":- num_subtopics = decompose_config.get(- "auto_max_subtopics", decompose_config.get("initial_subtopics", 5)- )- self.logger.info(f"📌 Using Auto mode, max subtopics: {num_subtopics}")- else:- num_subtopics = decompose_config.get("initial_subtopics", 5)- self.logger.info(f"📌 Using Manual mode, expected subtopics: {num_subtopics}")-- self._log_progress(- "planning", "decompose_started", requested_subtopics=num_subtopics, mode=mode- )-- self.agents["decompose"].set_citation_manager(self.citation_manager)-- decompose_result = await self.agents["decompose"].process(- topic=optimized_topic,- num_subtopics=num_subtopics,- mode=mode,- attachments=self.attachments if not planning_attachments_used else None,- )- self._log_progress(- "planning",- "decompose_completed",- generated_subtopics=decompose_result.get("total_subtopics", 0),- rag_context_length=len(decompose_result.get("rag_context", "") or ""),- )-- try:- step1_path = self.cache_dir / "step1_planning.json"- with open(step1_path, "w", encoding="utf-8") as f:- json.dump(- {- "main_topic": optimized_topic,- "sub_queries": decompose_result.get("sub_queries", []),- "rag_context": decompose_result.get("rag_context", ""),- "sub_topics": decompose_result.get("sub_topics", []),- "total_subtopics": decompose_result.get("total_subtopics", 0),- "timestamp": datetime.now().isoformat(),- },- f,- ensure_ascii=False,- indent=2,- )- self.logger.info(f"Planning stage data saved: {step1_path}")- except Exception as _e:- self.logger.warning(f"Failed to save Planning stage data: {_e}")-- self.logger.info("\n【Step 3】Initializing Queue...")- for sub_topic_data in decompose_result.get("sub_topics", []):- title = (sub_topic_data.get("title") or "").strip()- overview = sub_topic_data.get("overview", "")- if not title:- continue- try:- block = self.queue.add_block(sub_topic=title, overview=overview)- self._log_progress(- "planning",- "queue_seeded",- block_id=block.block_id,- sub_topic=block.sub_topic,- total_blocks=len(self.queue.blocks),- )- except RuntimeError as err:- self._log_progress(- "planning", "queue_capacity_reached", error=str(err), attempted_topic=title- )- self.logger.warning(- f"Queue reached capacity limit, stopping addition of initial topics: {err}"- )- break-- stats = self.queue.get_statistics()- self._log_progress("planning", "planning_completed", total_blocks=stats["total_blocks"])- self.logger.info("\nPhase 1 Completed:")- self.logger.info(f" - Optimized Topic: {optimized_topic}")- self.logger.info(f" - Subtopic Count: {stats['total_blocks']}")- self.agents["manager"].set_primary_topic(optimized_topic)-- return optimized_topic-- async def _phase2_researching(self):- """- Phase 2: Dynamic Research Loop- Routes to series or parallel execution based on configuration- """- execution_mode = self.config.get("researching", {}).get("execution_mode", "series")-- if execution_mode == "parallel":- await self._phase2_researching_parallel()- else:- await self._phase2_researching_series()-- async def _phase2_researching_series(self):- """- Phase 2: Dynamic Research Loop (Series Mode - Original Implementation)- """- # Initialize researching stage event list- if "researching" not in self._stage_events:- self._stage_events["researching"] = []-- manager = self.agents["manager"]- research = self.agents["research"]-- total_blocks = len(self.queue.blocks)- completed_blocks = 0-- self._log_researching_progress(- "researching_started", total_blocks=total_blocks, execution_mode="series"- )-- while not manager.is_research_complete():- # Get next task to research- block = manager.get_next_task()- if not block:- break-- self._log_researching_progress(- "block_started",- block_id=block.block_id,- sub_topic=block.sub_topic,- current_block=completed_blocks + 1,- total_blocks=total_blocks,- )-- # Create iteration progress callback for this block- iteration_callback = self._create_iteration_progress_callback(- block_id=block.block_id,- sub_topic=block.sub_topic,- execution_mode="series",- current_block=completed_blocks + 1,- total_blocks=total_blocks,- )-- # Execute research loop (unified handling by ResearchAgent.process)- result = await research.process(- topic_block=block,- call_tool_callback=self._call_tool,- note_agent=self.agents["note"],- citation_manager=self.citation_manager,- queue=self.queue,- manager_agent=manager,- config=self.config,- progress_callback=iteration_callback,- )-- # Mark as completed- manager.complete_task(block.block_id)- completed_blocks += 1-- # Update total_blocks in case new topics were added- total_blocks = len(self.queue.blocks)-- self._log_researching_progress(- "block_completed",- block_id=block.block_id,- sub_topic=block.sub_topic,- iterations=result.get("iterations", 0),- tools_used=result.get("tools_used", []),- queries_used=result.get("queries_used", []),- current_block=completed_blocks,- total_blocks=total_blocks,- )-- # Display statistics- manager.get_queue_status()-- stats = self.queue.get_statistics()- self._log_researching_progress(- "researching_completed",- completed_blocks=stats["completed"],- total_tool_calls=stats["total_tool_calls"],- )-- self.logger.info("\nPhase 2 Completed:")- self.logger.info(f" - Completed Topics: {stats['completed']}")- self.logger.info(f" - Total Tool Calls: {stats['total_tool_calls']}")-- async def _phase2_researching_parallel(self):- """- Phase 2: Dynamic Research Loop (Parallel Mode)- Executes multiple topic blocks in parallel with concurrency limit- """- # Initialize researching stage event list- if "researching" not in self._stage_events:- self._stage_events["researching"] = []-- manager = self.agents["manager"]- research = self.agents["research"]-- # Get configuration- max_parallel = self.config.get("researching", {}).get("max_parallel_topics", 5)- semaphore = asyncio.Semaphore(max_parallel)-- # Get all pending blocks at the start- from deeptutor.agents.research.data_structures import TopicStatus-- pending_blocks = [b for b in self.queue.blocks if b.status == TopicStatus.PENDING]- total_blocks = len(self.queue.blocks)-- self.logger.info(- f"\n🚀 Starting parallel research mode (max {max_parallel} concurrent topics)"- )- self._log_researching_progress(- "researching_started",- total_blocks=total_blocks,- execution_mode="parallel",- max_parallel=max_parallel,- initial_pending=len(pending_blocks),- )-- # Track completed blocks- completed_count = {"value": 0} # Use dict to allow modification in nested function-- # Create async wrappers for thread-safe operations in parallel mode- class AsyncCitationManagerWrapper:- """Wrapper to use async citation manager methods in parallel mode"""-- def __init__(self, cm):- self._cm = cm-- async def add_citation(self, citation_id, tool_type, tool_trace, raw_answer):- return await self._cm.add_citation_async(- citation_id, tool_type, tool_trace, raw_answer- )-- def __getattr__(self, name):- # Forward other attributes to original citation_manager- return getattr(self._cm, name)-- class AsyncManagerAgentWrapper:- """Wrapper to use async manager agent methods in parallel mode"""-- def __init__(self, ma):- self._ma = ma-- async def add_new_topic(self, sub_topic, overview):- return await self._ma.add_new_topic_async(sub_topic, overview)-- def __getattr__(self, name):- # Forward other attributes to original manager_agent- return getattr(self._ma, name)-- async_citation_manager = AsyncCitationManagerWrapper(self.citation_manager)- async_manager_agent = AsyncManagerAgentWrapper(manager)-- # Track active tasks for parallel progress display- active_tasks: dict[str, dict[str, Any]] = {} # block_id -> task info- active_tasks_lock = asyncio.Lock()-- async def update_active_task(block_id: str, info: dict[str, Any] | None):- """Update active task info (thread-safe)"""- async with active_tasks_lock:- if info is None:- active_tasks.pop(block_id, None)- else:- active_tasks[block_id] = info- # Send parallel status update- self._log_researching_progress(- "parallel_status_update",- active_tasks=list(active_tasks.values()),- active_count=len(active_tasks),- completed_count=completed_count["value"],- total_blocks=total_blocks,- )-- async def research_single_block(block: Any) -> dict[str, Any] | None:- """- Research a single topic block with semaphore control-- Args:- block: TopicBlock to research-- Returns:- Research result or None if failed- """- async with semaphore:- try:- # Mark as researching (thread-safe)- async with manager._lock:- # Refresh block status from queue- current_block = self.queue.get_block_by_id(block.block_id)- if current_block and current_block.status == TopicStatus.PENDING:- self.queue.mark_researching(block.block_id)-- # Add to active tasks- await update_active_task(- block.block_id,- {- "block_id": block.block_id,- "sub_topic": block.sub_topic,- "status": "starting",- "iteration": 0,- "current_tool": None,- "current_query": None,- },- )-- self._log_researching_progress(- "block_started",- block_id=block.block_id,- sub_topic=block.sub_topic,- execution_mode="parallel",- active_count=len(active_tasks),- )-- if self.logger:- self.logger.info(- f"\n[{block.block_id}] 🔍 Starting research: {block.sub_topic}"- )-- # Get max_iterations from config for this closure- config_max_iterations = self.config.get("researching", {}).get(- "max_iterations", 5- )-- # Create iteration callback for parallel mode- def parallel_iteration_callback(event_type: str, **data):- """Handle iteration progress in parallel mode"""- # Update active task info- task_info = {- "block_id": block.block_id,- "sub_topic": block.sub_topic,- "status": event_type,- "iteration": data.get("iteration", 0),- "max_iterations": data.get("max_iterations", config_max_iterations),- "current_tool": data.get("tool_type"),- "current_query": data.get("query"),- "tools_used": data.get("tools_used", []),- }- # Schedule async update- asyncio.create_task(update_active_task(block.block_id, task_info))-- # Also log the detailed progress- self._log_researching_progress(- event_type,- block_id=block.block_id,- sub_topic=block.sub_topic,- execution_mode="parallel",- **data,- )-- # Execute research loop with async wrappers- result = await research.process(- topic_block=block,- call_tool_callback=self._call_tool,- note_agent=self.agents["note"],- citation_manager=async_citation_manager,- queue=self.queue,- manager_agent=async_manager_agent,- config=self.config,- progress_callback=parallel_iteration_callback,- )-- # Mark as completed (thread-safe)- await manager.complete_task_async(block.block_id)- completed_count["value"] += 1-- # Remove from active tasks- await update_active_task(block.block_id, None)-- self._log_researching_progress(- "block_completed",- block_id=block.block_id,- sub_topic=block.sub_topic,- iterations=result.get("iterations", 0),- tools_used=result.get("tools_used", []),- queries_used=result.get("queries_used", []),- current_block=completed_count["value"],- total_blocks=total_blocks,- execution_mode="parallel",- )-- if self.logger:- self.logger.info(f"[{block.block_id}] ✓ Completed: {block.sub_topic}")-- return result-- except Exception as e:- # Mark as failed (thread-safe)- await manager.fail_task_async(block.block_id, str(e))- completed_count["value"] += 1-- # Remove from active tasks- await update_active_task(block.block_id, None)-- if self.logger:- self.logger.error(f"[{block.block_id}] ✗ Failed: {block.sub_topic} - {e}")-- self._log_researching_progress(- "block_failed",- block_id=block.block_id,- sub_topic=block.sub_topic,- error=str(e),- execution_mode="parallel",- )- return None-- # Execute all research tasks in parallel- tasks = [research_single_block(block) for block in pending_blocks]- results = await asyncio.gather(*tasks, return_exceptions=True)-- # Handle any exceptions that weren't caught- for i, result in enumerate(results):- if isinstance(result, Exception):- block = pending_blocks[i]- await manager.fail_task_async(block.block_id, str(result))- if self.logger:- self.logger.error(f"[{block.block_id}] ✗ Exception: {result}")-- # Wait for any dynamically added topics (if manager adds new topics during research)- # Continue until all tasks are processed (completed or failed)- max_wait_iterations = 100 # Prevent infinite loop- wait_count = 0-- while True:- # Check if all blocks are processed (COMPLETED or FAILED, not PENDING or RESEARCHING)- stats = self.queue.get_statistics()- pending_count = stats.get("pending", 0)- researching_count = stats.get("researching", 0)-- # Exit if no pending or researching tasks- if pending_count == 0 and researching_count == 0:- break-- # Get any newly added pending blocks- new_pending = [b for b in self.queue.blocks if b.status == TopicStatus.PENDING]- if not new_pending:- # No pending blocks, but there might be researching ones- # Wait a bit for them to complete- wait_count += 1- if wait_count > max_wait_iterations:- self.logger.warning(- "Max wait iterations reached, exiting parallel research loop"- )- break- await asyncio.sleep(0.1)- continue-- # Reset wait count when we have new work- wait_count = 0-- # Research newly added blocks- new_tasks = [research_single_block(block) for block in new_pending]- new_results = await asyncio.gather(*new_tasks, return_exceptions=True)-- for i, result in enumerate(new_results):- if isinstance(result, Exception):- block = new_pending[i]- await manager.fail_task_async(block.block_id, str(result))-- stats = self.queue.get_statistics()- self._log_researching_progress(- "researching_completed",- completed_blocks=stats["completed"],- total_tool_calls=stats["total_tool_calls"],- execution_mode="parallel",- )-- self.logger.info("\nPhase 2 Completed (Parallel Mode):")- self.logger.info(f" - Completed Topics: {stats['completed']}")- self.logger.info(f" - Total Tool Calls: {stats['total_tool_calls']}")- self.logger.info(f" - Failed Topics: {stats.get('failed', 0)}")-- def _log_researching_progress(self, status: str, **payload: Any) -> None:- """Record researching stage progress (thread-safe for parallel mode)"""- event = {"status": status, "timestamp": datetime.now().isoformat()}- event.update({k: v for k, v in payload.items() if v is not None})-- # Use lock to prevent concurrent file writes in parallel mode- with self._progress_file_lock:- if "researching" not in self._stage_events:- self._stage_events["researching"] = []- self._stage_events["researching"].append(event)-- # Save to file- research_progress_file = self.cache_dir / "researching_progress.json"- context = {- "research_id": self.research_id,- "stage": "researching",- "input_topic": self.input_topic,- "optimized_topic": self.optimized_topic,- "events": self._stage_events["researching"],- }- with open(research_progress_file, "w", encoding="utf-8") as f:- json.dump(context, f, ensure_ascii=False, indent=2)-- # Send progress via callback- if self.progress_callback:- try:- progress_event = {- "type": "progress",- "stage": "researching",- "status": status,- "research_id": self.research_id,- **{k: v for k, v in payload.items() if v is not None},- }- self.progress_callback(progress_event)- except Exception as e:- self.logger.warning(f"Progress callback failed: {e}")-- def _create_iteration_progress_callback(- self,- block_id: str,- sub_topic: str,- execution_mode: str,- current_block: int = None,- total_blocks: int = None,- ) -> Callable:- """- Create a progress callback for research iterations-- Args:- block_id: Block ID for the current topic- sub_topic: Current sub-topic being researched- execution_mode: 'series' or 'parallel'- current_block: Current block number (for series mode)- total_blocks: Total number of blocks-- Returns:- Callback function for iteration progress- """-- def iteration_callback(event_type: str, **data: Any):- """Callback for iteration progress events"""- payload = {- "block_id": block_id,- "sub_topic": sub_topic,- "execution_mode": execution_mode,- }- if current_block is not None:- payload["current_block"] = current_block- if total_blocks is not None:- payload["total_blocks"] = total_blocks- payload.update(data)-- self._log_researching_progress(event_type, **payload)-- return iteration_callback-- async def _phase3_reporting(self, topic: str) -> dict[str, Any]:- """- Phase 3: Report Generation-- Args:- topic: Research topic-- Returns:- Report result- """- reporting = self.agents["reporting"]-- # Set citation manager- reporting.set_citation_manager(self.citation_manager)-- # Generate report- report_result = await reporting.process(- self.queue, topic, progress_callback=self._report_progress_callback- )-- self.logger.info("\nPhase 3 Completed:")- self.logger.info(f" - Report Word Count: {report_result['word_count']}")- self.logger.info(f" - Sections: {report_result['sections']}")- self.logger.info(f" - Citations: {report_result['citations']}")-- return report_result-- def _log_progress(self, stage: str, status: str, **payload: Any) -> None:- """Record stage progress to JSON file and send progress via callback"""- if stage not in self._stage_events:- return- event = {"status": status, "timestamp": datetime.now().isoformat()}- event.update({k: v for k, v in payload.items() if v is not None})- self._stage_events[stage].append(event)- file_path = self.plan_progress_file if stage == "planning" else self.report_progress_file- context = {- "research_id": self.research_id,- "stage": stage,- "input_topic": self.input_topic,- "optimized_topic": self.optimized_topic,- "events": self._stage_events[stage],- }- with open(file_path, "w", encoding="utf-8") as f:- json.dump(context, f, ensure_ascii=False, indent=2)-- # Send progress via callback (if callback function is set)- if self.progress_callback:- try:- progress_event = {- "type": "progress",- "stage": stage,- "status": status,- "research_id": self.research_id,- **{k: v for k, v in payload.items() if v is not None},- }- self.progress_callback(progress_event)- except Exception as e:- self.logger.warning(f"Progress callback failed: {e}")-- def _report_progress_callback(self, event: dict[str, Any]) -> None:- """Reporting stage progress callback"""- status = event.pop("status", "unknown")- self._log_progress("reporting", status, **event)---async def main():- """Main function"""- import argparse-- import yaml-- from deeptutor.services.llm import get_llm_config-- # Parse command line arguments- parser = argparse.ArgumentParser(description="DR-in-KG 2.0 - Deep Research System")- parser.add_argument("--topic", type=str, required=True, help="Research topic")- parser.add_argument("--config", type=str, default="config.yaml", help="Configuration file")- parser.add_argument(- "--preset", type=str, choices=["quick", "medium", "deep", "auto"], help="Preset mode"- )-- args = parser.parse_args()-- # Load configuration- config_path = PROJECT_ROOT / args.config- if not config_path.exists():- logger = logging.getLogger(__name__)- logger.error(f"Configuration file not found: {config_path}")- sys.exit(1)-- with open(config_path, encoding="utf-8") as f:- config = yaml.safe_load(f)-- # Apply preset- if args.preset and "presets" in config and args.preset in config["presets"]:- preset = config["presets"][args.preset]- # Merge preset configuration- for key, value in preset.items():- if key in config and isinstance(value, dict):- config[key].update(value)-- # Get LLM configuration- llm_config = get_llm_config()-- # Create research pipeline- pipeline = ResearchPipeline(- config=config, api_key=llm_config.api_key, base_url=llm_config.base_url- )-- # Execute research- result = await pipeline.run(args.topic)-- logger = logging.getLogger(__name__)- logger.info("\n🎉 Research completed!")- logger.info(f"Report location: {result['final_report_path']}")---if __name__ == "__main__":- if sys.platform == "win32":- asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())-- asyncio.run(main())---__all__ = ["ResearchPipeline"]diff --git a/deeptutor/agents/research/utils/citation_manager.py b/deeptutor/agents/research/utils/citation_manager.pyindex a8937abf9..157a73cf0 100644--- a/deeptutor/agents/research/utils/citation_manager.py+++ b/deeptutor/agents/research/utils/citation_manager.py@@ -6,6 +6,7 @@ Responsible for extracting citation information from tool calls and managing citimport asynciofrom datetime import datetime+import htmlimport jsonfrom pathlib import Pathfrom typing import Any@@ -236,6 +237,7 @@ class CitationManager:tool_type: str,tool_trace: Any,raw_answer: str, # Raw answer JSON string+ tool_metadata: dict[str, Any] | None = None,) -> bool:"""Add citation information@@ -245,6 +247,10 @@ class CitationManager:tool_type: Tool typetool_trace: ToolTrace objectraw_answer: Raw answer (JSON string)+ tool_metadata: Structured ToolResult.metadata for this call, when+ available. Extractors prefer this over reparsing ``raw_answer``+ because tool messages now carry the textual answer rather than+ a JSON payload.Returns:Whether addition was successful@@ -258,11 +264,11 @@ class CitationManager:)elif tool_type_lower == "web_search":citation_info = self._extract_web_citation(- citation_id, tool_type, raw_answer, tool_trace+ citation_id, tool_type, raw_answer, tool_trace, tool_metadata)elif tool_type_lower == "paper_search":citation_info = self._extract_paper_citation(- citation_id, tool_type, raw_answer, tool_trace+ citation_id, tool_type, raw_answer, tool_trace, tool_metadata)elif tool_type_lower == "run_code":citation_info = self._extract_code_citation(citation_id, tool_type, tool_trace)@@ -336,72 +342,112 @@ class CitationManager:return citation_infodef _extract_web_citation(- self, citation_id: str, tool_type: str, raw_answer: str, tool_trace: Any+ self,+ citation_id: str,+ tool_type: str,+ raw_answer: str,+ tool_trace: Any,+ tool_metadata: dict[str, Any] | None = None,) -> dict[str, Any]:- """Extract citation information for web search with URLs"""+ """Extract citation information for web search with URLs.++ Prefers the structured ``ToolResult.metadata`` (which carries the+ provider's ``citations``/``results`` list) because ``raw_answer`` is+ the textual answer surfaced to the LLM, not a JSON payload.+ """citation_info = {"citation_id": citation_id,"tool_type": tool_type,"query": tool_trace.query,"summary": tool_trace.summary,"timestamp": tool_trace.timestamp,- "web_sources": [], # List of web sources with URLs+ "web_sources": [],}- try:- # Parse raw_answer to extract web source information- answer_data = parse_json_response(raw_answer)-- web_sources = []+ web_sources: list[dict[str, Any]] = []- # Try different field names for web results- for field_name in ["results", "web_results", "search_results", "urls"]:- if field_name in answer_data:- result_list = answer_data[field_name]- if isinstance(result_list, list):- for result in result_list[:5]: # Limit to 5 sources- if isinstance(result, dict):- web_source = {- "title": result.get("title", ""),- "url": result.get("url", result.get("link", "")),- "snippet": result.get("snippet", result.get("description", ""))[- :200- ],- "domain": result.get("domain", ""),- }- if web_source["url"]: # Only add if URL exists- web_sources.append(web_source)+ candidate_lists: list[Any] = []+ if isinstance(tool_metadata, dict):+ for field_name in ("citations", "results", "web_results", "search_results", "urls"):+ value = tool_metadata.get(field_name)+ if isinstance(value, list) and value:+ candidate_lists.append(value)break- citation_info["web_sources"] = web_sources- citation_info["total_sources"] = len(web_sources)-- except (json.JSONDecodeError, Exception) as e:- # If parsing fails, still return basic citation info- print(f"⚠️ Failed to parse web source info: {e}")+ if not candidate_lists:+ try:+ answer_data = parse_json_response(raw_answer)+ if isinstance(answer_data, dict):+ for field_name in (+ "citations",+ "results",+ "web_results",+ "search_results",+ "urls",+ ):+ value = answer_data.get(field_name)+ if isinstance(value, list) and value:+ candidate_lists.append(value)+ break+ except (json.JSONDecodeError, Exception):+ pass++ for result_list in candidate_lists:+ for result in result_list:+ if not isinstance(result, dict):+ continue+ url = result.get("url") or result.get("link") or ""+ if not url:+ continue+ snippet = result.get("snippet") or result.get("description") or ""+ web_sources.append(+ {+ "title": result.get("title", ""),+ "url": url,+ "snippet": snippet[:200],+ "domain": result.get("domain", ""),+ }+ )+ citation_info["web_sources"] = web_sources+ citation_info["total_sources"] = len(web_sources)return citation_infodef _extract_paper_citation(- self, citation_id: str, tool_type: str, raw_answer: str, tool_trace: Any+ self,+ citation_id: str,+ tool_type: str,+ raw_answer: str,+ tool_trace: Any,+ tool_metadata: dict[str, Any] | None = None,) -> dict[str, Any]:- """Extract citation information for paper search - supports multiple papers"""+ """Extract citation information for paper search - supports multiple papers.++ Prefers ``tool_metadata['papers']`` (set by ``PaperSearchToolWrapper``)+ because the tool message ``content`` is a markdown listing rather than+ a JSON payload.+ """citation_info = {"citation_id": citation_id,"tool_type": tool_type,"query": tool_trace.query,"summary": tool_trace.summary,"timestamp": tool_trace.timestamp,- "papers": [], # Store all papers, not just the first one+ "papers": [],}try:- # Parse raw_answer JSON- answer_data = parse_json_response(raw_answer)- papers = answer_data.get("papers", [])+ papers: list[Any] = []+ if isinstance(tool_metadata, dict):+ meta_papers = tool_metadata.get("papers")+ if isinstance(meta_papers, list):+ papers = meta_papers+ if not papers:+ answer_data = parse_json_response(raw_answer)+ if isinstance(answer_data, dict):+ papers = answer_data.get("papers", []) or []if not papers:- # If no papers, return basic inforeturn citation_info# Process ALL papers (up to 5 for practicality)@@ -481,14 +527,12 @@ class CitationManager:return self.citations_filedef format_citation_for_report(self, citation_id: str) -> str | None:- """- Format citation information for report display-- Args:- citation_id: Citation ID+ """Render a reference-list entry for ``citation_id`` as HTML.- Returns:- Formatted citation string, or None if not found+ Output may include ``<em>``, ``<a>``, and ``<br>`` tags. All+ user-controlled fields are HTML-escaped inside this method so the+ caller can drop the result directly into the page without an extra+ escape pass."""citation = self.get_citation(citation_id)if not citation:@@ -497,69 +541,112 @@ class CitationManager:tool_type = citation.get("tool_type", "").lower()if tool_type == "paper_search":- # Standard academic citation format- title = citation.get("title", "")- authors = citation.get("authors", "")- year = citation.get("year", "")- url = citation.get("url", "")- arxiv_id = citation.get("arxiv_id", "")-- # Build citation string- parts = []- if authors:- parts.append(authors)- if year:- parts.append(f"({year})")- if title:- parts.append(f'"{title}"')- if arxiv_id:- parts.append(f"arXiv:{arxiv_id}")- if url:- parts.append(f"<{url}>")-- # Add note about additional papers if available- total_papers = citation.get("total_papers", 1)- if total_papers > 1:- parts.append(f"[+{total_papers - 1} more papers]")-- return " ".join(parts) if parts else None+ return self._format_paper_search_apa(citation)if tool_type in ("rag", "rag_naive", "rag_hybrid"):- query = citation.get("query", "")+ query = html.escape(str(citation.get("query", "")))kb_name = citation.get("kb_name", "")- sources = citation.get("sources", [])+ sources = citation.get("sources", []) or []parts = [f"RAG: {query}"]if kb_name:- parts.append(f"[KB: {kb_name}]")- if sources:- source_titles = [s.get("title", s.get("source_file", "")) for s in sources[:3] if s]- source_titles = [t for t in source_titles if t]- if source_titles:- parts.append(f"[Sources: {', '.join(source_titles)}]")-+ parts.append(f"[KB: {html.escape(str(kb_name))}]")+ source_titles = [+ html.escape(str(s.get("title") or s.get("source_file") or ""))+ for s in sources[:3]+ if s+ ]+ source_titles = [t for t in source_titles if t]+ if source_titles:+ parts.append(f"[Sources: {', '.join(source_titles)}]")return " ".join(parts)if tool_type == "web_search":- # Web search with URLs- query = citation.get("query", "")- web_sources = citation.get("web_sources", [])-- parts = [f"Web Search: {query}"]- if web_sources:- urls = [s.get("url", "") for s in web_sources[:3] if s.get("url")]- if urls:- parts.append(f"[URLs: {', '.join(urls)}]")-- return " ".join(parts)-- # Other types of citation formats- tool_type_display = {- "run_code": "Code Execution",- }.get(tool_type, tool_type)-- query = citation.get("query", "")- return f"{tool_type_display}: {query}"+ return self._format_web_search_with_links(citation)++ tool_type_display = {"run_code": "Code Execution"}.get(tool_type, tool_type)+ query = html.escape(str(citation.get("query", "")))+ return f"{html.escape(str(tool_type_display))}: {query}"++ def _format_paper_search_apa(self, citation: dict[str, Any]) -> str | None:+ """Render each paper in a paper_search citation as a separate APA-style+ entry, joined by ``<br>``.++ APA pattern used: ``Authors (Year). *Title*. arXiv. <url>``. Fields+ that are missing are skipped without leaving stray punctuation.+ """+ papers: list[dict[str, Any]] = list(citation.get("papers") or [])+ if not papers:+ # Fallback for citations that only carry top-level fields.+ fallback = {+ "title": citation.get("title", ""),+ "authors": citation.get("authors", ""),+ "year": citation.get("year", ""),+ "url": citation.get("url", ""),+ "arxiv_id": citation.get("arxiv_id", ""),+ }+ if any(fallback.values()):+ papers = [fallback]+ entries: list[str] = []+ for paper in papers:+ entry = self._format_one_apa(paper)+ if entry:+ entries.append(entry)+ if not entries:+ return None+ return "<br>".join(entries)++ @staticmethod+ def _format_one_apa(paper: dict[str, Any]) -> str | None:+ authors_raw = paper.get("authors") or paper.get("authors_list") or ""+ if isinstance(authors_raw, list):+ authors = ", ".join(str(a) for a in authors_raw[:3] if a)+ if len(authors_raw) > 3:+ authors += " et al."+ else:+ authors = str(authors_raw).strip()+ year = str(paper.get("year") or "").strip()+ title = str(paper.get("title") or "").strip()+ url = str(paper.get("url") or "").strip()+ arxiv_id = str(paper.get("arxiv_id") or "").strip()+ if not (title or authors):+ return None+ if not url and arxiv_id:+ url = f"https://arxiv.org/abs/{arxiv_id}"++ pieces: list[str] = []+ if authors:+ pieces.append(html.escape(authors))+ if year:+ pieces.append(f"({html.escape(year)}).")+ elif pieces:+ pieces[-1] = pieces[-1] + "."+ if title:+ pieces.append(f"<em>{html.escape(title)}</em>.")+ pieces.append("arXiv.")+ if url:+ safe_url = html.escape(url, quote=True)+ pieces.append(f'<a href="{safe_url}">{html.escape(url)}</a>')+ return " ".join(pieces)++ @staticmethod+ def _format_web_search_with_links(citation: dict[str, Any]) -> str:+ query = str(citation.get("query") or "").strip()+ web_sources = citation.get("web_sources") or []+ head = "Web Search"+ if query:+ head = f"Web Search: {html.escape(query)}"+ link_items: list[str] = []+ for source in web_sources:+ url = str(source.get("url") or "").strip()+ if not url:+ continue+ safe_url = html.escape(url, quote=True)+ title = str(source.get("title") or "").strip() or url+ link_items.append(f'<a href="{safe_url}">{html.escape(title)}</a>')+ if not link_items:+ return head+ return head + "<br>" + "<br>".join(link_items)# ========== Reference Number Mapping Methods ==========@@ -769,21 +856,11 @@ class CitationManager:tool_type: str,tool_trace: Any,raw_answer: str,+ tool_metadata: dict[str, Any] | None = None,) -> bool:- """- Thread-safe async version of add_citation for parallel mode-- Args:- citation_id: Citation ID- tool_type: Tool type- tool_trace: ToolTrace object- raw_answer: Raw answer (JSON string)-- Returns:- Whether addition was successful- """+ """Thread-safe async version of :meth:`add_citation`."""async with self._lock:- return self.add_citation(citation_id, tool_type, tool_trace, raw_answer)+ return self.add_citation(citation_id, tool_type, tool_trace, raw_answer, tool_metadata)__all__ = ["CitationManager"]diff --git a/deeptutor/agents/solve/__init__.py b/deeptutor/agents/solve/__init__.pyindex 3917cf05a..4c9159dab 100644--- a/deeptutor/agents/solve/__init__.py+++ b/deeptutor/agents/solve/__init__.py@@ -1,12 +1,21 @@-"""-Solve Agent — Plan -> ReAct -> Write architecture.+"""Solve agent — agentic-engine-based pipeline.++Public surface: :class:`SolvePipeline`. The legacy ``MainSolver`` ++``SolverSessionManager`` + three-agent (planner / solver / writer) stack+has been replaced by a single label-driven pipeline that runs on top of+:mod:`deeptutor.core.agentic`."""-from .main_solver import MainSolver-from .session_manager import SolverSessionManager, get_solver_session_manager+from .pipeline import (+ Plan,+ PlanStep,+ SolvePipeline,+ StepFinish,+)__all__ = [- "MainSolver",- "SolverSessionManager",- "get_solver_session_manager",+ "Plan",+ "PlanStep",+ "SolvePipeline",+ "StepFinish",]diff --git a/deeptutor/agents/solve/agents/__init__.py b/deeptutor/agents/solve/agents/__init__.pydeleted file mode 100644index 550fdaec4..000000000--- a/deeptutor/agents/solve/agents/__init__.py+++ /dev/null@@ -1,7 +0,0 @@-"""Solve Agent — three-agent architecture."""--from .planner_agent import PlannerAgent-from .solver_agent import SolverAgent-from .writer_agent import WriterAgent--__all__ = ["PlannerAgent", "SolverAgent", "WriterAgent"]diff --git a/deeptutor/agents/solve/agents/planner_agent.py b/deeptutor/agents/solve/agents/planner_agent.pydeleted file mode 100644index 9a35418ab..000000000--- a/deeptutor/agents/solve/agents/planner_agent.py+++ /dev/null@@ -1,471 +0,0 @@-"""-PlannerAgent — Decomposes the user question into ordered solving steps.--Called once at the start (Phase 1) and optionally on replan requests.-Before planning, it can perform tool-driven pre-retrieval and LLM aggregation-to provide the planner with relevant knowledge context.-"""--from __future__ import annotations--import asyncio-import logging-from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.core.context import Attachment-from deeptutor.core.trace import build_trace_metadata, derive_trace_metadata, new_call_id-from deeptutor.utils.json_parser import parse_json_response--from ..memory.scratchpad import Plan, PlanStep, Scratchpad-from ..tool_runtime import SolveToolRuntime-from ..utils.json_utils import extract_json_from_text--logger = logging.getLogger(__name__)--_MAX_CHARS_PER_RETRIEVAL = 2000-_MAX_AGGREGATE_INPUT_CHARS = 6000-_NUM_QUERIES = 3---class PlannerAgent(BaseAgent):- """Generates a high-level solving plan from the user question."""-- def __init__(- self,- config: dict[str, Any] | None = None,- api_key: str | None = None,- base_url: str | None = None,- model: str | None = None,- api_version: str | None = None,- token_tracker: Any | None = None,- language: str = "en",- tool_runtime: SolveToolRuntime | None = None,- enable_pre_retrieve: bool = True,- ) -> None:- super().__init__(- module_name="solve",- agent_name="planner_agent",- api_key=api_key,- base_url=base_url,- model=model,- api_version=api_version,- config=config or {},- token_tracker=token_tracker,- language=language,- )- self._tool_runtime = tool_runtime or SolveToolRuntime([], language=language)- self._enable_pre_retrieve = enable_pre_retrieve-- async def process(- self,- question: str,- scratchpad: Scratchpad,- kb_name: str = "",- replan: bool = False,- memory_context: str = "",- image_url: str | None = None,- attachments: list[Any] | None = None,- ) -> Plan:- """Generate or revise the solving plan.-- Args:- question: The user's original question.- scratchpad: Current scratchpad state.- kb_name: Knowledge base name (informational).- replan: If True, this is a replan request — include progress so far.- memory_context: Historical memory context string.- image_url: Optional image URL for multimodal questions.- attachments: Optional chat attachments for multimodal input.-- Returns:- A Plan object with ordered steps.- """- trace_root = "replan" if replan else "plan"- retrieved_context = (- await self._pre_retrieve(question, kb_name, trace_root=trace_root)- if self._enable_pre_retrieve- else "(retrieval disabled)"- )-- system_prompt = self._build_system_prompt()- user_prompt = self._build_user_prompt(- question=question,- scratchpad=scratchpad,- kb_name=kb_name,- replan=replan,- memory_context=memory_context,- retrieved_context=retrieved_context,- )-- llm_kwargs: dict[str, Any] = {- "user_prompt": user_prompt,- "system_prompt": system_prompt,- "response_format": {"type": "json_object"},- "stage": "plan" if not replan else "replan",- "trace_meta": build_trace_metadata(- call_id=new_call_id(trace_root),- phase="planning",- label="Revise plan" if replan else "Create plan",- call_kind="llm_planning",- trace_id=trace_root,- trace_role="plan",- trace_group="plan",- replan=replan,- ),- }-- llm_attachments = list(attachments or [])- if image_url:- llm_attachments.append(Attachment(type="image", url=image_url))- if llm_attachments:- llm_kwargs["attachments"] = llm_attachments-- chunks: list[str] = []- async for chunk in self.stream_llm(**llm_kwargs):- chunks.append(chunk)- response = "".join(chunks)-- return self._parse_plan(response, scratchpad if replan else None)-- # ------------------------------------------------------------------- # Retrieval pre-processing pipeline- # -------------------------------------------------------------------- async def _pre_retrieve(- self,- question: str,- kb_name: str,- trace_root: str = "plan",- ) -> str:- """Run the full pre-retrieval pipeline: generate queries → parallel- retrieval → LLM aggregation. Returns the aggregated knowledge- context string, or a fallback placeholder on any failure."""- if not kb_name or not self._tool_runtime.has_tool("rag"):- return "(no knowledge base available)"- try:- queries = await self._generate_search_queries(question, trace_root=trace_root)- retrievals = await self._parallel_retrieve(- queries,- kb_name,- trace_root=trace_root,- )- if not any(r.get("answer") for r in retrievals):- return "(no relevant knowledge retrieved)"- return await self._aggregate_retrieval_results(retrievals, trace_root=trace_root)- except Exception as exc:- logger.warning("Pre-retrieval pipeline failed: %s", exc)- return "(knowledge retrieval failed)"-- async def _generate_search_queries(- self,- question: str,- num_queries: int = _NUM_QUERIES,- trace_root: str = "plan",- ) -> list[str]:- """Use a lightweight LLM call to derive multiple search queries from- the user question."""- prompt_template = self.get_prompt("generate_queries") if self.has_prompts() else None- if not prompt_template:- prompt_template = (- "Generate {num_queries} concise and diverse knowledge-base "- "search queries for the following question. Each query should "- "target a different aspect (e.g. definitions, formulas, "- "theorems, examples).\n\n"- "Question: {question}\n\n"- 'Return strict JSON: {{"queries": ["q1", "q2", "q3"]}}'- )-- user_prompt = prompt_template.format(- question=question,- num_queries=num_queries,- )- try:- parts: list[str] = []- async for chunk in self.stream_llm(- user_prompt=user_prompt,- system_prompt="",- response_format={"type": "json_object"},- stage="plan_generate_queries",- trace_meta=build_trace_metadata(- call_id=new_call_id(f"{trace_root}-queries"),- phase="planning",- label="Generate search queries",- call_kind="llm_query_planning",- trace_id=trace_root,- trace_role="plan",- trace_group="plan",- ),- ):- parts.append(chunk)- response = "".join(parts)- payload = parse_json_response(response, logger_instance=logger)- queries = payload.get("queries", [])- if not isinstance(queries, list):- queries = []- clean = [q.strip() for q in queries if isinstance(q, str) and q.strip()]- result = clean[:num_queries] or [question]- logger.info("Generated %d search queries", len(result))- return result- except Exception as exc:- logger.warning("Query generation failed, fallback to raw question: %s", exc)- return [question]-- async def _parallel_retrieve(- self,- queries: list[str],- kb_name: str,- trace_root: str = "plan",- ) -> list[dict[str, Any]]:- """Execute retrieval tool calls for all queries in parallel."""-- async def _single_search(query: str, index: int) -> dict[str, Any]:- trace_meta = build_trace_metadata(- call_id=new_call_id(f"{trace_root}-retrieve"),- phase="planning",- label=f"Retrieve {index}",- call_kind="rag_retrieval",- trace_role="retrieve",- trace_group="retrieve",- trace_id=f"{trace_root}-retrieve-{index}",- query=query,- query_index=index,- tool_name="rag",- )-- async def _event_sink(- event_type: str,- message: str = "",- metadata: dict[str, Any] | None = None,- ) -> None:- await self._emit_trace_event(- {- "event": "tool_log",- "message": message,- **derive_trace_metadata(- trace_meta,- trace_kind=str(event_type or "tool_log"),- **(metadata or {}),- ),- }- )-- await self._emit_trace_event(- {- "event": "tool_log",- "message": f"Query: {query}",- **derive_trace_metadata(- trace_meta,- trace_kind="call_status",- call_state="running",- ),- }- )- try:- result = await self._tool_runtime.execute(- "rag",- query,- kb_name=kb_name,- event_sink=_event_sink,- )- await self._emit_trace_event(- {- "event": "tool_log",- "message": f"Retrieve complete ({len(result.content)} chars)",- **derive_trace_metadata(- trace_meta,- trace_kind="call_status",- call_state="complete",- ),- }- )- return {"query": query, "answer": result.content}- except Exception as exc:- logger.warning("Retrieval failed for query '%s': %s", query[:60], exc)- await self._emit_trace_event(- {- "event": "tool_log",- "message": f"Retrieve failed: {exc}",- **derive_trace_metadata(- trace_meta,- trace_kind="call_status",- call_state="error",- error=str(exc),- ),- }- )- return {"query": query, "answer": ""}-- results = await asyncio.gather(- *[_single_search(query, index + 1) for index, query in enumerate(queries)]- )- logger.info(- "Parallel retrieval: %d/%d returned content",- sum(1 for r in results if r.get("answer")),- len(results),- )- return list(results)-- async def _aggregate_retrieval_results(- self,- retrievals: list[dict[str, Any]],- trace_root: str = "plan",- ) -> str:- """Use an LLM call to aggregate raw retrieval results into a- structured knowledge summary. The user question is NOT passed- to keep the output neutral (pure knowledge consolidation)."""- sections: list[str] = []- total_chars = 0- for item in retrievals:- answer = (item.get("answer") or "").strip()- if not answer:- continue- clipped = answer[:_MAX_CHARS_PER_RETRIEVAL]- if total_chars + len(clipped) > _MAX_AGGREGATE_INPUT_CHARS:- clipped = clipped[: max(0, _MAX_AGGREGATE_INPUT_CHARS - total_chars)]- if clipped:- sections.append(f"=== Source: {item.get('query', '?')} ===\n{clipped}")- total_chars += len(clipped)-- if not sections:- return "(no relevant knowledge retrieved)"-- raw_text = "\n\n".join(sections)-- prompt_template = self.get_prompt("aggregate_context") if self.has_prompts() else None- if not prompt_template:- prompt_template = (- "Below are several passages retrieved from a knowledge base. "- "Your task is to consolidate them into a single structured "- "knowledge summary.\n\n"- "Rules:\n"- "- Remove duplicate information.\n"- "- Organize by topic (definitions, formulas/theorems, key facts, examples).\n"- "- Do NOT solve any problem or make inferences.\n"- "- Do NOT reference any question — just organize the knowledge.\n"- "- Be concise; keep the summary under 3000 characters.\n\n"- "{raw_retrieval_text}"- )-- user_prompt = prompt_template.format(raw_retrieval_text=raw_text)- try:- parts: list[str] = []- async for chunk in self.stream_llm(- user_prompt=user_prompt,- system_prompt="You are a knowledge organizer. Consolidate the provided passages into a clean, structured summary.",- stage="plan_aggregate_context",- trace_meta=build_trace_metadata(- call_id=new_call_id(f"{trace_root}-aggregate"),- phase="planning",- label="Aggregate retrieval context",- call_kind="llm_summary",- trace_id=trace_root,- trace_role="plan",- trace_group="plan",- ),- ):- parts.append(chunk)- result = "".join(parts)- logger.info("Aggregated retrieved context: %d chars", len(result))- return result.strip() or raw_text- except Exception as exc:- logger.warning("Retrieval aggregation failed, using raw text: %s", exc)- return raw_text-- # ------------------------------------------------------------------- # Prompt construction- # -------------------------------------------------------------------- def _build_system_prompt(self) -> str:- prompt = self.get_prompt("system") if self.has_prompts() else None- if prompt:- return prompt- return (- "You are a problem-solving planner. Analyze the user's question and "- "decompose it into ordered steps. Each step should be a verifiable sub-goal "- "describing WHAT to establish, not HOW. Do not specify tools. "- "Simple questions need only 1 step; complex ones may need 3-6 steps. "- "If retrieved knowledge is provided, use it to make a more informed plan. "- 'Output strict JSON: {"analysis": "...", "steps": [{"id": "S1", '- '"goal": "..."}]}'- )-- def _build_user_prompt(- self,- question: str,- scratchpad: Scratchpad,- kb_name: str,- replan: bool,- memory_context: str = "",- retrieved_context: str = "",- ) -> str:- template = self.get_prompt("user_template") if self.has_prompts() else None-- # Build scratchpad summary for replan- scratchpad_summary = "(initial plan — no progress yet)"- if replan and scratchpad.plan:- parts: list[str] = []- for step in scratchpad.plan.steps:- entries = scratchpad.get_entries_for_step(step.id)- notes = " | ".join(e.self_note for e in entries if e.self_note)- status_label = step.status.upper()- parts.append(f"[{step.id}] ({status_label}) {step.goal}")- if notes:- parts.append(f" Notes: {notes}")- # Include the replan reason from the last entry- if scratchpad.entries:- last = scratchpad.entries[-1]- if last.action == "replan" and last.action_input:- parts.append(f"\nReplan reason: {last.action_input}")- scratchpad_summary = "\n".join(parts)-- tools_desc = self._tool_runtime.build_planner_description(kb_name=kb_name)-- if template:- return template.format(- question=question,- retrieved_context=retrieved_context or "(no retrieved knowledge)",- tools_description=tools_desc,- scratchpad_summary=scratchpad_summary,- memory_context=memory_context or "(no historical memory)",- )-- # Fallback- return (- f"## Question\n{question}\n\n"- f"## Retrieved Knowledge\n{retrieved_context or '(none)'}\n\n"- f"## Available Tools\n{tools_desc}\n\n"- f"## Progress So Far\n{scratchpad_summary}\n\n"- f"## Memory Context\n{memory_context or '(none)'}"- )-- # ------------------------------------------------------------------- # Response parsing- # -------------------------------------------------------------------- def _parse_plan(self, response: str, old_scratchpad: Scratchpad | None) -> Plan:- """Parse LLM JSON response into a Plan object."""- data = extract_json_from_text(response)- if not data or not isinstance(data, dict):- # Graceful fallback: single-step plan- return Plan(- analysis="Failed to parse plan; using single-step fallback.",- steps=[PlanStep(id="S1", goal="Answer the question directly")],- )-- analysis = data.get("analysis", "")- raw_steps = data.get("steps", [])-- steps: list[PlanStep] = []- for i, s in enumerate(raw_steps):- step_id = s.get("id", f"S{i + 1}")- goal = s.get("goal", "")- tools_hint = s.get("tools_hint", [])- if isinstance(tools_hint, str):- tools_hint = [tools_hint]- steps.append(PlanStep(id=step_id, goal=goal, tools_hint=tools_hint))-- if not steps:- steps = [PlanStep(id="S1", goal="Answer the question")]-- return Plan(analysis=analysis, steps=steps)diff --git a/deeptutor/agents/solve/agents/solver_agent.py b/deeptutor/agents/solve/agents/solver_agent.pydeleted file mode 100644index dc9e6d50f..000000000--- a/deeptutor/agents/solve/agents/solver_agent.py+++ /dev/null@@ -1,202 +0,0 @@-"""-SolverAgent — ReAct agent that iteratively gathers information for each plan step.--For every step in the plan, the SolverAgent runs a think-act-observe loop:- 1. THINK — reason about what information is still missing- 2. ACT — choose one enabled action from the unified tool/runtime layer- 3. OBSERVE — the tool result is appended to the Scratchpad (outside this agent)--The agent outputs a single JSON decision per call.-"""--from __future__ import annotations--from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.core.context import Attachment-from deeptutor.core.trace import build_trace_metadata, new_call_id--from ..memory.scratchpad import PlanStep, Scratchpad-from ..tool_runtime import SolveToolRuntime-from ..utils.json_utils import extract_json_from_text---class SolverAgent(BaseAgent):- """ReAct reasoning agent — one LLM call per iteration."""-- def __init__(- self,- config: dict[str, Any] | None = None,- api_key: str | None = None,- base_url: str | None = None,- model: str | None = None,- api_version: str | None = None,- token_tracker: Any | None = None,- language: str = "en",- tool_runtime: SolveToolRuntime | None = None,- ) -> None:- super().__init__(- module_name="solve",- agent_name="solver_agent",- api_key=api_key,- base_url=base_url,- model=model,- api_version=api_version,- config=config or {},- token_tracker=token_tracker,- language=language,- )- self._tool_runtime = tool_runtime or SolveToolRuntime([], language=language)-- async def process(- self,- question: str,- current_step: PlanStep,- scratchpad: Scratchpad,- memory_context: str = "",- image_url: str | None = None,- round_index: int | None = None,- ) -> dict[str, str]:- """Run one ReAct iteration for the given plan step.-- Args:- question: The user's original question.- current_step: The plan step being solved.- scratchpad: Current scratchpad state.- memory_context: Historical memory context string.- image_url: Optional image URL for multimodal questions.-- Returns:- dict with keys: thought, action, action_input, self_note- """- system_prompt = self._build_system_prompt()- user_prompt = self._build_user_prompt(- question=question,- current_step=current_step,- scratchpad=scratchpad,- memory_context=memory_context,- )-- trace_meta = build_trace_metadata(- call_id=new_call_id(f"solve-{current_step.id.lower()}"),- phase="reasoning",- label=(- f"{current_step.id} / Round {round_index}"- if round_index is not None- else current_step.id- ),- call_kind="react_round",- trace_id=(- f"{current_step.id.lower()}-round-{round_index}"- if round_index is not None- else current_step.id.lower()- ),- trace_role="thought",- trace_group="react_round",- step_id=current_step.id,- round=round_index,- )- llm_kwargs: dict[str, object] = {- "user_prompt": user_prompt,- "system_prompt": system_prompt,- "response_format": {"type": "json_object"},- "stage": f"solve_{current_step.id}",- "trace_meta": trace_meta,- }-- if image_url:- llm_kwargs["attachments"] = [Attachment(type="image", url=image_url)]-- chunks: list[str] = []- async for chunk in self.stream_llm(**llm_kwargs):- chunks.append(chunk)- response = "".join(chunks)-- decision = self._parse_decision(response)- decision["_trace"] = trace_meta- return decision-- # ------------------------------------------------------------------- # Prompt construction- # -------------------------------------------------------------------- def _build_system_prompt(self) -> str:- tools_desc = self._tool_runtime.build_solver_description()-- prompt = self.get_prompt("system") if self.has_prompts() else None- if prompt:- try:- return prompt.format(tools_description=tools_desc)- except KeyError:- return prompt-- # Fallback- return (- "You are a ReAct problem-solving agent. For the current step, decide what "- "action to take next. Output strict JSON with keys: thought, action, "- "action_input, self_note.\n\n"- f"Available actions:\n{tools_desc}\n\n"- "self_note: write a 1-sentence summary of what you learned this round."- )-- def _build_user_prompt(- self,- question: str,- current_step: PlanStep,- scratchpad: Scratchpad,- memory_context: str = "",- ) -> str:- template = self.get_prompt("user_template") if self.has_prompts() else None-- ctx = scratchpad.build_solver_context(current_step.id)-- current_step_text = f"[{current_step.id}] {current_step.goal}"-- if template:- return template.format(- question=question,- plan=ctx["plan"],- current_step=current_step_text,- step_history=ctx["step_history"],- previous_knowledge=ctx["previous_knowledge"],- memory_context=memory_context or "(no historical memory)",- )-- # Fallback- return (- f"## Original Question\n{question}\n\n"- f"## Plan\n{ctx['plan']}\n\n"- f"## Current Step\n{current_step_text}\n\n"- f"## Previous Actions for This Step\n{ctx['step_history']}\n\n"- f"## Knowledge from Previous Steps\n{ctx['previous_knowledge']}\n\n"- f"## Historical Knowledge\n{memory_context or '(none)'}"- )-- # ------------------------------------------------------------------- # Response parsing- # -------------------------------------------------------------------- def _parse_decision(self, response: str) -> dict[str, str]:- """Parse the LLM JSON response into a decision dict."""- data = extract_json_from_text(response)-- if not data or not isinstance(data, dict):- # If parsing completely fails, default to done- return {- "thought": "Failed to parse response; ending step.",- "action": "done",- "action_input": "",- "self_note": "Parse error — defaulting to done.",- }-- action = str(data.get("action", "done")).strip().lower()- if action not in self._tool_runtime.valid_actions:- action = "done"-- return {- "thought": str(data.get("thought", "")),- "action": action,- "action_input": str(data.get("action_input", "")),- "self_note": str(data.get("self_note", "")),- }diff --git a/deeptutor/agents/solve/agents/writer_agent.py b/deeptutor/agents/solve/agents/writer_agent.pydeleted file mode 100644index 8edf578a1..000000000--- a/deeptutor/agents/solve/agents/writer_agent.py+++ /dev/null@@ -1,393 +0,0 @@-"""-WriterAgent — Generates the final structured answer from the Scratchpad.--Supports two modes:- - **Simple** (`process`): single LLM call producing the complete answer.- - **Detailed / Iterative** (`process_iterative`): step-by-step incremental- writing that processes evidence in chunks, then generates a concise answer.-"""--from __future__ import annotations--from collections.abc import Awaitable, Callable-from typing import Any--from deeptutor.agents.base_agent import BaseAgent-from deeptutor.core.trace import build_trace_metadata, new_call_id--from ..memory.scratchpad import Scratchpad--ContentChunkCallback = Callable[[str], Awaitable[None]]---class WriterAgent(BaseAgent):- """Produces the final answer from accumulated evidence."""-- def __init__(- self,- config: dict[str, Any] | None = None,- api_key: str | None = None,- base_url: str | None = None,- model: str | None = None,- api_version: str | None = None,- token_tracker: Any | None = None,- language: str = "en",- ) -> None:- super().__init__(- module_name="solve",- agent_name="writer_agent",- api_key=api_key,- base_url=base_url,- model=model,- api_version=api_version,- config=config or {},- token_tracker=token_tracker,- language=language,- )-- # ==================================================================- # Simple mode — single-shot writing- # ==================================================================-- async def process(- self,- question: str,- scratchpad: Scratchpad,- language: str = "en",- preference: str = "",- on_content_chunk: ContentChunkCallback | None = None,- ) -> str:- """Generate the final Markdown answer in a single LLM call.-- When *on_content_chunk* is provided the LLM response is streamed- token-by-token; each chunk is forwarded via the callback so the- caller can push it to the frontend in real time.- """- system_prompt = self._build_system_prompt()- user_prompt = self._build_user_prompt(question, scratchpad, language, preference)-- trace_meta = build_trace_metadata(- call_id=new_call_id("write"),- phase="writing",- label="Write answer",- call_kind="llm_final_answer",- trace_id="write",- )-- if on_content_chunk is not None:- chunks: list[str] = []- async for chunk in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- max_tokens=self.get_max_tokens() or 8192,- stage="write",- trace_meta=trace_meta,- ):- chunks.append(chunk)- await on_content_chunk(chunk)- response = "".join(chunks)- else:- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- max_tokens=self.get_max_tokens() or 8192,- stage="write",- trace_meta=trace_meta,- )-- full_answer = self._ensure_references(response.strip(), scratchpad)-- if on_content_chunk is not None:- suffix = full_answer[len(response.strip()) :]- if suffix:- await on_content_chunk(suffix)-- return full_answer-- # ==================================================================- # Detailed / Iterative mode- # ==================================================================-- async def process_iterative(- self,- question: str,- scratchpad: Scratchpad,- language: str = "en",- preference: str = "",- on_content_chunk: ContentChunkCallback | None = None,- ) -> str:- """Generate a detailed answer through iterative step-by-step writing.-- Flow:- Iteration 1 : evidence(S1) + evidence(S2) → draft_1- Iteration 2 : draft_1 + evidence(S3) → draft_2- ...- Final : draft_N → concise_answer- Output : concise_answer + "---" + draft_N-- Individual draft/concise LLM calls stream via trace panel.- The assembled final answer is sent to *on_content_chunk* if provided.- """- if scratchpad.plan is None:- return await self.process(- question,- scratchpad,- language,- preference,- on_content_chunk=on_content_chunk,- )-- # Collect completed/in_progress steps that have entries- steps_with_evidence = []- for step in scratchpad.plan.steps:- if step.status in ("completed", "in_progress"):- entries = scratchpad.get_entries_for_step(step.id)- # Only include steps with actual tool observations- evidence_entries = [- e for e in entries if e.action not in ("done", "replan") and e.observation- ]- if evidence_entries:- steps_with_evidence.append((step, evidence_entries))-- if not steps_with_evidence:- return await self.process(question, scratchpad, language, preference)-- sources_text = scratchpad.format_sources_markdown()-- # --- Iterative draft building ---- draft = ""-- for i, (step, entries) in enumerate(steps_with_evidence):- step_evidence = self._format_step_evidence(step, entries)-- if i == 0:- # First iteration: if there's a second step, bundle it- if len(steps_with_evidence) > 1:- step2, entries2 = steps_with_evidence[1]- step_evidence += "\n\n---\n\n" + self._format_step_evidence(step2, entries2)- draft = await self._write_draft(- question=question,- previous_draft="(this is the first draft — no previous draft)",- new_evidence=step_evidence,- sources=sources_text,- language=language,- iteration=i + 1,- preference=preference,- )- elif i == 1:- # Second step was already bundled in iteration 0; skip- continue- else:- # Subsequent iterations: previous draft + new step evidence- draft = await self._write_draft(- question=question,- previous_draft=draft,- new_evidence=step_evidence,- sources=sources_text,- language=language,- iteration=i,- preference=preference,- )-- # --- Concise answer generation ---- concise = await self._write_concise(- question=question,- detailed_answer=draft,- language=language,- preference=preference,- )-- # --- Assemble final output ---- final = f"## Summary\n\n{concise}\n\n---\n\n{draft}"- full_answer = self._ensure_references(final, scratchpad)-- if on_content_chunk is not None:- await on_content_chunk(full_answer)-- return full_answer-- # ------------------------------------------------------------------- # Internal helpers for iterative mode- # -------------------------------------------------------------------- async def _write_draft(- self,- question: str,- previous_draft: str,- new_evidence: str,- sources: str,- language: str,- iteration: int,- preference: str = "",- ) -> str:- """Run one iteration of the incremental draft builder."""- system_prompt = self._get_iterative_system_prompt()- template = self.get_prompt("iterative_user_template") if self.has_prompts() else None-- if template:- user_prompt = template.format(- question=question,- previous_draft=previous_draft,- new_evidence=new_evidence,- sources=sources or "(no external sources)",- preference=preference or "(no specific preference)",- language=language,- )- else:- user_prompt = (- f"## Question\n{question}\n\n"- f"## Previous Draft\n{previous_draft}\n\n"- f"## New Evidence\n{new_evidence}\n\n"- f"## Available Sources\n{sources or '(none)'}\n\n"- f"## User Preference\n{preference or '(none)'}\n\n"- f"## Language\n{language}"- )-- chunks: list[str] = []- async for chunk in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- max_tokens=self.get_max_tokens() or 8192,- stage=f"write_iter_{iteration}",- trace_meta=build_trace_metadata(- call_id=new_call_id(f"write-draft-{iteration}"),- phase="writing",- label=f"Write draft {iteration}",- call_kind="llm_generation",- trace_id=f"write-draft-{iteration}",- iteration=iteration,- ),- ):- chunks.append(chunk)- return "".join(chunks).strip()-- async def _write_concise(- self,- question: str,- detailed_answer: str,- language: str,- preference: str = "",- ) -> str:- """Generate a concise answer from the completed detailed draft."""- system_prompt = self._get_concise_system_prompt()- template = self.get_prompt("concise_user_template") if self.has_prompts() else None-- if template:- user_prompt = template.format(- question=question,- detailed_answer=detailed_answer,- language=language,- )- else:- user_prompt = (- f"## Question\n{question}\n\n"- f"## Detailed Answer\n{detailed_answer}\n\n"- f"## Language\n{language}"- )-- chunks: list[str] = []- async for chunk in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- max_tokens=1024,- stage="write_concise",- trace_meta=build_trace_metadata(- call_id=new_call_id("write-concise"),- phase="writing",- label="Write concise answer",- call_kind="llm_summary",- trace_id="write-concise",- ),- ):- chunks.append(chunk)- return "".join(chunks).strip()-- @staticmethod- def _format_step_evidence(step, entries) -> str:- """Format raw observations from a step into a single evidence block."""- parts = [f"### Step {step.id}: {step.goal}"]- for e in entries:- block = f"**Action**: {e.action}({e.action_input})\n**Observation**:\n{e.observation}"- parts.append(block)- return "\n\n".join(parts)-- # ------------------------------------------------------------------- # Post-processing- # -------------------------------------------------------------------- @staticmethod- def _ensure_references(answer: str, scratchpad: Scratchpad) -> str:- """Append a References section if the LLM omitted one."""- if not answer:- return answer- has_refs = "## References" in answer or "## 参考文献" in answer- if has_refs:- return answer- refs = scratchpad.format_sources_markdown()- if not refs:- return answer- return f"{answer}\n\n---\n\n{refs}"-- # ------------------------------------------------------------------- # Prompt construction- # -------------------------------------------------------------------- def _build_system_prompt(self) -> str:- prompt = self.get_prompt("system") if self.has_prompts() else None- if prompt:- return prompt- return (- "You are an expert answer writer. Write a structured, comprehensive answer "- "based on gathered evidence. Use Markdown with proper headings. "- "All math must use LaTeX: inline $...$ and block $$...$$. "- "Cite sources inline as [source-id]. Include a ## References section at the end."- )-- def _get_iterative_system_prompt(self) -> str:- prompt = self.get_prompt("iterative_system") if self.has_prompts() else None- if prompt:- return prompt- return (- "You are an expert answer writer building an answer incrementally. "- "You receive a previous draft and new evidence. Expand and refine the draft "- "by integrating the new evidence. Use Markdown, LaTeX for math, and cite sources."- )-- def _get_concise_system_prompt(self) -> str:- prompt = self.get_prompt("concise_system") if self.has_prompts() else None- if prompt:- return prompt- return (- "Produce a concise answer (2-4 sentences) for the question based on the "- "detailed answer. If it's a multiple-choice or fill-in-the-blank question, "- "give the direct answer first."- )-- def _build_user_prompt(- self,- question: str,- scratchpad: Scratchpad,- language: str,- preference: str,- ) -> str:- template = self.get_prompt("user_template") if self.has_prompts() else None-- scratchpad_content = scratchpad.build_writer_context()- sources_text = scratchpad.format_sources_markdown()-- if template:- return template.format(- question=question,- scratchpad_content=scratchpad_content,- sources=sources_text or "(no external sources)",- preference=preference or "(no specific preference)",- language=language,- )-- return (- f"## Question\n{question}\n\n"- f"## Gathered Evidence\n{scratchpad_content}\n\n"- f"## Available Sources\n{sources_text or '(none)'}\n\n"- f"## User Preference\n{preference or '(none)'}\n\n"- f"## Language\n{language}"- )diff --git a/deeptutor/agents/solve/main_solver.py b/deeptutor/agents/solve/main_solver.pydeleted file mode 100644index 884914b14..000000000--- a/deeptutor/agents/solve/main_solver.py+++ /dev/null@@ -1,952 +0,0 @@-"""-MainSolver — Plan -> ReAct -> Write pipeline controller.--External interface (preserved for API compatibility):- solver = MainSolver(kb_name=..., ...)- await solver.ainit()- result = await solver.solve(question)-"""--from __future__ import annotations--import asyncio-from datetime import datetime-import logging-import os-from pathlib import Path-import traceback-from typing import Any--import yaml--from deeptutor.core.trace import derive_trace_metadata, new_call_id--from ...services.config import parse_language-from ...services.path_service import get_path_service-from .agents import PlannerAgent, SolverAgent, WriterAgent-from .memory import Scratchpad, Source-from .tool_runtime import SolveToolRuntime-from .utils.display_manager import get_display_manager-from .utils.token_tracker import TokenTracker---class MainSolver:- """Problem-Solving System Controller — Plan -> ReAct -> Write."""-- def __init__(- self,- config_path: str | None = None,- api_key: str | None = None,- base_url: str | None = None,- api_version: str | None = None,- model: str | None = None,- language: str | None = None,- kb_name: str | None = None,- output_base_dir: str | None = None,- enabled_tools: list[str] | None = None,- disable_memory: bool = False,- disable_planner_retrieve: bool = False,- max_tokens: int | None = None,- temperature: float | None = None,- ) -> None:- # Store init params for ainit()- self._config_path = config_path- self._api_key = api_key- self._base_url = base_url- self._api_version = api_version- self._model = model- self._language = language- self._kb_name = kb_name- self._output_base_dir = output_base_dir- self._enabled_tools = enabled_tools- self.disable_memory = disable_memory- self.disable_planner_retrieve = disable_planner_retrieve- self._max_tokens_override = max_tokens- self._temperature_override = temperature-- # Will be set in ainit()- self.config: dict[str, Any] = {}- self.api_key: str | None = None- self.base_url: str | None = None- self.api_version: str | None = None- self.kb_name = kb_name or ""- self.logger: logging.Logger = logging.getLogger("deeptutor.Solver")- self.display_manager = None- self._task_log_handler: logging.Handler | None = None- self.token_tracker: TokenTracker | None = None- self._trace_callback: Any = None- self._conversation_context: str = ""-- # Agents (set in ainit)- self.planner_agent: PlannerAgent | None = None- self.solver_agent: SolverAgent | None = None- self.writer_agent: WriterAgent | None = None- self.tool_runtime: SolveToolRuntime | None = None-- # ------------------------------------------------------------------- # Async initialisation- # -------------------------------------------------------------------- async def ainit(self) -> None:- """Complete async initialisation: config, logger, agents."""- await self._load_config()- self._init_logging()- self._init_agents()- self.logger.info("Solver ready (Plan -> ReAct -> Write)")-- def set_trace_callback(self, callback) -> None:- """Register a callback that receives structured LLM trace events."""- self._trace_callback = callback- for agent in (self.planner_agent, self.solver_agent, self.writer_agent):- if agent is not None:- agent.set_trace_callback(callback)-- async def _emit_trace_event(self, payload: dict[str, Any]) -> None:- callback = self._trace_callback- if callback is None:- return- try:- result = callback(payload)- if asyncio.iscoroutine(result):- await result- except Exception:- pass-- async def _load_config(self) -> None:- """Load configuration from main.yaml or custom path."""- config_path = self._config_path- language = self._language- output_base_dir = self._output_base_dir-- if config_path is None:- project_root = Path(__file__).parent.parent.parent.parent- from ...services.config.loader import load_config_with_main_async-- full_config = await load_config_with_main_async("main.yaml", project_root)- solve_config = full_config.get("capabilities", {}).get("solve", {})- paths_config = full_config.get("paths", {})- path_service = get_path_service()- default_solve_dir = str(path_service.get_solve_dir())-- self.config = {- "system": {- "output_base_dir": paths_config.get("solve_output_dir", default_solve_dir),- "save_intermediate_results": solve_config.get(- "save_intermediate_results", True- ),- "language": full_config.get("system", {}).get("language", "en"),- },- "logging": full_config.get("logging", {}),- "tools": full_config.get("tools", {}),- "paths": paths_config,- "solve": solve_config,- }- else:- local_config: dict[str, Any] = {}- if Path(config_path).exists():- try:-- def _load(p: str) -> dict:- with open(p, encoding="utf-8") as f:- return yaml.safe_load(f) or {}-- local_config = await asyncio.to_thread(_load, config_path)- except Exception:- pass- self.config = local_config if isinstance(local_config, dict) else {}-- if not isinstance(self.config, dict):- self.config = {}-- # Override language from UI- if language:- self.config.setdefault("system", {})- self.config["system"]["language"] = parse_language(language)-- # Override output dir- if output_base_dir:- self.config.setdefault("system", {})- self.config["system"]["output_base_dir"] = str(output_base_dir)-- # Load LLM credentials- api_key = self._api_key- base_url = self._base_url- api_version = self._api_version-- if api_key is None or base_url is None:- try:- from ...services.llm.config import get_llm_config_async-- llm_config = await get_llm_config_async()- api_key = api_key or llm_config.api_key- base_url = base_url or llm_config.base_url- api_version = api_version or getattr(llm_config, "api_version", None)- except ValueError as exc:- raise ValueError(f"LLM config error: {exc}") from exc-- from deeptutor.services.llm import is_local_llm_server-- if not api_key and not is_local_llm_server(base_url):- raise ValueError(- "API key not set. Configure the active LLM profile in Settings > Catalog"- )- if not api_key and is_local_llm_server(base_url):- api_key = "sk-no-key-required"-- self.api_key = api_key- self.base_url = base_url- self.api_version = api_version- self.kb_name = self._kb_name or ""-- def _init_logging(self) -> None:- """Initialise logger, display manager, and token tracker."""- self.logger = logging.getLogger("deeptutor.Solver")- self.display_manager = get_display_manager()-- self.token_tracker = TokenTracker(prefer_tiktoken=True)- if self.display_manager:- self.token_tracker.set_on_usage_added_callback(self.display_manager.update_token_stats)-- self._log_section("Solver Initialising (Plan -> ReAct -> Write)")- self.logger.info(f"Knowledge Base: {self.kb_name}")-- def _log_section(self, title: str) -> None:- self.logger.info("=" * 60)- self.logger.info(title)- self.logger.info("=" * 60)-- def _log_stage(self, stage_name: str, status: str = "start", detail: str | None = None) -> None:- suffix = f" | {detail}" if detail else ""- self.logger.info("%s %s%s", stage_name, status, suffix, extra={"stage": stage_name})-- def _add_task_log_handler(self, task_log: str) -> None:- self._remove_task_log_handler()- path = Path(task_log)- path.parent.mkdir(parents=True, exist_ok=True)- handler = logging.FileHandler(path, encoding="utf-8")- handler.setLevel(logging.DEBUG)- handler.setFormatter(- logging.Formatter("%(asctime)s [%(levelname)s] %(name)s - %(message)s")- )- self.logger.addHandler(handler)- self._task_log_handler = handler-- def _remove_task_log_handler(self) -> None:- if self._task_log_handler is None:- return- self.logger.removeHandler(self._task_log_handler)- self._task_log_handler.close()- self._task_log_handler = None-- def _update_token_stats(self, summary: dict[str, Any]) -> None:- if self.display_manager and summary:- self.display_manager.update_token_stats(summary)-- def _init_agents(self) -> None:- """Create the three agents."""- from deeptutor.runtime.registry.tool_registry import get_tool_registry-- lang = parse_language(self.config.get("system", {}).get("language", "en"))- self._core_tool_registry = get_tool_registry()- self.tool_runtime = SolveToolRuntime(- enabled_tools=self._enabled_tools,- language=lang,- core_registry=self._core_tool_registry,- )- common = dict(- config=self.config,- api_key=self.api_key,- base_url=self.base_url,- api_version=self.api_version,- model=self._model,- token_tracker=self.token_tracker,- language=lang,- )- self.planner_agent = PlannerAgent(- **common,- tool_runtime=self.tool_runtime,- enable_pre_retrieve=not self.disable_planner_retrieve,- )- self.solver_agent = SolverAgent(**common, tool_runtime=self.tool_runtime)- self.writer_agent = WriterAgent(**common)- if self._trace_callback is not None:- self.set_trace_callback(self._trace_callback)-- # Apply per-run overrides from benchmark config (pipeline.max_tokens / pipeline.temperature)- if self._max_tokens_override is not None or self._temperature_override is not None:- for agent in (self.planner_agent, self.solver_agent, self.writer_agent):- if self._max_tokens_override is not None:- agent._agent_params["max_tokens"] = self._max_tokens_override- if self._temperature_override is not None:- agent._agent_params["temperature"] = self._temperature_override-- self.logger.info(- f"Agents initialised (lang={lang}), tools registered: {self.tool_runtime.tool_names}"- )-- # ------------------------------------------------------------------- # Main entry point- # -------------------------------------------------------------------- async def solve(- self,- question: str,- image_url: str | None = None,- attachments: list[Any] | None = None,- verbose: bool = True,- detailed: bool | None = None,- conversation_context: str = "",- ) -> dict[str, Any]:- """Run the full Plan -> ReAct -> Write pipeline.-- Args:- question: The user question to solve.- image_url: Optional image URL for multimodal questions.- attachments: Optional multimodal attachments from the chat composer.- verbose: Enable verbose logging.- detailed: If True, use iterative detailed writing. If None, read from config.-- Returns a dict compatible with the existing API contract.- """- # Resolve detailed flag: explicit param > config > default False- if detailed is None:- detailed = self.config.get("solve", {}).get("detailed_answer", False)- self._detailed = detailed- self._conversation_context = conversation_context.strip()-- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- path_service = get_path_service()- output_base = self.config.get("system", {}).get(- "output_base_dir", str(path_service.get_solve_dir())- )- output_dir = os.path.join(output_base, f"solve_{timestamp}")- os.makedirs(output_dir, exist_ok=True)-- # Task-level log file- task_log = os.path.join(output_dir, "task.log")- self._add_task_log_handler(task_log)-- self._log_section("Problem Solving Started")- self.logger.info(f"Question: {question[:100]}{'...' if len(question) > 100 else ''}")- self.logger.info(f"Output: {output_dir}")-- try:- result = await self._run_pipeline(- question,- output_dir,- image_url=image_url,- attachments=attachments,- )- result["metadata"] = {- **result.get("metadata", {}),- "mode": "plan_react_write",- "timestamp": timestamp,- "output_dir": output_dir,- }-- # Cost report- if self.token_tracker:- summary = self.token_tracker.get_summary()- if summary["total_calls"] > 0:- self.logger.info(f"\n{self.token_tracker.format_summary()}")- cost_file = os.path.join(output_dir, "cost_report.json")- self.token_tracker.save(cost_file)- result["metadata"]["cost_summary"] = {- "total_cost_usd": summary.get("total_cost_usd", 0),- "total_tokens": summary.get("total_tokens", 0),- "total_calls": summary.get("total_calls", 0),- }- self.token_tracker.reset()-- self.logger.info("Problem solving completed")- self._remove_task_log_handler()- return result-- except Exception as exc:- self.logger.error(f"Solving failed: {exc}")- self.logger.error(traceback.format_exc())- self._remove_task_log_handler()- raise-- # ------------------------------------------------------------------- # Pipeline- # -------------------------------------------------------------------- async def _run_pipeline(- self,- question: str,- output_dir: str,- image_url: str | None = None,- attachments: list[Any] | None = None,- ) -> dict[str, Any]:- solve_cfg = self.config.get("solve", {})- max_react = solve_cfg.get("max_react_iterations", 5)- max_replans = solve_cfg.get("max_replans", 2)-- scratchpad = Scratchpad.load_or_create(output_dir, question)-- # ============================================================- # Phase 1: PLAN- # ============================================================- self._log_stage("Phase 1", "start", "Planning")- if self.display_manager:- self.display_manager.set_agent_status("PlannerAgent", "running")- if hasattr(self, "_send_progress_update"):- self._send_progress_update("plan", {"status": "planning"})-- memory_ctx = ""- if not self.disable_memory:- memory_ctx = await self._get_planner_memory_context(question)-- plan = await self.planner_agent.process(- question=question,- scratchpad=scratchpad,- kb_name=self.kb_name,- memory_context=memory_ctx,- image_url=image_url,- attachments=attachments,- )- scratchpad.set_plan(plan)- scratchpad.save(output_dir)-- if self.display_manager:- self.display_manager.set_agent_status("PlannerAgent", "done")- self.logger.info(f"Plan: {len(plan.steps)} steps — {plan.analysis[:80]}")- for s in plan.steps:- self.logger.info(f" [{s.id}] {s.goal}")- self._update_token_stats(self.token_tracker.get_summary())-- # ============================================================- # Phase 2: SOLVE (ReAct loop per step)- # ============================================================- self._log_stage("Phase 2", "start", "Solving")- if self.display_manager:- self.display_manager.set_agent_status("SolverAgent", "running")- if hasattr(self, "_send_progress_update"):- self._send_progress_update("solve", {"status": "starting"})-- replan_count = 0- safety_limit = (len(plan.steps) + max_replans) * (max_react + 1)- iterations = 0-- while not scratchpad.is_all_completed():- iterations += 1- if iterations > safety_limit:- self.logger.warning("Safety iteration limit reached")- break-- step = scratchpad.get_next_pending_step()- if step is None:- break-- scratchpad.mark_step_status(step.id, "in_progress")- self.logger.info(f" Step {step.id}: {step.goal}")- step_memory_context = ""- if not self.disable_memory:- step_memory_context = await self._get_solver_memory_context(step.goal)-- # Compute step index for progress reporting- step_index = (- next(- (i + 1 for i, s in enumerate(scratchpad.plan.steps) if s.id == step.id),- 0,- )- if scratchpad.plan- else 0- )- if hasattr(self, "_send_progress_update"):- self._send_progress_update(- "solve",- {- "step_id": step.id,- "step_index": step_index,- "step_target": step.goal,- },- )-- for round_num in range(max_react):- decision = await self.solver_agent.process(- question=question,- current_step=step,- scratchpad=scratchpad,- memory_context=step_memory_context,- image_url=image_url,- round_index=round_num + 1,- )-- action = decision["action"]- action_input = decision["action_input"]- thought = decision["thought"]- self_note = decision["self_note"]- trace_meta = decision.get("_trace", {})-- self.logger.info(f" Round {round_num + 1}: {action}({action_input[:60]}...)")- self.logger.debug(f" Thought: {thought[:120]}")-- if action == "done":- if self_note:- await self._emit_trace_event(- {- "event": "llm_observation",- "state": "complete",- "response": self_note,- **trace_meta,- }- )- scratchpad.add_entry(- step_id=step.id,- round_num=round_num,- thought=thought,- action="done",- action_input="",- observation="",- self_note=self_note,- )- scratchpad.mark_step_status(step.id, "completed")- scratchpad.save(output_dir)- self.logger.info(f" -> Step {step.id} completed")- break-- if action == "replan":- if self_note:- await self._emit_trace_event(- {- "event": "llm_observation",- "state": "complete",- "response": self_note,- **trace_meta,- }- )- replan_count += 1- self.logger.info(- f" -> Replan requested ({replan_count}/{max_replans}): {action_input[:80]}"- )- # Record the replan entry- scratchpad.add_entry(- step_id=step.id,- round_num=round_num,- thought=thought,- action="replan",- action_input=action_input,- observation="",- self_note=self_note,- )- if replan_count <= max_replans:- if self.display_manager:- self.display_manager.set_agent_status("PlannerAgent", "running")- replan_memory = ""- if not self.disable_memory:- replan_memory = await self._get_planner_memory_context(question)- new_plan = await self.planner_agent.process(- question=question,- scratchpad=scratchpad,- kb_name=self.kb_name,- replan=True,- memory_context=replan_memory,- image_url=image_url,- attachments=attachments,- )- scratchpad.update_plan(new_plan)- scratchpad.save(output_dir)- if self.display_manager:- self.display_manager.set_agent_status("PlannerAgent", "done")- self.logger.info(f" Plan revised: {len(new_plan.steps)} steps")- else:- self.logger.warning(" Max replans reached — marking step completed")- scratchpad.mark_step_status(step.id, "completed")- scratchpad.save(output_dir)- break-- # Execute tool- await self._emit_trace_event(- {- "event": "tool_call",- "state": "running",- "tool_name": action,- "tool_args": {"input": action_input},- **trace_meta,- }- )- observation, sources = await self._execute_tool(- action=action,- action_input=action_input,- output_dir=output_dir,- question=question,- scratchpad=scratchpad,- trace_meta=trace_meta,- )- await self._emit_trace_event(- {- "event": "tool_result",- "state": "complete",- "tool_name": action,- "result": observation,- "sources": [s.to_dict() for s in sources],- **trace_meta,- }- )- if self_note:- await self._emit_trace_event(- {- "event": "llm_observation",- "state": "complete",- "response": self_note,- **trace_meta,- }- )-- scratchpad.add_entry(- step_id=step.id,- round_num=round_num,- thought=thought,- action=action,- action_input=action_input,- observation=observation,- self_note=self_note,- sources=sources,- )- scratchpad.save(output_dir)- self._update_token_stats(self.token_tracker.get_summary())- else:- # Max rounds exhausted for this step- self.logger.warning(f" Max ReAct iterations reached for {step.id}")- scratchpad.mark_step_status(step.id, "completed")- scratchpad.save(output_dir)-- if self.display_manager:- self.display_manager.set_agent_status("SolverAgent", "done")-- completed = scratchpad.get_completed_steps()- total = len(scratchpad.plan.steps) if scratchpad.plan else 0- self.logger.info(f" Solve phase done: {len(completed)}/{total} steps completed")- self._update_token_stats(self.token_tracker.get_summary())-- # ============================================================- # Phase 3: WRITE- # ============================================================- detailed = getattr(self, "_detailed", False)- write_mode = "detailed iterative" if detailed else "simple"- self._log_stage("Phase 3", "start", f"Writing answer ({write_mode})")- if self.display_manager:- self.display_manager.set_agent_status("WriterAgent", "running")- if hasattr(self, "_send_progress_update"):- self._send_progress_update("write", {"status": "writing"})-- language = self.config.get("system", {}).get("language", "en")- lang_code = parse_language(language)-- preference = "" if self.disable_memory else self._get_user_preference()-- content_cb = getattr(self, "_content_callback", None)-- if detailed:- final_answer = await self.writer_agent.process_iterative(- question=question,- scratchpad=scratchpad,- language=lang_code,- preference=preference,- on_content_chunk=content_cb,- )- else:- final_answer = await self.writer_agent.process(- question=question,- scratchpad=scratchpad,- language=lang_code,- preference=preference,- on_content_chunk=content_cb,- )-- if self.display_manager:- self.display_manager.set_agent_status("WriterAgent", "done")-- # Save final answer- answer_file = Path(output_dir) / "final_answer.md"- with open(answer_file, "w", encoding="utf-8") as f:- f.write(final_answer)- self.logger.info(f"Final answer saved: {answer_file}")- self._update_token_stats(self.token_tracker.get_summary())-- if not self.disable_memory:- await self._publish_event(question, final_answer, scratchpad, output_dir)-- return {- "question": question,- "output_dir": output_dir,- "final_answer": final_answer,- "output_md": str(answer_file),- "output_json": str(Path(output_dir) / "scratchpad.json"),- "formatted_solution": final_answer,- "citations": [s["id"] for s in scratchpad.get_all_sources()],- "pipeline": "plan_react_write",- "total_steps": total,- "completed_steps": len(completed),- "total_react_entries": len(scratchpad.entries),- "plan_revisions": scratchpad.metadata.get("plan_revisions", 0),- "metadata": {- "total_steps": total,- "completed_steps": len(completed),- "plan_revisions": scratchpad.metadata.get("plan_revisions", 0),- },- }-- # ------------------------------------------------------------------- # Tool execution- # -------------------------------------------------------------------- async def _execute_tool(- self,- action: str,- action_input: str,- output_dir: str,- question: str = "",- scratchpad: Scratchpad | None = None,- trace_meta: dict[str, Any] | None = None,- ) -> tuple[str, list[Source]]:- """Execute a tool and return (observation_text, sources)."""- obs_max = self.config.get("solve", {}).get("observation_max_tokens", 2000)- sources: list[Source] = []- retrieve_trace = self._build_retrieve_trace_meta(action, action_input, trace_meta)-- try:- if self.tool_runtime is None:- raise RuntimeError("Solve tool runtime is not initialised.")- if action not in self.tool_runtime.valid_actions:- observation = f"Unknown action: {action}"- return observation, sources-- async def _event_sink(- event_type: str,- message: str = "",- metadata: dict[str, Any] | None = None,- ) -> None:- if retrieve_trace is None or not message:- return- await self._emit_trace_event(- {- "event": "tool_log",- "message": message,- **derive_trace_metadata(- retrieve_trace,- trace_kind=str(event_type or "tool_log"),- **(metadata or {}),- ),- }- )-- if retrieve_trace is not None:- await self._emit_trace_event(- {- "event": "tool_log",- "message": f"Query: {action_input}"- if action_input- else "Starting retrieval",- **derive_trace_metadata(- retrieve_trace,- trace_kind="call_status",- call_state="running",- ),- }- )-- result = await self.tool_runtime.execute(- action,- action_input,- kb_name=self.kb_name or None,- output_dir=output_dir,- reason_context=self._build_reason_context(question, scratchpad),- api_key=self.api_key,- base_url=self.base_url,- model=self.solver_agent.get_model() if self.solver_agent else None,- event_sink=_event_sink if retrieve_trace is not None else None,- )- if retrieve_trace is not None:- await self._emit_trace_event(- {- "event": "tool_log",- "message": f"Retrieve complete ({len(result.content)} chars)",- **derive_trace_metadata(- retrieve_trace,- trace_kind="call_status",- call_state="complete",- ),- }- )- observation = self._format_tool_observation(- action, result.content, result.metadata, obs_max- )- sources = self._convert_tool_sources(result.sources, result.metadata)- except Exception as exc:- observation = f"Tool error ({action}): {exc}"- self.logger.warning(f" Tool error: {exc}")- if retrieve_trace is not None:- await self._emit_trace_event(- {- "event": "tool_log",- "message": f"Retrieve failed: {exc}",- **derive_trace_metadata(- retrieve_trace,- trace_kind="call_status",- call_state="error",- error=str(exc),- ),- }- )-- return observation, sources-- def _build_retrieve_trace_meta(- self,- action: str,- action_input: str,- trace_meta: dict[str, Any] | None,- ) -> dict[str, Any] | None:- if self.tool_runtime is None or not trace_meta:- return None- resolved_tool = self.tool_runtime.resolve_tool_name(action)- if resolved_tool != "rag":- return None- return derive_trace_metadata(- trace_meta,- call_id=new_call_id("solve-retrieve"),- label="Retrieve",- call_kind="rag_retrieval",- trace_role="retrieve",- trace_group="retrieve",- trace_id=f"{trace_meta.get('trace_id', 'solve')}-retrieve",- query=action_input,- tool_name=resolved_tool,- )-- def _build_reason_context(- self,- question: str,- scratchpad: Scratchpad | None,- ) -> str:- # Build context from scratchpad so the reasoning LLM has background- context_parts: list[str] = []- if question:- context_parts.append(f"Original question: {question}")- if scratchpad:- if scratchpad.plan:- context_parts.append(f"Plan:\n{scratchpad._format_plan()}")- # Summaries of completed steps- completed = scratchpad.get_completed_steps()- if completed:- notes: list[str] = []- for step in completed:- entries = scratchpad.get_entries_for_step(step.id)- step_notes = [e.self_note for e in entries if e.self_note]- if step_notes:- notes.append(f"[{step.id}] {step.goal}: {' '.join(step_notes)}")- if notes:- context_parts.append("Knowledge from previous steps:\n" + "\n".join(notes))-- return "\n\n".join(context_parts)-- @staticmethod- def _format_tool_observation(- action: str,- content: str,- metadata: dict[str, Any],- max_chars: int,- ) -> str:- text = (content or "").strip() or "(no results)"- if action in {"code_execution", "code_execute", "run_code"}:- code = (metadata.get("code") or "").strip()- if code:- text = f"Code:\n```python\n{code}\n```\n\n{text}"- return text[: max_chars * 4]-- @staticmethod- def _convert_tool_sources(- tool_sources: list[dict[str, Any]] | None,- metadata: dict[str, Any],- ) -> list[Source]:- sources: list[Source] = []- for item in tool_sources or []:- if not isinstance(item, dict):- continue- sources.append(- Source(- type=str(item.get("type", "reference")),- file=item.get("file") or item.get("title") or item.get("kb_name"),- page=item.get("page"),- url=item.get("url"),- chunk_id=item.get("chunk_id") or item.get("query") or item.get("identifier"),- )- )-- for artifact_path in metadata.get("artifact_paths", []):- sources.append(Source(type="code", file=Path(artifact_path).name))- return sources-- # ------------------------------------------------------------------- # Helpers- # -------------------------------------------------------------------- def _get_user_preference(self) -> str:- """Get personalisation preference (optional)."""- try:- from deeptutor.services.memory import get_memory_service-- return get_memory_service().get_preferences_text()- except Exception:- return ""-- async def _get_planner_memory_context(self, question: str) -> str:- _ = question- return self._merge_memory_context("")-- async def _get_solver_memory_context(self, step_goal: str) -> str:- _ = step_goal- return self._merge_memory_context(- "",- include_conversation=False,- )-- def _merge_memory_context(- self,- memory_context: str,- include_conversation: bool = True,- ) -> str:- parts = []- if include_conversation and self._conversation_context:- parts.append(f"Conversation context:\n{self._conversation_context}")- if memory_context:- parts.append(memory_context)- return "\n\n".join(part for part in parts if part)-- async def _publish_event(- self,- question: str,- answer: str,- scratchpad: Scratchpad,- output_dir: str,- ) -> None:- """Publish SOLVE_COMPLETE event for personalisation."""- try:- from deeptutor.events.event_bus import Event, EventType, get_event_bus-- task_id = Path(output_dir).name- tools_used = list(- {e.action for e in scratchpad.entries if e.action not in ("done", "replan")}- )-- event = Event(- type=EventType.SOLVE_COMPLETE,- task_id=task_id,- user_input=question,- agent_output=answer[:2000],- tools_used=tools_used,- success=True,- metadata={- "total_steps": len(scratchpad.plan.steps) if scratchpad.plan else 0,- "completed_steps": len(scratchpad.get_completed_steps()),- "citations_count": len(scratchpad.get_all_sources()),- "output_dir": output_dir,- },- )- await get_event_bus().publish(event)- self.logger.debug("Published SOLVE_COMPLETE event")- except Exception as exc:- self.logger.debug(f"Failed to publish event: {exc}")diff --git a/deeptutor/agents/solve/memory/__init__.py b/deeptutor/agents/solve/memory/__init__.pydeleted file mode 100644index f696bd266..000000000--- a/deeptutor/agents/solve/memory/__init__.py+++ /dev/null@@ -1,11 +0,0 @@-"""Solve Agent Memory — unified Scratchpad."""--from .scratchpad import Entry, Plan, PlanStep, Scratchpad, Source--__all__ = [- "Scratchpad",- "Plan",- "PlanStep",- "Entry",- "Source",-]diff --git a/deeptutor/agents/solve/memory/scratchpad.py b/deeptutor/agents/solve/memory/scratchpad.pydeleted file mode 100644index 772566b18..000000000--- a/deeptutor/agents/solve/memory/scratchpad.py+++ /dev/null@@ -1,470 +0,0 @@-"""-Scratchpad - Unified memory for the Plan -> ReAct -> Write pipeline.--Replaces InvestigateMemory + SolveMemory + CitationMemory with a single-linear data structure that tracks the plan, all ReAct iterations, and-sources for citation.-"""--from __future__ import annotations--from dataclasses import asdict, dataclass, field-from datetime import datetime-import json-import os-from typing import Any--# Optional tiktoken for accurate token counting-try:- import tiktoken-- _TIKTOKEN_AVAILABLE = True-except ImportError:- _TIKTOKEN_AVAILABLE = False---# ----------------------------------------------------------------------------# Data classes-# ------------------------------------------------------------------------------@dataclass-class Source:- """A citation source attached to a retrieval entry."""-- type: str # rag, web, code- file: str | None = None- page: int | None = None- url: str | None = None- chunk_id: str | None = None-- # ---------- serialisation helpers ----------- def to_dict(self) -> dict[str, Any]:- return {k: v for k, v in asdict(self).items() if v is not None}-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> Source:- return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})---@dataclass-class PlanStep:- """One step in the plan produced by PlannerAgent."""-- id: str- goal: str- tools_hint: list[str] = field(default_factory=list)- status: str = "pending" # pending | in_progress | completed | skipped-- def to_dict(self) -> dict[str, Any]:- return asdict(self)-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> PlanStep:- return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})---@dataclass-class Plan:- """High-level plan output by PlannerAgent."""-- analysis: str = ""- steps: list[PlanStep] = field(default_factory=list)-- def to_dict(self) -> dict[str, Any]:- return {- "analysis": self.analysis,- "steps": [s.to_dict() for s in self.steps],- }-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> Plan:- steps = [PlanStep.from_dict(s) for s in data.get("steps", [])]- return cls(analysis=data.get("analysis", ""), steps=steps)---@dataclass-class Entry:- """One ReAct iteration entry."""-- step_id: str- round: int- thought: str = ""- action: str = ""- action_input: str = ""- observation: str = ""- self_note: str = ""- sources: list[Source] = field(default_factory=list)- timestamp: str = field(default_factory=lambda: datetime.now().isoformat())-- def to_dict(self) -> dict[str, Any]:- d = asdict(self)- d["sources"] = [s.to_dict() for s in self.sources]- return d-- @classmethod- def from_dict(cls, data: dict[str, Any]) -> Entry:- sources = [Source.from_dict(s) for s in data.get("sources", [])]- filtered = {- k: v for k, v in data.items() if k in cls.__dataclass_fields__ and k != "sources"- }- return cls(sources=sources, **filtered)---# ----------------------------------------------------------------------------# Scratchpad-# ------------------------------------------------------------------------------class Scratchpad:- """Unified memory: plan + ReAct entries + metadata."""-- VERSION = "1.0"- FILENAME = "scratchpad.json"-- def __init__(self, question: str) -> None:- self.question: str = question- self.plan: Plan | None = None- self.entries: list[Entry] = []- self.metadata: dict[str, Any] = {- "total_llm_calls": 0,- "total_tokens": 0,- "start_time": datetime.now().isoformat(),- "plan_revisions": 0,- }-- # ------------------------------------------------------------------- # Plan management- # -------------------------------------------------------------------- def set_plan(self, plan: Plan) -> None:- """Set the initial plan."""- self.plan = plan-- def update_plan(self, new_plan: Plan) -> None:- """Replan: keep completed steps from the old plan, replace the rest."""- if self.plan is None:- self.plan = new_plan- return-- self.metadata["plan_revisions"] = self.metadata.get("plan_revisions", 0) + 1-- completed = [s for s in self.plan.steps if s.status == "completed"]- completed_ids = {s.id for s in completed}-- # New steps = completed (preserved) + new pending steps (with fresh IDs)- new_pending = [s for s in new_plan.steps if s.id not in completed_ids]- self.plan.analysis = new_plan.analysis- self.plan.steps = completed + new_pending-- # ------------------------------------------------------------------- # Step status management- # -------------------------------------------------------------------- def mark_step_status(self, step_id: str, status: str) -> None:- if self.plan is None:- return- for step in self.plan.steps:- if step.id == step_id:- step.status = status- return-- def get_next_pending_step(self) -> PlanStep | None:- if self.plan is None:- return None- for step in self.plan.steps:- if step.status == "pending":- return step- return None-- def get_completed_steps(self) -> list[PlanStep]:- if self.plan is None:- return []- return [s for s in self.plan.steps if s.status == "completed"]-- def is_all_completed(self) -> bool:- if self.plan is None:- return True- return all(s.status in ("completed", "skipped") for s in self.plan.steps)-- # ------------------------------------------------------------------- # Entry management- # -------------------------------------------------------------------- def add_entry(- self,- step_id: str,- round_num: int,- thought: str,- action: str,- action_input: str,- observation: str,- self_note: str,- sources: list[Source] | None = None,- ) -> Entry:- entry = Entry(- step_id=step_id,- round=round_num,- thought=thought,- action=action,- action_input=action_input,- observation=observation,- self_note=self_note,- sources=sources or [],- )- self.entries.append(entry)- return entry-- def get_entries_for_step(self, step_id: str) -> list[Entry]:- return [e for e in self.entries if e.step_id == step_id]-- # ------------------------------------------------------------------- # Context builders (for prompt construction with compression)- # -------------------------------------------------------------------- def build_solver_context(- self,- current_step_id: str,- max_tokens: int = 6000,- ) -> dict[str, str]:- """Build compressed context for SolverAgent prompt.-- Returns dict with keys: plan, current_step, step_history, previous_knowledge- """- # Plan summary- plan_text = self._format_plan()-- # Current step description- current_step_text = ""- if self.plan:- for s in self.plan.steps:- if s.id == current_step_id:- current_step_text = f"[{s.id}] {s.goal}"- break-- # Step history (current step entries – full observations)- current_entries = self.get_entries_for_step(current_step_id)- step_history_parts: list[str] = []- for e in current_entries:- step_history_parts.append(- f"Round {e.round}:\n"- f" Thought: {e.thought}\n"- f" Action: {e.action}({e.action_input})\n"- f" Observation: {e.observation}\n"- f" Note: {e.self_note}"- )- step_history = "\n\n".join(step_history_parts) if step_history_parts else "(no actions yet)"-- # Tool usage stats for the current step — helps the agent detect- # repeated calls to the same tool and consider switching strategy.- tool_actions = [e.action for e in current_entries if e.action not in ("done", "replan", "")]- if tool_actions:- from collections import Counter-- counts = Counter(tool_actions)- stats = ", ".join(f"{tool} ×{n}" for tool, n in counts.most_common())- step_history += f"\n\n[Tool usage this step: {stats}]"-- # Previous knowledge from completed steps (compressed)- previous_parts: list[str] = []- if self.plan:- completed_ids = [s.id for s in self.plan.steps if s.status == "completed"]- for sid in completed_ids:- entries = self.get_entries_for_step(sid)- step_obj = next((s for s in self.plan.steps if s.id == sid), None)- goal_text = step_obj.goal if step_obj else sid- notes = [e.self_note for e in entries if e.self_note]- if notes:- previous_parts.append(f"[{sid}] {goal_text}: {' '.join(notes)}")-- previous_knowledge = (- "\n".join(previous_parts) if previous_parts else "(no previous steps completed)"- )-- # Token budget check – if over budget, aggressively compress previous_knowledge- total = self._estimate_tokens(- plan_text + current_step_text + step_history + previous_knowledge- )- if total > max_tokens and previous_parts:- # Keep only self_notes, one line each- compressed = []- for sid in completed_ids:- entries = self.get_entries_for_step(sid)- notes = " | ".join(e.self_note for e in entries if e.self_note)- if notes:- compressed.append(f"[{sid}]: {notes}")- previous_knowledge = "\n".join(compressed) if compressed else "(compressed)"-- return {- "plan": plan_text,- "current_step": current_step_text,- "step_history": step_history,- "previous_knowledge": previous_knowledge,- }-- def build_writer_context(self, max_tokens: int = 12000) -> str:- """Build context for WriterAgent – preserves more detail."""- parts: list[str] = []-- if self.plan:- parts.append("## Plan\n" + self._format_plan())-- if not self.plan:- return "\n\n".join(parts) or "(no evidence gathered)"-- for step in self.plan.steps:- if step.status not in ("completed", "in_progress"):- continue- entries = self.get_entries_for_step(step.id)- if not entries:- continue-- step_parts = [f"### Step {step.id}: {step.goal}"]- for e in entries:- entry_text = (- f"**Round {e.round}** — Action: {e.action}({e.action_input})\n"- f"Note: {e.self_note}\n"- f"Observation:\n{e.observation}"- )- step_parts.append(entry_text)- parts.append("\n\n".join(step_parts))-- full = "\n\n---\n\n".join(parts)-- # If over budget, drop observations from early steps- if self._estimate_tokens(full) > max_tokens and self.plan:- parts_compressed: list[str] = []- step_list = [s for s in self.plan.steps if s.status in ("completed", "in_progress")]- n = len(step_list)- for i, step in enumerate(step_list):- entries = self.get_entries_for_step(step.id)- if not entries:- continue- step_parts_c = [f"### Step {step.id}: {step.goal}"]- for e in entries:- if i < n - 2:- # Early steps: notes only- step_parts_c.append(f"Round {e.round}: {e.self_note}")- else:- # Recent steps: full observation- step_parts_c.append(- f"**Round {e.round}** — Action: {e.action}({e.action_input})\n"- f"Note: {e.self_note}\n"- f"Observation:\n{e.observation}"- )- parts_compressed.append("\n".join(step_parts_c))- full = "\n\n---\n\n".join(parts_compressed)-- return full or "(no evidence gathered)"-- # ------------------------------------------------------------------- # Sources- # -------------------------------------------------------------------- def get_all_sources(self) -> list[dict[str, Any]]:- """Return deduplicated list of all sources with IDs.-- Each distinct (type, file, url, chunk_id) tuple is a unique source.- For RAG sources this means different queries produce separate citations- even when they target the same knowledge base.- """- seen: set[str] = set()- result: list[dict[str, Any]] = []- counter: dict[str, int] = {}- for entry in self.entries:- for src in entry.sources:- key = f"{src.type}|{src.file or ''}|{src.url or ''}|{src.chunk_id or ''}"- if key not in seen:- seen.add(key)- prefix = src.type if src.type in ("rag", "web", "code") else "src"- counter[prefix] = counter.get(prefix, 0) + 1- source_id = f"{prefix}-{counter[prefix]}"- d = src.to_dict()- d["id"] = source_id- result.append(d)- return result-- def format_sources_markdown(self) -> str:- """Format sources as a Markdown references section with clickable URLs."""- sources = self.get_all_sources()- if not sources:- return ""- lines = ["## References\n"]- for s in sources:- label = self._source_label(s)- url = s.get("url", "")- if url:- lines.append(f"- **[{s['id']}]** [{label}]({url})")- else:- lines.append(f"- **[{s['id']}]** {label}")- return "\n".join(lines)-- @staticmethod- def _source_label(s: dict[str, Any]) -> str:- """Build a human-readable label for a source entry.-- RAG sources use the query text as primary label with the knowledge-base- name as qualifier, so different queries are visually distinguishable.- """- if s.get("type") == "rag" and s.get("chunk_id"):- query_text = s["chunk_id"]- kb = s.get("file")- return f"{query_text} ({kb})" if kb else query_text- return s.get("file") or s.get("url") or s.get("chunk_id") or "unknown"-- # ------------------------------------------------------------------- # Persistence- # -------------------------------------------------------------------- def save(self, output_dir: str) -> str:- path = os.path.join(output_dir, self.FILENAME)- data = {- "version": self.VERSION,- "question": self.question,- "plan": self.plan.to_dict() if self.plan else None,- "entries": [e.to_dict() for e in self.entries],- "metadata": self.metadata,- }- with open(path, "w", encoding="utf-8") as f:- json.dump(data, f, ensure_ascii=False, indent=2)- return path-- @classmethod- def load_or_create(cls, output_dir: str, question: str) -> Scratchpad:- path = os.path.join(output_dir, cls.FILENAME)- if os.path.exists(path):- with open(path, encoding="utf-8") as f:- data = json.load(f)- pad = cls(question=data.get("question", question))- if data.get("plan"):- pad.plan = Plan.from_dict(data["plan"])- pad.entries = [Entry.from_dict(e) for e in data.get("entries", [])]- pad.metadata = data.get("metadata", pad.metadata)- return pad- return cls(question=question)-- # ------------------------------------------------------------------- # Internal helpers- # -------------------------------------------------------------------- def _format_plan(self) -> str:- if self.plan is None:- return "(no plan yet)"- lines = [f"Analysis: {self.plan.analysis}"]- for s in self.plan.steps:- status_mark = {"completed": "[x]", "in_progress": "[>]", "skipped": "[-]"}.get(- s.status, "[ ]"- )- lines.append(f" {status_mark} {s.id}: {s.goal}")- return "\n".join(lines)-- @staticmethod- def _estimate_tokens(text: str) -> int:- """Estimate token count. Uses tiktoken if available, else chars/4."""- if _TIKTOKEN_AVAILABLE:- try:- enc = tiktoken.get_encoding("cl100k_base")- return len(enc.encode(text))- except Exception:- pass- return len(text) // 4diff --git a/deeptutor/agents/solve/pipeline.py b/deeptutor/agents/solve/pipeline.pynew file mode 100644index 000000000..c85637a7f--- /dev/null+++ b/deeptutor/agents/solve/pipeline.py@@ -0,0 +1,1698 @@+"""SolvePipeline — agentic-engine-based replacement for ``MainSolver``.++Phase shape:++* **Phase 0 (Pre-retrieve)** — only when a KB is attached: one ``QUERIES``+ labeled step generates N queries, ``rag`` runs them in parallel, then one+ ``SUMMARY`` labeled step aggregates the results into a knowledge note.+* **Phase 1 (Plan)** — one ``PLAN`` labeled step emits a JSON plan. On+ ``REPLAN`` from Phase 2 the planner is re-entered with the previous+ attempt + replan reason as additional context.+* **Phase 2 (Solve)** — for each step, one agentic loop over the four+ ``THINK`` / ``TOOL`` / ``FINISH`` / ``REPLAN`` labels (see+ :mod:`deeptutor.core.agentic`). Each ``FINISH`` text is streamed as a+ user-facing section that flows into the next step's prompt context so+ the sections read as one continuous answer.+* **Phase 3 (Synthesize)** — one ``FINISH`` labeled step emits the precise+ final answer + a short recap.++The orchestrator owns control flow (replan back-edge, exhaustion handling)+and per-step prompt assembly; everything else is delegated to the engine+primitives.+"""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Awaitable+from dataclasses import dataclass, field+from typing import Any++from deeptutor.core.agentic import (+ DispatchOutcome,+ LLMClientConfig,+ LabeledStepResult,+ LabelProtocol,+ LoopOutcome,+ UsageTracker,+ build_completion_kwargs,+ build_openai_client,+ can_use_native_tool_calling,+ dispatch_tool_calls,+ run_agentic_loop,+ run_labeled_step,+)+from deeptutor.capabilities._shared import emit_capability_result+from deeptutor.core.agentic.labels import find_inline_labels+from deeptutor.core.agentic.tool_dispatch import (+ MAX_PARALLEL_TOOL_CALLS,+ execute_tool_call,+)+from deeptutor.core.context import Attachment, UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import (+ build_trace_metadata,+ derive_trace_metadata,+ merge_trace_metadata,+ new_call_id,+)+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.config import parse_language+from deeptutor.services.llm import get_llm_config, prepare_multimodal_messages+from deeptutor.services.path_service import get_path_service+from deeptutor.services.prompt import get_prompt_manager+from deeptutor.services.prompt.language import append_language_directive+from deeptutor.utils.json_parser import parse_json_response++logger = logging.getLogger(__name__)+++SOURCE = "deep_solve"++# Labels each phase emits — must match what the YAML prompts instruct the LLM+# to produce.+LABEL_QUERIES = "QUERIES"+LABEL_SUMMARY = "SUMMARY"+LABEL_PLAN = "PLAN"+LABEL_THINK = "THINK"+LABEL_TOOL = "TOOL"+LABEL_FINISH = "FINISH"+LABEL_REPLAN = "REPLAN"+LABEL_EXPLAIN = "EXPLAIN"+LABEL_SKIP = "SKIP"++_PROTOCOL_QUERIES = LabelProtocol(+ allowed=(LABEL_QUERIES,),+ terminal=frozenset({LABEL_QUERIES}),+ intermediate=frozenset(),+ final=frozenset(),+ tool_label=None,+)+_PROTOCOL_SUMMARY = LabelProtocol(+ allowed=(LABEL_SUMMARY,),+ terminal=frozenset({LABEL_SUMMARY}),+ intermediate=frozenset(),+ final=frozenset(),+ tool_label=None,+)+_PROTOCOL_PLAN = LabelProtocol(+ allowed=(LABEL_PLAN,),+ terminal=frozenset({LABEL_PLAN}),+ intermediate=frozenset(),+ final=frozenset(),+ tool_label=None,+)+_PROTOCOL_STEP = LabelProtocol(+ allowed=(LABEL_THINK, LABEL_TOOL, LABEL_FINISH, LABEL_REPLAN),+ terminal=frozenset({LABEL_FINISH, LABEL_REPLAN}),+ intermediate=frozenset({LABEL_THINK}),+ final=frozenset({LABEL_FINISH}),+ tool_label=LABEL_TOOL,+)+_PROTOCOL_SYNTHESIZE = LabelProtocol(+ allowed=(LABEL_FINISH,),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset(),+ final=frozenset({LABEL_FINISH}),+ tool_label=None,+)+_PROTOCOL_EXPLAIN_JUDGE = LabelProtocol(+ allowed=(LABEL_EXPLAIN, LABEL_SKIP),+ terminal=frozenset({LABEL_EXPLAIN, LABEL_SKIP}),+ intermediate=frozenset(),+ final=frozenset(),+ tool_label=None,+)+_PROTOCOL_EXPLAIN = LabelProtocol(+ allowed=(LABEL_FINISH,),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset(),+ final=frozenset({LABEL_FINISH}),+ tool_label=None,+)++# Per-step iteration ceiling (Frank's choice: 7). Total replans across one+# turn are bounded separately by :attr:`SolvePipeline.max_replans`.+DEFAULT_MAX_ITERATIONS_PER_STEP = 7+DEFAULT_MAX_REPLANS = 2+DEFAULT_NUM_QUERIES = 3+DEFAULT_MAX_TOKENS = 8000+SYNTHESIZE_MAX_TOKENS = 2000+PRE_RETRIEVE_MAX_TOKENS = 2000+EXPLAIN_JUDGE_MAX_TOKENS = 500+EXPLAIN_MAX_TOKENS = 8000++# Caps that match the legacy planner's pre-retrieve sub-DAG so we don't+# blow up the aggregation call when retrieval pulls a lot of text.+MAX_CHARS_PER_RETRIEVAL = 2000+MAX_AGGREGATE_INPUT_CHARS = 6000++FINALIZATION_REPAIR_ATTEMPTS = 3+++def _load_solve_settings() -> dict[str, Any]:+ """Read ``capabilities.solve`` from main.yaml. Missing → empty dict.++ Kept narrow on purpose: only the iteration knobs are settings-driven+ today (``max_iterations_per_step`` and ``max_replans``). Other budgets+ remain code-level constants because they're prompt-engineering-coupled.+ """+ try:+ from deeptutor.services.config import load_config_with_main++ cfg = load_config_with_main("main.yaml") or {}+ capabilities = cfg.get("capabilities") or {}+ solve_cfg = capabilities.get("solve") or {}+ return solve_cfg if isinstance(solve_cfg, dict) else {}+ except Exception:+ logger.debug("Failed to load solve settings; using hardcoded defaults", exc_info=True)+ return {}+++# ---------------------------------------------------------------------------+# Data shapes+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class PlanStep:+ id: str+ goal: str+++@dataclass(frozen=True)+class Plan:+ analysis: str+ steps: list[PlanStep] = field(default_factory=list)+++@dataclass(frozen=True)+class StepFinish:+ step: PlanStep+ text: str+++# ---------------------------------------------------------------------------+# SolvePipeline+# ---------------------------------------------------------------------------+++class SolvePipeline:+ """One-shot orchestrator: instantiate per turn, call :meth:`run` once."""++ def __init__(+ self,+ *,+ language: str = "en",+ kb_name: str | None = None,+ enabled_tools: list[str] | None = None,+ max_iterations_per_step: int | None = None,+ max_replans: int | None = None,+ num_queries: int = DEFAULT_NUM_QUERIES,+ ) -> None:+ self.language = parse_language(language)+ self.kb_name = (kb_name or "").strip() or None+ self.enabled_tools = list(enabled_tools or [])+ # Iteration limits are settings-driven (capabilities.solve in+ # main.yaml). Explicit constructor args still win so tests can+ # pin a tight loop; ``None`` (the default) means "read settings".+ solve_settings = _load_solve_settings()+ self.max_iterations_per_step = max(+ 1,+ int(+ max_iterations_per_step+ if max_iterations_per_step is not None+ else solve_settings.get("max_iterations_per_step", DEFAULT_MAX_ITERATIONS_PER_STEP)+ ),+ )+ self.max_replans = max(+ 0,+ int(+ max_replans+ if max_replans is not None+ else solve_settings.get("max_replans", DEFAULT_MAX_REPLANS)+ ),+ )+ self.num_queries = max(1, int(num_queries))++ self.llm_config = get_llm_config()+ self.binding = getattr(self.llm_config, "binding", None) or "openai"+ self.model = getattr(self.llm_config, "model", None)+ self.api_key = getattr(self.llm_config, "api_key", None)+ self.base_url = getattr(self.llm_config, "base_url", None)+ self.api_version = getattr(self.llm_config, "api_version", None)+ self.extra_headers = getattr(self.llm_config, "extra_headers", None) or {}+ self.client_config = LLMClientConfig(+ binding=self.binding,+ model=self.model,+ api_key=self.api_key,+ base_url=self.base_url,+ api_version=self.api_version,+ extra_headers=self.extra_headers or None,+ )++ self.registry = get_tool_registry()+ self.usage = UsageTracker(model=self.model)++ self._temperature = 0.2+ try:+ self._prompts: dict[str, Any] = (+ get_prompt_manager().load_prompts(+ module_name="solve",+ agent_name="pipeline",+ language=self.language,+ )+ or {}+ )+ except Exception as exc:+ logger.warning("Failed to load solve pipeline prompts: %s", exc)+ self._prompts = {}++ # ------------------------------------------------------------------+ # Public entry point+ # ------------------------------------------------------------------+ async def run(+ self,+ *,+ context: UnifiedContext,+ question: str,+ attachments: list[Attachment] | None = None,+ conversation_context: str = "",+ memory_context: str = "",+ stream: StreamBus,+ ) -> dict[str, Any]:+ """Drive the four phases. Streams content + trace events; returns the+ final-answer payload for the capability to forward into+ ``stream.result``.++ Wraps each phase transition in a ``_visible_failure`` guard so any+ runtime exception surfaces in the trace UI as a labeled error card+ (a bare ``bus.error`` without ``call_id`` is not rendered by the+ frontend's ``TracePanels`` and would look like a silent termination).+ """+ attachments = list(attachments or [])+ conversation_context = conversation_context.strip()+ memory_context = memory_context.strip()++ client = self._build_client()+ image_attachments = [a for a in attachments if getattr(a, "type", "") == "image"]++ try:+ return await self._run_inner(+ context=context,+ question=question,+ conversation_context=conversation_context,+ memory_context=memory_context,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )+ except Exception as exc:+ logger.exception("SolvePipeline.run failed: %s", exc)+ await self._emit_visible_failure(stream, exc)+ raise++ async def _emit_visible_failure(self, stream: StreamBus, exc: BaseException) -> None:+ """Make a runtime failure visible to the user.++ Emits a trace card (so the panel shows up next to the plan card) plus+ a content event (so the chat bubble shows the error inline). The+ capability layer / orchestrator still gets the exception via+ ``re-raise`` so logs and DONE events fire normally.+ """+ call_id = new_call_id("solve-failure")+ meta = build_trace_metadata(+ call_id=call_id,+ phase="reasoning",+ label=self._t("labels.solve_step", default="Solve step"),+ call_kind="llm_final_response",+ trace_id=call_id,+ trace_role="response",+ trace_group="stage",+ )+ message = f"{type(exc).__name__}: {exc}" if str(exc) else type(exc).__name__+ await stream.error(+ message,+ source=SOURCE,+ stage="reasoning",+ metadata=merge_trace_metadata(meta, {"trace_kind": "error"}),+ )+ # A bare ``bus.error`` isn't rendered by the chat bubble; pipe the+ # same text through ``content`` so the user actually sees what went+ # wrong instead of an empty assistant message.+ prefix = "⚠️ " if self.language == "zh" else "⚠ "+ await stream.content(+ f"{prefix}{message}",+ source=SOURCE,+ stage="reasoning",+ metadata=merge_trace_metadata(meta, {"trace_kind": "llm_output"}),+ )++ async def _run_inner(+ self,+ *,+ context: UnifiedContext,+ question: str,+ conversation_context: str,+ memory_context: str,+ image_attachments: list[Attachment],+ stream: StreamBus,+ client: Any,+ ) -> dict[str, Any]:+ logger.info(+ "SolvePipeline.run start: lang=%s kb=%s tools=%s max_iter/step=%d max_replans=%d",+ self.language,+ self.kb_name,+ self.enabled_tools,+ self.max_iterations_per_step,+ self.max_replans,+ )++ # ----- Phase 0 + Phase 1 (planning umbrella) -----+ async with stream.stage("planning", source=SOURCE):+ retrieved_context = await self._pre_retrieve(+ question=question,+ stream=stream,+ client=client,+ context=context,+ )+ plan = await self._plan(+ question=question,+ retrieved_context=retrieved_context,+ memory_context=memory_context,+ conversation_context=conversation_context,+ replan_reason=None,+ previous_attempt=[],+ attempt_index=0,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )+ logger.info(+ "SolvePipeline plan: analysis=%r steps=%d",+ plan.analysis[:80],+ len(plan.steps),+ )++ # ----- Phase 2 (solve steps) -----+ step_finishes: list[StepFinish] = []+ replan_count = 0+ plan_attempt = 0+ async with stream.stage("reasoning", source=SOURCE):+ while True:+ plan_attempt += 1+ replanned = False+ attempt_finishes: list[StepFinish] = []+ for step_index, step in enumerate(plan.steps):+ logger.info(+ "SolvePipeline step %s (%d/%d, attempt %d)",+ step.id,+ step_index + 1,+ len(plan.steps),+ plan_attempt,+ )+ outcome = await self._solve_step(+ step=step,+ step_index=step_index,+ total_steps=len(plan.steps),+ plan=plan,+ question=question,+ retrieved_context=retrieved_context,+ previous_finishes=attempt_finishes,+ memory_context=memory_context,+ conversation_context=conversation_context,+ image_attachments=image_attachments,+ context=context,+ stream=stream,+ client=client,+ )+ if outcome.final_label == LABEL_REPLAN:+ if replan_count >= self.max_replans:+ await stream.progress(+ self._t("notices.replan_budget_exhausted"),+ source=SOURCE,+ stage="reasoning",+ metadata={"trace_kind": "warning"},+ )+ # Accept the replan reason as the step's content+ # so the synthesize phase still has something to+ # work with.+ attempt_finishes.append(+ StepFinish(step=step, text=outcome.final_text.strip())+ )+ continue+ replan_count += 1+ plan = await self._plan(+ question=question,+ retrieved_context=retrieved_context,+ memory_context=memory_context,+ conversation_context=conversation_context,+ replan_reason=outcome.final_text.strip(),+ previous_attempt=attempt_finishes,+ attempt_index=plan_attempt,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )+ replanned = True+ break+ # FINISH (or exhaustion-forced FINISH). After the step's+ # section has streamed to the user, optionally ask the+ # model whether a deeper explanation is worth appending,+ # and if so stream it live under the FINISH content.+ finish_text = outcome.final_text.strip()+ # Force a markdown block break before whatever streams+ # next (the explain expansion if EXPLAIN, otherwise the+ # next step's FINISH or the synthesize section). Without+ # this the next chunk would glue onto the last sentence+ # of this step.+ await self._emit_section_break(stream)+ explanation = await self._maybe_explain_step(+ step=step,+ question=question,+ finish_text=finish_text,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )+ combined_text = (+ f"{finish_text}\n\n{explanation}" if explanation else finish_text+ )+ attempt_finishes.append(+ StepFinish(step=step, text=combined_text)+ )+ if not replanned:+ step_finishes = attempt_finishes+ break++ # ----- Phase 3 (synthesize) -----+ logger.info(+ "SolvePipeline synthesize: %d completed steps", len(step_finishes)+ )+ final_text = ""+ async with stream.stage("writing", source=SOURCE):+ final_text = await self._synthesize(+ question=question,+ step_finishes=step_finishes,+ conversation_context=conversation_context,+ stream=stream,+ client=client,+ )++ result_payload: dict[str, Any] = {+ "response": self._compose_full_response(step_finishes, final_text),+ "step_count": len(plan.steps),+ "completed_steps": len(step_finishes),+ "plan_revisions": replan_count,+ "metadata": {+ "mode": "agentic_solve",+ "step_count": len(plan.steps),+ "plan_revisions": replan_count,+ },+ }+ await emit_capability_result(+ stream, result_payload, source=SOURCE, usage=self.usage+ )+ return result_payload++ # ------------------------------------------------------------------+ # Phase 0: pre-retrieve+ # ------------------------------------------------------------------+ async def _pre_retrieve(+ self,+ *,+ question: str,+ stream: StreamBus,+ client: Any,+ context: UnifiedContext,+ ) -> str:+ if not self.kb_name or not self._tool_in_registry("rag"):+ await stream.progress(+ self._t("notices.pre_retrieve_unavailable"),+ source=SOURCE,+ stage="planning",+ metadata={"trace_kind": "info"},+ )+ return self._t("empty.no_kb_retrieved")++ try:+ queries = await self._generate_search_queries(+ question=question, stream=stream, client=client+ )+ retrievals = await self._parallel_retrieve(+ queries=queries, stream=stream, context=context+ )+ if not any(item.get("answer") for item in retrievals):+ return self._t("empty.no_kb_retrieved")+ return await self._aggregate_retrieval_results(+ retrievals=retrievals, stream=stream, client=client+ )+ except Exception as exc:+ logger.warning("Pre-retrieval pipeline failed: %s", exc)+ return self._t("empty.no_kb_retrieved")++ async def _generate_search_queries(+ self,+ *,+ question: str,+ stream: StreamBus,+ client: Any,+ ) -> list[str]:+ system_prompt = self._t("pre_retrieve.gen_queries.system")+ user_prompt = self._t(+ "pre_retrieve.gen_queries.user_template",+ num_queries=self.num_queries,+ question=question,+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ iter_meta = self._build_simple_trace_meta(+ call_id_root="solve-queries",+ label=self._t("labels.gen_queries", default="Generate queries"),+ stage="planning",+ call_kind="llm_planning",+ trace_role="plan",+ trace_group="plan",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_QUERIES,+ stream=stream,+ stage="planning",+ iter_meta=iter_meta,+ )+ payload = parse_json_response(step.text, logger_instance=logger, fallback={})+ if isinstance(payload, list):+ queries = payload+ elif isinstance(payload, dict):+ queries = payload.get("queries", [])+ else:+ queries = []+ cleaned = [+ q.strip()+ for q in queries+ if isinstance(q, str) and q.strip()+ ]+ return cleaned[: self.num_queries] or [question]++ async def _parallel_retrieve(+ self,+ *,+ queries: list[str],+ stream: StreamBus,+ context: UnifiedContext,+ ) -> list[dict[str, Any]]:+ async def _one(query: str, index: int) -> dict[str, Any]:+ trace_call_id = new_call_id(f"solve-retrieve-{index}")+ retrieve_meta = build_trace_metadata(+ call_id=trace_call_id,+ phase="planning",+ label=f"{self._t('labels.retrieve', default='Retrieve')} {index}",+ call_kind="rag_retrieval",+ trace_id=trace_call_id,+ trace_role="retrieve",+ trace_group="retrieve",+ query=query,+ tool_name="rag",+ )+ try:+ result = await execute_tool_call(+ registry=self.registry,+ tool_name="rag",+ tool_args={"query": query, "kb_name": self.kb_name, "mode": "hybrid"},+ stream=stream,+ source=SOURCE,+ stage="planning",+ retrieve_meta=retrieve_meta,+ empty_tool_result_message=self._t("notices.empty_tool_result"),+ start_retrieval_message=self._t(+ "notices.start_retrieval", default="Starting retrieval"+ ),+ retrieve_label=self._t("labels.retrieve", default="Retrieve"),+ unknown_error_message_factory=lambda tn: self._t(+ "notices.tool_unknown_error",+ tool=tn,+ default=f"Error executing {tn}.",+ ),+ )+ return {"query": query, "answer": result.get("result_text", "")}+ except Exception as exc:+ logger.warning("Retrieval failed for query %r: %s", query[:60], exc)+ return {"query": query, "answer": ""}++ return await asyncio.gather(+ *[_one(q, i + 1) for i, q in enumerate(queries)]+ )++ async def _aggregate_retrieval_results(+ self,+ *,+ retrievals: list[dict[str, Any]],+ stream: StreamBus,+ client: Any,+ ) -> str:+ sections: list[str] = []+ total_chars = 0+ for item in retrievals:+ answer = (item.get("answer") or "").strip()+ if not answer:+ continue+ clipped = answer[:MAX_CHARS_PER_RETRIEVAL]+ if total_chars + len(clipped) > MAX_AGGREGATE_INPUT_CHARS:+ clipped = clipped[: max(0, MAX_AGGREGATE_INPUT_CHARS - total_chars)]+ if clipped:+ sections.append(f"=== Source: {item.get('query', '?')} ===\n{clipped}")+ total_chars += len(clipped)+ if not sections:+ return self._t("empty.no_kb_retrieved")+ raw_text = "\n\n".join(sections)++ system_prompt = self._t("pre_retrieve.aggregate.system")+ user_prompt = self._t(+ "pre_retrieve.aggregate.user_template",+ raw_retrieval_text=raw_text,+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ iter_meta = self._build_simple_trace_meta(+ call_id_root="solve-aggregate",+ label=self._t("labels.aggregate", default="Aggregate knowledge"),+ stage="planning",+ call_kind="llm_planning",+ trace_role="plan",+ trace_group="plan",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_SUMMARY,+ stream=stream,+ stage="planning",+ iter_meta=iter_meta,+ max_tokens=PRE_RETRIEVE_MAX_TOKENS,+ )+ return step.text.strip() or raw_text++ # ------------------------------------------------------------------+ # Phase 1: plan+ # ------------------------------------------------------------------+ async def _plan(+ self,+ *,+ question: str,+ retrieved_context: str,+ memory_context: str,+ conversation_context: str,+ replan_reason: str | None,+ previous_attempt: list[StepFinish],+ attempt_index: int,+ image_attachments: list[Attachment],+ stream: StreamBus,+ client: Any,+ ) -> Plan:+ system_prompt = self._t("plan.system")+ user_prompt = self._t(+ "plan.user_template",+ question=question,+ retrieved_context=retrieved_context or self._t("empty.no_kb_retrieved"),+ memory_context=memory_context or self._t("empty.no_memory"),+ conversation_context=conversation_context or self._t("empty.no_conversation"),+ previous_attempt=self._render_step_finishes(previous_attempt)+ if previous_attempt+ else self._t("empty.no_previous_attempt"),+ replan_reason=(replan_reason or "").strip()+ or self._t("empty.no_previous_attempt"),+ )+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )+ is_replan = replan_reason is not None+ label = self._t(+ "labels.replan" if is_replan else "labels.plan",+ default="Replan" if is_replan else "Plan",+ )+ # ``call_kind=llm_planning`` + ``trace_role=plan`` is what the+ # frontend's TracePanels.tsx renders as the "Plan / 计划" card; the+ # default ``llm_reasoning`` / ``thought`` pair would show "Thought /+ # 思考" which misreads the phase.+ iter_meta = self._build_simple_trace_meta(+ call_id_root=f"solve-plan-{attempt_index}",+ label=label,+ stage="planning",+ call_kind="llm_planning",+ trace_role="plan",+ trace_group="plan",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_PLAN,+ stream=stream,+ stage="planning",+ iter_meta=iter_meta,+ max_tokens=PRE_RETRIEVE_MAX_TOKENS,+ )+ return self._parse_plan(step.text)++ def _parse_plan(self, raw: str) -> Plan:+ data = parse_json_response(raw, logger_instance=logger, fallback={})+ if not isinstance(data, dict) or not data:+ return Plan(+ analysis="Failed to parse plan; using single-step fallback.",+ steps=[PlanStep(id="S1", goal="Answer the question directly")],+ )+ analysis = str(data.get("analysis", "") or "")+ steps: list[PlanStep] = []+ for i, raw_step in enumerate(data.get("steps") or []):+ if not isinstance(raw_step, dict):+ continue+ step_id = str(raw_step.get("id") or f"S{i + 1}").strip() or f"S{i + 1}"+ goal = str(raw_step.get("goal") or "").strip()+ if not goal:+ continue+ steps.append(PlanStep(id=step_id, goal=goal))+ if not steps:+ steps = [PlanStep(id="S1", goal="Answer the question")]+ return Plan(analysis=analysis, steps=steps)++ # ------------------------------------------------------------------+ # Phase 2: solve one step+ # ------------------------------------------------------------------+ async def _solve_step(+ self,+ *,+ step: PlanStep,+ step_index: int,+ total_steps: int,+ plan: Plan,+ question: str,+ retrieved_context: str,+ previous_finishes: list[StepFinish],+ memory_context: str,+ conversation_context: str,+ image_attachments: list[Attachment],+ context: UnifiedContext,+ stream: StreamBus,+ client: Any,+ ) -> LoopOutcome:+ tool_schemas = self._build_llm_tool_schemas() if self._use_native_tools() else None+ system_prompt = self._build_step_system_prompt(+ step=step,+ step_index=step_index,+ total_steps=total_steps,+ )+ user_prompt = self._t(+ "solve_step.user_template",+ question=question,+ plan_summary=self._render_plan_summary(plan),+ step_id=step.id,+ step_goal=step.goal,+ previous_finishes=self._render_step_finishes(previous_finishes)+ if previous_finishes+ else self._t("empty.no_step_sections"),+ memory_context=memory_context or self._t("empty.no_memory"),+ conversation_context=conversation_context or self._t("empty.no_conversation"),+ )+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )++ host = _StepLoopHost(+ pipeline=self,+ step=step,+ stream=stream,+ context=context,+ client=client,+ )+ return await run_agentic_loop(+ initial_messages=messages,+ protocol=_PROTOCOL_STEP,+ client=client,+ model=self.model,+ completion_kwargs=self._completion_kwargs(DEFAULT_MAX_TOKENS),+ binding=self.binding,+ tool_schemas=tool_schemas,+ stream=stream,+ source=SOURCE,+ stage="reasoning",+ max_iterations=self.max_iterations_per_step,+ host=host,+ usage=self.usage,+ stream_body_live=True,+ eager_sub_trace=True,+ )++ def _build_step_system_prompt(+ self,+ *,+ step: PlanStep,+ step_index: int,+ total_steps: int,+ ) -> str:+ tone_key = self._tone_key(step_index, total_steps)+ tone_guidance = self._t(f"solve_step.tone.{tone_key}")+ tool_list = self.registry.build_prompt_text(+ self._resolved_tools(),+ format="list_with_usage",+ language=self.language,+ ) or self._fallback_empty_tool_list()+ kb_note = self._kb_system_note()+ system = self._t(+ "solve_step.system",+ step_index_human=step_index + 1,+ total_steps=total_steps,+ tone_guidance=tone_guidance,+ kb_note=kb_note,+ tool_list=tool_list,+ )+ return append_language_directive(system, self.language)++ @staticmethod+ def _tone_key(step_index: int, total_steps: int) -> str:+ if total_steps <= 1:+ return "only"+ if step_index == 0:+ return "first"+ if step_index == total_steps - 1:+ return "last"+ return "middle"++ # ------------------------------------------------------------------+ # Forced-finish per step (host hook for max-iter exhaustion)+ # ------------------------------------------------------------------+ async def _force_finish_step(+ self,+ *,+ client: Any,+ messages: list[dict[str, Any]],+ stream: StreamBus,+ start_iteration: int,+ step: PlanStep,+ ) -> tuple[str, bool, int]:+ calls = 0+ messages.append({"role": "user", "content": self._t("protocol.force_finish")})+ await stream.progress(+ self._t("notices.max_iterations_reached"),+ source=SOURCE,+ stage="reasoning",+ metadata={"trace_kind": "warning"},+ )+ for attempt in range(FINALIZATION_REPAIR_ATTEMPTS):+ iter_meta = self._build_simple_trace_meta(+ call_id_root=f"solve-{step.id}-force-{start_iteration + attempt}",+ label=self._t("labels.reasoning", default="Reasoning"),+ stage="reasoning",+ step_id=step.id,+ )+ step_result = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=LabelProtocol(+ allowed=(LABEL_FINISH,),+ terminal=frozenset({LABEL_FINISH}),+ intermediate=frozenset(),+ final=frozenset({LABEL_FINISH}),+ tool_label=None,+ ),+ stream=stream,+ stage="reasoning",+ iter_meta=iter_meta,+ )+ calls += 1+ if step_result.label == LABEL_FINISH and not find_inline_labels(+ step_result.text, allowed_labels=_PROTOCOL_STEP.allowed+ ):+ final_meta = build_trace_metadata(+ call_id=new_call_id(f"solve-{step.id}-final"),+ phase="reasoning",+ label=self._t("labels.solve_step", default="Solve step") + f" {step.id}",+ call_kind="llm_final_response",+ trace_id=f"solve-{step.id}-final",+ trace_role="response",+ trace_group="stage",+ step_id=step.id,+ )+ await self._emit_step_final(stream, step_result.text, final_meta)+ return step_result.text, True, calls+ messages.append({"role": "assistant", "content": step_result.text[:500]})+ messages.append(+ {"role": "user", "content": self._t("protocol.force_finish_repair")}+ )+ return self._t("protocol.fallback_final"), False, calls++ async def _emit_step_final(+ self,+ stream: StreamBus,+ text: str,+ final_meta: dict[str, Any],+ ) -> None:+ if not text:+ return+ await stream.content(+ text,+ source=SOURCE,+ stage="reasoning",+ metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_output"}),+ )++ async def _emit_section_break(self, stream: StreamBus) -> None:+ """Emit a blank-line content event between live-streamed sections.++ Without this, the next section's first streamed chunk concatenates+ directly onto the previous section's last chunk in the chat bubble+ — a leading ``##`` would render as inline text instead of a heading,+ and consecutive paragraphs would collapse into one. Emitted after+ every step FINISH (before the explain triage) and after every+ deep-explain expansion.++ ``section_break: True`` rides on the metadata so the frontend (and+ tests) can distinguish this housekeeping event from real model+ output.+ """+ break_id = new_call_id("solve-section-break")+ meta = build_trace_metadata(+ call_id=break_id,+ phase="reasoning",+ label="",+ call_kind="llm_final_response",+ trace_id=break_id,+ trace_role="response",+ trace_group="stage",+ )+ await stream.content(+ "\n\n",+ source=SOURCE,+ stage="reasoning",+ metadata=merge_trace_metadata(+ meta, {"trace_kind": "llm_output", "section_break": True}+ ),+ )++ # ------------------------------------------------------------------+ # Phase 2.5: explain judge + deep explain+ # ------------------------------------------------------------------+ async def _maybe_explain_step(+ self,+ *,+ step: PlanStep,+ question: str,+ finish_text: str,+ image_attachments: list[Attachment],+ stream: StreamBus,+ client: Any,+ ) -> str:+ """After a step's FINISH content has streamed, decide whether to+ append a deeper explanation, and if so stream it live under the+ FINISH section. Returns the explain text (empty when SKIPped or+ when something fails)."""+ if not finish_text:+ return ""+ try:+ should_explain, explain_focus = await self._judge_explain(+ step=step,+ question=question,+ finish_text=finish_text,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )+ except Exception as exc:+ logger.warning("Explain triage failed for step %s: %s", step.id, exc)+ return ""+ if not should_explain:+ return ""+ try:+ return await self._run_explain(+ step=step,+ question=question,+ finish_text=finish_text,+ explain_focus=explain_focus,+ image_attachments=image_attachments,+ stream=stream,+ client=client,+ )+ except Exception as exc:+ logger.warning("Deep explain failed for step %s: %s", step.id, exc)+ return ""++ async def _judge_explain(+ self,+ *,+ step: PlanStep,+ question: str,+ finish_text: str,+ image_attachments: list[Attachment],+ stream: StreamBus,+ client: Any,+ ) -> tuple[bool, str]:+ """Run the triage LLM call. Returns ``(should_explain, focus)``;+ ``focus`` is a one-sentence hint of what to deepen, empty when+ the triage says SKIP."""+ system_prompt = self._t("explain_judge.system")+ user_prompt = self._t(+ "explain_judge.user_template",+ question=question,+ step_id=step.id,+ step_goal=step.goal,+ finish_text=finish_text,+ )+ if not system_prompt or not user_prompt:+ return False, ""+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )+ iter_meta = self._build_simple_trace_meta(+ call_id_root=f"solve-{step.id}-explain-judge",+ label=self._t("labels.explain_judge", default="Explain check"),+ stage="reasoning",+ call_kind="llm_planning",+ trace_role="plan",+ trace_group="stage",+ step_id=step.id,+ )+ result = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_EXPLAIN_JUDGE,+ stream=stream,+ stage="reasoning",+ iter_meta=iter_meta,+ max_tokens=EXPLAIN_JUDGE_MAX_TOKENS,+ )+ if result.label == LABEL_EXPLAIN:+ focus = result.text.strip()+ return True, focus+ # SKIP or LABEL_UNKNOWN both fall back to "no explanation" so a+ # protocol miss never adds dubious content under the step.+ return False, ""++ async def _run_explain(+ self,+ *,+ step: PlanStep,+ question: str,+ finish_text: str,+ explain_focus: str,+ image_attachments: list[Attachment],+ stream: StreamBus,+ client: Any,+ ) -> str:+ """Stream a deeper explanation directly under the step's FINISH+ content. Returns the explain text so the caller can fold it into+ ``StepFinish.text`` for downstream context + final-response join."""+ system_prompt = self._t("explain.system")+ user_prompt = self._t(+ "explain.user_template",+ question=question,+ step_id=step.id,+ step_goal=step.goal,+ finish_text=finish_text,+ explain_focus=explain_focus+ or self._t("empty.no_explain_focus", default="(no specific focus — pick the most useful angle)"),+ )+ if not system_prompt or not user_prompt:+ return ""+ messages = self._build_system_user_messages(+ system_prompt, user_prompt, image_attachments=image_attachments+ )+ iter_meta = self._build_simple_trace_meta(+ call_id_root=f"solve-{step.id}-explain",+ label=self._t("labels.explain", default="Deep explain"),+ stage="reasoning",+ call_kind="llm_final_response",+ trace_role="response",+ trace_group="stage",+ step_id=step.id,+ )+ final_call_id = new_call_id(f"solve-{step.id}-explain-final")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase="reasoning",+ label=self._t("labels.explain", default="Deep explain"),+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ step_id=step.id,+ )+ # Wrap the deep-explain section in a default-open <details> block so+ # the user can fold it away once they've absorbed the FINISH content.+ # The opening + closing tags are emitted as their own content events+ # (so the live stream sees them in order with the LLM body in between)+ # AND folded into the returned text (so the persisted response /+ # downstream synthesize input keeps the same collapsible structure).+ summary_label = self._t("labels.explain_summary", default="Deep explanation")+ summary_text = (+ f"{summary_label}: {explain_focus}" if explain_focus else summary_label+ )+ details_open = f"<details open>\n<summary>{summary_text}</summary>\n\n"+ details_close = "\n\n</details>"+ wrapper_meta = merge_trace_metadata(+ final_meta,+ {"trace_kind": "llm_output", "details_wrapper": True},+ )+ await stream.content(+ details_open,+ source=SOURCE,+ stage="reasoning",+ metadata=wrapper_meta,+ )+ result = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_EXPLAIN,+ stream=stream,+ stage="reasoning",+ iter_meta=iter_meta,+ max_tokens=EXPLAIN_MAX_TOKENS,+ final_meta=final_meta,+ )+ await stream.content(+ details_close,+ source=SOURCE,+ stage="reasoning",+ metadata=wrapper_meta,+ )+ # Section break so the next streamed section (next step's FINISH+ # or synthesize) starts on a fresh markdown block.+ await self._emit_section_break(stream)+ return f"{details_open}{result.text.strip()}{details_close}"++ # ------------------------------------------------------------------+ # Phase 3: synthesize+ # ------------------------------------------------------------------+ async def _synthesize(+ self,+ *,+ question: str,+ step_finishes: list[StepFinish],+ conversation_context: str,+ stream: StreamBus,+ client: Any,+ ) -> str:+ system_prompt = self._t("synthesize.system")+ user_prompt = self._t(+ "synthesize.user_template",+ question=question,+ step_finishes=self._render_step_finishes(step_finishes)+ if step_finishes+ else self._t("empty.no_step_sections"),+ conversation_context=conversation_context or self._t("empty.no_conversation"),+ )+ messages = self._build_system_user_messages(system_prompt, user_prompt)+ # Two metadata bundles: ``iter_meta`` would scope a reasoning+ # sub-trace card (synthesize doesn't open one — its label is in+ # ``final_labels``), and ``final_meta`` scopes the body content+ # so the chat bubble streams chunk-by-chunk via+ # :func:`run_labeled_step` (``stream_body_live`` semantics).+ synth_label = self._t("labels.synthesize", default="Synthesize")+ iter_meta = self._build_simple_trace_meta(+ call_id_root="solve-synthesize",+ label=synth_label,+ stage="writing",+ call_kind="llm_final_response",+ trace_role="response",+ trace_group="stage",+ )+ final_call_id = new_call_id("solve-synthesize-final")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase="writing",+ label=synth_label,+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ )+ step = await self._run_labeled_step(+ client=client,+ messages=messages,+ tool_schemas=None,+ protocol=_PROTOCOL_SYNTHESIZE,+ stream=stream,+ stage="writing",+ iter_meta=iter_meta,+ max_tokens=SYNTHESIZE_MAX_TOKENS,+ final_meta=final_meta,+ )+ return step.text.strip()++ # ------------------------------------------------------------------+ # Tool integration (mirrors chat's pattern)+ # ------------------------------------------------------------------+ def _resolved_tools(self) -> list[str]:+ """Filter the user's enabled_tools by what the registry actually has,+ and ensure ``rag`` is mounted when a KB is attached."""+ resolved: list[str] = []+ for tool in self.registry.get_enabled(self.enabled_tools):+ if tool.name in resolved:+ continue+ resolved.append(tool.name)+ if self.kb_name and self._tool_in_registry("rag") and "rag" not in resolved:+ resolved.append("rag")+ return resolved++ def _build_llm_tool_schemas(self) -> list[dict[str, Any]]:+ schemas = self.registry.build_openai_schemas(self._resolved_tools())+ kb_choices = [self.kb_name] if self.kb_name else []+ for schema in schemas:+ function = schema.get("function") if isinstance(schema, dict) else None+ if not isinstance(function, dict):+ continue+ parameters = function.get("parameters")+ if not isinstance(parameters, dict):+ continue+ properties = parameters.get("properties") or {}+ if function.get("name") == "rag" and isinstance(properties, dict):+ if isinstance(properties.get("query"), dict):+ properties["query"].setdefault("minLength", 1)+ kb_schema = properties.get("kb_name")+ if isinstance(kb_schema, dict) and kb_choices:+ kb_schema["enum"] = kb_choices+ parameters["additionalProperties"] = False+ return schemas++ def _augment_tool_kwargs(+ self,+ tool_name: str,+ args: dict[str, Any],+ context: UnifiedContext,+ ) -> dict[str, Any]:+ kwargs = dict(args)+ turn_id = str(context.metadata.get("turn_id", "") or "").strip()+ task_dir = None+ if turn_id:+ task_dir = get_path_service().get_task_workspace("deep_solve", turn_id)+ if tool_name == "rag":+ kwargs.setdefault("mode", "hybrid")+ if self.kb_name:+ kwargs.setdefault("kb_name", self.kb_name)+ elif tool_name == "code_execution":+ kwargs.setdefault("intent", context.user_message)+ kwargs.setdefault("timeout", 30)+ kwargs.setdefault("feature", "deep_solve")+ kwargs.setdefault("session_id", context.session_id)+ kwargs.setdefault("turn_id", turn_id)+ if task_dir is not None:+ kwargs.setdefault("workspace_dir", str(task_dir / "code_runs"))+ elif tool_name in {"reason", "brainstorm"}:+ kwargs.setdefault("context", context.user_message)+ elif tool_name == "web_search":+ kwargs.setdefault("query", context.user_message)+ if task_dir is not None:+ kwargs.setdefault("output_dir", str(task_dir / "web_search"))+ return kwargs++ def _retrieve_trace_metadata(+ self,+ tool_meta: dict[str, Any],+ *,+ tool_name: str,+ tool_args: dict[str, Any],+ ) -> dict[str, Any] | None:+ if tool_name != "rag":+ return None+ return derive_trace_metadata(+ tool_meta,+ label=self._t("labels.retrieve", default="Retrieve"),+ call_kind="rag_retrieval",+ trace_role="retrieve",+ trace_group="retrieve",+ query=str(tool_args.get("query", "") or ""),+ )++ def _use_native_tools(self) -> bool:+ return bool(self._resolved_tools()) and can_use_native_tool_calling(+ binding=self.binding, model=self.model+ )++ def _tool_in_registry(self, name: str) -> bool:+ try:+ return self.registry.get(name) is not None+ except Exception:+ return False++ # ------------------------------------------------------------------+ # LLM call helpers+ # ------------------------------------------------------------------+ def _build_client(self) -> Any:+ return build_openai_client(self.client_config)++ def _completion_kwargs(self, max_tokens: int) -> dict[str, Any]:+ return build_completion_kwargs(+ temperature=self._temperature,+ model=self.model,+ max_tokens=max_tokens,+ )++ async def _run_labeled_step(+ self,+ *,+ client: Any,+ messages: list[dict[str, Any]],+ tool_schemas: list[dict[str, Any]] | None,+ protocol: LabelProtocol,+ stream: StreamBus,+ stage: str,+ iter_meta: dict[str, Any],+ max_tokens: int = DEFAULT_MAX_TOKENS,+ final_meta: dict[str, Any] | None = None,+ eager_sub_trace: bool = True,+ ) -> LabeledStepResult:+ """Solve-flavored thin wrapper over :func:`run_labeled_step`.++ Pass ``final_meta`` (a trace-metadata dict) to make a final-label+ body stream chunk-by-chunk into ``stream.content``. This is how+ :meth:`_synthesize` makes its ``FINISH`` answer feel typewriter-y+ instead of slamming the whole text into the bubble at once.++ ``eager_sub_trace`` defaults to ``True`` for solve so each phase's+ trace card appears immediately when the LLM call begins, closing+ the visual gap during time-to-first-token between calls.+ """+ return await run_labeled_step(+ client=client,+ model=self.model,+ messages=messages,+ completion_kwargs=self._completion_kwargs(max_tokens),+ tool_schemas=tool_schemas,+ allowed_labels=protocol.allowed,+ final_labels=protocol.final,+ tool_label=protocol.tool_label,+ stream=stream,+ source=SOURCE,+ stage=stage,+ iter_meta=iter_meta,+ binding=self.binding,+ usage=self.usage,+ final_meta=final_meta,+ eager_sub_trace=eager_sub_trace,+ )++ # ------------------------------------------------------------------+ # Message + trace assembly+ # ------------------------------------------------------------------+ def _build_system_user_messages(+ self,+ system_prompt: str,+ user_prompt: str,+ *,+ image_attachments: list[Attachment] | None = None,+ ) -> list[dict[str, Any]]:+ messages: list[dict[str, Any]] = [+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": user_prompt},+ ]+ if image_attachments:+ mm_result = prepare_multimodal_messages(+ messages, image_attachments, binding=self.binding, model=self.model+ )+ return mm_result.messages+ return messages++ def _build_simple_trace_meta(+ self,+ *,+ call_id_root: str,+ label: str,+ stage: str,+ call_kind: str = "llm_reasoning",+ trace_role: str = "thought",+ trace_group: str = "stage",+ **extra: Any,+ ) -> dict[str, Any]:+ """Construct trace metadata for a sub-trace card.++ ``call_kind`` + ``trace_role`` drive the frontend's panel title (see+ ``web/components/chat/home/TracePanels.tsx``). Defaults emit a generic+ "Reasoning / 思考" card; callers override for ``Plan``, ``Retrieve``,+ etc.+ """+ call_id = new_call_id(call_id_root)+ return build_trace_metadata(+ call_id=call_id,+ phase=stage,+ label=label,+ call_kind=call_kind,+ trace_id=call_id,+ trace_role=trace_role,+ trace_group=trace_group,+ **extra,+ )++ # ------------------------------------------------------------------+ # Rendering helpers+ # ------------------------------------------------------------------+ def _render_plan_summary(self, plan: Plan) -> str:+ if not plan.steps:+ return "(empty plan)"+ lines = []+ if plan.analysis:+ lines.append(f"Analysis: {plan.analysis}")+ for step in plan.steps:+ lines.append(f" - [{step.id}] {step.goal}")+ return "\n".join(lines)++ def _render_step_finishes(self, finishes: list[StepFinish]) -> str:+ if not finishes:+ return self._t("empty.no_step_sections")+ blocks = []+ for finish in finishes:+ blocks.append(f"### [{finish.step.id}] {finish.step.goal}\n\n{finish.text}")+ return "\n\n".join(blocks)++ def _compose_full_response(+ self,+ step_finishes: list[StepFinish],+ synthesis_text: str,+ ) -> str:+ """Join the step sections + synthesis into one string for the+ ``stream.result.response`` payload (the per-section content already+ streamed live as ``stream.content`` events)."""+ parts = [finish.text.strip() for finish in step_finishes if finish.text.strip()]+ synthesis = (synthesis_text or "").strip()+ if synthesis:+ parts.append(synthesis)+ return "\n\n".join(parts)++ def _kb_system_note(self) -> str:+ if not self.kb_name:+ return ""+ if self.language == "zh":+ return f"用户已挂载知识库:{self.kb_name}。调用 rag 时,kb_name 必须填这个名称。"+ return (+ f"Attached knowledge bases: {self.kb_name}. When calling rag, kb_name "+ f"must be {self.kb_name!r}."+ )++ def _fallback_empty_tool_list(self) -> str:+ return "- 无" if self.language == "zh" else "- none"++ # ------------------------------------------------------------------+ # YAML lookup+ # ------------------------------------------------------------------+ def _t(self, key: str, default: str = "", **kwargs: Any) -> str:+ """Look up a YAML-loaded prompt by dotted key (same contract as the+ chat pipeline's ``_t``)."""+ value: Any = self._prompts+ for part in key.split("."):+ if not isinstance(value, dict) or part not in value:+ return default+ value = value[part]+ if not isinstance(value, str):+ return default+ if kwargs:+ try:+ return value.format(**kwargs)+ except (KeyError, IndexError, ValueError):+ return value+ return value+++# ---------------------------------------------------------------------------+# Per-step LoopHost+# ---------------------------------------------------------------------------+++class _StepLoopHost:+ """Binds a ``SolvePipeline`` + current step + stream/context/client so the+ generic loop primitive can call back for chat-style hooks scoped to one+ solve step."""++ def __init__(+ self,+ *,+ pipeline: SolvePipeline,+ step: PlanStep,+ stream: StreamBus,+ context: UnifiedContext,+ client: Any,+ ) -> None:+ self._pipeline = pipeline+ self._step = step+ self._stream = stream+ self._context = context+ self._client = client++ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:+ # Solve doesn't run its own context-window guard for v1 — each step's+ # loop is bounded by ``max_iterations_per_step`` and the messages+ # buffer is reset per step, so it never grows like chat's.+ return++ def build_iteration_trace_meta(+ self, iteration: int+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ iter_call_id = new_call_id(f"solve-{self._step.id}-iter-{iteration}")+ iter_meta = build_trace_metadata(+ call_id=iter_call_id,+ phase="reasoning",+ label=self._pipeline._t("labels.reasoning", default="Reasoning"),+ call_kind="llm_reasoning",+ trace_id=iter_call_id,+ trace_role="thought",+ trace_group="stage",+ step_id=self._step.id,+ )+ final_call_id = new_call_id(f"solve-{self._step.id}-final")+ final_meta = build_trace_metadata(+ call_id=final_call_id,+ phase="reasoning",+ label=f"{self._pipeline._t('labels.solve_step', default='Solve step')} {self._step.id}",+ call_kind="llm_final_response",+ trace_id=final_call_id,+ trace_role="response",+ trace_group="stage",+ step_id=self._step.id,+ )+ return iter_meta, final_meta++ async def dispatch_tools(+ self,+ *,+ iteration: int,+ tool_calls: list[dict[str, Any]],+ ) -> DispatchOutcome:+ too_many = None+ if len(tool_calls) > MAX_PARALLEL_TOOL_CALLS:+ too_many = self._pipeline._t(+ "notices.too_many_tool_calls",+ requested=len(tool_calls),+ limit=MAX_PARALLEL_TOOL_CALLS,+ )+ return await dispatch_tool_calls(+ tool_calls=tool_calls,+ context=self._context,+ stream=self._stream,+ source=SOURCE,+ stage="reasoning",+ iteration_index=iteration,+ registry=self._pipeline.registry,+ kwarg_augmenter=self._pipeline._augment_tool_kwargs,+ retrieve_meta_factory=lambda meta, tn, ta: self._pipeline._retrieve_trace_metadata(+ meta, tool_name=tn, tool_args=ta+ ),+ tool_call_label=self._pipeline._t("labels.tool_call", default="Tool call"),+ retrieve_label=self._pipeline._t("labels.retrieve", default="Retrieve"),+ empty_tool_result_message=self._pipeline._t("notices.empty_tool_result"),+ start_retrieval_message=self._pipeline._t(+ "notices.start_retrieval", default="Starting retrieval"+ ),+ too_many_tool_calls_message=too_many,+ unknown_error_message_factory=lambda tn: self._pipeline._t(+ "notices.tool_unknown_error",+ tool=tn,+ default=f"Error executing {tn}.",+ ),+ trace_id_prefix=f"solve-{self._step.id}-iter",+ )++ async def resolve_pause(self, dispatch: DispatchOutcome) -> bool:+ # Solve does not currently surface ask_user. If a tool ever requests+ # pause we fall through to terminate so the turn cleanly closes.+ return False++ async def emit_terminator(self, payload: dict[str, Any] | None) -> None:+ if not payload:+ return+ content = str(payload.get("content") or "").strip()+ if not content:+ return+ final_meta = build_trace_metadata(+ call_id=new_call_id(f"solve-{self._step.id}-final"),+ phase="reasoning",+ label=f"{self._pipeline._t('labels.solve_step', default='Solve step')} {self._step.id}",+ call_kind="llm_final_response",+ trace_id=f"solve-{self._step.id}-final",+ trace_role="response",+ trace_group="stage",+ step_id=self._step.id,+ )+ await self._stream.content(+ content,+ source=SOURCE,+ stage="reasoning",+ metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_output"}),+ )++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ await self._pipeline._emit_step_final(self._stream, text, final_meta)++ def assistant_message_with_tool_calls(+ self,+ *,+ content: str,+ tool_calls: list[dict[str, Any]],+ ) -> dict[str, Any]:+ return {+ "role": "assistant",+ "content": content or None,+ "tool_calls": [+ {+ "id": tc["id"],+ "type": "function",+ "function": {+ "name": tc["name"],+ "arguments": tc.get("arguments") or "{}",+ },+ }+ for tc in tool_calls+ ],+ }++ def protocol_retry_notice(self) -> str:+ return self._pipeline._t(+ "notices.protocol_retry",+ default="The model violated the action-label protocol; retrying.",+ )++ def protocol_repair_message(self, violation: str) -> str:+ return self._pipeline._t(+ f"protocol.{violation}",+ default=f"Protocol violation: {violation}.",+ )++ async def force_finalize(+ self,+ *,+ messages: list[dict[str, Any]],+ start_iteration: int,+ ) -> tuple[str, bool, int]:+ return await self._pipeline._force_finish_step(+ client=self._client,+ messages=messages,+ stream=self._stream,+ start_iteration=start_iteration,+ step=self._step,+ )+++# Awaitable re-export so the host's force_finalize / dispatch_tools return+# types resolve cleanly when callers type-check this module in isolation.+_ = Awaitable # type: ignore[assignment]diff --git a/deeptutor/agents/solve/prompts/en/answer_now.yaml b/deeptutor/agents/solve/prompts/en/answer_now.yamldeleted file mode 100644index b2e25269a..000000000--- a/deeptutor/agents/solve/prompts/en/answer_now.yaml+++ /dev/null@@ -1,17 +0,0 @@-system: |- You are the writer component of DeepTutor. The user is already waiting,- so produce the final user-facing answer right now using only the partial- reasoning trace that has streamed so far. Do not plan further or call- tools, and do not mention internal stages. If something is still- uncertain, acknowledge it briefly while still giving the most useful- answer you can.--user_template: |- Original user request:- {original}-- {current_draft}-- {execution_trace}-- Produce the final user-facing answer using only this context.diff --git a/deeptutor/agents/solve/prompts/en/pipeline.yaml b/deeptutor/agents/solve/prompts/en/pipeline.yamlnew file mode 100644index 000000000..234c3d2f3--- /dev/null+++ b/deeptutor/agents/solve/prompts/en/pipeline.yaml@@ -0,0 +1,320 @@+# SolvePipeline prompts (English)+#+# One YAML file owns the protocol for every LLM call solve makes:+# * pre_retrieve.gen_queries — emit ``QUERIES`` + JSON list+# * pre_retrieve.aggregate — emit ``SUMMARY`` + consolidated notes+# * plan — emit ``PLAN`` + JSON {analysis, steps[]}+# * solve_step — agentic loop with ``THINK`` / ``TOOL`` /+# ``FINISH`` / ``REPLAN``+# * synthesize — emit ``FINISH`` + precise answer + summary+#+# Loaded via PromptManager as module="solve", agent_name="pipeline".++# ---------------------------------------------------------------------------+# Trace labels (UI rows in CallTracePanel)+# ---------------------------------------------------------------------------+labels:+ pre_retrieve: "Pre-retrieve"+ gen_queries: "Generate queries"+ aggregate: "Aggregate knowledge"+ retrieve: "Retrieve"+ plan: "Plan"+ replan: "Replan"+ solve_step: "Solve step"+ reasoning: "Reasoning"+ tool_call: "Tool call"+ synthesize: "Synthesize"+ answer_now: "Answer now"+ explain_judge: "Explain check"+ explain: "Deep explain"+ explain_summary: "Deep explanation"++# ---------------------------------------------------------------------------+# Phase 0: Pre-retrieve (only runs when a KB is attached)+# ---------------------------------------------------------------------------+pre_retrieve:+ gen_queries:+ system: |-+ You are a knowledge-base query planner.++ Reply MUST begin with the protocol label ``QUERIES`` on the very first line, wrapped in two backticks on each side. After the label, output exactly one JSON array of strings — nothing else.++ Each query should target a different aspect of the user's question (definitions, formulas / theorems, examples, edge cases, etc.). Keep each query concise.+ user_template: |-+ Generate {num_queries} concise, diverse knowledge-base search queries for the following question.++ Question: {question}++ aggregate:+ system: |-+ You are a knowledge organizer.++ Reply MUST begin with ``SUMMARY``. After the label, write a single structured knowledge summary based on the supplied passages.++ Rules:+ - Remove duplicated information across passages.+ - Organize by topic (definitions, formulas / theorems, key facts, examples).+ - Do NOT solve any problem or infer beyond what the passages state.+ - Do NOT reference any question — just organize the raw knowledge.+ - Keep the summary under 3000 characters.+ user_template: |-+ Below are several passages retrieved from a knowledge base. Consolidate them.++ {raw_retrieval_text}++# ---------------------------------------------------------------------------+# Phase 1: Plan (also re-entered on REPLAN — Phase 2 hands back the reason)+# ---------------------------------------------------------------------------+plan:+ system: |-+ You are a Problem-Solving Planner. Your job is to decompose the user's question into ordered solving steps.++ Reply MUST begin with ``PLAN`` on the very first line. After the label, output exactly one JSON object of the form:++ {{"analysis": "brief framing of what the problem asks for", "steps": [{{"id": "S1", "goal": "..."}}, {{"id": "S2", "goal": "..."}}]}}++ Rules:+ 1. Each step is a **verifiable sub-goal** — describe WHAT needs to be established or answered, NOT HOW. Do not mention tools.+ 2. Keep the plan minimal but sufficient:+ - Simple factual question → 1 step.+ - Multi-part analytical question → 2–4 steps.+ - Complex derivation / multi-hop problem → 3–6 steps.+ 3. Step ids follow the pattern S1, S2, S3, ...+ 4. If a "Replan reason" section is present, the previous plan failed. Address the reason directly. You may keep useful step goals from the previous attempt or introduce new ones — the previous step results stay available as context for the new plan.+ 5. If retrieved knowledge is provided, use it to make a more informed plan.+ user_template: |-+ ## Question+ {question}++ ## Retrieved knowledge+ {retrieved_context}++ ## Memory context+ {memory_context}++ ## Conversation context+ {conversation_context}++ ## Previous attempt (only present on replan)+ {previous_attempt}++ ## Replan reason (only present on replan)+ {replan_reason}++# ---------------------------------------------------------------------------+# Phase 2: Solve step (agentic loop, one call per iteration)+# ---------------------------------------------------------------------------+solve_step:+ system: |-+ You are solving step {step_index_human} of {total_steps} in a multi-step problem.++ # Output protocol (mandatory — every reply must comply)++ Every reply MUST begin with exactly one of these four labels on the very first line, all-caps, wrapped with two backticks on each side:++ ``THINK`` → Intermediate reasoning. No tools. After the label, write your reasoning. The loop continues, and the next iteration can build on this.+ ``TOOL`` → You need a tool. After the label, write one short sentence of intent, then emit native tool_calls in the same reply.+ ``FINISH`` → This step is done. After the label, write **the user-facing section of the final answer that corresponds to this step**. Do NOT call tools.+ ``REPLAN`` → The current plan is no longer appropriate. After the label, write **only the reason** the current plan is wrong (do NOT write a new plan; the planner will revise based on your reason). Do NOT call tools.++ The runtime treats ``FINISH`` and ``REPLAN`` as terminal for this step. ``THINK`` and tool results keep the loop alive.++ One LLM reply chooses **exactly one** action label. Do not include a second protocol label anywhere in the body. ``THINK``, ``FINISH``, and ``REPLAN`` must NOT emit tool_calls.++ # Writing the FINISH content++ Each step's ``FINISH`` text is concatenated into the final user-facing answer. Write it as a coherent section, and make the section itself **substantive** — don't merely state, develop the idea: give intuition, walk through formulas, show concrete examples and sub-cases when they exist.++ **Mandatory format:** your FINISH content MUST begin with a single H2 heading on the first line of the form:++ ## Step {step_index_human}: <concise topic of this step>++ Pick a short, descriptive topic (5–10 words) for ``<concise topic>``. **Do not** prefix the heading with a transitional phrase ("Let's first…", "Next…", "Now, putting it together…") — the heading itself is the section anchor. After the heading line, leave a blank line, then write the section body.++ {tone_guidance}++ Cite retrieved passages inline as [source-id] when you use them.++ Use the full markdown affordances when they genuinely improve clarity (**only when they help — do not force them**):+ - **Headings**: ``## H2`` and ``### H3`` are appropriate for structuring a substantive FINISH section. Do **not** use ``#`` (H1) — that level is reserved for the chat answer's top container.+ - **Tables** for comparisons, parameter listings, before/after.+ - **LaTeX** for math: inline $...$ and block $$...$$.+ - **Bullet / numbered lists** for enumerations.+ - **Mermaid blocks** (use a ```mermaid code fence) when a diagram clarifies a flow, sequence, or relationship.+ - **Callouts** (`> **Note:** ...`, `> **Warning:** ...`) for important asides.+ - **Bold / italic** for key terms; **inline code** for symbols / identifiers.++ # Per-iteration reasoning++ 1. If you already have enough information for this step, close with ``FINISH``.+ 2. If you need external info / computation / retrieval, use ``TOOL`` with real tool_calls.+ 3. If you want to think out loud before acting, use ``THINK``.+ 4. If you genuinely believe the plan is wrong (e.g., a missing step, a wrong assumption upstream), use ``REPLAN`` with a clear reason.++ Hard rules for tool calls:+ - Copy tool names, parameter names, and KB names verbatim from the "Enabled tools" / "Knowledge bases" blocks. Never invent.+ - Arguments must be concrete and executable; empty queries are invalid.++ {kb_note}+ Enabled tools:+ {tool_list}+ user_template: |-+ ## Original question+ {question}++ ## Full plan+ {plan_summary}++ ## Current step+ [{step_id}] {step_goal}++ ## Sections already written for previous steps+ {previous_finishes}++ ## Memory context+ {memory_context}++ ## Conversation context+ {conversation_context}++ Begin reasoning for step {step_id}.++ # Tone guidance is selected by the orchestrator per step position and+ # injected into the system prompt above as ``{tone_guidance}``. The step+ # heading is now the section anchor, so tone no longer dictates opening+ # phrases — it just steers how the body closes (forward-looking vs final).+ tone:+ only: |-+ This is the **only step** of the answer. After the heading, write a complete, self-contained section that frames the problem briefly and lands the take-away at the end.+ first: |-+ This is the **first step**. After the heading, develop the section substantively. **Do not** include closing remarks — more steps follow.+ middle: |-+ This is a **middle step**. After the heading, develop the section substantively. **Do not** include closing remarks — more steps follow.+ last: |-+ This is the **final step**. After the heading, develop the section substantively. You may end with a brief one-sentence close; a short synthesize section will follow.++# ---------------------------------------------------------------------------+# Phase 2.5: Explain judge + Deep explain (optional, runs after each step's+# FINISH content has already streamed to the user)+# ---------------------------------------------------------------------------+explain_judge:+ system: |-+ You are a triage step deciding whether the just-finished step section needs a deeper explanation expansion below it.++ Reply MUST begin with one of two labels on the very first line, wrapped in two backticks on each side:++ ``EXPLAIN`` → the section uses non-trivial concepts, derivations, formulas, edge cases, or intuition that the user would genuinely benefit from unpacking more deeply. After the label, write **one short sentence** naming what to deepen (e.g., "the intuition behind the conservation law", "why this inequality is tight", "how the recursion bottoms out").+ ``SKIP`` → the section is already self-explanatory for an attentive reader, or further explanation would just repeat what is already on screen. After the label, write nothing.++ **Be conservative**: default to ``SKIP`` unless there is real pedagogical value in expanding (a concept worth unpacking, an intuition worth surfacing, a non-obvious step worth justifying). **Do not** ``EXPLAIN`` just because the section is short, and do not ``EXPLAIN`` just because the topic is complex — only when an expansion would actually help the user understand.+ user_template: |-+ ## Original question+ {question}++ ## Current step+ [{step_id}] {step_goal}++ ## Section the user just saw+ {finish_text}++explain:+ system: |-+ You are writing a deeper explanation expansion that will be streamed immediately under the step's section above. The user has already seen the section; your job is to unpack the underlying concepts, derivations, or intuition **more deeply and more thoroughly** than the section did.++ Reply MUST begin with ``FINISH`` on the very first line, wrapped in two backticks on each side. After the label, write the deeper explanation.++ The expansion should:+ - Go **deeper than the section above** — explain *why* and *how*, not just restate *what*.+ - Add concrete grounding: worked sub-examples, special cases, common pitfalls, geometric / physical / algorithmic intuition.+ - **Not repeat** the section's claims verbatim — build on them, fill in gaps, surface the reasoning behind statements that were assumed, help the reader build a mental model.+ - Stay scoped to **this step**; do NOT start solving the next step.+ - Be richer than the FINISH section — you can be longer and more structured.++ Use the full markdown affordances when they genuinely improve clarity (**only when they help — do not force them**):+ - **Headings**: keep all subheadings at ``### H3`` or smaller (H4, H5). Do **not** use ``#`` (H1) or ``## H2`` — the FINISH section above already anchors at H2, and the deep-explain expansion must nest under it at H3 or deeper.+ - **Tables** for comparisons, parameter sweeps, before/after, special-case enumeration.+ - **LaTeX** for math: inline $...$ and block $$...$$.+ - **Bullet / numbered lists** for key points / sub-steps.+ - **Mermaid blocks** (use a ```mermaid code fence) when a diagram clarifies a flow, sequence, state machine, or relationship.+ - **Callouts** (`> **Note:** ...`, `> **Warning:** ...`, `> **Intuition:** ...`) for important asides.+ - **Bold / italic** for key terms; **inline code** for symbols / identifiers / formula fragments.+ user_template: |-+ ## Original question+ {question}++ ## Current step+ [{step_id}] {step_goal}++ ## Section the user just saw+ {finish_text}++ ## What to deepen (from triage)+ {explain_focus}++# ---------------------------------------------------------------------------+# Phase 3: Synthesize (single FINISH call after all steps are done)+# ---------------------------------------------------------------------------+synthesize:+ system: |-+ You are wrapping up a multi-step problem solution. The user has already seen each step's section streamed live; your job is to land the answer.++ Reply MUST begin with ``FINISH`` on the very first line. After the label, do (in order):++ 1. **Precise final answer** — if the original question asks for a specific value, choice, judgment, or short answer, give it directly in one sentence. If the question is open-ended (e.g., "explain"), skip this and go to (2).+ 2. **Brief overall recap** — one short paragraph summarizing the path through the steps. Keep it tight; the per-step sections are already on screen.++ Use Markdown. Math in LaTeX. No tool calls.+ user_template: |-+ ## Original question+ {question}++ ## Step-by-step sections already shown to the user+ {step_finishes}++ ## Conversation context+ {conversation_context}++# ---------------------------------------------------------------------------+# Protocol violation repair messages (host returns these to the loop)+# ---------------------------------------------------------------------------+protocol:+ missing_label: |-+ Protocol correction: your previous reply did not begin with a protocol label, so this iteration is not complete. Your next reply must choose exactly one action label, written once on the first line only: ``THINK``, ``TOOL``, ``FINISH``, or ``REPLAN``. Do not include a second protocol label anywhere in the body.+ multiple_labels: |-+ Protocol correction: your previous reply contained multiple protocol labels. Your next reply must use exactly one action label on the first line. Do not put a second label inside the body.+ tool_without_calls: |-+ Protocol correction: you chose ``TOOL`` but emitted no real tool_calls. Use ``TOOL`` only when you emit native tool_calls in that same reply; otherwise use ``THINK``, ``FINISH``, or ``REPLAN``.+ think_with_tools: |-+ Protocol correction: you chose ``THINK`` while emitting tool_calls. ``THINK`` is reasoning-only. Use ``TOOL`` if you need a tool, or ``THINK`` without tool_calls.+ finish_with_tools: |-+ Protocol correction: you chose ``FINISH`` while emitting tool_calls. ``FINISH`` ends the step with the user-facing section — no tools. Use ``TOOL`` first if you still need information.+ label_with_tools: |-+ Protocol correction: you chose ``REPLAN`` while emitting tool_calls. ``REPLAN`` is a planning signal — no tool calls. Use ``TOOL`` for retrieval, ``THINK`` for reasoning, or write the replan reason after ``REPLAN``.+ force_finish: |-+ The iteration budget for this step is exhausted. Now produce the user-facing section for the step: the first line must be ``FINISH``. Do not call tools, do not use ``THINK`` or ``REPLAN``. If information is still incomplete, state the uncertainty briefly while still writing the most useful section you can.+ force_finish_repair: |-+ Finalization protocol correction: the previous reply did not produce a valid ``FINISH``. Now output only a final section: first line ``FINISH``, then the user-facing content. Do not write ``THINK``, ``TOOL``, or ``REPLAN``; do not call tools.+ fallback_final: |-+ I reached the iteration limit for this step without a valid ``FINISH``. The step was closed without a complete section.++# ---------------------------------------------------------------------------+# Notices (warnings emitted into the trace stream)+# ---------------------------------------------------------------------------+notices:+ start_retrieval: "Starting retrieval"+ empty_tool_result: "The tool completed without returning text output."+ too_many_tool_calls: "The model requested {requested} tools. At most {limit} can run in parallel in one iteration, so the list was truncated."+ tool_unknown_error: "An unknown error occurred while executing {tool}."+ protocol_retry: "The model violated the action-label protocol; retrying this iteration."+ max_iterations_reached: "Reached the per-step iteration ceiling. Producing the best section I can with what I have."+ context_window_guard: "Trimmed older tool results to keep this step within the model's context window."+ final_protocol_failed: "The model still did not produce a valid FINISH reply after the finalization prompt."+ pre_retrieve_unavailable: "No knowledge base attached — skipping pre-retrieval."+ replan_budget_exhausted: "Replan budget exhausted; closing the step with a best-effort FINISH."++empty:+ no_step_sections: "(no completed sections yet)"+ no_previous_attempt: "(this is the first plan attempt — no replan context)"+ no_kb_retrieved: "(no knowledge base attached — no pre-retrieval)"+ no_memory: "(no historical memory)"+ no_conversation: "(no prior conversation)"diff --git a/deeptutor/agents/solve/prompts/en/planner_agent.yaml b/deeptutor/agents/solve/prompts/en/planner_agent.yamldeleted file mode 100644index b3066a1c8..000000000--- a/deeptutor/agents/solve/prompts/en/planner_agent.yaml+++ /dev/null@@ -1,65 +0,0 @@-system: |- # Role- You are a **Problem-Solving Planner**. Your job is to analyse the user's question and produce an ordered list of solving steps.-- # Rules- 1. Each step must be a **verifiable sub-goal** — describe **what** needs to be established or answered, NOT **how** (no tool names, no action instructions).- - Good: "Establish the mathematical definition of linear convolution"- - Bad: "Search for convolution" or "Call a tool to find the definition"- 2. Keep the plan **minimal but sufficient**.- - A simple factual question → **1 step**.- - A multi-part analytical question → **2–4 steps**.- - A complex derivation / multi-hop problem → **3–6 steps**.- 3. Do NOT specify which tools to use. The solving agent will independently decide the best approach for each step.- 4. Step IDs must follow the pattern S1, S2, S3, …- 5. If this is a **replan** request (progress is shown below), preserve all completed steps unchanged and only revise or add pending steps.- 6. If memory context is provided, use it as historical reference, but do not copy old plans directly.- 7. If **Retrieved Knowledge** is provided, use it to make a more precise and informed plan. It may reveal what knowledge is available, what concepts are involved, and what sub-problems exist.-- # Output Format- Output **strict JSON** with no extra text:- ```json- {- "analysis": "Brief analysis of the question and what is needed to solve it",- "steps": [- {"id": "S1", "goal": "..."},- {"id": "S2", "goal": "..."}- ]- }- ```--generate_queries: |- Generate {num_queries} concise and diverse knowledge-base search queries for the following question. Each query should target a different aspect of the problem (e.g. core definitions, relevant formulas or theorems, related examples or techniques).-- Question: {question}-- Return strict JSON:- {{"queries": ["query1", "query2", "query3"]}}--aggregate_context: |- Below are several passages retrieved from a knowledge base. Your task is to consolidate them into a single structured knowledge summary.-- Rules:- - Remove duplicate information across passages.- - Organize by topic: definitions, formulas/theorems, key facts, examples.- - Do NOT solve any problem or make inferences beyond what the passages state.- - Do NOT reference any question — just organize the raw knowledge.- - Be concise; keep the summary under 3000 characters.-- {raw_retrieval_text}--user_template: |- ## Question- {question}-- ## Retrieved Knowledge- {retrieved_context}-- ## Available Tools- {tools_description}-- ## Progress So Far- {scratchpad_summary}-- ## Memory Context- {memory_context}diff --git a/deeptutor/agents/solve/prompts/en/solver_agent.yaml b/deeptutor/agents/solve/prompts/en/solver_agent.yamldeleted file mode 100644index b241d14a1..000000000--- a/deeptutor/agents/solve/prompts/en/solver_agent.yaml+++ /dev/null@@ -1,43 +0,0 @@-system: |- # Role- You are a **ReAct Problem-Solving Agent**. You operate in a think → act → observe loop to gather the information needed for the current step.-- # Available Actions- {tools_description}-- # Guidelines- - **One action per response.** Choose the single best next action.- - Before each action, explain your reasoning in `thought`.- - After observing a result, critically assess: Is the information **sufficient and reliable** for this step? If not, try a different query or a different tool before declaring `done`.- - `self_note`: Write a **1-sentence** factual summary of what you learned (or "no useful information found"). This is used for context compression in future rounds.- - The "Historical Knowledge" section may contain relevant experience from previous problem-solving sessions.-- # Output Format- Output **strict JSON** with no extra text:- ```json- {{- "thought": "My reasoning about what to do next...",- "action": "<one available action>",- "action_input": "The concrete input for that action",- "self_note": "One factual sentence summarising what this round established"- }}- ```--user_template: |- ## Original Question- {question}-- ## Plan- {plan}-- ## Current Step- {current_step}-- ## Previous Actions for This Step- {step_history}-- ## Knowledge from Previous Steps- {previous_knowledge}-- ## Historical Knowledge- {memory_context}diff --git a/deeptutor/agents/solve/prompts/en/writer_agent.yaml b/deeptutor/agents/solve/prompts/en/writer_agent.yamldeleted file mode 100644index 38228628b..000000000--- a/deeptutor/agents/solve/prompts/en/writer_agent.yaml+++ /dev/null@@ -1,140 +0,0 @@-system: |- # Role- You are an **Expert Answer Writer**. Your task is to compose a clear, well-structured, and visually rich answer based on the evidence gathered during the solving process.-- # Formatting Rules- - Use **Markdown** with appropriate headings (`##`, `###`).- - All mathematical expressions **must** use LaTeX:- - Inline: `$...$`- - Block / display: `$$...$$`- - **Do NOT** use `\(...\)` or `\[...\]` or bare symbols.- - Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.- - If code execution produced images that appear in the evidence as actual artifacts (with real file paths), embed them using the path from the evidence. **Never invent or guess image file names** — only reference artifacts that explicitly exist in the gathered evidence.- - For code results, show only the key logic or result — not the full script.- - Use tables where they improve clarity (e.g. comparisons, parameter lists, categorical summaries).- - **Visual enhancement**: When content involves processes, architectures, taxonomies, timelines, or decision logic, use Mermaid diagrams to present them visually:- - Processes / steps → `flowchart` or `graph`- - Timelines / phases → `timeline`- - Hierarchies / taxonomies → `mindmap`- - Interactions / call sequences → `sequenceDiagram`- - State transitions → `stateDiagram-v2`- - Example:- ```mermaid- flowchart LR- A[Input] --> B[Process] --> C[Output]- ```- Mermaid diagrams should be woven naturally into the text to help readers grasp complex relationships — they supplement rather than replace written explanations. Do not force them — only include a diagram when it genuinely improves understanding.- - Use **blockquotes** (`>`) to highlight core conclusions, key insights, or important caveats.- - Leverage nested ordered and unordered lists for multi-level points.-- # Writing Style- - **Elaborate sufficiently**: Do not merely list bullet points — expand each key concept with 2–4 sentences of explanation or analysis. Avoid overly terse, telegraphic writing.- - **Smooth transitions**: Bridge paragraphs and sections with connecting sentences that guide the reader through the logical progression, rather than jumping abruptly to the next topic.- - **Explain the "why", not just the "what"**: Go beyond stating facts — illuminate the underlying reasons, motivations, or significance to help readers build deeper understanding.- - **Use analogies and concrete examples**: For abstract or technical concepts, offer everyday analogies or specific scenarios to make the material more accessible and engaging.- - **Professional yet approachable tone**: Maintain academic rigour while avoiding stiff, mechanical phrasing. Write as a patient, knowledgeable teacher explaining to an eager learner.- - **Balance depth and brevity**: Give core arguments rich, detailed treatment; supporting details can be more concise — this creates a natural reading rhythm.-- # Structure- 1. Open with a concise summary (1–3 sentences) if the question warrants it.- 2. Provide a thorough explanation organised by logical sections, with smooth transitions between them.- 3. Include relevant derivations, examples, or calculations, accompanied by sufficient context.- 4. Where complex concepts or multi-step processes arise, consider supplementing with visuals (tables, Mermaid diagrams).- 5. End with a **## References** section listing all cited sources.-- # Important- - Base your answer **only** on the provided evidence. Do not fabricate information.- - **Never reference images or files that do not appear in the evidence.** If no code execution artifact exists, do not embed any image.- - If the evidence is insufficient, state what is missing rather than guessing.- - Write in the language requested by the user (see the Language field).- - Mermaid diagram labels should also use the same language as the rest of the answer.--user_template: |- ## Question- {question}-- ## Gathered Evidence- {scratchpad_content}-- ## Available Sources- {sources}-- ## User Preference- {preference}-- ## Language- Write the answer in **{language}**.--# --- Iterative detailed writing prompts -----iterative_system: |- # Role- You are an **Expert Answer Writer** building an answer incrementally. You will receive either:- - Two pieces of new evidence (first iteration), OR- - A previous draft answer + one piece of new evidence (subsequent iterations).-- Your task is to produce a **comprehensive, well-structured draft** that integrates ALL available information.-- # Formatting Rules- - Use **Markdown** with appropriate headings (`##`, `###`).- - All mathematical expressions **must** use LaTeX: inline `$...$`, block `$$...$$`.- - **Do NOT** use `\(...\)` or `\[...\]`.- - Cite sources inline using their IDs, e.g. `[rag-1]`, `[web-1]`.- - If code execution produced images that appear in the evidence as actual artifacts (with real file paths), embed them using the path from the evidence. **Never invent or guess image file names.**- - Use tables where they improve clarity.- - **Visual enhancement**: When content involves processes, architectures, taxonomies, or decision logic, use Mermaid diagrams (`flowchart`, `sequenceDiagram`, `mindmap`, etc.) to supplement the explanation. Only include a diagram when it genuinely improves understanding — do not force them.- - Use blockquotes (`>`) to highlight core conclusions or key insights.-- # Writing Style- - Elaborate each key concept with 2–4 sentences rather than terse bullet points.- - Use smooth transitions between paragraphs and sections to guide the reader through the logical flow.- - Explain not just "what" but "why" — illuminate underlying reasons and significance.- - Write in a professional yet approachable tone, like a patient teacher explaining to an eager learner.-- # Guidelines- - When a previous draft is provided, **expand and refine it** with the new evidence — do not discard prior content. Also polish existing prose to improve overall fluency.- - Reorganise sections if the new evidence changes the logical flow, but ensure transitions remain natural.- - As evidence accumulates, consider whether to add or update visual elements (tables, Mermaid diagrams) to better present the overall structure.- - Base your answer **only** on the provided evidence and prior draft. Do not fabricate information.- - **Never reference images or files that do not appear in the evidence.** If no code execution artifact exists, do not embed any image.- - Write in the language specified. Mermaid diagram labels should also use the same language as the answer.--iterative_user_template: |- ## Question- {question}-- ## Previous Draft- {previous_draft}-- ## New Evidence- {new_evidence}-- ## Available Sources- {sources}-- ## User Preference- {preference}-- ## Language- Write in **{language}**.--concise_system: |- # Role- You are producing a **Concise Answer** for the given question based on a detailed draft.-- # Rules- - If the question is a **multiple-choice, true/false, or fill-in-the-blank** question, give the **direct answer first** (e.g., "The answer is B" or "42").- - Otherwise, write a **2–4 sentence summary** that captures the core answer.- - Use LaTeX for any math: inline `$...$`, block `$$...$$`.- - Do NOT include headings, references, or lengthy explanations — keep it concise.- - Write in the language specified.--concise_user_template: |- ## Question- {question}-- ## Detailed Answer- {detailed_answer}-- ## Language- Write in **{language}**.diff --git a/deeptutor/agents/solve/prompts/zh/answer_now.yaml b/deeptutor/agents/solve/prompts/zh/answer_now.yamldeleted file mode 100644index 385244595..000000000--- a/deeptutor/agents/solve/prompts/zh/answer_now.yaml+++ /dev/null@@ -1,15 +0,0 @@-system: |- 你是 DeepTutor 的写作组件。用户已经在等待,- 你必须基于当前已经收集到的推理与工具调用轨迹直接输出最终答复。- 不要再做新的规划或调用工具,不要提到内部阶段。- 如果信息仍有缺口,请诚实说明不确定之处,但仍尽可能给出当前最有用的回答。--user_template: |- 用户原始问题:- {original}-- {current_draft}-- {execution_trace}-- 请基于以上材料立即生成给用户的最终回答。diff --git a/deeptutor/agents/solve/prompts/zh/pipeline.yaml b/deeptutor/agents/solve/prompts/zh/pipeline.yamlnew file mode 100644index 000000000..50eb3d623--- /dev/null+++ b/deeptutor/agents/solve/prompts/zh/pipeline.yaml@@ -0,0 +1,302 @@+# SolvePipeline 提示词(中文)+# 见对应的 en/pipeline.yaml 了解协议总览。++labels:+ pre_retrieve: "预检索"+ gen_queries: "生成检索词"+ aggregate: "聚合知识"+ retrieve: "检索"+ plan: "规划"+ replan: "重规划"+ solve_step: "解题步骤"+ reasoning: "推理"+ tool_call: "工具调用"+ synthesize: "总结"+ answer_now: "立即作答"+ explain_judge: "解释判定"+ explain: "深度解释"+ explain_summary: "深入解释"++# ---------------------------------------------------------------------------+# 阶段 0:预检索(仅在挂载知识库时运行)+# ---------------------------------------------------------------------------+pre_retrieve:+ gen_queries:+ system: |-+ 你是知识库检索词规划器。++ 回复**必须**以协议标签 ``QUERIES`` 开头,第一行用两个反引号包裹。标签之后只输出一个 JSON 字符串数组,**不要包含其他内容**。++ 每个检索词应聚焦问题的不同侧面(定义、公式 / 定理、例题、边界情况等),尽量简洁。+ user_template: |-+ 为以下问题生成 {num_queries} 条简洁、互补的知识库检索词。++ 问题:{question}++ aggregate:+ system: |-+ 你是知识整理器。++ 回复**必须**以 ``SUMMARY`` 开头。标签之后,基于给定段落写一段结构化的知识总结。++ 规则:+ - 跨段落去重+ - 按主题组织(定义、公式 / 定理、关键事实、例题)+ - **不要**回答任何问题,**不要**做超出段落内容的推断+ - **不要**引用任何问题——只整理原始知识+ - 总结控制在 3000 字以内+ user_template: |-+ 下面是从知识库检索到的若干段落,请整合。++ {raw_retrieval_text}++# ---------------------------------------------------------------------------+# 阶段 1:规划(REPLAN 时也回到这里,会带上失败理由重新规划)+# ---------------------------------------------------------------------------+plan:+ system: |-+ 你是问题分解规划器。把用户问题拆成有序的解题步骤。++ 回复**必须**以 ``PLAN`` 开头,第一行用两个反引号包裹。标签之后输出**恰好一个** JSON 对象:++ {{"analysis": "对问题的简要分析", "steps": [{{"id": "S1", "goal": "..."}}, {{"id": "S2", "goal": "..."}}]}}++ 规则:+ 1. 每个步骤是可验证的子目标——描述「做什么」,而不是「怎么做」,**不要**提工具。+ 2. 计划要最小可行:+ - 简单事实题 → 1 步+ - 多角度分析 → 2–4 步+ - 复杂推导 / 多跳问题 → 3–6 步+ 3. 步骤 id 遵循 S1, S2, S3 … 的格式。+ 4. 如果出现「Replan reason」字段,说明上一轮计划出了问题。直接针对该理由修订计划。可以保留之前可用的步骤目标,也可以引入新的——上一轮已完成的步骤结果会作为新计划的上下文保留。+ 5. 如果提供了检索到的知识,请基于此做出更有依据的计划。+ user_template: |-+ ## 问题+ {question}++ ## 检索到的知识+ {retrieved_context}++ ## 记忆上下文+ {memory_context}++ ## 对话上下文+ {conversation_context}++ ## 上一轮尝试(仅 replan 时存在)+ {previous_attempt}++ ## 重规划理由(仅 replan 时存在)+ {replan_reason}++# ---------------------------------------------------------------------------+# 阶段 2:解题步骤(每步一个 agentic loop,每轮一次 LLM 调用)+# ---------------------------------------------------------------------------+solve_step:+ system: |-+ 你正在解决一个多步骤问题中的第 {step_index_human}/{total_steps} 步。++ # 输出协议(强制)++ 每次回复**必须**以以下四个标签之一开头,全大写,第一行用两个反引号包裹:++ ``THINK`` → 纯思考,不调工具。标签后写出推理。循环继续,下一轮可以接着想。+ ``TOOL`` → 需要工具。标签后写一句简短意图,然后在同一次回复里发出原生 tool_calls。+ ``FINISH`` → 本步骤完成。标签后写**对应这一步、面向用户的整体回答中的一段**。**不要**调工具。+ ``REPLAN`` → 当前计划不再合适。标签后**只写**计划为什么不合适的原因(**不要**写新计划,规划器会基于你的理由重新规划)。**不要**调工具。++ 运行时把 ``FINISH`` 和 ``REPLAN`` 视为本步骤的终止信号。``THINK`` 和工具结果会让循环继续。++ 一次回复**只**选择一个动作标签,正文里**不要**再出现第二个协议标签。``THINK``、``FINISH``、``REPLAN`` **不允许**带 tool_calls。++ # FINISH 内容的写法++ 每一步的 ``FINISH`` 文本会拼接成最终面向用户的答案。把它写成**连贯的一节**,同时**段落本身要写得充分**——不只是给结论,还要展开论证、给直觉、走公式、举具体例子或子情形(当存在时)。++ **强制格式**:FINISH 内容**必须**以以下形式的单行 H2 标题作为第一行:++ ## Step {step_index_human}:<本步骤的简短主题>++ 主题用 5–10 个字概括即可。**不要**在标题前加任何过渡语(如「让我们先 ……」「接下来 ……」「现在,把这些综合起来 ……」)——标题本身就是这一节的锚点。标题行之后留一个空行,再开始正文。++ {tone_guidance}++ 如果用到检索段落,用 [source-id] 行内引用。++ 充分利用 Markdown 富文本能力(**仅在真正能提升清晰度时使用,不要硬上**):+ - **标题**:FINISH 段落里可以用 ``## H2`` 和 ``### H3`` 来组织子内容。**不要**用 ``#``(H1)——那一级留给整个对话答复的最外层容器。+ - **表格** 用于对比、参数列表、前后对照。+ - **LaTeX** 数学:行内 $...$,行间 $$...$$。+ - **项目符号 / 编号列表** 用于枚举。+ - **Mermaid 图表**(用 ```mermaid 代码块)当图能澄清流程、时序、关系时。+ - **Callout**(`> **注意:** ...`、`> **警告:** ...`)用于重要旁注。+ - **加粗 / 斜体** 标记关键术语;**行内 code** 用于符号 / 标识符。++ # 每轮的推理++ 1. 如果本步骤的证据已经够用,用 ``FINISH`` 收束。+ 2. 如果需要外部信息 / 计算 / 检索,用 ``TOOL`` 并发出真实的 tool_calls。+ 3. 如果想先思考再行动,用 ``THINK``。+ 4. 如果你**确实**认为计划有问题(缺步骤、上游有错误假设等),用 ``REPLAN`` 并给出清晰理由。++ 工具调用的硬规则:+ - 工具名、参数名、知识库名必须**逐字**抄自下方「启用的工具」/「知识库」块。**不要**编造。+ - 参数必须具体可执行;空查询无效。++ {kb_note}+ 启用的工具:+ {tool_list}+ user_template: |-+ ## 原问题+ {question}++ ## 完整计划+ {plan_summary}++ ## 当前步骤+ [{step_id}] {step_goal}++ ## 之前步骤已经输出的内容+ {previous_finishes}++ ## 记忆上下文+ {memory_context}++ ## 对话上下文+ {conversation_context}++ 开始为第 {step_id} 步推理。++ # 语气指引由编排器按步骤位置选择,注入到上面的 system 提示中的 {tone_guidance}。+ # 标题已经成为这一节的锚点,所以 tone 不再要求"以过渡语开头",只引导收束方式。+ tone:+ only: |-+ 这是答案的**唯一一步**。标题之后写一段完整、自洽的内容,简要框定问题、给出关键结论。+ first: |-+ 这是**第一步**。标题之后展开实质内容。**不要**写收束性的话——后面还有更多步骤。+ middle: |-+ 这是**中间步骤**。标题之后展开实质内容。**不要**写收束性的话——后面还有更多步骤。+ last: |-+ 这是**最后一步**。标题之后展开实质内容,可以用一句话简短收束;后面的总结环节会处理整体回顾。++# ---------------------------------------------------------------------------+# 阶段 2.5:解释判定 + 深度解释(每个 step FINISH 完成后可选触发)+# ---------------------------------------------------------------------------+explain_judge:+ system: |-+ 你是一个分诊环节,判断刚刚结束的步骤段落是否需要在下面接一段更深的解释。++ 回复**必须**以以下两个标签之一开头,第一行用两个反引号包裹:++ ``EXPLAIN`` → 该段落涉及非平凡的概念、推导、公式、边界情况或直觉,值得更深入地展开。标签后**写一句话**,说明要深入的是什么(例如:"守恒律背后的直觉"、"为什么这个不等式取等"、"递归的终止条件如何成立")。+ ``SKIP`` → 段落对认真阅读的用户已经自解释,进一步展开只是重复屏幕上已有的内容。标签后**不要写任何内容**。++ **保守判定**:除非确实有教学价值(值得展开的概念 / 值得点透的直觉 / 非显然的步骤值得论证),否则默认 ``SKIP``。**不要**仅因为段落短就 ``EXPLAIN``;也**不要**仅因为话题复杂就 ``EXPLAIN``——只有当展开真的能帮到用户理解时,才触发。+ user_template: |-+ ## 原问题+ {question}++ ## 当前步骤+ [{step_id}] {step_goal}++ ## 用户刚看到的段落+ {finish_text}++explain:+ system: |-+ 你正在为刚刚那一步的段落写一段更深的解释,会紧接着在用户看到的内容下方流式输出。用户已经看过上面的段落;你的任务是比那段**更深入、更详细**地展开底层概念、推导或直觉。++ 回复**必须**以 ``FINISH`` 开头,第一行用两个反引号包裹。标签之后写更深的解释。++ 展开内容应该:+ - 比上面段落**更深入**——讲清「为什么」和「怎么来的」,而不是重述「是什么」。+ - 加入具体落地:小例子、特殊情形、常见误区、几何 / 物理 / 算法直觉。+ - **不要**逐字复述段落里的结论——在它的基础上补足、揭示假设、把跳跃的推理填上、给读者构建心智模型。+ - 只聚焦**当前步骤**,**不要**开始解下一步。+ - 写得比 FINISH 段更丰富——可以更长、更结构化。++ 充分利用 Markdown 富文本能力(**仅在真正能提升清晰度时使用,不要硬上**):+ - **标题**:所有子标题**最多用 ``### H3``** 或更小(H4、H5 等)。**不要**用 ``#``(H1)或 ``## H2``——上面的 FINISH 段已经锚定在 H2 级别,深度解释作为它的展开必须嵌套在 H3 或更深的层级。+ - **表格** 用于对比、参数列表、前后对照、特殊情形枚举。+ - **LaTeX** 数学:行内 $...$,行间 $$...$$。+ - **项目符号 / 编号列表** 用于枚举要点 / 步骤。+ - **Mermaid 图表**(用 ```mermaid 代码块)当图能澄清流程、时序、状态机或关系时。+ - **Callout**(`> **注意:** ...`、`> **警告:** ...`、`> **直觉:** ...`)用于重要旁注。+ - **加粗 / 斜体** 标记关键术语;**行内 code** 用于符号 / 标识符 / 公式片段。+ user_template: |-+ ## 原问题+ {question}++ ## 当前步骤+ [{step_id}] {step_goal}++ ## 用户刚看到的段落+ {finish_text}++ ## 需要深入的方向(来自分诊)+ {explain_focus}++# ---------------------------------------------------------------------------+# 阶段 3:总结(所有步骤完成后的单次 FINISH 调用)+# ---------------------------------------------------------------------------+synthesize:+ system: |-+ 你正在为一个多步骤问题收尾。用户已经看到每一步分段流式输出的内容;你的任务是落地最终答案。++ 回复**必须**以 ``FINISH`` 开头,第一行用两个反引号包裹。标签之后按顺序:++ 1. **精确的最终答案**——如果原问题需要一个具体值、选项、判断或简短答案,用一句话直接给出。如果是开放性问题(如「解释 ……」),跳过这条,直接进入第 2 条。+ 2. **简短的整体回顾**——一小段,串联各步骤的思路。**保持简短**;每一步的分段已经在屏幕上了。++ 使用 Markdown,数学用 LaTeX。**不要**调工具。+ user_template: |-+ ## 原问题+ {question}++ ## 用户已经看到的分步内容+ {step_finishes}++ ## 对话上下文+ {conversation_context}++# ---------------------------------------------------------------------------+# 协议违规修复提示(host 返回给 loop 用)+# ---------------------------------------------------------------------------+protocol:+ missing_label: |-+ 协议修正:你上一轮回复没有以协议标签开头,本轮还不算完成。下一次回复**必须**在第一行写**且仅写**一个动作标签:``THINK``、``TOOL``、``FINISH`` 或 ``REPLAN``。正文里**不要**再出现第二个协议标签。+ multiple_labels: |-+ 协议修正:上一轮回复出现了多个协议标签。下一次回复在第一行**只**写一个动作标签,正文里**不要**再放第二个标签。+ tool_without_calls: |-+ 协议修正:你选择了 ``TOOL`` 但没有发出真实的 tool_calls。``TOOL`` 必须在同一次回复里发出 tool_calls;否则改用 ``THINK``、``FINISH`` 或 ``REPLAN``。+ think_with_tools: |-+ 协议修正:你选择了 ``THINK`` 同时发起了工具调用。``THINK`` 只用于思考。需要工具就用 ``TOOL``;只想思考就用 ``THINK`` 且**不要**调工具。+ finish_with_tools: |-+ 协议修正:你选择了 ``FINISH`` 同时发起了工具调用。``FINISH`` 用面向用户的内容收束本步——**不要**调工具。如果还需要信息,先用 ``TOOL``。+ label_with_tools: |-+ 协议修正:你选择了 ``REPLAN`` 同时发起了工具调用。``REPLAN`` 是规划信号——**不要**带 tool_calls。如果需要检索用 ``TOOL``,需要思考用 ``THINK``,否则在 ``REPLAN`` 之后写明重规划的理由。+ force_finish: |-+ 本步骤的迭代预算已用完。现在必须给出本步骤面向用户的最终段落:第一行必须是 ``FINISH``,**不要**再调用工具、**不要**用 ``THINK`` 或 ``REPLAN``。即使信息不完整,也请简短说明不确定性,并仍写出当前最有用的段落。+ force_finish_repair: |-+ 最终化协议修正:上一轮没有按 ``FINISH`` 协议输出。现在只输出最终段落:第一行 ``FINISH``,后面直接写面向用户的内容。**不要**写 ``THINK`` / ``TOOL`` / ``REPLAN``,**不要**调工具。+ fallback_final: |-+ 本步骤已达迭代上限但模型未给出有效的 ``FINISH``。本步骤以未完成的状态结束。++notices:+ start_retrieval: "开始检索"+ empty_tool_result: "工具完成但未返回文本输出。"+ too_many_tool_calls: "模型请求了 {requested} 个工具。一次最多并行 {limit} 个,已截断。"+ tool_unknown_error: "执行 {tool} 时出现未知错误。"+ protocol_retry: "模型违反了动作标签协议;本轮重试。"+ max_iterations_reached: "已达单步迭代上限。基于当前已有内容输出段落。"+ context_window_guard: "为了保持在模型上下文窗口内,裁剪了较早的工具结果。"+ final_protocol_failed: "最终化提示之后模型仍未给出有效的 FINISH 回复。"+ pre_retrieve_unavailable: "未挂载知识库——跳过预检索。"+ replan_budget_exhausted: "重规划预算已用完;以尽力 FINISH 的方式收束本步骤。"++empty:+ no_step_sections: "(尚无已完成的段落)"+ no_previous_attempt: "(这是第一次规划——无重规划上下文)"+ no_kb_retrieved: "(未挂载知识库——无预检索)"+ no_memory: "(无历史记忆)"+ no_conversation: "(无对话上下文)"diff --git a/deeptutor/agents/solve/prompts/zh/planner_agent.yaml b/deeptutor/agents/solve/prompts/zh/planner_agent.yamldeleted file mode 100644index 9de448148..000000000--- a/deeptutor/agents/solve/prompts/zh/planner_agent.yaml+++ /dev/null@@ -1,65 +0,0 @@-system: |- # 角色- 你是一个**问题求解规划器**。你的任务是分析用户的问题,并生成一个有序的求解步骤列表。-- # 规则- 1. 每个步骤必须是一个**可验证的子目标** — 描述**需要确定或回答什么**,而不是**如何做**(不要提及工具名称或操作指令)。- - 好的例子:"建立线性卷积的数学定义"- - 不好的例子:"搜索卷积" 或 "调用工具查找卷积定义"- 2. 计划应当**精简但充分**。- - 简单的事实性问题 → **1 个步骤**。- - 多部分的分析性问题 → **2–4 个步骤**。- - 复杂的推导 / 多跳问题 → **3–6 个步骤**。- 3. 不要指定使用哪些工具。求解 agent 会独立决定每个步骤的最佳方法。- 4. 步骤 ID 必须遵循 S1, S2, S3, … 的模式。- 5. 如果这是一个**重新规划**请求(下方会显示进度),保留所有已完成的步骤不变,只修改或添加待处理的步骤。- 6. 如果提供了记忆上下文,可将其作为历史参考,但不要直接照搬旧计划。- 7. 如果提供了**检索到的知识**,请利用它来制定更精准的计划。它可能揭示了可用的知识、涉及的概念以及存在的子问题。-- # 输出格式- 输出**严格的 JSON**,不要有额外文字:- ```json- {- "analysis": "对问题的简要分析以及求解所需的内容",- "steps": [- {"id": "S1", "goal": "..."},- {"id": "S2", "goal": "..."}- ]- }- ```--generate_queries: |- 针对以下问题,生成 {num_queries} 个简洁且多角度的知识库检索查询。-- 问题:{question}-- 返回严格的 JSON:- {{"queries": ["查询1", "查询2", "查询3"]}}--aggregate_context: |- 以下是从知识库中检索到的多段内容。你的任务是将它们整合为一份结构化的知识摘要。-- 规则:- - 去除各段之间的重复信息。- - 按主题组织:定义、公式/定理、关键事实、示例。- - 不要解答任何问题,也不要做超出原文的推断。- - 不要提及任何问题 — 只整理原始知识。- - 保持简洁,摘要控制在 3000 字符以内。-- {raw_retrieval_text}--user_template: |- ## 问题- {question}-- ## 检索到的知识- {retrieved_context}-- ## 可用工具- {tools_description}-- ## 当前进度- {scratchpad_summary}-- ## 记忆上下文- {memory_context}diff --git a/deeptutor/agents/solve/prompts/zh/solver_agent.yaml b/deeptutor/agents/solve/prompts/zh/solver_agent.yamldeleted file mode 100644index 9fe9d259a..000000000--- a/deeptutor/agents/solve/prompts/zh/solver_agent.yaml+++ /dev/null@@ -1,43 +0,0 @@-system: |- # 角色- 你是一个**ReAct 问题求解 Agent**。你在 思考 → 行动 → 观察 的循环中工作,为当前步骤收集所需信息。-- # 可用操作- {tools_description}-- # 指导原则- - **每次回复只执行一个操作。** 选择当前最佳的下一个操作。- - 每次操作前,在 `thought` 中解释你的推理过程。- - 观察结果后,批判性地评估:该信息对当前步骤是否**充分且可靠**?如果不够,在宣布 `done` 之前尝试不同的查询或不同的工具。- - `self_note`:写一个**一句话**的事实性总结,说明你在这一轮中学到了什么(或"未找到有用信息")。这用于后续轮次的上下文压缩。- - "历史知识"段可能包含来自以往解题过程的相关经验,可作为补充参考。-- # 输出格式- 输出**严格的 JSON**,不要有额外文字:- ```json- {{- "thought": "我对下一步该做什么的推理...",- "action": "<一个可用操作>",- "action_input": "该操作对应的具体输入",- "self_note": "一句事实性总结,说明这一轮确认了什么"- }}- ```--user_template: |- ## 原始问题- {question}-- ## 计划- {plan}-- ## 当前步骤- {current_step}-- ## 当前步骤的历史操作- {step_history}-- ## 前序步骤的知识- {previous_knowledge}-- ## 历史知识- {memory_context}diff --git a/deeptutor/agents/solve/prompts/zh/writer_agent.yaml b/deeptutor/agents/solve/prompts/zh/writer_agent.yamldeleted file mode 100644index 340f3d071..000000000--- a/deeptutor/agents/solve/prompts/zh/writer_agent.yaml+++ /dev/null@@ -1,140 +0,0 @@-system: |- # 角色- 你是一个**专业的解答撰写者**。你的任务是根据求解过程中收集的证据,撰写一篇清晰、结构良好、视觉丰富的解答。-- # 格式规则- - 使用 **Markdown** 和适当的标题(`##`、`###`)。- - 所有数学表达式**必须**使用 LaTeX:- - 行内:`$...$`- - 独立块/展示:`$$...$$`- - **不要**使用 `\(...\)` 或 `\[...\]` 或裸符号。- - 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。- - 如果代码执行生成了图片,且这些图片作为实际 artifact(带有真实文件路径)出现在证据中,则使用证据中的路径嵌入图片。**绝对不要捏造或猜测图片文件名** — 只引用证据中明确存在的 artifact。- - 对于代码结果,只展示关键逻辑或结果 — 不要展示完整脚本。- - 在表格能提高清晰度时使用表格(如对比、参数列表、分类汇总等)。- - **可视化增强**:当内容涉及流程、架构、分类关系、时间线或决策逻辑时,使用 Mermaid 图表来直观呈现:- - 流程/步骤 → `flowchart` 或 `graph`- - 时间线/阶段 → `timeline`- - 层次/分类 → `mindmap`- - 交互/调用 → `sequenceDiagram`- - 状态转换 → `stateDiagram-v2`- - 例如:- ```mermaid- flowchart LR- A[输入] --> B[处理] --> C[输出]- ```- Mermaid 图应作为辅助手段自然穿插在文本中,帮助读者理解复杂关系,而非替代文字解释。不必强行使用 — 仅在图表确实能增强理解时才加入。- - 善用 **引用块**(`>`)来突出核心结论、关键洞察或重要提醒。- - 对于多层次的要点,灵活运用有序列表和无序列表的嵌套。-- # 写作风格- - **充分展开论述**:不要只罗列要点,每个关键概念都应有 2–4 句话的解释或分析。避免过于简短、电报式的表达。- - **自然流畅的过渡**:段落与段落之间、章节与章节之间应有衔接语句,引导读者理解内容的逻辑推进,而非生硬地跳跃到下一个话题。- - **解释"为什么"而非仅仅"是什么"**:不要只陈述事实,还要说明背后的原因、动机或意义,帮助读者建立深层理解。- - **善用类比与具体示例**:对于抽象或专业的概念,尝试用日常类比或具体场景来辅助说明,让内容更易理解。- - **语气专业但亲切**:保持学术严谨性的同时,避免过于生硬刻板的措辞。像一位有耐心的老师在给学生讲解一样。- - **详略得当**:核心论点要浓墨重彩地展开,辅助信息可以适当精简,形成节奏感。-- # 结构- 1. 如果问题需要,以简洁的摘要开头(1–3 句话)。- 2. 按逻辑章节提供详尽的解释,章节之间有过渡和衔接。- 3. 包含相关的推导、示例或计算,并附上必要的上下文说明。- 4. 在涉及复杂概念或多步流程时,考虑用可视化(表格、Mermaid 图)辅助说明。- 5. 以 **## 参考文献** 部分结束,列出所有引用的来源。-- # 重要提示- - 你的回答**只能**基于提供的证据。不要编造信息。- - **绝对不要引用证据中不存在的图片或文件。** 如果不存在代码执行 artifact,不要嵌入任何图片。- - 如果证据不足,说明缺少什么,而不是猜测。- - 使用用户要求的语言撰写(参见"语言"字段)。- - Mermaid 图中的内容也应使用与正文一致的语言。--user_template: |- ## 问题- {question}-- ## 收集的证据- {scratchpad_content}-- ## 可用来源- {sources}-- ## 用户偏好- {preference}-- ## 语言- 请使用 **{language}** 撰写解答。--# --- 迭代式详细写作提示词 -----iterative_system: |- # 角色- 你是一个**专业的解答撰写者**,正在逐步构建一份完整的解答。你将收到以下内容之一:- - 两份新证据(第一次迭代),或者- - 上一轮的草稿解答 + 一份新证据(后续迭代)。-- 你的任务是生成一份**全面、结构良好的草稿**,整合所有可用信息。-- # 格式规则- - 使用 **Markdown** 和适当的标题(`##`、`###`)。- - 所有数学表达式**必须**使用 LaTeX:行内 `$...$`,独立块 `$$...$$`。- - **不要**使用 `\(...\)` 或 `\[...\]`。- - 使用来源 ID 进行行内引用,例如 `[rag-1]`、`[web-1]`。- - 如果代码执行生成了图片,且这些图片作为实际 artifact(带有真实文件路径)出现在证据中,则使用证据中的路径嵌入图片。**绝对不要捏造或猜测图片文件名。**- - 在表格能提高清晰度时使用表格。- - **可视化增强**:当内容涉及流程、架构、分类关系或决策逻辑时,可使用 Mermaid 图表(`flowchart`、`sequenceDiagram`、`mindmap` 等)来辅助说明。仅在图表确实能增强理解时才加入,不要强行使用。- - 善用引用块(`>`)来突出核心结论或关键洞察。-- # 写作风格- - 充分展开每个关键概念(2–4 句解释),避免过于简短的罗列。- - 段落和章节之间要有自然的过渡衔接,引导读者理解逻辑推进。- - 不仅陈述"是什么",还要说明"为什么",帮助读者建立深层理解。- - 语气专业但亲切,像一位耐心的老师在讲解。-- # 指导原则- - 当提供了上一轮草稿时,**在其基础上扩展和完善** — 不要丢弃之前的内容。同时润色已有文字,使整体行文更流畅。- - 如果新证据改变了逻辑流程,可以重新组织章节,但要确保过渡自然。- - 随着证据的积累,考虑是否需要添加或更新可视化元素(表格、Mermaid 图)来更好地呈现整体结构。- - 你的回答**只能**基于提供的证据和之前的草稿。不要编造信息。- - **绝对不要引用证据中不存在的图片或文件。** 如果不存在代码执行 artifact,不要嵌入任何图片。- - 使用指定的语言撰写。Mermaid 图中的内容也应使用与正文一致的语言。--iterative_user_template: |- ## 问题- {question}-- ## 上一轮草稿- {previous_draft}-- ## 新证据- {new_evidence}-- ## 可用来源- {sources}-- ## 用户偏好- {preference}-- ## 语言- 请使用 **{language}** 撰写。--concise_system: |- # 角色- 你正在根据一份详细的草稿,为给定问题生成一个**精简回答**。-- # 规则- - 如果问题是**选择题、判断题或填空题**,**先直接给出答案**(例如:"答案是 B" 或 "42")。- - 否则,写一个 **2–4 句话的摘要**,抓住核心回答。- - 数学表达式使用 LaTeX:行内 `$...$`,独立块 `$$...$$`。- - 不要包含标题、参考文献或冗长的解释 — 保持精简。- - 使用指定的语言撰写。--concise_user_template: |- ## 问题- {question}-- ## 详细解答- {detailed_answer}-- ## 语言- 请使用 **{language}** 撰写。diff --git a/deeptutor/agents/solve/session_manager.py b/deeptutor/agents/solve/session_manager.pydeleted file mode 100644index decfbb1ff..000000000--- a/deeptutor/agents/solve/session_manager.py+++ /dev/null@@ -1,216 +0,0 @@-#!/usr/bin/env python-"""-SolverSessionManager - Solver session persistence and management.--This module handles:-- Creating new solver sessions-- Updating sessions with new messages-- Retrieving session history-- Listing recent sessions-- Deleting sessions--Now inherits from BaseSessionManager for consistent behavior across all modules.-"""--from typing import Any--from deeptutor.services.session import BaseSessionManager---class SolverSessionManager(BaseSessionManager):- """- Manages persistent storage of solver sessions.-- Legacy JSON sessions are stored under ``data/user/workspace/chat/deep_solve/sessions.json``.- Each session contains:- - session_id: Unique identifier- - title: Session title (usually first user question)- - messages: List of messages with role, content, output_dir, timestamp- - kb_name: Knowledge base used- - token_stats: Cost and token usage statistics- - created_at: Creation timestamp- - updated_at: Last update timestamp- """-- DEFAULT_TOKEN_STATS = {- "model": "Unknown",- "calls": 0,- "tokens": 0,- "input_tokens": 0,- "output_tokens": 0,- "cost": 0.0,- }-- def __init__(self):- """Initialize SolverSessionManager."""- super().__init__("solve")-- # =========================================================================- # BaseSessionManager Abstract Method Implementations- # =========================================================================-- def _get_session_id_prefix(self) -> str:- """Return the prefix for session IDs."""- return "solve_"-- def _get_default_title(self) -> str:- """Return the default title for new sessions."""- return "New Solver Session"-- def _create_session_data(- self,- kb_name: str = "",- token_stats: dict[str, Any] | None = None,- **kwargs,- ) -> dict[str, Any]:- """- Create solver-specific session data.-- Args:- kb_name: Knowledge base name- token_stats: Token usage statistics-- Returns:- Dict with kb_name and token_stats- """- return {- "kb_name": kb_name,- "token_stats": token_stats or self.DEFAULT_TOKEN_STATS.copy(),- }-- def _get_session_summary(self, session: dict[str, Any]) -> dict[str, Any]:- """- Create a summary of a solver session for listing.-- Args:- session: The full session data-- Returns:- Dict containing summary fields- """- messages = session.get("messages", [])- return {- "session_id": session.get("session_id"),- "title": session.get("title"),- "message_count": len(messages),- "kb_name": session.get("kb_name"),- "token_stats": session.get("token_stats"),- "created_at": session.get("created_at"),- "updated_at": session.get("updated_at"),- # Include preview of last message- "last_message": (messages[-1].get("content", "")[:100] if messages else ""),- }-- # =========================================================================- # Solver-Specific Methods- # =========================================================================-- def create_session(- self,- title: str | None = None,- kb_name: str = "",- token_stats: dict[str, Any] | None = None,- ) -> dict[str, Any]:- """- Create a new solver session.-- Args:- title: Session title (uses default if None)- kb_name: Knowledge base name- token_stats: Optional token usage statistics-- Returns:- New session dict with session_id- """- return super().create_session(- title=title,- kb_name=kb_name,- token_stats=token_stats,- )-- def add_message(- self,- session_id: str,- role: str,- content: str,- output_dir: str | None = None,- ) -> dict[str, Any] | None:- """- Add a single message to a session.-- Args:- session_id: Session identifier- role: Message role ('user' or 'assistant')- content: Message content- output_dir: Optional output directory (for assistant messages)-- Returns:- Updated session or None if not found- """- return super().add_message(- session_id=session_id,- role=role,- content=content,- output_dir=output_dir,- )-- def update_session(- self,- session_id: str,- messages: list[dict[str, Any]] | None = None,- title: str | None = None,- kb_name: str | None = None,- token_stats: dict[str, Any] | None = None,- ) -> dict[str, Any] | None:- """- Update a session with new data.-- Args:- session_id: Session identifier- messages: New messages list (replaces existing)- title: New title (optional)- kb_name: New knowledge base name (optional)- token_stats: New token stats (optional)-- Returns:- Updated session or None if not found- """- return super().update_session(- session_id=session_id,- messages=messages,- title=title,- kb_name=kb_name,- token_stats=token_stats,- )-- def update_token_stats(- self,- session_id: str,- token_stats: dict[str, Any],- ) -> dict[str, Any] | None:- """- Update token stats for a session.-- Args:- session_id: Session identifier- token_stats: Token usage statistics-- Returns:- Updated session or None if not found- """- return self.update_session(session_id, token_stats=token_stats)---# Singleton instance for convenience-_solver_session_manager: SolverSessionManager | None = None---def get_solver_session_manager() -> SolverSessionManager:- """Get or create the global SolverSessionManager instance."""- global _solver_session_manager- if _solver_session_manager is None:- _solver_session_manager = SolverSessionManager()- return _solver_session_manager---__all__ = ["SolverSessionManager", "get_solver_session_manager"]diff --git a/deeptutor/agents/solve/tool_runtime.py b/deeptutor/agents/solve/tool_runtime.pydeleted file mode 100644index 29c1b8497..000000000--- a/deeptutor/agents/solve/tool_runtime.py+++ /dev/null@@ -1,219 +0,0 @@-"""Unified solve runtime built on the core tool registry."""--from __future__ import annotations--import os-from typing import TYPE_CHECKING, Any--from deeptutor.runtime.registry.tool_registry import ToolRegistry as CoreToolRegistry-from deeptutor.runtime.registry.tool_registry import get_tool_registry--if TYPE_CHECKING:- from deeptutor.core.tool_protocol import ToolResult--_CONTROL_ACTIONS = {- "en": [- {- "name": "done",- "when_to_use": "Use when the current step already has enough reliable evidence to move on.",- "input_format": "Empty string.",- },- {- "name": "replan",- "when_to_use": "Use when the current plan is no longer appropriate and the planner should revise it.",- "input_format": "A short reason describing why replanning is needed.",- },- ],- "zh": [- {- "name": "done",- "when_to_use": "当当前步骤已经获得足够且可靠的证据,可以进入下一步时使用。",- "input_format": "空字符串。",- },- {- "name": "replan",- "when_to_use": "当现有计划已不合适,需要重新规划时使用。",- "input_format": "简要说明为何需要重规划。",- },- ],-}--_ACTION_INPUT_PARAM_CANDIDATES = ("query", "intent", "task", "prompt", "input", "code")---class SolveToolRuntime:- """Solve-specific wrapper over the shared tool registry."""-- def __init__(- self,- enabled_tools: list[str] | None,- language: str = "en",- core_registry: CoreToolRegistry | None = None,- ) -> None:- self.language = language- self._core_registry = core_registry or get_tool_registry()- self._tool_names: list[str] = []- self._valid_actions: set[str] = {"done", "replan"}-- for name in enabled_tools or []:- tool = self._core_registry.get(name)- if tool is None:- continue- if tool.name not in self._tool_names:- self._tool_names.append(tool.name)- self._valid_actions.add(tool.name)- self._valid_actions.add(name)- for alias in tool.get_prompt_hints(language=self.language).aliases:- if alias.name:- self._valid_actions.add(alias.name)-- @property- def tool_names(self) -> list[str]:- return list(self._tool_names)-- @property- def valid_actions(self) -> set[str]:- return set(self._valid_actions)-- def has_tool(self, name: str) -> bool:- tool = self._core_registry.get(name)- return bool(tool and tool.name in self._tool_names)-- def resolve_tool_name(self, name: str) -> str | None:- tool = self._core_registry.get(name)- if tool is None:- return None- return tool.name-- def build_planner_description(self, kb_name: str = "") -> str:- return self._core_registry.build_prompt_text(- self._tool_names,- format="list",- language=self.language,- kb_name=kb_name,- )-- def build_solver_description(self) -> str:- table = self._core_registry.build_prompt_text(- self._tool_names,- format="table",- language=self.language,- control_actions=_CONTROL_ACTIONS.get(self.language, _CONTROL_ACTIONS["en"]),- )- aliases = self._core_registry.build_prompt_text(- self._tool_names,- format="aliases",- language=self.language,- )- return "\n\n".join(part for part in (table, aliases) if part.strip())-- async def execute(- self,- action: str,- action_input: str,- *,- kb_name: str | None = None,- output_dir: str | None = None,- reason_context: str = "",- api_key: str | None = None,- base_url: str | None = None,- model: str | None = None,- max_tokens: int | None = None,- temperature: float | None = None,- event_sink: Any | None = None,- ) -> ToolResult:- from deeptutor.core.tool_protocol import ToolResult as _ToolResult-- tool = self._core_registry.get(action)- if tool is None:- raise KeyError(f"Unknown tool action: {action}")- if tool.name not in self._tool_names:- raise PermissionError(f"Tool action '{action}' is not enabled for solve.")-- # Defensive guard: rag without a knowledge base must never reach the- # underlying RAG service. Returning a structured ToolResult keeps the- # ReAct loop alive (the LLM sees a clear observation and can replan).- if tool.name == "rag" and not kb_name:- return _ToolResult(- content=(- "RAG retrieval was requested, but no knowledge base is "- "configured for this turn. Continue without retrieved "- "knowledge or ask the user to select a knowledge base."- ),- sources=[],- metadata={"skipped": True, "reason": "no_kb_selected"},- success=False,- )-- kwargs = self._build_action_input_kwargs(tool.name, action_input)- kwargs = self._apply_runtime_context(- tool_name=tool.name,- kwargs=kwargs,- kb_name=kb_name,- output_dir=output_dir,- reason_context=reason_context,- api_key=api_key,- base_url=base_url,- model=model,- max_tokens=max_tokens,- temperature=temperature,- event_sink=event_sink,- )- return await self._core_registry.execute(action, **kwargs)-- def _build_action_input_kwargs(self, tool_name: str, action_input: str) -> dict[str, Any]:- tool = self._core_registry.get(tool_name)- if tool is None:- return {}-- definition = tool.get_definition()- for candidate in _ACTION_INPUT_PARAM_CANDIDATES:- for param in definition.parameters:- if param.name == candidate:- return {candidate: action_input}- return {}-- @staticmethod- def _apply_runtime_context(- *,- tool_name: str,- kwargs: dict[str, Any],- kb_name: str | None,- output_dir: str | None,- reason_context: str,- api_key: str | None,- base_url: str | None,- model: str | None,- max_tokens: int | None,- temperature: float | None,- event_sink: Any | None,- ) -> dict[str, Any]:- if event_sink is not None:- kwargs.setdefault("event_sink", event_sink)-- if tool_name == "rag" and kb_name:- kwargs.setdefault("kb_name", kb_name)-- if tool_name == "web_search" and output_dir:- kwargs.setdefault("output_dir", output_dir)-- if tool_name == "code_execution":- kwargs.setdefault("timeout", 30)- if output_dir:- kwargs.setdefault("workspace_dir", os.path.join(output_dir, "code_runs"))-- if tool_name == "reason":- if reason_context:- kwargs.setdefault("context", reason_context)- if api_key:- kwargs.setdefault("api_key", api_key)- if base_url:- kwargs.setdefault("base_url", base_url)- if model:- kwargs.setdefault("model", model)- if max_tokens is not None:- kwargs.setdefault("max_tokens", max_tokens)- if temperature is not None:- kwargs.setdefault("temperature", temperature)-- return kwargsdiff --git a/deeptutor/agents/solve/utils/__init__.py b/deeptutor/agents/solve/utils/__init__.pydeleted file mode 100644index 66aba428b..000000000--- a/deeptutor/agents/solve/utils/__init__.py+++ /dev/null@@ -1,9 +0,0 @@-"""Utility exports for the solve agent."""--from .token_tracker import TokenTracker, calculate_cost, get_model_pricing--__all__ = [- "TokenTracker",- "calculate_cost",- "get_model_pricing",-]diff --git a/deeptutor/agents/solve/utils/display_manager.py b/deeptutor/agents/solve/utils/display_manager.pydeleted file mode 100644index 229938c34..000000000--- a/deeptutor/agents/solve/utils/display_manager.py+++ /dev/null@@ -1,218 +0,0 @@-"""-Display Manager - Terminal display manager-Uses rich library to implement beautiful terminal interface, including fixed header (status/statistics) and scrolling log area-"""--from datetime import datetime-import sys-from typing import Any--try:- from rich.console import Console- from rich.layout import Layout- from rich.live import Live- from rich.panel import Panel- from rich.table import Table- from rich.text import Text-- RICH_AVAILABLE = True-except ImportError:- RICH_AVAILABLE = False---class DisplayManager:- """- Terminal display manager-- If rich is available, use TUI interface:- - Top: Agent status checklist + Token/Cost statistics- - Bottom: Scrolling logs-- If rich is not available, fall back to standard stdout output- """-- def __init__(self):- self.rich_available = RICH_AVAILABLE-- self.agents_status = {- "PlannerAgent": "pending",- "SolverAgent": "pending",- "WriterAgent": "pending",- }-- self.stats = {- "model": "Unknown",- "calls": 0,- "tokens": 0,- "input_tokens": 0,- "output_tokens": 0,- "cost": 0.0,- }-- # Log buffer- self.log_buffer = []- self.max_log_lines = 20-- # Early return if rich not available (but after initializing core attributes)- if not self.rich_available:- self.console = None- self.layout = None- self.live = None- return-- # Explicitly use raw stdout, bypass logger redirection- self.console = Console(file=sys.__stdout__)-- # Layout- self.layout = self._make_layout()-- # Live update context- self.live = None-- def start(self):- """Start Live Display"""- if self.rich_available and self.live is None:- self.live = Live(- self.layout,- refresh_per_second=4,- console=self.console,- transient=True, # Remove interface on exit to avoid blocking subsequent input- )- self.live.start()-- def stop(self):- """Stop Live Display"""- if self.rich_available and self.live:- self.live.stop()- self.live = None-- def _make_layout(self) -> "Layout":- """Create layout"""- layout = Layout()-- # Split into upper part (fixed info) and lower part (logs)- layout.split_column(Layout(name="header", size=10), Layout(name="body"))-- # Split upper part into left (Agents) and right (Stats)- layout["header"].split_row(Layout(name="agents", ratio=1), Layout(name="stats", ratio=2))-- return layout-- def update(self):- """Update interface content"""- if not self.rich_available:- return-- # Update Agents status panel- agents_table = Table(show_header=False, box=None, padding=(0, 1), expand=True)- agents_table.add_column("Status", width=2)- agents_table.add_column("Name")-- for name, status in self.agents_status.items():- if status == "done":- icon = "✓"- style = "green"- elif status == "running":- icon = "●"- style = "yellow"- elif status == "error":- icon = "✗"- style = "red"- else:- icon = " "- style = "dim"-- agents_table.add_row(Text(icon, style=style), Text(name, style=style))-- self.layout["agents"].update(- Panel(- agents_table,- title="📦 Agents Status",- border_style="blue",- padding=(0, 1), # Increase panel padding- )- )-- # Update statistics panel- stats_content = (- f"[bold]{self.stats['model']}[/bold]\n"- f"Calls: {self.stats['calls']}\n"- f"Tokens: {self.stats['tokens']:,} "- f"(Input: {self.stats['input_tokens']:,}, Output: {self.stats['output_tokens']:,})\n"- f"[bold yellow]Cost: ${self.stats['cost']:.6f} USD[/bold yellow]"- )-- self.layout["stats"].update(- Panel(- stats_content,- title="📊 Performance & Cost",- border_style="green",- padding=(0, 1), # Increase panel padding- )- )-- # Update log panel- log_text = "\n".join(self.log_buffer[-self.max_log_lines :])- self.layout["body"].update(- Panel(- log_text,- title="📝 Activity Log",- border_style="white",- padding=(0, 1), # Increase panel padding- )- )-- def set_agent_status(self, agent_name: str, status: str):- """Set Agent status (pending, running, done, error)"""- self.agents_status[agent_name] = status- self.update()-- def update_token_stats(self, summary: dict[str, Any]):- """Update Token statistics"""- self.stats["calls"] = summary.get("total_calls", 0)- self.stats["tokens"] = summary.get("total_tokens", 0)- self.stats["input_tokens"] = summary.get("total_prompt_tokens", 0)- self.stats["output_tokens"] = summary.get("total_completion_tokens", 0)- self.stats["cost"] = summary.get("total_cost_usd", 0.0)-- # Try to get the main model used- by_model = summary.get("by_model", {})- if by_model:- # Find the most called model- top_model = max(by_model.items(), key=lambda x: x[1]["calls"])[0]- self.stats["model"] = top_model-- self.update()-- def log(self, message: str):- """Add log"""- if not self.rich_available:- print(message)- return-- # Simple cleaning- clean_msg = message.rstrip()- if not clean_msg:- return-- # Add timestamp- timestamp = datetime.now().strftime("%H:%M:%S")- formatted_msg = f"[{timestamp}] {clean_msg}"-- self.log_buffer.append(formatted_msg)- # Maintain buffer size- if len(self.log_buffer) > 100:- self.log_buffer = self.log_buffer[-50:]-- self.update()---# Global instance-_display_manager = None---def get_display_manager() -> DisplayManager:- global _display_manager- if _display_manager is None:- _display_manager = DisplayManager()- return _display_managerdiff --git a/deeptutor/agents/solve/utils/json_utils.py b/deeptutor/agents/solve/utils/json_utils.pydeleted file mode 100644index b7dc97f93..000000000--- a/deeptutor/agents/solve/utils/json_utils.py+++ /dev/null@@ -1,97 +0,0 @@-#!/usr/bin/env python-"""-JSON Utils - JSON parsing utilities-Specifically for extracting and parsing JSON data from LLM output,-supports Markdown code block processing and is robust to Python-triple-quoted strings generated by LLMs.-"""--import json-import re-from typing import Any---def _escape_triple_quoted_strings(text: str) -> str:- """- Convert Python triple-quoted strings (\"\"\" ... \"\"\")- into JSON-safe escaped strings.-- This fixes cases where LLMs generate Python code inside JSON,- which would otherwise violate JSON syntax.- """-- def replacer(match: re.Match) -> str:- content = match.group(1)- # json.dumps safely escapes newlines and quotes- return json.dumps(content)-- pattern = re.compile(r'"""([\s\S]*?)"""')- return pattern.sub(replacer, text)---def extract_json_from_text(text: str) -> dict[str, Any] | list[Any] | None:- """- Extract JSON object or array from text.-- Supports:- 1. ```json ... ``` code blocks- 2. ``` ... ``` code blocks- 3. Pure JSON text- 4. JSON containing Python triple-quoted strings (sanitized)-- Args:- text: Original text containing JSON-- Returns:- Parsed JSON object (dict) or array (list),- or None if parsing fails.- """- if not text:- return None-- # 🔧 FIX: sanitize triple-quoted strings before any JSON parsing- text = _escape_triple_quoted_strings(text)-- # 1. Try matching Markdown code blocks- code_block_pattern = re.compile(r"```(?:json)?\s*([\s\S]*?)\s*```")- match = code_block_pattern.search(text)-- if match:- json_str = match.group(1).strip()- try:- return json.loads(json_str)- except json.JSONDecodeError:- pass-- # 2. Try parsing the full text directly- try:- return json.loads(text)- except json.JSONDecodeError:- pass-- # 3. Try extracting outermost JSON object- json_obj_pattern = re.compile(r"\{[\s\S]*\}")- match_obj = json_obj_pattern.search(text)- if match_obj:- try:- return json.loads(match_obj.group(0))- except json.JSONDecodeError:- pass-- # 4. Try extracting outermost JSON array- json_arr_pattern = re.compile(r"\[[\s\S]*\]")- match_arr = json_arr_pattern.search(text)- if match_arr:- try:- return json.loads(match_arr.group(0))- except json.JSONDecodeError:- pass-- return None---def clean_json_string(json_str: str) -> str:- """- Clean JSON string by removing illegal control characters.- """- return re.sub(r"[\x00-\x1f\x7f-\x9f]", "", json_str)diff --git a/deeptutor/agents/solve/utils/token_tracker.py b/deeptutor/agents/solve/utils/token_tracker.pydeleted file mode 100644index ae6ca65c7..000000000--- a/deeptutor/agents/solve/utils/token_tracker.py+++ /dev/null@@ -1,482 +0,0 @@-#!/usr/bin/env python-"""-Token Tracker - LLM Token usage and cost tracking system (Advanced)-Uses tiktoken for precise token counting, supports multiple models and more accurate cost calculation-"""--from dataclasses import asdict, dataclass, field-from datetime import datetime-import json-from typing import Any--# Try importing tiktoken (if available)-try:- import tiktoken-- TIKTOKEN_AVAILABLE = True-except ImportError:- TIKTOKEN_AVAILABLE = False- tiktoken = None--LITELLM_AVAILABLE = False---# Model pricing table (price per 1K tokens, unit: USD)-# Data source: Official pricing from various vendors (November 2024)-MODEL_PRICING = {- # OpenAI GPT Series- "gpt-4o": {"input": 0.0025, "output": 0.010},- "gpt-4o-mini": {"input": 0.00015, "output": 0.0006},- "gpt-4-turbo": {"input": 0.01, "output": 0.03},- "gpt-4": {"input": 0.03, "output": 0.06},- "gpt-4-32k": {"input": 0.06, "output": 0.12},- "gpt-3.5-turbo": {"input": 0.0005, "output": 0.0015},- "gpt-3.5-turbo-16k": {"input": 0.003, "output": 0.004},- # DeepSeek Series- "deepseek-chat": {"input": 0.00014, "output": 0.00028},- "deepseek-coder": {"input": 0.00014, "output": 0.00028},- # Anthropic Claude Series- "claude-3-opus": {"input": 0.015, "output": 0.075},- "claude-3-sonnet": {"input": 0.003, "output": 0.015},- "claude-3-haiku": {"input": 0.00025, "output": 0.00125},- "claude-3-5-sonnet": {"input": 0.003, "output": 0.015},- # Google Gemini Series- "gemini-pro": {"input": 0.0005, "output": 0.0015},- "gemini-1.5-pro": {"input": 0.00125, "output": 0.005},- "gemini-1.5-flash": {"input": 0.000075, "output": 0.0003},-}---def get_tiktoken_encoding(model_name: str):- """- Get tiktoken encoder (for precise token counting)-- Args:- model_name: Model name-- Returns:- tiktoken.Encoding object, returns None if not available- """- if not TIKTOKEN_AVAILABLE:- return None-- try:- # Try getting encoding based on model name- if "gpt-4" in model_name.lower() or "gpt-3.5" in model_name.lower():- return tiktoken.encoding_for_model(model_name)- if "gpt-4o" in model_name.lower():- return tiktoken.encoding_for_model("gpt-4o")- # Default to cl100k_base (encoding for GPT-3.5/GPT-4)- return tiktoken.get_encoding("cl100k_base")- except Exception:- # If fails, use default encoding- return tiktoken.get_encoding("cl100k_base")---def count_tokens_with_tiktoken(text: str, model_name: str) -> int:- """- Precisely calculate token count using tiktoken-- Args:- text: Text to calculate- model_name: Model name (for selecting correct encoding)-- Returns:- Token count- """- if not TIKTOKEN_AVAILABLE:- return 0-- encoding = get_tiktoken_encoding(model_name)- if encoding is None:- return 0-- return len(encoding.encode(text))---def count_tokens_with_litellm(messages: list[dict], model_name: str) -> dict[str, int]:- """Count tokens from messages using tiktoken (litellm removed)."""- if not TIKTOKEN_AVAILABLE:- return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}- try:- text = "\n".join(str(m.get("content", "")) for m in messages)- count = count_tokens_with_tiktoken(text, model_name)- return {"prompt_tokens": count, "completion_tokens": 0, "total_tokens": count}- except Exception:- return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}---def calculate_cost_with_litellm(model: str, prompt_tokens: int, completion_tokens: int) -> float:- """Calculate cost using built-in pricing table."""- return calculate_cost(model, prompt_tokens, completion_tokens)---def get_model_pricing(model_name: str) -> dict[str, float]:- """- Get model pricing information-- Args:- model_name: Model name-- Returns:- {'input': float, 'output': float} Price per 1K tokens (USD)- """- # Try exact match- if model_name in MODEL_PRICING:- return MODEL_PRICING[model_name]-- # Try fuzzy match (handle model names with version numbers)- model_lower = model_name.lower()- for key, pricing in MODEL_PRICING.items():- if key.lower() in model_lower or model_lower in key.lower():- return pricing-- return MODEL_PRICING.get("gpt-4o-mini", {"input": 0.00015, "output": 0.0006})---def calculate_cost(model_name: str, prompt_tokens: int, completion_tokens: int) -> float:- """- Calculate LLM call cost (backward compatibility function)-- Args:- model_name: Model name- prompt_tokens: Number of input tokens- completion_tokens: Number of output tokens-- Returns:- Cost (USD)- """- pricing = get_model_pricing(model_name)-- input_cost = (prompt_tokens / 1000.0) * pricing["input"]- output_cost = (completion_tokens / 1000.0) * pricing["output"]-- return input_cost + output_cost---@dataclass-class TokenUsage:- """Token usage record for a single LLM call"""-- agent_name: str- stage: str- model: str- prompt_tokens: int = 0- completion_tokens: int = 0- total_tokens: int = 0- cost_usd: float = 0.0- timestamp: str = field(default_factory=lambda: datetime.now().isoformat())- # New field- calculation_method: str = "api" # "api", "tiktoken", "litellm", "estimated"-- def to_dict(self) -> dict[str, Any]:- return asdict(self)---class TokenTracker:- """- Token Tracker (Advanced Version)- Supports multiple token counting methods: API response > tiktoken > litellm > estimation- """-- def __init__(self, prefer_tiktoken: bool = True, prefer_litellm: bool = False):- """- Initialize tracker.-- Args:- prefer_tiktoken: If API doesn't return usage, prefer tiktoken calculation (default True)- prefer_litellm: Whether to prefer litellm (requires litellm installation, default False)- """- self.usage_records: list[TokenUsage] = []- self.total_prompt_tokens = 0- self.total_completion_tokens = 0- self.total_tokens = 0- self.total_cost_usd = 0.0- self.prefer_tiktoken = prefer_tiktoken and TIKTOKEN_AVAILABLE- self.prefer_litellm = prefer_litellm and LITELLM_AVAILABLE-- # Callback for real-time updates (e.g., to display_manager)- self._on_usage_added_callback = None-- def set_on_usage_added_callback(self, callback):- """- Set a callback to be called whenever usage is added.- The callback receives the summary dict.-- Args:- callback: Function that takes summary dict as argument- """- self._on_usage_added_callback = callback-- def add_usage(- self,- agent_name: str,- stage: str,- model: str,- prompt_tokens: int = 0,- completion_tokens: int = 0,- token_counts: dict[str, int] | None = None,- # New parameters: for precise calculation- system_prompt: str | None = None,- user_prompt: str | None = None,- response_text: str | None = None,- messages: list[dict] | None = None,- ):- """- Add token usage record (supports multiple calculation methods)-- Args:- agent_name: Agent name- stage: Stage name- model: Model name- prompt_tokens: Input tokens (will be overridden if token_counts is provided)- completion_tokens: Output tokens (will be overridden if token_counts is provided)- token_counts: Optional token count dictionary (from API response, most accurate)- system_prompt: System prompt (for tiktoken calculation)- user_prompt: User prompt (for tiktoken calculation)- response_text: Response text (for tiktoken calculation)- messages: Message list (for litellm calculation)- """- calculation_method = "api"-- # If token_counts is provided (from API response), prioritize using it- if token_counts:- prompt_tokens = token_counts.get("prompt_tokens", prompt_tokens)- completion_tokens = token_counts.get("completion_tokens", completion_tokens)- calculation_method = "api"- # If no API data, try using tiktoken for precise calculation- elif self.prefer_tiktoken and system_prompt and user_prompt:- prompt_tokens = count_tokens_with_tiktoken(system_prompt + "\n" + user_prompt, model)- if response_text:- completion_tokens = count_tokens_with_tiktoken(response_text, model)- calculation_method = "tiktoken"- # If litellm is available and messages are provided- elif self.prefer_litellm and messages:- result = count_tokens_with_litellm(messages, model)- prompt_tokens = result["prompt_tokens"]- completion_tokens = result.get("completion_tokens", completion_tokens)- calculation_method = "litellm"- # If none available, use estimation (fallback)- elif system_prompt and user_prompt:- # Simple estimation- estimated_prompt_tokens = int(- (len(system_prompt.split()) + len(user_prompt.split())) * 1.3- )- prompt_tokens = estimated_prompt_tokens- if response_text:- completion_tokens = int(len(response_text.split()) * 1.3)- calculation_method = "estimated"-- total_tokens = prompt_tokens + completion_tokens-- # Calculate cost (prefer litellm, otherwise manual calculation)- if self.prefer_litellm and LITELLM_AVAILABLE:- cost_usd = calculate_cost_with_litellm(model, prompt_tokens, completion_tokens)- else:- cost_usd = calculate_cost(model, prompt_tokens, completion_tokens)-- # Create usage record- usage = TokenUsage(- agent_name=agent_name,- stage=stage,- model=model,- prompt_tokens=prompt_tokens,- completion_tokens=completion_tokens,- total_tokens=total_tokens,- cost_usd=cost_usd,- calculation_method=calculation_method,- )-- self.usage_records.append(usage)-- # Update totals- self.total_prompt_tokens += prompt_tokens- self.total_completion_tokens += completion_tokens- self.total_tokens += total_tokens- self.total_cost_usd += cost_usd-- # Invoke callback for real-time updates- if self._on_usage_added_callback:- try:- self._on_usage_added_callback(self.get_summary())- except Exception:- pass # Don't let callback errors affect main flow-- def get_summary(self) -> dict[str, Any]:- """- Get usage summary-- Returns:- {- 'total_prompt_tokens': int,- 'total_completion_tokens': int,- 'total_tokens': int,- 'total_cost_usd': float,- 'total_calls': int,- 'by_agent': Dict[str, Dict],- 'by_model': Dict[str, Dict],- 'by_method': Dict[str, Dict], # New: statistics by calculation method- 'tiktoken_available': bool,- 'litellm_available': bool- }- """- by_agent: dict[str, dict[str, Any]] = {}- by_model: dict[str, dict[str, Any]] = {}- by_method: dict[str, dict[str, Any]] = {}-- for usage in self.usage_records:- # Statistics by Agent- if usage.agent_name not in by_agent:- by_agent[usage.agent_name] = {- "prompt_tokens": 0,- "completion_tokens": 0,- "total_tokens": 0,- "cost_usd": 0.0,- "calls": 0,- }- by_agent[usage.agent_name]["prompt_tokens"] += usage.prompt_tokens- by_agent[usage.agent_name]["completion_tokens"] += usage.completion_tokens- by_agent[usage.agent_name]["total_tokens"] += usage.total_tokens- by_agent[usage.agent_name]["cost_usd"] += usage.cost_usd- by_agent[usage.agent_name]["calls"] += 1-- # Statistics by model- if usage.model not in by_model:- by_model[usage.model] = {- "prompt_tokens": 0,- "completion_tokens": 0,- "total_tokens": 0,- "cost_usd": 0.0,- "calls": 0,- }- by_model[usage.model]["prompt_tokens"] += usage.prompt_tokens- by_model[usage.model]["completion_tokens"] += usage.completion_tokens- by_model[usage.model]["total_tokens"] += usage.total_tokens- by_model[usage.model]["cost_usd"] += usage.cost_usd- by_model[usage.model]["calls"] += 1-- # Statistics by calculation method- method = usage.calculation_method- if method not in by_method:- by_method[method] = {- "prompt_tokens": 0,- "completion_tokens": 0,- "total_tokens": 0,- "cost_usd": 0.0,- "calls": 0,- }- by_method[method]["prompt_tokens"] += usage.prompt_tokens- by_method[method]["completion_tokens"] += usage.completion_tokens- by_method[method]["total_tokens"] += usage.total_tokens- by_method[method]["cost_usd"] += usage.cost_usd- by_method[method]["calls"] += 1-- return {- "total_prompt_tokens": self.total_prompt_tokens,- "total_completion_tokens": self.total_completion_tokens,- "total_tokens": self.total_tokens,- "total_cost_usd": self.total_cost_usd,- "total_calls": len(self.usage_records),- "by_agent": by_agent,- "by_model": by_model,- "by_method": by_method, # New: statistics by calculation method- "tiktoken_available": TIKTOKEN_AVAILABLE,- "litellm_available": LITELLM_AVAILABLE,- }-- def format_summary(self) -> str:- """- Format usage summary as readable string-- Returns:- Formatted summary string- """- summary = self.get_summary()-- lines = [- "=" * 70,- "💰 LLM Cost Statistics",- "=" * 70,- f"Total calls: {summary['total_calls']}",- f"Total Tokens: {summary['total_tokens']:,}",- f" - Input: {summary['total_prompt_tokens']:,}",- f" - Output: {summary['total_completion_tokens']:,}",- f"Total cost: ${summary['total_cost_usd']:.6f} USD",- ]-- # If advanced features are used, show tool status and calculation method statistics- if summary.get("tiktoken_available") or summary.get("litellm_available"):- lines.append("")- lines.append("Calculation Tool Status:")- lines.append(- f" - tiktoken: {'✓ Available' if summary['tiktoken_available'] else '✗ Unavailable'}"- )- lines.append(- f" - litellm: {'✓ Available' if summary['litellm_available'] else '✗ Unavailable'}"- )-- if summary.get("by_method"):- lines.append("")- lines.append("Statistics by Calculation Method:")- lines.append("-" * 70)- for method, stats in sorted(summary["by_method"].items()):- method_name = {- "api": "API Response",- "tiktoken": "tiktoken Precise Calculation",- "litellm": "litellm Calculation",- "estimated": "Estimation",- }.get(method, method)- lines.append(f" {method_name}:")- lines.append(f" Calls: {stats['calls']}")- lines.append(f" Tokens: {stats['total_tokens']:,}")- lines.append(f" Cost: ${stats['cost_usd']:.6f} USD")- lines.append("")-- lines.append("Statistics by Agent:")- lines.append("-" * 70)- for agent_name, stats in sorted(summary["by_agent"].items()):- lines.append(f" {agent_name}:")- lines.append(f" Calls: {stats['calls']}")- lines.append(- f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})"- )- lines.append(f" Cost: ${stats['cost_usd']:.6f} USD")- lines.append("")-- lines.append("Statistics by Model:")- lines.append("-" * 70)- for model, stats in sorted(summary["by_model"].items()):- lines.append(f" {model}:")- lines.append(f" Calls: {stats['calls']}")- lines.append(- f" Tokens: {stats['total_tokens']:,} (Input: {stats['prompt_tokens']:,}, Output: {stats['completion_tokens']:,})"- )- lines.append(f" Cost: ${stats['cost_usd']:.6f} USD")- lines.append("")-- lines.append("=" * 70)-- return "\n".join(lines)-- def reset(self):- """Reset all statistics"""- self.usage_records.clear()- self.total_prompt_tokens = 0- self.total_completion_tokens = 0- self.total_tokens = 0- self.total_cost_usd = 0.0-- def save(self, filepath: str):- """- Save usage records to file-- Args:- filepath: Save path- """- data = {- "summary": self.get_summary(),- "records": [usage.to_dict() for usage in self.usage_records],- }-- with open(filepath, "w", encoding="utf-8") as f:- json.dump(data, f, ensure_ascii=False, indent=2)diff --git a/deeptutor/api/routers/solve.py b/deeptutor/api/routers/solve.pydeleted file mode 100644index d60c0cc69..000000000--- a/deeptutor/api/routers/solve.py+++ /dev/null@@ -1,374 +0,0 @@-"""-Solve API Router-================--WebSocket endpoint for real-time problem solving with streaming logs.-"""--import asyncio-import logging-from pathlib import Path-import re-from typing import Any--from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect--from deeptutor.agents.solve import MainSolver, SolverSessionManager-from deeptutor.api.utils.task_id_manager import TaskIDManager-from deeptutor.capabilities.deep_solve import DeepSolveCapability-from deeptutor.logging import bind_log_context, capture_process_logs-from deeptutor.services.config import PROJECT_ROOT, load_config_with_main-from deeptutor.services.llm import get_llm_config-from deeptutor.services.path_service import get_path_service-from deeptutor.services.settings.interface_settings import get_ui_language--config = load_config_with_main("main.yaml", PROJECT_ROOT)-log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")-logger = logging.getLogger(__name__)--router = APIRouter()---def _get_session_manager() -> SolverSessionManager:- return SolverSessionManager()---# =============================================================================-# REST Endpoints for Session Management-# =============================================================================--[email protected]("/solve/sessions")-async def list_solver_sessions(limit: int = 20):- return _get_session_manager().list_sessions(limit=limit, include_messages=False)--[email protected]("/solve/sessions/{session_id}")-async def get_solver_session(session_id: str):- session = _get_session_manager().get_session(session_id)- if not session:- raise HTTPException(status_code=404, detail="Session not found")- return session--[email protected]("/solve/sessions/{session_id}")-async def delete_solver_session(session_id: str):- if _get_session_manager().delete_session(session_id):- return {"status": "deleted", "session_id": session_id}- raise HTTPException(status_code=404, detail="Session not found")---# =============================================================================-# WebSocket Endpoint for Solving-# =============================================================================--[email protected]("/solve")-async def websocket_solve(websocket: WebSocket):- from deeptutor.api.routers.auth import ws_auth_failed, ws_require_auth- from deeptutor.multi_user.context import reset_current_user-- user_token = await ws_require_auth(websocket)- if user_token is ws_auth_failed:- return-- await websocket.accept()-- task_manager = TaskIDManager.get_instance()- connection_closed = asyncio.Event()- log_queue = asyncio.Queue()- pusher_task = None-- async def safe_send_json(data: dict[str, Any]):- if connection_closed.is_set():- return False- try:- await websocket.send_json(data)- return True- except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:- logger.debug(f"WebSocket connection closed: {e}")- connection_closed.set()- return False- except Exception as e:- logger.debug(f"Error sending WebSocket message: {e}")- return False-- async def log_pusher():- while not connection_closed.is_set():- try:- entry = await asyncio.wait_for(log_queue.get(), timeout=0.5)- try:- await websocket.send_json(entry)- except (WebSocketDisconnect, RuntimeError, ConnectionError) as e:- logger.debug(f"WebSocket connection closed in log_pusher: {e}")- connection_closed.set()- log_queue.task_done()- break- except Exception as e:- logger.debug(f"Error sending log entry: {e}")- log_queue.task_done()- except asyncio.TimeoutError:- continue- except Exception as e:- logger.debug(f"Error in log_pusher: {e}")- break-- session_id = None-- try:- data = await websocket.receive_json()- question = data.get("question")- tools = data.get("tools")- enabled_tools = (- list(DeepSolveCapability.manifest.tools_used)- if tools is None- else [str(name) for name in tools]- )- rag_enabled = "rag" in enabled_tools- kb_name = data.get("kb_name", "ai-textbook") if rag_enabled else None- session_id = data.get("session_id")- detailed_answer = data.get("detailed_answer", False)-- if not question:- await websocket.send_json({"type": "error", "content": "Question is required"})- return-- sm = _get_session_manager()-- if session_id:- session = sm.get_session(session_id)- if not session:- session = sm.create_session(- title=question[:50] + ("..." if len(question) > 50 else ""),- kb_name=kb_name or "",- )- session_id = session["session_id"]- else:- session = sm.create_session(- title=question[:50] + ("..." if len(question) > 50 else ""),- kb_name=kb_name or "",- )- session_id = session["session_id"]-- await websocket.send_json({"type": "session", "session_id": session_id})-- sm.add_message(- session_id=session_id,- role="user",- content=question,- )-- task_key = f"solve_{kb_name}_{hash(str(question))}"- task_id = task_manager.generate_task_id("solve", task_key)-- await websocket.send_json({"type": "task_id", "task_id": task_id})-- path_service = get_path_service()- output_base = path_service.get_solve_dir()-- try:- llm_config = get_llm_config()- api_key = llm_config.api_key- base_url = llm_config.base_url- api_version = getattr(llm_config, "api_version", None)- except Exception as e:- logger.error(f"Failed to get LLM config: {e}", exc_info=True)- await websocket.send_json({"type": "error", "content": f"LLM configuration error: {e}"})- return-- ui_language = get_ui_language(default=config.get("system", {}).get("language", "en"))- solver = MainSolver(- kb_name=kb_name,- output_base_dir=str(output_base),- api_key=api_key,- base_url=base_url,- api_version=api_version,- language=ui_language,- enabled_tools=enabled_tools,- disable_planner_retrieve=not (rag_enabled and kb_name),- )-- await solver.ainit()-- logger.info(f"[{task_id}] Solving: {question[:50]}...")-- display_manager = getattr(solver, "display_manager", None)- if display_manager:- original_set_status = display_manager.set_agent_status-- def wrapped_set_status(agent_name: str, status: str):- original_set_status(agent_name, status)- try:- log_queue.put_nowait(- {- "type": "agent_status",- "agent": agent_name,- "status": status,- "all_agents": display_manager.agents_status.copy(),- }- )- except Exception:- pass-- display_manager.set_agent_status = wrapped_set_status-- original_update_stats = display_manager.update_token_stats-- def wrapped_update_stats(summary: dict[str, Any]):- original_update_stats(summary)- try:- stats_copy = display_manager.stats.copy()- logger.debug(- f"Sending token_stats: model={stats_copy.get('model')}, calls={stats_copy.get('calls')}, cost={stats_copy.get('cost')}"- )- log_queue.put_nowait({"type": "token_stats", "stats": stats_copy})- except Exception as e:- logger.debug(f"Failed to send token_stats: {e}")-- display_manager.update_token_stats = wrapped_update_stats-- if hasattr(solver, "token_tracker") and solver.token_tracker:- solver.token_tracker.set_on_usage_added_callback(wrapped_update_stats)-- def send_progress_update(stage: str, progress: dict[str, Any]):- try:- log_queue.put_nowait({"type": "progress", "stage": stage, "progress": progress})- except Exception:- pass-- solver._send_progress_update = send_progress_update-- pusher_task = asyncio.create_task(log_pusher())-- loop = asyncio.get_running_loop()-- def emit_process_log(event):- loop.call_soon_threadsafe(log_queue.put_nowait, event.to_dict())-- with bind_log_context(- task_id=task_id,- session_id=session_id,- capability="deep_solve",- sink="ui",- ):- process_logs = capture_process_logs(emit_process_log, task_id=task_id)- with process_logs:- await safe_send_json({"type": "status", "content": "started"})-- if display_manager:- await safe_send_json(- {- "type": "agent_status",- "agent": "all",- "status": "initial",- "all_agents": display_manager.agents_status.copy(),- }- )- await safe_send_json(- {"type": "token_stats", "stats": display_manager.stats.copy()}- )-- logger.info(f"[{task_id}] Solving started")-- result = await solver.solve(question, verbose=True, detailed=detailed_answer)-- logger.info(f"[{task_id}] Solving completed")- task_manager.update_task_status(task_id, "completed")-- final_answer = result.get("final_answer", "")- output_dir_str = result.get("output_dir", "")-- if output_dir_str and final_answer:- try:- output_dir = Path(output_dir_str)-- if not output_dir.is_absolute():- output_dir = output_dir.resolve()-- path_str = str(output_dir).replace("\\", "/")- parts = path_str.split("/")-- if "user" in parts:- idx = parts.index("user")- rel_path = "/".join(parts[idx + 1 :])- base_url = f"/api/outputs/{rel_path}"-- pattern = r"\]\(artifacts/([^)]+)\)"- replacement = rf"]({base_url}/artifacts/\1)"- final_answer = re.sub(pattern, replacement, final_answer)- except Exception as e:- logger.debug(f"Error processing image paths: {e}")-- if display_manager:- final_agent_status = dict.fromkeys(display_manager.agents_status.keys(), "done")- await safe_send_json(- {- "type": "agent_status",- "agent": "all",- "status": "complete",- "all_agents": final_agent_status,- }- )-- dir_name = ""- if output_dir_str:- parts = output_dir_str.replace("\\", "/").split("/")- dir_name = parts[-1] if parts else ""-- final_res = {- "type": "result",- "session_id": session_id,- "final_answer": final_answer,- "output_dir": output_dir_str,- "output_dir_name": dir_name,- "metadata": result.get("metadata"),- }- await safe_send_json(final_res)-- if session_id:- sm.add_message(- session_id=session_id,- role="assistant",- content=final_answer,- output_dir=dir_name,- )- if display_manager:- sm.update_token_stats(- session_id=session_id,- token_stats=display_manager.stats.copy(),- )-- except Exception as e:- connection_closed.set()- await safe_send_json({"type": "error", "content": str(e)})- logger.error(f"[{task_id if 'task_id' in locals() else 'unknown'}] Solving failed: {e}")- if "task_id" in locals():- task_manager.update_task_status(task_id, "error", error=str(e))- finally:- connection_closed.set()- if pusher_task:- pusher_task.cancel()- try:- await pusher_task- except asyncio.CancelledError:- pass- except Exception as e:- logger.debug(f"Error waiting for pusher task: {e}")-- try:- if hasattr(websocket, "client_state"):- state = websocket.client_state- if hasattr(state, "name") and state.name != "DISCONNECTED":- await websocket.close()- else:- await websocket.close()- except (WebSocketDisconnect, RuntimeError, ConnectionError):- pass- except Exception as e:- logger.debug(f"Error closing WebSocket: {e}")-- if user_token is not None:- try:- reset_current_user(user_token)- except Exception:- passdiff --git a/deeptutor/capabilities/deep_question.py b/deeptutor/capabilities/deep_question.pyindex 4a2c9b2ec..26d3e747f 100644--- a/deeptutor/capabilities/deep_question.py+++ b/deeptutor/capabilities/deep_question.py@@ -1,19 +1,23 @@-"""-Deep Question Capability-========================+"""Deep Question Capability.++Routes one user turn through the right quiz-generation path:-Multi-agent question generation pipeline: Idea -> Evaluate -> Generate -> Validate.-Wraps the existing ``AgentCoordinator``.+* followup — single-call ``FollowupAgent`` reply about one prior question.+* custom mode — new ``QuestionPipeline`` (explore → plan → per-question loop).+* mimic mode — same pipeline, but PDF parsing produces the templates+ and ``templates_override`` skips explore + plan."""from __future__ import annotationsimport base64-import reimport tempfilefrom typing import Any+from deeptutor.capabilities._i18n import StatusI18n+from deeptutor.capabilities._shared import emit_capability_resultfrom deeptutor.capabilities.request_contracts import get_capability_request_schema+from deeptutor.core.agentic.usage import UsageTrackerfrom deeptutor.core.capability_protocol import BaseCapability, CapabilityManifestfrom deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBus@@ -31,20 +35,14 @@ class DeepQuestionCapability(BaseCapability):)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:- from deeptutor.agents.question.coordinator import AgentCoordinator- from deeptutor.capabilities._answer_now import extract_answer_now_contextfrom deeptutor.services.llm.config import get_llm_configfrom deeptutor.services.path_service import get_path_service- answer_now_payload = extract_answer_now_context(context)- if answer_now_payload is not None:- await self._run_answer_now(context, stream, answer_now_payload)- return-llm_config = get_llm_config()kb_name = context.knowledge_bases[0] if context.knowledge_bases else Noneturn_id = str(context.metadata.get("turn_id", "") or context.session_id or "deep-question")output_dir = get_path_service().get_task_workspace("deep_question", turn_id)+ i18n = StatusI18n(self.name, context.language)overrides = context.config_overridesfollowup_question_context = context.metadata.get("question_followup_context", {}) or {}@@ -53,13 +51,15 @@ class DeepQuestionCapability(BaseCapability):):from deeptutor.agents.question.agents.followup_agent import FollowupAgent+ usage = UsageTracker(model=getattr(llm_config, "model", None))agent = FollowupAgent(language=context.language,api_key=llm_config.api_key,base_url=llm_config.base_url,api_version=llm_config.api_version,+ token_tracker=usage,)- agent.set_trace_callback(self._build_trace_bridge(stream))+ agent.set_trace_callback(self._build_trace_bridge(stream, i18n=i18n))async with stream.stage("generation", source=self.name):answer = await agent.process(user_message=context.user_message,@@ -76,297 +76,120 @@ class DeepQuestionCapability(BaseCapability):"mode": "followup","question_id": followup_question_context.get("question_id", ""),}- cost_meta = self._collect_cost_summary("question")- if cost_meta:- followup_payload["metadata"] = {"cost_summary": cost_meta}- await stream.result(followup_payload, source=self.name)+ await emit_capability_result(+ stream, followup_payload, source=self.name, usage=usage+ )returnmode = str(overrides.get("mode", "custom") or "custom").strip().lower()topic = str(overrides.get("topic") or context.user_message or "").strip()num_questions = int(overrides.get("num_questions", 1) or 1)difficulty = str(overrides.get("difficulty", "") or "")- question_type = str(overrides.get("question_type", "") or "")- preference = str(overrides.get("preference", "") or "")- history_context = str(context.metadata.get("conversation_context_text", "") or "").strip()- enabled_tools = set(- self.manifest.tools_used if context.enabled_tools is None else context.enabled_tools+ raw_types = overrides.get("question_types") or []+ question_types = list(raw_types) if isinstance(raw_types, list) else []+ raw_counts = overrides.get("per_type_counts") or {}+ per_type_counts = (+ {str(k): int(v) for k, v in raw_counts.items() if isinstance(v, int) and v > 0}+ if isinstance(raw_counts, dict)+ else {})- # rag is gated on attached knowledge bases, not on a separate flag.- rag_available = bool(kb_name)- tool_flags_override = {- "rag": rag_available,- "web_search": "web_search" in enabled_tools,- "code_execution": "code_execution" in enabled_tools,- }-- coordinator = AgentCoordinator(- api_key=llm_config.api_key,- base_url=llm_config.base_url,- api_version=llm_config.api_version,- kb_name=kb_name,- language=context.language,- output_dir=str(output_dir),- tool_flags_override=tool_flags_override,- enable_idea_rag=rag_available,- )-- _trace_bridge = self._build_trace_bridge(stream)+ history_context = str(context.metadata.get("conversation_context_text", "") or "").strip()- # Bridge ws_callback to StreamBus- async def _ws_bridge(update: dict[str, Any]) -> None:- update_type = update.get("type", "")- inner = str(update.get("stage", "") or "")- if update_type == "result" or inner in {"generation", "complete"}:- stage = "generation"- elif inner in {"parsing", "extracting", "ideation"}:- stage = "ideation"- else:- stage = "generation" if update_type == "question_update" else "ideation"- message = self._format_bridge_message(update_type, update)- metadata = {- key: value for key, value in update.items() if key not in {"type", "message"}- }- if "question_id" in update:- metadata.setdefault("trace_id", str(update.get("question_id")))- metadata.setdefault(- "label",- f"Generate {self._humanize_question_id(update.get('question_id'))}",- )- elif "batch" in update:- metadata.setdefault("trace_id", f"batch-{update.get('batch')}")- metadata.setdefault("label", f"Batch {update.get('batch')}")- metadata["update_type"] = update_type- metadata.setdefault("phase", stage)- await stream.progress(- message=message,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(metadata, {"trace_kind": "progress"}),+ if mode != "mimic":+ # New custom-mode pipeline: explore → plan → per-question quiz loop.+ # The pipeline owns its own stream.content / stream.result emission;+ # nothing here to render afterwards.+ from deeptutor.agents.question.history import load_session_quiz_history+ from deeptutor.agents.question.pipeline import QuestionPipeline+ from deeptutor.agents.question.request_config import (+ build_question_runtime_config,)+ from deeptutor.services.config import load_config_with_main- coordinator.set_ws_callback(_ws_bridge)- if hasattr(coordinator, "set_trace_callback"):- coordinator.set_trace_callback(_trace_bridge)-- if mode == "mimic":- result = await self._run_mimic_mode(- coordinator=coordinator,- context=context,- stream=stream,- overrides=overrides,- )- if not result:- return- else:if not topic:await stream.error(- "Topic is required for custom question generation.", source=self.name+ i18n.t(+ "topic_required",+ "Topic is required for custom question generation.",+ ),+ source=self.name,)return- async with stream.stage("ideation", source=self.name):- await stream.thinking(- "Generating question templates...", source=self.name, stage="ideation"- )-- result = await coordinator.generate_from_topic(- user_topic=topic,- preference=preference,+ quiz_history = await load_session_quiz_history(context.session_id or "")+ runtime_config = build_question_runtime_config(+ base_config=load_config_with_main("main.yaml"),+ )+ pipeline = QuestionPipeline(+ language=context.language,+ kb_name=kb_name,+ enabled_tools=list(context.enabled_tools or []),+ runtime_config=runtime_config,+ )+ await pipeline.run(+ context=context,+ user_message=topic,num_questions=num_questions,difficulty=difficulty,- question_type=question_type,- history_context=history_context,+ question_types=question_types,+ per_type_counts=per_type_counts,+ conversation_context=history_context,attachments=context.attachments,+ quiz_history=quiz_history,+ stream=stream,)+ return- content = self._render_summary_markdown(result)- if content:- await stream.content(content, source=self.name, stage="generation")-- result_payload: dict[str, Any] = {- "response": content or "No questions generated.",- "summary": result,- "mode": mode,- }- cost_meta = self._collect_cost_summary("question")- if cost_meta:- result_payload["metadata"] = {"cost_summary": cost_meta}- await stream.result(result_payload, source=self.name)+ # Mimic mode — also runs through QuestionPipeline, but parses the+ # exam paper into templates first and passes them via+ # ``templates_override`` so explore + plan are skipped.+ await self._run_mimic_mode(+ context=context,+ stream=stream,+ kb_name=kb_name,+ output_dir=output_dir,+ overrides=overrides,+ history_context=history_context,+ num_questions=num_questions,+ i18n=i18n,+ )- async def _run_answer_now(+ async def _run_mimic_mode(self,+ *,context: UnifiedContext,stream: StreamBus,- payload: dict[str, Any],+ kb_name: str | None,+ output_dir,+ overrides: dict[str, Any],+ history_context: str,+ num_questions: int,+ i18n: StatusI18n | None = None,) -> None:- """- Fast-path for ``deep_question``: skip ideation/template generation- and synthesise a complete quiz in one structured LLM call.+ """Resolve an exam paper → templates → ``QuestionPipeline.run`` with+ ``templates_override``. No legacy AgentCoordinator involvement.- The result envelope mirrors the standard pipeline (``summary.results``- with ``qa_pair`` items) so the existing ``QuizViewer`` renders it- without changes.- """+ Three input shapes:- from deeptutor.capabilities._answer_now import (- build_answer_now_trace_metadata,- format_trace_summary,- join_chunks,- labeled_block,- load_answer_now_prompts,- make_skip_notice,- stream_synthesis,- )-- original = str(payload.get("original_user_message") or context.user_message).strip()- partial = str(payload.get("partial_response") or "").strip()- trace_summary = format_trace_summary(payload.get("events"), language=context.language)-- overrides = context.config_overrides- topic = str(overrides.get("topic") or original).strip() or original- num_questions = max(1, int(overrides.get("num_questions", 1) or 1))- difficulty = str(overrides.get("difficulty", "") or "auto")- question_type = str(overrides.get("question_type", "") or "auto")-- prompts = load_answer_now_prompts("question", context.language)- system_prompt = str(prompts.get("system", "")).strip()- user_prompt = str(prompts.get("user_template", "")).format(- topic=topic,- num_questions=num_questions,- question_type=question_type,- difficulty=difficulty,- current_draft=labeled_block("Current Draft", partial),- execution_trace=labeled_block("Execution Trace", trace_summary),- )-- trace_meta = build_answer_now_trace_metadata(- capability=self.name, phase="generation", label="Answer now"+ * Uploaded PDF attachment → write to tmpfile, parse with MinerU+ * Server-side parsed directory → skip parsing, just extract questions+ * ``[Attached Documents]`` in → no paper available; fall back to+ the user_message text custom-mode pipeline with a+ "mimic the attached source" hint+ prefixed onto the user_message+ """+ from deeptutor.agents.question.history import load_session_quiz_history+ from deeptutor.agents.question.mimic_source import (+ parse_exam_paper_to_templates,)-- notice = make_skip_notice(- capability=self.name,- language=context.language,- stages_skipped=["ideation"],+ from deeptutor.agents.question.pipeline import QuestionPipeline+ from deeptutor.agents.question.request_config import (+ build_question_runtime_config,)+ from deeptutor.services.config import load_config_with_main- chunks: list[str] = []- async with stream.stage("generation", source=self.name, metadata=trace_meta):- async for chunk in stream_synthesis(- stream=stream,- source=self.name,- stage="generation",- trace_meta=trace_meta,- system_prompt=system_prompt,- user_prompt=user_prompt,- max_tokens=2400,- push_content=False,- response_format={"type": "json_object"},- ):- chunks.append(chunk)-- raw = join_chunks(chunks).strip()- questions = self._parse_answer_now_json(raw, num_questions=num_questions)-- results = [- {- "qa_pair": {- "question_id": q.get("question_id") or f"q_{idx + 1}",- "question": q.get("question", ""),- "question_type": q.get("question_type", "written"),- "options": q.get("options") or {},- "correct_answer": q.get("correct_answer", ""),- "explanation": q.get("explanation", ""),- "difficulty": q.get("difficulty", ""),- "concentration": q.get("concentration", ""),- },- "metadata": {"answer_now": True},- }- for idx, q in enumerate(questions)- ]- summary = {"results": results, "mode": "answer_now"}-- markdown = self._render_summary_markdown(summary)- body = (notice + "\n\n" + markdown).strip() if notice else markdown- if body:- await stream.content(body, source=self.name, stage="generation")-- result_payload: dict[str, Any] = {- "response": body or "No questions generated.",- "summary": summary,- "mode": "answer_now",- "metadata": {"answer_now": True},- }- cost_meta = self._collect_cost_summary("question")- if cost_meta:- result_payload["metadata"]["cost_summary"] = cost_meta- await stream.result(result_payload, source=self.name)-- @staticmethod- def _parse_answer_now_json(raw: str, *, num_questions: int) -> list[dict[str, Any]]:- """Tolerantly parse the model's JSON answer-now payload.-- We accept either ``{"questions": [...]}`` or a bare list. Anything- unparseable yields a single placeholder so the UI doesn't crash.- """- import json-- if not raw:- return []- text = raw.strip()- # Some models wrap JSON in fences even when response_format=json_object- # is requested; strip a single fenced block defensively.- if text.startswith("```"):- text = text.strip("`")- if "\n" in text:- text = text.split("\n", 1)[1]- if text.endswith("```"):- text = text[:-3]- text = text.strip()- try:- parsed = json.loads(text)- except json.JSONDecodeError:- return [- {- "question_id": "q_1",- "question": raw[:500],- "question_type": "written",- "correct_answer": "",- "explanation": "Model returned unparseable JSON during answer-now.",- }- ]-- if isinstance(parsed, dict):- items = parsed.get("questions")- else:- items = parsed- if not isinstance(items, list):- return []- cleaned = [item for item in items if isinstance(item, dict)]- return cleaned[: max(num_questions, 1)] if cleaned else []-- @staticmethod- def _collect_cost_summary(module_name: str) -> dict[str, Any] | None:- from deeptutor.agents.base_agent import BaseAgent-- stats = BaseAgent._shared_stats.get(module_name)- if not stats or not stats.calls:- return None- s = stats.get_summary()- stats.reset()- return {- "total_cost_usd": s.get("cost_usd", 0),- "total_tokens": s.get("total_tokens", 0),- "total_calls": s.get("calls", 0),- }-- async def _run_mimic_mode(- self,- coordinator,- context: UnifiedContext,- stream: StreamBus,- overrides: dict[str, Any],- ) -> dict[str, Any]:+ if i18n is None:+ i18n = StatusI18n(self.name, context.language)paper_path = str(overrides.get("paper_path", "") or "").strip()max_questions = int(overrides.get("max_questions", 10) or 10)pdf_attachment = next(@@ -380,168 +203,105 @@ class DeepQuestionCapability(BaseCapability):None,)+ runtime_config = build_question_runtime_config(+ base_config=load_config_with_main("main.yaml"),+ )+ pipeline = QuestionPipeline(+ language=context.language,+ kb_name=kb_name,+ enabled_tools=list(context.enabled_tools or []),+ runtime_config=runtime_config,+ )+ quiz_history = await load_session_quiz_history(context.session_id or "")++ async def _emit_parse_notice(message: str) -> None:+ async with stream.stage("exploring", source=self.name):+ await stream.thinking(message, source=self.name, stage="exploring")+if pdf_attachment and pdf_attachment.base64:- async with stream.stage("ideation", source=self.name):- await stream.thinking(+ await _emit_parse_notice(+ i18n.t(+ "parsing_uploaded","Parsing uploaded exam paper and extracting templates...",- source=self.name,- stage="ideation",)-+ )with tempfile.NamedTemporaryFile(suffix=".pdf", delete=True) as temp_pdf:temp_pdf.write(base64.b64decode(pdf_attachment.base64))temp_pdf.flush()- return await coordinator.generate_from_exam(- exam_paper_path=temp_pdf.name,+ templates, _ = await parse_exam_paper_to_templates(+ temp_pdf.name,max_questions=max_questions,paper_mode="upload",- history_context=str(- context.metadata.get("conversation_context_text", "") or ""- ).strip(),+ output_dir=output_dir,)+ await pipeline.run(+ context=context,+ user_message=context.user_message,+ num_questions=len(templates) or num_questions,+ difficulty="",+ conversation_context=history_context,+ attachments=context.attachments,+ quiz_history=quiz_history,+ templates_override=templates,+ stream=stream,+ )+ returnif paper_path:- async with stream.stage("ideation", source=self.name):- await stream.thinking(+ await _emit_parse_notice(+ i18n.t(+ "parsing_directory","Loading parsed exam paper and extracting templates...",- source=self.name,- stage="ideation",)- return await coordinator.generate_from_exam(- exam_paper_path=paper_path,+ )+ templates, _ = await parse_exam_paper_to_templates(+ paper_path,max_questions=max_questions,paper_mode="parsed",- history_context=str(- context.metadata.get("conversation_context_text", "") or ""- ).strip(),+ output_dir=output_dir,)+ await pipeline.run(+ context=context,+ user_message=context.user_message,+ num_questions=len(templates) or num_questions,+ difficulty="",+ conversation_context=history_context,+ attachments=context.attachments,+ quiz_history=quiz_history,+ templates_override=templates,+ stream=stream,+ )+ returnif "[Attached Documents]" in context.user_message:- async with stream.stage("ideation", source=self.name):- await stream.thinking(- "Using extracted attachment text as the quiz source...",- source=self.name,- stage="ideation",- )- return await coordinator.generate_from_topic(- user_topic=context.user_message,- preference=(- "Mimic the attached source document as closely as possible: "- "style, difficulty, structure, and assessed concepts."- ),+ # No paper available — degrade to custom-mode generation but+ # bias the pipeline toward shadowing the attached source by+ # prefixing the user message with an explicit instruction.+ mimic_hint = (+ "[Mimic the attached source document as closely as possible: "+ "style, difficulty, structure, and assessed concepts.]\n\n"+ )+ await pipeline.run(+ context=context,+ user_message=mimic_hint + context.user_message,num_questions=max_questions,- history_context=str(- context.metadata.get("conversation_context_text", "") or ""- ).strip(),+ difficulty="",+ conversation_context=history_context,attachments=context.attachments,+ quiz_history=quiz_history,+ stream=stream,)+ returnawait stream.error(- "Mimic mode requires either an uploaded PDF or a parsed exam directory.",+ i18n.t(+ "mimic_needs_paper",+ "Mimic mode requires either an uploaded PDF or a parsed exam directory.",+ ),source=self.name,)- return {}- @staticmethod- def _format_bridge_message(update_type: str, update: dict[str, Any]) -> str:- """Build a human-readable progress line from a coordinator ws_callback."""- if update_type == "progress":- stage = update.get("stage", "")- status = update.get("status", "")- cur = update.get("current", "")- tot = update.get("total", "")- qid = update.get("question_id", "")- batch = update.get("batch", "")- parts = [f"[{stage}]" if stage else ""]- if status:- parts.append(status)- if cur != "" and tot:- parts.append(f"({cur}/{tot})")- if batch:- parts.append(f"batch={batch}")- if qid:- parts.append(f"question={qid}")- return " ".join(p for p in parts if p) or update_type-- if update_type == "templates_ready":- count = update.get("count", 0)- batch = update.get("batch", "")- templates = update.get("templates", [])- prefix = (- f"Templates ready (batch {batch}): {count}"- if batch- else f"Templates ready: {count}"- )- lines = [prefix]- for t in templates:- if isinstance(t, dict):- lines.append(- f" [{t.get('question_id', '')}] {t.get('concentration', '')[:80]} "- f"({t.get('question_type', '')}/{t.get('difficulty', '')})"- )- return "\n".join(lines)-- if update_type == "question_update":- qid = DeepQuestionCapability._humanize_question_id(update.get("question_id", ""))- current = update.get("current", "")- total = update.get("total", "")- return f"Generating {qid} ({current}/{total})"-- if update_type == "result":- qid = DeepQuestionCapability._humanize_question_id(update.get("question_id", ""))- idx = update.get("index", "")- q = update.get("question", {})- qt = q.get("question_type", "") if isinstance(q, dict) else ""- diff = q.get("difficulty", "") if isinstance(q, dict) else ""- success = update.get("success", True)- ordinal = ""- if isinstance(idx, int):- ordinal = f"#{idx + 1}, "- return f"{qid} done ({ordinal}{qt}/{diff}, success={success})"-- return update.get("message", update_type)-- @staticmethod- def _humanize_question_id(question_id: Any) -> str:- raw = str(question_id or "").strip()- match = re.fullmatch(r"q_(\d+)", raw.lower())- if match:- return f"Question {match.group(1)}"- return raw or "Question"-- def _render_summary_markdown(self, summary: dict[str, Any]) -> str:- results = summary.get("results", []) if isinstance(summary, dict) else []- if not results:- return ""-- lines: list[str] = []- for idx, item in enumerate(results, 1):- qa_pair = item.get("qa_pair", {}) if isinstance(item, dict) else {}- question = qa_pair.get("question", "")- if not question:- continue-- lines.append(f"### Question {idx}\n")- lines.append(question)-- options = qa_pair.get("options", {})- if isinstance(options, dict) and options:- for key, value in options.items():- lines.append(f"- {key}. {value}")-- answer = qa_pair.get("correct_answer", "")- if answer:- lines.append(f"\n**Answer:** {answer}")-- explanation = qa_pair.get("explanation", "")- if explanation:- lines.append(f"\n**Explanation:** {explanation}")-- lines.append("")-- return "\n".join(lines).strip()-- def _build_trace_bridge(self, stream: StreamBus):+ def _build_trace_bridge(self, stream: StreamBus, i18n: StatusI18n | None = None):async def _trace_bridge(update: dict[str, Any]) -> None:event = str(update.get("event", "") or "")stage = str(update.get("phase") or update.get("stage") or "generation")@@ -604,8 +364,13 @@ class DeepQuestionCapability(BaseCapability):)returnif state == "error":+ fallback = (+ i18n.t("llm_call_failed", "LLM call failed.")+ if i18n is not None+ else "LLM call failed."+ )await stream.error(- str(update.get("response", "") or "LLM call failed."),+ str(update.get("response", "") or fallback),source=self.name,stage=stage,metadata=merge_trace_metadata(diff --git a/deeptutor/capabilities/deep_research.py b/deeptutor/capabilities/deep_research.pyindex 4b0468195..70323de59 100644--- a/deeptutor/capabilities/deep_research.py+++ b/deeptutor/capabilities/deep_research.py@@ -1,27 +1,43 @@-"""-Deep Research Capability-========================--Multi-agent deep research with report generation.-Wraps ``ResearchPipeline`` as a first-class built-in capability.+"""Deep Research capability — agentic-engine-based deep research.++Thin shim that delegates to :class:`ResearchPipeline`. All orchestration+— rephrase (mini agentic loop with ``ask_user``), decompose, per-block+research loops with ``THINK`` / ``TOOL`` / ``APPEND`` / ``FINISH``,+queue scheduler, and iterative reporting — lives in the pipeline+module. The capability only handles:++* request-config validation,+* the outline-preview two-stage flow (first call returns sub-topics+ the user edits / confirms; second call drives Phase 3+4 with the+ confirmed outline).++Tool composition is delegated to the shared+:mod:`deeptutor.agents._shared.tool_composition` policy — same as chat,+so the user's composer toggles + the attached KB drive what the per-block+research loop actually has access to. There is no separate "sources"+knob."""from __future__ import annotations-import asynciofrom typing import Any+from deeptutor.agents.research.pipeline import ResearchPipeline, SubTopicItem+from deeptutor.agents.research.request_config import (+ build_research_runtime_config,+ validate_research_request_config,+)from deeptutor.capabilities.request_contracts import get_capability_request_schemafrom deeptutor.core.capability_protocol import BaseCapability, CapabilityManifestfrom deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBus-from deeptutor.core.trace import derive_trace_metadata, merge_trace_metadata, new_call_id+from deeptutor.services.config import load_config_with_mainclass DeepResearchCapability(BaseCapability):manifest = CapabilityManifest(name="deep_research",- description="Multi-agent deep research with report generation.",+ description="Agentic-loop deep research with iterative report generation.",stages=["rephrasing", "decomposing", "researching", "reporting"],tools_used=["rag", "web_search", "paper_search", "code_execution"],cli_aliases=["research"],@@ -29,488 +45,55 @@ class DeepResearchCapability(BaseCapability):)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:- from deeptutor.agents.research.request_config import (- build_research_runtime_config,- validate_research_request_config,- )- from deeptutor.agents.research.research_pipeline import ResearchPipeline- from deeptutor.capabilities._answer_now import extract_answer_now_context- from deeptutor.services.config import load_config_with_main- from deeptutor.services.llm.config import get_llm_config-- answer_now_payload = extract_answer_now_context(context)- if answer_now_payload is not None:- await self._run_answer_now(context, stream, answer_now_payload)- return-- llm_config = get_llm_config()kb_name = context.knowledge_bases[0] if context.knowledge_bases else None- topic = context.user_message- enabled_tools = set(- self.manifest.tools_used if context.enabled_tools is None else context.enabled_tools- )request_config = validate_research_request_config(context.config_overrides)- # Consistency normalization: if "kb" is selected as a research source- # but no knowledge base is actually attached, drop "kb" from the- # effective sources. This avoids any code path falling through to a- # placeholder KB at the pipeline layer. If after the downgrade no- # source is left at all, surface a clear error to the user.- if "kb" in request_config.sources and not kb_name:- request_config = request_config.model_copy(- update={- "sources": [src for src in request_config.sources if src != "kb"],- }- )- await stream.progress(- message=(- "Knowledge base source was selected, but no knowledge "- "base is attached; KB retrieval is disabled for this "- "research run."- ),- source=self.name,- stage="rephrasing",- metadata={"trace_kind": "warning", "reason": "kb_without_kb_name"},- )- if not request_config.sources:- await stream.error(- "Deep research requires at least one source. Please "- "either attach a knowledge base or enable web/papers "- "sources.",- source=self.name,- )- return-- config = build_research_runtime_config(+ enabled_tools = list(context.enabled_tools or [])+ runtime_config = build_research_runtime_config(base_config=load_config_with_main("main.yaml"),request_config=request_config,- enabled_tools=enabled_tools,kb_name=kb_name,)- def _normalize_stage(stage: str) -> str:- mapping = {- "rephrase": "rephrasing",- "check_satisfaction": "rephrasing",- "decompose": "decomposing",- "decompose_no_rag": "decomposing",- "check_sufficiency": "researching",- "generate_query_plan": "researching",- "plan_next_step": "researching",- "generate_summary": "researching",- "deduplicate": "reporting",- "generate_outline": "reporting",- "write_introduction": "reporting",- "write_section_body": "reporting",- "write_conclusion": "reporting",- "write_full_report": "reporting",- }- return mapping.get(stage, stage or "researching")-- def _stage_card(stage: str, status: str = "") -> str:- if stage in {"rephrasing"} or status.startswith(("planning_started", "rephrase")):- return "understand"- if stage in {"decomposing"} or status.startswith(("decompose", "queue_")):- return "decompose"- if stage == "reporting":- return "result"- return "evidence"-- def _progress_message(data: dict[str, Any]) -> str:- status = str(data.get("status") or data.get("type") or "").strip()- pretty_map = {- "planning_started": "Clarifying the research question",- "rephrase_completed": "Refined the research focus",- "rephrase_skipped": "Using the original topic directly",- "decompose_started": "Breaking the topic into subtopics",- "decompose_completed": "Prepared subtopics for investigation",- "queue_seeded": "Queued a research subtopic",- "researching_started": "Searching for evidence",- "block_started": "Investigating a subtopic",- "block_completed": "Completed one evidence block",- "researching_completed": "Evidence gathering finished",- "reporting_started": "Drafting the final result",- "reporting_completed": "Final result is ready",- }- return pretty_map.get(- status,- str(data.get("message") or status or data.get("type") or "").strip(),- )-- async def _emit_progress(data: dict[str, Any]) -> None:- raw_stage = str(data.get("stage") or "researching")- stage = _normalize_stage(raw_stage)- status = str(data.get("status") or data.get("type") or "")- message = _progress_message(data)- if not message:- return- await stream.progress(- message=message,- source=self.name,- stage=stage,- metadata={- key: value- for key, value in data.items()- if key not in {"message", "status", "type", "stage"}- }- | {- "research_stage_card": _stage_card(stage, status),- "research_status": status,- },- )-- def _progress_cb(data: dict[str, Any]) -> None:- try:- loop = asyncio.get_running_loop()- except RuntimeError:- return- loop.create_task(_emit_progress(data))-- def _label_from_update(update: dict[str, Any], stage: str) -> str:- agent_name = str(update.get("agent_name") or "")- raw_stage = str(update.get("stage") or "")- block_id = str(update.get("block_id") or "")- iteration = update.get("iteration")-- if agent_name == "rephrase_agent":- return "Rephrase topic"- if agent_name == "decompose_agent":- return "Decompose topic"- if agent_name == "note_agent":- return "Summarize evidence"- if stage == "reporting":- if raw_stage == "generate_outline":- return "Generate outline"- if raw_stage.startswith("write_"):- return "Write report"- return "Reporting"- if block_id and isinstance(iteration, int):- return f"{block_id.replace('_', ' ').title()} · Round {iteration}"- if block_id:- return block_id.replace("_", " ").title()- return "Research step"-- async def _trace_cb(update: dict[str, Any]) -> None:- event = str(update.get("event", "") or "")- stage = _normalize_stage(- str(update.get("phase") or update.get("stage") or "researching")- )- raw_stage = str(update.get("stage") or "")- base_metadata = {- key: value- for key, value in update.items()- if key- not in {"event", "state", "response", "chunk", "result", "tool_name", "tool_args"}- }- call_id = str(base_metadata.get("call_id") or new_call_id("research"))- base_metadata.setdefault("call_id", call_id)- base_metadata.setdefault("phase", stage)- base_metadata.setdefault("label", _label_from_update(update, stage))- base_metadata.setdefault("research_stage_card", _stage_card(stage, raw_stage))-- if event == "llm_call":- state = str(update.get("state", "running"))- label = str(base_metadata.get("label", "") or "")- if state == "running":- await stream.progress(- message=label,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "call_status", "call_state": "running"},- ),- )- return- if state == "streaming":- chunk = str(update.get("chunk", "") or "")- if chunk:- await stream.thinking(- chunk,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "llm_chunk"},- ),- )- return- if state == "complete":- was_streaming = update.get("streaming", False)- if not was_streaming:- response = str(update.get("response", "") or "")- if response:- await stream.thinking(- response,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "llm_output"},- ),- )- await stream.progress(- message=label,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "call_status", "call_state": "complete"},- ),- )- return- if state == "error":- await stream.error(- str(update.get("response", "") or "LLM call failed."),- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "call_status", "call_state": "error"},- ),- )- return-- if event == "tool_call":- await stream.tool_call(- tool_name=str(update.get("tool_name", "") or "tool"),- args=update.get("tool_args", {}) or {},- source=self.name,- stage=stage,- metadata=derive_trace_metadata(- base_metadata,- trace_role="tool",- trace_kind="tool_call",- ),- )- return-- if event == "tool_result":- state = str(update.get("state", "complete") or "complete")- result = str(update.get("result", "") or "")- if state == "error":- await stream.error(- result,- source=self.name,- stage=stage,- metadata=derive_trace_metadata(- base_metadata,- trace_role="tool",- trace_kind="tool_result",- ),- )- return- await stream.tool_result(- tool_name=str(update.get("tool_name", "") or "tool"),- result=result,- source=self.name,- stage=stage,- metadata=derive_trace_metadata(- base_metadata,- trace_role="tool",- trace_kind="tool_result",- ),- )- return-- confirmed_outline = request_config.confirmed_outline- conversation_history = context.conversation_history or []-- if confirmed_outline is None:- outline_items = await self._generate_outline_preview(- config=config,- llm_config=llm_config,- kb_name=kb_name,- topic=topic,- stream=stream,- progress_callback=_progress_cb,- trace_callback=_trace_cb,- conversation_history=conversation_history,- attachments=context.attachments,- )- sub_topics_data = []- for item in outline_items:- model_dump = getattr(item, "model_dump", None)- sub_topics_data.append(model_dump() if callable(model_dump) else item)-- outline_md = self._outline_to_markdown(topic, sub_topics_data)- await stream.content(outline_md, source=self.name, stage="decomposing")-- await stream.result(- {- "outline_preview": True,- "sub_topics": sub_topics_data,- "topic": topic,- "research_config": {- "mode": request_config.mode,- "depth": request_config.depth,- "sources": list(request_config.sources),- **(- {"manual_subtopics": request_config.manual_subtopics}- if request_config.manual_subtopics is not None- else {}- ),- **(- {"manual_max_iterations": request_config.manual_max_iterations}- if request_config.manual_max_iterations is not None- else {}- ),- },- },- source=self.name,- )- return-- pre_outline = [- {"title": item.title, "overview": item.overview} for item in confirmed_outline- ]+ # Outline-preview two-stage flow: first call lacks a confirmed+ # outline → pipeline returns ``outline_preview`` and exits; the+ # frontend surfaces the outline editor and (after the user+ # confirms) sends a second call with ``confirmed_outline`` set.+ confirmed_outline_items: list[SubTopicItem] | None = None+ if request_config.confirmed_outline is not None:+ confirmed_outline_items = [+ SubTopicItem(title=item.title, overview=item.overview or "")+ for item in request_config.confirmed_outline+ ]pipeline = ResearchPipeline(- config=config,- api_key=llm_config.api_key,- base_url=llm_config.base_url or "",- api_version=llm_config.api_version,- kb_name=kb_name,- progress_callback=_progress_cb,- trace_callback=_trace_cb,- pre_confirmed_outline=pre_outline,- attachments=context.attachments,- )-- async with stream.stage("researching", source=self.name):- await stream.thinking(- f"Researching topic: {topic}", source=self.name, stage="researching"- )- result = await pipeline.run(topic=topic)-- report = result.get("report", "")- if report:- async with stream.stage("reporting", source=self.name):- await stream.content(report, source=self.name, stage="reporting")-- await stream.result(- {"response": report, "metadata": result.get("metadata", {})},- source=self.name,- )-- async def _run_answer_now(- self,- context: UnifiedContext,- stream: StreamBus,- payload: dict[str, Any],- ) -> None:- """- Fast-path for ``deep_research``: skip the rephrase/decompose/research- loop and synthesize the report directly from whatever evidence the- partial trace already contains.- """- from deeptutor.capabilities._answer_now import (- build_answer_now_trace_metadata,- format_trace_summary,- join_chunks,- labeled_block,- load_answer_now_prompts,- make_skip_notice,- stream_synthesis,- )-- original = str(payload.get("original_user_message") or context.user_message).strip()- partial = str(payload.get("partial_response") or "").strip()- trace_summary = format_trace_summary(payload.get("events"), language=context.language)-- prompts = load_answer_now_prompts("research", context.language)- system_prompt = str(prompts.get("system", "")).strip()- user_prompt = str(prompts.get("user_template", "")).format(- original=original,- current_draft=labeled_block("Current Draft", partial),- research_trace=labeled_block("Research Trace", trace_summary),- )-- trace_meta = build_answer_now_trace_metadata(- capability=self.name, phase="reporting", label="Answer now"- )- notice = make_skip_notice(- capability=self.name,language=context.language,- stages_skipped=["rephrasing", "decomposing", "researching"],- )-- async with stream.stage("reporting", source=self.name, metadata=trace_meta):- if notice:- await stream.content(notice + "\n\n", source=self.name, stage="reporting")- chunks: list[str] = []- async for chunk in stream_synthesis(- stream=stream,- source=self.name,- stage="reporting",- trace_meta=trace_meta,- system_prompt=system_prompt,- user_prompt=user_prompt,- max_tokens=3200,- ):- chunks.append(chunk)-- report = join_chunks(chunks)- full = (notice + "\n\n" + report).strip() if notice else report- await stream.result(- {- "response": full,- "metadata": {"answer_now": True},- },- source=self.name,- )-- @staticmethod- def _outline_to_markdown(topic: str, sub_topics: list[dict[str, str]]) -> str:- """Serialize an outline to Markdown so it is persisted in session history."""- lines = [f"**Research Outline — {topic}**\n"]- for i, item in enumerate(sub_topics, 1):- lines.append(f"{i}. **{item.get('title', '')}**")- overview = item.get("overview", "")- if overview:- lines.append(f" {overview}")- return "\n".join(lines)-- async def _generate_outline_preview(- self,- *,- config: dict[str, Any],- llm_config: Any,- kb_name: str | None,- topic: str,- stream: StreamBus,- progress_callback: Any,- trace_callback: Any,- conversation_history: list[dict[str, Any]] | None = None,- attachments: list[Any] | None = None,- ) -> list[dict[str, str]]:- """Run only the planning phase (rephrase + decompose) and return sub-topics."""- from deeptutor.agents.research.research_pipeline import ResearchPipeline-- if conversation_history:- config = {**config, "conversation_history": conversation_history}-- pipeline = ResearchPipeline(- config=config,- api_key=llm_config.api_key,- base_url=llm_config.base_url,- api_version=llm_config.api_version,+ runtime_config=runtime_config,kb_name=kb_name,- progress_callback=progress_callback,- trace_callback=trace_callback,- attachments=attachments,+ enabled_tools=enabled_tools,+ )+ result = await pipeline.run(+ context=context,+ topic=context.user_message,+ confirmed_outline=confirmed_outline_items,+ attachments=context.attachments,+ stream=stream,)- async with stream.stage("decomposing", source=self.name):- await stream.thinking(- f"Generating research outline for: {topic}",+ # Outline-preview payloads carry the sub-topics + the original+ # request config so the second call has everything it needs to+ # confirm and resume. Fields live at top level so+ # ``event.metadata.outline_preview`` resolves on the FE.+ if result.get("outline_preview"):+ research_config: dict[str, Any] = {+ "mode": request_config.mode,+ "depth": request_config.depth,+ }+ if request_config.manual_subtopics is not None:+ research_config["manual_subtopics"] = request_config.manual_subtopics+ if request_config.manual_max_iterations is not None:+ research_config["manual_max_iterations"] = request_config.manual_max_iterations+ await stream.result(+ {**result, "research_config": research_config},source=self.name,- stage="decomposing",)- optimized_topic = await pipeline._phase1_planning(topic)-- sub_topics = []- for block in pipeline.queue.blocks:- sub_topics.append({"title": block.sub_topic, "overview": block.overview})-- return sub_topicsdiff --git a/deeptutor/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.pyindex fe15bb077..5bdd399ae 100644--- a/deeptutor/capabilities/deep_solve.py+++ b/deeptutor/capabilities/deep_solve.py@@ -1,26 +1,18 @@-"""-Deep Solve Capability-=====================+"""Deep Solve capability — agentic-engine-based multi-step problem solving.-Multi-agent problem solving pipeline: Plan -> ReAct -> Write.-Wraps the existing ``MainSolver``.+Thin shim that delegates to :class:`SolvePipeline`. All orchestration (the+pre-retrieve sub-DAG, per-step agentic loops with ``THINK`` / ``TOOL`` /+``FINISH`` / ``REPLAN``, replan back-edge, synthesize) lives in the pipeline+module; the capability just wires the manifest."""from __future__ import annotations-import asyncio-from typing import Any-+from deeptutor.agents.solve.pipeline import SolvePipelinefrom deeptutor.capabilities.request_contracts import get_capability_request_schemafrom deeptutor.core.capability_protocol import BaseCapability, CapabilityManifestfrom deeptutor.core.context import UnifiedContextfrom deeptutor.core.stream_bus import StreamBus-from deeptutor.core.trace import derive_trace_metadata, merge_trace_metadata---def _image_attachments(attachments: list[Any]) -> list[Any]:- """Return the image attachments to forward into multimodal LLM calls."""- return [att for att in attachments or [] if getattr(att, "type", "") == "image"]class DeepSolveCapability(BaseCapability):@@ -34,325 +26,28 @@ class DeepSolveCapability(BaseCapability):)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:- from deeptutor.agents.solve.main_solver import MainSolver- from deeptutor.capabilities._answer_now import extract_answer_now_context- from deeptutor.services.llm.config import get_llm_config-- answer_now_payload = extract_answer_now_context(context)- if answer_now_payload is not None:- await self._run_answer_now(context, stream, answer_now_payload)- return-- llm_config = get_llm_config()- detailed = context.config_overrides.get("detailed_answer", True)- # Attached knowledge bases are the single source of truth for whether- # rag should be available — there is no separate "enable rag" toggle.+ # Knowledge bases are the single source of truth for whether ``rag``+ # is available. There is no separate "enable rag" toggle.kb_name = context.knowledge_bases[0] if context.knowledge_bases else Nonerequested = list(self.manifest.tools_used if context.enabled_tools is None else context.enabled_tools)+ # Drop ``rag`` from the user-visible toggle list — the pipeline mounts+ # it itself when a KB is attached, and never when none is.enabled_tools = [tool for tool in requested if tool != "rag"]- if kb_name:- enabled_tools.append("rag")- solver = MainSolver(- api_key=llm_config.api_key,- base_url=llm_config.base_url,- api_version=llm_config.api_version,- kb_name=kb_name,+ pipeline = SolvePipeline(language=context.language,+ kb_name=kb_name,enabled_tools=enabled_tools,- disable_planner_retrieve=kb_name is None,)- await solver.ainit()-- # Also bridge the explicit progress callback- def _normalize_stage(stage: str) -> str:- mapping = {- "plan": "planning",- "planning": "planning",- "solve": "reasoning",- "solving": "reasoning",- "reasoning": "reasoning",- "write": "writing",- "writing": "writing",- }- return mapping.get(stage, stage or "reasoning")-- async def _trace_bridge(update: dict) -> None:- event = str(update.get("event", "") or "")- stage = str(update.get("phase") or update.get("stage") or "reasoning")- stage = _normalize_stage(stage)- base_metadata = {- key: value- for key, value in update.items()- if key- not in {"event", "state", "response", "chunk", "result", "tool_args", "tool_name"}- }-- if event == "llm_call":- state = str(update.get("state", "running"))- label = str(update.get("label", "") or "")- if state == "running":- await stream.progress(- message=label,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "call_status", "call_state": "running"},- ),- )- return- if state == "streaming":- chunk = str(update.get("chunk", "") or "")- if chunk:- await stream.thinking(- chunk,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "llm_chunk"},- ),- )- return- if state == "complete":- was_streaming = update.get("streaming", False)- if not was_streaming:- response = str(update.get("response", "") or "")- if response:- await stream.thinking(- response,- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "llm_output"},- ),- )- await stream.progress(- message="",- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "call_status", "call_state": "complete"},- ),- )- return- if state == "error":- await stream.error(- str(update.get("response", "") or "LLM call failed."),- source=self.name,- stage=stage,- metadata=merge_trace_metadata(- base_metadata,- {"trace_kind": "call_status", "call_state": "error"},- ),- )- return-- if event == "llm_observation":- response = str(update.get("response", "") or "")- if response:- await stream.observation(- response,- source=self.name,- stage=stage,- metadata=derive_trace_metadata(- base_metadata,- trace_role="observe",- trace_kind="observation",- ),- )- return-- if event == "tool_call":- await stream.tool_call(- tool_name=str(update.get("tool_name", "") or "tool"),- args=update.get("tool_args", {}) or {},- source=self.name,- stage=stage,- metadata=derive_trace_metadata(- base_metadata,- trace_role="tool",- trace_kind="tool_call",- ),- )- return-- if event == "tool_result":- await stream.tool_result(- tool_name=str(update.get("tool_name", "") or "tool"),- result=str(update.get("result", "") or ""),- source=self.name,- stage=stage,- metadata=derive_trace_metadata(- base_metadata,- trace_role="tool",- trace_kind="tool_result",- sources=update.get("sources", []) or [],- ),- )- return-- if event == "tool_log":- message = str(update.get("message", "") or "")- if not message:- return- await stream.progress(- message=message,- source=self.name,- stage=stage,- metadata=derive_trace_metadata(- base_metadata,- trace_role="retrieve",- trace_group="retrieve",- trace_kind=str(update.get("trace_kind", "tool_log") or "tool_log"),- ),- )- return-- def _progress_bridge(stage: str, progress: dict):- async def _emit() -> None:- status = str(progress.get("status", stage))- detail_parts = []- if "step_id" in progress:- detail_parts.append(f"[{progress['step_id']}]")- if "step_target" in progress:- detail_parts.append(str(progress["step_target"])[:80])- detail = " ".join(detail_parts)- msg = f"{status}: {detail}" if detail else status- await stream.progress(- message=msg,- source=self.name,- stage=_normalize_stage(stage),- )-- try:- asyncio.get_running_loop().create_task(_emit())- except RuntimeError:- pass-- setattr(solver, "_send_progress_update", _progress_bridge)- if hasattr(solver, "set_trace_callback"):- solver.set_trace_callback(_trace_bridge)-- # Content callback — streams writer tokens to the main chat area- content_streamed = False-- async def _content_sink(chunk: str) -> None:- nonlocal content_streamed- content_streamed = True- await stream.content(- chunk,- source=self.name,- stage="writing",- )-- setattr(solver, "_content_callback", _content_sink)-- result = await solver.solve(+ await pipeline.run(+ context=context,question=context.user_message,- attachments=_image_attachments(context.attachments),- verbose=False,- detailed=detailed,+ attachments=context.attachments,conversation_context=str(context.metadata.get("conversation_context_text", "") or "").strip(),- )-- final_answer = result.get("final_answer", "")-- if final_answer and not content_streamed:- async with stream.stage("writing", source=self.name):- await stream.content(final_answer, source=self.name, stage="writing")-- await stream.result(- {- "response": final_answer,- "output_dir": result.get("output_dir", ""),- "metadata": result.get("metadata", {}),- },- source=self.name,- )-- async def _run_answer_now(- self,- context: UnifiedContext,- stream: StreamBus,- payload: dict[str, Any],- ) -> None:- """- Fast-path for ``deep_solve``: skip Plan + ReAct, jump straight into- the writer with whatever reasoning trace has streamed so far.-- The result payload preserves the same envelope shape as a normal- ``deep_solve`` turn (``response`` + ``metadata``) so the frontend- renders it identically.- """- from deeptutor.capabilities._answer_now import (- build_answer_now_trace_metadata,- format_trace_summary,- join_chunks,- labeled_block,- load_answer_now_prompts,- make_skip_notice,- stream_synthesis,- )-- original = str(payload.get("original_user_message") or context.user_message).strip()- partial = str(payload.get("partial_response") or "").strip()- trace_summary = format_trace_summary(payload.get("events"), language=context.language)-- prompts = load_answer_now_prompts("solve", context.language)- system_prompt = str(prompts.get("system", "")).strip()- user_prompt = str(prompts.get("user_template", "")).format(- original=original,- current_draft=labeled_block("Current Draft", partial),- execution_trace=labeled_block("Execution Trace", trace_summary),- )- notice_label = "Writing"-- trace_meta = build_answer_now_trace_metadata(- capability=self.name, phase="writing", label="Answer now"- )-- notice = make_skip_notice(- capability=self.name,- language=context.language,- stages_skipped=["planning", "reasoning"],- )-- async with stream.stage("writing", source=self.name, metadata=trace_meta):- if notice:- await stream.content(- notice + "\n\n",- source=self.name,- stage="writing",- )- chunks: list[str] = []- async for chunk in stream_synthesis(- stream=stream,- source=self.name,- stage="writing",- trace_meta=trace_meta,- system_prompt=system_prompt,- user_prompt=user_prompt,- max_tokens=2000,- ):- chunks.append(chunk)-- final_answer = join_chunks(chunks)- await stream.result(- {- "response": (notice + "\n\n" + final_answer).strip() if notice else final_answer,- "output_dir": "",- "metadata": {- "answer_now": True,- "synthesizer": notice_label,- },- },- source=self.name,+ memory_context=str(context.memory_context or "").strip(),+ stream=stream,)diff --git a/deeptutor/core/agentic/__init__.py b/deeptutor/core/agentic/__init__.pynew file mode 100644index 000000000..6a97478b2--- /dev/null+++ b/deeptutor/core/agentic/__init__.py@@ -0,0 +1,66 @@+r"""Foundational agentic engine primitives.++These modules implement the chat-style ``\`\`LABEL\`\`+content`` LLM protocol as+reusable building blocks. Any capability that wants a streaming, label-driven+LLM loop (chat, solve step, etc.) composes them.++Layering:++* :mod:`labels` — protocol-label parsing (parametric label set).+* :mod:`client` — OpenAI/Azure client factory + completion kwargs.+* :mod:`usage` — token-usage accumulator shared across steps.+* :mod:`labeled_step` — one streaming LLM call with label routing.+* :mod:`tool_dispatch` — parallel tool execution with per-tool sub-traces.+* :mod:`loop` — iteration scheduler that ties the above together.++Capability-specific concerns (system prompt assembly, tool whitelist, KB enums,+answer-now fast paths, force-finalize strategies, context-window guards) live+in each capability's own module — the primitives expose hooks but do not bake+those decisions in.+"""++from deeptutor.core.agentic.client import (+ LLMClientConfig,+ build_completion_kwargs,+ build_openai_client,+ can_use_native_tool_calling,+)+from deeptutor.core.agentic.labeled_step import LabeledStepResult, run_labeled_step+from deeptutor.core.agentic.labels import (+ LABEL_PROBE_MAX_CHARS,+ LABEL_UNKNOWN,+ classify_label,+ find_inline_labels,+ strip_label_probe_prefix,+)+from deeptutor.core.agentic.loop import LabelProtocol, LoopHost, LoopOutcome, run_agentic_loop+from deeptutor.core.agentic.tool_dispatch import (+ MAX_PARALLEL_TOOL_CALLS,+ DispatchOutcome,+ dispatch_tool_calls,+ execute_tool_call,+)+from deeptutor.core.agentic.usage import UsageTracker++__all__ = [+ "LABEL_PROBE_MAX_CHARS",+ "LABEL_UNKNOWN",+ "LLMClientConfig",+ "LabelProtocol",+ "LabeledStepResult",+ "LoopHost",+ "LoopOutcome",+ "MAX_PARALLEL_TOOL_CALLS",+ "DispatchOutcome",+ "UsageTracker",+ "build_completion_kwargs",+ "build_openai_client",+ "can_use_native_tool_calling",+ "classify_label",+ "dispatch_tool_calls",+ "execute_tool_call",+ "find_inline_labels",+ "run_agentic_loop",+ "run_labeled_step",+ "strip_label_probe_prefix",+]diff --git a/deeptutor/core/agentic/client.py b/deeptutor/core/agentic/client.pynew file mode 100644index 000000000..eefb43b8f--- /dev/null+++ b/deeptutor/core/agentic/client.py@@ -0,0 +1,79 @@+"""OpenAI-compatible client factory and completion kwargs.++Lifted from chat's pipeline so any capability that wants a streaming LLM call+with tools can construct the same client + kwargs without re-implementing+provider gating, Azure detection, SSL bypass, or per-model token caps.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++import httpx+from openai import AsyncAzureOpenAI, AsyncOpenAI++from deeptutor.services.config import load_system_settings+from deeptutor.services.llm import get_token_limit_kwargs, supports_tools++# Providers that don't reliably support OpenAI function-calling. The loop+# still runs without tool schemas — the model just produces prose.+_NATIVE_TOOL_BLOCKED_BINDINGS: frozenset[str] = frozenset(+ {"anthropic", "claude", "ollama", "lm_studio", "vllm", "llama_cpp"}+)+++@dataclass(frozen=True)+class LLMClientConfig:+ """Provider-neutral handle for constructing an OpenAI-compatible client."""++ binding: str+ model: str | None+ api_key: str | None+ base_url: str | None+ api_version: str | None = None+ extra_headers: dict[str, str] | None = None+++def build_openai_client(config: LLMClientConfig) -> Any:+ """Construct an ``AsyncOpenAI`` / ``AsyncAzureOpenAI`` client."""+ http_client = None+ if load_system_settings()["disable_ssl_verify"]:+ http_client = httpx.AsyncClient(verify=False) # nosec B501+ default_headers = config.extra_headers or None+ if config.binding == "azure_openai" or (+ config.binding == "openai" and config.api_version+ ):+ return AsyncAzureOpenAI(+ api_key=config.api_key or "sk-no-key-required",+ azure_endpoint=config.base_url,+ api_version=config.api_version,+ http_client=http_client,+ default_headers=default_headers,+ )+ return AsyncOpenAI(+ api_key=config.api_key or "sk-no-key-required",+ base_url=config.base_url or None,+ http_client=http_client,+ default_headers=default_headers,+ )+++def build_completion_kwargs(+ *,+ temperature: float,+ model: str | None,+ max_tokens: int,+) -> dict[str, Any]:+ """Compose temperature + per-model token-limit kwargs into one dict."""+ kwargs: dict[str, Any] = {"temperature": temperature}+ if model:+ kwargs.update(get_token_limit_kwargs(model, max_tokens))+ return kwargs+++def can_use_native_tool_calling(*, binding: str, model: str | None) -> bool:+ """Whether the current provider supports OpenAI-style function calling."""+ if not supports_tools(binding, model):+ return False+ return binding not in _NATIVE_TOOL_BLOCKED_BINDINGSdiff --git a/deeptutor/core/agentic/labeled_step.py b/deeptutor/core/agentic/labeled_step.pynew file mode 100644index 000000000..4adb76459--- /dev/null+++ b/deeptutor/core/agentic/labeled_step.py@@ -0,0 +1,630 @@+r"""One streaming LLM call with protocol-label routing.++The core single-round-trip primitive. Given an OpenAI-compatible streaming+client, optional tool schemas, and a label protocol, this:++* Parses the first chunks for a ``\`\`LABEL\`\``` prefix.+* For *non-final* labels (e.g. ``THINK``, ``TOOL``, ``REPLAN``), streams+ post-label text live to ``stream.thinking`` under the supplied+ ``iter_meta`` — i.e. into a reasoning sub-trace.+* For *final* labels (e.g. ``FINISH``, ``PLAN``, ``SUMMARY``), buffers the+ post-label text and returns it to the caller; the caller decides whether+ to emit it as body content (so a mixed ``FINISH+TOOL`` reply never leaks+ prose into the answer area before the protocol is validated).+* Accumulates ``tool_calls`` deltas. When ``tool_label`` is set and tool-call+ deltas arrive before the label resolves, force-resolves the label to that+ value (tool-call presence is authoritative).+* When a reasoning model prepends a literal ``<think>...</think>`` block+ *before* the protocol label, that prelude is detected and streamed live+ into the reasoning sub-trace (same routing as the ``THINK`` label).+ Label probing resumes on the content after ``</think>``: if the label+ resolves to an intermediate label (e.g. ``THINK``) the post-label text+ continues into the *same* sub-trace; if it resolves to a final label+ (e.g. ``FINISH``) the post-label text routes to the final-response area+ as usual. The ``<think>``/``</think>`` markers themselves are not emitted+ live, only kept in the accumulated buffer so ``clean_thinking_tags`` can+ strip the block from the returned text.++Returns the resolved label, the accumulated post-label text (with provider+``<think>`` tags stripped), and the parsed tool calls.+"""++from __future__ import annotations++import asyncio+import re+from contextlib import suppress+from dataclasses import dataclass, field+from typing import Any++from deeptutor.core.agentic.labels import (+ LABEL_PROBE_MAX_CHARS,+ LABEL_UNKNOWN,+ classify_label,+ strip_label_probe_prefix,+)+from deeptutor.core.agentic.usage import UsageTracker+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import merge_trace_metadata+from deeptutor.services.llm import clean_thinking_tags++# Reasoning models (Qwen, Deepseek-R1 via certain proxies, etc.) sometimes+# inline a literal ``<think>...</think>`` block in the content stream before+# emitting the protocol label. Match the opening tag *only* at the start of+# the (whitespace-stripped) probe buffer — anything later belongs to the+# post-label body and is handled by ``clean_thinking_tags`` at the end.+#+# Backticks must appear in matched pairs (e.g. `` `<think>` `` or+# ``<think>``) — a lone optional ``backtick on either side would greedily+# eat a leading ```` of the protocol label that follows (e.g. ``</think>``+# immediately preceding ``\`\`FINISH\`\```), corrupting the post-prelude+# label probe.+_THINK_OPEN_RE = re.compile(+ r"\A(?:`<\s*think(?:ing)?\b[^>]*>`|<\s*think(?:ing)?\b[^>]*>)",+ re.IGNORECASE,+)+_THINK_CLOSE_RE = re.compile(+ r"(?:`<\s*/\s*think(?:ing)?\s*>`|<\s*/\s*think(?:ing)?\s*>)",+ re.IGNORECASE,+)+# Headroom for ``</think>`` plus optional surrounding backticks/whitespace.+# We keep at most this many trailing chars of the prelude unsent so a close+# tag that arrives split across chunks is still detectable.+_THINK_CLOSE_TAIL_GUARD = 24+# Once a provider has explicitly sent ``finish_reason`` the text generation is+# done. Some OpenAI-compatible gateways keep the SSE connection open while+# waiting for an optional usage trailer; wait briefly for that frame, then+# close locally so the UI can receive RESULT/DONE promptly.+_USAGE_TRAILER_GRACE_TIMEOUT_S = 1.0+# Defensive fallback for gateways that never emit ``finish_reason`` but have+# already sent a final-label answer and then leave the stream idle.+_FINAL_LABEL_IDLE_TIMEOUT_S = 8.0+++@dataclass(frozen=True)+class LabeledStepResult:+ """Outcome of a single labeled LLM call."""++ label: str # one of allowed_labels, or LABEL_UNKNOWN on protocol failure+ text: str # post-label content with provider <think> tags cleaned+ tool_calls: list[dict[str, Any]] = field(default_factory=list)+++class _UsageShim:+ """Adapt streaming ``CompletionUsage`` to the shape ``UsageTracker`` wants."""++ def __init__(self, raw: Any) -> None:+ self.usage = raw+++def _message_content_chars(message: dict[str, Any]) -> int:+ """Best-effort character count for usage fallback estimates."""+ content = message.get("content")+ if isinstance(content, str):+ return len(content)+ if isinstance(content, list):+ total = 0+ for part in content:+ if isinstance(part, dict):+ if part.get("type") == "text":+ total += len(str(part.get("text") or ""))+ elif "text" in part:+ total += len(str(part.get("text") or ""))+ elif isinstance(part, str):+ total += len(part)+ return total+ if content is None:+ return 0+ return len(str(content))+++def _is_stream_options_unsupported(exc: Exception) -> bool:+ """Detect providers that reject OpenAI's ``stream_options`` parameter."""+ response = getattr(exc, "response", None)+ body = (+ getattr(exc, "body", None)+ or getattr(exc, "doc", None)+ or getattr(response, "text", None)+ or getattr(exc, "message", None)+ or str(exc)+ )+ text = str(body).lower()+ return any(+ marker in text+ for marker in (+ "stream_options",+ "stream options",+ "unknown parameter",+ "unrecognized request argument",+ "unsupported parameter",+ "extra inputs are not permitted",+ "unexpected keyword",+ )+ )+++async def run_labeled_step(+ *,+ client: Any,+ model: str | None,+ messages: list[dict[str, Any]],+ completion_kwargs: dict[str, Any],+ tool_schemas: list[dict[str, Any]] | None,+ allowed_labels: tuple[str, ...],+ final_labels: frozenset[str],+ tool_label: str | None,+ stream: StreamBus,+ source: str,+ stage: str,+ iter_meta: dict[str, Any],+ binding: str | None = None,+ usage: UsageTracker | None = None,+ final_meta: dict[str, Any] | None = None,+ eager_sub_trace: bool = False,+ implicit_think_label: str | None = None,+) -> LabeledStepResult:+ """Drive one streaming LLM call under the label protocol.++ ``final_meta`` opts the post-label stream into **live body streaming**:+ when set, every chunk that resolves under a label in ``final_labels``+ is emitted as a :py:meth:`StreamBus.content` event using ``final_meta``+ (with ``trace_kind="llm_chunk"``), so the chat bubble fills up+ chunk-by-chunk instead of appearing in one shot at the end. When+ ``final_meta`` is ``None`` (chat's existing behavior), final-label+ text is buffered and the caller emits it after protocol validation.++ ``eager_sub_trace=True`` opens the iteration's sub-trace card before+ the LLM stream begins, so the trace panel renders a "running" indicator+ immediately instead of after the first chunk arrives. This closes the+ visual gap during the time-to-first-token of each call (often 0.5–3s+ of network + model warm-up). Lazy default keeps chat's existing+ behavior — its cards only open when there is actual reasoning text to+ show, avoiding empty "Reasoning…" cards for direct FINISH replies.++ ``implicit_think_label`` lets a caller (e.g. chat) say "if a reasoning+ model emits ``<think>...</think>`` without following it with one of my+ protocol labels, treat the whole iteration as *this* label". The intent+ is to gracefully accept native-format reasoning models — they think in+ ``<think>`` blocks and may not parrot back the protocol's+ ``\`\`THINK\`\``` token. Without this, the loop would see a missing+ label and burn iterations on repair-retries. When the implicit+ resolution fires, the prelude markers are preserved in the returned+ ``text`` so the next iteration's assistant context still shows the+ model's reasoning verbatim.+ """+ kwargs: dict[str, Any] = {+ "model": model,+ "messages": messages,+ "stream": True,+ **completion_kwargs,+ }+ auto_stream_options_added = False+ if usage is not None and "stream_options" not in kwargs:+ kwargs["stream_options"] = {"include_usage": True}+ auto_stream_options_added = True+ if tool_schemas:+ kwargs["tools"] = tool_schemas+ kwargs["tool_choice"] = "auto"++ label: str | None = None+ label_buf = ""+ in_prelude_think = False+ # Trailing slice of the in-progress prelude held back so a ``</think>``+ # split across chunks is still detectable.+ prelude_tail = ""+ # True once we have observed a pre-label ``<think>`` opener. The final+ # ``clean_thinking_tags`` pass is gated on ``binding`` to preserve+ # existing behavior; we always force the cleanup when a prelude was+ # detected so the synthetic markers we recorded don't leak out.+ saw_pre_label_think = False+ sub_trace_opened = False+ content_acc: list[str] = []+ tc_acc: dict[int, dict[str, Any]] = {}+ usage_seen: Any = None+ output_chars_seen = 0+ finish_reason_seen: str | None = None+ usage_trailer_waited = False++ async def _open_sub_trace() -> None:+ nonlocal sub_trace_opened+ if sub_trace_opened:+ return+ await stream.progress(+ iter_meta.get("label", ""),+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(+ iter_meta,+ {"trace_kind": "call_status", "call_state": "running"},+ ),+ )+ sub_trace_opened = True++ async def _emit_text(text: str) -> None:+ """Route post-label fragments.++ * Final-label text: buffered. If ``final_meta`` was supplied, the+ fragment is *also* emitted live as a ``content`` event so the chat+ bubble streams chunk-by-chunk (call_kind ``llm_final_response``).+ * Non-final labels: streamed into the reasoning sub-trace.+ """+ nonlocal output_chars_seen+ if not text:+ return+ output_chars_seen += len(text)+ content_acc.append(text)+ if label in final_labels:+ if final_meta is not None:+ await stream.content(+ text,+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(final_meta, {"trace_kind": "llm_chunk"}),+ )+ return+ await _open_sub_trace()+ await stream.thinking(+ text,+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(iter_meta, {"trace_kind": "llm_chunk"}),+ )++ async def _emit_prelude_content(text: str) -> None:+ """Stream pre-label ``<think>`` body content into the reasoning+ sub-trace, identical to the routing used for the non-final ``THINK``+ label so a real ``THINK`` label that follows naturally merges into+ the same trace. The raw text is also retained in ``content_acc`` so+ :func:`clean_thinking_tags` can strip the entire prelude block from+ the returned text at the end.+ """+ nonlocal output_chars_seen+ if not text:+ return+ output_chars_seen += len(text)+ content_acc.append(text)+ await _open_sub_trace()+ await stream.thinking(+ text,+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(iter_meta, {"trace_kind": "llm_chunk"}),+ )++ async def _emit_prelude_marker(tag_text: str) -> None:+ """Stream a ``<think>``/``</think>`` marker live into the reasoning+ sub-trace AND record it in ``content_acc``.++ The marker is visible in the trace UI (so users see the actual+ ``<think>...</think>`` structure the model emitted) and the+ accumulated buffer keeps the literal tag so downstream consumers+ — including the implicit-``THINK`` resolution path — can preserve+ or strip the prelude block as needed.+ """+ nonlocal output_chars_seen+ if not tag_text:+ return+ output_chars_seen += len(tag_text)+ content_acc.append(tag_text)+ await _open_sub_trace()+ await stream.thinking(+ tag_text,+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(iter_meta, {"trace_kind": "llm_chunk"}),+ )++ async def _close_prelude_artificially() -> None:+ """Force-end an in-progress ``<think>`` prelude (used when tool+ calls arrive mid-prelude or the stream ends with no close tag).+ Flushes any held-back tail to the live sub-trace and emits a+ synthesized ``</think>`` marker so both the trace and the+ accumulated buffer reflect a clean close."""+ nonlocal in_prelude_think, prelude_tail+ if prelude_tail:+ await _emit_prelude_content(prelude_tail)+ prelude_tail = ""+ await _emit_prelude_marker("</think>")+ in_prelude_think = False++ async def _drain_prelude_or_close() -> None:+ """While ``in_prelude_think`` is set, scan ``prelude_tail`` for a+ ``</think>`` close tag. If found, emit the content before the tag+ live, emit the close marker live, and move whatever follows the+ tag into ``label_buf`` so label probing resumes. If not found,+ emit as much of the tail as we can while keeping a small guard+ window so a close tag split across chunks is still detectable+ next time."""+ nonlocal in_prelude_think, prelude_tail, label_buf+ close_m = _THINK_CLOSE_RE.search(prelude_tail)+ if close_m is None:+ if len(prelude_tail) > _THINK_CLOSE_TAIL_GUARD:+ split = len(prelude_tail) - _THINK_CLOSE_TAIL_GUARD+ safe = prelude_tail[:split]+ prelude_tail = prelude_tail[split:]+ await _emit_prelude_content(safe)+ return+ before = prelude_tail[: close_m.start()]+ if before:+ await _emit_prelude_content(before)+ await _emit_prelude_marker(close_m.group(0))+ in_prelude_think = False+ label_buf = prelude_tail[close_m.end() :]+ prelude_tail = ""++ async def _ingest_pre_label(text: str) -> None:+ """Drive the pre-label state machine for one streamed chunk.++ Handles, in a single chunk if the data permits: continuing an open+ ``<think>`` prelude, entering a new prelude when the buffer opens+ with ``<think>``, closing a prelude on ``</think>``, resolving the+ protocol label, and the probe-overflow fallback.+ """+ nonlocal label, label_buf, in_prelude_think, prelude_tail+ nonlocal saw_pre_label_think++ if in_prelude_think:+ prelude_tail += text+ elif text:+ label_buf += text++ # Drive the state machine forward as long as the current buffers+ # allow progress. A single chunk can carry the entire prelude AND+ # the label AND the post-label text, so we keep looping until either+ # the label resolves or we run out of decidable input.+ while True:+ if in_prelude_think:+ await _drain_prelude_or_close()+ if in_prelude_think:+ return # waiting for ``</think>``+ # ``</think>`` consumed; ``label_buf`` now holds the+ # post-prelude remainder. Continue to label probing.++ stripped = strip_label_probe_prefix(label_buf)+ open_m = _THINK_OPEN_RE.match(stripped)+ if open_m:+ leading_len = len(label_buf) - len(stripped)+ if leading_len:+ # Preserve incidental leading whitespace verbatim — the+ # final ``cleaned.strip()`` inside+ # ``clean_thinking_tags`` will smooth over it.+ content_acc.append(label_buf[:leading_len])+ in_prelude_think = True+ saw_pre_label_think = True+ prelude_tail = stripped[open_m.end() :]+ label_buf = ""+ # Emit the ``<think>`` marker live so the reasoning sub-+ # trace shows the model's native structure. This also+ # opens the sub-trace card immediately, so short preludes+ # (≤24 chars) still surface UI activity even before the+ # close-tag guard window flushes any content.+ await _emit_prelude_marker(open_m.group(0))+ continue # re-enter loop to drain the new prelude++ parsed = classify_label(label_buf, allowed_labels=allowed_labels)+ if parsed is not None:+ label, after_label = parsed+ label_buf = ""+ await _emit_text(after_label)+ return++ if len(label_buf) > LABEL_PROBE_MAX_CHARS:+ # Probe window exhausted with no protocol label match. If+ # we previously consumed a ``<think>`` prelude AND the+ # caller opted into implicit-THINK semantics, treat this+ # iteration as an implicit ``THINK`` — the model is a+ # reasoning model speaking its native dialect. Otherwise+ # fall to ``LABEL_UNKNOWN`` so the caller can repair.+ if (+ saw_pre_label_think+ and implicit_think_label+ and implicit_think_label in allowed_labels+ ):+ label = implicit_think_label+ else:+ label = LABEL_UNKNOWN+ flushed = label_buf+ label_buf = ""+ await _emit_text(flushed)+ return++ return # no further decision possible without more input++ if eager_sub_trace:+ # Open the sub-trace card *before* the LLM stream begins so the+ # trace panel renders activity during the time-to-first-token of+ # the upcoming call (which would otherwise be silent UI).+ await _open_sub_trace()++ async def _create_response_stream() -> Any:+ try:+ return await client.chat.completions.create(**kwargs)+ except Exception as exc:+ if auto_stream_options_added and _is_stream_options_unsupported(exc):+ retry_kwargs = dict(kwargs)+ retry_kwargs.pop("stream_options", None)+ return await client.chat.completions.create(**retry_kwargs)+ raise++ response_stream = await _create_response_stream()+ try:+ stream_iter = response_stream.__aiter__()+ while True:+ timeout: float | None = None+ if finish_reason_seen:+ if usage is not None and usage_seen is None and not usage_trailer_waited:+ timeout = _USAGE_TRAILER_GRACE_TIMEOUT_S+ usage_trailer_waited = True+ else:+ break+ elif label in final_labels and content_acc:+ timeout = _FINAL_LABEL_IDLE_TIMEOUT_S+ try:+ if timeout is None:+ chunk = await stream_iter.__anext__()+ else:+ chunk = await asyncio.wait_for(stream_iter.__anext__(), timeout=timeout)+ except StopAsyncIteration:+ break+ except asyncio.TimeoutError:+ # Terminal enough for the chat UI: the model already sent a+ # final-label answer (or an explicit finish_reason), but the+ # gateway is holding the connection open.+ if finish_reason_seen or label in final_labels:+ break+ raise+ if getattr(chunk, "usage", None):+ usage_seen = chunk.usage+ choices = getattr(chunk, "choices", None) or []+ if not choices:+ continue+ choice = choices[0]+ if getattr(choice, "finish_reason", None):+ finish_reason_seen = str(choice.finish_reason)+ delta = choice.delta+ if delta is None:+ continue++ # Reasoning models that surface chain-of-thought via the dedicated+ # ``reasoning_content`` (or ``reasoning``) field — e.g. DeepSeek-R1+ # via certain providers, OpenAI o1/o3 in some compatibility modes+ # — emit *no* ``delta.content`` during the reasoning phase. Without+ # this branch the UI would sit frozen for the entire reasoning+ # duration, then the answer chunk would arrive and the user would+ # see only the answer with no reasoning trace. Route the reasoning+ # stream live into the same sub-trace the inline-``<think>``+ # prelude uses, so both flavors of reasoning model surface+ # identically. ``saw_pre_label_think`` forces the final cleanup+ # path to run even when ``binding`` is unset.+ reasoning_text = getattr(delta, "reasoning_content", None) or getattr(+ delta, "reasoning", None+ )+ if reasoning_text and label is None:+ output_chars_seen += len(reasoning_text)+ saw_pre_label_think = True+ await _open_sub_trace()+ await stream.thinking(+ reasoning_text,+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(+ iter_meta, {"trace_kind": "llm_chunk"}+ ),+ )++ if delta.content:+ text = delta.content+ if label is None:+ await _ingest_pre_label(text)+ else:+ await _emit_text(text)++ for tc_delta in getattr(delta, "tool_calls", None) or []:+ fn_for_chars = getattr(tc_delta, "function", None)+ output_chars_seen += len(str(getattr(fn_for_chars, "name", "") or ""))+ output_chars_seen += len(str(getattr(fn_for_chars, "arguments", "") or ""))+ # Tool-call deltas are authoritative for the tool branch. If+ # we're still buffering a label when tool-call deltas arrive,+ # force-resolve to ``tool_label`` so the buffered prose+ # flushes into the reasoning sub-trace and subsequent prose+ # continues there.+ if label is None and tool_label:+ label = tool_label+ if in_prelude_think:+ # Close out the prelude before treating any buffered+ # prose as the tool branch's reasoning preamble.+ await _close_prelude_artificially()+ flushed = label_buf+ label_buf = ""+ if flushed:+ await _emit_text(flushed)+ idx = getattr(tc_delta, "index", 0)+ entry = tc_acc.setdefault(idx, {"id": "", "name": "", "arguments": ""})+ if getattr(tc_delta, "id", None):+ entry["id"] = tc_delta.id+ fn = getattr(tc_delta, "function", None)+ if fn is not None:+ if getattr(fn, "name", None):+ entry["name"] = entry["name"] + fn.name+ if getattr(fn, "arguments", None):+ entry["arguments"] = entry["arguments"] + fn.arguments+ finally:+ close = getattr(response_stream, "close", None)+ if callable(close):+ with suppress(Exception):+ await close()++ # Stream ended while still buffering a label. Decide how to resolve:+ #+ # - If we saw a ``<think>`` prelude and the caller opted into+ # implicit-THINK semantics, treat the iteration as an implicit+ # ``THINK`` so the loop continues (reasoning models that natively+ # speak ``<think>...</think>`` get accepted instead of treated as+ # protocol violators).+ # - Otherwise fall to ``LABEL_UNKNOWN`` and let the caller repair.+ if label is None:+ if in_prelude_think:+ # Stream ended mid-prelude — flush remaining reasoning live so+ # the user sees what the model managed to produce, then close+ # the block synthetically.+ await _close_prelude_artificially()+ final_parsed = classify_label(+ label_buf,+ allowed_labels=allowed_labels,+ final=True,+ )+ if final_parsed is not None:+ label, after_label = final_parsed+ label_buf = ""+ await _emit_text(after_label)+ if (+ label is None+ and saw_pre_label_think+ and implicit_think_label+ and implicit_think_label in allowed_labels+ ):+ label = implicit_think_label+ elif label is None:+ label = LABEL_UNKNOWN+ if label_buf:+ await _emit_text(label_buf)+ label_buf = ""++ if usage_seen is not None and usage is not None:+ usage.add_from_response(_UsageShim(usage_seen))+ elif usage is not None:+ input_chars = sum(_message_content_chars(message) for message in messages)+ if input_chars or output_chars_seen:+ usage.add_estimated(+ input_chars=input_chars,+ output_chars=output_chars_seen,+ )++ if sub_trace_opened:+ await stream.progress(+ "",+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(+ iter_meta,+ {"trace_kind": "call_status", "call_state": "complete"},+ ),+ )++ text = "".join(content_acc)+ # Preserve the literal ``<think>...</think>`` block when we resolved the+ # iteration implicitly as ``THINK`` — the next iteration's assistant+ # context should reflect the model's reasoning verbatim, not a stripped+ # empty draft. For all other resolutions, fall through to the standard+ # cleanup so downstream consumers (assistant messages, final-response+ # text) aren't polluted with the prelude markers.+ implicit_think_resolved = bool(+ saw_pre_label_think+ and implicit_think_label+ and label == implicit_think_label+ )+ if (binding or saw_pre_label_think) and not implicit_think_resolved:+ text = clean_thinking_tags(text, binding, model)+ ordered_tool_calls = [tc_acc[k] for k in sorted(tc_acc.keys())]+ ordered_tool_calls = [tc for tc in ordered_tool_calls if tc.get("name")]+ return LabeledStepResult(label=label, text=text, tool_calls=ordered_tool_calls)diff --git a/deeptutor/core/agentic/labels.py b/deeptutor/core/agentic/labels.pynew file mode 100644index 000000000..5e331a028--- /dev/null+++ b/deeptutor/core/agentic/labels.py@@ -0,0 +1,119 @@+r"""Protocol-label parsing for streaming LLM responses.++The agentic engine drives LLM calls with a ``\`\`LABEL\`\`+content`` protocol:+prompts require one allowed label, double-backtick-wrapped, on the first line+of every reply, then the rest of the content. The parser detects that label+up front, tolerates a few provider/model formatting slips, and routes the+post-label stream accordingly.++Label sets are caller-supplied: chat uses ``(FINISH, TOOL, THINK)``, a solve+step uses ``(THINK, TOOL, FINISH, REPLAN)``, plan uses ``(PLAN,)``, etc.+"""++from __future__ import annotations++import re++LABEL_UNKNOWN = "UNKNOWN"+LABEL_PROBE_MAX_CHARS = 64++_INVISIBLE_PREFIX_CHARS = ""+_LABEL_SEPARATOR_CHARS = "\n\r \t::-–—"+++def strip_label_probe_prefix(buffer: str) -> str:+ """Trim leading whitespace and zero-width chars before label probing."""+ stripped = str(buffer or "")+ previous = None+ while stripped != previous:+ previous = stripped+ stripped = stripped.lstrip().lstrip(_INVISIBLE_PREFIX_CHARS)+ return stripped+++def classify_label(+ buffer: str,+ *,+ allowed_labels: tuple[str, ...],+ final: bool = False,+) -> tuple[str, str] | None:+ r"""Inspect a content buffer for a leading ``\`\`LABEL\`\``` prefix.++ Returns ``(label, after_text)`` once an allowed label is detected after any+ leading whitespace — caller routes ``after_text`` and all subsequent chunks+ accordingly.++ Returns ``None`` while the buffer is too short or still a partial prefix+ match. The caller keeps buffering and tries again on the next chunk, and+ must fall back to :data:`LABEL_UNKNOWN` once the buffer exceeds+ :data:`LABEL_PROBE_MAX_CHARS` without a match.++ Accepts the wrapped form (``\`\`LABEL\`\``` preferred, with common+ one-/three-backtick variants tolerated) and a bare fallback (``LABEL``+ followed by a separator) — some models drop or alter the backticks on+ one-shot prompts and the bare form is unambiguous as long as the+ protocol labels are all-uppercase tokens. The wrapped form may be+ followed immediately by body text because Markdown inline-code styling+ visually separates the label even when the raw stream has no whitespace+ (for example ``\`\`FINISH\`\`你好``).++ ``final=True`` means the caller knows no more chunks are coming, so an+ exact bare label such as ``FINISH`` can be accepted even without a+ trailing separator.+ """+ stripped = strip_label_probe_prefix(buffer)+ for label in allowed_labels:+ wrapped = re.match(+ rf"^(?P<ticks>`+)\s*{re.escape(label)}\s*(?P=ticks)(?P<after>.*)$",+ stripped,+ flags=re.DOTALL,+ )+ if wrapped is not None:+ after = wrapped.group("after")+ if after and after[0] == "`":+ # Avoid accepting an over-closed / still-streaming wrapper+ # such as ``FINISH``` and leaking the extra backtick into+ # the routed body. A non-backtick tail is real body text,+ # even when the model forgot the separator after the label.+ continue+ # Eat the separating newline / spaces / punctuation after the+ # label so the body / reasoning text doesn't start with stray+ # blank lines or a locale-specific colon.+ return label, after.lstrip(_LABEL_SEPARATOR_CHARS)+ # Bare-label fallback: only when the label is followed by a clear+ # separator so we don't false-positive on a body that happens to+ # start with a token like ``FINISHED``. An empty tail (label+ # exactly matches buffer) is ambiguous while streaming — keep+ # buffering until the next chunk reveals a separator or a+ # continuation char. At stream end (``final=True``), accept it.+ if stripped.startswith(label):+ tail = stripped[len(label) :]+ if tail and tail[0] in _LABEL_SEPARATOR_CHARS:+ return label, tail.lstrip(_LABEL_SEPARATOR_CHARS)+ if final and not tail:+ return label, ""+ return None+++def find_inline_labels(text: str, *, allowed_labels: tuple[str, ...]) -> list[str]:+ """Return labels that appear inside post-label body text.++ The protocol requires exactly one label per reply (on the first line).+ A second label found at the start of a later body line is a violation+ worth flagging. Mentions inside prose such as "next I should use+ ``TOOL``" are not action labels and must not trigger repair loops.+ """+ if not allowed_labels:+ return []+ pattern = "|".join(re.escape(label) for label in allowed_labels)+ raw = str(text or "")+ separators = re.escape(_LABEL_SEPARATOR_CHARS)+ wrapped = [+ match.group("label")+ for match in re.finditer(+ rf"(?m)^[^\S\r\n]*(?P<ticks>`+)\s*(?P<label>{pattern})\s*(?P=ticks)(?=$|[{separators}])",+ raw,+ )+ ]+ bare = re.findall(rf"(?m)^[^\S\r\n]*({pattern})(?=$|[{separators}])", raw)+ return [*wrapped, *bare]diff --git a/deeptutor/core/agentic/loop.py b/deeptutor/core/agentic/loop.pynew file mode 100644index 000000000..495509e32--- /dev/null+++ b/deeptutor/core/agentic/loop.py@@ -0,0 +1,458 @@+"""Label-driven iteration scheduler.++The agentic loop drives a conversation with the LLM until one of the+caller-declared *terminal labels* fires. Each iteration is one+:func:`~deeptutor.core.agentic.labeled_step.run_labeled_step` call, after+which the loop:++* validates the protocol (one label, no inline duplicates, tools only with+ the tool label),+* on a terminal label, optionally streams the buffered post-label text as+ body content (for labels in :attr:`LabelProtocol.final`) and exits,+* on the tool label, appends the assistant + tool messages and dispatches+ the requested tool calls via the host,+* on intermediate labels (e.g. ``THINK``), preserves the prose as+ assistant context so the next iteration builds on it,+* on protocol violations, emits a retry notice and feeds the host's+ repair message back into the conversation.++Capability-specific bits — context-window guard, iteration trace metadata,+tool dispatch, pause/terminate handling, max-iter forced finalization,+protocol-violation copy — are delegated to :class:`LoopHost`. The loop+itself stays capability-agnostic.+"""++from __future__ import annotations++from collections.abc import Awaitable+from dataclasses import dataclass, field+from typing import Any, Protocol++from deeptutor.core.agentic.labeled_step import LabeledStepResult, run_labeled_step+from deeptutor.core.agentic.labels import LABEL_UNKNOWN, find_inline_labels+from deeptutor.core.agentic.tool_dispatch import DispatchOutcome+from deeptutor.core.agentic.usage import UsageTracker+from deeptutor.core.stream_bus import StreamBus+++@dataclass(frozen=True)+class LabelProtocol:+ """Declarative description of a capability's label vocabulary.++ * ``allowed`` — every label the LLM may emit on the first line.+ * ``terminal`` — labels that exit the loop. The outcome's+ ``final_label`` reflects which one fired.+ * ``intermediate`` — labels that keep the loop running (the post-label+ prose is appended as assistant context).+ * ``final`` — labels whose post-label text should be emitted as+ body content via the host's ``emit_final``. ``final`` is independent+ of ``terminal`` / ``intermediate``: a terminal label may opt out of+ body emission (e.g. ``REPLAN`` bubbles up text without streaming),+ and an intermediate label may opt **in** to body emission so its+ text appears in the user-facing chat bubble while the loop continues+ (e.g. chat's ``PAUSE`` — narrate to the user mid-reasoning without+ ending the turn).+ * ``tool_label`` — the single label that means "call tools this+ round" (or ``None`` to disable native tool calling for this loop).+ """++ allowed: tuple[str, ...]+ terminal: frozenset[str]+ intermediate: frozenset[str]+ final: frozenset[str]+ tool_label: str | None+++@dataclass(frozen=True)+class LoopOutcome:+ """Result of one agentic loop run."""++ final_label: str # the label that exited the loop (empty when terminated by tool)+ final_text: str # post-label text (already streamed if in protocol.final)+ iterations: int+ sources: list[dict[str, Any]] = field(default_factory=list)+ messages: list[dict[str, Any]] = field(default_factory=list)+ completed: bool = False+++class LoopHost(Protocol):+ """Capability-supplied hooks the loop calls back into.++ Implementations bundle all chat-/solve-/etc.-specific behavior (trace+ metadata, tool dispatch, prompt copy) so the loop core stays generic.+ """++ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:+ """Optionally trim ``messages`` to keep within the model's window."""++ def build_iteration_trace_meta(+ self, iteration: int+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ """Allocate ``(iter_meta, final_meta)`` for one iteration."""++ async def dispatch_tools(+ self,+ *,+ iteration: int,+ tool_calls: list[dict[str, Any]],+ ) -> DispatchOutcome:+ """Execute the iteration's tool calls in parallel."""++ async def resolve_pause(self, dispatch: DispatchOutcome) -> bool:+ """Handle a ``pause_for_user`` request. Return ``True`` to resume."""++ async def emit_terminator(self, payload: dict[str, Any] | None) -> None:+ """Emit the terminating tool's content as a final-response event."""++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ """Emit body content for a label in :attr:`LabelProtocol.final`."""++ async def validate_terminal(self, label: str, text: str) -> str | None:+ """Optional stateful validation before accepting a terminal label.++ Return a protocol-violation key to repair/retry instead of ending+ the loop, or ``None`` to accept the terminal label.+ """+ return None++ def assistant_message_with_tool_calls(+ self,+ *,+ content: str,+ tool_calls: list[dict[str, Any]],+ ) -> dict[str, Any]:+ """Format the assistant turn that carries this iteration's tool calls."""++ def protocol_retry_notice(self) -> str:+ """Notice text shown when a protocol violation triggers a retry."""++ def protocol_repair_message(self, violation: str) -> str:+ """Per-violation correction prompt fed back to the next LLM call."""++ async def force_finalize(+ self,+ *,+ messages: list[dict[str, Any]],+ start_iteration: int,+ ) -> tuple[str, bool, int]:+ """Drive whatever recovery the capability wants when ``max_iterations``+ is exhausted without a terminal label. Returns+ ``(final_text, completed, extra_iterations_consumed)``."""++ async def before_iteration(+ self,+ *,+ messages: list[dict[str, Any]],+ iteration: int,+ max_iterations: int,+ ) -> None:+ """Optional hook fired at the start of each iteration, **after**+ :py:meth:`guard_context_window` and **before** the LLM call.++ Capabilities can use this to inject per-iteration context the model+ should see — e.g. a small "you are at iteration N/M" marker so the+ LLM can pace itself. The hook mutates ``messages`` in place; the+ loop checks for the method's presence with ``getattr`` so existing+ hosts keep working unchanged. Returning anything is ignored.+ """+ return None++ async def on_intermediate(self, label: str, text: str) -> str | None:+ """Optional side-effect hook for intermediate labels.++ Called *after* the loop has appended an intermediate label's+ post-label prose as an assistant message, before the next+ iteration begins. Capabilities can override to mutate their own+ state (e.g. extending a dynamic topic queue when an ``APPEND``+ label fires) and optionally return a non-empty string which the+ loop appends as a ``role=user`` feedback message — useful to+ confirm a successful mutation or report a rejection so the LLM+ can adapt in the next iteration.++ Returning ``None`` (the default) is a no-op. Implementing this+ hook is optional — hosts that omit it preserve the legacy+ behaviour of just appending the prose and continuing. The loop+ checks for the method's presence with ``getattr`` so existing+ hosts (chat, solve) keep working unchanged without having to+ spell out a stub.+ """+ return None+++async def run_agentic_loop(+ *,+ initial_messages: list[dict[str, Any]],+ protocol: LabelProtocol,+ client: Any,+ model: str | None,+ completion_kwargs: dict[str, Any],+ binding: str | None,+ tool_schemas: list[dict[str, Any]] | None,+ stream: StreamBus,+ source: str,+ stage: str,+ max_iterations: int,+ host: LoopHost,+ usage: UsageTracker | None = None,+ stream_body_live: bool = False,+ eager_sub_trace: bool = False,+ implicit_think_label: str | None = None,+) -> LoopOutcome:+ """Run a label-driven LLM loop until a terminal label fires or the+ iteration budget is exhausted.++ ``initial_messages`` is mutated in place (and returned via+ :attr:`LoopOutcome.messages`) so the caller can inspect / reuse the+ full message history if needed.++ ``stream_body_live=True`` makes the labeled step stream final-label+ chunks directly to ``stream.content`` (chunk-by-chunk body output) and+ causes the loop to skip :py:meth:`LoopHost.emit_final` — the text is+ already on the wire. Default ``False`` preserves chat's existing+ one-shot emit behavior.++ ``eager_sub_trace=True`` opens the per-iteration sub-trace card before+ the LLM stream begins, eliminating the visible "nothing happening"+ gap during each call's time-to-first-token (network + model warm-up).+ Default ``False`` keeps chat's lazy-open behavior so FINISH-only+ iterations don't spawn empty "Reasoning…" cards.+ """+ messages = initial_messages+ aggregated_sources: list[dict[str, Any]] = []+ final_text = ""+ final_label_seen = ""+ completed = False+ iterations_run = 0+ max_iter = max(1, max_iterations)++ for iteration in range(max_iter):+ await host.guard_context_window(messages)+ before_iteration = getattr(host, "before_iteration", None)+ if before_iteration is not None:+ await before_iteration(+ messages=messages,+ iteration=iteration,+ max_iterations=max_iter,+ )+ iter_meta, final_meta = host.build_iteration_trace_meta(iteration)++ step = await run_labeled_step(+ client=client,+ model=model,+ messages=messages,+ completion_kwargs=completion_kwargs,+ tool_schemas=tool_schemas,+ allowed_labels=protocol.allowed,+ final_labels=protocol.final,+ tool_label=protocol.tool_label,+ stream=stream,+ source=source,+ stage=stage,+ iter_meta=iter_meta,+ binding=binding,+ usage=usage,+ final_meta=final_meta if stream_body_live else None,+ eager_sub_trace=eager_sub_trace,+ implicit_think_label=implicit_think_label,+ )+ iterations_run += 1++ violation = _protocol_violation(step, protocol)+ if violation:+ await _emit_retry_notice(+ stream=stream,+ source=source,+ stage=stage,+ host=host,+ violation=violation,+ )+ _append_repair_messages(+ messages=messages,+ iteration_text=step.text,+ violation=violation,+ host=host,+ )+ continue++ if step.label in protocol.terminal:+ validate_terminal = getattr(host, "validate_terminal", None)+ if validate_terminal is not None:+ violation = await validate_terminal(step.label, step.text)+ if violation:+ await _emit_retry_notice(+ stream=stream,+ source=source,+ stage=stage,+ host=host,+ violation=violation,+ )+ _append_repair_messages(+ messages=messages,+ iteration_text=step.text,+ violation=violation,+ host=host,+ )+ continue+ if step.label in protocol.final and not stream_body_live:+ # When body chunks have already been streamed live by+ # ``run_labeled_step``, calling ``host.emit_final`` here+ # would double-emit the text into the chat bubble.+ await host.emit_final(step.text, final_meta)+ final_text = step.text+ final_label_seen = step.label+ completed = True+ break++ if protocol.tool_label is not None and step.label == protocol.tool_label:+ messages.append(+ host.assistant_message_with_tool_calls(+ content=step.text,+ tool_calls=step.tool_calls,+ )+ )+ outcome = await host.dispatch_tools(+ iteration=iteration,+ tool_calls=step.tool_calls,+ )+ aggregated_sources.extend(outcome.sources)+ messages.extend(outcome.tool_messages)+ if outcome.pause:+ resumed = await host.resolve_pause(outcome)+ if not resumed:+ completed = False+ break+ continue+ if outcome.terminate:+ await host.emit_terminator(outcome.terminate_payload)+ final_text = (outcome.terminate_payload or {}).get("content", "")+ completed = True+ break+ continue++ if step.label in protocol.intermediate:+ # An intermediate label may also be marked ``final``: that+ # means "stream this prose into the user-facing chat bubble,+ # but don't end the turn" (chat's ``PAUSE``). The text is+ # also kept as assistant context below so the next iteration+ # sees what was already told to the user.+ if step.label in protocol.final and step.text and not stream_body_live:+ await host.emit_final(step.text, final_meta)+ if step.text:+ messages.append({"role": "assistant", "content": step.text})+ # Optional hook for capabilities that attach side-effects to+ # intermediate labels (e.g. research's ``APPEND`` mutates the+ # topic queue). When the hook returns a non-empty string we+ # inject it as the next iteration's user message so the+ # model sees structured feedback (e.g. "Appended block #4").+ on_intermediate = getattr(host, "on_intermediate", None)+ if on_intermediate is not None:+ feedback = await on_intermediate(step.label, step.text)+ if feedback:+ messages.append({"role": "user", "content": feedback})+ continue++ # Defensive fallback for any future label value not covered above.+ # Do not terminate; repair and retry.+ await _emit_retry_notice(+ stream=stream,+ source=source,+ stage=stage,+ host=host,+ violation="unknown_action",+ )+ _append_repair_messages(+ messages=messages,+ iteration_text=step.text,+ violation="unknown_action",+ host=host,+ )+ continue+ else:+ finish_text, did_finish, extra_calls = await host.force_finalize(+ messages=messages,+ start_iteration=max_iter,+ )+ iterations_run += extra_calls+ final_text = finish_text+ completed = did_finish++ return LoopOutcome(+ final_label=final_label_seen,+ final_text=final_text,+ iterations=iterations_run,+ sources=aggregated_sources,+ messages=messages,+ completed=completed,+ )+++def _protocol_violation(+ step: LabeledStepResult,+ protocol: LabelProtocol,+) -> str | None:+ """Classify a labeled-step result against the protocol; return a+ violation key (matching the host's repair-message vocabulary) or+ ``None`` if compliant."""+ if step.label == LABEL_UNKNOWN:+ return "missing_label"+ if find_inline_labels(step.text, allowed_labels=protocol.allowed):+ return "multiple_labels"+ if protocol.tool_label is not None:+ if step.label == protocol.tool_label and not step.tool_calls:+ return "tool_without_calls"+ if step.label != protocol.tool_label and step.tool_calls:+ # The violation key carries the actual offending label so the+ # host can render an accurate repair message. The legacy keys+ # ``think_with_tools`` / ``finish_with_tools`` are still+ # produced for the canonical THINK/FINISH labels, but new+ # label vocabularies (e.g. chat's ``PAUSE`` — intermediate ++ # final) get their own ``{label}_with_tools`` key.+ return f"{step.label.lower()}_with_tools"+ return None+++async def _emit_retry_notice(+ *,+ stream: StreamBus,+ source: str,+ stage: str,+ host: LoopHost,+ violation: str,+) -> None:+ await stream.progress(+ host.protocol_retry_notice(),+ source=source,+ stage=stage,+ metadata={"trace_kind": "warning", "protocol_violation": violation},+ )+++_REPAIR_PREVIEW_CHARS = 500+++def _append_repair_messages(+ *,+ messages: list[dict[str, Any]],+ iteration_text: str,+ violation: str,+ host: LoopHost,+) -> None:+ """Preserve the model's unlabeled draft as assistant context, then add+ a correction prompt that tells the next iteration what to do."""+ clipped = str(iteration_text or "").strip()+ if clipped:+ if len(clipped) > _REPAIR_PREVIEW_CHARS:+ clipped = clipped[:_REPAIR_PREVIEW_CHARS].rstrip() + "\n...[truncated]"+ messages.append({"role": "assistant", "content": clipped})+ messages.append({"role": "user", "content": host.protocol_repair_message(violation)})+++# Re-export ``Awaitable`` here so consumers needn't import it just to type+# their host implementations (mirrors what ``asyncio`` does with ``Future``).+__all__ = [+ "Awaitable",+ "LabelProtocol",+ "LoopHost",+ "LoopOutcome",+ "run_agentic_loop",+]diff --git a/deeptutor/core/agentic/tool_dispatch.py b/deeptutor/core/agentic/tool_dispatch.pynew file mode 100644index 000000000..f9a34d1bb--- /dev/null+++ b/deeptutor/core/agentic/tool_dispatch.py@@ -0,0 +1,517 @@+"""Parallel tool-call dispatch with per-tool sub-traces.++Lifted from chat's pipeline. Capability-agnostic: the caller supplies:++* a ``KwargAugmenter`` — how to enrich the LLM-supplied tool args with+ server-side context (e.g. chat injects ``source_index`` for ``read_source``;+ solve will do the same for its own tools).+* a ``RetrieveMetaFactory`` — how to derive a "retrieve" trace variant for+ rag-flavored tools (so their internal progress events stay grouped under+ the same sub-trace icon).+* labels for the trace UI rows (``tool_call``, ``retrieve``) plus the+ capability-specific copy for empty results / over-quota / unknown errors.++The dispatcher executes all tool calls in parallel, emits one sub-trace per+tool call, and returns a :class:`DispatchOutcome` carrying the role=tool+messages, accumulated sources, and pause/terminate signals for the loop.+"""++from __future__ import annotations++import asyncio+from collections.abc import Awaitable, Callable+from dataclasses import dataclass, field+import json+import logging+from typing import Any++from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import (+ build_trace_metadata,+ derive_trace_metadata,+ merge_trace_metadata,+ new_call_id,+)+from deeptutor.runtime.registry.tool_registry import ToolRegistry, get_tool_registry+from deeptutor.utils.json_parser import parse_json_response++logger = logging.getLogger(__name__)++MAX_PARALLEL_TOOL_CALLS = 8+++KwargAugmenter = Callable[[str, dict[str, Any], UnifiedContext], dict[str, Any]]+RetrieveMetaFactory = Callable[+ [dict[str, Any], str, dict[str, Any]], dict[str, Any] | None+]+UnknownErrorMessageFactory = Callable[[str], str]+++@dataclass(frozen=True)+class DispatchOutcome:+ """Aggregated result of one iteration's tool dispatch.++ * ``terminate`` — a tool requested the loop end after this iteration; its+ content becomes the terminal assistant artefact. No built-in chat tool+ currently uses this; ``ask_user`` switched to ``pause`` instead.+ * ``pause`` (e.g. ``ask_user``) — the turn stays alive; the caller awaits+ a user reply, substitutes it into the matching ``role=tool`` message,+ and resumes iterating. The first tool to request pause wins; other+ parallel tools still execute and their results ride along.+ """++ sources: list[dict[str, Any]] = field(default_factory=list)+ tool_messages: list[dict[str, Any]] = field(default_factory=list)+ tool_metadata_by_id: dict[str, dict[str, Any]] = field(default_factory=dict)+ terminate: bool = False+ terminate_payload: dict[str, Any] | None = None+ pause: bool = False+ pause_payload: dict[str, Any] | None = None+ pause_tool_call_id: str | None = None+++async def dispatch_tool_calls(+ *,+ tool_calls: list[dict[str, Any]],+ context: UnifiedContext,+ stream: StreamBus,+ source: str,+ stage: str,+ iteration_index: int,+ registry: ToolRegistry | None = None,+ kwarg_augmenter: KwargAugmenter | None = None,+ retrieve_meta_factory: RetrieveMetaFactory | None = None,+ tool_call_label: str = "Tool call",+ retrieve_label: str = "Retrieve",+ empty_tool_result_message: str = "",+ start_retrieval_message: str = "Starting retrieval",+ too_many_tool_calls_message: str | None = None,+ unknown_error_message_factory: UnknownErrorMessageFactory | None = None,+ trace_id_prefix: str = "iter",+) -> DispatchOutcome:+ """Execute tool calls in parallel and assemble a :class:`DispatchOutcome`."""+ registry = registry or get_tool_registry()++ if len(tool_calls) > MAX_PARALLEL_TOOL_CALLS:+ if too_many_tool_calls_message:+ await stream.progress(+ too_many_tool_calls_message,+ source=source,+ stage=stage,+ metadata={"trace_kind": "warning"},+ )+ tool_calls = tool_calls[:MAX_PARALLEL_TOOL_CALLS]++ prepared = _prepare_tool_args(tool_calls, context, kwarg_augmenter)+ # Collapse duplicates within this parallel batch. Models occasionally+ # emit repeated tool_calls in one assistant message. For most tools,+ # "duplicate" means same tool + same JSON-normalised args. For+ # ``ask_user``, any second call in the same batch is a duplicate even+ # when args differ: multiple ask_user calls would render multiple+ # cards while the runtime can only pause on one reply.+ #+ # The first occurrence runs as normal; later duplicates short-circuit+ # to a stub role=tool result so OpenAI's tool-call/tool-message pairing+ # stays intact for the next API call. Duplicate ``ask_user`` calls are+ # also hidden from the user-facing trace stream to avoid duplicate Ask+ # Me rows/cards during the live turn.+ duplicate_of = _detect_duplicate_calls(prepared)+ suppress_ui_indices = {+ idx for idx in duplicate_of if prepared[idx][1] == "ask_user"+ }+ per_tool_trace_meta = _build_per_tool_trace_meta(+ prepared,+ context=context,+ iteration_index=iteration_index,+ stage=stage,+ tool_call_label=tool_call_label,+ trace_id_prefix=trace_id_prefix,+ )++ for tool_index, (_tcid, tool_name, exec_args) in enumerate(prepared):+ if tool_index in suppress_ui_indices:+ continue+ await stream.tool_call(+ tool_name=tool_name,+ args=exec_args,+ source=source,+ stage=stage,+ metadata=merge_trace_metadata(+ per_tool_trace_meta[tool_index],+ {"trace_kind": "tool_call"},+ ),+ )++ async def _run_one(tool_index: int) -> dict[str, Any]:+ primary_idx = duplicate_of.get(tool_index)+ if primary_idx is not None:+ primary_call_id = prepared[primary_idx][0]+ return _duplicate_stub_result(+ primary_call_id=primary_call_id,+ tool_name=prepared[tool_index][1],+ )+ _tcid, tool_name, exec_args = prepared[tool_index]+ return await execute_tool_call(+ registry=registry,+ tool_name=tool_name,+ tool_args=exec_args,+ stream=stream,+ source=source,+ stage=stage,+ retrieve_meta=(+ retrieve_meta_factory(+ per_tool_trace_meta[tool_index],+ tool_name,+ exec_args,+ )+ if retrieve_meta_factory+ else None+ ),+ empty_tool_result_message=empty_tool_result_message,+ start_retrieval_message=start_retrieval_message,+ unknown_error_message_factory=unknown_error_message_factory,+ retrieve_label=retrieve_label,+ )++ results = await asyncio.gather(*[_run_one(i) for i in range(len(prepared))])++ return await _collect_outcome(+ prepared=prepared,+ results=results,+ per_tool_trace_meta=per_tool_trace_meta,+ suppress_ui_indices=suppress_ui_indices,+ stream=stream,+ source=source,+ stage=stage,+ )+++def _detect_duplicate_calls(+ prepared: list[tuple[str, str, dict[str, Any]]],+) -> dict[int, int]:+ """Map duplicate-call indices to their primary occurrence.++ Two calls are duplicates when their (tool_name, JSON-normalised+ args) keys are identical. ``ask_user`` is stricter: the first+ ``ask_user`` call is the primary and every later ``ask_user`` in the+ same parallel batch maps to it, regardless of args, because the UI and+ pause/resume runtime only support one pending Ask Me card per model+ tool batch. Non-serialisable args fall through to ``str()`` so unusual+ values still produce a deterministic key.+ """+ duplicate_of: dict[int, int] = {}+ seen: dict[tuple[str, str], int] = {}+ first_ask_user_idx: int | None = None+ for idx, (_tcid, tool_name, exec_args) in enumerate(prepared):+ if tool_name == "ask_user":+ if first_ask_user_idx is not None:+ duplicate_of[idx] = first_ask_user_idx+ continue+ first_ask_user_idx = idx+ try:+ args_key = json.dumps(exec_args, sort_keys=True, default=str)+ except (TypeError, ValueError):+ args_key = str(exec_args)+ key = (tool_name, args_key)+ primary = seen.get(key)+ if primary is None:+ seen[key] = idx+ else:+ duplicate_of[idx] = primary+ return duplicate_of+++def _duplicate_stub_result(+ *,+ primary_call_id: str,+ tool_name: str,+) -> dict[str, Any]:+ """Synthetic result for a duplicate parallel tool_call.++ Carries no ``pause_for_user`` / ``terminate_turn`` / ``metadata`` so+ only the primary call drives pause/terminate decisions and the+ frontend renders a single card. The ``result_text`` is a directive+ aimed at the model: a one-line explanation it can read in the next+ iteration so it learns not to emit identical parallel tool_calls.+ """+ if tool_name == "ask_user":+ result_text = (+ "(duplicate parallel ask_user tool_call — skipped. The earlier "+ f"ask_user call with id={primary_call_id!r} is the only one that "+ "will pause for the user's reply. Ask all clarifying questions in "+ "one ask_user call's `questions` list; never emit multiple "+ "ask_user tool_calls in one assistant message.)"+ )+ else:+ result_text = (+ "(duplicate parallel tool_call — skipped. The identical call "+ f"with id={primary_call_id!r} already ran in this batch; "+ "see its result. Do NOT emit two identical tool_calls in one "+ "assistant message — parallel calls must differ in arguments.)"+ )+ return {+ "result_text": result_text,+ "sources": [],+ }+++def _prepare_tool_args(+ tool_calls: list[dict[str, Any]],+ context: UnifiedContext,+ kwarg_augmenter: KwargAugmenter | None,+) -> list[tuple[str, str, dict[str, Any]]]:+ prepared: list[tuple[str, str, dict[str, Any]]] = []+ for tc in tool_calls:+ tool_name = str(tc.get("name") or "").strip()+ tool_call_id = str(tc.get("id") or "").strip()+ tool_args = parse_json_response(+ tc.get("arguments") or "{}",+ logger_instance=logger,+ fallback={},+ )+ if not isinstance(tool_args, dict):+ tool_args = {}+ exec_args = (+ kwarg_augmenter(tool_name, tool_args, context)+ if kwarg_augmenter is not None+ else dict(tool_args)+ )+ prepared.append((tool_call_id, tool_name, exec_args))+ return prepared+++def _build_per_tool_trace_meta(+ prepared: list[tuple[str, str, dict[str, Any]]],+ *,+ context: UnifiedContext,+ iteration_index: int,+ stage: str,+ tool_call_label: str,+ trace_id_prefix: str,+) -> list[dict[str, Any]]:+ """Allocate a fresh trace ``call_id`` for each tool so each appears as its+ own sub-trace row in the frontend's CallTracePanel."""+ metas: list[dict[str, Any]] = []+ for tool_index, (tool_call_id, tool_name, _exec_args) in enumerate(prepared):+ trace_call_id = new_call_id(+ f"{trace_id_prefix}-{iteration_index}-tool-{tool_index}"+ )+ base_meta = build_trace_metadata(+ call_id=trace_call_id,+ phase=stage,+ label=tool_call_label,+ call_kind="tool_planning",+ trace_id=trace_call_id,+ trace_role="tool",+ trace_group="tool_call",+ )+ metas.append(+ merge_trace_metadata(+ base_meta,+ {+ "tool_call_id": tool_call_id,+ "tool_name": tool_name,+ "tool_index": tool_index,+ "iteration_index": iteration_index,+ "session_id": context.session_id,+ "turn_id": str(context.metadata.get("turn_id", "")),+ },+ )+ )+ return metas+++async def execute_tool_call(+ *,+ registry: ToolRegistry,+ tool_name: str,+ tool_args: dict[str, Any],+ stream: StreamBus,+ source: str,+ stage: str,+ retrieve_meta: dict[str, Any] | None,+ empty_tool_result_message: str = "",+ start_retrieval_message: str = "Starting retrieval",+ retrieve_label: str = "Retrieve",+ unknown_error_message_factory: UnknownErrorMessageFactory | None = None,+) -> dict[str, Any]:+ """Run one tool, emitting retrieve-flavored progress events when relevant.++ Returns a structured ``{result_text, success, sources, metadata,+ terminate_turn, pause_for_user}`` dict (same shape the dispatcher uses+ internally). Capabilities that want to invoke a single tool outside the+ parallel-dispatch path call this directly.+ """++ async def _event_sink(+ event_type: str,+ message: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ if retrieve_meta is None or not message:+ return+ await stream.progress(+ message,+ source=source,+ stage=stage,+ metadata=derive_trace_metadata(+ retrieve_meta,+ trace_kind=str(event_type or "tool_log"),+ **(metadata or {}),+ ),+ )++ if retrieve_meta is not None:+ query = str(retrieve_meta.get("query") or tool_args.get("query") or "").strip()+ await stream.progress(+ f"Query: {query}" if query else start_retrieval_message,+ source=source,+ stage=stage,+ metadata=derive_trace_metadata(+ retrieve_meta,+ trace_kind="call_status",+ call_state="running",+ ),+ )+ try:+ result = await registry.execute(+ tool_name,+ event_sink=_event_sink if retrieve_meta is not None else None,+ **tool_args,+ )+ if retrieve_meta is not None:+ await stream.progress(+ f"Retrieve complete ({len(result.content)} chars)",+ source=source,+ stage=stage,+ metadata=derive_trace_metadata(+ retrieve_meta,+ trace_kind="call_status",+ call_state="complete",+ ),+ )+ return {+ "result_text": result.content or empty_tool_result_message,+ "success": result.success,+ "sources": result.sources,+ "metadata": result.metadata,+ "terminate_turn": getattr(result, "terminate_turn", False),+ "pause_for_user": getattr(result, "pause_for_user", None),+ }+ except Exception as exc:+ logger.error("Tool %s failed", tool_name, exc_info=True)+ if retrieve_meta is not None:+ await stream.error(+ f"Retrieve failed: {exc}",+ source=source,+ stage=stage,+ metadata=derive_trace_metadata(+ retrieve_meta,+ trace_kind="call_status",+ call_state="error",+ error=str(exc),+ ),+ )+ unknown_msg = (+ unknown_error_message_factory(tool_name)+ if unknown_error_message_factory is not None+ else f"Error executing {tool_name}: {exc}"+ )+ return {+ "result_text": unknown_msg,+ "success": False,+ "sources": [],+ "metadata": {"error": str(exc)},+ "terminate_turn": False,+ "pause_for_user": None,+ }+++async def _collect_outcome(+ *,+ prepared: list[tuple[str, str, dict[str, Any]]],+ results: list[dict[str, Any]],+ per_tool_trace_meta: list[dict[str, Any]],+ suppress_ui_indices: set[int] | None = None,+ stream: StreamBus,+ source: str,+ stage: str,+) -> DispatchOutcome:+ """Walk tool results: emit ``tool_result`` events and assemble the outcome.++ First terminating tool wins; first paused tool wins independently. Pause+ and terminate are mutually exclusive at the loop level — pause skips+ terminator emission because the loop will produce a real final answer+ after the user reply resumes.+ """+ aggregated_sources: list[dict[str, Any]] = []+ tool_messages: list[dict[str, Any]] = []+ tool_metadata_by_id: dict[str, dict[str, Any]] = {}+ terminate = False+ terminate_payload: dict[str, Any] | None = None+ pause = False+ pause_payload: dict[str, Any] | None = None+ pause_tool_call_id: str | None = None+ suppress_ui_indices = suppress_ui_indices or set()+ for tool_index, ((tool_call_id, tool_name, _exec_args), result) in enumerate(+ zip(prepared, results, strict=False)+ ):+ result_text = str(result["result_text"])+ tool_meta = per_tool_trace_meta[tool_index]+ tool_extra_meta = (+ result.get("metadata") if isinstance(result, dict) else None+ )+ result_event_meta = merge_trace_metadata(+ tool_meta, {"trace_kind": "tool_result"}+ )+ if isinstance(tool_extra_meta, dict) and tool_extra_meta:+ result_event_meta = merge_trace_metadata(+ result_event_meta,+ {"tool_metadata": dict(tool_extra_meta)},+ )+ if tool_index not in suppress_ui_indices:+ await stream.tool_result(+ tool_name=tool_name,+ result=result_text,+ source=source,+ stage=stage,+ metadata=result_event_meta,+ )+ aggregated_sources.extend(result.get("sources") or [])+ tool_messages.append(+ {+ "role": "tool",+ "tool_call_id": tool_call_id,+ "name": tool_name,+ "content": result_text,+ }+ )+ if isinstance(tool_extra_meta, dict) and tool_extra_meta:+ tool_metadata_by_id[tool_call_id] = dict(tool_extra_meta)+ if result.get("terminate_turn") and not terminate:+ terminate = True+ terminate_payload = {+ "tool_name": tool_name,+ "content": result_text,+ "metadata": dict(tool_extra_meta) if isinstance(tool_extra_meta, dict) else {},+ }+ pause_request = result.get("pause_for_user")+ if pause_request and not pause:+ pause = True+ pause_payload = {+ "tool_name": tool_name,+ "ask_user": pause_request,+ }+ pause_tool_call_id = tool_call_id++ return DispatchOutcome(+ sources=aggregated_sources,+ tool_messages=tool_messages,+ tool_metadata_by_id=tool_metadata_by_id,+ terminate=terminate,+ terminate_payload=terminate_payload,+ pause=pause,+ pause_payload=pause_payload,+ pause_tool_call_id=pause_tool_call_id,+ )diff --git a/deeptutor/core/agentic/usage.py b/deeptutor/core/agentic/usage.pynew file mode 100644index 000000000..831eb8a6f--- /dev/null+++ b/deeptutor/core/agentic/usage.py@@ -0,0 +1,96 @@+"""Token-usage accumulator shared across LLM calls within a single turn."""++from __future__ import annotations++from typing import Any+++class UsageTracker:+ """Accumulate prompt/completion tokens across many streaming LLM calls.++ Two ingestion paths:++ * :meth:`add_from_response` — read OpenAI ``CompletionUsage`` (or the+ streaming ``usage`` chunk) when the provider returns it.+ * :meth:`add_estimated` — fall back to a coarse ``chars / 3.5`` estimate+ for providers that don't emit ``usage`` (used by chat's answer-now path).++ Construct with ``model=<name>`` so :meth:`summary` can resolve a+ ``total_cost_usd`` via the pricing table in ``deeptutor.logging.stats``.+ """++ def __init__(self, *, model: str | None = None) -> None:+ self.prompt_tokens: int = 0+ self.completion_tokens: int = 0+ self.total_tokens: int = 0+ self.calls: int = 0+ self.model: str | None = model++ def add_from_response(self, response_or_usage: Any) -> None:+ usage = getattr(response_or_usage, "usage", None) or response_or_usage+ prompt = int(getattr(usage, "prompt_tokens", 0) or 0)+ completion = int(getattr(usage, "completion_tokens", 0) or 0)+ total = int(getattr(usage, "total_tokens", prompt + completion) or 0)+ if prompt or completion or total:+ self.prompt_tokens += prompt+ self.completion_tokens += completion+ self.total_tokens += total+ self.calls += 1++ def add_estimated(self, *, input_chars: int, output_chars: int) -> None:+ est_input = int(input_chars / 3.5)+ est_output = int(output_chars / 3.5)+ self.prompt_tokens += est_input+ self.completion_tokens += est_output+ self.total_tokens += est_input + est_output+ self.calls += 1++ def add_usage(+ self,+ *,+ agent_name: str = "",+ stage: str = "",+ model: str = "",+ system_prompt: str = "",+ user_prompt: str = "",+ response_text: str = "",+ ) -> None:+ """Adapter for :class:`~deeptutor.agents.base_agent.BaseAgent`.++ ``BaseAgent._track_tokens`` looks for an external tracker exposing+ ``add_usage(...)``; this method lets a :class:`UsageTracker` be+ passed as the ``token_tracker`` constructor argument so a+ capability pipeline can aggregate cost across all of its+ BaseAgent-derived sub-agents in one place.++ We fall back to a character-based estimate because BaseAgent+ only hands us the prompt/response text (the raw provider usage+ object is not available at that layer).+ """+ if model and not self.model:+ self.model = model+ input_chars = len(system_prompt or "") + len(user_prompt or "")+ output_chars = len(response_text or "")+ if input_chars or output_chars:+ self.add_estimated(input_chars=input_chars, output_chars=output_chars)++ def summary(self) -> dict[str, Any] | None:+ if self.calls == 0:+ return None+ cost_usd = 0.0+ if self.model:+ # Local import keeps ``core.agentic`` import-light at module load.+ from deeptutor.logging.stats.llm_stats import get_pricing++ pricing = get_pricing(self.model)+ cost_usd = (+ (self.prompt_tokens / 1000.0) * pricing.get("input", 0.0)+ + (self.completion_tokens / 1000.0) * pricing.get("output", 0.0)+ )+ return {+ "total_cost_usd": cost_usd,+ "total_tokens": self.total_tokens,+ "total_calls": self.calls,+ "prompt_tokens": self.prompt_tokens,+ "completion_tokens": self.completion_tokens,+ }diff --git a/tests/agents/question/test_generator.py b/tests/agents/question/test_generator.pydeleted file mode 100644index 1e0f68aa8..000000000--- a/tests/agents/question/test_generator.py+++ /dev/null@@ -1,88 +0,0 @@-from __future__ import annotations--import pytest--from deeptutor.agents.question.agents.generator import Generator-from deeptutor.agents.question.models import QuestionTemplate---class StubGenerator(Generator):- def __init__(self, repaired_payload: dict | None = None) -> None:- self._repaired_payload = repaired_payload or {}-- async def _repair_payload(self, **kwargs): # type: ignore[override]- return self._repaired_payload---async def test_generator_repairs_coding_question_that_looks_like_multiple_choice() -> None:- generator = StubGenerator(- repaired_payload={- "question_type": "coding",- "question": "Write pseudocode that alternates answer order across iterations to mitigate positional bias.",- "options": None,- "correct_answer": 'for i in range(total_iterations):\n if i % 2 == 0:\n prompt = f"{query} Answer 1: {answer1} Answer 2: {answer2}"\n else:\n prompt = f"{query} Answer 1: {answer2} Answer 2: {answer1}"\n evaluate(prompt)',- "explanation": "Alternate the two answers deterministically so each appears in each position equally often.",- }- )- template = QuestionTemplate(- question_id="q_3",- concentration="win-rate comparison positional bias mitigation",- question_type="coding",- difficulty="hard",- )- invalid_payload = {- "question_type": "coding",- "question": "Select the code logic that best mitigates positional bias across iterations.",- "options": {- "A": "fixed order",- "B": "alternate order every iteration",- "C": "randomize order",- "D": "always reverse order",- },- "correct_answer": "B",- "explanation": "B is correct.",- }-- normalized, validation = await generator._validate_and_repair_payload(- template=template,- payload=invalid_payload,- user_topic="win-rate comparison",- preference="",- history_context="",- knowledge_context="",- available_tools="(no tools available)",- )-- assert normalized["question_type"] == "coding"- assert normalized["options"] is None- assert normalized["correct_answer"].startswith("for i in range")- assert validation["repaired"] is True- assert validation["schema_ok"] is True- assert validation["issues"] == []---def test_generator_normalizes_choice_answer_from_option_text() -> None:- payload = Generator._normalize_payload_shape(- "choice",- {- "question_type": "choice",- "question": "Which option is correct?",- "options": {- "a": "Alpha",- "b": "Beta",- "c": "Gamma",- "d": "Delta",- },- "correct_answer": "Gamma",- "explanation": "Because gamma matches the requirement.",- },- )-- assert payload["options"] == {- "A": "Alpha",- "B": "Beta",- "C": "Gamma",- "D": "Delta",- }- assert payload["correct_answer"] == "C"diff --git a/tests/agents/question/test_language_prompts.py b/tests/agents/question/test_language_prompts.pyindex 4e99f005a..33d02b6d1 100644--- a/tests/agents/question/test_language_prompts.py+++ b/tests/agents/question/test_language_prompts.py@@ -1,70 +1,20 @@from __future__ import annotations-from types import SimpleNamespace+from typing import Anyimport pytestfrom deeptutor.agents.question.agents.followup_agent import FollowupAgent-from deeptutor.agents.question.agents.generator import Generator-from deeptutor.agents.question.agents.idea_agent import IdeaAgent-from deeptutor.agents.question.models import QuestionTemplate---class CaptureIdeaAgent(IdeaAgent):- def __init__(self, language: str = "zh") -> None:- self.language = language- self.prompts = {- "system": "Idea agent system",- "generate_ideas": (- "Topic: {user_topic}\n"- "Preference: {preference}\n"- "Knowledge context:\n{knowledge_context}\n"- "Existing concentrations:\n{existing_concentrations}\n"- 'Return JSON {{"ideas":[{{"idea_id":"idea_1","concentration":"基础概念","question_type":"written","difficulty":"medium","rationale":"覆盖核心知识点"}}]}}'- ),- }- self.logger = SimpleNamespace(warning=lambda *args, **kwargs: None)- self.captured_system_prompts: list[str] = []-- async def stream_llm(self, **kwargs): # type: ignore[override]- self.captured_system_prompts.append(str(kwargs["system_prompt"]))- yield (- '{"ideas":[{"idea_id":"idea_1","concentration":"基础概念",'- '"question_type":"written","difficulty":"medium",'- '"rationale":"覆盖核心知识点"}]}'- )---class CaptureGenerator(Generator):- def __init__(self, language: str = "zh") -> None:- self.language = language- self.prompts = {- "system": "Generator system",- "generate": (- "QuestionTemplate:\n{template}\n"- "User topic:\n{user_topic}\n"- "User preference:\n{preference}\n"- "Knowledge context:\n{knowledge_context}\n"- "Tools:\n{available_tools}\n"- "History:\n{history_context}\n"- "Previous questions:\n{previous_questions}\n"- 'Return JSON {{"question_type":"written","question":"问题","options":null,"correct_answer":"答案","explanation":"解释"}}'- ),- }- self.captured_system_prompts: list[str] = []-- async def stream_llm(self, **kwargs): # type: ignore[override]- self.captured_system_prompts.append(str(kwargs["system_prompt"]))- yield (- '{"question_type":"written","question":"问题",'- '"options":null,"correct_answer":"答案","explanation":"解释"}'- )class CaptureFollowupAgent(FollowupAgent):+ """``FollowupAgent`` subclass that records every system prompt sent to+ the LLM (so the language-directive injection can be asserted), while+ short-circuiting the actual network call."""+def __init__(self, language: str = "zh") -> None:self.language = language- self.prompts = {+ self.prompts: dict[str, Any] = {"system": "Followup system","answer_followup": ("Question context:\n{question_context}\n\n"@@ -79,61 +29,6 @@ class CaptureFollowupAgent(FollowupAgent):yield "已回答"-async def test_idea_agent_appends_language_directive_to_system_prompt() -> None:- agent = CaptureIdeaAgent(language="zh")-- templates = await agent._generate_templates(- user_topic="线性代数",- preference="请用中文出题",- knowledge_context="矩阵和向量空间",- num_ideas=1,- )-- assert templates- assert agent.captured_system_prompts- assert "Idea agent system" in agent.captured_system_prompts[0]- assert "请严格使用中文(简体)" in agent.captured_system_prompts[0]---async def test_generator_appends_language_directive_to_generate_and_repair_prompts() -> None:- agent = CaptureGenerator(language="zh")- template = QuestionTemplate(- question_id="q_1",- concentration="矩阵乘法",- question_type="written",- difficulty="medium",- )-- payload = await agent._generate_payload(- template=template,- user_topic="线性代数",- preference="请使用中文",- history_context="",- knowledge_context="矩阵乘法的定义",- available_tools="(no tools available)",- )-- repaired = await agent._repair_payload(- template=template,- payload=payload,- issues=["missing_explanation"],- user_topic="线性代数",- preference="请使用中文",- history_context="",- knowledge_context="矩阵乘法的定义",- available_tools="(no tools available)",- )-- assert repaired["question"] == "问题"- assert len(agent.captured_system_prompts) == 2- assert "Generator system" in agent.captured_system_prompts[0]- assert "请严格使用中文(简体)" in agent.captured_system_prompts[0]- assert "You fix malformed quiz payloads" in agent.captured_system_prompts[1]- assert "请严格使用中文(简体)" in agent.captured_system_prompts[1]--@pytest.mark.asyncioasync def test_followup_agent_appends_language_directive_to_system_prompt() -> None:agent = CaptureFollowupAgent(language="zh")diff --git a/tests/agents/question/test_pipeline.py b/tests/agents/question/test_pipeline.pynew file mode 100644index 000000000..4b1d30cc4--- /dev/null+++ b/tests/agents/question/test_pipeline.py@@ -0,0 +1,989 @@+"""Unit tests for the new QuestionPipeline primitives.++These tests cover the pure helpers (plan parsing, payload normalization,+issue collection) and the structured per-question emission. End-to-end+flow (loop driving + LLM streaming) is exercised by integration tests+that mock the LLM client; out of scope here.+"""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from typing import Any+from unittest.mock import patch++import pytest++from deeptutor.agents.question.pipeline import (+ CALL_KIND_QUIZ_QUESTION,+ QuestionPipeline,+ QuizPair,+ QuizPlan,+ QuizTemplate,+ STAGE_QUIZZING,+)+++# ---------------------------------------------------------------------------+# Test helpers+# ---------------------------------------------------------------------------+++def _make_pipeline(language: str = "en") -> QuestionPipeline:+ """Build a pipeline without hitting the network for LLM config."""+ # Tests don't drive ``run`` — they only exercise pure helpers and the+ # YAML-driven trace metadata builders. So the LLM config can be the+ # production one (env-based) without making any actual API calls.+ return QuestionPipeline(language=language)+++class _StubStreamBus:+ """Captures every emission for assertion. No event ordering checks+ beyond ``contents`` containing what we expect."""++ def __init__(self) -> None:+ # Instance attributes are kept distinct from the method names so the+ # methods don't get shadowed when ``progress``/``error`` are called.+ # (The original version named both the list and the method+ # ``progress``, which silently dropped every captured event.)+ self.contents: list[dict[str, Any]] = []+ self.progress_events: list[dict[str, Any]] = []+ self.error_events: list[dict[str, Any]] = []++ async def content(+ self,+ text: str,+ source: str = "",+ stage: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ self.contents.append(+ {"text": text, "source": source, "stage": stage, "metadata": metadata or {}}+ )++ async def progress(+ self,+ message: str,+ current: int = 0,+ total: int = 0,+ source: str = "",+ stage: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ self.progress_events.append(+ {+ "message": message,+ "source": source,+ "stage": stage,+ "metadata": metadata or {},+ }+ )++ async def error(+ self,+ message: str,+ source: str = "",+ stage: str = "",+ metadata: dict[str, Any] | None = None,+ ) -> None:+ self.error_events.append(+ {"message": message, "source": source, "stage": stage, "metadata": metadata or {}}+ )+++# ---------------------------------------------------------------------------+# parse_plan+# ---------------------------------------------------------------------------+++def test_parse_plan_happy_path() -> None:+ pipeline = _make_pipeline()+ raw = json.dumps(+ {+ "analysis": "mix of recall + applied",+ "templates": [+ {"topic": "Definition of X", "question_type": "choice", "difficulty": "easy"},+ {"topic": "Apply X to Y", "question_type": "written", "difficulty": "medium"},+ ],+ }+ )+ plan = pipeline._parse_plan(raw, requested=2, allowed_types=[], target_difficulty="")+ assert plan.analysis == "mix of recall + applied"+ assert [t.topic for t in plan.templates] == ["Definition of X", "Apply X to Y"]+ assert [t.question_id for t in plan.templates] == ["q_1", "q_2"]+ assert plan.templates[0].question_type == "choice"+ assert plan.templates[1].difficulty == "medium"+++def test_parse_plan_dedupes_topics_case_insensitive() -> None:+ pipeline = _make_pipeline()+ raw = json.dumps(+ {+ "templates": [+ {"topic": "Matrix Multiplication", "question_type": "written"},+ {"topic": "matrix multiplication", "question_type": "choice"},+ {"topic": "Eigenvalues", "question_type": "written"},+ ]+ }+ )+ plan = pipeline._parse_plan(raw, requested=3, allowed_types=[], target_difficulty="")+ assert len(plan.templates) == 2+ assert plan.templates[0].topic == "Matrix Multiplication"+ assert plan.templates[1].topic == "Eigenvalues"+++def test_parse_plan_respects_user_specified_type_and_difficulty() -> None:+ """When ``allowed_types`` restricts the set to a single type, every+ template must use that type. Difficulty override behaves the same way."""+ pipeline = _make_pipeline()+ raw = json.dumps(+ {+ "templates": [+ {"topic": "T1", "question_type": "choice", "difficulty": "easy"},+ {"topic": "T2", "question_type": "written", "difficulty": "hard"},+ ]+ }+ )+ plan = pipeline._parse_plan(+ raw, requested=2, allowed_types=["coding"], target_difficulty="medium"+ )+ assert all(t.question_type == "coding" for t in plan.templates)+ assert all(t.difficulty == "medium" for t in plan.templates)+++def test_parse_plan_invalid_json_returns_empty() -> None:+ pipeline = _make_pipeline()+ plan = pipeline._parse_plan(+ "not even json", requested=3, allowed_types=[], target_difficulty=""+ )+ assert isinstance(plan, QuizPlan)+ assert plan.templates == []+++def test_parse_plan_truncates_to_requested() -> None:+ pipeline = _make_pipeline()+ raw = json.dumps(+ {+ "templates": [+ {"topic": f"T{i}", "question_type": "written", "difficulty": "easy"}+ for i in range(5)+ ]+ }+ )+ plan = pipeline._parse_plan(raw, requested=2, allowed_types=[], target_difficulty="")+ assert len(plan.templates) == 2+++# ---------------------------------------------------------------------------+# Payload normalization + issue collection+# ---------------------------------------------------------------------------+++def test_normalize_choice_resolves_answer_text_to_key() -> None:+ template = QuizTemplate(question_id="q_1", topic="t", question_type="choice", difficulty="easy")+ payload = {+ "question": "What?",+ "options": {"A": "alpha", "B": "beta", "C": "gamma", "D": "delta"},+ "correct_answer": "beta",+ "explanation": "because",+ }+ normalized = QuestionPipeline._normalize_quiz_payload(template, payload)+ assert normalized["correct_answer"] == "B"+ assert set(normalized["options"].keys()) == {"A", "B", "C", "D"}+++def test_collect_issues_choice_missing_keys() -> None:+ template = QuizTemplate(question_id="q_1", topic="t", question_type="choice", difficulty="easy")+ payload = {+ "question": "What?",+ "options": {"A": "x", "B": "y", "C": "z"},+ "correct_answer": "A",+ "explanation": "ok",+ }+ normalized = QuestionPipeline._normalize_quiz_payload(template, payload)+ issues = QuestionPipeline._collect_quiz_issues(template, normalized)+ assert "choice_options_must_be_a_to_d" in issues+++def test_collect_issues_written_must_not_have_options() -> None:+ template = QuizTemplate(+ question_id="q_1", topic="t", question_type="written", difficulty="medium"+ )+ payload = {+ "question": "Explain X.",+ "options": {"A": "x", "B": "y", "C": "z", "D": "w"},+ "correct_answer": "Because…",+ "explanation": "ok",+ }+ normalized = QuestionPipeline._normalize_quiz_payload(template, payload)+ # Normalization strips options for non-choice types — so the issue surfaces+ # only when the LLM emits a choice-looking shape (single A-D answer key)+ # AND options got stripped during normalization. Here options are stripped+ # so the structural issue disappears; what remains is the answer-key smell.+ assert normalized["options"] is None+ issues = QuestionPipeline._collect_quiz_issues(template, normalized)+ assert issues == [] # answer text "Because…" is not a single A-D key+++def test_collect_issues_written_answer_looks_like_key() -> None:+ template = QuizTemplate(+ question_id="q_1", topic="t", question_type="written", difficulty="medium"+ )+ payload = {+ "question": "Which is right?",+ "correct_answer": "B",+ "explanation": "ok",+ }+ normalized = QuestionPipeline._normalize_quiz_payload(template, payload)+ issues = QuestionPipeline._collect_quiz_issues(template, normalized)+ assert "non_choice_correct_answer_looks_like_option_key" in issues+++def test_collect_issues_missing_fields() -> None:+ template = QuizTemplate(+ question_id="q_1", topic="t", question_type="written", difficulty="medium"+ )+ payload: dict[str, Any] = {"question": " ", "correct_answer": "", "explanation": ""}+ normalized = QuestionPipeline._normalize_quiz_payload(template, payload)+ issues = QuestionPipeline._collect_quiz_issues(template, normalized)+ assert {"missing_question", "missing_correct_answer", "missing_explanation"} <= set(issues)+++# ---------------------------------------------------------------------------+# _emit_quiz_question — structured event shape+# ---------------------------------------------------------------------------+++def test_emit_quiz_question_structures_metadata() -> None:+ pipeline = _make_pipeline()+ bus = _StubStreamBus()+ qa_pair = QuizPair(+ question_id="q_2",+ question="Solve x.",+ question_type="written",+ correct_answer="42",+ explanation="because",+ topic="algebra",+ difficulty="easy",+ )+ asyncio.run(+ pipeline._emit_quiz_question(stream=bus, qa_pair=qa_pair, index=1, total=3)+ )+ assert len(bus.contents) == 1+ event = bus.contents[0]+ assert event["source"] == "deep_question"+ assert event["stage"] == STAGE_QUIZZING+ meta = event["metadata"]+ assert meta["call_kind"] == CALL_KIND_QUIZ_QUESTION+ assert meta["trace_role"] == "quiz_question"+ assert meta["question_index"] == 1+ assert meta["total_questions"] == 3+ # qa_pair is the structured payload the frontend reads to render the card+ assert meta["qa_pair"]["question_id"] == "q_2"+ assert meta["qa_pair"]["question_type"] == "written"+++# ---------------------------------------------------------------------------+# Quiz history loader integration with the sqlite store+# ---------------------------------------------------------------------------+++def tmp_sqlite_store(tmp_path: Path):+ """Spin up an isolated SQLite session store + force the global getter+ to return it for the duration of the test."""+ from deeptutor.services.session.sqlite_store import SQLiteSessionStore++ store = SQLiteSessionStore(db_path=tmp_path / "session.db")+ with patch(+ "deeptutor.services.session.sqlite_store.get_sqlite_session_store",+ return_value=store,+ ):+ yield store+++def test_history_loader_returns_session_scoped_entries(tmp_sqlite_store) -> None:+ """Insert two sessions' worth of quiz answers; loader returns only the+ target session's entries, oldest first, with is_correct=None when the+ learner never answered."""+ from deeptutor.agents.question.history import load_session_quiz_history++ store = tmp_sqlite_store++ async def setup() -> None:+ await store.create_session(session_id="s1", title="quiz session")+ await store.create_session(session_id="s2", title="other session")+ await store.upsert_notebook_entries(+ "s1",+ [+ {+ "turn_id": "t1",+ "question_id": "q_1",+ "question": "What is 2+2?",+ "question_type": "written",+ "options": {},+ "correct_answer": "4",+ "explanation": "addition",+ "difficulty": "easy",+ "user_answer": "4",+ "is_correct": True,+ },+ {+ "turn_id": "t1",+ "question_id": "q_2",+ "question": "What is 3*3?",+ "question_type": "written",+ "options": {},+ "correct_answer": "9",+ "explanation": "multiplication",+ "difficulty": "easy",+ "user_answer": "8",+ "is_correct": False,+ },+ {+ "turn_id": "t2",+ "question_id": "q_3",+ "question": "What is e^0?",+ "question_type": "written",+ "options": {},+ "correct_answer": "1",+ "explanation": "exp",+ "difficulty": "medium",+ # Unanswered: empty user_answer + is_correct=False (default)+ "user_answer": "",+ "is_correct": False,+ },+ ],+ )+ await store.upsert_notebook_entries(+ "s2",+ [+ {+ "turn_id": "t99",+ "question_id": "q_1",+ "question": "OTHER SESSION should not leak",+ "question_type": "written",+ "correct_answer": "x",+ "explanation": "x",+ "user_answer": "x",+ "is_correct": True,+ }+ ],+ )++ asyncio.run(setup())++ entries = asyncio.run(load_session_quiz_history("s1"))+ questions = [e.question for e in entries]+ assert "OTHER SESSION should not leak" not in questions+ assert questions == ["What is 2+2?", "What is 3*3?", "What is e^0?"] # chronological+ assert entries[0].is_correct is True+ assert entries[1].is_correct is False+ # Unanswered entry: user_answer was empty, so loader surfaces None+ # (so the prompt renders "unknown" instead of misleadingly "incorrect").+ assert entries[2].is_correct is None+ assert entries[2].user_answer == ""+++def test_history_loader_returns_empty_for_unknown_session(tmp_sqlite_store) -> None:+ from deeptutor.agents.question.history import load_session_quiz_history++ entries = asyncio.run(load_session_quiz_history(""))+ assert entries == []+ entries = asyncio.run(load_session_quiz_history("does-not-exist"))+ assert entries == []+++# ---------------------------------------------------------------------------+# Tool wiring — regression for the bug where _current_context was None+# at schema-build time, leaving the model with no native tool schemas and+# causing it to improvise fake ``tool_calls`` JSON inside the THINK body.+# ---------------------------------------------------------------------------+++def test_tool_schemas_populated_when_kb_attached() -> None:+ """With a KB attached, ``rag`` must be auto-mounted and the tool+ schemas the LLM receives must include it with the right ``kb_name``+ enum. A regression here means the explore loop runs schema-less and+ the model fakes tool calls in text."""+ from deeptutor.core.context import UnifiedContext++ pipeline = QuestionPipeline(+ language="en",+ kb_name="demo-kb",+ enabled_tools=["web_search"],+ )+ ctx = UnifiedContext(+ user_message="test",+ session_id="s1",+ metadata={},+ enabled_tools=["web_search"],+ knowledge_bases=["demo-kb"],+ )++ resolved = pipeline._resolved_tools(ctx)+ assert "rag" in resolved+ assert "web_search" in resolved+ assert pipeline._use_native_tools(ctx) is True++ schemas = pipeline._build_llm_tool_schemas(ctx)+ names = [s["function"]["name"] for s in schemas if isinstance(s, dict)]+ assert "rag" in names+ assert "web_search" in names++ rag = next(s for s in schemas if s.get("function", {}).get("name") == "rag")+ kb_schema = rag["function"]["parameters"]["properties"].get("kb_name", {})+ assert kb_schema.get("enum") == ["demo-kb"], (+ "kb_name enum must be populated so the model can't hallucinate"+ )+++def test_use_native_tools_false_when_no_tools_resolved() -> None:+ """If the registry returns no tools for this turn (rare — e.g. user+ has every tool disabled), ``_use_native_tools`` must return False so+ we don't pass an empty tools array while the prompt still mentions+ tools. Otherwise the model invents calls in text."""+ from deeptutor.core.context import UnifiedContext++ pipeline = _make_pipeline()+ pipeline.kb_name = None+ ctx = UnifiedContext(+ user_message="test",+ session_id="s1",+ metadata={},+ enabled_tools=[],+ knowledge_bases=[],+ )++ # web_fetch / github / ask_user are always auto-mounted, so we still+ # expect _use_native_tools True under the default registry. The point+ # of this regression is the *guard*: the function inspects resolved+ # tools at all, not just binding/model — so an empty tool list won't+ # silently pass through.+ if pipeline._resolved_tools(ctx):+ assert pipeline._use_native_tools(ctx) is True+ else: # pragma: no cover — only reachable in stripped registries+ assert pipeline._use_native_tools(ctx) is False+++# ---------------------------------------------------------------------------+# Mimic mode — templates_override path+# ---------------------------------------------------------------------------+++def test_reference_block_renders_for_mimic_templates() -> None:+ """mimic templates expose their original exam-paper question + answer+ so the quiz step can shadow / paraphrase the source. custom templates+ get the no-reference placeholder instead, so the model knows to+ invent the stem."""+ pipeline = _make_pipeline()++ custom = QuizTemplate(+ question_id="q_1", topic="t", question_type="written", difficulty="medium"+ )+ block_custom = pipeline._render_reference_block(custom)+ assert "no reference" in block_custom.lower() or block_custom.startswith("(")++ mimic = QuizTemplate(+ question_id="q_1",+ topic="t",+ question_type="written",+ difficulty="medium",+ source="mimic",+ reference_question="Prove that the eigenvalues of a Hermitian matrix are real.",+ reference_answer="Use ⟨Ax, x⟩ = ⟨x, Ax⟩ …",+ )+ block_mimic = pipeline._render_reference_block(mimic)+ assert "Reference question" in block_mimic+ assert "Hermitian" in block_mimic+ assert "Reference answer" in block_mimic+++def test_build_result_payload_mode_mimic() -> None:+ """``is_mimic=True`` flips the envelope's ``mode`` + ``summary.source``+ so the frontend / notebook layer can distinguish topic-driven from+ exam-driven quizzes. Without this, mimic results were indistinguishable+ from custom and the analytics rolled them together."""+ pipeline = _make_pipeline()+ plan = QuizPlan(+ analysis="from-exam",+ templates=[+ QuizTemplate(+ question_id="q_1",+ topic="Hermitian eigenvalues",+ question_type="written",+ difficulty="medium",+ source="mimic",+ reference_question="ref Q",+ reference_answer="ref A",+ )+ ],+ )+ qa = QuizPair(+ question_id="q_1",+ question="Prove …",+ question_type="written",+ correct_answer="…",+ explanation="…",+ topic="Hermitian eigenvalues",+ difficulty="medium",+ )++ payload_mimic = pipeline._build_result_payload(plan, [qa], is_mimic=True)+ assert payload_mimic["mode"] == "mimic"+ assert payload_mimic["summary"]["source"] == "exam"+ # source / reference fields ride along on the template snapshot for+ # downstream consumers that want to render "from exam paper" badges.+ assert payload_mimic["summary"]["templates"][0]["source"] == "mimic"+ assert payload_mimic["summary"]["templates"][0]["reference_question"] == "ref Q"++ payload_custom = pipeline._build_result_payload(plan, [qa], is_mimic=False)+ assert payload_custom["mode"] == "custom"+ assert payload_custom["summary"]["source"] == "topic"+++def test_run_with_templates_override_skips_explore_and_plan(monkeypatch) -> None:+ """``templates_override`` is the mimic-mode hook: when provided, the+ pipeline must jump straight to the quiz phase. This guards against a+ refactor accidentally re-enabling the explore / plan calls for mimic+ (which would burn extra LLM rounds and clobber the planner-fixed+ template list with one the LLM invented).++ We patch out ``_explore``, ``_plan``, ``_quiz_one``, and ``stream.result``+ so we can inspect *which* phases ran without the LLM client touching+ the network.+ """+ from deeptutor.core.context import UnifiedContext++ pipeline = QuestionPipeline(language="en")+ ctx = UnifiedContext(+ user_message="please quiz me",+ session_id="s1",+ metadata={},+ enabled_tools=[],+ knowledge_bases=[],+ )++ explore_calls: list[None] = []+ plan_calls: list[None] = []+ quiz_calls: list[QuizTemplate] = []++ async def _fake_explore(**kwargs: Any) -> str:+ explore_calls.append(None)+ return "should not run"++ async def _fake_plan(**kwargs: Any) -> QuizPlan:+ plan_calls.append(None)+ return QuizPlan(analysis="", templates=[])++ async def _fake_quiz_one(*, template: QuizTemplate, **kwargs: Any) -> QuizPair:+ quiz_calls.append(template)+ return QuizPair(+ question_id=template.question_id,+ question=template.reference_question or template.topic,+ question_type=template.question_type,+ correct_answer="A",+ explanation="…",+ topic=template.topic,+ difficulty=template.difficulty,+ )++ async def _fake_emit(**kwargs: Any) -> None:+ return None++ from contextlib import asynccontextmanager++ bus = _StubStreamBus()++ @asynccontextmanager+ async def _fake_stage(*args: Any, **kwargs: Any):+ yield None++ async def _fake_result(payload: dict[str, Any], **kwargs: Any) -> None:+ bus.contents.append({"text": "result", "metadata": payload})++ bus.stage = _fake_stage # type: ignore[attr-defined]+ bus.result = _fake_result # type: ignore[attr-defined]++ monkeypatch.setattr(pipeline, "_explore", _fake_explore)+ monkeypatch.setattr(pipeline, "_plan", _fake_plan)+ monkeypatch.setattr(pipeline, "_quiz_one", _fake_quiz_one)+ monkeypatch.setattr(pipeline, "_emit_quiz_question", _fake_emit)+ # build_openai_client tries to materialise a real client; stub it.+ monkeypatch.setattr(+ "deeptutor.agents.question.pipeline.build_openai_client",+ lambda config: object(),+ )++ templates = [+ QuizTemplate(+ question_id="q_1",+ topic="ref topic 1",+ question_type="written",+ difficulty="medium",+ source="mimic",+ reference_question="Q1?",+ reference_answer="A1",+ ),+ QuizTemplate(+ question_id="q_2",+ topic="ref topic 2",+ question_type="written",+ difficulty="medium",+ source="mimic",+ reference_question="Q2?",+ reference_answer="A2",+ ),+ ]++ payload = asyncio.run(+ pipeline.run(+ context=ctx,+ user_message="please quiz me",+ num_questions=2,+ templates_override=templates,+ stream=bus,+ )+ )++ assert explore_calls == [], "explore must NOT run when templates_override is set"+ assert plan_calls == [], "plan must NOT run when templates_override is set"+ assert [t.question_id for t in quiz_calls] == ["q_1", "q_2"]+ assert payload["mode"] == "mimic"+ assert payload["summary"]["source"] == "exam"+ assert payload["summary"]["template_count"] == 2+++# ---------------------------------------------------------------------------+# Exploration trace rendering + protocol-label stripping+# ---------------------------------------------------------------------------+++def test_strip_protocol_label_removes_only_leading_label() -> None:+ """The trace renderer feeds each assistant message through this helper.+ Only the leading protocol label should be stripped; later occurrences+ (e.g., the model referencing ``THINK`` inside its own prose) must stay+ so the rendered trace remains faithful."""+ assert QuestionPipeline._strip_protocol_label(+ "``THINK``\nfirst I need to check ``TOOL`` mounting."+ ) == "first I need to check ``TOOL`` mounting."+ assert QuestionPipeline._strip_protocol_label("``FINISH``\nDone.") == "Done."+ assert QuestionPipeline._strip_protocol_label("no label here") == "no label here"+++def test_render_exploration_trace_walks_messages_in_order() -> None:+ """Walks a synthetic post-initial message buffer and asserts the+ rendered markdown contains an iteration block per assistant THINK,+ one per tool_call, and one per role=tool result. The final FINISH+ block must appear last so downstream phases read the closing+ synthesis after the tool history."""+ pipeline = _make_pipeline()++ messages = [+ {"role": "assistant", "content": "``THINK``\nI should retrieve the topic."},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [+ {+ "id": "call_abc",+ "type": "function",+ "function": {+ "name": "rag",+ "arguments": json.dumps({"query": "eigenvalues", "kb_name": "demo"}),+ },+ }+ ],+ },+ {+ "role": "tool",+ "tool_call_id": "call_abc",+ "content": "Eigenvalues are scalars λ where Av = λv. [source-1]",+ },+ {"role": "user", "content": "(protocol nudge — should be filtered)"},+ {"role": "assistant", "content": "``THINK``\nGood, I have grounding now."},+ ]++ rendered = pipeline._render_exploration_trace(+ messages, finish_text="I researched X; now let me generate 3 questions."+ )++ # Order: thought, tool call, tool result, thought, finish note. Find+ # each header's index and assert ascending order.+ indices = []+ for marker in [+ "Iteration 1 — Thought",+ "Iteration 2 — Tool call: rag",+ "Iteration 2 — Tool result (summarized): rag",+ "Iteration 3 — Thought",+ "Final exploration preface",+ ]:+ idx = rendered.find(marker)+ assert idx != -1, f"missing trace section: {marker!r}\n--- rendered ---\n{rendered}"+ indices.append(idx)+ assert indices == sorted(indices)++ # The protocol nudge (role=user) must NOT bleed into the trace.+ assert "protocol nudge" not in rendered+ # Tool call args block must include the query verbatim.+ assert "eigenvalues" in rendered+ # The leading ``THINK`` label must be stripped from rendered thoughts.+ assert "``THINK``" not in rendered+ # FINISH text is at the bottom.+ assert rendered.rstrip().endswith("I researched X; now let me generate 3 questions.")+++def test_render_exploration_trace_empty_inputs_uses_marker() -> None:+ pipeline = _make_pipeline()+ rendered = pipeline._render_exploration_trace([], finish_text="")+ # The YAML's empty marker should surface so the planner prompt isn't+ # left with a dangling section header.+ assert rendered.strip().startswith("(")+++# ---------------------------------------------------------------------------+# Runtime config wiring+# ---------------------------------------------------------------------------+++def test_runtime_config_overrides_max_iterations_and_summarizer_tokens() -> None:+ """``QuestionPipeline.__init__`` must honor the runtime_config payload+ that ``DeepQuestionCapability`` builds via+ ``build_question_runtime_config``. A regression here means the+ capability's config-driven knobs silently do nothing."""+ pipeline = QuestionPipeline(+ language="en",+ runtime_config={+ "exploring": {+ "max_iterations": 12,+ "tool_summarizer": {"enabled": False, "max_tokens": 1234},+ }+ },+ )+ assert pipeline.max_explore_iterations == 12+ assert pipeline.tool_summarizer_enabled is False+ assert pipeline.tool_summarizer_max_tokens == 1234+++def test_runtime_config_falls_back_to_defaults_when_missing() -> None:+ """A missing / empty ``exploring`` block must not crash __init__; the+ module-level defaults take over."""+ from deeptutor.agents.question.pipeline import (+ DEFAULT_MAX_EXPLORE_ITERATIONS,+ DEFAULT_TOOL_SUMMARIZER_MAX_TOKENS,+ )++ pipeline = QuestionPipeline(language="en", runtime_config={})+ assert pipeline.max_explore_iterations == DEFAULT_MAX_EXPLORE_ITERATIONS+ assert pipeline.tool_summarizer_enabled is True+ assert pipeline.tool_summarizer_max_tokens == DEFAULT_TOOL_SUMMARIZER_MAX_TOKENS+++def test_build_question_runtime_config_reads_capabilities_section() -> None:+ from deeptutor.agents.question.request_config import (+ build_question_runtime_config,+ )++ rc = build_question_runtime_config(+ base_config={+ "capabilities": {+ "deep_question": {+ "exploring": {+ "max_iterations": 10,+ "tool_summarizer": {"enabled": False, "max_tokens": 500},+ }+ }+ }+ }+ )+ assert rc["exploring"]["max_iterations"] == 10+ assert rc["exploring"]["tool_summarizer"]["enabled"] is False+ assert rc["exploring"]["tool_summarizer"]["max_tokens"] == 500+++def test_build_question_runtime_config_defaults_when_unconfigured() -> None:+ from deeptutor.agents.question.request_config import (+ build_question_runtime_config,+ )++ rc = build_question_runtime_config(base_config=None)+ assert rc["exploring"]["max_iterations"] == 8+ assert rc["exploring"]["tool_summarizer"]["enabled"] is True+ assert rc["exploring"]["tool_summarizer"]["max_tokens"] == 800+++# ---------------------------------------------------------------------------+# Tool Summarizer — substitution + streaming+# ---------------------------------------------------------------------------+++def test_summarize_tool_result_streams_chunks_and_returns_assembled_text() -> None:+ """The summarizer must:++ * Open a "Reflecting..." sub-trace node before streaming.+ * Emit each model chunk to ``stream.thinking`` (so the trace panel+ shows the compression happening live).+ * Return the assembled summary text for the host to substitute into+ the tool message buffer.++ Regression target: if the streaming loop ever broke (e.g., chunks+ weren't being appended), the host would silently swap the raw+ tool_result with an empty string downstream.+ """+ pipeline = _make_pipeline()+ bus = _StubStreamBus()+ # Capture thinking events too — the base stub only logs ``content`` /+ # ``progress`` / ``error``. Add ``thinking`` here.+ bus.thinking_events: list[dict[str, Any]] = [] # type: ignore[attr-defined]++ async def _thinking(text, source="", stage="", metadata=None):+ bus.thinking_events.append( # type: ignore[attr-defined]+ {"text": text, "source": source, "stage": stage, "metadata": metadata or {}}+ )++ bus.thinking = _thinking # type: ignore[assignment]++ # Build a minimal fake OpenAI client whose .chat.completions.create+ # returns an async iterator of fake chunks (each with a single content+ # delta), plus a trailing usage frame the summarizer ignores.+ class _Delta:+ def __init__(self, content: str | None) -> None:+ self.content = content++ class _Choice:+ def __init__(self, content: str | None) -> None:+ self.delta = _Delta(content)++ class _Chunk:+ def __init__(self, content: str | None, usage: Any = None) -> None:+ self.choices = [_Choice(content)] if content is not None else []+ self.usage = usage++ async def _stream_chunks():+ for piece in ["Eigenvalues are ", "scalars λ ", "where Av = λv."]:+ yield _Chunk(piece)+ # Trailing usage frame with no choices.+ yield _Chunk(None, usage=None)++ class _Completions:+ async def create(self, **kwargs):+ assert kwargs["stream"] is True+ return _stream_chunks()++ class _Chat:+ def __init__(self) -> None:+ self.completions = _Completions()++ class _FakeClient:+ def __init__(self) -> None:+ self.chat = _Chat()++ summary = asyncio.run(+ pipeline._summarize_tool_result(+ tool_name="rag",+ tool_result="<long raw rag result here>",+ iteration=1,+ stream=bus,+ client=_FakeClient(),+ )+ )++ assert summary == "Eigenvalues are scalars λ where Av = λv."+ # ``Reflecting...`` sub-trace opened (running) and closed (complete).+ states = [ev["metadata"].get("call_state") for ev in bus.progress_events]+ assert "running" in states+ assert "complete" in states+ # Each chunk became a ``thinking`` event with the reflecting trace_role.+ assert bus.thinking_events # type: ignore[attr-defined]+ roles = {ev["metadata"].get("trace_role") for ev in bus.thinking_events} # type: ignore[attr-defined]+ assert roles == {"reflection"}+ # Concatenated thinking text matches the returned summary.+ joined = "".join(ev["text"] for ev in bus.thinking_events) # type: ignore[attr-defined]+ assert joined == summary+++def test_summarize_tool_result_empty_input_returns_none() -> None:+ """No LLM call should fire for an empty/whitespace result — and the+ method must return None so the host keeps the original (empty) tool+ message instead of substituting nothing."""+ pipeline = _make_pipeline()+ bus = _StubStreamBus()++ class _DummyClient:+ pass++ result = asyncio.run(+ pipeline._summarize_tool_result(+ tool_name="rag",+ tool_result=" ",+ iteration=0,+ stream=bus,+ client=_DummyClient(),+ )+ )+ assert result is None+ # No streaming events at all — short-circuit before the model call.+ assert bus.progress_events == []+++# ---------------------------------------------------------------------------+# Backward-compat helpers that still need to exist for legacy callers+# ---------------------------------------------------------------------------+++def test_parse_exam_paper_to_templates_happy_path(monkeypatch, tmp_path: Path) -> None:+ """End-to-end of the mimic adapter, mocking out MinerU + the question+ extractor. Verifies that the JSON payload becomes a list of+ ``QuizTemplate`` with ``source="mimic"`` and the reference fields+ populated."""+ from deeptutor.agents.question import mimic_source++ parsed_dir = tmp_path / "parsed-001"+ parsed_dir.mkdir()+ questions_file = parsed_dir / "exam_questions.json"+ questions_file.write_text(+ json.dumps(+ {+ "questions": [+ {+ "question_text": "Define an eigenvalue.",+ "question_type": "written",+ "answer": "A scalar λ such that Av = λv …",+ },+ {+ "question_text": "What is the rank of an identity matrix?",+ "question_type": "choice",+ "answer": "n",+ },+ # Blank rows must be skipped, not crash the loop.+ {"question_text": "", "question_type": "written"},+ ]+ }+ )+ )++ monkeypatch.setattr(+ mimic_source, "parse_pdf_with_mineru", lambda *a, **k: True+ )+ monkeypatch.setattr(+ mimic_source, "extract_questions_from_paper", lambda *a, **k: True+ )++ templates, trace = asyncio.run(+ mimic_source.parse_exam_paper_to_templates(+ parsed_dir,+ max_questions=10,+ paper_mode="parsed",+ output_dir=tmp_path,+ )+ )++ assert len(templates) == 2 # the blank row was filtered+ assert all(t.source == "mimic" for t in templates)+ assert templates[0].reference_question.startswith("Define")+ assert templates[0].reference_answer.startswith("A scalar")+ assert templates[1].question_type == "choice"+ assert trace["template_count"] == "2"+ assert trace["question_file"].endswith("exam_questions.json")diff --git a/tests/agents/research/test_block_loop_host_append.py b/tests/agents/research/test_block_loop_host_append.pynew file mode 100644index 000000000..4a4876ec6--- /dev/null+++ b/tests/agents/research/test_block_loop_host_append.py@@ -0,0 +1,559 @@+"""Unit tests for ``_BlockLoopHost.on_intermediate`` — APPEND handling.++The hook is the only place where the dynamic topic queue is mutated+during the per-block agentic loop, so this is the most behaviourally+load-bearing piece of the new pipeline. We exercise it directly+(without spinning up the full loop) by constructing a host and calling+the hook against an in-memory queue.++Note summarization, tool dispatch, and the actual LLM calls aren't+covered here; they happen earlier in dispatch_tools and are mocked at+that boundary by the broader pipeline tests (task 15).+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from deeptutor.agents.research.data_structures import DynamicTopicQueue, ToolTrace+from deeptutor.agents.research.pipeline import (+ LABEL_APPEND,+ LABEL_FINISH,+ LABEL_THINK,+ ResearchPipeline,+ ResearchedBlock,+ _BlockLoopHost,+)+from deeptutor.agents.research.utils.citation_manager import CitationManager+from deeptutor.core.agentic.tool_dispatch import DispatchOutcome+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+++def _make_pipeline(monkeypatch: pytest.MonkeyPatch) -> ResearchPipeline:+ """Build a pipeline without touching real LLM config / registry I/O."""++ class _FakeLLM:+ binding = "openai"+ model = "gpt-x"+ api_key = "k"+ base_url = "u"+ api_version = None+ extra_headers = {}++ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM()+ )+ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.get_tool_registry", lambda: _FakeRegistry()+ )+ return ResearchPipeline(language="en", runtime_config={"queue": {"max_length": 5}})+++class _FakeRegistry:+ def build_openai_schemas(self, _names):+ return []++ def build_prompt_text(self, _names, **_kwargs):+ return "- none"++ def get(self, _name):+ return None++ def get_enabled(self, _names):+ return []+++class _ToolRegistry:+ def __init__(self, names: set[str]) -> None:+ self.names = names++ def build_openai_schemas(self, names):+ return [+ {"type": "function", "function": {"name": name, "parameters": {}}}+ for name in names+ if name in self.names+ ]++ def build_prompt_text(self, names, **_kwargs):+ return "\n".join(f"- {name}" for name in names)++ def get(self, name):+ return SimpleNamespace(name=name) if name in self.names else None++ def get_enabled(self, names):+ return [+ SimpleNamespace(name=name)+ for name in names+ if name in self.names+ ]+++class _FakeCitationManager:+ def __init__(self) -> None:+ self.calls = []+ self._counter = 0++ def generate_research_citation_id(self, block_id: str) -> str:+ self._counter += 1+ return f"CIT-{block_id}-{self._counter:02d}"++ def add_citation(self, *args, **kwargs):+ self.calls.append((args, kwargs))+ return True++ def get_all_citations(self):+ return {}+++async def _drain_bus(bus: StreamBus) -> list:+ events: list = []++ async def _consume():+ async for event in bus.subscribe():+ events.append(event)++ import asyncio++ task = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ return events, task+++def _make_host(+ pipeline: ResearchPipeline,+ queue: DynamicTopicQueue,+ bus: StreamBus,+):+ parent_block = queue.blocks[0]+ return _BlockLoopHost(+ pipeline=pipeline,+ block=parent_block,+ queue=queue,+ citations=_FakeCitationManager(),+ topic="Test topic",+ stream=bus,+ context=UnifiedContext(session_id="s1", user_message="m"),+ client=None,+ ), parent_block+++def _make_pipeline_with_registry(+ monkeypatch: pytest.MonkeyPatch,+ *,+ registry: _ToolRegistry,+ enabled_tools: list[str],+ kb_name: str | None = None,+ binding: str = "openai",+ model: str = "gpt-x",+) -> ResearchPipeline:+ fake_binding = binding+ fake_model = model++ class _FakeLLM:+ binding = fake_binding+ model = fake_model+ api_key = "k"+ base_url = "u"+ api_version = None+ extra_headers = {}++ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM()+ )+ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.get_tool_registry", lambda: registry+ )+ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.user_has_memory", lambda: False+ )+ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.user_has_notebooks", lambda: False+ )+ return ResearchPipeline(+ language="en",+ runtime_config={"queue": {"max_length": 5}},+ enabled_tools=enabled_tools,+ kb_name=kb_name,+ )+++def test_block_tool_names_keep_only_research_evidence_tools(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The research block loop should not inherit chat's always-on+ convenience tools. It should expose only tools that can back block+ evidence and citations."""+ registry = _ToolRegistry(+ {+ "rag",+ "web_search",+ "paper_search",+ "code_execution",+ "reason",+ "write_memory",+ "web_fetch",+ "github",+ }+ )+ pipeline = _make_pipeline_with_registry(+ monkeypatch,+ registry=registry,+ enabled_tools=["web_search", "paper_search", "code_execution", "reason"],+ kb_name="kb-main",+ )++ assert pipeline._block_tool_names() == [+ "web_search",+ "paper_search",+ "code_execution",+ "rag",+ ]+++async def test_block_host_rejects_finish_before_tool_when_tools_available(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ registry = _ToolRegistry({"web_search"})+ pipeline = _make_pipeline_with_registry(+ monkeypatch,+ registry=registry,+ enabled_tools=["web_search"],+ )+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Parent topic", "")+ bus = StreamBus()+ host, _parent = _make_host(pipeline, queue, bus)++ assert await host.validate_terminal(LABEL_FINISH, "direct answer") == (+ "finish_without_tool"+ )+ host._tool_rounds_used = 1+ assert await host.validate_terminal(LABEL_FINISH, "after evidence") is None+++async def test_block_host_allows_finish_when_model_cannot_call_native_tools(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ registry = _ToolRegistry({"web_search"})+ pipeline = _make_pipeline_with_registry(+ monkeypatch,+ registry=registry,+ enabled_tools=["web_search"],+ binding="ollama",+ model="llama3.2",+ )+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Parent topic", "")+ bus = StreamBus()+ host, _parent = _make_host(pipeline, queue, bus)++ assert pipeline._block_tool_names() == ["web_search"]+ assert pipeline._use_native_block_tools(["web_search"]) is False+ assert await host.validate_terminal(LABEL_FINISH, "direct answer") is None+++async def test_block_host_records_citable_tool_results(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ registry = _ToolRegistry({"web_search"})+ pipeline = _make_pipeline_with_registry(+ monkeypatch,+ registry=registry,+ enabled_tools=["web_search"],+ )++ async def _fake_summary(**_kwargs):+ return "Agentic RAG uses an agent-controlled retrieval loop."++ monkeypatch.setattr(pipeline, "_summarise_tool_result", _fake_summary)+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Agentic RAG definition", "")+ block = queue.blocks[0]+ citations = CitationManager("test-research", cache_dir=tmp_path)+ host = _BlockLoopHost(+ pipeline=pipeline,+ block=block,+ queue=queue,+ citations=citations,+ topic="Agentic RAG",+ stream=StreamBus(),+ context=UnifiedContext(session_id="s1", user_message="m"),+ client=None,+ )+ outcome = DispatchOutcome(+ tool_messages=[+ {+ "role": "tool",+ "tool_call_id": "call-1",+ "name": "web_search",+ "content": "raw web answer",+ }+ ]+ )++ await host._summarise_and_record(+ [{"id": "call-1", "name": "web_search", "arguments": {"query": "agentic rag"}}],+ outcome,+ )++ assert block.tool_traces+ assert block.tool_traces[0].citation_id == "CIT-1-01"+ assert outcome.tool_messages[0]["content"].startswith("[CIT-1-01]")+ assert "CIT-1-01" in citations.get_all_citations()+ references = pipeline._render_reference_list(citations)+ assert '<details id="references" open' in references+ assert '<li id="ref-cit-1-01" data-citation-id="CIT-1-01">' in references+ assert "<strong>" not in references+ assert '<span data-ref-number="1">' in references+ linked = pipeline._linkify_report_citations(+ "Agentic RAG [CIT-1-01] uses evidence; unknown [CIT-9-01] stays raw.",+ citations,+ )+ assert '[1](#ref-cit-1-01 "citation")' in linked+ assert "[CIT-9-01]" not in linked+++async def test_report_markdown_normalises_headings_and_prelinked_citations(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ registry = _ToolRegistry({"web_search"})+ pipeline = _make_pipeline_with_registry(+ monkeypatch,+ registry=registry,+ enabled_tools=["web_search"],+ )+ queue = DynamicTopicQueue("t", max_length=5)+ block = queue.add_block("Agentic RAG definition", "")+ citations = CitationManager("test-research", cache_dir=tmp_path)+ tool_trace = ToolTrace.create_with_size_limit(+ tool_id="tool-1",+ citation_id="CIT-1-01",+ tool_type="web_search",+ query="agentic rag definition",+ raw_answer="raw",+ summary="Agentic RAG adds an agent control layer.",+ )+ block.add_tool_trace(tool_trace)+ await citations.add_citation_async("CIT-1-01", "web_search", tool_trace, "raw")++ cleaned = pipeline._normalise_report_markdown(+ '## ## [S1]: Definition\nBody [CIT-1-01](#ref-cit-1-01 "citation") and [CIT-9-01].',+ citations,+ )+ linked = pipeline._linkify_report_citations(+ cleaned, citations, citation_numbers={"CIT-1-01": 1}+ )++ assert cleaned.startswith("## Definition")+ assert "[CIT-9-01]" not in cleaned+ assert '[1](#ref-cit-1-01 "citation")' in linked+++async def test_on_intermediate_ignores_non_append_labels(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Parent", "")+ bus = StreamBus()+ events, consumer = await _drain_bus(bus)++ host, _parent = _make_host(pipeline, queue, bus)+ feedback = await host.on_intermediate(LABEL_THINK, "thinking aloud")+ await bus.close()+ await consumer++ assert feedback is None+ assert len(queue.blocks) == 1+ assert events == []+++async def test_on_intermediate_append_adds_block_and_returns_confirmation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Parent topic", "")+ bus = StreamBus()+ events, consumer = await _drain_bus(bus)++ host, parent = _make_host(pipeline, queue, bus)+ body = "Quantum entanglement basics\nFoundational concepts and definitions"+ feedback = await host.on_intermediate(LABEL_APPEND, body)+ await bus.close()+ await consumer++ assert feedback is not None+ assert "Quantum entanglement basics" in feedback+ assert len(queue.blocks) == 2+ new_block = queue.blocks[-1]+ assert new_block.sub_topic == "Quantum entanglement basics"+ assert new_block.overview == "Foundational concepts and definitions"+ assert new_block.metadata.get("parent_block_id") == parent.block_id++ queue_append_events = [+ e+ for e in events+ if (e.metadata or {}).get("trace_kind") == "queue_append"+ ]+ assert queue_append_events+ assert queue_append_events[-1].metadata["new_block_id"] == new_block.block_id+++async def test_on_intermediate_append_rejects_duplicate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Quantum entanglement basics", "")+ bus = StreamBus()+ events, consumer = await _drain_bus(bus)++ host, _parent = _make_host(pipeline, queue, bus)+ feedback = await host.on_intermediate(+ LABEL_APPEND, "quantum entanglement basics"+ )+ await bus.close()+ await consumer++ assert feedback is not None+ assert "similar" in feedback.lower() or "rejected" in feedback.lower()+ # Queue size unchanged.+ assert len(queue.blocks) == 1+ rejected = [+ e+ for e in events+ if (e.metadata or {}).get("trace_kind") == "queue_append_rejected"+ ]+ assert rejected+ assert rejected[-1].metadata.get("reason") == "duplicate"+++async def test_on_intermediate_append_rejects_when_queue_full(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ queue = DynamicTopicQueue("t", max_length=2)+ queue.add_block("a", "")+ queue.add_block("b", "")+ bus = StreamBus()+ events, consumer = await _drain_bus(bus)++ host, _parent = _make_host(pipeline, queue, bus)+ feedback = await host.on_intermediate(LABEL_APPEND, "c\n(overview)")+ await bus.close()+ await consumer++ assert feedback is not None+ # No new block added.+ assert len(queue.blocks) == 2+ rejected = [+ e+ for e in events+ if (e.metadata or {}).get("trace_kind") == "queue_append_rejected"+ ]+ assert rejected+ # The retained host emits ``"full"`` as the reason value. (Older+ # drafts used ``"queue_full"`` — verify against the canonical key.)+ assert rejected[-1].metadata.get("reason") == "full"+++async def test_on_intermediate_append_strips_markdown_heading_prefix(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """LLMs sometimes prefix the title with ``#`` markers — strip them so+ the queue stores a clean title."""+ pipeline = _make_pipeline(monkeypatch)+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Parent", "")+ bus = StreamBus()+ events, consumer = await _drain_bus(bus)++ host, _parent = _make_host(pipeline, queue, bus)+ feedback = await host.on_intermediate(LABEL_APPEND, "## Cleaner title")+ await bus.close()+ await consumer++ assert feedback is not None+ new_block = queue.blocks[-1]+ assert new_block.sub_topic == "Cleaner title"+++async def test_on_intermediate_append_rejects_empty_body(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ queue = DynamicTopicQueue("t", max_length=5)+ queue.add_block("Parent", "")+ bus = StreamBus()+ events, consumer = await _drain_bus(bus)++ host, _parent = _make_host(pipeline, queue, bus)+ feedback = await host.on_intermediate(LABEL_APPEND, " \n ")+ await bus.close()+ await consumer++ assert feedback is not None+ # No new block added.+ assert len(queue.blocks) == 1+++def test_report_outline_parser_repairs_missing_block_coverage(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ queue = DynamicTopicQueue("t", max_length=5)+ b1 = queue.add_block("Background", "history and definitions")+ b2 = queue.add_block("Risk analysis", "safety and failure modes")+ b3 = queue.add_block("Deployment playbook", "rollout and monitoring")+ blocks = [+ ResearchedBlock(block=b1, knowledge="Foundational context."),+ ResearchedBlock(block=b2, knowledge="Risk controls."),+ ResearchedBlock(block=b3, knowledge="Operational rollout."),+ ]++ outline = pipeline._parse_report_outline(+ "AI safety operations",+ """+ {+ "title": "AI Safety Operations",+ "sections": [+ {+ "id": "S1",+ "title": "Background",+ "intent": "Definitions and history",+ "block_ids": ["block_1"]+ },+ {+ "id": "S2",+ "title": "## [S2]:Deployment",+ "intent": "Rollout plan",+ "block_ids": []+ }+ ]+ }+ """,+ blocks,+ )++ covered = {+ block_id for section in outline.sections for block_id in section.block_ids+ }+ assert covered == {"block_1", "block_2", "block_3"}+ assert all(section.block_ids for section in outline.sections)+ assert outline.sections[1].title == "Deployment"diff --git a/tests/agents/research/test_dynamic_topic_queue.py b/tests/agents/research/test_dynamic_topic_queue.pynew file mode 100644index 000000000..aec184473--- /dev/null+++ b/tests/agents/research/test_dynamic_topic_queue.py@@ -0,0 +1,126 @@+"""Unit tests for the queue extensions used by the new research pipeline.++The new agentic-loop refactor relies on three additions to+:class:`DynamicTopicQueue`:++* ``is_full()`` — capacity check without raising+* ``find_similar()`` — fuzzy dedup so the ``APPEND`` label can't+ silently flood the queue with near-duplicate sub-topics+* ``append_child()`` — non-raising tail append that records the parent+ block id in ``metadata`` for later topic-tree reconstruction+"""++from __future__ import annotations++from deeptutor.agents.research.data_structures import (+ DEFAULT_TOPIC_SIMILARITY_THRESHOLD,+ DynamicTopicQueue,+ TopicStatus,+)+++def _queue(max_length: int | None = None) -> DynamicTopicQueue:+ return DynamicTopicQueue("test", max_length=max_length)+++def test_is_full_returns_false_when_no_cap_configured() -> None:+ q = _queue()+ for i in range(50):+ q.add_block(f"topic {i}", "")+ assert q.is_full() is False+++def test_is_full_returns_true_at_cap() -> None:+ q = _queue(max_length=2)+ q.add_block("a", "")+ assert q.is_full() is False+ q.add_block("b", "")+ assert q.is_full() is True+++def test_find_similar_exact_match_returns_block() -> None:+ q = _queue()+ a = q.add_block("Quantum Entanglement Basics", "")+ match = q.find_similar("quantum entanglement basics")+ assert match is a+++def test_find_similar_returns_fuzzy_match_above_threshold() -> None:+ q = _queue()+ a = q.add_block("Quantum entanglement basics", "")+ # Reordered words / slight rewording — should still match above 0.85+ match = q.find_similar("Quantum entanglement: basic concepts")+ # The default threshold accepts highly similar titles; verify we get+ # back the only existing block.+ if match is not None:+ assert match is a+++def test_find_similar_catches_reordered_token_equivalents() -> None:+ q = _queue()+ a = q.add_block("AI safety governance frameworks", "")++ assert q.find_similar("Governance framework for AI safety") is a+++def test_find_similar_rejects_distinct_topic() -> None:+ q = _queue()+ q.add_block("Photosynthesis fundamentals", "")+ assert q.find_similar("History of jazz music") is None+++def test_find_similar_honours_custom_threshold() -> None:+ q = _queue()+ q.add_block("Photosynthesis fundamentals", "")+ # Force a punishingly high threshold so even close variants miss.+ assert q.find_similar("Photosynthesis basics", threshold=0.99) is None+++def test_find_similar_returns_none_for_empty_title() -> None:+ q = _queue()+ q.add_block("x", "")+ assert q.find_similar("") is None+ assert q.find_similar(" ") is None+++def test_append_child_returns_new_block_with_parent_id_in_metadata() -> None:+ q = _queue()+ parent = q.add_block("Parent topic", "ctx")+ child = q.append_child(parent=parent, sub_topic="Child topic", overview="more")+ assert child is not None+ assert child.sub_topic == "Child topic"+ assert child.overview == "more"+ assert child.metadata.get("parent_block_id") == parent.block_id+ assert child.status == TopicStatus.PENDING+ # New blocks land at the tail.+ assert q.blocks[-1] is child+++def test_append_child_without_parent_records_no_lineage() -> None:+ q = _queue()+ child = q.append_child(parent=None, sub_topic="orphan", overview="")+ assert child is not None+ assert "parent_block_id" not in child.metadata+++def test_append_child_returns_none_when_queue_full() -> None:+ q = _queue(max_length=1)+ q.add_block("only one", "")+ rejected = q.append_child(parent=None, sub_topic="overflow", overview="")+ assert rejected is None+ assert len(q.blocks) == 1+++def test_append_child_increments_counter_consistently_with_add_block() -> None:+ """``add_block`` and ``append_child`` must share the same id allocator."""+ q = _queue()+ a = q.add_block("a", "")+ b = q.append_child(parent=a, sub_topic="b", overview="")+ c = q.add_block("c", "")+ assert a.block_id == "block_1"+ assert b is not None and b.block_id == "block_2"+ assert c.block_id == "block_3"+++def test_default_threshold_constant_in_reasonable_range() -> None:+ assert 0.7 <= DEFAULT_TOPIC_SIMILARITY_THRESHOLD <= 0.95diff --git a/tests/agents/research/test_rephrase_loop_host.py b/tests/agents/research/test_rephrase_loop_host.pynew file mode 100644index 000000000..f501f86b8--- /dev/null+++ b/tests/agents/research/test_rephrase_loop_host.py@@ -0,0 +1,125 @@+"""Unit tests for ``_RephraseLoopHost``.++Covers the two pieces unique to the rephrase mini-loop:++* Non-``ask_user`` tool calls inside this phase are rejected inline (the+ LLM gets a synthetic tool message telling it ``ask_user`` is the only+ available tool).+* Once the ``max_rounds`` budget for ``ask_user`` calls is exhausted,+ further requests are answered with a synthetic tool message telling+ the model to FINISH with the best refined topic it can produce.+"""++from __future__ import annotations++import pytest++from deeptutor.agents.research.pipeline import ResearchPipeline, _RephraseLoopHost+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+++class _FakeLLM:+ binding = "openai"+ model = "gpt-x"+ api_key = "k"+ base_url = "u"+ api_version = None+ extra_headers = {}+++class _FakeRegistry:+ def build_openai_schemas(self, _names):+ return []++ def build_prompt_text(self, _names, **_kwargs):+ return "- none"++ def get(self, _name):+ return None++ def get_enabled(self, _names):+ return []+++def _make_pipeline(monkeypatch: pytest.MonkeyPatch) -> ResearchPipeline:+ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.get_llm_config", lambda: _FakeLLM()+ )+ monkeypatch.setattr(+ "deeptutor.agents.research.pipeline.get_tool_registry", lambda: _FakeRegistry()+ )+ return ResearchPipeline(language="en", runtime_config={})+++def _make_host(pipeline: ResearchPipeline, *, max_rounds: int = 3) -> _RephraseLoopHost:+ return _RephraseLoopHost(+ pipeline=pipeline,+ stream=StreamBus(),+ context=UnifiedContext(session_id="s1", user_message="m"),+ client=None,+ max_rounds=max_rounds,+ )+++async def test_rephrase_rejects_non_ask_user_tool_call(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An LLM that tries to call a non-``ask_user`` tool inside the+ rephrase phase should get a synthetic tool message back instead of+ actually executing the call. No real dispatch happens."""+ pipeline = _make_pipeline(monkeypatch)+ host = _make_host(pipeline, max_rounds=3)++ tool_calls = [+ {"id": "call_1", "name": "rag", "arguments": '{"query": "x"}'},+ ]+ outcome = await host.dispatch_tools(iteration=0, tool_calls=tool_calls)++ assert outcome.tool_messages+ assert outcome.tool_messages[0]["tool_call_id"] == "call_1"+ assert outcome.tool_messages[0]["name"] == "rag"+ assert "ask_user" in outcome.tool_messages[0]["content"].lower()+++async def test_rephrase_round_cap_short_circuits_dispatch(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """After max_rounds ``ask_user`` calls, the next ``ask_user`` is+ answered with a synthetic FINISH directive rather than being+ dispatched."""+ pipeline = _make_pipeline(monkeypatch)+ host = _make_host(pipeline, max_rounds=2)+ host._rounds_used = 2 # simulate already consumed budget++ tool_calls = [+ {"id": "call_x", "name": "ask_user", "arguments": "{}"},+ ]+ outcome = await host.dispatch_tools(iteration=3, tool_calls=tool_calls)++ assert outcome.tool_messages+ assert outcome.tool_messages[0]["tool_call_id"] == "call_x"+ content = outcome.tool_messages[0]["content"].lower()+ assert "finish" in content or "limit" in content+ # Round counter unchanged — the cap-reply doesn't consume another+ # round (and dispatch_tool_calls was never invoked).+ assert host._rounds_used == 2+++async def test_rephrase_force_finalize_returns_empty_text(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """If the inner loop runs out of iterations the host's force_finalize+ yields an empty result so the caller falls back to the raw topic."""+ pipeline = _make_pipeline(monkeypatch)+ host = _make_host(pipeline, max_rounds=3)++ text, completed, calls = await host.force_finalize(+ messages=[], start_iteration=10+ )+ assert text == ""+ assert completed is False+ assert calls == 0diff --git a/tests/agents/research/test_request_config.py b/tests/agents/research/test_request_config.pyindex 26eeb01f1..0a55dd57c 100644--- a/tests/agents/research/test_request_config.py+++ b/tests/agents/research/test_request_config.py@@ -1,25 +1,34 @@-from __future__ import annotations+"""Tests for the research request-config helpers.++The legacy multi-agent prompt manifests (rephrase_agent.yaml,+decompose_agent.yaml, research_agent.yaml, note_agent.yaml,+reporting_agent.yaml) were deleted in the agentic-loop refactor. The+``sources`` knob was retired alongside them — tool composition now+goes through ``compose_enabled_tools`` like chat, driven by the user's+composer toggles plus the attached KB (auto-mounted as ``rag``). What+remains is coverage for the public ``request_config`` helpers that+drive runtime composition.+"""-import pytest+from __future__ import annotationsfrom deeptutor.agents.research.request_config import (build_research_execution_policy,build_research_runtime_config,validate_research_request_config,)-from deeptutor.services.prompt import get_prompt_manager-def test_validate_research_request_config_allows_empty_sources() -> None:+def test_validate_research_request_config_accepts_minimal_payload() -> None:request = validate_research_request_config({"mode": "notes","depth": "quick",- "sources": [],})- assert request.sources == []+ assert request.mode == "notes"+ assert request.depth == "quick"def test_build_research_execution_policy_maps_intent_to_internal_settings() -> None:@@ -27,53 +36,29 @@ def test_build_research_execution_policy_maps_intent_to_internal_settings() -> N{"mode": "comparison","depth": "deep",- "sources": ["kb", "papers"],})- policy = build_research_execution_policy(- request_config=request,- enabled_tools={"code_execution"},- )+ policy = build_research_execution_policy(request_config=request)assert policy["planning"]["rephrase"]["enabled"] is Trueassert policy["planning"]["decompose"]["mode"] == "manual"assert policy["researching"]["execution_mode"] == "parallel"- assert policy["researching"]["enable_rag"] is True- assert policy["researching"]["enable_web_search"] is False- assert policy["researching"]["enable_paper_search"] is True- assert policy["researching"]["enable_run_code"] is True+ # Source-derived enable_* flags were removed: tool composition is+ # delegated to the shared ``compose_enabled_tools`` policy at runtime.+ assert "enable_rag" not in policy["researching"]+ assert "enable_web_search" not in policy["researching"]+ assert "enable_paper_search" not in policy["researching"]+ assert "enable_run_code" not in policy["researching"]+ assert "enabled_tools" not in policy["researching"]assert policy["reporting"]["style"] == "comparison"- assert "outline_contract" not in policy["reporting"]assert policy["queue"]["max_length"] == 8-def test_build_research_execution_policy_supports_llm_only_mode() -> None:- request = validate_research_request_config(- {- "mode": "report",- "depth": "standard",- "sources": [],- }- )- policy = build_research_execution_policy(- request_config=request,- enabled_tools=set(),- )-- assert policy["researching"]["enable_rag"] is False- assert policy["researching"]["enable_web_search"] is False- assert policy["researching"]["enable_paper_search"] is False- assert policy["researching"]["enable_run_code"] is False- assert policy["researching"]["enabled_tools"] == []- assert policy["intent"]["sources"] == []---def test_build_research_runtime_config_uses_intent_and_sources() -> None:+def test_build_research_runtime_config_carries_intent_without_sources() -> None:request = validate_research_request_config({"mode": "learning_path","depth": "standard",- "sources": ["web"],})@@ -88,10 +73,8 @@ def test_build_research_runtime_config_uses_intent_and_sources() -> None:},"rag": {"default_mode": "hybrid"},},- "tools": {"web_search": {"enabled": True}},},request_config=request,- enabled_tools=set(),kb_name="research-kb",)@@ -99,231 +82,10 @@ def test_build_research_runtime_config_uses_intent_and_sources() -> None:assert runtime["planning"]["decompose"]["auto_max_subtopics"] == 4assert runtime["researching"]["max_iterations"] == 3assert runtime["researching"]["execution_mode"] == "series"- assert runtime["researching"]["enable_web_search"] is True- assert runtime["researching"]["enable_rag"] is Falseassert runtime["reporting"]["style"] == "learning_path"- assert "outline_contract" not in runtime["reporting"]assert runtime["queue"]["max_length"] == 5assert runtime["rag"]["kb_name"] == "research-kb"assert runtime["intent"]["mode"] == "learning_path"assert runtime["intent"]["depth"] == "standard"- assert runtime["intent"]["sources"] == ["web"]---def test_reporting_mode_contracts_live_in_prompt_files() -> None:- prompts = get_prompt_manager().load_prompts(- module_name="research",- agent_name="reporting_agent",- language="en",- )-- mode_contracts = prompts["mode_contracts"]- assert "comparison document" in mode_contracts["comparison_single_pass"]- assert "revision notes" in mode_contracts["study_notes_single_pass"]- assert "study plan" in mode_contracts["learning_path_single_pass"]--- ("agent_name", "language", "expected_keys"),- [- (- "rephrase_agent",- "en",- [- "study_notes_rephrase",- "report_rephrase",- "comparison_rephrase",- "learning_path_rephrase",- ],- ),- (- "rephrase_agent",- "zh",- [- "study_notes_rephrase",- "report_rephrase",- "comparison_rephrase",- "learning_path_rephrase",- ],- ),- (- "decompose_agent",- "en",- [- "study_notes_decompose",- "report_decompose",- "comparison_decompose",- "learning_path_decompose",- ],- ),- (- "decompose_agent",- "zh",- [- "study_notes_decompose",- "report_decompose",- "comparison_decompose",- "learning_path_decompose",- ],- ),- (- "research_agent",- "en",- [- "study_notes_research",- "report_research",- "comparison_research",- "learning_path_research",- ],- ),- (- "research_agent",- "zh",- [- "study_notes_research",- "report_research",- "comparison_research",- "learning_path_research",- ],- ),- (- "note_agent",- "en",- [- "study_notes_note",- "report_note",- "comparison_note",- "learning_path_note",- ],- ),- (- "note_agent",- "zh",- [- "study_notes_note",- "report_note",- "comparison_note",- "learning_path_note",- ],- ),- (- "reporting_agent",- "zh",- [- "study_notes_single_pass",- "report_single_pass",- "comparison_single_pass",- "learning_path_single_pass",- ],- ),- ],-)-def test_research_agent_mode_contracts_load_from_prompt_files(- agent_name: str,- language: str,- expected_keys: list[str],-) -> None:- prompts = get_prompt_manager().load_prompts(- module_name="research",- agent_name=agent_name,- language=language,- )-- mode_contracts = prompts["mode_contracts"]- for key in expected_keys:- assert key in mode_contracts- assert isinstance(mode_contracts[key], str)- assert mode_contracts[key].strip()---# -----------------------------------------------------------------# Mode-specific process template tests (ReportingAgent)-# ------------------------------------------------------------------_MODE_PROCESS_KEYS = [- "generate_outline",- "write_introduction",- "write_section_body",- "write_conclusion",- "write_full_report",-]--_NON_REPORT_MODES = ["study_notes", "comparison", "learning_path"]--[email protected]("language", ["en", "zh"])[email protected]("mode", _NON_REPORT_MODES)-def test_reporting_mode_process_templates_exist(language: str, mode: str) -> None:- """Each non-report mode must have all 5 mode-specific process keys."""- prompts = get_prompt_manager().load_prompts(- module_name="research",- agent_name="reporting_agent",- language=language,- )- process = prompts["process"]- for base_key in _MODE_PROCESS_KEYS:- full_key = f"{base_key}_{mode}"- assert full_key in process, f"Missing process.{full_key} in {language}/reporting_agent.yaml"- assert isinstance(process[full_key], str)- assert len(process[full_key].strip()) > 50, f"process.{full_key} is too short"--[email protected]("language", ["en", "zh"])-def test_reporting_generic_process_templates_still_exist(language: str) -> None:- """Generic (report-mode) process templates must still be present as fallback."""- prompts = get_prompt_manager().load_prompts(- module_name="research",- agent_name="reporting_agent",- language=language,- )- process = prompts["process"]- for base_key in _MODE_PROCESS_KEYS:- assert base_key in process, f"Missing generic process.{base_key}"---def _simulate_get_mode_process_prompt(- prompts: dict, report_style: str, base_key: str, default: str = ""-) -> str:- """Replicate the logic of ReportingAgent._get_mode_process_prompt without importing it."""-- def _get(section: str, key: str, dflt: str = "") -> str:- try:- return prompts[section][key]- except (KeyError, TypeError):- return dflt-- if report_style and report_style != "report":- mode_key = f"{base_key}_{report_style}"- mode_prompt = _get("process", mode_key, "")- if mode_prompt:- return mode_prompt- return _get("process", base_key, default)---def test_get_mode_process_prompt_selects_mode_template() -> None:- """Mode-specific template is preferred over generic for non-report modes."""- prompts = get_prompt_manager().load_prompts(- module_name="research",- agent_name="reporting_agent",- language="en",- )-- mode_prompt = _simulate_get_mode_process_prompt(prompts, "study_notes", "generate_outline")- generic_prompt = prompts["process"]["generate_outline"]-- assert mode_prompt != generic_prompt- assert "study" in mode_prompt.lower()---def test_get_mode_process_prompt_falls_back_for_report() -> None:- """For report mode, the generic template is used as fallback."""- prompts = get_prompt_manager().load_prompts(- module_name="research",- agent_name="reporting_agent",- language="en",- )-- mode_prompt = _simulate_get_mode_process_prompt(prompts, "report", "generate_outline")- generic_prompt = prompts["process"]["generate_outline"]-- assert mode_prompt == generic_prompt+ assert "sources" not in runtime["intent"]+ assert "tools" not in runtime # no source-derived tools overridesdiff --git a/tests/agents/research/test_research_pipeline_rag.py b/tests/agents/research/test_research_pipeline_rag.pydeleted file mode 100644index c411cbdb5..000000000--- a/tests/agents/research/test_research_pipeline_rag.py+++ /dev/null@@ -1,194 +0,0 @@-"""-Tests for RAG safety in the deep-research pipeline.--These tests pin two contracts:--* The deprecated ``DE-all`` placeholder fallback is gone — when no- knowledge base is configured, ``ResearchPipeline._call_tool``- short-circuits with a structured ``status: skipped`` JSON instead of- invoking the RAG service against a non-existent KB.-* ``DecomposeAgent`` defensively disables RAG when no ``kb_name`` is- available, even when the runtime config still says- ``enable_rag: True``.-"""--from __future__ import annotations--import json-from types import SimpleNamespace-from typing import Any--import pytest--from deeptutor.agents.research.agents.decompose_agent import DecomposeAgent-from deeptutor.agents.research.research_pipeline import ResearchPipeline---def _minimal_pipeline_config() -> dict[str, Any]:- return {- "system": {"language": "en", "verbose": False},- "planning": {- "rephrase": {"enabled": False, "max_iterations": 1},- "decompose": {- "mode": "manual",- "initial_subtopics": 1,- "auto_max_subtopics": 1,- },- },- "researching": {- "max_iterations": 1,- "iteration_mode": "fixed",- "execution_mode": "series",- "max_parallel_topics": 1,- "new_topic_min_score": 0.9,- "enable_rag": True,- "enable_web_search": False,- "enable_paper_search": False,- "enable_run_code": False,- "enabled_tools": ["rag"],- "tool_timeout": 5,- "tool_max_retries": 0,- },- "reporting": {- "min_section_length": 10,- "report_single_pass_threshold": 1,- "enable_citation_list": False,- "enable_inline_citations": False,- "deduplicate_enabled": False,- "style": "report",- "mode": "report",- "depth": "quick",- },- "queue": {"max_length": 2},- "rag": {},- "intent": {- "mode": "report",- "depth": "quick",- "sources": [],- "manual_subtopics": None,- "manual_max_iterations": None,- "confirmed_outline": None,- },- "tools": {"web_search": {"enabled": False}},- "paths": {},- }---def _build_bare_pipeline(config: dict[str, Any]) -> ResearchPipeline:- """Build a ``ResearchPipeline`` skeleton with just the attributes- ``_call_tool`` reads — avoids the heavy agent-initialisation tree."""- pipeline = ResearchPipeline.__new__(ResearchPipeline)- pipeline.config = config- pipeline.research_id = "test"- pipeline.cache_dir = "/tmp/test" # type: ignore[assignment]- pipeline.trace_callback = None- pipeline._stage_events = {"planning": [], "reporting": [], "researching": []}- return pipeline---async def test_research_pipeline_call_tool_rag_without_kb_returns_skipped_json() -> None:- """The DE-all fallback is gone: ``rag`` without a ``kb_name`` must be a no-op."""- pipeline = _build_bare_pipeline(_minimal_pipeline_config())-- raw = await pipeline._call_tool("rag", "What is convolution?")- payload = json.loads(raw)-- assert payload["status"] == "skipped"- assert payload["reason"] == "no_kb_selected"- assert payload["tool"] == "rag"---async def test_research_pipeline_call_tool_unknown_tool_returns_failed_not_rag() -> None:- """Unknown tool types must not silently fall through to RAG anymore."""- pipeline = _build_bare_pipeline(_minimal_pipeline_config())-- raw = await pipeline._call_tool("not_a_real_tool", "anything")- payload = json.loads(raw)-- assert payload["status"] == "failed"- assert payload["reason"] == "unknown_tool"- assert payload["tool"] == "not_a_real_tool"---def test_decompose_agent_disables_rag_when_no_kb_name() -> None:- """Defensive guard at the agent layer: no ``kb_name`` ⇒ ``enable_rag = False``."""- config = _minimal_pipeline_config()- config["rag"] = {"kb_name": None}- config["researching"]["enable_rag"] = True-- agent = DecomposeAgent(config=config, api_key="sk-test", kb_name=None)-- assert agent.kb_name is None- assert agent.enable_rag is False---def test_decompose_agent_keeps_rag_when_kb_name_provided_via_kwarg() -> None:- config = _minimal_pipeline_config()- config["rag"] = {}- config["researching"]["enable_rag"] = True-- agent = DecomposeAgent(config=config, api_key="sk-test", kb_name="my-kb")-- assert agent.kb_name == "my-kb"- assert agent.enable_rag is True---def test_decompose_agent_no_longer_falls_back_to_ai_textbook() -> None:- """The hardcoded ``ai_textbook`` fallback was removed."""- config = _minimal_pipeline_config()- config["rag"] = {}- config["researching"]["enable_rag"] = True-- agent = DecomposeAgent(config=config, api_key="sk-test", kb_name=None)-- assert agent.kb_name is None # NOT "ai_textbook"- assert agent.enable_rag is False---async def test_research_planning_forwards_attachments_when_rephrase_has_zero_iterations(- tmp_path,-) -> None:- """If rephrase is enabled but performs no LLM call, decompose is the first LLM."""- config = _minimal_pipeline_config()- config["planning"]["rephrase"] = {"enabled": True, "max_iterations": 0}- attachment = object()- captured: dict[str, Any] = {}-- class FakeDecomposeAgent:- def set_citation_manager(self, citation_manager: Any) -> None:- captured["citation_manager"] = citation_manager-- async def process(self, **kwargs: Any) -> dict[str, Any]:- captured["decompose"] = kwargs- return {- "sub_topics": [],- "sub_queries": [],- "rag_context": "",- "total_subtopics": 0,- }-- pipeline = ResearchPipeline.__new__(ResearchPipeline)- pipeline.config = config- pipeline.attachments = [attachment]- pipeline.pre_confirmed_outline = None- pipeline.cache_dir = tmp_path- pipeline.citation_manager = object()- pipeline.agents = {- "decompose": FakeDecomposeAgent(),- "manager": SimpleNamespace(set_primary_topic=lambda _topic: None),- }- pipeline.queue = SimpleNamespace(blocks=[], get_statistics=lambda: {"total_blocks": 0})- pipeline.logger = SimpleNamespace(- info=lambda *_args, **_kwargs: None,- success=lambda *_args, **_kwargs: None,- warning=lambda *_args, **_kwargs: None,- )- pipeline._log_progress = lambda *_args, **_kwargs: None-- result = await pipeline._phase1_planning("Research this image")-- assert result == "Research this image"- assert captured["decompose"]["attachments"] == [attachment]diff --git a/tests/agents/solve/test_pipeline.py b/tests/agents/solve/test_pipeline.pynew file mode 100644index 000000000..91a06630c--- /dev/null+++ b/tests/agents/solve/test_pipeline.py@@ -0,0 +1,854 @@+"""Unit + integration tests for ``SolvePipeline``.++Covers:++* JSON plan parsing (valid / empty / malformed)+* Tone-key selection by step position+* Step-finish rendering (empty / non-empty)+* One-step happy path: pre-retrieve skipped, plan, ``FINISH`` per step,+ synthesize, ``stream.result`` payload+* Multi-step ``REPLAN`` back-edge: step 1 emits ``REPLAN``, plan re-runs,+ new plan completes+* Replan budget exhaustion: ``REPLAN`` fallback becomes step content+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from deeptutor.agents.solve.pipeline import (+ Plan,+ PlanStep,+ SolvePipeline,+ StepFinish,+ _PROTOCOL_STEP,+)+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.stream_bus import StreamBus+++# ---------------------------------------------------------------------------+# Plumbing+# ---------------------------------------------------------------------------+++async def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asyncio.Task[Any]]:+ events: list[StreamEvent] = []++ async def _consume() -> None:+ async for event in bus.subscribe():+ events.append(event)++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ return events, consumer # type: ignore[return-value]+++def _llm_chunk(+ *,+ content: str | None = None,+ tool_calls: list[dict[str, Any]] | None = None,+) -> SimpleNamespace:+ delta_fields: dict[str, Any] = {"content": content}+ if tool_calls is not None:+ delta_fields["tool_calls"] = [+ SimpleNamespace(+ index=tc.get("index", i),+ id=tc.get("id"),+ function=SimpleNamespace(+ name=tc.get("name"),+ arguments=tc.get("arguments"),+ ),+ )+ for i, tc in enumerate(tool_calls)+ ]+ else:+ delta_fields["tool_calls"] = None+ return SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(**delta_fields))])+++async def _async_stream(chunks: list[SimpleNamespace]):+ for chunk in chunks:+ yield chunk+++class _ScriptedChatClient:+ """Plays back a queue of scripted streams. Each call to+ ``chat.completions.create`` pops one stream from ``script``."""++ def __init__(self, scripted: list[list[SimpleNamespace]]) -> None:+ self._script = list(scripted)+ self.calls: list[dict[str, Any]] = []++ outer = self++ class _Completions:+ async def create(self, **kwargs: Any):+ outer.calls.append(+ {**kwargs, "messages": list(kwargs.get("messages") or [])}+ )+ if not outer._script:+ raise RuntimeError("Scripted client exhausted")+ return _async_stream(outer._script.pop(0))++ class _Chat:+ completions = _Completions()++ self.chat = _Chat()+++def _stub_llm_config(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "deeptutor.agents.solve.pipeline.get_llm_config",+ lambda: SimpleNamespace(+ binding="openai",+ model="gpt-test",+ api_key="k",+ base_url="https://x.test",+ api_version=None,+ extra_headers=None,+ ),+ )+++def _stub_empty_tool_registry(monkeypatch: pytest.MonkeyPatch) -> None:+ registry = SimpleNamespace(+ get_enabled=lambda selected: [],+ get=lambda name: None,+ build_openai_schemas=lambda names: [],+ build_prompt_text=lambda *_args, **_kwargs: "",+ )+ monkeypatch.setattr(+ "deeptutor.agents.solve.pipeline.get_tool_registry",+ lambda: registry,+ )+++def _make_pipeline(monkeypatch: pytest.MonkeyPatch, **overrides: Any) -> SolvePipeline:+ _stub_llm_config(monkeypatch)+ _stub_empty_tool_registry(monkeypatch)+ return SolvePipeline(**overrides)+++# ---------------------------------------------------------------------------+# Unit tests+# ---------------------------------------------------------------------------+++def test_parse_plan_valid_json(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = _make_pipeline(monkeypatch)+ raw = '{"analysis": "two-part", "steps": [{"id":"S1","goal":"first"},{"id":"S2","goal":"second"}]}'+ plan = pipeline._parse_plan(raw)+ assert plan.analysis == "two-part"+ assert [s.id for s in plan.steps] == ["S1", "S2"]+ assert [s.goal for s in plan.steps] == ["first", "second"]+++def test_parse_plan_empty_steps_falls_back_to_single_step(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ pipeline = _make_pipeline(monkeypatch)+ plan = pipeline._parse_plan('{"analysis": "x", "steps": []}')+ assert len(plan.steps) == 1+ assert plan.steps[0].id == "S1"+++def test_parse_plan_malformed_falls_back(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = _make_pipeline(monkeypatch)+ plan = pipeline._parse_plan("not json at all")+ assert len(plan.steps) == 1+ assert "Failed to parse" in plan.analysis+++def test_parse_plan_skips_step_without_goal(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = _make_pipeline(monkeypatch)+ raw = '{"analysis":"a","steps":[{"id":"S1","goal":""},{"id":"S2","goal":"keeper"}]}'+ plan = pipeline._parse_plan(raw)+ assert [s.id for s in plan.steps] == ["S2"]+++def test_tone_key_dispatch(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = _make_pipeline(monkeypatch)+ assert pipeline._tone_key(0, 1) == "only"+ assert pipeline._tone_key(0, 3) == "first"+ assert pipeline._tone_key(1, 3) == "middle"+ assert pipeline._tone_key(2, 3) == "last"+++def test_render_step_finishes_renders_blocks(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = _make_pipeline(monkeypatch)+ finishes = [+ StepFinish(step=PlanStep(id="S1", goal="setup"), text="Let's first ..."),+ StepFinish(step=PlanStep(id="S2", goal="wrap"), text="Finally ..."),+ ]+ rendered = pipeline._render_step_finishes(finishes)+ assert "[S1]" in rendered and "setup" in rendered+ assert "[S2]" in rendered and "wrap" in rendered+ assert "Let's first ..." in rendered+ assert "Finally ..." in rendered+++def test_render_step_finishes_empty_falls_back(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = _make_pipeline(monkeypatch)+ rendered = pipeline._render_step_finishes([])+ # YAML "empty.no_step_sections" — checks the fallback string is non-empty.+ assert rendered.strip() != ""+++def test_resolved_tools_auto_mounts_rag_with_kb(monkeypatch: pytest.MonkeyPatch) -> None:+ """When a KB is attached and ``rag`` is registry-resident, it gets+ auto-mounted even if the caller didn't request it."""+ _stub_llm_config(monkeypatch)+ rag_tool = SimpleNamespace(name="rag")+ registry = SimpleNamespace(+ get_enabled=lambda selected: [],+ get=lambda name: rag_tool if name == "rag" else None,+ build_openai_schemas=lambda names: [],+ build_prompt_text=lambda *_a, **_k: "",+ )+ monkeypatch.setattr(+ "deeptutor.agents.solve.pipeline.get_tool_registry",+ lambda: registry,+ )+ pipeline = SolvePipeline(kb_name="course-kb", enabled_tools=[])+ assert "rag" in pipeline._resolved_tools()+++def test_compose_full_response_concatenates(monkeypatch: pytest.MonkeyPatch) -> None:+ pipeline = _make_pipeline(monkeypatch)+ finishes = [+ StepFinish(step=PlanStep(id="S1", goal="g"), text="first section"),+ StepFinish(step=PlanStep(id="S2", goal="g"), text="second section"),+ ]+ body = pipeline._compose_full_response(finishes, "final wrap-up")+ assert body == "first section\n\nsecond section\n\nfinal wrap-up"+++# ---------------------------------------------------------------------------+# Integration: one-step happy path+# ---------------------------------------------------------------------------+++async def test_one_step_happy_path_emits_plan_finish_synthesize(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """End-to-end: no KB, one-step plan, one ``FINISH`` iteration, then the+ synthesize ``FINISH``. Verifies the orchestrator drives the three phases+ and the result payload reflects the full conversation."""+ pipeline = _make_pipeline(monkeypatch)+ client = _ScriptedChatClient(+ [+ # Phase 1: planner emits ``PLAN`` + JSON+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(+ content='{"analysis":"single","steps":[{"id":"S1","goal":"answer"}]}'+ ),+ ],+ # Phase 2: step S1 emits ``FINISH`` directly+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="The answer to the question is 42."),+ ],+ # Phase 2.5: explain triage decides this is too simple → SKIP+ [+ _llm_chunk(content="``SKIP``\n"),+ ],+ # Phase 3: synthesize emits ``FINISH`` with the precise answer+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="Final: 42. Briefly: we computed 42."),+ ],+ ]+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: client)++ bus = StreamBus()+ events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-1",+ user_message="what is the answer?",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "turn-1"},+ )+ payload = await pipeline.run(+ context=context,+ question=context.user_message,+ attachments=None,+ conversation_context="",+ memory_context="",+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ # Four LLM calls: plan, step S1, explain-judge (SKIP), synthesize.+ assert len(client.calls) == 4+ # The step FINISH and synthesize FINISH both streamed as content events.+ content_events = [+ e for e in events if e.type == StreamEventType.CONTENT and e.source == "deep_solve"+ ]+ bodies = "".join(e.content for e in content_events)+ assert "The answer to the question is 42." in bodies+ assert "Final: 42" in bodies+ # Result payload reflects step count + synthesis.+ assert payload["step_count"] == 1+ assert payload["completed_steps"] == 1+ assert payload["plan_revisions"] == 0+ assert "The answer to the question is 42." in payload["response"]+ assert "Final: 42" in payload["response"]+++# ---------------------------------------------------------------------------+# Integration: multi-step happy path+# ---------------------------------------------------------------------------+++async def test_two_step_happy_path(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """End-to-end: 2-step plan, each step's loop closes with ``FINISH`` on the+ first iteration, then synthesize. Verifies the per-step loop actually+ advances to the next step (the bug Frank saw was Phase 2 silently stopping+ after the first plan)."""+ pipeline = _make_pipeline(monkeypatch)+ client = _ScriptedChatClient(+ [+ # Phase 1: planner emits a 2-step plan+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(+ content='{"analysis":"two parts","steps":[{"id":"S1","goal":"explore"},{"id":"S2","goal":"conclude"}]}'+ ),+ ],+ # Phase 2 / step S1: FINISH directly+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="Let's first explore the concept."),+ ],+ # Step S1 explain triage → SKIP+ [+ _llm_chunk(content="``SKIP``\n"),+ ],+ # Phase 2 / step S2: FINISH directly+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="Finally, we conclude with the answer."),+ ],+ # Step S2 explain triage → SKIP+ [+ _llm_chunk(content="``SKIP``\n"),+ ],+ # Phase 3: synthesize+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="Overall: explored and concluded."),+ ],+ ]+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: client)++ bus = StreamBus()+ events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-multi",+ user_message="what is agentic rag?",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "turn-multi"},+ )+ payload = await pipeline.run(+ context=context,+ question=context.user_message,+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ # Six LLM calls: plan + step1 + judge1 + step2 + judge2 + synthesize.+ assert len(client.calls) == 6, (+ f"Expected 6 LLM calls (plan + 2 steps + 2 explain-judges + synthesize), got {len(client.calls)}"+ )+ assert payload["step_count"] == 2+ assert payload["completed_steps"] == 2+ assert payload["plan_revisions"] == 0+ # All three FINISH bodies stream to user as content.+ body = payload["response"]+ assert "Let's first explore" in body+ assert "Finally, we conclude" in body+ assert "Overall: explored and concluded" in body+++# ---------------------------------------------------------------------------+# Integration: REPLAN back-edge+# ---------------------------------------------------------------------------+++async def test_replan_back_edge_reruns_planner(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Step 1 of the first plan emits ``REPLAN``; the orchestrator re-enters+ the planner, the new plan's step 1 emits ``FINISH``, synthesis runs."""+ pipeline = _make_pipeline(monkeypatch, max_replans=2)+ client = _ScriptedChatClient(+ [+ # First plan+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(+ content='{"analysis":"v1","steps":[{"id":"S1","goal":"old approach"}]}'+ ),+ ],+ # Step S1 of plan v1: REPLAN+ [+ _llm_chunk(content="``REPLAN``\n"),+ _llm_chunk(content="The plan misses an upstream dependency."),+ ],+ # Plan v2 (with replan reason in prompt)+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(+ content='{"analysis":"v2","steps":[{"id":"S1","goal":"new approach"}]}'+ ),+ ],+ # Step S1 of plan v2: FINISH+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="Revised section."),+ ],+ # Explain triage for the FINISHed step → SKIP+ [+ _llm_chunk(content="``SKIP``\n"),+ ],+ # Synthesize+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="All wrapped up."),+ ],+ ]+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: client)++ bus = StreamBus()+ _events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-2",+ user_message="something complex",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "turn-2"},+ )+ payload = await pipeline.run(+ context=context,+ question=context.user_message,+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ assert payload["plan_revisions"] == 1+ assert payload["step_count"] == 1 # final plan had one step+ assert "Revised section." in payload["response"]+ assert "All wrapped up." in payload["response"]+ # 6 LLM calls: plan v1, REPLAN, plan v2, FINISH, explain-judge (SKIP), synthesize.+ # REPLAN does NOT trigger explain triage — only true FINISH does.+ assert len(client.calls) == 6+++# ---------------------------------------------------------------------------+# Integration: replan budget exhaustion+# ---------------------------------------------------------------------------+++async def test_replan_budget_exhausted_keeps_reason_as_step_content(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When ``max_replans=0`` and the step emits ``REPLAN``, the orchestrator+ accepts the REPLAN reason text as the step's section so synthesis still+ has something to anchor on."""+ pipeline = _make_pipeline(monkeypatch, max_replans=0)+ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(+ content='{"analysis":"a","steps":[{"id":"S1","goal":"go"}]}'+ ),+ ],+ [+ _llm_chunk(content="``REPLAN``\n"),+ _llm_chunk(content="The plan is bad, but we have no budget."),+ ],+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="Best-effort synthesis."),+ ],+ ]+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: client)++ bus = StreamBus()+ _events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-3",+ user_message="hi",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "turn-3"},+ )+ payload = await pipeline.run(+ context=context,+ question=context.user_message,+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ assert payload["plan_revisions"] == 0 # no successful replan+ assert "The plan is bad" in payload["response"]+ assert "Best-effort synthesis." in payload["response"]+++# ---------------------------------------------------------------------------+# Integration: FINISH content streams chunk-by-chunk+# ---------------------------------------------------------------------------+++async def test_step_finish_streams_chunks_live(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Each step's ``FINISH`` text must arrive as multiple ``content`` events+ (one per upstream chunk) so the chat bubble fills typewriter-style,+ rather than landing in a single buffered event at the end."""+ pipeline = _make_pipeline(monkeypatch)+ finish_chunks = ["Let's first ", "explore ", "the topic. ", "Done."]+ client = _ScriptedChatClient(+ [+ # Plan: 1 step+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(content='{"analysis":"a","steps":[{"id":"S1","goal":"go"}]}'),+ ],+ # Step S1 FINISH streamed in 4 separate chunks+ [_llm_chunk(content="``FINISH``\n"), *(_llm_chunk(content=c) for c in finish_chunks)],+ # Explain triage → SKIP+ [_llm_chunk(content="``SKIP``\n")],+ # Synthesize: also chunked+ [_llm_chunk(content="``FINISH``\n"), _llm_chunk(content="Wrap "), _llm_chunk(content="up.")],+ ]+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: client)++ bus = StreamBus()+ events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-stream",+ user_message="q",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "t-stream"},+ )+ await pipeline.run(+ context=context,+ question=context.user_message,+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ body_content_events = [+ e+ for e in events+ if e.type == StreamEventType.CONTENT+ and (e.metadata or {}).get("call_kind") == "llm_final_response"+ ]+ body_texts = [e.content for e in body_content_events]+ # Per-step FINISH chunks land as separate events (live streaming):+ for piece in finish_chunks:+ assert piece in body_texts, (+ f"expected chunk {piece!r} to appear as its own content event; got {body_texts!r}"+ )+ # Synthesize chunks also stream live (separate events).+ assert "Wrap " in body_texts and "up." in body_texts+++async def test_step_finish_streams_many_small_chunks(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Real LLMs typically emit FINISH content as 20–100 small chunks. Confirm+ each one lands as its own ``content`` event so the chat bubble fills+ character-by-character, not in one buffered burst."""+ pipeline = _make_pipeline(monkeypatch)+ # 20 chunks of 1–4 chars each.+ step_chunks = [+ "L", "et", "'s ", "f", "irst", " ex", "pl", "ore",+ " the", " co", "n", "ce", "pt", ".", " ", "T", "h", "en", ":", " done.",+ ]+ expected_full_text = "".join(step_chunks)++ client = _ScriptedChatClient(+ [+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(content='{"analysis":"x","steps":[{"id":"S1","goal":"g"}]}'),+ ],+ [_llm_chunk(content="``FINISH``\n"), *(_llm_chunk(content=c) for c in step_chunks)],+ # Explain triage → SKIP (so the step's FINISH chunks are still the only+ # llm_final_response events in stage=reasoning).+ [_llm_chunk(content="``SKIP``\n")],+ [_llm_chunk(content="``FINISH``\n"), _llm_chunk(content="done.")],+ ]+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: client)++ bus = StreamBus()+ events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-many",+ user_message="q",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "t-many"},+ )+ payload = await pipeline.run(+ context=context, question=context.user_message, stream=bus+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ # Find the per-step FINISH chunks (stage=reasoning). Filter out+ # section-break events the pipeline injects between sections so they+ # don't inflate the per-chunk count.+ step_body_events = [+ e+ for e in events+ if e.type == StreamEventType.CONTENT+ and e.stage == "reasoning"+ and (e.metadata or {}).get("call_kind") == "llm_final_response"+ and not (e.metadata or {}).get("section_break")+ ]+ # Each scripted chunk produces its own event — exactly 20 events for+ # the step's FINISH content (one per upstream chunk).+ assert len(step_body_events) == len(step_chunks), (+ f"expected {len(step_chunks)} per-chunk events, got {len(step_body_events)}"+ )+ # Concatenation matches the original text — nothing dropped or reordered.+ assert "".join(e.content for e in step_body_events) == expected_full_text+ assert expected_full_text in payload["response"]+ # A section break must be emitted between the step's FINISH and the+ # synthesize phase — otherwise '## Header' in the next section would+ # glue onto the prior paragraph's last chunk and collapse.+ section_breaks = [+ e+ for e in events+ if e.type == StreamEventType.CONTENT+ and (e.metadata or {}).get("section_break")+ ]+ assert section_breaks, "expected at least one section-break event between sections"+ assert all(e.content == "\n\n" for e in section_breaks)+++# ---------------------------------------------------------------------------+# Integration: deep-explain triage triggers explain expansion under FINISH+# ---------------------------------------------------------------------------+++async def test_explain_triage_explain_path_streams_under_finish(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When the triage call returns ``EXPLAIN``, the pipeline runs a deeper+ explanation pass whose text streams as additional ``content`` events+ under the step's FINISH and is folded into the final response payload."""+ pipeline = _make_pipeline(monkeypatch)+ client = _ScriptedChatClient(+ [+ # Plan: 1 step+ [+ _llm_chunk(content="``PLAN``\n"),+ _llm_chunk(content='{"analysis":"a","steps":[{"id":"S1","goal":"derive"}]}'),+ ],+ # Step S1: FINISH with a non-trivial concept+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="By symmetry, the integral vanishes."),+ ],+ # Explain triage → EXPLAIN with a focus sentence+ [+ _llm_chunk(content="``EXPLAIN``\n"),+ _llm_chunk(content="the parity argument behind the vanishing integral."),+ ],+ # Deep explain → FINISH with the expansion+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="**Intuition:** odd integrand over a symmetric domain integrates to zero."),+ ],+ # Synthesize+ [+ _llm_chunk(content="``FINISH``\n"),+ _llm_chunk(content="Wrap-up."),+ ],+ ]+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: client)++ bus = StreamBus()+ events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-explain",+ user_message="why does this integral vanish?",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "turn-explain"},+ )+ payload = await pipeline.run(+ context=context,+ question=context.user_message,+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ # Five LLM calls: plan + step + judge (EXPLAIN) + deep-explain + synthesize.+ assert len(client.calls) == 5, (+ f"Expected 5 LLM calls, got {len(client.calls)}: judge must trigger deep-explain"+ )+ # Both the FINISH text and the deep-explain text appear in the final response.+ body = payload["response"]+ assert "By symmetry, the integral vanishes." in body+ assert "odd integrand over a symmetric domain" in body+ # Both should also have streamed as user-visible content events.+ content_events = [+ e+ for e in events+ if e.type == StreamEventType.CONTENT+ and (e.metadata or {}).get("call_kind") == "llm_final_response"+ ]+ bodies = "".join(e.content for e in content_events)+ assert "By symmetry" in bodies+ assert "odd integrand over a symmetric domain" in bodies+ # The EXPLAIN content is wrapped in a <details open> block so the user+ # can fold it. Both the live stream and the persisted response payload+ # must contain the wrapping tags (with the triage focus in the summary).+ assert "<details open>" in bodies+ assert "</details>" in bodies+ assert "<summary>" in bodies+ assert "parity argument behind the vanishing integral" in bodies # focus+ assert "<details open>" in body+ assert "</details>" in body+ # The wrapping events carry a ``details_wrapper`` flag so the frontend+ # / tests can distinguish them from the LLM body.+ wrapper_events = [+ e for e in events if (e.metadata or {}).get("details_wrapper")+ ]+ assert len(wrapper_events) == 2, (+ f"Expected exactly 2 details-wrapper events (open + close), got {len(wrapper_events)}"+ )+ # Two section breaks must fire on the EXPLAIN path: one after the step+ # FINISH (before the explain expansion starts) and one after the deep+ # explain (before the synthesize section starts). Without them the+ # next chunk would glue onto the prior sentence and break markdown+ # block rendering (e.g. a leading ``##`` would no longer be a heading).+ section_breaks = [+ e+ for e in events+ if e.type == StreamEventType.CONTENT+ and (e.metadata or {}).get("section_break")+ ]+ assert len(section_breaks) == 2, (+ f"Expected 2 section breaks (after FINISH, after EXPLAIN), got {len(section_breaks)}"+ )+ assert all(e.content == "\n\n" for e in section_breaks)+++# ---------------------------------------------------------------------------+# Visible failure: pipeline exceptions surface as ERROR + CONTENT+# ---------------------------------------------------------------------------+++async def test_pipeline_failure_surfaces_visible_error_and_reraises(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """If an LLM call raises (network error, bad arg, ...) the pipeline must+ emit a labeled ERROR card + a CONTENT event so the chat bubble shows the+ problem instead of looking like a silent termination — then re-raise so+ the orchestrator's normal error path runs."""+ pipeline = _make_pipeline(monkeypatch)++ class _FailingCompletions:+ async def create(self, **kwargs: Any):+ raise RuntimeError("simulated upstream failure")++ failing_client = SimpleNamespace(+ chat=SimpleNamespace(completions=_FailingCompletions())+ )+ monkeypatch.setattr(pipeline, "_build_client", lambda: failing_client)++ bus = StreamBus()+ events, consumer = await _collect_bus_events(bus)+ context = UnifiedContext(+ session_id="s-fail",+ user_message="hi",+ knowledge_bases=[],+ language="en",+ metadata={"turn_id": "turn-fail"},+ )++ with pytest.raises(RuntimeError, match="simulated upstream failure"):+ await pipeline.run(+ context=context,+ question=context.user_message,+ stream=bus,+ )+ await asyncio.sleep(0)+ await bus.close()+ await consumer++ error_events = [e for e in events if e.type == StreamEventType.ERROR]+ content_events = [+ e+ for e in events+ if e.type == StreamEventType.CONTENT+ and (e.metadata or {}).get("call_kind") == "llm_final_response"+ ]+ assert error_events, "pipeline must emit a visible ERROR event on failure"+ assert any("simulated upstream failure" in e.content for e in error_events)+ assert content_events, "pipeline must also emit a CONTENT event so the chat bubble renders"+ assert any("simulated upstream failure" in e.content for e in content_events)+ # The error card has a call_id so TracePanels groups it under a real card+ # (a bare bus.error without call_id is invisible in the chat-bubble UI).+ err = error_events[0]+ assert (err.metadata or {}).get("call_id"), "error event must carry call_id"+++# ---------------------------------------------------------------------------+# Smoke: protocol constants are wired correctly+# ---------------------------------------------------------------------------+++def test_protocol_step_label_set() -> None:+ assert _PROTOCOL_STEP.allowed == ("THINK", "TOOL", "FINISH", "REPLAN")+ assert _PROTOCOL_STEP.terminal == frozenset({"FINISH", "REPLAN"})+ assert _PROTOCOL_STEP.final == frozenset({"FINISH"})+ assert _PROTOCOL_STEP.intermediate == frozenset({"THINK"})+ assert _PROTOCOL_STEP.tool_label == "TOOL"diff --git a/tests/agents/solve/test_tool_runtime.py b/tests/agents/solve/test_tool_runtime.pydeleted file mode 100644index 0bea165d8..000000000--- a/tests/agents/solve/test_tool_runtime.py+++ /dev/null@@ -1,187 +0,0 @@-from __future__ import annotations--from typing import Any--import pytest--from deeptutor.agents.solve.agents.planner_agent import PlannerAgent-from deeptutor.agents.solve.tool_runtime import SolveToolRuntime-from deeptutor.core.tool_protocol import (- ToolAlias,- ToolDefinition,- ToolParameter,- ToolPromptHints,- ToolResult,-)---class _FakeTool:- def __init__(- self,- name: str,- parameters: list[ToolParameter],- *,- aliases: list[ToolAlias] | None = None,- ) -> None:- self.name = name- self._parameters = parameters- self._aliases = aliases or []-- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name=self.name, description=f"{self.name} tool", parameters=self._parameters- )-- def get_prompt_hints(self, language: str = "en") -> ToolPromptHints: # noqa: ARG002- return ToolPromptHints(- short_description=f"{self.name} short description",- when_to_use=f"use {self.name}",- input_format="Natural language",- aliases=self._aliases,- )---class _FakeCoreRegistry:- def __init__(self, tools: dict[str, _FakeTool]) -> None:- self._tools = tools- self.prompt_calls: list[tuple[tuple[str, ...], str, dict[str, Any]]] = []- self.exec_calls: list[tuple[str, dict[str, Any]]] = []-- def get(self, name: str):- return self._tools.get(name)-- def build_prompt_text(- self,- names: list[str],- format: str = "list",- language: str = "en", # noqa: ARG002- **kwargs: Any,- ) -> str:- self.prompt_calls.append((tuple(names), format, kwargs))- return f"{format}:{','.join(names)}"-- async def execute(self, name: str, **kwargs: Any) -> ToolResult:- self.exec_calls.append((name, kwargs))- return ToolResult(content="ok", metadata={})---def test_solve_tool_runtime_builds_prompt_text_via_core_registry() -> None:- rag_tool = _FakeTool(- "rag",- [ToolParameter(name="query", type="string")],- aliases=[ToolAlias(name="rag_hybrid")],- )- registry = _FakeCoreRegistry({"rag": rag_tool, "rag_hybrid": rag_tool})-- runtime = SolveToolRuntime(["rag"], language="en", core_registry=registry)-- description = runtime.build_solver_description()-- assert description == "table:rag\n\naliases:rag"- assert runtime.tool_names == ["rag"]- assert "rag_hybrid" in runtime.valid_actions- assert ("rag",) == registry.prompt_calls[0][0]- assert [call[1] for call in registry.prompt_calls] == ["table", "aliases"]---async def test_solve_tool_runtime_executes_via_core_registry_with_context_binding() -> None:- code_tool = _FakeTool(- "code_execution",- [ToolParameter(name="intent", type="string")],- aliases=[ToolAlias(name="run_code")],- )- registry = _FakeCoreRegistry({"code_execution": code_tool, "run_code": code_tool})-- runtime = SolveToolRuntime(["code_execution"], language="en", core_registry=registry)-- result = await runtime.execute("run_code", "check determinant", output_dir="/tmp/solve")-- assert result.content == "ok"- assert registry.exec_calls == [- (- "run_code",- {- "intent": "check determinant",- "timeout": 30,- "workspace_dir": "/tmp/solve/code_runs",- },- )- ]---async def test_solve_tool_runtime_passes_event_sink_to_registry() -> None:- rag_tool = _FakeTool("rag", [ToolParameter(name="query", type="string")])- registry = _FakeCoreRegistry({"rag": rag_tool})- runtime = SolveToolRuntime(["rag"], language="en", core_registry=registry)-- async def _sink(- _event_type: str, _message: str = "", _metadata: dict[str, Any] | None = None- ) -> None:- return None-- await runtime.execute("rag", "definition", kb_name="algebra", event_sink=_sink)-- assert registry.exec_calls == [- (- "rag",- {- "query": "definition",- "event_sink": _sink,- "kb_name": "algebra",- },- )- ]---async def test_solve_tool_runtime_rag_without_kb_returns_graceful_skip() -> None:- """`rag` invoked without a kb_name must never reach the underlying RAG service.-- The runtime should return a structured ``ToolResult`` describing the skip- so the ReAct loop can keep going (the LLM sees a clear observation and- can replan or finalise).- """- rag_tool = _FakeTool("rag", [ToolParameter(name="query", type="string")])- registry = _FakeCoreRegistry({"rag": rag_tool})- runtime = SolveToolRuntime(["rag"], language="en", core_registry=registry)-- result = await runtime.execute("rag", "definition", kb_name=None)-- assert result.success is False- assert result.metadata == {"skipped": True, "reason": "no_kb_selected"}- assert "no knowledge base" in result.content.lower()- assert registry.exec_calls == [], "rag must NOT be forwarded to the registry"---async def test_solve_tool_runtime_rag_with_empty_kb_name_returns_graceful_skip() -> None:- rag_tool = _FakeTool("rag", [ToolParameter(name="query", type="string")])- registry = _FakeCoreRegistry({"rag": rag_tool})- runtime = SolveToolRuntime(["rag"], language="en", core_registry=registry)-- result = await runtime.execute("rag", "definition", kb_name="")-- assert result.success is False- assert result.metadata.get("reason") == "no_kb_selected"- assert registry.exec_calls == []---async def test_planner_agent_skips_retrieval_when_rag_not_enabled(- monkeypatch: pytest.MonkeyPatch,-) -> None:- web_tool = _FakeTool("web_search", [ToolParameter(name="query", type="string")])- registry = _FakeCoreRegistry({"web_search": web_tool})- runtime = SolveToolRuntime(["web_search"], language="en", core_registry=registry)- agent = PlannerAgent(config={}, language="en", tool_runtime=runtime)-- async def _unexpected_queries(*_args, **_kwargs):- raise AssertionError("query generation should not run when rag is disabled")-- monkeypatch.setattr(agent, "_generate_search_queries", _unexpected_queries)-- result = await agent._pre_retrieve("What is convolution?", "algebra")-- assert result == "(no knowledge base available)"diff --git a/tests/agents/solve/utils/__init__.py b/tests/agents/solve/utils/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/tests/agents/solve/utils/test_json_utils.py b/tests/agents/solve/utils/test_json_utils.pydeleted file mode 100644index 5b7629a58..000000000--- a/tests/agents/solve/utils/test_json_utils.py+++ /dev/null@@ -1,37 +0,0 @@-from deeptutor.agents.solve.utils.json_utils import extract_json_from_text---def test_extract_json_with_triple_quoted_python_code():- raw = '''- {- "tool_calls": [- {- "type": "code_execution",- "query": """-def foo():- print("hello")-"""- }- ]- }- '''-- parsed = extract_json_from_text(raw)-- assert parsed is not None- assert isinstance(parsed, dict)- assert "tool_calls" in parsed- assert parsed["tool_calls"][0]["type"] == "code_execution"- assert "def foo" in parsed["tool_calls"][0]["query"]---# How to run the test-# From repo root:-# pytest---# Or just this test:-# pytest tests/agents/solve/utils/test_json_utils.py--# Expected output-# 1 passeddiff --git a/tests/api/test_solve_router.py b/tests/api/test_solve_router.pydeleted file mode 100644index 688231eab..000000000--- a/tests/api/test_solve_router.py+++ /dev/null@@ -1,106 +0,0 @@-from __future__ import annotations--import importlib-from pathlib import Path-from types import SimpleNamespace--import pytest--pytest.importorskip("fastapi")--FastAPI = pytest.importorskip("fastapi").FastAPI-TestClient = pytest.importorskip("fastapi.testclient").TestClient-router = importlib.import_module("deeptutor.api.routers.solve").router-DeepSolveCapability = importlib.import_module(- "deeptutor.capabilities.deep_solve"-).DeepSolveCapability---def _build_app() -> FastAPI:- app = FastAPI()- app.include_router(router, prefix="/api/v1")- return app---def test_solve_router_uses_explicit_default_tools(monkeypatch, tmp_path) -> None:- captured: dict[str, object] = {}-- class FakeMainSolver:- def __init__(self, **kwargs) -> None:- captured["init"] = kwargs- self.display_manager = None- self.token_tracker = None-- async def ainit(self) -> None:- captured["ainit"] = True-- async def solve(self, *_args, **_kwargs):- return {"final_answer": "done", "output_dir": str(tmp_path / "solve"), "metadata": {}}-- monkeypatch.setattr("deeptutor.api.routers.solve.MainSolver", FakeMainSolver)- monkeypatch.setattr(- "deeptutor.api.routers.solve.get_llm_config",- lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),- )- monkeypatch.setattr(- "deeptutor.api.routers.solve.get_path_service",- lambda: SimpleNamespace(get_solve_dir=lambda: Path(tmp_path)),- )- monkeypatch.setattr("deeptutor.api.routers.solve.get_ui_language", lambda default="en": default)-- app = _build_app()-- with TestClient(app) as client:- with client.websocket_connect("/api/v1/solve") as websocket:- websocket.send_json({"question": "Solve x^2=4"})- messages = [websocket.receive_json() for _ in range(4)]-- assert [message["type"] for message in messages] == ["session", "task_id", "status", "result"]- assert captured["init"]["enabled_tools"] == list(DeepSolveCapability.manifest.tools_used)- assert captured["init"]["kb_name"] == "ai-textbook"- assert captured["init"]["disable_planner_retrieve"] is False---def test_solve_router_respects_disabled_tools(monkeypatch, tmp_path) -> None:- captured: dict[str, object] = {}-- class FakeMainSolver:- def __init__(self, **kwargs) -> None:- captured["init"] = kwargs- self.display_manager = None- self.token_tracker = None-- async def ainit(self) -> None:- captured["ainit"] = True-- async def solve(self, *_args, **_kwargs):- return {"final_answer": "done", "output_dir": str(tmp_path / "solve"), "metadata": {}}-- monkeypatch.setattr("deeptutor.api.routers.solve.MainSolver", FakeMainSolver)- monkeypatch.setattr(- "deeptutor.api.routers.solve.get_llm_config",- lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),- )- monkeypatch.setattr(- "deeptutor.api.routers.solve.get_path_service",- lambda: SimpleNamespace(get_solve_dir=lambda: Path(tmp_path)),- )- monkeypatch.setattr("deeptutor.api.routers.solve.get_ui_language", lambda default="en": default)-- app = _build_app()-- with TestClient(app) as client:- with client.websocket_connect("/api/v1/solve") as websocket:- websocket.send_json(- {- "question": "Solve x^2=4",- "tools": [],- "kb_name": "algebra",- }- )- messages = [websocket.receive_json() for _ in range(4)]-- assert [message["type"] for message in messages] == ["session", "task_id", "status", "result"]- assert captured["init"]["enabled_tools"] == []- assert captured["init"]["kb_name"] is None- assert captured["init"]["disable_planner_retrieve"] is Truediff --git a/tests/core/test_agentic_labels.py b/tests/core/test_agentic_labels.pynew file mode 100644index 000000000..d9b116457--- /dev/null+++ b/tests/core/test_agentic_labels.py@@ -0,0 +1,62 @@+from deeptutor.core.agentic.labels import classify_label, find_inline_labels+++_ALLOWED = ("FINISH", "TOOL", "THINK", "PAUSE")+++def test_classify_label_accepts_common_wrapper_variants() -> None:+ assert classify_label("`FINISH`\nDone", allowed_labels=_ALLOWED) == (+ "FINISH",+ "Done",+ )+ assert classify_label("```FINISH```\nDone", allowed_labels=_ALLOWED) == (+ "FINISH",+ "Done",+ )+ assert classify_label("FINISH:Done", allowed_labels=_ALLOWED) == (+ "FINISH",+ "Done",+ )+++def test_classify_label_accepts_body_adjacent_to_wrapped_label() -> None:+ assert classify_label("``FINISH``你好!", allowed_labels=_ALLOWED) == (+ "FINISH",+ "你好!",+ )+ assert classify_label("``THINK``I need one private step.", allowed_labels=_ALLOWED) == (+ "THINK",+ "I need one private step.",+ )+++def test_classify_label_waits_for_unambiguous_bare_label_until_final() -> None:+ assert classify_label("FINISH", allowed_labels=_ALLOWED) is None+ assert classify_label("FINISH", allowed_labels=_ALLOWED, final=True) == (+ "FINISH",+ "",+ )+ assert classify_label("FINISHED", allowed_labels=_ALLOWED, final=True) is None+++def test_classify_label_does_not_accept_split_wrapped_label_too_early() -> None:+ assert classify_label("``FINISH`", allowed_labels=_ALLOWED) is None+ assert classify_label("``FINISH```", allowed_labels=_ALLOWED) is None+ assert classify_label("``FINISH``\nDone", allowed_labels=_ALLOWED) == (+ "FINISH",+ "Done",+ )+++def test_find_inline_labels_detects_tolerated_label_variants() -> None:+ assert find_inline_labels(+ "draft\n`THINK`\nmore\n```TOOL```\nFINISH:again",+ allowed_labels=_ALLOWED,+ ) == ["THINK", "TOOL", "FINISH"]+++def test_find_inline_labels_ignores_prose_mentions() -> None:+ assert find_inline_labels(+ "I should use ``TOOL`` next, then finish with ``FINISH``.",+ allowed_labels=_ALLOWED,+ ) == []diff --git a/tests/core/test_agentic_loop_intermediate.py b/tests/core/test_agentic_loop_intermediate.pynew file mode 100644index 000000000..f8f034be8--- /dev/null+++ b/tests/core/test_agentic_loop_intermediate.py@@ -0,0 +1,498 @@+"""Tests for the optional ``LoopHost.on_intermediate`` hook.++The hook fires after the loop appends an intermediate-label assistant+message; if the host returns a non-empty string it gets injected as+the next iteration's user message. Used by research's ``APPEND`` label+to feed structured "queue mutated" feedback back to the LLM. Existing+hosts (chat, solve) do not implement the hook and must continue to+work unchanged.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from deeptutor.core.agentic.loop import LabelProtocol, run_agentic_loop+from deeptutor.core.agentic.tool_dispatch import DispatchOutcome+from deeptutor.core.stream_bus import StreamBus+++# --------------------------- scripted LLM client ---------------------------+++def _llm_chunk(content: str) -> SimpleNamespace:+ return SimpleNamespace(+ choices=[+ SimpleNamespace(+ delta=SimpleNamespace(content=content, tool_calls=None)+ )+ ]+ )+++async def _async_stream(chunks: list[SimpleNamespace]):+ for chunk in chunks:+ yield chunk+++class _ScriptedClient:+ """Minimal LLM client returning pre-scripted streamed chunks."""++ def __init__(self, scripts: list[list[SimpleNamespace]]) -> None:+ self._scripts = list(scripts)+ self.calls: list[list[dict[str, Any]]] = []++ class _Completions:+ def __init__(self, parent: _ScriptedClient) -> None:+ self.parent = parent++ async def create(self, **kwargs: Any):+ self.parent.calls.append(list(kwargs.get("messages") or []))+ if not self.parent._scripts:+ raise RuntimeError("scripted client exhausted")+ return _async_stream(self.parent._scripts.pop(0))++ class _Chat:+ def __init__(self, parent: _ScriptedClient) -> None:+ self.completions = _Completions(parent)++ self.chat = _Chat(self)+++# ---------------------------- host implementations ---------------------------+++class _BaseHost:+ """LoopHost stub with the minimal required surface, no ``on_intermediate``."""++ def __init__(self) -> None:+ self.final_text: str | None = None++ async def guard_context_window(self, messages: list[dict[str, Any]]) -> None:+ return None++ def build_iteration_trace_meta(+ self, iteration: int+ ) -> tuple[dict[str, Any], dict[str, Any]]:+ return ({"iter": iteration}, {"iter": iteration, "final": True})++ async def dispatch_tools(self, *, iteration, tool_calls): # pragma: no cover+ return DispatchOutcome(sources=[], tool_messages=[])++ async def resolve_pause(self, dispatch): # pragma: no cover+ return False++ async def emit_terminator(self, payload): # pragma: no cover+ return None++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ self.final_text = text++ def assistant_message_with_tool_calls(self, *, content, tool_calls):+ return {"role": "assistant", "content": content, "tool_calls": tool_calls}++ def protocol_retry_notice(self) -> str:+ return "retry"++ def protocol_repair_message(self, violation: str) -> str:+ return f"repair:{violation}"++ async def force_finalize(self, *, messages, start_iteration):+ return ("", False, 0)+++class _AppendHost(_BaseHost):+ """Host that mutates state on a synthetic ``APPEND`` intermediate label+ and returns a confirmation note the loop will inject as user feedback."""++ def __init__(self) -> None:+ super().__init__()+ self.appended: list[str] = []++ async def on_intermediate(self, label: str, text: str) -> str | None:+ if label != "APPEND":+ return None+ title = (text or "").strip().split("\n", 1)[0].strip()+ if not title:+ return None+ self.appended.append(title)+ return f"Appended block #{len(self.appended)}: {title}"+++# ------------------------------- tests -------------------------------+++_PROTOCOL = LabelProtocol(+ allowed=("THINK", "APPEND", "FINISH"),+ terminal=frozenset({"FINISH"}),+ intermediate=frozenset({"THINK", "APPEND"}),+ final=frozenset({"FINISH"}),+ tool_label=None,+)+++def _script_for_two_iterations(+ first_label: str,+ first_body: str,+ final_body: str = "done",+) -> list[list[SimpleNamespace]]:+ return [+ [_llm_chunk(f"``{first_label}``\n{first_body}")],+ [_llm_chunk(f"``FINISH``\n{final_body}")],+ ]+++async def test_loop_without_on_intermediate_hook_preserves_legacy_behavior() -> None:+ """A host that does NOT implement ``on_intermediate`` (e.g. chat,+ solve) must still drive the loop end-to-end. The intermediate+ label's text becomes an assistant message; no user feedback is+ injected."""+ client = _ScriptedClient(_script_for_two_iterations("THINK", "reasoning step"))+ host = _BaseHost()+ bus = StreamBus()++ async def _consume() -> None:+ async for _ in bus.subscribe():+ pass++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ try:+ outcome = await run_agentic_loop(+ initial_messages=[{"role": "user", "content": "hi"}],+ protocol=_PROTOCOL,+ client=client,+ model="x",+ completion_kwargs={},+ binding="openai",+ tool_schemas=None,+ stream=bus,+ source="test",+ stage="test",+ max_iterations=4,+ host=host,+ )+ finally:+ await bus.close()+ await consumer++ assert outcome.completed is True+ assert outcome.final_text.strip() == "done"+ # Iteration 2 saw the THINK text as assistant context; no user feedback.+ iter2_msgs = client.calls[1]+ assistant_msgs = [m for m in iter2_msgs if m.get("role") == "assistant"]+ user_msgs = [m for m in iter2_msgs if m.get("role") == "user"]+ assert any("reasoning step" in (m.get("content") or "") for m in assistant_msgs)+ # Only the original user prompt — no feedback injected.+ assert len(user_msgs) == 1+ assert user_msgs[0]["content"] == "hi"+++async def test_loop_calls_on_intermediate_and_injects_feedback() -> None:+ """A host implementing ``on_intermediate`` for ``APPEND`` should+ (a) be called with the label + text, and+ (b) have its non-empty return value injected as a user message+ visible to the next LLM iteration."""+ client = _ScriptedClient(+ _script_for_two_iterations("APPEND", "Quantum entanglement basics")+ )+ host = _AppendHost()+ bus = StreamBus()++ async def _consume() -> None:+ async for _ in bus.subscribe():+ pass++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ try:+ outcome = await run_agentic_loop(+ initial_messages=[{"role": "user", "content": "go"}],+ protocol=_PROTOCOL,+ client=client,+ model="x",+ completion_kwargs={},+ binding="openai",+ tool_schemas=None,+ stream=bus,+ source="test",+ stage="test",+ max_iterations=4,+ host=host,+ )+ finally:+ await bus.close()+ await consumer++ assert outcome.completed is True+ assert host.appended == ["Quantum entanglement basics"]++ # Iteration 2's messages must include both the assistant APPEND+ # prose AND a user feedback note carrying the host's confirmation.+ iter2_msgs = client.calls[1]+ assistant_texts = [+ m.get("content") or "" for m in iter2_msgs if m.get("role") == "assistant"+ ]+ user_texts = [m.get("content") or "" for m in iter2_msgs if m.get("role") == "user"]+ assert any("Quantum entanglement basics" in t for t in assistant_texts)+ assert any(+ "Appended block #1: Quantum entanglement basics" in t for t in user_texts+ )+++async def test_loop_validate_terminal_can_repair_premature_finish() -> None:+ """A host can reject a terminal label when stateful requirements have+ not been met, causing the loop to inject a normal protocol repair and+ continue instead of accepting the FINISH."""++ class _TerminalGuardHost(_BaseHost):+ def __init__(self) -> None:+ super().__init__()+ self.rejections = 0++ async def validate_terminal(self, label: str, text: str) -> str | None:+ if self.rejections == 0:+ self.rejections += 1+ return "finish_without_tool"+ return None++ client = _ScriptedClient(+ [+ [_llm_chunk("``FINISH``\nPremature synthesis")],+ [_llm_chunk("``FINISH``\nEvidence-backed synthesis")],+ ]+ )+ host = _TerminalGuardHost()+ bus = StreamBus()++ async def _consume() -> None:+ async for _ in bus.subscribe():+ pass++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ try:+ outcome = await run_agentic_loop(+ initial_messages=[{"role": "user", "content": "go"}],+ protocol=_PROTOCOL,+ client=client,+ model="x",+ completion_kwargs={},+ binding="openai",+ tool_schemas=None,+ stream=bus,+ source="test",+ stage="test",+ max_iterations=4,+ host=host,+ )+ finally:+ await bus.close()+ await consumer++ assert outcome.completed is True+ assert outcome.final_text.strip() == "Evidence-backed synthesis"+ assert host.rejections == 1+ iter2_user_texts = [+ m.get("content") or "" for m in client.calls[1] if m.get("role") == "user"+ ]+ assert any("repair:finish_without_tool" in t for t in iter2_user_texts)+++async def test_intermediate_label_in_final_set_streams_body_and_continues() -> None:+ """A label that is BOTH intermediate AND final (e.g. chat's PAUSE)+ must:+ 1. emit its post-label text to the user-facing body via+ ``emit_final`` so the chat bubble streams it,+ 2. NOT exit the loop — the next iteration runs and can FINISH.+ """++ class _RecordingHost(_BaseHost):+ def __init__(self) -> None:+ super().__init__()+ self.emit_final_calls: list[str] = []++ async def emit_final(self, text: str, final_meta: dict[str, Any]) -> None:+ self.emit_final_calls.append(text)+ self.final_text = text++ protocol = LabelProtocol(+ allowed=("THINK", "PAUSE", "FINISH"),+ terminal=frozenset({"FINISH"}),+ intermediate=frozenset({"THINK", "PAUSE"}),+ # ``PAUSE`` is intermediate AND final — body-streaming + loop continues.+ final=frozenset({"FINISH", "PAUSE"}),+ tool_label=None,+ )+ client = _ScriptedClient(+ [+ [_llm_chunk("``PAUSE``\nlet me check first")],+ [_llm_chunk("``FINISH``\nhere is the answer")],+ ]+ )+ host = _RecordingHost()+ bus = StreamBus()++ async def _consume() -> None:+ async for _ in bus.subscribe():+ pass++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ try:+ outcome = await run_agentic_loop(+ initial_messages=[{"role": "user", "content": "hi"}],+ protocol=protocol,+ client=client,+ model="x",+ completion_kwargs={},+ binding="openai",+ tool_schemas=None,+ stream=bus,+ source="test",+ stage="test",+ max_iterations=4,+ host=host,+ )+ finally:+ await bus.close()+ await consumer++ # Loop completed via FINISH, not via PAUSE.+ assert outcome.completed is True+ assert outcome.final_label == "FINISH"+ assert outcome.final_text.strip() == "here is the answer"+ # emit_final was called twice: once for PAUSE (mid-loop), once for FINISH.+ assert len(host.emit_final_calls) == 2+ assert host.emit_final_calls[0].strip() == "let me check first"+ assert host.emit_final_calls[1].strip() == "here is the answer"+ # The PAUSE prose is also kept as assistant context for iteration 2.+ iter2_msgs = client.calls[1]+ assistant_texts = [+ m.get("content") or "" for m in iter2_msgs if m.get("role") == "assistant"+ ]+ assert any("let me check first" in t for t in assistant_texts)+++async def test_before_iteration_hook_runs_each_iteration() -> None:+ """``LoopHost.before_iteration`` (optional) fires once per iteration+ after ``guard_context_window`` and before the LLM call. The host can+ use it to inject per-iteration context — e.g. a "you are at N/M"+ marker so the LLM can pace itself."""++ class _MarkerHost(_BaseHost):+ def __init__(self) -> None:+ super().__init__()+ self.fired: list[tuple[int, int]] = []++ async def before_iteration(+ self,+ *,+ messages: list[dict[str, Any]],+ iteration: int,+ max_iterations: int,+ ) -> None:+ self.fired.append((iteration, max_iterations))+ messages.append(+ {"role": "user", "content": f"[marker] {iteration + 1}/{max_iterations}"}+ )++ client = _ScriptedClient(+ [+ [_llm_chunk("``THINK``\nfirst pass")],+ [_llm_chunk("``FINISH``\ndone")],+ ]+ )+ host = _MarkerHost()+ bus = StreamBus()++ async def _consume() -> None:+ async for _ in bus.subscribe():+ pass++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ try:+ outcome = await run_agentic_loop(+ initial_messages=[{"role": "user", "content": "hi"}],+ protocol=_PROTOCOL,+ client=client,+ model="x",+ completion_kwargs={},+ binding="openai",+ tool_schemas=None,+ stream=bus,+ source="test",+ stage="test",+ max_iterations=5,+ host=host,+ )+ finally:+ await bus.close()+ await consumer++ assert outcome.completed is True+ # Fired twice — once per iteration, with the right counters.+ assert host.fired == [(0, 5), (1, 5)]+ # Both LLM calls saw a marker in their messages tail.+ iter1_markers = [+ m for m in client.calls[0] if "[marker]" in (m.get("content") or "")+ ]+ iter2_markers = [+ m for m in client.calls[1] if "[marker]" in (m.get("content") or "")+ ]+ assert any("1/5" in m.get("content", "") for m in iter1_markers)+ assert any("2/5" in m.get("content", "") for m in iter2_markers)+++async def test_loop_on_intermediate_returning_none_injects_nothing() -> None:+ """If ``on_intermediate`` returns ``None`` (or empty), the loop must+ not inject any user message — same as the no-hook behavior."""++ class _SilentHost(_BaseHost):+ async def on_intermediate(self, label: str, text: str) -> str | None:+ return None # never inject++ client = _ScriptedClient(_script_for_two_iterations("THINK", "x"))+ host = _SilentHost()+ bus = StreamBus()++ async def _consume() -> None:+ async for _ in bus.subscribe():+ pass++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ try:+ await run_agentic_loop(+ initial_messages=[{"role": "user", "content": "hi"}],+ protocol=_PROTOCOL,+ client=client,+ model="x",+ completion_kwargs={},+ binding="openai",+ tool_schemas=None,+ stream=bus,+ source="test",+ stage="test",+ max_iterations=4,+ host=host,+ )+ finally:+ await bus.close()+ await consumer++ iter2_msgs = client.calls[1]+ user_msgs = [m for m in iter2_msgs if m.get("role") == "user"]+ assert len(user_msgs) == 1+ assert user_msgs[0]["content"] == "hi"diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.pyindex 6e6709505..fa400ccdb 100644--- a/tests/core/test_capabilities_runtime.py+++ b/tests/core/test_capabilities_runtime.py@@ -117,51 +117,44 @@ async def test_chat_capability_streams_content_and_geogebra_context(@pytest.mark.asyncio@pytest.mark.parametrize(- ("enabled_tools", "knowledge_bases", "expected_tools", "expected_kb", "expected_disable"),+ ("enabled_tools", "knowledge_bases", "expected_kb"),[- # Non-rag tools + attached KB → rag auto-appended.- (["code_execution"], ["algebra"], ["code_execution", "rag"], "algebra", False),- # Default tool set (manifest) is normalised, then rag is appended last.- (None, ["algebra"], ["web_search", "code_execution", "reason", "rag"], "algebra", False),- # Legacy callers that still pass "rag" without attaching a KB get rag stripped.- (["rag", "web_search"], [], ["web_search"], None, True),+ # Non-rag tools + attached KB → kb_name forwarded; pipeline mounts rag.+ (["code_execution"], ["algebra"], "algebra"),+ # Default tool set (manifest) flows through; rag absent from the+ # forwarded toggle list because the pipeline owns mounting.+ (None, ["algebra"], "algebra"),+ # Legacy callers that still pass "rag" without attaching a KB get+ # rag stripped at the capability boundary, and kb_name stays None.+ (["rag", "web_search"], [], None),],)-async def test_deep_solve_capability_bridges_solver_output(+async def test_deep_solve_capability_forwards_to_pipeline(monkeypatch: pytest.MonkeyPatch,enabled_tools: list[str] | None,knowledge_bases: list[str],- expected_tools: list[str],expected_kb: str | None,- expected_disable: bool,) -> None:+ """The deep_solve capability is a thin shim over ``SolvePipeline``:+ it strips ``rag`` from the enabled-tools list (the pipeline mounts rag+ itself based on ``kb_name``) and forwards everything else."""captured: dict[str, Any] = {}- class FakeMainSolver:+ class FakePipeline:def __init__(self, **kwargs: Any) -> None:- captured["solver_init"] = kwargs- self.logger = SimpleNamespace(- logger=SimpleNamespace(addHandler=lambda *_: None, removeHandler=lambda *_: None)- )-- async def ainit(self) -> None:- captured["ainit"] = True+ captured["pipeline_init"] = kwargs- async def solve(self, **kwargs: Any) -> dict[str, Any]:- self._send_progress_update("reasoning", {"status": "solver-progress"})- captured["solve"] = kwargs- return {- "final_answer": "final solution",- "output_dir": "/tmp/solve",+ async def run(self, *, stream: StreamBus, **kwargs: Any) -> dict[str, Any]:+ captured["pipeline_run"] = kwargs+ await stream.content("final solution", source="deep_solve", stage="writing")+ payload = {+ "response": "final solution","metadata": {"steps": 2},}+ await stream.result(payload, source="deep_solve")+ return payload- _install_module(monkeypatch, "deeptutor.agents.solve.main_solver", MainSolver=FakeMainSolver)- _install_module(- monkeypatch,- "deeptutor.services.llm.config",- get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),- )+ monkeypatch.setattr("deeptutor.capabilities.deep_solve.SolvePipeline", FakePipeline)context = UnifiedContext(user_message="solve x^2=4",@@ -173,14 +166,11 @@ async def test_deep_solve_capability_bridges_solver_output(capability = DeepSolveCapability()events = await _collect_events(lambda bus: capability.run(context, bus))- assert captured["solver_init"]["enabled_tools"] == expected_tools- assert captured["solver_init"]["kb_name"] == expected_kb- assert captured["solver_init"]["disable_planner_retrieve"] is expected_disable- assert captured["solve"]["attachments"][0].filename == "graph.png"- assert any(- event.type == StreamEventType.PROGRESS and event.content == "solver-progress"- for event in events- )+ init = captured["pipeline_init"]+ assert init["kb_name"] == expected_kb+ assert "rag" not in init["enabled_tools"]+ # Attachments flow through unmodified.+ assert captured["pipeline_run"]["attachments"][0].filename == "graph.png"assert any(event.type == StreamEventType.CONTENT and "final solution" in event.contentfor event in events@@ -189,205 +179,12 @@ async def test_deep_solve_capability_bridges_solver_output(assert result_event.metadata["response"] == "final solution"-async def test_deep_solve_capability_bridges_observation_and_retrieve_events(- monkeypatch: pytest.MonkeyPatch,-) -> None:- class FakeMainSolver:- def __init__(self, **_kwargs: Any) -> None:- self._trace_callback = None- self.logger = SimpleNamespace(- logger=SimpleNamespace(addHandler=lambda *_: None, removeHandler=lambda *_: None)- )-- async def ainit(self) -> None:- return None-- def set_trace_callback(self, callback) -> None:- self._trace_callback = callback-- async def solve(self, **_kwargs: Any) -> dict[str, Any]:- assert self._trace_callback is not None- await self._trace_callback(- {- "event": "llm_observation",- "phase": "reasoning",- "response": "round summary",- "call_id": "solve-s1-round-1",- "trace_role": "observe",- "trace_group": "react_round",- }- )- await self._trace_callback(- {- "event": "tool_log",- "phase": "reasoning",- "message": "Retrieving from KB...",- "call_id": "solve-retrieve-1",- "call_kind": "rag_retrieval",- "trace_role": "retrieve",- "trace_group": "retrieve",- "trace_kind": "status",- }- )- return {- "final_answer": "final solution",- "output_dir": "/tmp/solve",- "metadata": {"steps": 1},- }-- _install_module(monkeypatch, "deeptutor.agents.solve.main_solver", MainSolver=FakeMainSolver)- _install_module(- monkeypatch,- "deeptutor.services.llm.config",- get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),- )-- context = UnifiedContext(- user_message="solve x^2=4",- enabled_tools=["rag"],- knowledge_bases=["algebra"],- language="en",- )- capability = DeepSolveCapability()- events = await _collect_events(lambda bus: capability.run(context, bus))-- observation_event = next(event for event in events if event.type == StreamEventType.OBSERVATION)- assert observation_event.content == "round summary"- assert observation_event.metadata["trace_role"] == "observe"-- retrieve_event = next(- event- for event in events- if event.type == StreamEventType.PROGRESS and event.metadata.get("trace_role") == "retrieve"- )- assert retrieve_event.content == "Retrieving from KB..."- assert retrieve_event.metadata["trace_group"] == "retrieve"---async def test_deep_question_capability_uses_user_message_as_topic(- monkeypatch: pytest.MonkeyPatch,-) -> None:- captured: dict[str, Any] = {}-- class FakeCoordinator:- def __init__(self, **kwargs: Any) -> None:- captured["init"] = kwargs- self._callback = None-- def set_ws_callback(self, callback) -> None:- self._callback = callback-- async def generate_from_topic(self, **kwargs: Any) -> dict[str, Any]:- captured["topic_call"] = kwargs- await self._callback({"type": "idea_round", "message": "ideas"})- await self._callback({"type": "generating", "message": "writing"})- return {- "results": [- {- "qa_pair": {- "question": "What is a matrix?",- "options": {"A": "A table", "B": "A scalar"},- "correct_answer": "A",- "explanation": "A matrix is a table.",- }- }- ]- }-- _install_module(- monkeypatch,- "deeptutor.agents.question.coordinator",- AgentCoordinator=FakeCoordinator,- )- _install_module(- monkeypatch,- "deeptutor.services.llm.config",- get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),- )-- context = UnifiedContext(- user_message="linear algebra fundamentals",- config_overrides={},- language="en",- attachments=[Attachment(type="image", base64="ZmFrZQ==", filename="topic.png")],- )- capability = DeepQuestionCapability()- events = await _collect_events(lambda bus: capability.run(context, bus))-- assert captured["topic_call"]["user_topic"] == "linear algebra fundamentals"- assert captured["topic_call"]["attachments"][0].filename == "topic.png"- assert any(- event.type == StreamEventType.PROGRESS and event.stage == "ideation" for event in events- )- result_event = next(event for event in events if event.type == StreamEventType.RESULT)- assert "Question 1" in result_event.metadata["response"]---async def test_deep_question_mimic_uses_extracted_attachment_text_when_pdf_was_stripped(- monkeypatch: pytest.MonkeyPatch,-) -> None:- captured: dict[str, Any] = {}-- class FakeCoordinator:- def __init__(self, **_kwargs: Any) -> None:- self._callback = None-- def set_ws_callback(self, callback) -> None:- self._callback = callback-- async def generate_from_exam(self, **_kwargs: Any) -> dict[str, Any]:- raise AssertionError("raw PDF path should not be required after document extraction")-- async def generate_from_topic(self, **kwargs: Any) -> dict[str, Any]:- captured["topic_call"] = kwargs- return {- "results": [- {- "qa_pair": {- "question": "Question from attached paper?",- "correct_answer": "Yes",- "explanation": "The extracted document text was used.",- }- }- ]- }-- _install_module(- monkeypatch,- "deeptutor.agents.question.coordinator",- AgentCoordinator=FakeCoordinator,- )- _install_module(- monkeypatch,- "deeptutor.services.llm.config",- get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),- )-- context = UnifiedContext(- user_message="[Attached Documents]\n[File: paper.pdf]\nExam text\n\n[User Question]\n",- config_overrides={"mode": "mimic", "max_questions": 4},- language="en",- attachments=[- Attachment(- type="pdf",- filename="paper.pdf",- base64="",- mime_type="application/pdf",- )- ],- )-- capability = DeepQuestionCapability()- events = await _collect_events(lambda bus: capability.run(context, bus))-- assert "Exam text" in captured["topic_call"]["user_topic"]- assert captured["topic_call"]["num_questions"] == 4- assert captured["topic_call"]["attachments"][0].filename == "paper.pdf"- result_event = next(event for event in events if event.type == StreamEventType.RESULT)- assert "Question 1" in result_event.metadata["response"]+# Legacy tests for the AgentCoordinator-based custom + mimic paths were+# removed when those code paths were deleted in the Phase A → C quiz+# refactor. New-pipeline coverage lives in+# ``tests/agents/question/test_pipeline.py`` (plan parsing, payload+# normalization, templates_override / mimic flow, structured emission,+# tool wiring, history loader, etc.).@pytest.mark.asyncio@@ -481,34 +278,18 @@ async def test_deep_question_capability_uses_single_call_followup_agent(assert result_event.metadata["question_id"] == "q_3"-def test_deep_question_capability_humanizes_question_progress_labels() -> None:- assert DeepQuestionCapability._humanize_question_id("q_3") == "Question 3"- assert (- DeepQuestionCapability._format_bridge_message(- "question_update",- {"question_id": "q_3", "current": 3, "total": 3},- )- == "Generating Question 3 (3/3)"- )- assert (- DeepQuestionCapability._format_bridge_message(- "result",- {- "question_id": "q_3",- "index": 2,- "question": {"question_type": "coding", "difficulty": "hard"},- "success": True,- },- )- == "Question 3 done (#3, coding/hard, success=True)"- )--@pytest.mark.asyncio-async def test_deep_research_capability_requires_explicit_config_and_streams_trace(+async def test_deep_research_capability_delegates_to_pipeline(monkeypatch: pytest.MonkeyPatch,) -> None:+ """The capability shim validates the request config, normalises+ KB-without-KB, builds a runtime config, and hands the heavy lifting+ to :class:`ResearchPipeline`. We mock the pipeline at its import site+ in the capability module so we can assert what it was called with+ without spinning up real LLM I/O.+ """import deeptutor.agents.research.request_config # noqa: F401+ import deeptutor.capabilities.deep_research as deep_research_modcaptured: dict[str, Any] = {}@@ -516,63 +297,29 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_tradef __init__(self, **kwargs: Any) -> None:captured["pipeline_init"] = kwargs- async def run(self, topic: str) -> dict[str, Any]:- # progress_callback is fire-and-forget (sync) inside the- # capability; just call it.- captured["pipeline_init"]["progress_callback"](- {"status": "gathering evidence", "stage": "researching", "block_id": "block_1"}- )- await captured["pipeline_init"]["trace_callback"](- {- "event": "llm_call",- "state": "running",- "agent_name": "rephrase_agent",- "stage": "rephrase",- }- )- await captured["pipeline_init"]["trace_callback"](- {- "event": "tool_call",- "phase": "researching",- "tool_name": "web_search",- "tool_args": {"query": "agent-native tutoring"},- "label": "Use web_search",- "call_id": "research-tool-1",- }- )- # Allow the scheduled progress task to flush onto the bus.- await asyncio.sleep(0)- return {"report": f"Report about {topic}", "metadata": {"citations": 3}}+ async def run(self, **kwargs: Any) -> dict[str, Any]:+ captured["pipeline_run"] = kwargs+ return {+ "response": f"Report about {kwargs['topic']}",+ "metadata": {"mode": "agentic_research", "block_count": 2},+ }def fake_load_config_with_main(_: str) -> dict[str, Any]:return {- "research": {- "researching": {- "note_agent_mode": "auto",- "tool_timeout": 60,- "tool_max_retries": 2,- "paper_search_years_limit": 3,- },- "rag": {"default_mode": "hybrid"},+ "capabilities": {+ "research": {+ "researching": {+ "note_agent_mode": "auto",+ "tool_timeout": 60,+ "tool_max_retries": 2,+ "paper_search_years_limit": 3,+ },+ }},- "tools": {"web_search": {"enabled": True}},}- _install_module(- monkeypatch,- "deeptutor.agents.research.research_pipeline",- ResearchPipeline=FakeResearchPipeline,- )- _install_module(- monkeypatch,- "deeptutor.services.config",- load_config_with_main=fake_load_config_with_main,- )- _install_module(- monkeypatch,- "deeptutor.services.llm.config",- get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),- )+ monkeypatch.setattr(deep_research_mod, "ResearchPipeline", FakeResearchPipeline)+ monkeypatch.setattr(deep_research_mod, "load_config_with_main", fake_load_config_with_main)context = UnifiedContext(user_message="agent-native tutoring",@@ -582,9 +329,9 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_traconfig_overrides={"mode": "report","depth": "standard",- "sources": ["kb", "web", "papers"],# Provide a confirmed outline so the capability skips the- # outline-preview short-circuit and runs the full pipeline.+ # outline-preview short-circuit and drives the full+ # research + reporting flow on the pipeline."confirmed_outline": [{"title": "Background", "overview": "Why this topic matters"},{"title": "Approaches", "overview": "How to do it"},@@ -593,31 +340,39 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_tralanguage="en",)capability = DeepResearchCapability()- events = await _collect_events(lambda bus: capability.run(context, bus))-- config = captured["pipeline_init"]["config"]- assert captured["pipeline_init"]["attachments"][0].filename == "brief.png"- assert config["planning"]["decompose"]["mode"] == "auto"- assert config["planning"]["decompose"]["auto_max_subtopics"] == 4- assert config["researching"]["max_iterations"] == 3- assert config["researching"]["enable_paper_search"] is True- assert config["researching"]["enable_web_search"] is True- assert config["reporting"]["style"] == "report"- assert config["tools"]["web_search"]["enabled"] is True- progress_event = next(- event- for event in events- if event.type == StreamEventType.PROGRESS and event.content == "gathering evidence"- )- assert progress_event.metadata["research_stage_card"] == "evidence"- tool_call_event = next(- event- for event in events- if event.type == StreamEventType.TOOL_CALL and event.content == "web_search"- )- assert tool_call_event.metadata["research_stage_card"] == "evidence"- result_event = next(event for event in events if event.type == StreamEventType.RESULT)- assert result_event.metadata["response"] == "Report about agent-native tutoring"+ await _collect_events(lambda bus: capability.run(context, bus))++ init_kwargs = captured["pipeline_init"]+ runtime_cfg = init_kwargs["runtime_config"]+ assert init_kwargs["kb_name"] == "research-kb"+ assert init_kwargs["language"] == "en"+ # ``enabled_tools`` is the user's composer toggles forwarded+ # unchanged. The pipeline's per-block ``compose_enabled_tools`` call+ # is what decides what the block loop actually exposes.+ assert init_kwargs["enabled_tools"] == ["rag", "web_search", "paper_search"]+ # Runtime config carries the structured policy sub-dicts the+ # pipeline reads at init time. We only assert the keys the runtime+ # config builder is contractually responsible for producing.+ assert "planning" in runtime_cfg+ assert "researching" in runtime_cfg+ assert "reporting" in runtime_cfg+ # Source-derived enable_* flags were removed; the block loop now+ # composes tools the same way chat does (user toggles + auto-mounts).+ assert "enable_rag" not in runtime_cfg["researching"]+ assert "enable_web_search" not in runtime_cfg["researching"]+ assert "enable_paper_search" not in runtime_cfg["researching"]+ assert "enable_run_code" not in runtime_cfg["researching"]++ run_kwargs = captured["pipeline_run"]+ assert run_kwargs["topic"] == "agent-native tutoring"+ assert run_kwargs["confirmed_outline"] is not None+ assert [item.title for item in run_kwargs["confirmed_outline"]] == [+ "Background",+ "Approaches",+ ]+ # Attachments are forwarded verbatim so the rephrase / decompose+ # prompts can see image evidence.+ assert run_kwargs["attachments"][0].filename == "brief.png"@pytest.mark.asynciodiff --git a/tests/core/test_labeled_step_finish_usage.py b/tests/core/test_labeled_step_finish_usage.pynew file mode 100644index 000000000..27ad5dfb5--- /dev/null+++ b/tests/core/test_labeled_step_finish_usage.py@@ -0,0 +1,174 @@+from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++import deeptutor.core.agentic.labeled_step as labeled_step_module+from deeptutor.core.agentic.labeled_step import run_labeled_step+from deeptutor.core.agentic.usage import UsageTracker+from deeptutor.core.stream_bus import StreamBus+++def _chunk(+ content: str | None = None,+ *,+ finish_reason: str | None = None,+ usage: Any = None,+) -> SimpleNamespace:+ return SimpleNamespace(+ choices=[+ SimpleNamespace(+ delta=SimpleNamespace(content=content, tool_calls=None),+ finish_reason=finish_reason,+ )+ ],+ usage=usage,+ )+++def _usage_chunk(*, prompt: int, completion: int, total: int) -> SimpleNamespace:+ return SimpleNamespace(+ choices=[],+ usage=SimpleNamespace(+ prompt_tokens=prompt,+ completion_tokens=completion,+ total_tokens=total,+ ),+ )+++class _Stream:+ def __init__(self, chunks: list[SimpleNamespace], *, stall_after_chunks: bool = False) -> None:+ self._chunks = list(chunks)+ self.stall_after_chunks = stall_after_chunks+ self.closed = False++ def __aiter__(self) -> "_Stream":+ return self++ async def __anext__(self) -> SimpleNamespace:+ if self._chunks:+ return self._chunks.pop(0)+ if self.stall_after_chunks:+ await asyncio.sleep(60)+ raise StopAsyncIteration++ async def close(self) -> None:+ self.closed = True+++class _Client:+ def __init__(+ self,+ streams: list[_Stream],+ *,+ fail_first_stream_options: bool = False,+ ) -> None:+ self._streams = list(streams)+ self.fail_first_stream_options = fail_first_stream_options+ self.calls: list[dict[str, Any]] = []++ class _Completions:+ def __init__(self, parent: _Client) -> None:+ self.parent = parent++ async def create(self, **kwargs: Any) -> _Stream:+ self.parent.calls.append(dict(kwargs))+ if (+ self.parent.fail_first_stream_options+ and len(self.parent.calls) == 1+ and "stream_options" in kwargs+ ):+ raise ValueError("unknown parameter: stream_options")+ if not self.parent._streams:+ raise RuntimeError("no scripted stream")+ return self.parent._streams.pop(0)++ class _Chat:+ def __init__(self, parent: _Client) -> None:+ self.completions = _Completions(parent)++ self.chat = _Chat(self)+++async def _run_step(client: _Client, usage: UsageTracker) -> Any:+ return await run_labeled_step(+ client=client,+ model="gpt-test",+ messages=[{"role": "user", "content": "hello"}],+ completion_kwargs={},+ tool_schemas=None,+ allowed_labels=("FINISH", "THINK", "TOOL"),+ final_labels=frozenset({"FINISH"}),+ tool_label="TOOL",+ stream=StreamBus(),+ source="test",+ stage="responding",+ iter_meta={"label": "Reasoning"},+ binding="openai",+ usage=usage,+ )+++async def test_finish_reason_closes_stalled_stream_and_estimates_usage(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(labeled_step_module, "_USAGE_TRAILER_GRACE_TIMEOUT_S", 0.01)+ stream = _Stream(+ [_chunk("``FINISH``\nDone.", finish_reason="stop")],+ stall_after_chunks=True,+ )+ usage = UsageTracker(model="gpt-test")+ client = _Client([stream])++ result = await _run_step(client, usage)++ assert result.label == "FINISH"+ assert result.text == "Done."+ assert stream.closed is True+ assert client.calls[0]["stream_options"] == {"include_usage": True}+ summary = usage.summary()+ assert summary is not None+ assert summary["total_calls"] == 1+ assert summary["total_tokens"] > 0+++async def test_finish_reason_consumes_usage_trailer_before_closing() -> None:+ stream = _Stream(+ [+ _chunk("``FINISH``\nDone.", finish_reason="stop"),+ _usage_chunk(prompt=10, completion=4, total=14),+ ]+ )+ usage = UsageTracker(model="gpt-test")+ client = _Client([stream])++ result = await _run_step(client, usage)++ assert result.label == "FINISH"+ summary = usage.summary()+ assert summary is not None+ assert summary["prompt_tokens"] == 10+ assert summary["completion_tokens"] == 4+ assert summary["total_tokens"] == 14+ assert summary["total_calls"] == 1+++async def test_stream_options_unsupported_retries_without_usage_request() -> None:+ stream = _Stream([_chunk("``FINISH``\nRetried.", finish_reason="stop")])+ usage = UsageTracker(model="gpt-test")+ client = _Client([stream], fail_first_stream_options=True)++ result = await _run_step(client, usage)++ assert result.label == "FINISH"+ assert result.text == "Retried."+ assert len(client.calls) == 2+ assert "stream_options" in client.calls[0]+ assert "stream_options" not in client.calls[1]diff --git a/tests/core/test_labeled_step_think_prelude.py b/tests/core/test_labeled_step_think_prelude.pynew file mode 100644index 000000000..275d4b703--- /dev/null+++ b/tests/core/test_labeled_step_think_prelude.py@@ -0,0 +1,561 @@+"""Tests for the pre-label ``<think>...</think>`` prelude handling in+:func:`deeptutor.core.agentic.labeled_step.run_labeled_step`.++Reasoning models (Qwen, Deepseek-R1 via certain proxies, …) sometimes+emit a literal ``<think>...</think>`` block *before* the protocol label.+The streaming parser must:++1. Route prelude content live into the reasoning sub-trace immediately+ (so the user sees activity during reasoning, not a frozen UI).+2. After ``</think>``, resume label probing on the remainder.+3. If the resolved label is intermediate (e.g. ``THINK``), the post-label+ text continues into the *same* reasoning sub-trace.+4. If the resolved label is final (e.g. ``FINISH``), the post-label text+ routes to the final-response area via ``final_meta``.+5. Strip the ``<think>...</think>`` markers + body from the returned+ ``text`` so the next iteration's assistant context isn't polluted.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from typing import Any++import pytest++from deeptutor.core.agentic.labeled_step import run_labeled_step+from deeptutor.core.stream import StreamEventType+from deeptutor.core.stream_bus import StreamBus+++def _chunk(content: str | None = None, tool_calls: Any = None) -> SimpleNamespace:+ return SimpleNamespace(+ choices=[+ SimpleNamespace(+ delta=SimpleNamespace(content=content, tool_calls=tool_calls)+ )+ ],+ usage=None,+ )+++def _reasoning_chunk(reasoning_text: str) -> SimpleNamespace:+ """A chunk that surfaces reasoning via the dedicated ``reasoning_content``+ field (e.g. DeepSeek-R1 in OpenAI-compatible mode). ``delta.content`` is+ empty during the reasoning phase for these models."""+ return SimpleNamespace(+ choices=[+ SimpleNamespace(+ delta=SimpleNamespace(+ content=None,+ tool_calls=None,+ reasoning_content=reasoning_text,+ )+ )+ ],+ usage=None,+ )+++def _tc_chunk(+ *,+ index: int = 0,+ tc_id: str | None = None,+ name: str | None = None,+ arguments: str | None = None,+) -> SimpleNamespace:+ fn = SimpleNamespace(name=name, arguments=arguments)+ return _chunk(+ content=None,+ tool_calls=[SimpleNamespace(index=index, id=tc_id, function=fn)],+ )+++async def _async_stream(chunks: list[SimpleNamespace]):+ for chunk in chunks:+ yield chunk+++class _ScriptedClient:+ """Minimal OpenAI-compatible streaming client returning pre-scripted+ chunk lists for each ``chat.completions.create`` call."""++ def __init__(self, scripts: list[list[SimpleNamespace]]) -> None:+ self._scripts = list(scripts)++ class _Completions:+ def __init__(self, parent: _ScriptedClient) -> None:+ self.parent = parent++ async def create(self, **kwargs: Any):+ if not self.parent._scripts:+ raise RuntimeError("scripted client exhausted")+ return _async_stream(self.parent._scripts.pop(0))++ class _Chat:+ def __init__(self, parent: _ScriptedClient) -> None:+ self.completions = _Completions(parent)++ self.chat = _Chat(self)+++async def _collect_events(bus: StreamBus, fn) -> list[Any]:+ """Run ``fn(bus)`` to completion and return the events that landed on+ the bus during it."""+ events: list[Any] = []++ async def _consume() -> None:+ async for event in bus.subscribe():+ events.append(event)++ consumer = asyncio.create_task(_consume())+ await asyncio.sleep(0)+ try:+ result = await fn()+ finally:+ await bus.close()+ await consumer+ return events, result+++def _thinking_texts(events: list[Any]) -> list[str]:+ return [e.content for e in events if e.type == StreamEventType.THINKING]+++def _content_texts(events: list[Any]) -> list[str]:+ return [e.content for e in events if e.type == StreamEventType.CONTENT]+++_ALLOWED = ("FINISH", "TOOL", "THINK", "PAUSE")+_FINAL = frozenset({"FINISH"})+_FINAL_MIXED = frozenset({"FINISH", "PAUSE"})+++async def _run(+ chunks: list[SimpleNamespace],+ *,+ allowed: tuple[str, ...] = _ALLOWED,+ final_labels: frozenset[str] = _FINAL,+ tool_label: str | None = "TOOL",+ final_meta: dict[str, Any] | None = None,+ implicit_think_label: str | None = None,+):+ client = _ScriptedClient([chunks])+ bus = StreamBus()+ iter_meta = {"label": "Reasoning", "trace_id": "iter-1"}++ async def _do():+ return await run_labeled_step(+ client=client,+ model="x",+ messages=[{"role": "user", "content": "hi"}],+ completion_kwargs={},+ tool_schemas=None,+ allowed_labels=allowed,+ final_labels=final_labels,+ tool_label=tool_label,+ stream=bus,+ source="test",+ stage="test",+ iter_meta=iter_meta,+ binding="openai",+ final_meta=final_meta,+ implicit_think_label=implicit_think_label,+ )++ events, result = await _collect_events(bus, _do)+ return events, result+++# ---------------------------- the tests ----------------------------+++async def test_prelude_then_finish_routes_split_streams_and_strips_prelude() -> None:+ """A ``<think>prelude</think>`` then ``FINISH`` should stream the prelude+ *including* its ``<think>``/``</think>`` markers into the reasoning+ sub-trace (so users see the model's native structure), the final answer+ into the chat bubble (when ``final_meta`` is supplied), and return text+ with the prelude block fully stripped."""+ final_meta = {"label": "Final", "trace_id": "final-1"}+ events, result = await _run(+ [+ _chunk("<think>let me reason about this</think>"),+ _chunk("``FINISH``\nThe answer is 42."),+ ],+ final_meta=final_meta,+ )++ assert result.label == "FINISH"+ assert result.text == "The answer is 42."+ thinking_joined = "".join(_thinking_texts(events))+ # Prelude content streamed live as THINKING (reasoning sub-trace).+ assert "let me reason about this" in thinking_joined+ # The ``<think>``/``</think>`` markers ARE visible in the trace.+ assert "<think>" in thinking_joined+ assert "</think>" in thinking_joined+ # Final-label body streamed live as CONTENT (chat bubble).+ assert "The answer is 42." in "".join(_content_texts(events))+++ ("label_prefix", "expected_text"),+ [+ ("`FINISH`\n", "Single-backtick final."),+ ("```FINISH```\n", "Triple-backtick final."),+ ("FINISH:", "Fullwidth-colon final."),+ ],+)+async def test_prelude_then_finish_accepts_common_label_variants(+ label_prefix: str,+ expected_text: str,+) -> None:+ """Reasoning models often obey the action token but alter the wrapper+ after ``</think>``. The parser should still recognize the real FINISH+ label rather than letting the implicit-THINK fallback consume it."""+ final_meta = {"label": "Final", "trace_id": "final-1"}+ events, result = await _run(+ [+ _chunk("<think>native reasoning</think>"),+ _chunk(f"{label_prefix}{expected_text}"),+ ],+ final_meta=final_meta,+ implicit_think_label="THINK",+ )++ assert result.label == "FINISH"+ assert result.text == expected_text+ assert "native reasoning" in "".join(_thinking_texts(events))+ assert expected_text in "".join(_content_texts(events))+++async def test_prelude_then_bare_finish_at_stream_end_wins_over_implicit_think() -> None:+ """A terminal bare label with no body is only decidable at EOF. If a+ prelude was seen, it must still resolve as FINISH instead of falling+ through to implicit THINK."""+ events, result = await _run(+ [+ _chunk("<think>done thinking</think>"),+ _chunk("FINISH"),+ ],+ implicit_think_label="THINK",+ )++ assert result.label == "FINISH"+ assert result.text == ""+ assert "done thinking" in "".join(_thinking_texts(events))+++async def test_prelude_then_think_merges_into_same_subtrace() -> None:+ """Prelude content + a subsequent ``THINK`` label should both route to+ the THINKING channel (same reasoning sub-trace). The returned text+ keeps only the post-label body — ``<think>...</think>`` is stripped."""+ events, result = await _run(+ [+ _chunk("<think>prelude reasoning</think>"),+ _chunk("``THINK``\nstill thinking out loud"),+ ],+ )++ assert result.label == "THINK"+ assert result.text == "still thinking out loud"+ thinking = _thinking_texts(events)+ joined = "".join(thinking)+ # Both prelude and post-label text on the reasoning sub-trace.+ assert "prelude reasoning" in joined+ assert "still thinking out loud" in joined+ # Nothing on the final-content channel.+ assert _content_texts(events) == []+++async def test_prelude_close_tag_split_across_chunks_still_detected() -> None:+ """If ``</think>`` arrives split across chunks (e.g. ``</think`` then+ ``>``), the parser still recognizes the close tag thanks to the trailing+ guard window."""+ events, result = await _run(+ [+ _chunk("<think>reasoning content here</think"),+ _chunk(">"),+ _chunk("``FINISH``\nDone."),+ ],+ )++ assert result.label == "FINISH"+ assert result.text == "Done."+ assert "reasoning content here" in "".join(_thinking_texts(events))+++async def test_prelude_then_split_wrapped_finish_waits_for_matching_backticks() -> None:+ """The tolerant wrapper parser must not resolve ````FINISH``` after+ seeing only one of the two closing backticks; otherwise the remaining+ backtick leaks into the final answer."""+ events, result = await _run(+ [+ _chunk("<think>reasoning</think>"),+ _chunk("``FINISH`"),+ _chunk("`\nDone."),+ ],+ )++ assert result.label == "FINISH"+ assert result.text == "Done."+ assert "reasoning" in "".join(_thinking_texts(events))+++async def test_prelude_entire_response_in_single_chunk() -> None:+ """A single chunk that carries prelude, label, and body must still+ resolve the label inside the same ingestion — not get stuck waiting+ for a next chunk that never arrives."""+ final_meta = {"label": "Final", "trace_id": "final-1"}+ events, result = await _run(+ [+ _chunk("<think>quick thought</think>``FINISH``\nAll done."),+ ],+ final_meta=final_meta,+ )++ assert result.label == "FINISH"+ assert result.text == "All done."+ assert "quick thought" in "".join(_thinking_texts(events))+ assert "All done." in "".join(_content_texts(events))+++async def test_prelude_then_tool_call_routes_correctly() -> None:+ """Prelude content followed by a ``TOOL`` label + real tool_calls must+ resolve the TOOL label, parse the tool call, and stream the prelude+ into the reasoning sub-trace."""+ events, result = await _run(+ [+ _chunk("<think>need to look this up</think>"),+ _chunk("``TOOL``\nCalling search now."),+ _tc_chunk(tc_id="call_1", name="search", arguments=""),+ _tc_chunk(arguments='{"q": "x"}'),+ ],+ )++ assert result.label == "TOOL"+ assert result.tool_calls == [+ {"id": "call_1", "name": "search", "arguments": '{"q": "x"}'}+ ]+ assert result.text == "Calling search now."+ joined_think = "".join(_thinking_texts(events))+ assert "need to look this up" in joined_think+ assert "Calling search now." in joined_think+++async def test_tool_calls_mid_prelude_close_prelude_synthetically() -> None:+ """If tool_call deltas arrive while still inside an open ``<think>``+ prelude, force-resolve to TOOL, flush remaining prelude content into+ the reasoning sub-trace, and ensure the returned text is clean."""+ events, result = await _run(+ [+ _chunk("<think>still reasoning"), # never closes+ _tc_chunk(tc_id="call_a", name="lookup", arguments='{"k":1}'),+ ],+ )++ assert result.label == "TOOL"+ assert result.tool_calls == [+ {"id": "call_a", "name": "lookup", "arguments": '{"k":1}'}+ ]+ # Even though </think> never arrived, the returned text must not leak+ # the prelude content (clean_thinking_tags strips the synthesized block).+ assert "<think>" not in result.text+ assert "still reasoning" not in result.text+ # Prelude content was still streamed live so the user saw activity.+ assert "still reasoning" in "".join(_thinking_texts(events))+++async def test_prelude_unclosed_then_stream_ends() -> None:+ """If the stream ends mid-prelude with no ``</think>`` and no label,+ fall back to ``LABEL_UNKNOWN``, surface the partial reasoning to the+ user via the sub-trace, and strip the prelude from the returned text."""+ events, result = await _run(+ [+ _chunk("<think>incomplete reasoning, no close tag"),+ ],+ )++ assert result.label == "UNKNOWN"+ # No prelude leakage in the returned text.+ assert "incomplete reasoning" not in result.text+ assert "<think>" not in result.text+ # User still saw the partial reasoning live.+ assert "incomplete reasoning, no close tag" in "".join(_thinking_texts(events))+++async def test_no_prelude_still_works() -> None:+ """Regression: when the model follows the protocol cleanly (no ``<think>``+ prelude), behavior must be identical to the previous implementation."""+ final_meta = {"label": "Final", "trace_id": "final-1"}+ events, result = await _run(+ [+ _chunk("``FINISH``\nDirect answer."),+ ],+ final_meta=final_meta,+ )+ assert result.label == "FINISH"+ assert result.text == "Direct answer."+ assert "Direct answer." in "".join(_content_texts(events))+ # No reasoning trace events emitted for a clean FINISH.+ assert _thinking_texts(events) == []+++async def test_wrapped_finish_with_adjacent_body_routes_to_final_not_reasoning() -> None:+ """Some models attach CJK/prose directly after the inline-code label+ (````FINISH``你好``). That is still a valid completed wrapper and must+ not be treated as missing-label reasoning."""+ final_meta = {"label": "Final", "trace_id": "final-1"}+ events, result = await _run(+ [+ _chunk("``FINISH``你好!我是 DeepTutor。"),+ ],+ final_meta=final_meta,+ )++ assert result.label == "FINISH"+ assert result.text == "你好!我是 DeepTutor。"+ assert "你好!我是 DeepTutor。" in "".join(_content_texts(events))+ assert _thinking_texts(events) == []+++async def test_reasoning_content_field_streams_to_reasoning_subtrace() -> None:+ """Models that put chain-of-thought in ``delta.reasoning_content`` (rather+ than inline ``<think>`` in content) must still surface live activity in+ the reasoning sub-trace, and the subsequent labeled answer in+ ``delta.content`` must resolve normally."""+ events, result = await _run(+ [+ _reasoning_chunk("step 1 of my reasoning"),+ _reasoning_chunk(" — step 2 continues"),+ _chunk("``FINISH``\nThe answer is X."),+ ],+ )++ assert result.label == "FINISH"+ assert result.text == "The answer is X."+ thinking_joined = "".join(_thinking_texts(events))+ assert "step 1 of my reasoning" in thinking_joined+ assert "step 2 continues" in thinking_joined+++async def test_reasoning_content_then_inline_think_merge_into_same_subtrace() -> None:+ """Some providers emit *both* a ``reasoning_content`` stream AND inline+ ``<think>...</think>`` in ``content``. Both should land in the same+ reasoning sub-trace; the final returned text must not leak either."""+ events, result = await _run(+ [+ _reasoning_chunk("external reasoning"),+ _chunk("<think>inline reasoning</think>``FINISH``\nDone."),+ ],+ )+ assert result.label == "FINISH"+ assert result.text == "Done."+ thinking_joined = "".join(_thinking_texts(events))+ assert "external reasoning" in thinking_joined+ assert "inline reasoning" in thinking_joined+++async def test_implicit_think_resolves_when_prelude_has_no_protocol_label() -> None:+ """A reasoning model that emits ``<think>...</think>`` and *nothing else*+ that matches the protocol should be accepted as an implicit ``THINK``+ iteration when the caller opts in. Without this, the loop would treat+ the iteration as a protocol violation and burn budget on repair."""+ events, result = await _run(+ [+ _chunk("<think>I'm thinking about this carefully</think>"),+ ],+ implicit_think_label="THINK",+ )++ assert result.label == "THINK"+ # The full reasoning structure is preserved in the returned text so the+ # next iteration's assistant context shows the model's native dialect.+ assert "<think>" in result.text+ assert "I'm thinking about this carefully" in result.text+ assert "</think>" in result.text+++async def test_implicit_think_resolves_on_probe_overflow_with_unlabeled_tail() -> None:+ """If a reasoning model emits ``<think>...</think>`` followed by a long+ body that doesn't include a protocol label, the implicit-THINK opt-in+ should still resolve to ``THINK`` (rather than ``UNKNOWN``) so the loop+ can continue with the next iteration."""+ long_unlabeled_tail = "x" * 200 # well past the 64-char probe window+ events, result = await _run(+ [+ _chunk(f"<think>some reasoning</think>{long_unlabeled_tail}"),+ ],+ implicit_think_label="THINK",+ )+ assert result.label == "THINK"+ # Both the prelude and the post-close trailing prose stay in text.+ assert "<think>" in result.text+ assert "some reasoning" in result.text+ assert long_unlabeled_tail in result.text+++async def test_implicit_think_does_not_fire_without_opt_in() -> None:+ """Existing callers that don't opt into implicit-THINK must keep the+ legacy ``LABEL_UNKNOWN`` fallback so their repair / retry paths are+ not silently bypassed."""+ events, result = await _run(+ [+ _chunk("<think>private reasoning</think>"),+ ],+ )+ assert result.label == "UNKNOWN"+++async def test_implicit_think_skips_when_label_not_in_allowed() -> None:+ """A caller whose protocol does not include the implicit label (e.g.+ a ``FINISH``-only forced-finalization step) must not get an implicit+ ``THINK`` resolution — it would corrupt their state machine."""+ events, result = await _run(+ [+ _chunk("<think>reasoning</think>"),+ ],+ allowed=("FINISH",),+ final_labels=frozenset({"FINISH"}),+ tool_label=None,+ implicit_think_label="THINK", # not in allowed+ )+ assert result.label == "UNKNOWN"+++async def test_prelude_with_long_body_emits_chunks_progressively() -> None:+ """A long prelude body should be emitted live in pieces, not buffered+ until ``</think>`` arrives. The trailing guard window keeps at most a+ small slice unsent so a split close tag stays detectable."""+ long_body = "x" * 500+ events, result = await _run(+ [+ _chunk("<think>" + long_body), # huge prelude, no close yet+ _chunk("</think>``FINISH``\nok"),+ ],+ )+ assert result.label == "FINISH"+ assert result.text == "ok"+ # Most of the long body must have been flushed live (the guard window+ # only holds back ~24 trailing chars).+ flushed = "".join(_thinking_texts(events))+ assert flushed.count("x") >= 500 - 24