mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 00:19:26 +08:00
fix(book): give Book a reachable token budget, and retry a starved plan
A book built with a reasoning model arrives as a single "Overview" chapter, or with the right chapter count and every learning objective and summary empty (#1316). Two independent faults compose into that. `get_agent_params` maps a module name to a section of agents.yaml, and `book` was not in the map — so the function returned the source-level `global_defaults` of 4096 *before* ever opening the file. That budget was therefore not the shipped default and not overridable: adding a `capabilities.book` block did nothing, and only editing the source could change it. It is now mapped, seeded at 12000 in DEFAULT_AGENTS_SETTINGS (so a stale agents.yaml still gets it), and honoured from the yaml. 12000 rather than a larger figure matches `research`, the closest analogue, and keeps the request under the output cap of providers that enforce one. The budget is the trigger, not the fault. A reasoning model pays for its hidden tokens out of the same `max_tokens` as its answer, so on a large prompt asking for a whole JSON object it can spend the lot and emit nothing. The provider does not raise — it returns a truncated body, or none — and `parse_json_response` hands back the caller's fallback, which in `SpineSynthesizer._materialise` is one placeholder chapter. Where the budget ran out *mid*-object, json-repair closes the fragment and the caller gets chapters whose objectives never arrived: the same failure wearing a different face. `blocks/_llm_writer.llm_json` already knew the escape hatch — ask again with thinking turned down — but only block generators went through it. The four pipeline agents each parsed their own response and had no retry at all. `book/json_retry.py` is now the one place that rule lives, and ideation, both source-explorer calls, all three spine rounds and the page planner go through it; `llm_json` shares its predicate so the two cannot drift. Each caller names the key that proves the payload arrived, which is what lets a repaired-but-gutted object trigger the retry rather than settle the stage. `BaseAgent.call_llm` / `stream_llm` gained the `reasoning_effort` parameter this needs; it was already the shape `llm_text` used.
This commit is contained in:
@@ -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 tracking
|
||||
attachments: 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 check
|
||||
if 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 logging
|
||||
attachments: 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 check
|
||||
if response_format:
|
||||
try:
|
||||
|
||||
@@ -11,9 +11,9 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.agents.base_agent import BaseAgent
|
||||
from deeptutor.utils.json_parser import parse_json_response
|
||||
|
||||
from ..inputs import IdeationContext
|
||||
from ..json_retry import json_with_reasoning_retry
|
||||
from ..models import BookProposal
|
||||
|
||||
|
||||
@@ -54,19 +54,25 @@ class IdeationAgent(BaseAgent):
|
||||
user_template = self.get_prompt("user_template") or _FALLBACK_USER
|
||||
user_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)
|
||||
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)
|
||||
|
||||
payload = parse_json_response(raw, logger_instance=self.logger, fallback={})
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
# ``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)
|
||||
|
||||
|
||||
@@ -33,9 +33,7 @@ from __future__ import annotations
|
||||
import logging
|
||||
from 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_json
|
||||
from ..blocks._prompts import get_book_prompt, load_book_prompts
|
||||
from ..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)
|
||||
|
||||
@@ -36,8 +36,8 @@ from typing import Any
|
||||
from deeptutor.agents.base_agent import BaseAgent
|
||||
from deeptutor.core.context import UnifiedContext
|
||||
from deeptutor.runtime.stream_bus import StreamBus
|
||||
from deeptutor.utils.json_parser import parse_json_response
|
||||
|
||||
from ..json_retry import json_with_reasoning_retry
|
||||
from ..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")
|
||||
|
||||
@@ -35,8 +35,8 @@ import logging
|
||||
from typing import Any
|
||||
|
||||
from deeptutor.agents.base_agent import BaseAgent
|
||||
from deeptutor.utils.json_parser import parse_json_response
|
||||
|
||||
from ..json_retry import json_with_reasoning_retry
|
||||
from ..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_directive
|
||||
|
||||
system_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)
|
||||
|
||||
@@ -21,6 +21,8 @@ from deeptutor.services.llm import (
|
||||
from deeptutor.services.prompt.language import append_language_directive
|
||||
from 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/scratchpad
|
||||
tokens and leave the visible JSON object empty. For structured book blocks
|
||||
we 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_EFFORT
|
||||
return retry_data
|
||||
return data or retry_data
|
||||
|
||||
|
||||
79
deeptutor/book/json_retry.py
Normal file
79
deeptutor/book/json_retry.py
Normal file
@@ -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",
|
||||
]
|
||||
@@ -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"),
|
||||
|
||||
@@ -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},
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -60,3 +60,90 @@ async def test_call_json_returns_an_empty_payload_when_the_call_fails(
|
||||
)
|
||||
|
||||
assert payload == {}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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"}]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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]
|
||||
|
||||
50
tests/services/config/test_book_agent_params.py
Normal file
50
tests/services/config/test_book_agent_params.py
Normal file
@@ -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}
|
||||
Reference in New Issue
Block a user