DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(book): give Book a reachable token budget, and retry a starved plan
Bingxi Zhao (Frank)5ac8e2c9d3dd
diff --git a/deeptutor/agents/base_agent.py b/deeptutor/agents/base_agent.pyindex ecf222373..bd0f30a91 100644--- a/deeptutor/agents/base_agent.py+++ b/deeptutor/agents/base_agent.py@@ -358,6 +358,7 @@ class BaseAgent(ABC):stage: str | None = None,attachments: list[Any] | None = None,trace_meta: dict[str, Any] | None = None,+ reasoning_effort: str | None = None,) -> str:"""Unified interface for calling LLM (non-streaming).@@ -376,6 +377,9 @@ class BaseAgent(ABC):verbose: Whether to print raw LLM output (default True)stage: Stage marker for logging and trackingattachments: Image/file attachments for multimodal input (optional)+ reasoning_effort: Override the model's thinking level for this one+ call. Callers use it to free the token budget for the answer+ when a reasoning model spent it all on hidden tokens.Returns:LLM response text@@ -397,6 +401,9 @@ class BaseAgent(ABC):if max_tokens:kwargs.update(get_token_limit_kwargs(model, max_tokens))+ if reasoning_effort is not None:+ kwargs["reasoning_effort"] = reasoning_effort+# Handle response_format with capability checkif response_format:try:@@ -520,6 +527,7 @@ class BaseAgent(ABC):stage: str | None = None,attachments: list[Any] | None = None,trace_meta: dict[str, Any] | None = None,+ reasoning_effort: str | None = None,) -> AsyncGenerator[str, None]:"""Unified interface for streaming LLM responses.@@ -537,6 +545,8 @@ class BaseAgent(ABC):response_format: JSON schema for structured output (optional)stage: Stage marker for loggingattachments: Image/file attachments for multimodal input (optional)+ reasoning_effort: Override the model's thinking level for this one+ call (see :meth:`call_llm`).Yields:Response chunks as strings@@ -555,6 +565,9 @@ class BaseAgent(ABC):if max_tokens:kwargs.update(get_token_limit_kwargs(model, max_tokens))+ if reasoning_effort is not None:+ kwargs["reasoning_effort"] = reasoning_effort+# Handle response_format with capability checkif response_format:try:diff --git a/deeptutor/book/agents/ideation_agent.py b/deeptutor/book/agents/ideation_agent.pyindex 149431cb7..667ecab73 100644--- a/deeptutor/book/agents/ideation_agent.py+++ b/deeptutor/book/agents/ideation_agent.py@@ -11,9 +11,9 @@ from __future__ import annotationsfrom typing import Anyfrom deeptutor.agents.base_agent import BaseAgent-from deeptutor.utils.json_parser import parse_json_responsefrom ..inputs import IdeationContext+from ..json_retry import json_with_reasoning_retryfrom ..models import BookProposal@@ -54,19 +54,25 @@ class IdeationAgent(BaseAgent):user_template = self.get_prompt("user_template") or _FALLBACK_USERuser_prompt = user_template.format(ideation_context=ideation_context.render())- chunks: list[str] = []- async for chunk in self.stream_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- response_format={"type": "json_object"},- stage="ideation",- ):- chunks.append(chunk)- raw = "".join(chunks)-- payload = parse_json_response(raw, logger_instance=self.logger, fallback={})- if not isinstance(payload, dict):- payload = {}+ async def _run(reasoning_effort: str | None) -> str:+ chunks: list[str] = []+ async for chunk in self.stream_llm(+ user_prompt=user_prompt,+ system_prompt=system_prompt,+ response_format={"type": "json_object"},+ stage="ideation",+ reasoning_effort=reasoning_effort,+ ):+ chunks.append(chunk)+ return "".join(chunks)++ # ``title`` is the one field the proposal cannot be rebuilt without, so+ # it is what tells a thinking-only response apart from a real one.+ payload = await json_with_reasoning_retry(+ _run,+ expected_key="title",+ logger_instance=self.logger,+ )return self._coerce_proposal(payload, ideation_context)diff --git a/deeptutor/book/agents/page_planner.py b/deeptutor/book/agents/page_planner.pyindex c7e01d044..e2a1b4ca1 100644--- a/deeptutor/book/agents/page_planner.py+++ b/deeptutor/book/agents/page_planner.py@@ -33,9 +33,7 @@ from __future__ import annotationsimport loggingfrom typing import Any-from deeptutor.utils.json_parser import parse_json_response--from ..blocks._llm_writer import llm_text+from ..blocks._llm_writer import llm_jsonfrom ..blocks._prompts import get_book_prompt, load_book_promptsfrom ..models import (Block,@@ -330,7 +328,11 @@ class SectionArchitect:try:system_prompt, user_template = _architect_prompts(language)- raw = await llm_text(+ # ``llm_json`` rather than ``llm_text`` + a parse: it retries once+ # with thinking turned down when the first response is all hidden+ # tokens and no JSON, which is what silently dropped whole chapter+ # plans back to the static planner (#1316).+ payload = await llm_json(user_prompt=_architect_user_prompt(chapter=chapter,language=language,@@ -340,17 +342,13 @@ class SectionArchitect:system_prompt=system_prompt,max_tokens=1200,temperature=0.6,- response_format={"type": "json_object"},language=language,+ expected_key="blocks",)except Exception as exc:logger.warning(f"SectionArchitect LLM failed → fallback static: {exc}")return self.plan_blocks(chapter, depth=depth, allowed=allowed)- payload = parse_json_response(raw, logger_instance=logger, fallback={})- if not isinstance(payload, dict):- return self.plan_blocks(chapter, depth=depth, allowed=allowed)-items = payload.get("blocks")if not isinstance(items, list) or not items:return self.plan_blocks(chapter, depth=depth, allowed=allowed)diff --git a/deeptutor/book/agents/source_explorer.py b/deeptutor/book/agents/source_explorer.pyindex 34ce9746c..10aaf9d37 100644--- a/deeptutor/book/agents/source_explorer.py+++ b/deeptutor/book/agents/source_explorer.py@@ -36,8 +36,8 @@ from typing import Anyfrom deeptutor.agents.base_agent import BaseAgentfrom deeptutor.core.context import UnifiedContextfrom deeptutor.runtime.stream_bus import StreamBus-from deeptutor.utils.json_parser import parse_json_response+from ..json_retry import json_with_reasoning_retryfrom ..models import (BookInputs,BookProposal,@@ -297,23 +297,28 @@ class SourceExplorer(BaseAgent):extra_context=extra_context,)- try:+ async def _run(reasoning_effort: str | None) -> str:chunks: list[str] = []async for piece in self.stream_llm(user_prompt=user_prompt,system_prompt=system_prompt,response_format={"type": "json_object"},stage="explore_queries",+ reasoning_effort=reasoning_effort,):chunks.append(piece)- raw = "".join(chunks)+ return "".join(chunks)++ try:+ payload = await json_with_reasoning_retry(+ _run,+ expected_key="queries",+ logger_instance=self.logger,+ )except Exception as exc:logger.warning(f"SourceExplorer query LLM failed: {exc}")return []- payload = parse_json_response(raw, logger_instance=self.logger, fallback={})- if not isinstance(payload, dict):- return []queries_raw = payload.get("queries")if not isinstance(queries_raw, list):return []@@ -681,24 +686,28 @@ class SourceExplorer(BaseAgent):chunks_block=chunks_block,)- try:+ async def _run(reasoning_effort: str | None) -> str:buf: list[str] = []async for piece in self.stream_llm(user_prompt=user_prompt,system_prompt=system_prompt,response_format={"type": "json_object"},stage="explore_summary",+ reasoning_effort=reasoning_effort,):buf.append(piece)- raw = "".join(buf)+ return "".join(buf)++ try:+ payload = await json_with_reasoning_retry(+ _run,+ expected_key="summary",+ logger_instance=self.logger,+ )except Exception as exc:logger.warning(f"SourceExplorer summary LLM failed: {exc}")return ("", [], [])- payload = parse_json_response(raw, logger_instance=self.logger, fallback={})- if not isinstance(payload, dict):- return ("", [], [])-summary = _clip(str(payload.get("summary") or ""), 2400)concepts_raw = payload.get("candidate_concepts")notes_raw = payload.get("notes")diff --git a/deeptutor/book/agents/spine_synthesizer.py b/deeptutor/book/agents/spine_synthesizer.pyindex 1b32d5f31..697b45e28 100644--- a/deeptutor/book/agents/spine_synthesizer.py+++ b/deeptutor/book/agents/spine_synthesizer.py@@ -35,8 +35,8 @@ import loggingfrom typing import Anyfrom deeptutor.agents.base_agent import BaseAgent-from deeptutor.utils.json_parser import parse_json_response+from ..json_retry import json_with_reasoning_retryfrom ..models import (BookProposal,Chapter,@@ -201,6 +201,7 @@ class SpineSynthesizer(BaseAgent):system_prompt=system_prompt,user_prompt=user_prompt,stage="spine_draft",+ expected_key="chapters",)async def _critique(@@ -248,6 +249,7 @@ class SpineSynthesizer(BaseAgent):system_prompt=system_prompt,user_prompt=user_prompt,stage="spine_revise",+ expected_key="chapters",)async def _call_json(@@ -256,26 +258,38 @@ class SpineSynthesizer(BaseAgent):system_prompt: str,user_prompt: str,stage: str,+ expected_key: str | None = None,) -> dict[str, Any]:from ..blocks._language import language_directivesystem_prompt = system_prompt.rstrip() + language_directive(self.language)- try:++ async def _run(reasoning_effort: str | None) -> str:# Blocking rather than streamed: nothing consumes the partial JSON,# and a reasoning model's <think> prelude never reaches the parser# this way, so a truncated spine cannot collapse to one placeholder# chapter (#707).- raw = await self.call_llm(+ return await self.call_llm(user_prompt=user_prompt,system_prompt=system_prompt,response_format={"type": "json_object"},stage=stage,+ reasoning_effort=reasoning_effort,+ )++ try:+ # A reasoning model can spend the whole budget thinking and return+ # nothing to parse; the retry asks the same question with thinking+ # turned down rather than letting the spine silently degrade to a+ # single "Overview" chapter (#1316).+ return await json_with_reasoning_retry(+ _run,+ expected_key=expected_key,+ logger_instance=self.logger,)except Exception as exc:logger.warning(f"SpineSynthesizer LLM call ({stage}) failed: {exc}")return {}- payload = parse_json_response(raw, logger_instance=self.logger, fallback={})- return payload if isinstance(payload, dict) else {}# ------------------------------------------------------------------ ## Materialise: payload → Spine + ConceptGraph (with validation)diff --git a/deeptutor/book/blocks/_llm_writer.py b/deeptutor/book/blocks/_llm_writer.pyindex 9babf58af..8224e453c 100644--- a/deeptutor/book/blocks/_llm_writer.py+++ b/deeptutor/book/blocks/_llm_writer.py@@ -21,6 +21,8 @@ from deeptutor.services.llm import (from deeptutor.services.prompt.language import append_language_directivefrom deeptutor.utils.json_parser import parse_json_response+from ..json_retry import RETRY_REASONING_EFFORT, json_payload_is_usable+async def llm_text(*,@@ -81,15 +83,6 @@ def _normalize_json_payload(data: Any, expected_key: str | None = None) -> dict[return {}-def _json_has_expected(data: dict[str, Any], expected_key: str | None) -> bool:- if not data:- return False- if expected_key is None:- return True- value = data.get(expected_key)- return bool(value)--def _strip_thinking_preamble(text: str) -> str:"""Strip model thinking/reasoning preamble before JSON output.@@ -145,9 +138,9 @@ async def llm_json(Reasoning models can spend the whole response budget on hidden/scratchpadtokens and leave the visible JSON object empty. For structured book blockswe first honor the configured reasoning mode, then retry once with low- reasoning effort if parsing fails or the expected top-level key is missing.- ("low" rather than "minimal": local/Qwen models served via vLLM reject- "minimal", and "minimal" disables thinking entirely.)+ reasoning effort if parsing fails or the expected top-level key is missing+ — the same rule the Book pipeline agents apply via+ :func:`deeptutor.book.json_retry.json_with_reasoning_retry`.Also strips thinking/reasoning preamble text (common with local models)before JSON parsing.@@ -176,12 +169,12 @@ async def llm_json(return _normalize_json_payload(recovered, expected_key=expected_key)data = await _once(None)- if _json_has_expected(data, expected_key):+ if json_payload_is_usable(data, expected_key):return data- retry_data = await _once("low")- if _json_has_expected(retry_data, expected_key):- retry_data.setdefault("_metadata", {})["reasoning_retry"] = "low"+ retry_data = await _once(RETRY_REASONING_EFFORT)+ if json_payload_is_usable(retry_data, expected_key):+ retry_data.setdefault("_metadata", {})["reasoning_retry"] = RETRY_REASONING_EFFORTreturn retry_datareturn data or retry_datadiff --git a/deeptutor/book/json_retry.py b/deeptutor/book/json_retry.pynew file mode 100644index 000000000..17bda8d98--- /dev/null+++ b/deeptutor/book/json_retry.py@@ -0,0 +1,79 @@+"""One retry for a structured call a reasoning model failed to answer.++A reasoning model pays for its hidden tokens out of the same ``max_tokens``+budget as its visible answer. When a prompt is large and the requested payload+is a whole JSON object — a book proposal, a spine, a page plan — the thinking+phase can consume the budget before a single character of JSON is emitted. The+provider does not raise: it returns a truncated body, or none at all, and+``parse_json_response`` hands back the caller's fallback. Every Book stage then+degrades silently — most visibly the spine, which collapses to one placeholder+"Overview" chapter (#1316).++The escape hatch is to ask the same model for the same thing with its thinking+turned down, which frees the budget for the answer. ``"low"`` rather than+``"minimal"``: local/Qwen models served via vLLM reject ``"minimal"``, and it+disables thinking outright.++This is the shared half of what ``blocks/_llm_writer.llm_json`` already did for+block generators; the pipeline agents (ideation, source explorer, spine+synthesiser, page planner) each parsed their own response and had no retry at+all.+"""++from __future__ import annotations++from collections.abc import Awaitable, Callable+from typing import Any++from deeptutor.utils.json_parser import parse_json_response++#: Reasoning level used for the second attempt. Not ``"minimal"`` — see module+#: docstring.+RETRY_REASONING_EFFORT = "low"+++def json_payload_is_usable(payload: Any, expected_key: str | None) -> bool:+ """Whether a parsed payload is worth keeping without a retry."""+ if not isinstance(payload, dict) or not payload:+ return False+ if expected_key is None:+ return True+ return bool(payload.get(expected_key))+++async def json_with_reasoning_retry(+ run: Callable[[str | None], Awaitable[str]],+ *,+ expected_key: str | None = None,+ logger_instance: Any = None,+) -> dict[str, Any]:+ """Run ``run`` for a JSON object, retrying once at low reasoning effort.++ ``run`` receives the ``reasoning_effort`` to use (``None`` on the first+ attempt = whatever the model is configured for) and returns the raw+ response text. Returns ``{}`` when neither attempt produced an object, so+ callers keep their existing "empty means fall back" handling.+ """+ payload = parse_json_response(await run(None), logger_instance=logger_instance, fallback={})+ if json_payload_is_usable(payload, expected_key):+ return payload++ retried = parse_json_response(+ await run(RETRY_REASONING_EFFORT),+ logger_instance=logger_instance,+ fallback={},+ )+ if json_payload_is_usable(retried, expected_key):+ return retried++ for candidate in (payload, retried):+ if isinstance(candidate, dict) and candidate:+ return candidate+ return {}+++__all__ = [+ "RETRY_REASONING_EFFORT",+ "json_payload_is_usable",+ "json_with_reasoning_retry",+]diff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.pyindex 74b2707be..33a969378 100644--- a/deeptutor/services/config/loader.py+++ b/deeptutor/services/config/loader.py@@ -213,6 +213,7 @@ def get_agent_params(module_name: str) -> dict:- "question": Question module agents- "brainstorm": Brainstorm tool settings- "co_writer": CoWriter module agents+ - "book": Book module agents (ideation / explore / spine / page plan)- "narrator": Narrator agent (independent, for TTS)- "llm_probe": Settings → LLM diagnostic probe@@ -236,6 +237,12 @@ def get_agent_params(module_name: str) -> dict:"question": ("capabilities", "question"),"co_writer": ("capabilities", "co_writer"),"visualize": ("capabilities", "visualize"),+ # Book was missing here, so ``get_agent_params("book")`` returned the+ # 4096 global fallback *before* ever opening agents.yaml — a budget no+ # user could raise, and one a reasoning model spends entirely on hidden+ # tokens, leaving the spine stage an empty response and the book a+ # single "Overview" chapter (#1316).+ "book": ("capabilities", "book"),"brainstorm": ("tools", "brainstorm"),"vision_solver": ("plugins", "vision_solver"),"math_animator": ("plugins", "math_animator"),diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.pyindex f332122c0..22577040b 100644--- a/deeptutor/services/setup/init.py+++ b/deeptutor/services/setup/init.py@@ -75,6 +75,14 @@ DEFAULT_AGENTS_SETTINGS = {"question": {"temperature": 0.7, "max_tokens": 4096},"co_writer": {"temperature": 0.7, "max_tokens": 4096},"visualize": {"temperature": 0.4, "max_tokens": 16384},+ # A book spine is one JSON payload holding a concept graph plus every+ # chapter, and a reasoning model pays for its hidden tokens out of the+ # same budget. 4096 (the old, unreachable global fallback) truncated+ # both (#1316). Matched to `research` rather than pushed higher: the+ # same "long structured output" shape, the same accepted risk against+ # providers that cap `max_tokens`, and the low-effort retry in+ # `book/json_retry.py` is what actually rescues a starved round.+ "book": {"temperature": 0.5, "max_tokens": 12000},"chat": {"temperature": 0.2,"responding": {"max_tokens": 8000},diff --git a/tests/book/test_block_type_controls.py b/tests/book/test_block_type_controls.pyindex b18b0bc2f..f356ef884 100644--- a/tests/book/test_block_type_controls.py+++ b/tests/book/test_block_type_controls.py@@ -26,10 +26,10 @@ def _types(blocks) -> list[BlockType]:def _install_llm(monkeypatch: pytest.MonkeyPatch, blocks: list[dict[str, object]]) -> None:- async def fake_llm_text(**_kwargs) -> str:- return json.dumps({"blocks": blocks})+ async def fake_llm_json(**_kwargs) -> dict[str, object]:+ return json.loads(json.dumps({"blocks": blocks}))- monkeypatch.setattr(page_planner, "llm_text", fake_llm_text)+ monkeypatch.setattr(page_planner, "llm_json", fake_llm_json)def test_allowed_none_leaves_static_plan_unchanged() -> None:diff --git a/tests/book/test_spine_synthesizer_llm_call.py b/tests/book/test_spine_synthesizer_llm_call.pyindex dc8618ea6..b08d4a5c8 100644--- a/tests/book/test_spine_synthesizer_llm_call.py+++ b/tests/book/test_spine_synthesizer_llm_call.py@@ -60,3 +60,90 @@ async def test_call_json_returns_an_empty_payload_when_the_call_fails()assert payload == {}+++async def test_call_json_retries_at_low_effort_when_reasoning_ate_the_budget(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A thinking-only first response must not settle the spine.++ A reasoning model pays for its hidden tokens out of the same ``max_tokens``+ as its answer; on the spine prompt it can spend the lot and return nothing+ to parse. That used to reach ``_materialise`` as ``{}`` and collapse a+ whole book into one placeholder "Overview" chapter (#1316). The second+ attempt asks for the same JSON with thinking turned down.+ """+ efforts: list[str | None] = []++ async def _call_llm(self: BaseAgent, **kwargs: Any) -> str:+ efforts.append(kwargs.get("reasoning_effort"))+ if len(efforts) == 1:+ return ""+ return json.dumps({"chapters": [{"title": "Vectors"}, {"title": "Matrices"}]})++ monkeypatch.setattr(BaseAgent, "call_llm", _call_llm)++ payload = await SpineSynthesizer()._call_json(+ system_prompt="Design a spine.",+ user_prompt="About linear algebra.",+ stage="spine_draft",+ expected_key="chapters",+ )++ assert efforts == [None, "low"]+ assert len(payload["chapters"]) == 2+++async def test_call_json_retries_when_the_payload_lost_its_chapters(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """json-repair closing a truncated object is not a usable spine.++ A budget that runs out mid-JSON leaves a repairable fragment, so parsing+ succeeds and hands back an object whose ``chapters`` never arrived — the+ shape behind "the spine has chapters but every learning objective and+ summary is empty".+ """+ calls: list[str | None] = []++ async def _call_llm(self: BaseAgent, **kwargs: Any) -> str:+ calls.append(kwargs.get("reasoning_effort"))+ if len(calls) == 1:+ return json.dumps({"concept_graph": {"nodes": [], "edges": []}})+ return json.dumps({"chapters": [{"title": "Vectors"}]})++ monkeypatch.setattr(BaseAgent, "call_llm", _call_llm)++ payload = await SpineSynthesizer()._call_json(+ system_prompt="Design a spine.",+ user_prompt="About linear algebra.",+ stage="spine_draft",+ expected_key="chapters",+ )++ assert calls == [None, "low"]+ assert payload["chapters"] == [{"title": "Vectors"}]+++async def test_call_json_does_not_retry_a_good_first_answer(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ calls: list[str | None] = []++ async def _call_llm(self: BaseAgent, **kwargs: Any) -> str:+ calls.append(kwargs.get("reasoning_effort"))+ return json.dumps({"chapters": [{"title": "Vectors"}]})++ monkeypatch.setattr(BaseAgent, "call_llm", _call_llm)++ await SpineSynthesizer()._call_json(+ system_prompt="Design a spine.",+ user_prompt="About linear algebra.",+ stage="spine_draft",+ expected_key="chapters",+ )++ assert calls == [None]diff --git a/tests/services/config/test_book_agent_params.py b/tests/services/config/test_book_agent_params.pynew file mode 100644index 000000000..8c0fe5d7b--- /dev/null+++ b/tests/services/config/test_book_agent_params.py@@ -0,0 +1,50 @@+"""The Book module's token budget must be resolvable and user-overridable.++``get_agent_params("book")`` returned the 4096 source-level fallback because+``book`` was absent from ``section_map`` — the function returned *before*+opening agents.yaml, so adding a ``capabilities.book`` block did nothing. A+reasoning model spends that budget on hidden tokens and leaves the spine stage+an empty response, which degrades a whole book to one "Overview" chapter+(#1316).+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++import yaml++from deeptutor.services.config import loader as loader_module+from deeptutor.services.config.loader import get_agent_params+from deeptutor.services.setup.init import DEFAULT_AGENTS_SETTINGS+++def _write_agents_yaml(tmp_path: Path, content: dict[str, Any]) -> Path:+ settings_dir = tmp_path / "data" / "user" / "settings"+ settings_dir.mkdir(parents=True, exist_ok=True)+ (settings_dir / "agents.yaml").write_text(yaml.dump(content), encoding="utf-8")+ return tmp_path+++def test_book_falls_back_to_the_shipped_default_not_the_global_4096(+ tmp_path: Path, monkeypatch+) -> None:+ """A stale agents.yaml (no ``book`` block) still gets the real budget."""+ project_root = _write_agents_yaml(tmp_path, {"capabilities": {"solve": {"temperature": 0.3}}})+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)++ params = get_agent_params("book")++ assert params["max_tokens"] == DEFAULT_AGENTS_SETTINGS["capabilities"]["book"]["max_tokens"]+ assert params["max_tokens"] > 4096+++def test_book_budget_is_overridable_from_agents_yaml(tmp_path: Path, monkeypatch) -> None:+ project_root = _write_agents_yaml(+ tmp_path,+ {"capabilities": {"book": {"temperature": 0.2, "max_tokens": 32000}}},+ )+ monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)++ assert get_agent_params("book") == {"temperature": 0.2, "max_tokens": 32000}