refactor(config): put every LLM budget in agents.yaml, one entry per stage

A capability that makes several different LLM calls cannot be described
by one max_tokens: the step emitting a whole JSON plan and the step
writing one paragraph need different room. `chat` has said so since it
grew `exploring`/`responding`. `question` and `research` said the same
thing in module constants instead, where no user could reach them.

The cost of that was not theoretical. `capabilities.question.max_tokens`
governed exactly one of question's six LLM calls — the follow-up agent —
while the pipeline's five steps used constants that ignored it. The plan
step's constant sat below the capability's own ceiling, which is how
#1318 shipped a step that could spend its whole allowance thinking and
emit zero templates without an error. `EXPLORE_FINISH_MAX_TOKENS` had
been dead since it was written.

Generalises the seam that already worked rather than adding a parallel
one: `get_chat_params` becomes `get_capability_params(capability)` over a
table of per-stage defaults, and `question`, `research` and
`explore_context` get tables of their own holding the numbers they
already ran on. The pipelines resolve once in `__init__` beside the
budget they already cached. Unknown keys are dropped, so a misspelled
stage cannot become a silent no-op that reads like a setting.

The rule this establishes, stated in the tables: **agents.yaml owns every
LLM budget** (temperature, max_tokens, per stage); **main.yaml owns
runtime behaviour** (iteration caps, timeouts, retry policy, modes). A
budget in main.yaml is a bug. `tool_summarizer.max_tokens` still reads
its main.yaml value first so nobody's existing configuration moves; new
installs reach the same number through agents.yaml like everything else.
GraphRAG's reachability probe is the one documented exemption — tuning it
could only make a health check lie.

Seeds are derived from the same tables the pipelines read, because two
lists of the same numbers is how a default and its seed drift apart —
the shape of #1316. Tests pin both halves: the shipped values, and that
every stage in code is present in the seeded file.

No behaviour change: every default is the constant it replaced.
6902 passed, 24 skipped.
This commit is contained in:
Bingxi Zhao (Frank)
2026-09-11 03:59:06 +08:00
parent 0f8759f730
commit ed85fe9bc2
8 changed files with 286 additions and 60 deletions

View File

@@ -78,6 +78,7 @@ from deeptutor.runtime.agentic.usage import record_streamed_usage
from deeptutor.runtime.registry.tool_registry import get_tool_registry
from deeptutor.runtime.stream_bus import StreamBus
from deeptutor.services.config import parse_language
from deeptutor.services.config.loader import get_capability_params
from deeptutor.services.llm import get_llm_config, prepare_multimodal_messages
from deeptutor.services.llm.reasoning_params import RETRY_REASONING_EFFORT
from deeptutor.services.prompt import get_prompt_manager
@@ -137,26 +138,18 @@ _PROTOCOL_REPAIR = LabelProtocol(
DEFAULT_MAX_EXPLORE_ITERATIONS = 8
DEFAULT_MAX_QUIZ_ITERATIONS_PER_QUESTION = 5
DEFAULT_MAX_TOKENS = 4000
EXPLORE_FINISH_MAX_TOKENS = 3000
# Plan is the one step asked for a whole JSON object in a single shot, and it
# was the tightest budget in this file — below even the 4096 the ``question``
# capability ships with. A reasoning model pays for its hidden tokens out of
# this same allowance, so on a rich exploration trace it could spend the lot
# deliberating and end the stream before writing a single template (#1318).
# Reachable, not generous: the plan itself is a few hundred tokens, the rest
# is headroom to think in, and the low-effort retry below covers the models
# that want more than any fixed number.
PLAN_MAX_TOKENS = 6000
QUIZ_FINISH_MAX_TOKENS = 3000
REPAIR_MAX_TOKENS = 2500
# Token budgets live in agents.yaml, one entry per stage — see
# ``DEFAULT_QUESTION_PARAMS`` in services.config.loader. They used to be
# constants here, which meant no user could raise the plan step's ceiling
# (#1318) and that ``capabilities.question.max_tokens`` governed only the
# follow-up agent while these five calls ignored it. ``EXPLORE_FINISH`` went
# with them: it had been dead since it was written, referenced nowhere.
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
@@ -410,11 +403,16 @@ class QuestionPipeline:
if isinstance(exploring_cfg.get("tool_summarizer"), dict)
else {}
)
self._budgets = get_capability_params("question")
summarizer_tokens = summarizer_cfg.get("max_tokens")
if isinstance(summarizer_tokens, int) and summarizer_tokens > 0:
# main.yaml still wins where a user already set it, so nobody's
# existing configuration changes underneath them. New installs
# reach the same number through agents.yaml like every other
# budget.
self.tool_summarizer_max_tokens = int(summarizer_tokens)
else:
self.tool_summarizer_max_tokens = DEFAULT_TOOL_SUMMARIZER_MAX_TOKENS
self.tool_summarizer_max_tokens = int(self._budgets["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))
@@ -693,7 +691,7 @@ class QuestionPipeline:
protocol=_PROTOCOL_EXPLORE,
client=client,
model=self.model,
completion_kwargs=self._completion_kwargs(DEFAULT_MAX_TOKENS),
completion_kwargs=self._completion_kwargs(self._budgets["answering"]["max_tokens"]),
binding=self.binding,
tool_schemas=tool_schemas,
stream=stream,
@@ -755,7 +753,7 @@ class QuestionPipeline:
stream=stream,
stage=STAGE_PLANNING,
iter_meta=iter_meta,
max_tokens=PLAN_MAX_TOKENS,
max_tokens=self._budgets["planning"]["max_tokens"],
)
if step.reasoning_only:
# The round was all thinking and no plan. Parsing it would hand
@@ -784,7 +782,7 @@ class QuestionPipeline:
stream=stream,
stage=STAGE_PLANNING,
iter_meta=iter_meta,
max_tokens=PLAN_MAX_TOKENS,
max_tokens=self._budgets["planning"]["max_tokens"],
reasoning_effort=RETRY_REASONING_EFFORT,
)
plan = self._parse_plan(
@@ -926,7 +924,7 @@ class QuestionPipeline:
protocol=_PROTOCOL_QUIZ,
client=client,
model=self.model,
completion_kwargs=self._completion_kwargs(QUIZ_FINISH_MAX_TOKENS),
completion_kwargs=self._completion_kwargs(self._budgets["quiz_finish"]["max_tokens"]),
binding=self.binding,
tool_schemas=tool_schemas,
stream=stream,
@@ -1009,7 +1007,7 @@ class QuestionPipeline:
stream=stream,
stage=STAGE_QUIZZING,
iter_meta=iter_meta,
max_tokens=REPAIR_MAX_TOKENS,
max_tokens=self._budgets["repair"]["max_tokens"],
)
return self._parse_quiz_payload(step.text)
@@ -1519,7 +1517,7 @@ class QuestionPipeline:
stream=stream,
stage=stage,
iter_meta=iter_meta,
max_tokens=DEFAULT_MAX_TOKENS,
max_tokens=self._budgets["answering"]["max_tokens"],
final_meta=final_meta,
)
calls += 1
@@ -1744,11 +1742,13 @@ class QuestionPipeline:
stream: StreamBus,
stage: str,
iter_meta: dict[str, Any],
max_tokens: int = DEFAULT_MAX_TOKENS,
max_tokens: int | None = None,
reasoning_effort: str | None = None,
final_meta: dict[str, Any] | None = None,
eager_sub_trace: bool = True,
) -> LabeledStepResult:
if max_tokens is None:
max_tokens = int(self._budgets["answering"]["max_tokens"])
return await run_labeled_step(
client=client,
model=self.model,

View File

@@ -88,6 +88,7 @@ from deeptutor.runtime.agentic.tool_dispatch import (
from deeptutor.runtime.registry.tool_registry import get_tool_registry
from deeptutor.runtime.stream_bus import StreamBus
from deeptutor.services.config import parse_language
from deeptutor.services.config.loader import get_capability_params
from deeptutor.services.llm import get_llm_config, prepare_multimodal_messages
from deeptutor.services.prompt import get_prompt_manager
from deeptutor.services.prompt.language import append_language_directive
@@ -237,7 +238,6 @@ def _is_citable_tool(name: str) -> bool:
# 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
@@ -249,13 +249,11 @@ DEFAULT_REPHRASE_MAX_ITERATIONS = (
)
DEFAULT_REPHRASE_MAX_ROUNDS = 3
DEFAULT_REPHRASE_MAX_QUESTIONS_PER_ROUND = 3
# Per-stage token budgets moved to agents.yaml — see
# ``DEFAULT_RESEARCH_PARAMS`` in services.config.loader. agents.yaml owns
# every LLM budget; this module keeps only runtime behaviour (iteration
# caps, tool policy), which is main.yaml's half of the split.
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_REPORT_STEP_MAX_ATTEMPTS = 3
DEFAULT_INITIAL_SUBTOPICS = 5
DEFAULT_MAX_PARALLEL_TOPICS = 3
@@ -406,6 +404,7 @@ class ResearchPipeline:
# ``geogebra_analysis`` uses for the same reason, and retries are off by
# default: only a caller who knows its tools are flaky (rather than
# slow) should pay for a second attempt.
self._budgets = get_capability_params("research")
self.tool_timeout = max(
1,
_read_int(
@@ -769,7 +768,7 @@ class ResearchPipeline:
protocol=_PROTOCOL_REPHRASE,
client=client,
model=self.model,
completion_kwargs=self._completion_kwargs(DEFAULT_BLOCK_MAX_TOKENS),
completion_kwargs=self._completion_kwargs(self._budgets["block"]["max_tokens"]),
binding=self.binding,
tool_schemas=tool_schemas,
stream=stream,
@@ -844,7 +843,7 @@ class ResearchPipeline:
stream=stream,
stage="decomposing",
iter_meta=iter_meta,
max_tokens=DEFAULT_OUTLINE_MAX_TOKENS,
max_tokens=self._budgets["outline"]["max_tokens"],
eager_sub_trace=False,
)
return self._parse_outline(topic, step.text)
@@ -960,7 +959,7 @@ class ResearchPipeline:
protocol=_PROTOCOL_BLOCK,
client=client,
model=self.model,
completion_kwargs=self._completion_kwargs(DEFAULT_BLOCK_MAX_TOKENS),
completion_kwargs=self._completion_kwargs(self._budgets["block"]["max_tokens"]),
binding=self.binding,
tool_schemas=tool_schemas,
stream=stream,
@@ -1198,7 +1197,7 @@ class ResearchPipeline:
)
messages = self._build_system_user_messages(system_prompt, user_prompt)
try:
kwargs = self._completion_kwargs(DEFAULT_NOTE_MAX_TOKENS)
kwargs = self._completion_kwargs(self._budgets["note"]["max_tokens"])
response = await client.chat.completions.create(
model=self.model, messages=messages, stream=False, **kwargs
)
@@ -1514,7 +1513,7 @@ class ResearchPipeline:
stream=stream,
stage="reporting",
iter_meta=iter_meta,
max_tokens=DEFAULT_REPORT_OUTLINE_MAX_TOKENS,
max_tokens=self._budgets["report_outline"]["max_tokens"],
eager_sub_trace=False,
)
return self._parse_report_outline(topic, step.text, blocks)
@@ -1668,7 +1667,7 @@ class ResearchPipeline:
client=client,
label=self._t("labels.report_intro", default="Introduction"),
call_id_root="research-report-intro",
max_tokens=DEFAULT_REPORT_INTRO_MAX_TOKENS,
max_tokens=self._budgets["report_intro"]["max_tokens"],
extra_meta={
"research_status_key": "report_intro",
"report_part": "intro",
@@ -1711,7 +1710,7 @@ class ResearchPipeline:
client=client,
label=(f"{self._t('labels.report_section', default='Section')}: {section.title}"),
call_id_root=f"research-report-section-{section.id}",
max_tokens=DEFAULT_REPORT_SECTION_MAX_TOKENS,
max_tokens=self._budgets["report_section"]["max_tokens"],
extra_meta={
"research_status_key": "report_section",
"report_part": "section",
@@ -1755,7 +1754,7 @@ class ResearchPipeline:
client=client,
label=self._t("labels.report_conclusion", default="Conclusion"),
call_id_root="research-report-conclusion",
max_tokens=DEFAULT_REPORT_CONCLUSION_MAX_TOKENS,
max_tokens=self._budgets["report_conclusion"]["max_tokens"],
extra_meta={
"research_status_key": "report_conclusion",
"report_part": "conclusion",
@@ -2125,11 +2124,13 @@ class ResearchPipeline:
stream: StreamBus,
stage: str,
iter_meta: dict[str, Any],
max_tokens: int = DEFAULT_BLOCK_MAX_TOKENS,
max_tokens: int | None = None,
final_meta: dict[str, Any] | None = None,
eager_sub_trace: bool = True,
) -> LabeledStepResult:
"""Research-flavoured thin wrapper over :func:`run_labeled_step`."""
if max_tokens is None:
max_tokens = int(self._budgets["block"]["max_tokens"])
return await run_labeled_step(
client=client,
model=self.model,

View File

@@ -42,6 +42,7 @@ from deeptutor.runtime.agentic.messages import assistant_message_with_tool_calls
from deeptutor.runtime.agentic.tool_call_stream import ToolCallAccumulator
from deeptutor.runtime.registry.tool_registry import get_tool_registry
from deeptutor.runtime.stream_bus import StreamBus
from deeptutor.services.config.loader import get_capability_params
from deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargs
from deeptutor.services.llm import stream as llm_stream
from deeptutor.services.llm.capabilities import threads_session_id
@@ -60,14 +61,23 @@ EXPLORE_SOURCE = "chat"
# finishes earlier by writing its investigation without a tool call. The last
# round runs with tools disabled so it is always forced to finish.
MAX_LOOP_ROUNDS = 5
LOOP_MAX_TOKENS = 2000
def _budgets() -> dict:
"""This capability's per-stage token budgets, from agents.yaml.
Read at the call site rather than at import: a user who edits
``capabilities.explore_context`` should not have to restart the process,
and both call sites here run once per turn at most.
"""
return get_capability_params("explore_context")
# Single-pass fallback budgets. The same sources remain reachable via
# ``read_source`` in the loop path, so clipping here only bounds the fallback.
MAX_SOURCES = 12
CHARS_PER_SOURCE = 8000
TOTAL_CHARS = 48000
BRIEFING_MAX_TOKENS = 1400
# Maps a manifest source-id prefix to a human kind label (en, zh).
_KIND_BY_PREFIX: dict[str, tuple[str, str]] = {
@@ -278,7 +288,7 @@ class ContextExplorer:
**build_completion_kwargs(
temperature=0.2,
model=self.model,
max_tokens=LOOP_MAX_TOKENS,
max_tokens=_budgets()["loop"]["max_tokens"],
binding=self.binding,
reasoning_effort=self.reasoning_effort,
),
@@ -419,7 +429,7 @@ class ContextExplorer:
api_version=self.api_version,
binding=self.binding,
temperature=0.2,
**self._token_kwargs(BRIEFING_MAX_TOKENS),
**self._token_kwargs(_budgets()["briefing"]["max_tokens"]),
):
if not chunk:
continue

View File

@@ -293,30 +293,94 @@ DEFAULT_CHAT_PARAMS: dict[str, Any] = {
"responding": {"max_tokens": 8000},
}
# A capability that makes several different LLM calls cannot be described by
# one ``max_tokens``: the step that emits a whole JSON plan and the step that
# writes one paragraph need different room. ``chat`` has said so since it
# gained ``exploring``/``responding``; ``question`` and ``research`` said the
# same thing in module-level constants instead, where no user could reach them
# — which is how #1318 shipped a plan step budgeted below the capability's own
# 4096, and how ``capabilities.question.max_tokens`` came to govern exactly one
# of that capability's LLM calls (the follow-up agent) while five others
# ignored it.
#
# The rule these tables enforce: **agents.yaml owns every LLM budget**
# (temperature, max_tokens, per stage), **main.yaml owns runtime behaviour**
# (iteration caps, timeouts, retry policy, modes). A budget in main.yaml is a
# bug, not a style choice.
#
# Values here are the ones these pipelines shipped as constants, so adopting
# the table changes nothing until somebody edits agents.yaml. Stage names are
# the pipeline's own vocabulary — they are the key a user types.
DEFAULT_QUESTION_PARAMS: dict[str, Any] = {
"answering": {"max_tokens": 4000},
"planning": {"max_tokens": 6000},
"quiz_finish": {"max_tokens": 3000},
"repair": {"max_tokens": 2500},
"tool_summarizer": {"max_tokens": 800},
}
def get_chat_params() -> dict[str, Any]:
"""
Read ``capabilities.chat`` from agents.yaml with deep-merged defaults.
DEFAULT_RESEARCH_PARAMS: dict[str, Any] = {
"note": {"max_tokens": 1500},
"block": {"max_tokens": 6000},
"outline": {"max_tokens": 2000},
"report_outline": {"max_tokens": 2000},
"report_intro": {"max_tokens": 3000},
"report_section": {"max_tokens": 6000},
"report_conclusion": {"max_tokens": 3000},
}
Unlike :func:`get_agent_params`, the chat capability has per-stage
sub-sections (``exploring``, ``responding``), each with its own
``max_tokens``. A single ``temperature`` and round budget are shared
across the chat loop. Legacy keys from the targeting-era schema
(``max_iterations``, ``max_explore_rounds``, …) are filtered out.
DEFAULT_EXPLORE_CONTEXT_PARAMS: dict[str, Any] = {
"loop": {"max_tokens": 2000},
"briefing": {"max_tokens": 1400},
}
_STAGED_CAPABILITY_DEFAULTS: dict[str, dict[str, Any]] = {
"chat": DEFAULT_CHAT_PARAMS,
"question": DEFAULT_QUESTION_PARAMS,
"research": DEFAULT_RESEARCH_PARAMS,
"explore_context": DEFAULT_EXPLORE_CONTEXT_PARAMS,
}
def get_capability_params(capability: str) -> dict[str, Any]:
"""Read one capability's per-stage settings from agents.yaml.
Unlike :func:`get_agent_params` — which answers "what temperature and
ceiling does this module's :class:`BaseAgent` use" — this answers "what
does each *step* of this capability's pipeline get". Unknown keys in the
user's file are dropped rather than merged, so a legacy or misspelled
entry cannot smuggle a value into a stage that does not exist.
Returns:
dict: Deep-merged chat configuration. Always contains every stage key
from :data:`DEFAULT_CHAT_PARAMS` so callers can index without checks.
dict: the shipped defaults deep-merged with the user's overrides.
Every stage in the capability's default table is present, so callers
index without checks.
Raises:
KeyError: if ``capability`` has no staged defaults. Adding a stage
means adding it to the table above, which is the point: there is
one list of budgets, and it is this one.
"""
defaults = _STAGED_CAPABILITY_DEFAULTS[capability]
path = get_runtime_settings_dir(PROJECT_ROOT) / "agents.yaml"
cfg: dict[str, Any] = {}
if path.exists():
with open(path, encoding="utf-8") as f:
agents_config = yaml.safe_load(f) or {}
cfg = (agents_config.get("capabilities", {}) or {}).get("chat", {}) or {}
known_keys = set(DEFAULT_CHAT_PARAMS)
cfg = (agents_config.get("capabilities", {}) or {}).get(capability, {}) or {}
known_keys = set(defaults)
filtered_cfg = {key: value for key, value in cfg.items() if key in known_keys}
return _deep_merge(DEFAULT_CHAT_PARAMS, filtered_cfg)
return _deep_merge(defaults, filtered_cfg)
def get_chat_params() -> dict[str, Any]:
"""Read ``capabilities.chat`` from agents.yaml with deep-merged defaults.
Kept as its own name because the chat loop reads it on a hot path and
every caller already spells it this way; the behaviour is
:func:`get_capability_params` with ``"chat"``.
"""
return get_capability_params("chat")
__all__ = [

View File

@@ -49,6 +49,10 @@ logger = logging.getLogger(__name__)
# kept for tests / call sites that reference the defaults directly.
RESPONSE_TYPE = "Multiple Paragraphs"
DEFAULT_COMMUNITY_LEVEL = 2
# Deliberately not in agents.yaml with the other budgets: this is the
# reachability probe, not a generation call a reader ever sees. It asks a
# model to prove it answers at all, and a user tuning it would only be
# able to make the health check lie.
PROBE_MAX_TOKENS = 1024
PROBE_TIMEOUT_SECONDS = 25
EMBEDDING_PROBE_TEXT = "DeepTutor GraphRAG embedding compatibility test"

View File

@@ -10,6 +10,11 @@ from pathlib import Path
import yaml
from deeptutor.services.config.loader import (
DEFAULT_EXPLORE_CONTEXT_PARAMS,
DEFAULT_QUESTION_PARAMS,
DEFAULT_RESEARCH_PARAMS,
)
from deeptutor.services.path_service import get_path_service
# Initialize logger for setup operations
@@ -26,6 +31,7 @@ DEFAULT_INTERFACE_SETTINGS = {
},
}
DEFAULT_MAIN_SETTINGS = {
"system": {
"language": "en",
@@ -100,6 +106,20 @@ DEFAULT_AGENTS_SETTINGS = {
},
}
# Per-stage budgets are seeded from the same tables the pipelines read, so a
# fresh agents.yaml shows every knob that governs a run and Settings can edit
# it. Derived rather than copied: two lists of the same numbers is how a
# default and its seed drift apart, which is the shape of #1316.
for _capability, _stages in (
("question", DEFAULT_QUESTION_PARAMS),
("research", DEFAULT_RESEARCH_PARAMS),
("explore_context", DEFAULT_EXPLORE_CONTEXT_PARAMS),
):
_section = DEFAULT_AGENTS_SETTINGS["capabilities"].setdefault(_capability, {})
for _stage, _values in _stages.items():
_section.setdefault(_stage, dict(_values))
del _capability, _stages, _section, _stage, _values
def _get_setup_logger():
"""Get logger for setup operations"""

View File

@@ -805,15 +805,16 @@ def test_runtime_config_overrides_max_iterations_and_summarizer_tokens() -> None
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,
)
from deeptutor.agents.question.pipeline import DEFAULT_MAX_EXPLORE_ITERATIONS
from deeptutor.services.config.loader import DEFAULT_QUESTION_PARAMS
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
assert (
pipeline.tool_summarizer_max_tokens
== DEFAULT_QUESTION_PARAMS["tool_summarizer"]["max_tokens"]
)
def test_build_question_runtime_config_reads_capabilities_section() -> None:

View File

@@ -0,0 +1,126 @@
"""Every LLM budget is addressable from agents.yaml, and only from there.
``question`` and ``research`` used to keep their per-step budgets as module
constants, so ``capabilities.question.max_tokens`` governed exactly one of
that capability's six LLM calls (the follow-up agent) and a user who wanted a
longer plan had to edit source. That is how #1318 shipped a plan step budgeted
below the capability's own ceiling.
These tests pin the two properties that keep it fixed: the stage a pipeline
asks for exists, and the number it gets is the one the project shipped.
"""
from __future__ import annotations
from pathlib import Path
from typing import Any
import pytest
import yaml
from deeptutor.services.config import loader as loader_module
from deeptutor.services.config.loader import (
_STAGED_CAPABILITY_DEFAULTS,
get_capability_params,
)
# The values these pipelines ran on before the budgets moved into agents.yaml.
# Written out rather than derived: a test that recomputes the table from the
# table cannot notice the table changing. An intentional retune edits this map
# in the same commit and says why.
SHIPPED_BUDGETS: dict[str, dict[str, int]] = {
"question": {
"answering": 4000,
"planning": 6000,
"quiz_finish": 3000,
"repair": 2500,
"tool_summarizer": 800,
},
"research": {
"note": 1500,
"block": 6000,
"outline": 2000,
"report_outline": 2000,
"report_intro": 3000,
"report_section": 6000,
"report_conclusion": 3000,
},
"explore_context": {
"loop": 2000,
"briefing": 1400,
},
}
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
@pytest.mark.parametrize("capability", sorted(SHIPPED_BUDGETS))
def test_defaults_are_the_budgets_the_pipelines_shipped_with(capability: str) -> None:
"""Moving a budget into config must not quietly change it."""
table = _STAGED_CAPABILITY_DEFAULTS[capability]
actual = {stage: values["max_tokens"] for stage, values in table.items()}
assert actual == SHIPPED_BUDGETS[capability]
def test_every_staged_capability_seeds_every_stage_it_defines() -> None:
"""A default nobody seeds is a default no user can discover or edit.
``get_agent_params`` reads the shipped settings as its per-module defaults,
so a stage present in code but absent from the seed is exactly the #1316
shape: a number that governs a run and lives nowhere the user can reach.
"""
from deeptutor.services.setup.init import DEFAULT_AGENTS_SETTINGS
seeded = DEFAULT_AGENTS_SETTINGS["capabilities"]
for capability, stages in SHIPPED_BUDGETS.items():
section = seeded.get(capability)
assert isinstance(section, dict), f"{capability} is not seeded at all"
for stage, max_tokens in stages.items():
assert section.get(stage) == {"max_tokens": max_tokens}, (
f"{capability}.{stage} is missing from the shipped agents.yaml"
)
def test_a_user_override_reaches_the_stage(tmp_path: Path, monkeypatch) -> None:
project_root = _write_agents_yaml(
tmp_path,
{"capabilities": {"question": {"planning": {"max_tokens": 20000}}}},
)
monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_capability_params("question")
assert params["planning"]["max_tokens"] == 20000
# Stages the user did not mention keep their shipped value rather than
# disappearing — callers index without checks.
assert params["repair"]["max_tokens"] == SHIPPED_BUDGETS["question"]["repair"]
def test_unknown_keys_in_the_users_file_are_dropped(tmp_path: Path, monkeypatch) -> None:
"""A misspelled stage must not become a stage.
Merging it in would give a silent no-op that reads like a setting, which
is the failure this whole seam exists to remove.
"""
project_root = _write_agents_yaml(
tmp_path,
{"capabilities": {"question": {"planing": {"max_tokens": 1}, "max_tokens": 4096}}},
)
monkeypatch.setattr(loader_module, "PROJECT_ROOT", project_root)
params = get_capability_params("question")
assert "planing" not in params
# ``max_tokens`` at the capability level belongs to get_agent_params, not
# to the staged table; it must not leak in as a pseudo-stage either.
assert "max_tokens" not in params
assert params["planning"]["max_tokens"] == SHIPPED_BUDGETS["question"]["planning"]
def test_an_unstaged_capability_raises_rather_than_inventing_a_budget() -> None:
"""Adding a stage means adding it to the table — that is the point."""
with pytest.raises(KeyError):
get_capability_params("no_such_capability")