Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat(search): give fetch summaries a larger separate input budget (#7313)

LearningCircuit4c7468c8177c
diff --git a/changelog.d/+fetch-content-max-length.feature.md b/changelog.d/+fetch-content-max-length.feature.md
index 074ac45ce5..b66b247cdf 100644
--- a/changelog.d/+fetch-content-max-length.feature.md
+++ b/changelog.d/+fetch-content-max-length.feature.md
@@ -1 +1 @@
-Added a `search.fetch.content_max_length` setting (Fetch Content Max Length, default 10000, range 1000–50000) below the fetch mode setting. It caps fetched page text per URL before it is returned directly (`full` mode) or sent to the LLM for focused extraction (`summary_focus` / `summary_focus_query`).
+Added a `search.fetch.content_max_length` setting (Fetch Full-Text Max Length, default 10000, range 1000–50000) below the fetch mode setting. It caps fetched page text per URL that is returned directly in `full` mode. The `summary_focus` and `summary_focus_query` modes use the separate `search.fetch.summary_input_max_length` budget instead.
diff --git a/changelog.d/+fetch-summary-input-budget.feature.md b/changelog.d/+fetch-summary-input-budget.feature.md
new file mode 100644
index 0000000000..2250cc83b1
--- /dev/null
+++ b/changelog.d/+fetch-summary-input-budget.feature.md
@@ -0,0 +1 @@
+Give focused fetch summaries a separate 500,000-character input budget (`search.fetch.summary_input_max_length`), configurable to any positive integer with no fixed upper setting limit. Full-text fetches keep their separate 10,000-character default. Unless the research model uses a cloud provider with unrestricted context, page text is also cut so the whole summary prompt fits the model's context window minus its reply allowance (`llm.max_tokens`, capped at 80% of the window), estimated at 4 characters per token: 16,384 characters for the default 20,480-token local window. The window is the one the research model was built with, after any per-run provider override: the local window for Ollama, LM Studio and llama.cpp, or the declared cloud window when unrestricted context is off. OpenAI- and Anthropic-compatible endpoints with unrestricted context, which may be local or private, use the local window too. Their summary calls also cap the requested output to the reserved allowance without changing the shared research model. With unrestricted cloud context (the default), a summary fetch on a long page can now send up to 50 times more text than the previous 10,000-character cap, which raises token cost and latency; lower the new setting to limit this. An invalid value for the setting or its `LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH` override makes summary fetches fail with an error naming both; an invalid override is also logged as a warning, and settings pages and research start keep working.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 74100ba1c7..329324102e 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -654,9 +654,10 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.zenodo.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_ZENODO_USE_IN_AUTO_SEARCH` | `false` | Include Zenodo in auto search mode | SEARCH |
| `search.engine.web.zenodo.weaknesses` | `LDR_SEARCH_ENGINE_WEB_ZENODO_WEAKNESSES` | ``["research focus", "variable quality", "metadata only"]`` | Limitations of Zenodo. | SEARCH |
| `search.favorites` | `LDR_SEARCH_FAVORITES` | ``["arxiv", "searxng", "library", "openalex"]`` | List of favorite search engine IDs that appear at the top of the dropdown. Edit as JSON array, e.g. ["arxiv", "brave"] | SEARCH |
-| `search.fetch.content_max_length` | `LDR_SEARCH_FETCH_CONTENT_MAX_LENGTH` | `10000` | Maximum page text (in characters) passed to the fetch_content and fetch_archive tools per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled. | SEARCH |
+| `search.fetch.content_max_length` | `LDR_SEARCH_FETCH_CONTENT_MAX_LENGTH` | `10000` | Maximum page text (in characters) returned directly to the research agent per URL in 'full' fetch mode. Applies to HTTP pages and local library documents. Default is 10000, with a range of 1000 to 50000. Summary modes use Fetch Summary Input Max Length instead. Applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools. | SEARCH |
| `search.fetch.max_per_topic` | `LDR_SEARCH_FETCH_MAX_PER_TOPIC` | `2` | Maximum number of page content fetches (fetch_content and fetch_archive calls sharing one budget) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets). | SEARCH |
| `search.fetch.mode` | `LDR_SEARCH_FETCH_MODE` | `summary_focus_query` | Controls the LangGraph agent's fetch_content and fetch_archive tools. 'summary_focus_query' (default) asks the LLM to extract only spans relevant to a focus question the agent supplies per call AND the original research query, so vague focus can be disambiguated — keeps small-model context clean. 'summary_focus' is the same but uses only the per-call focus question. 'full' returns the entire extracted page text (legacy behavior; can flood small-model context with boilerplate/metadata and degrade benchmark accuracy). 'disabled' removes both tools entirely so the agent works from search snippets only — useful for diagnosing whether fetching is helping or hurting accuracy. Note: This setting applies exclusively to the langgraph-agent strategy; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled. | SEARCH |
+| `search.fetch.summary_input_max_length` | `LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH` | `500000` | Maximum page text (in characters) sent to the separate summarization step per URL in 'summary_focus' and 'summary_focus_query' fetch modes. Applies to HTTP pages and local library documents; the research agent receives the extracted summary. Default is 500000. Accepts any positive integer, with no fixed upper setting limit. Unless the research model uses a cloud provider with Use Unrestricted Cloud Context Window on, page text is also cut so the whole summarization prompt fits the model's context window minus its reply allowance, estimated at 4 characters per token; at least one character of page text is always kept. The reply allowance is Max Tokens, capped at 80% of the window, or the full 80% when Max Tokens is unset or not supported. For example, a 20480-token window with the default Max Tokens leaves 4096 tokens, or 16384 characters, for the prompt. The window is Local Provider Context Window Size for Ollama, LlamaCpp and LM Studio, and Cloud Provider Context Window Limit for other providers when Use Unrestricted Cloud Context Window is off. LDR sends the local window to Ollama only, so set it to the context length of your LlamaCpp or LM Studio server. With Use Unrestricted Cloud Context Window on, an OpenAI- or Anthropic-compatible endpoint, a provider LDR does not ship and a model LDR did not build use Local Provider Context Window Size instead. For compatible endpoints with Max Tokens supported and set, the summary call also caps requested output to the reserved allowance without changing the research model. Invalid managed context-window or reply settings must be corrected before fetching. Chinese, Japanese and other text that uses more tokens per character can still exceed the window. With unrestricted cloud context, this budget is sent as configured; larger inputs increase latency and cost. Full-text mode uses Fetch Full-Text Max Length instead. Applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools. | SEARCH |
| `search.final_max_results` | `LDR_SEARCH_FINAL_MAX_RESULTS` | `100` | Maximum unique sources to include in the final research output. Applied in pipeline/source-based strategies once after all search iterations complete, deduplicating and filtering across all accumulated results. Note: Autonomous agent strategies (like langgraph-agent) manage context autonomously and do not cap final results. | SEARCH |
| `search.iterations` | `LDR_SEARCH_ITERATIONS` | `3` | Number of search-and-refine cycles to run. Each iteration generates follow-up questions based on previous results to progressively deepen the research. More iterations yield better coverage but increase search and LLM API usage. | SEARCH |
| `search.journal_reputation.enable_llm_scoring` | `LDR_SEARCH_JOURNAL_REPUTATION_ENABLE_LLM_SCORING` | `false` | Enable Tier 4 LLM journal scoring via SearXNG. When disabled (default), only bundled data (OpenAlex, DOAJ, predatory lists) is used for scoring journal reputation. Tier 4 adds significant latency (1 SearXNG search + 1 LLM call per unknown journal) and only helps for journals outside the 217K-row reference DB. Requires SearXNG to be available. | SEARCH |
diff --git a/src/local_deep_research/advanced_search_system/tools/archive.py b/src/local_deep_research/advanced_search_system/tools/archive.py
index 54afc530f5..8e90e45049 100644
--- a/src/local_deep_research/advanced_search_system/tools/archive.py
+++ b/src/local_deep_research/advanced_search_system/tools/archive.py
@@ -20,7 +20,10 @@ from .fetch import (
FETCH_MODES,
_check_and_record_fetch,
_enforce_url_policy,
+ _read_content_max_length_setting,
_read_max_fetches_setting,
+ _read_summary_input_max_length_setting,
+ _summary_invocation_budget,
build_fetch_tool,
)
@@ -93,6 +96,14 @@ def build_archive_fetch_tool(
# gate the API before reserving the shared quota slot.
_enforce_url_policy(url, egress_context)
_enforce_url_policy(AVAILABLE_API, egress_context)
+ # Refuse an invalid configured budget before archive lookup or
+ # reservation of a shared fetch slot. The delegated page tool
+ # applies the same budget to the selected capture.
+ if mode == "full":
+ _read_content_max_length_setting(settings_snapshot)
+ else:
+ _read_summary_input_max_length_setting(settings_snapshot)
+ _summary_invocation_budget(model, settings_snapshot)
error, count = _check_and_record_fetch(
collector, limit, subagent_id=subagent_id
)
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
index 357cd39210..be82c7743f 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
@@ -40,7 +40,10 @@ from local_deep_research.security import (
sanitize_error_for_agent,
)
from local_deep_research.settings.exceptions import SettingsValueError
-from local_deep_research.utilities.type_utils import unwrap_setting
+from local_deep_research.utilities.type_utils import (
+ to_positive_int,
+ unwrap_setting,
+)
from local_deep_research.utilities.llm_utils import invoke_llm_sync
from .library_resolver import (
@@ -56,13 +59,29 @@ from .prompts import SUMMARY_FOCUS_PROMPT, SUMMARY_FOCUS_QUERY_PROMPT
# orchestration.
CONTENT_FETCH_TIMEOUT = 30
CONTENT_MAX_LENGTH = 10_000
+SUMMARY_INPUT_MAX_LENGTH = 500_000
# Bounds for the user-configurable ``search.fetch.content_max_length``
-# setting (see default_settings.json). The fetch tool truncates page text
-# to this length BEFORE summary_focus / summary_focus_query extraction.
+# setting in full mode (see default_settings.json). Summary modes have a
+# separate input budget with no fixed upper setting limit.
CONTENT_MAX_LENGTH_MIN = 1_000
CONTENT_MAX_LENGTH_MAX = 50_000
+# The summary prompt limit is counted in characters, estimated at four per
+# token. That rate fits English-like text. Text that needs more tokens per
+# character, such as Chinese or Japanese or long runs of digits, can still
+# exceed the window.
+SUMMARY_INPUT_CHARS_PER_TOKEN = 4
+
+# Fixed text: it never echoes the configured value. It names the
+# environment variable because an override there takes precedence and is
+# not editable in the web UI.
+SUMMARY_INPUT_MAX_LENGTH_ERROR = (
+ "search.fetch.summary_input_max_length must be a positive integer. "
+ "Check the setting and any LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH "
+ "environment override."
+)
+
FETCH_MODES = (
"disabled",
@@ -150,9 +169,9 @@ def _read_content_max_length_setting(
) -> int:
"""Read the ``search.fetch.content_max_length`` setting from a settings snapshot.
- The value caps page text (HTTP or local library document) BEFORE it is
- returned directly (``full`` mode) or sent to the LLM for focused
- extraction (``summary_focus`` / ``summary_focus_query``).
+ The value caps page text (HTTP or local library document) before it is
+ returned directly in ``full`` mode. Summary modes use their own input
+ budget instead.
Returns the configured length clamped to
[CONTENT_MAX_LENGTH_MIN, CONTENT_MAX_LENGTH_MAX]. Missing, non-positive,
@@ -196,6 +215,169 @@ def _read_content_max_length_setting(
return default
+def _read_summary_input_max_length_setting(
+ settings_snapshot: dict | None,
+) -> int:
+ """Read the positive summary-input character budget without an upper clamp.
+
+ Missing settings use the generous default. Invalid configured values
+ raise rather than silently increasing a user's intended budget. Settings
+ loads keep an invalid value, including an invalid environment override,
+ unchanged, so this per-fetch read is where it fails. Zero is not an
+ unlimited sentinel: HTTP and library slicing treat it differently.
+ """
+ from local_deep_research.config.thread_settings import (
+ get_setting_from_snapshot,
+ )
+
+ value = unwrap_setting(
+ get_setting_from_snapshot(
+ "search.fetch.summary_input_max_length",
+ default=SUMMARY_INPUT_MAX_LENGTH,
+ settings_snapshot=settings_snapshot,
+ )
+ )
+ try:
+ return to_positive_int(value)
+ except ValueError:
+ pass
+ raise ValueError(SUMMARY_INPUT_MAX_LENGTH_ERROR)
+
+
+def _built_model_provider(
+ model: Any, settings_snapshot: dict | None
+) -> tuple[str | None, dict | None]:
+ """Return the provider and settings ``get_llm`` built *model* with.
+
+ ``get_llm`` records both on the ``ProcessingLLMWrapper`` it returns,
+ after any per-run provider override, so they describe the model that
+ runs. Any other model has no known provider (``None``), and the
+ tool's own snapshot stands in for its settings.
+ """
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+ from local_deep_research.llm.providers.base import normalize_provider
+
+ if not isinstance(model, ProcessingLLMWrapper):
+ return None, settings_snapshot
+ provider = getattr(model, "_provider", None)
+ snapshot = getattr(model, "_settings_snapshot", None)
+ if not isinstance(snapshot, dict):
+ snapshot = settings_snapshot
+ # Registry overrides can use a built-in provider's name for an arbitrary
+ # shared instance or factory. Its invocation contract and context are not
+ # those of the provider LDR builds, even though get_llm wraps it.
+ if model._owns_llm is False:
+ return None, snapshot
+ if not isinstance(provider, str) or not provider.strip():
+ return None, snapshot
+ return normalize_provider(provider.strip()), snapshot
+
+
+def _summary_invocation_budget(
+ model: Any, settings_snapshot: dict | None
+) -> tuple[int | None, dict[str, int]]:
+ """Return the summary prompt character limit and per-call model options.
+
+ ``None`` means no limit: the model was built for a cloud provider with
+ unrestricted context, which enforces its own limit.
+
+ Otherwise the limit is the context window minus the response
+ allowance, in tokens, at ``SUMMARY_INPUT_CHARS_PER_TOKEN`` characters
+ per token. The whole prompt counts, so the page gets what its
+ instructions, focus, query, title and URL leave.
+
+ The window is resolved with ``get_context_window_for_provider``, as
+ the built-in providers' builds resolve it, from the provider and
+ settings ``get_llm`` used (see ``_built_model_provider``):
+
+ - Ollama: ``llm.local_context_window_size``, sent as ``num_ctx``.
+ - LM Studio and llama.cpp: ``llm.local_context_window_size``. It caps
+ their ``max_tokens`` but is not sent; each server keeps its own
+ context length.
+ - Any other provider: ``llm.context_window_size`` when
+ ``llm.context_window_unrestricted`` is off.
+
+ When that resolves no window and the provider is not a known cloud
+ provider (the egress policy's ``_CLOUD_LLM_PROVIDERS``),
+ ``llm.local_context_window_size`` is assumed. That covers an
+ OpenAI- or Anthropic-compatible endpoint, which may be local or
+ private, a provider LDR does not ship, and a model ``get_llm`` did not
+ build. A window that is unusable or below 1 falls back to that local
+ window, then to ``DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE``.
+
+ The response allowance is ``compute_max_tokens`` for that window:
+ ``llm.max_tokens``, capped at ``MAX_TOKENS_CONTEXT_SHARE`` (80%) of
+ it, which is the ``max_tokens`` OpenAI-compatible and Anthropic builds
+ request. When that yields no positive value, for example with
+ ``llm.supports_max_tokens`` off, the full 80% share is kept. Ollama is
+ sent no ``max_tokens``, but its reply must fit in ``num_ctx`` too, so
+ it keeps the same allowance.
+
+ An unrestricted compatible endpoint's existing model may request more
+ output than the assumed local window permits. Pass the capped allowance
+ through the existing model wrappers for this summary call only; do not
+ mutate the shared model or bind around its rate limiter.
+ """
+ from local_deep_research.config.thread_settings import (
+ NoSettingsContextError,
+ )
+ from local_deep_research.llm.providers._helpers import (
+ DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE,
+ MAX_TOKENS_CONTEXT_SHARE,
+ compute_max_tokens,
+ get_context_window_for_provider,
+ get_local_context_window,
+ )
+ from local_deep_research.security.egress.policy import (
+ _CLOUD_LLM_PROVIDERS,
+ )
+
+ unusable = (TypeError, ValueError, OverflowError, NoSettingsContextError)
+ provider, snapshot = _built_model_provider(model, settings_snapshot)
+ try:
+ window = get_context_window_for_provider(
+ provider, settings_snapshot=snapshot
+ )
+ except SettingsValueError:
+ raise
+ except unusable:
+ window = None
+ else:
+ if window is None and provider in _CLOUD_LLM_PROVIDERS:
+ return None, {}
+ local_window_assumed = window is None or window < 1
+ if local_window_assumed:
+ try:
+ window = get_local_context_window(snapshot)
+ except SettingsValueError:
+ raise
+ except unusable:
+ window = None
+ if window is None or window < 1:
+ window = DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE
+
+ try:
+ allowance = compute_max_tokens(
+ settings_snapshot=snapshot, context_window_size=window
+ )
+ except SettingsValueError:
+ raise
+ except unusable:
+ allowance = None
+ invocation_kwargs = {}
+ if not isinstance(allowance, int) or allowance < 1:
+ allowance = int(window * MAX_TOKENS_CONTEXT_SHARE)
+ elif local_window_assumed and provider in (
+ "openai_endpoint",
+ "anthropic_endpoint",
+ ):
+ invocation_kwargs["max_tokens"] = allowance
+ return (
+ max(1, (window - allowance) * SUMMARY_INPUT_CHARS_PER_TOKEN),
+ invocation_kwargs,
+ )
+
+
_warned_collector_missing_fetch_cap = False
@@ -1069,6 +1251,21 @@ def _make_summary_fetch_tool(
archive_metadata = source_metadata
try:
+ prompt_char_limit = None
+ invocation_kwargs = {}
+ if content_max_length is not None:
+ page_budget = content_max_length
+ else:
+ # Validated first, so an invalid budget fails before the
+ # window lookup and any fetch.
+ page_budget = _read_summary_input_max_length_setting(
+ settings_snapshot
+ )
+ prompt_char_limit, invocation_kwargs = (
+ _summary_invocation_budget(model, settings_snapshot)
+ )
+ if prompt_char_limit is not None:
+ page_budget = min(page_budget, prompt_char_limit)
archive_metadata, archive_guard = _archive_fetch_context(
url, collector, source_metadata, url_guard
)
@@ -1082,7 +1279,7 @@ def _make_summary_fetch_tool(
max_fetches=limit if record_fetch else None,
subagent_id=subagent_id,
content_cache=content_cache,
- content_max_length=content_max_length,
+ content_max_length=page_budget,
url_guard=archive_guard,
source_metadata=archive_metadata,
availability=availability,
@@ -1126,9 +1323,22 @@ def _make_summary_fetch_tool(
if use_query:
fmt_kwargs["overall_query"] = overall_query
prompt = template.format(**fmt_kwargs)
+ if (
+ prompt_char_limit is not None
+ and len(prompt) > prompt_char_limit
+ ):
+ # Cut the page tail so the whole prompt fits. At least one
+ # character is kept, so a window too small for the prompt's
+ # own text still overflows.
+ excess = len(prompt) - prompt_char_limit
+ content = content[: max(1, len(content) - excess)]
+ fmt_kwargs["content"] = content
+ prompt = template.format(**fmt_kwargs)
try:
- summary_msg = invoke_llm_sync(model, prompt)
+ summary_msg = invoke_llm_sync(
+ model, prompt, **invocation_kwargs
+ )
summary = getattr(
summary_msg, "content", str(summary_msg)
).strip()
@@ -1245,6 +1455,17 @@ def build_fetch_tool(
JS-rendering toggle can be read on a worker thread (where
``threading.local`` context does not propagate).
+ ``content_max_length`` explicitly overrides the page-text budget in
+ any mode, without a context-window limit. Otherwise, ``full`` reads
+ ``search.fetch.content_max_length`` and summary modes read
+ ``search.fetch.summary_input_max_length``. Unless *model* was built
+ for a cloud provider with unrestricted context, summary modes then cut
+ the page text so the whole extraction prompt fits the model's context
+ window minus its response allowance, estimated at four characters per
+ token (see ``_summary_invocation_budget``). That budget limits only the
+ separate extraction prompt, not the tool's summary returned to the
+ research agent.
+
``egress_context`` is captured by the closure so the per-call URL
can be policy-gated; when ``None``, no policy enforcement runs
(preserves legacy non-LangGraph callers).
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 8a93818775..b70429bc86 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -1028,11 +1028,11 @@
},
"search.fetch.content_max_length": {
"category": "search_parameters",
- "description": "Maximum page text (in characters) passed to the fetch_content and fetch_archive tools per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
+ "description": "Maximum page text (in characters) returned directly to the research agent per URL in 'full' fetch mode. Applies to HTTP pages and local library documents. Default is 10000, with a range of 1000 to 50000. Summary modes use Fetch Summary Input Max Length instead. Applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools.",
"editable": true,
"max_value": 50000,
"min_value": 1000,
- "name": "Fetch Content Max Length",
+ "name": "Fetch Full-Text Max Length",
"options": null,
"step": 500,
"type": "SEARCH",
@@ -1040,6 +1040,20 @@
"value": 10000,
"visible": true
},
+ "search.fetch.summary_input_max_length": {
+ "category": "search_parameters",
+ "description": "Maximum page text (in characters) sent to the separate summarization step per URL in 'summary_focus' and 'summary_focus_query' fetch modes. Applies to HTTP pages and local library documents; the research agent receives the extracted summary. Default is 500000. Accepts any positive integer, with no fixed upper setting limit. Unless the research model uses a cloud provider with Use Unrestricted Cloud Context Window on, page text is also cut so the whole summarization prompt fits the model's context window minus its reply allowance, estimated at 4 characters per token; at least one character of page text is always kept. The reply allowance is Max Tokens, capped at 80% of the window, or the full 80% when Max Tokens is unset or not supported. For example, a 20480-token window with the default Max Tokens leaves 4096 tokens, or 16384 characters, for the prompt. The window is Local Provider Context Window Size for Ollama, LlamaCpp and LM Studio, and Cloud Provider Context Window Limit for other providers when Use Unrestricted Cloud Context Window is off. LDR sends the local window to Ollama only, so set it to the context length of your LlamaCpp or LM Studio server. With Use Unrestricted Cloud Context Window on, an OpenAI- or Anthropic-compatible endpoint, a provider LDR does not ship and a model LDR did not build use Local Provider Context Window Size instead. For compatible endpoints with Max Tokens supported and set, the summary call also caps requested output to the reserved allowance without changing the research model. Invalid managed context-window or reply settings must be corrected before fetching. Chinese, Japanese and other text that uses more tokens per character can still exceed the window. With unrestricted cloud context, this budget is sent as configured; larger inputs increase latency and cost. Full-text mode uses Fetch Full-Text Max Length instead. Applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools.",
+ "editable": true,
+ "max_value": null,
+ "min_value": 1,
+ "name": "Fetch Summary Input Max Length",
+ "options": null,
+ "step": 1,
+ "type": "SEARCH",
+ "ui_element": "number",
+ "value": 500000,
+ "visible": true
+ },
"search.fetch.max_per_topic": {
"category": "search_parameters",
"description": "Maximum number of page content fetches (fetch_content and fetch_archive calls sharing one budget) allowed per subagent (and lead agent) per topic/section in autonomous agent strategies (like langgraph-agent). Prevents agents from exhausting their recursion/turn budget on page fetches instead of searching and reasoning. Set to 0 for unlimited fetches (only capped by agent recursion limit). Default is 2 (subagents typically need at most 1-2 targeted page fetches to supplement search snippets; a conservative per-agent cap prevents runaway fetches without starving parallel subtopics or consuming entire turn budgets).",
diff --git a/src/local_deep_research/llm/providers/_helpers.py b/src/local_deep_research/llm/providers/_helpers.py
index 510a550068..d406711c3f 100644
--- a/src/local_deep_research/llm/providers/_helpers.py
+++ b/src/local_deep_research/llm/providers/_helpers.py
@@ -15,6 +15,9 @@ from ...settings.exceptions import SettingsValueError
DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE = 8192
DEFAULT_CLOUD_CONTEXT_WINDOW_SIZE = 128000
LOCAL_PROVIDERS = ("ollama", "llamacpp", "lmstudio")
+# compute_max_tokens caps llm.max_tokens at this share of a known context
+# window, which leaves the rest of the window for the prompt.
+MAX_TOKENS_CONTEXT_SHARE = 0.8
# ``llm.request_timeout`` is a *per-network-operation* bound, not a cap on
# the total wall-clock duration of a response. httpx (which every provider
@@ -47,6 +50,22 @@ MAX_MAX_RETRIES: Final = 5
MODEL_DISCOVERY_TIMEOUT_SECONDS: Final = 30
+def get_local_context_window(settings_snapshot=None):
+ """Resolve ``llm.local_context_window_size``, the local providers' window."""
+ from ...config.thread_settings import get_setting_from_snapshot
+
+ window_size = get_setting_from_snapshot(
+ "llm.local_context_window_size",
+ DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE,
+ settings_snapshot=settings_snapshot,
+ )
+ return (
+ int(window_size)
+ if window_size is not None
+ else DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE
+ )
+
+
def get_context_window_for_provider(provider_type, settings_snapshot=None):
"""Resolve effective context window size for a provider.
@@ -58,16 +77,7 @@ def get_context_window_for_provider(provider_type, settings_snapshot=None):
from ...config.thread_settings import get_setting_from_snapshot
if provider_type in LOCAL_PROVIDERS:
- window_size = get_setting_from_snapshot(
- "llm.local_context_window_size",
- DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE,
- settings_snapshot=settings_snapshot,
- )
- return (
- int(window_size)
- if window_size is not None
- else DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE
- )
+ return get_local_context_window(settings_snapshot)
use_unrestricted = get_setting_from_snapshot(
"llm.context_window_unrestricted",
True,
@@ -128,7 +138,9 @@ def compute_max_tokens(
return None
max_tokens = int(raw)
if context_window_size is not None:
- max_tokens = min(max_tokens, int(context_window_size * 0.8))
+ max_tokens = min(
+ max_tokens, int(context_window_size * MAX_TOKENS_CONTEXT_SHARE)
+ )
return max_tokens
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index 048f9dc86a..2950ab9d84 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -17,7 +17,7 @@ from .. import defaults
from ..__version__ import __version__ as package_version
from ..database.models import Setting, SettingType
from ..utilities.sql_utils import escape_like
-from ..utilities.type_utils import to_bool
+from ..utilities.type_utils import to_bool, to_positive_int
from ..web.models.settings import (
AppSetting,
BaseSetting,
@@ -243,6 +243,12 @@ def validate_imported_setting_value(
Returns ``None`` when the value is acceptable, or a human-readable
reason string when it is not.
"""
+ if key == "search.fetch.summary_input_max_length":
+ try:
+ to_positive_int(value)
+ except ValueError:
+ return "Value must be a positive integer"
+
ui_element = default_meta.get("ui_element")
if (
not isinstance(ui_element, str)
@@ -553,7 +559,8 @@ def get_typed_setting_value(
this setting before reading from the DB.
Returns:
- The value of the setting.
+ The typed value. The separate fetch-summary budget preserves an
+ invalid value, with a warning, until a summary fetch rejects it.
Raises:
SettingsValueError: The selected value cannot be converted, or its
@@ -575,6 +582,27 @@ def get_typed_setting_value(
setting_type = UI_ELEMENT_TO_SETTING_TYPE[ui_element]
if env_value is not None:
value = env_value
+ if key == "search.fetch.summary_input_max_length":
+ # This exact positive integer is validated again before a summary
+ # fetch. Keep a malformed budget visible without blocking unrelated
+ # research modes or the settings page used to repair it. All other
+ # settings and unsupported UI types retain the strict read contract.
+ try:
+ return to_positive_int(value)
+ except ValueError:
+ pass
+ location = (
+ f"LDR_{'_'.join(key.split('.')).upper()}"
+ if env_value is not None
+ else f"Setting {key}"
+ )
+ logger.warning(
+ "{} must be a positive integer (value omitted). Summary-mode "
+ "fetches will fail until it is corrected.",
+ location,
+ )
+ return value
+
if value is None:
return default
try:
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index 668fa0d2e9..a8d83d1085 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -26,10 +26,10 @@ __all__ = [
]
-def invoke_llm_sync(llm: Any, prompt: Any) -> Any:
+def invoke_llm_sync(llm: Any, prompt: Any, **kwargs: Any) -> Any:
"""Invoke an LLM on the synchronous client (#5854).
- This is deliberately a plain ``llm.invoke(prompt)`` and starts no
+ This is deliberately a plain ``llm.invoke(prompt, **kwargs)`` and starts no
event loop: langchain's cached ``httpx.AsyncClient`` is bound to the
loop that first used it, so bridging a sync caller onto ``ainvoke``
with a throwaway loop double-sends or hard-fails from the second call
@@ -43,12 +43,11 @@ def invoke_llm_sync(llm: Any, prompt: Any) -> Any:
Returns the RAW response object, so each caller's existing parsing
(``get_llm_response_text`` / ``.content`` / ``extract_json``) is
- untouched. Callers that pass extra keyword arguments to the model
- (for example ``relevance_filter.py`` calling
- ``llm.invoke(prompt, **invoke_kwargs)``) are outside this signature
- and keep calling the model directly.
+ untouched. Per-call model options pass through the existing wrappers
+ without changing the shared model's defaults or binding around a
+ rate-limiting wrapper.
"""
- return llm.invoke(prompt)
+ return llm.invoke(prompt, **kwargs)
async def ainvoke_llm(llm: Any, prompt: Any) -> Any:
diff --git a/src/local_deep_research/utilities/type_utils.py b/src/local_deep_research/utilities/type_utils.py
index e22580914a..017fefd9c4 100644
--- a/src/local_deep_research/utilities/type_utils.py
+++ b/src/local_deep_research/utilities/type_utils.py
@@ -9,6 +9,40 @@ avoid circular import issues.
from typing import Any, Dict, Optional
+def to_positive_int(value: Any) -> int:
+ """Parse a positive whole number without rounding or an upper clamp.
+
+ Accept integer values and decimal integer strings (including a .0
+ suffix). Shared by summary-input setting reads and writes so a saved
+ value cannot pass validation and then fail at fetch time.
+ """
+ error = "Value must be a positive integer"
+ if isinstance(value, str):
+ whole, dot, fraction = value.strip().partition(".")
+ if dot and fraction.strip("0"):
+ raise ValueError(error)
+ # Parse directly as an integer, avoiding float rounding and
+ # expansion of compact exponent strings into enormous integers.
+ value = whole
+ elif not isinstance(value, (int, float)):
+ raise ValueError(error)
+ try:
+ limit = int(value)
+ except (TypeError, ValueError, OverflowError):
+ # Raise below, outside the handler: ``from None`` only hides the
+ # parser error, whose message holds the raw value, from tracebacks
+ # while leaving it in ``__context__``.
+ limit = None
+ if (
+ limit is None
+ or isinstance(value, bool)
+ or (isinstance(value, float) and value != limit)
+ or limit < 1
+ ):
+ raise ValueError(error)
+ return limit
+
+
def to_bool(value: Any, default: bool = False) -> bool:
"""
Convert a value to boolean, handling string representations.
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index bc282fd0c8..d94a3482f2 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -99,7 +99,7 @@ from ...security.egress.validators import (
first_egress_validation_error,
)
from ...utilities.db_utils import get_settings_manager
-from ...utilities.type_utils import unwrap_setting
+from ...utilities.type_utils import to_positive_int, unwrap_setting
from ...utilities.url_utils import normalize_url
from ...settings.exceptions import SettingsValueError
@@ -578,6 +578,14 @@ def validate_setting(
Returns:
Tuple of (is_valid, error_message)
"""
+ if setting.key == "search.fetch.summary_input_max_length":
+ try:
+ to_positive_int(value)
+ except ValueError:
+ return False, "Value must be a positive integer"
+
+ # Validate the exact summary integer before generic number conversion
+ # or the blank-input handling for other optional numeric settings.
raw_value = value
numeric_ui = setting.ui_element in ("number", "slider", "range")
# Blank form inputs explicitly clear optional numeric settings; they are
@@ -681,6 +689,14 @@ def coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:
string like ``'{"k": "v"}'`` would become a dict, then ``str()``
would produce ``"{'k': 'v'}"`` (Python repr, not valid JSON).
"""
+ if key == "search.fetch.summary_input_max_length":
+ try:
+ return to_positive_int(value)
+ except ValueError:
+ # Preserve invalid input for validate_setting to reject, rather
+ # than losing a fractional part or treating it as optional/null.
+ return value
+
# check_env=False: we are persisting a user-supplied value, not reading
# from an environment variable override. check_env=True (the default)
# would silently replace the user's value with an env var, which is
@@ -1829,6 +1845,19 @@ def _save_all_settings_sync(form_data: dict, username: str):
# Get the setting metadata from pre-fetched dict
current_setting = all_db_settings.get(key)
+ if key == "search.fetch.summary_input_max_length":
+ try:
+ value = to_positive_int(value)
+ except ValueError:
+ validation_errors.append(
+ {
+ "key": key,
+ "name": "Fetch Summary Input Max Length",
+ "error": "Value must be a positive integer",
+ }
+ )
+ continue
+
# The sentinel guards below must see a JSON-STRING-encoded
# container coerced to its real dict/list shape, or a
# masked container submitted in that form (a supported
@@ -2579,6 +2608,13 @@ def _save_settings_sync(form_data: dict, username: str) -> dict:
try:
db_setting = all_db_settings.get(key)
+ if key == "search.fetch.summary_input_max_length":
+ try:
+ value = to_positive_int(value)
+ except ValueError:
+ failed_count += 1
+ continue
+
# Namespace validation: reject new keys outside allowed
# prefixes. Existing keys (updates) bypass this check — it
# only applies to creation of brand-new rows through this
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index ef542ffcf9..1670127fc3 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -8,6 +8,7 @@ from ...database.models import Setting
from ...settings.exceptions import SettingsValueError
from ...settings.manager import DYNAMIC_SETTINGS, get_typed_setting_value
from ...utilities.db_utils import get_settings_manager
+from ...utilities.type_utils import to_positive_int
# Settings with dynamically populated options (excluded from validation).
# Single source of truth lives in `settings/manager.py` (it is also used by
@@ -181,6 +182,14 @@ def validate_setting(
Returns:
tuple[bool, Optional[str]]: (is_valid, error_message)
"""
+ if setting.key == "search.fetch.summary_input_max_length":
+ try:
+ to_positive_int(value)
+ except ValueError:
+ return False, "Value must be a positive integer"
+
+ # Validate the exact summary integer before generic number conversion
+ # or the blank-input handling for other optional numeric settings.
raw_value = value
numeric_ui = setting.ui_element in ("number", "slider", "range")
# Blank form inputs explicitly clear optional numeric settings; they are
diff --git a/tests/advanced_search_system/tools/test_archive_fetch.py b/tests/advanced_search_system/tools/test_archive_fetch.py
index dafd45dd20..c6a45442fa 100644
--- a/tests/advanced_search_system/tools/test_archive_fetch.py
+++ b/tests/advanced_search_system/tools/test_archive_fetch.py
@@ -35,6 +35,10 @@ API = "https://archive.org/wayback/available"
REPLAY = f"https://web.archive.org/web/{CAPTURED}/{ORIGINAL}"
_SESSION_REQUEST = requests.sessions.Session.request
+# The fixture model is unregistered and has no configured context window:
+# 8192 fallback tokens minus 6553 reply tokens leaves 1639 * 4 characters.
+DEFAULT_SUMMARY_PAGE_LIMIT = 6556
+
MISMATCHED_TARGETS = [
pytest.param(
@@ -168,6 +172,95 @@ def _arguments(mode, *, url=ORIGINAL, **extra):
return arguments
[email protected]("mode", ["summary_focus", "summary_focus_query"])
[email protected]("budget", [0, -1, True, 1.5, None, "invalid"])
+def test_invalid_summary_budget_precedes_archive_lookup_and_quota(
+ mode, budget, runtime
+):
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ max_fetches=2,
+ settings_snapshot={
+ "search.fetch.summary_input_max_length": {
+ "value": budget,
+ "ui_element": "number",
+ }
+ },
+ )
+
+ message = tool.invoke(_arguments(mode))
+
+ assert "must be a positive integer" in message
+ assert "LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH" in message
+ assert collector.fetch_count == 0
+ assert collector.results == []
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+
+
[email protected]("mode", ["summary_focus", "summary_focus_query"])
+ ("key", "extra"),
+ [
+ ("llm.context_window_size", {"llm.context_window_unrestricted": False}),
+ ("llm.local_context_window_size", {}),
+ ("llm.max_tokens", {}),
+ ],
+)
+def test_invalid_managed_model_budget_precedes_archive_lookup_and_quota(
+ mode, key, extra, runtime
+):
+ collector = SearchResultsCollector([])
+ invalid = "private-invalid-config-value"
+ tool = archive.build_archive_fetch_tool(
+ mode,
+ collector,
+ model=runtime.model,
+ max_fetches=2,
+ settings_snapshot={
+ **extra,
+ key: {"value": invalid, "ui_element": "number"},
+ },
+ )
+
+ message = tool.invoke(_arguments(mode))
+
+ assert "Invalid setting" in message
+ assert key in message
+ assert invalid not in message
+ assert collector.fetch_count == 0
+ assert collector.results == []
+ runtime.getter.assert_not_called()
+ runtime.factory.assert_not_called()
+ runtime.model.invoke.assert_not_called()
+
+
+def test_invalid_summary_budget_keeps_archive_full_mode_available(runtime):
+ collector = SearchResultsCollector([])
+ tool = archive.build_archive_fetch_tool(
+ "full",
+ collector,
+ settings_snapshot={
+ "search.fetch.summary_input_max_length": {
+ "value": "invalid",
+ "ui_element": "number",
+ }
+ },
+ )
+
+ message = tool.invoke(_arguments("full"))
+
+ assert "Archived evidence" in message
+ assert collector.fetch_count == 1
+ _assert_source(collector)
+ runtime.getter.assert_called_once()
+ runtime.model.invoke.assert_not_called()
+
+
def _assert_source(collector, *, replay=REPLAY, timestamp=CAPTURED):
assert len(collector.results) == 1
source = collector.results[0]
@@ -306,7 +399,10 @@ def test_archive_canonical_target_keeps_actual_provenance_in_citation_and_output
assert collector.find_by_index(1)["original_url"] == actual
assert collector.find_by_index(1)["requested_url"] == requested
assert collector.fetch_count == 1
- runtime.fetcher.fetch.assert_called_once_with(replay, max_length=10_000)
+ runtime.fetcher.fetch.assert_called_once_with(
+ replay,
+ max_length=10_000 if mode == "full" else DEFAULT_SUMMARY_PAGE_LIMIT,
+ )
assert runtime.getter.call_args.kwargs["params"]["url"] == requested
@@ -560,7 +656,10 @@ def test_successful_archive_fetch_keeps_replay_citation_and_nearest_date(
runtime.getter.assert_called_once_with(
API, params=params, timeout=30, allow_redirects=False
)
- runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ runtime.fetcher.fetch.assert_called_once_with(
+ REPLAY,
+ max_length=10_000 if mode == "full" else DEFAULT_SUMMARY_PAGE_LIMIT,
+ )
assert collector.fetch_count == 1
if mode == "full":
assert "Archived evidence" in output
@@ -726,7 +825,10 @@ def test_empty_archive_content_or_summary_does_not_register_source(
assert "NOT RELEVANT" in output
assert collector.results == []
assert collector.fetch_count == 1
- runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ runtime.fetcher.fetch.assert_called_once_with(
+ REPLAY,
+ max_length=10_000 if mode == "full" else DEFAULT_SUMMARY_PAGE_LIMIT,
+ )
if empty_stage == "content":
runtime.model.invoke.assert_not_called()
else:
@@ -757,7 +859,10 @@ def test_replay_fetch_failure_never_substitutes_live_original(
assert not output.startswith("[1]")
assert collector.results == []
assert collector.fetch_count == 1
- runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ runtime.fetcher.fetch.assert_called_once_with(
+ REPLAY,
+ max_length=10_000 if mode == "full" else DEFAULT_SUMMARY_PAGE_LIMIT,
+ )
runtime.model.invoke.assert_not_called()
@@ -767,6 +872,10 @@ def test_archive_delegates_settings_limits_and_metadata_to_shared_fetch(
):
settings = {
"search.fetch.content_max_length": {"value": 3000},
+ "search.fetch.summary_input_max_length": {
+ "value": 4000,
+ "ui_element": "number",
+ },
"web.enable_javascript_rendering": {
"value": True,
"ui_element": "checkbox",
@@ -805,7 +914,9 @@ def test_archive_delegates_settings_limits_and_metadata_to_shared_fetch(
output = tool.invoke(_arguments(mode))
- runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=3000)
+ runtime.fetcher.fetch.assert_called_once_with(
+ REPLAY, max_length=3000 if mode == "full" else 4000
+ )
assert runtime.factory.call_args.kwargs["enable_js_rendering"] is True
assert runtime.factory.call_args.kwargs["egress_context"] is context
assert "EXCLUDED_TRAILING_EVIDENCE" not in output
@@ -814,8 +925,8 @@ def test_archive_delegates_settings_limits_and_metadata_to_shared_fetch(
assert "A" * 3001 not in output
else:
prompt = runtime.model.invoke.call_args.args[0]
- assert "A" * 3000 in prompt
- assert "A" * 3001 not in prompt
+ assert "A" * 4000 in prompt
+ assert "A" * 4001 not in prompt
assert "EXCLUDED_TRAILING_EVIDENCE" not in prompt
delegate.assert_called_once()
assert delegate.call_args.args == (mode, collector)
@@ -2209,7 +2320,10 @@ def test_partial_archive_provenance_is_recovered_before_fetch(
guard(REPLAY)
with pytest.raises(ValueError):
guard(ORIGINAL)
- runtime.fetcher.fetch.assert_called_once_with(REPLAY, max_length=10_000)
+ runtime.fetcher.fetch.assert_called_once_with(
+ REPLAY,
+ max_length=10_000 if mode == "full" else DEFAULT_SUMMARY_PAGE_LIMIT,
+ )
runtime.getter.assert_not_called()
assert runtime.model.invoke.call_count == (0 if mode == "full" else 1)
@@ -2273,7 +2387,9 @@ def test_non_capture_archive_page_keeps_ordinary_fetch_behavior(mode, runtime):
assert "Captured:" not in output
assert runtime.factory.call_args.kwargs.get("url_guard") is None
assert collector.fetch_count == 1
- runtime.fetcher.fetch.assert_called_once_with(url, max_length=10_000)
+ runtime.fetcher.fetch.assert_called_once_with(
+ url, max_length=10_000 if mode == "full" else DEFAULT_SUMMARY_PAGE_LIMIT
+ )
runtime.getter.assert_not_called()
diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.py
index 31e1b0dd44..61d7dfe48e 100644
--- a/tests/advanced_search_system/tools/test_fetch_modes.py
+++ b/tests/advanced_search_system/tools/test_fetch_modes.py
@@ -1601,7 +1601,7 @@ def test_explicit_content_max_length_overrides_snapshot():
assert len(body) == 1500
-def test_summary_mode_respects_content_max_length_setting():
+def test_summary_mode_respects_summary_input_max_length_setting():
"""Summary mode truncates library-doc text before LLM extraction."""
long_text = "C" * 20000
@@ -1620,7 +1620,9 @@ def test_summary_mode_respects_content_max_length_setting():
collector,
model=model,
library_resolver=_large_resolver,
- settings_snapshot={"search.fetch.content_max_length": {"value": 3000}},
+ settings_snapshot={
+ "search.fetch.summary_input_max_length": {"value": 3000}
+ },
)
out = tool.invoke(
diff --git a/tests/advanced_search_system/tools/test_fetch_settings_errors.py b/tests/advanced_search_system/tools/test_fetch_settings_errors.py
index b02970622a..206bfa56cd 100644
--- a/tests/advanced_search_system/tools/test_fetch_settings_errors.py
+++ b/tests/advanced_search_system/tools/test_fetch_settings_errors.py
@@ -18,15 +18,19 @@ from local_deep_research.settings.exceptions import SettingsValueError
KEY = "search.fetch.content_max_length"
ENVIRONMENT_KEY = "LDR_SEARCH_FETCH_CONTENT_MAX_LENGTH"
+SUMMARY_KEY = "search.fetch.summary_input_max_length"
+SUMMARY_ENVIRONMENT_KEY = "LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH"
INVALID_VALUE = "invalid-private-number"
-def _invalid_snapshot(monkeypatch, source):
+def _invalid_snapshot(monkeypatch, source, key=KEY):
monkeypatch.delenv(ENVIRONMENT_KEY, raising=False)
+ monkeypatch.delenv(SUMMARY_ENVIRONMENT_KEY, raising=False)
+ environment_key = ENVIRONMENT_KEY if key == KEY else SUMMARY_ENVIRONMENT_KEY
value = INVALID_VALUE if source == "value" else 12000
if source == "environment":
- monkeypatch.setenv(ENVIRONMENT_KEY, INVALID_VALUE)
- return {KEY: {"value": value, "ui_element": "number"}}
+ monkeypatch.setenv(environment_key, INVALID_VALUE)
+ return {key: {"value": value, "ui_element": "number"}}
@pytest.mark.parametrize("source", ["value", "environment"])
@@ -108,13 +112,14 @@ def _tool_case(monkeypatch, snapshot, mode, url):
def test_invalid_length_stops_fetch_without_consuming_budget(
monkeypatch, source, mode, url
):
- snapshot = _invalid_snapshot(monkeypatch, source)
+ key = KEY if mode == "full" else SUMMARY_KEY
+ snapshot = _invalid_snapshot(monkeypatch, source, key)
case = _tool_case(monkeypatch, snapshot, mode, url)
result = case.tool.invoke(case.arguments)
assert result.startswith("Error fetching ")
- assert KEY in result
+ assert key in result
assert INVALID_VALUE not in result
case.fetcher.assert_not_called()
case.resolver.assert_not_called()
@@ -133,9 +138,47 @@ def test_valid_length_allows_fetch_and_preserves_budget_accounting(
monkeypatch, mode, url
):
monkeypatch.delenv(ENVIRONMENT_KEY, raising=False)
- snapshot = {KEY: {"value": 12000, "ui_element": "number"}}
+ monkeypatch.delenv(SUMMARY_ENVIRONMENT_KEY, raising=False)
+ snapshot = {
+ KEY: {"value": 12000, "ui_element": "number"},
+ SUMMARY_KEY: {"value": 4000, "ui_element": "number"},
+ # Leave room for the summary input plus instructions and response.
+ "llm.local_context_window_size": 32768,
+ }
+ case = _tool_case(monkeypatch, snapshot, mode, url)
+
+ _assert_successful_fetch(case, mode, url)
+
+
[email protected]("source", ["value", "environment"])
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
+ "url", ["https://example.com/paper", "/library/document/example"]
+)
+def test_direct_tool_snapshot_does_not_read_inactive_length(
+ monkeypatch, source, mode, url
+):
+ """Direct tools read their own budget from a supplied partial snapshot.
+
+ This does not change strict validation when loading complete managed
+ settings; an invalid typed full-text setting still fails that load.
+ """
+ active_key = KEY if mode == "full" else SUMMARY_KEY
+ inactive_key = SUMMARY_KEY if mode == "full" else KEY
+ snapshot = _invalid_snapshot(monkeypatch, source, inactive_key)
+ snapshot[active_key] = {
+ "value": 12000 if mode == "full" else 4000,
+ "ui_element": "number",
+ }
+ snapshot["llm.local_context_window_size"] = 32768
case = _tool_case(monkeypatch, snapshot, mode, url)
+ _assert_successful_fetch(case, mode, url)
+
+
+def _assert_successful_fetch(case, mode, url):
result = case.tool.invoke(case.arguments)
assert result.startswith("[1] Title: Example")
@@ -146,7 +189,7 @@ def test_valid_length_allows_fetch_and_preserves_budget_accounting(
case.resolver.assert_called_once_with(url)
if url.startswith("https://"):
case.fetcher.return_value.__enter__.return_value.fetch.assert_called_once_with(
- url, max_length=12000
+ url, max_length=12000 if mode == "full" else 4000
)
assert case.collector.get_fetch_count() == 1
else:
diff --git a/tests/advanced_search_system/tools/test_fetch_summary_endpoint_budget.py b/tests/advanced_search_system/tools/test_fetch_summary_endpoint_budget.py
new file mode 100644
index 0000000000..1739fe7d90
--- /dev/null
+++ b/tests/advanced_search_system/tools/test_fetch_summary_endpoint_budget.py
@@ -0,0 +1,310 @@
+"""Summary context budgets match actual compatible-endpoint requests."""
+
+import json
+from pathlib import Path
+import socket
+
+import pytest
+
+
+PR_TREE = Path(__file__).resolve().parents[3]
+
+
[email protected](autouse=True)
+def no_network(monkeypatch):
+ def refused(*args, **kwargs):
+ raise AssertionError("This regression must not open a connection")
+
+ monkeypatch.setattr(socket.socket, "connect", refused)
+ monkeypatch.setattr(socket.socket, "connect_ex", refused)
+ monkeypatch.setattr(socket, "create_connection", refused)
+
+
+ "provider,unrestricted,reply_tokens,rate_limited,scenario",
+ [
+ (provider, unrestricted, reply, limited, "bounded")
+ for provider in ("openai_endpoint", "anthropic_endpoint")
+ for unrestricted in (True, False)
+ for reply in (30000, 1000)
+ for limited in (False, True)
+ ]
+ + [
+ (provider, True, 30000, limited, scenario)
+ for provider in ("openai_endpoint", "anthropic_endpoint")
+ for limited in (False, True)
+ for scenario in ("full", "explicit")
+ ]
+ + [
+ (provider, True, 30000, limited, "streaming")
+ for provider in ("openai_endpoint", "anthropic_endpoint")
+ for limited in (False, True)
+ ],
+)
+def test_built_endpoint_payload_and_summary_prompt_share_one_budget(
+ monkeypatch, provider, unrestricted, reply_tokens, rate_limited, scenario
+):
+ from langchain_core.messages import AIMessage, AIMessageChunk
+ from langchain_core.outputs import (
+ ChatGeneration,
+ ChatGenerationChunk,
+ ChatResult,
+ )
+ from local_deep_research.config.llm_config import get_llm
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
+ )
+
+ metadata = json.loads(
+ (
+ PR_TREE / "src/local_deep_research/defaults/default_settings.json"
+ ).read_text()
+ )
+ snapshot = {key: row["value"] for key, row in metadata.items()}
+ snapshot.update(
+ {
+ # An explicit per-run provider below overrides this saved value.
+ "llm.provider": "ollama",
+ "llm.context_window_unrestricted": unrestricted,
+ "llm.local_context_window_size": 20480,
+ "llm.context_window_size": 32768,
+ "llm.max_tokens": reply_tokens,
+ "llm.supports_max_tokens": True,
+ "llm.streaming": scenario == "streaming",
+ "llm.openai_endpoint.stream_usage": scenario == "streaming",
+ "llm.openai_endpoint.url": "http://127.0.0.1:9/v1",
+ "llm.anthropic_endpoint.url": "http://127.0.0.1:9",
+ "llm.openai_endpoint.api_key": "local-review-placeholder",
+ "llm.anthropic_endpoint.api_key": "local-review-placeholder",
+ "rate_limiting.llm_enabled": rate_limited,
+ "search.tool": "searxng",
+ "policy.egress_scope": "public_only",
+ "llm.require_local_endpoint": False,
+ }
+ )
+ model = get_llm(
+ model_name="review-model",
+ provider=provider,
+ settings_snapshot=snapshot,
+ )
+ try:
+ assert model._provider == provider
+ # Independently derive the documented prompt budget, so the same
+ # probe works before and after refactoring the private helper.
+ window = 20480 if unrestricted else 32768
+ limit = 4 * (window - min(reply_tokens, int(window * 0.8)))
+ raw_model = model.base_llm.base_llm if rate_limited else model.base_llm
+ original_payload = raw_model._get_request_payload("control")
+ captured = []
+ rate_limiter_calls = []
+
+ if rate_limited:
+
+ def capture_rate_limit(call):
+ rate_limiter_calls.append(True)
+ return call()
+
+ monkeypatch.setattr(
+ model.base_llm, "_call_rate_limited", capture_rate_limit
+ )
+
+ def capture(self, messages, stop=None, run_manager=None, **kwargs):
+ # Keep real LangChain dispatch and its binding kwargs, replacing
+ # only the method that would send the network request.
+ payload = self._get_request_payload(messages, stop=stop, **kwargs)
+ captured.append((messages, payload))
+ return ChatResult(
+ generations=[
+ ChatGeneration(message=AIMessage(content="Extracted fact"))
+ ]
+ )
+
+ if scenario == "streaming":
+ from local_deep_research.llm.cancellation import (
+ bind_llm_to_research,
+ )
+
+ # Exercise the real scoped Processing -> RateLimited -> SDK
+ # stream path; no provider or wrapper binding is mocked.
+ bind_llm_to_research(
+ model, "summary-budget-stream", stop_at=raw_model
+ )
+
+ def capture_stream(
+ self, messages, stop=None, run_manager=None, **kwargs
+ ):
+ kwargs["stream"] = True
+ payload = self._get_request_payload(
+ messages, stop=stop, **kwargs
+ )
+ captured.append((messages, payload))
+ yield ChatGenerationChunk(
+ message=AIMessageChunk(content="Extracted fact")
+ )
+
+ monkeypatch.setattr(type(raw_model), "_stream", capture_stream)
+ else:
+ monkeypatch.setattr(type(raw_model), "_generate", capture)
+ tool = build_fetch_tool(
+ "full" if scenario == "full" else "summary_focus_query",
+ SearchResultsCollector([]),
+ model=model,
+ overall_query="Research question",
+ settings_snapshot=snapshot,
+ content_max_length=50000 if scenario == "explicit" else None,
+ library_resolver=lambda url: {
+ "content": "x" * 600000,
+ "title": "Local document",
+ "url": url,
+ },
+ )
+ tool_input = {"url": "/library/document/review"}
+ if scenario != "full":
+ tool_input["focus"] = "Specific fact"
+ output = tool.invoke(tool_input)
+ # A fix must affect this one summary call, never mutate the shared
+ # research model's defaults or the caller-owned settings snapshot.
+ assert raw_model._get_request_payload("control") == original_payload
+ assert snapshot["llm.max_tokens"] == reply_tokens
+ if scenario == "full":
+ assert output.split("\n\n", 1)[1] == "x" * 10000
+ assert not captured
+ assert not rate_limiter_calls
+ return
+ assert "Extracted fact" in output, output
+ assert len(captured) == 1
+ assert len(rate_limiter_calls) == int(rate_limited)
+ messages, payload = captured[0]
+ if scenario == "streaming":
+ assert payload["stream"] is True
+ actual_prompt = messages[0].content
+ actual_reply = payload.get(
+ "max_completion_tokens", payload.get("max_tokens")
+ )
+ assert isinstance(actual_reply, int) and actual_reply > 0
+ if scenario == "explicit":
+ original_reply = original_payload.get(
+ "max_completion_tokens", original_payload.get("max_tokens")
+ )
+ page_text = actual_prompt.split("Page content:\n", 1)[1].split(
+ "\n\nOutput rules:", 1
+ )[0]
+ assert page_text == "x" * 50000
+ assert len(actual_prompt) > limit
+ assert actual_reply == original_reply
+ return
+ assert len(actual_prompt) == limit
+ estimated_prompt_tokens = len(actual_prompt) / 4
+ assert estimated_prompt_tokens + actual_reply <= window, (
+ f"{provider=} {unrestricted=} {limit=} {actual_reply=} "
+ f"{window=}; the summary limit must reserve the reply allowance "
+ "actually sent by this already-built provider"
+ )
+ finally:
+ model.close()
+
+
+ "provider", ["openai", "openai_endpoint", "anthropic_endpoint"]
+)
[email protected]("registration_kind", ["instance", "factory"])
+def test_registered_shadow_keeps_custom_model_invocation_contract(
+ provider, registration_kind
+):
+ from uuid import uuid4
+
+ from langchain_core.language_models import BaseChatModel
+ from langchain_core.messages import AIMessage
+ from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+ )
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
+ )
+ from local_deep_research.config.llm_config import get_llm
+ from local_deep_research.llm.llm_registry import (
+ get_llm_from_registry,
+ register_llm,
+ unregister_llm,
+ )
+
+ captured = []
+
+ class PromptOnlyModel(BaseChatModel):
+ @property
+ def _llm_type(self):
+ return "summary-budget-custom"
+
+ def _generate(self, messages, stop=None, run_manager=None, **kwargs):
+ raise AssertionError("The custom invoke method must be used")
+
+ def invoke(self, prompt):
+ # A registered model's public contract need not accept the
+ # built-in provider's max_tokens keyword.
+ captured.append(prompt)
+ return AIMessage(content="Custom extracted fact")
+
+ custom_model = PromptOnlyModel()
+
+ def factory(model_name, temperature, settings_snapshot):
+ return custom_model
+
+ shared_provider = get_llm_from_registry(provider)
+ username = f"summary-budget-shadow-{uuid4().hex}"
+ snapshot = {
+ "llm.provider": "ollama",
+ "llm.context_window_unrestricted": True,
+ "llm.local_context_window_size": 20480,
+ "llm.max_tokens": 30000,
+ "llm.supports_max_tokens": True,
+ "rate_limiting.llm_enabled": False,
+ "search.tool": "searxng",
+ "policy.egress_scope": "public_only",
+ "llm.require_local_endpoint": False,
+ "search.fetch.summary_input_max_length": 500000,
+ }
+ register_llm(
+ provider,
+ factory if registration_kind == "factory" else custom_model,
+ username=username,
+ )
+ model = None
+ try:
+ model = get_llm(
+ model_name="custom-summary-model",
+ provider=provider,
+ username=username,
+ settings_snapshot=snapshot,
+ )
+ assert model.base_llm is custom_model
+ assert model._owns_llm is False
+ tool = build_fetch_tool(
+ "summary_focus_query",
+ SearchResultsCollector([]),
+ model=model,
+ overall_query="Research question",
+ settings_snapshot=snapshot,
+ library_resolver=lambda url: {
+ "content": "x" * 600000,
+ "title": "Local document",
+ "url": url,
+ },
+ )
+ output = tool.invoke(
+ {"url": "/library/document/review", "focus": "Specific fact"}
+ )
+ assert "Custom extracted fact" in output, output
+ assert len(captured) == 1
+ # A user-owned registration is not proof of a known cloud model,
+ # even when it shadows a built-in provider's name.
+ assert len(captured[0]) == 4 * (20480 - int(20480 * 0.8))
+ assert snapshot["llm.max_tokens"] == 30000
+ finally:
+ if model is not None:
+ model.close()
+ unregister_llm(provider, username=username)
+ assert get_llm_from_registry(provider) is shared_provider
+ assert get_llm_from_registry(provider, username=username) is shared_provider
diff --git a/tests/advanced_search_system/tools/test_fetch_summary_input_limit.py b/tests/advanced_search_system/tools/test_fetch_summary_input_limit.py
new file mode 100644
index 0000000000..4416ab84a0
--- /dev/null
+++ b/tests/advanced_search_system/tools/test_fetch_summary_input_limit.py
@@ -0,0 +1,927 @@
+"""Summary input budgets stay separate from text returned to the agent."""
+
+from importlib import import_module
+from unittest.mock import MagicMock, patch
+
+import pytest
+from langchain_core.messages import AIMessage
+
+from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+)
+from local_deep_research.advanced_search_system.tools.fetch import (
+ _read_summary_input_max_length_setting,
+ build_fetch_tool,
+)
+from local_deep_research.content_fetcher.url_classifier import URLType
+
+
+SUMMARY_KEY = "search.fetch.summary_input_max_length"
+FULL_KEY = "search.fetch.content_max_length"
+ENV_VAR = "LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH"
+LOCAL_WINDOW_KEY = "llm.local_context_window_size"
+
+
[email protected]("mode", ["summary_focus", "summary_focus_query"])
[email protected]("source", ["http", "library", "citation"])
[email protected]("configured_limit", [None, 1, 1001, 600001])
+def test_summary_input_budget_reaches_extractor_only(
+ mode, source, configured_limit
+):
+ """Exercise real HTTP truncation and local/cited documents in both modes.
+
+ The model is built for a cloud provider with unrestricted context, so
+ the configured budget applies unchanged. The default reads past the
+ old 50k ceiling; a configured value can exceed even ContentFetcher's
+ 500k default or be below the old 1k floor.
+ """
+ limit = 500000 if configured_limit is None else configured_limit
+ # Non-ASCII text proves that the budget counts characters, not bytes.
+ page = "é" * (limit - 1) + "Z" + "TRUNCATED_TAIL"
+ settings = {FULL_KEY: {"value": 1000, "ui_element": "number"}}
+ if configured_limit is not None:
+ settings[SUMMARY_KEY] = {
+ "value": configured_limit,
+ "ui_element": "number",
+ }
+ url = (
+ "https://example.com/page"
+ if source == "http"
+ else "/library/document/large-doc"
+ )
+ collector = SearchResultsCollector([])
+ if source == "citation":
+ collector.add_results(
+ [{"title": "Page", "link": url, "snippet": "search snippet"}],
+ engine_name="library",
+ )
+ model, base = _built_model("openai", LOCAL_DEFAULTS)
+ resolver = MagicMock(
+ return_value={"content": page, "title": "Page", "url": url}
+ )
+ downloader = MagicMock()
+ downloader.download_with_result.return_value.is_success = True
+ downloader.download_with_result.return_value.content = page.encode()
+ downloader.get_metadata.return_value = {"title": "Page"}
+ tool = build_fetch_tool(
+ mode,
+ collector,
+ model=model,
+ overall_query="Research question",
+ settings_snapshot=settings,
+ library_resolver=None if source == "http" else resolver,
+ )
+
+ with (
+ patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.content_fetcher.fetcher.URLClassifier"
+ ) as classifier,
+ patch(
+ "local_deep_research.content_fetcher.fetcher.ContentFetcher._get_downloader",
+ return_value=downloader,
+ ),
+ ):
+ classifier.classify.return_value = URLType.HTML
+ classifier.get_source_name.return_value = "Web Page"
+ output = tool.invoke(
+ {"url": "[1]" if source == "citation" else url, "focus": "fact"}
+ )
+
+ base.invoke.assert_called_once()
+ prompt = base.invoke.call_args.args[0]
+ extracted_input = prompt.split("Page content:\n", 1)[1].split(
+ "\n\nOutput rules:", 1
+ )[0]
+ expected = page[:limit]
+ if source == "http":
+ expected += "\n\n[... content truncated ...]"
+ downloader.download_with_result.assert_called_once()
+ else:
+ downloader.download_with_result.assert_not_called()
+ resolver.assert_called_once_with(url)
+ assert extracted_input == expected
+ assert ("Overall research question:" in prompt) == (
+ mode == "summary_focus_query"
+ )
+ assert "Extracted fact" in output
+ assert "é" not in output
+ assert "TRUNCATED_TAIL" not in output
+ assert collector.results[-1]["snippet"] == "Extracted fact"
+
+
[email protected]("full_limit", [None, 3000])
+def test_full_mode_keeps_its_own_budget(full_limit):
+ settings = {SUMMARY_KEY: 900000}
+ if full_limit is not None:
+ settings[FULL_KEY] = full_limit
+ tool = build_fetch_tool(
+ "full",
+ SearchResultsCollector([]),
+ settings_snapshot=settings,
+ library_resolver=lambda url: {"content": "A" * 50000, "url": url},
+ )
+ output = tool.invoke({"url": "/library/document/large-doc"})
+ assert output.split("\n\n", 1)[1] == "A" * (
+ 10000 if full_limit is None else full_limit
+ )
+
+
[email protected]("mode", ["summary_focus", "summary_focus_query"])
+def test_explicit_summary_budget_still_overrides_settings(mode):
+ model = MagicMock()
+ model.invoke.return_value.content = "summary"
+ tool = build_fetch_tool(
+ mode,
+ SearchResultsCollector([]),
+ model=model,
+ overall_query="question",
+ settings_snapshot={SUMMARY_KEY: 900000, FULL_KEY: 1000},
+ library_resolver=lambda url: {"content": "A" * 50000, "url": url},
+ content_max_length=1500,
+ )
+ output = tool.invoke(
+ {"url": "/library/document/large-doc", "focus": "fact"}
+ )
+ assert "summary" in output
+ prompt = model.invoke.call_args.args[0]
+ assert "A" * 1500 in prompt
+ assert "A" * 1501 not in prompt
+
+
+ ("value", "expected"),
+ [
+ (1, 1),
+ (" 1 ", 1),
+ (1001, 1001),
+ (700000, 700000),
+ (2**53 + 1, 2**53 + 1),
+ (10**30, 10**30),
+ (1200.0, 1200),
+ ("1200.0", 1200),
+ (1000000.0, 1000000),
+ ],
+)
[email protected]("wrapped", [False, True])
+def test_summary_budget_accepts_positive_integers_without_clamping(
+ value, expected, wrapped
+):
+ setting = {"value": value, "ui_element": "number"} if wrapped else value
+ assert (
+ _read_summary_input_max_length_setting({SUMMARY_KEY: setting})
+ == expected
+ )
+
+
[email protected]("snapshot", [None, {}, {FULL_KEY: 1000}])
+def test_missing_summary_budget_uses_high_default(snapshot):
+ assert _read_summary_input_max_length_setting(snapshot) == 500000
+
+
+ "value",
+ [
+ 0,
+ -1,
+ True,
+ None,
+ 1.5,
+ "1.0000000000000001",
+ "1e10000000",
+ "invalid",
+ float("inf"),
+ ],
+)
[email protected]("wrapped", [False, True])
+def test_invalid_summary_budget_prevents_fetch_and_model_call(value, wrapped):
+ model = MagicMock()
+ resolver = MagicMock()
+ tool = build_fetch_tool(
+ "summary_focus",
+ SearchResultsCollector([]),
+ model=model,
+ settings_snapshot={
+ SUMMARY_KEY: {"value": value, "ui_element": "number"}
+ if wrapped
+ else value
+ },
+ library_resolver=resolver,
+ )
+ with patch("local_deep_research.content_fetcher.ContentFetcher") as fetcher:
+ output = tool.invoke(
+ {"url": "https://example.com/page", "focus": "fact"}
+ )
+ assert "must be a positive integer" in output
+ fetcher.assert_not_called()
+ resolver.assert_not_called()
+ model.invoke.assert_not_called()
+
+
[email protected]("value", ["invalid", "1.0000000000000001", "0"])
+def test_invalid_summary_environment_budget_cannot_reuse_stored_value(
+ monkeypatch, value
+):
+ from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+ )
+
+ monkeypatch.setenv(ENV_VAR, value)
+ queued_snapshot = {SUMMARY_KEY: {"value": 500000, "ui_element": "number"}}
+ # A queued snapshot can predate the operator's environment change.
+ # Dispatch keeps the invalid override rather than the stored budget,
+ # and a fetch-tool read of either snapshot rejects it by name.
+ refreshed = apply_environment_overrides_to_snapshot(queued_snapshot)
+ assert refreshed[SUMMARY_KEY]["value"] == value
+ for snapshot in (refreshed, queued_snapshot):
+ with pytest.raises(ValueError, match=ENV_VAR):
+ _read_summary_input_max_length_setting(snapshot)
+ assert queued_snapshot[SUMMARY_KEY]["value"] == 500000
+
+
[email protected]("value", [1, 600001, 2**53 + 1])
+def test_summary_environment_budget_stays_exact_across_read_paths(
+ monkeypatch, value
+):
+ from local_deep_research.settings.manager import (
+ SettingsManager,
+ apply_environment_overrides_to_snapshot,
+ )
+
+ monkeypatch.setenv("LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH", str(value))
+ manager = SettingsManager(db_session=None)
+ assert manager.get_setting(SUMMARY_KEY) == value
+ snapshot = manager.get_all_settings()
+ assert snapshot[SUMMARY_KEY]["value"] == value
+ assert _read_summary_input_max_length_setting(snapshot) == value
+ queued_snapshot = {SUMMARY_KEY: {"value": 500000, "ui_element": "number"}}
+ refreshed = apply_environment_overrides_to_snapshot(queued_snapshot)
+ assert refreshed[SUMMARY_KEY]["value"] == value
+ assert queued_snapshot[SUMMARY_KEY]["value"] == 500000
+
+
+def test_summary_environment_validation_does_not_change_other_number_settings(
+ monkeypatch,
+):
+ from local_deep_research.settings.manager import (
+ SettingsManager,
+ get_typed_setting_value,
+ )
+ from local_deep_research.web.routers.settings import (
+ coerce_setting_for_write,
+ )
+
+ monkeypatch.setenv("LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH", "invalid")
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.75")
+ manager = SettingsManager(db_session=None)
+ assert manager.get_setting("llm.temperature") == 0.75
+ # Writes validate their submitted value, independent of read overrides.
+ assert coerce_setting_for_write(SUMMARY_KEY, "600001", "number") == 600001
+ assert (
+ get_typed_setting_value(
+ SUMMARY_KEY, "600001", "number", check_env=False
+ )
+ == 600001
+ )
+
+
+ "read_path",
+ ["typed", "environment", "wrapped", "raw", "queued"],
+)
+def test_summary_budget_errors_do_not_retain_parser_context(
+ monkeypatch, read_path
+):
+ from local_deep_research.settings.manager import (
+ apply_environment_overrides_to_snapshot,
+ get_typed_setting_value,
+ )
+
+ invalid_value = "invalid-private-parser-input"
+ snapshot = {SUMMARY_KEY: {"value": invalid_value, "ui_element": "number"}}
+ if read_path in ("environment", "queued"):
+ monkeypatch.setenv(
+ "LDR_SEARCH_FETCH_SUMMARY_INPUT_MAX_LENGTH", invalid_value
+ )
+ snapshot[SUMMARY_KEY]["value"] = 500000
+ elif read_path == "raw":
+ snapshot[SUMMARY_KEY] = invalid_value
+
+ # Settings reads keep an unusable value instead of raising, so each
+ # path ends at the fetch-time read, which is where the value fails.
+ if read_path == "typed":
+ kept = get_typed_setting_value(
+ SUMMARY_KEY, invalid_value, "number", check_env=False
+ )
+ assert kept == invalid_value
+ snapshot = {SUMMARY_KEY: kept}
+ elif read_path == "queued":
+ snapshot = apply_environment_overrides_to_snapshot(snapshot)
+
+ with pytest.raises(ValueError, match="positive integer") as caught:
+ _read_summary_input_max_length_setting(snapshot)
+
+ assert invalid_value not in str(caught.value)
+ assert caught.value.__context__ is None
+ assert caught.value.__cause__ is None
+
+
+ "value",
+ ["invalid-private-parser-input", "1e10000000", float("inf"), float("nan")],
+)
+def test_positive_int_parser_errors_leave_no_context(value):
+ """A caller that does not re-wrap must not inherit the raw value."""
+ from local_deep_research.utilities.type_utils import to_positive_int
+
+ with pytest.raises(ValueError, match="positive integer") as caught:
+ to_positive_int(value)
+ assert caught.value.__context__ is None
+ assert caught.value.__cause__ is None
+
+
[email protected]("value", ["invalid-private-budget", "12.5", "-7"])
+def test_invalid_summary_environment_budget_fails_only_summary_fetches(
+ monkeypatch, loguru_caplog, value
+):
+ """One bad override must not stop whole-settings loads or dispatch.
+
+ The settings page, research start, benchmarks and MCP all load every
+ setting. The override is kept rather than replaced by the stored
+ budget, logged by name without its value, and rejected per fetch.
+ """
+ from local_deep_research.settings.manager import (
+ SettingsManager,
+ apply_environment_overrides_to_snapshot,
+ )
+
+ monkeypatch.setenv(ENV_VAR, value)
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.75")
+ manager = SettingsManager(db_session=None)
+ queued = {
+ SUMMARY_KEY: {"value": 500000, "ui_element": "number"},
+ "llm.temperature": {"value": 0.7, "ui_element": "range"},
+ }
+ with loguru_caplog.at_level("WARNING"):
+ all_settings = manager.get_all_settings()
+ snapshot = manager.get_settings_snapshot()
+ single = manager.get_setting(SUMMARY_KEY)
+ refreshed = apply_environment_overrides_to_snapshot(queued)
+
+ assert all_settings[SUMMARY_KEY]["value"] == value
+ assert all_settings[SUMMARY_KEY]["editable"] is False
+ assert snapshot[SUMMARY_KEY] == value
+ assert single == value
+ assert refreshed[SUMMARY_KEY] == {
+ "value": value,
+ "ui_element": "number",
+ "editable": False,
+ }
+ assert queued[SUMMARY_KEY]["value"] == 500000
+ # The other overrides in the same loads still apply.
+ assert snapshot["llm.temperature"] == 0.75
+ assert refreshed["llm.temperature"]["value"] == 0.75
+ warnings = [
+ record.getMessage()
+ for record in loguru_caplog.records
+ if ENV_VAR in record.getMessage()
+ ]
+ assert warnings
+ assert not any(value in message for message in warnings)
+
+ for fetch_snapshot in (snapshot, refreshed):
+ model = MagicMock()
+ resolver = MagicMock()
+ tool = build_fetch_tool(
+ "summary_focus_query",
+ SearchResultsCollector([]),
+ model=model,
+ overall_query="question",
+ settings_snapshot=fetch_snapshot,
+ library_resolver=resolver,
+ )
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher"
+ ) as fetcher:
+ output = tool.invoke(
+ {"url": "https://example.com/page", "focus": "fact"}
+ )
+ assert ENV_VAR in output
+ assert "must be a positive integer" in output
+ assert value not in output
+ fetcher.assert_not_called()
+ resolver.assert_not_called()
+ model.invoke.assert_not_called()
+
+ # Full-text fetches do not read the summary budget.
+ full = build_fetch_tool(
+ "full",
+ SearchResultsCollector([]),
+ settings_snapshot=snapshot,
+ library_resolver=lambda url: {"content": "A" * 20000, "url": url},
+ )
+ output = full.invoke({"url": "/library/document/large-doc"})
+ assert output.split("\n\n", 1)[1] == "A" * 10000
+
+
+def test_invalid_stored_summary_budget_is_kept_and_named(loguru_caplog):
+ from local_deep_research.settings.manager import get_typed_setting_value
+
+ with loguru_caplog.at_level("WARNING"):
+ kept = get_typed_setting_value(
+ SUMMARY_KEY,
+ "invalid-private-budget",
+ "number",
+ default=500000,
+ check_env=False,
+ )
+ # Never the default: that would silently replace the user's value.
+ assert kept == "invalid-private-budget"
+ assert f"Setting {SUMMARY_KEY} must be a positive integer" in (
+ loguru_caplog.text
+ )
+ assert "invalid-private-budget" not in loguru_caplog.text
+
+
+PAGE = "x" * 600000 + "TAIL"
+# Every window setting is explicit, so no read falls through to a thread
+# settings context.
+LOCAL_DEFAULTS = {
+ LOCAL_WINDOW_KEY: 20480,
+ "llm.max_tokens": 30000,
+ "llm.supports_max_tokens": True,
+ "llm.context_window_unrestricted": True,
+ "llm.context_window_size": 128000,
+}
+# compute_max_tokens keeps min(30000, 80% of 20480) = 16384 tokens of a
+# 20480-token window for the reply. That leaves 4096 tokens, or 16384
+# characters at four per token, for the whole prompt.
+LOCAL_PROMPT_LIMIT = 16384
+# A 32768-token window keeps 26214 tokens for the reply: 6554 tokens left.
+RESTRICTED_32K = {
+ "llm.context_window_unrestricted": False,
+ "llm.context_window_size": 32768,
+}
+RESTRICTED_32K_PROMPT_LIMIT = 26216
+# The 8192-token fallback window keeps 6553 tokens: 1639 tokens left.
+FALLBACK_PROMPT_LIMIT = 6556
+
+
+def _snapshot(provider, extra=None):
+ """One snapshot for the build and the tool, as a research run has."""
+ return {"llm.provider": provider, **LOCAL_DEFAULTS, **(extra or {})}
+
+
+def _built_model(provider, build_snapshot):
+ """Wrap a stand-in chat model the way ``get_llm`` wraps its build.
+
+ The fetch tool receives the wrapper. The stand-in records the prompt.
+ """
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ base = MagicMock()
+ base.invoke.return_value = AIMessage(content="Extracted fact")
+ model = wrap_llm_without_think_tags(
+ base,
+ provider=provider,
+ settings_snapshot={
+ "rate_limiting.llm_enabled": False,
+ **build_snapshot,
+ },
+ )
+ return model, base
+
+
+def _summary_prompt(
+ mode,
+ model,
+ tool_snapshot,
+ page,
+ source="library",
+ *,
+ title="Page",
+ url=None,
+ **tool_kwargs,
+):
+ """Run one summary fetch and return its prompt and the page text in it.
+
+ *model* is a ``_built_model`` wrapper, or a bare ``MagicMock`` that
+ stands for a model ``get_llm`` did not build.
+ """
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+
+ if isinstance(model, ProcessingLLMWrapper):
+ recorder = model.base_llm
+ else:
+ recorder = model
+ model.invoke.return_value.content = "Extracted fact"
+ if url is None:
+ url = (
+ "https://example.com/page"
+ if source == "http"
+ else "/library/document/large-doc"
+ )
+ downloader = MagicMock()
+ downloader.download_with_result.return_value.is_success = True
+ downloader.download_with_result.return_value.content = page.encode()
+ downloader.get_metadata.return_value = {"title": title}
+ tool = build_fetch_tool(
+ mode,
+ SearchResultsCollector([]),
+ model=model,
+ overall_query="Research question",
+ settings_snapshot=tool_snapshot,
+ library_resolver=None
+ if source == "http"
+ else (lambda u: {"content": page, "title": title, "url": u}),
+ **tool_kwargs,
+ )
+ with (
+ patch(
+ "local_deep_research.content_fetcher.fetcher.policy_aware_validate_url",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.content_fetcher.fetcher.URLClassifier"
+ ) as classifier,
+ patch(
+ "local_deep_research.content_fetcher.fetcher.ContentFetcher._get_downloader",
+ return_value=downloader,
+ ),
+ ):
+ classifier.classify.return_value = URLType.HTML
+ classifier.get_source_name.return_value = "Web Page"
+ output = tool.invoke({"url": url, "focus": "fact"})
+ assert "Extracted fact" in output
+ recorder.invoke.assert_called_once()
+ prompt = recorder.invoke.call_args.args[0]
+ page_text = prompt.split("Page content:\n", 1)[1].split(
+ "\n\nOutput rules:", 1
+ )[0]
+ return prompt, page_text
+
+
+def _assert_prompt_fills_limit(prompt, page_text, prompt_limit):
+ assert len(prompt) == prompt_limit
+ assert page_text == PAGE[: len(page_text)]
+ # The prompt's own text is under 1500 characters here.
+ assert len(page_text) > prompt_limit - 1500
+
+
[email protected]("mode", ["summary_focus", "summary_focus_query"])
+ ("provider", "extra", "prompt_limit"),
+ [
+ # Ollama is sent the local window as num_ctx.
+ ("ollama", None, LOCAL_PROMPT_LIMIT),
+ # LM Studio and llama.cpp cap max_tokens with the same window.
+ ("lmstudio", None, LOCAL_PROMPT_LIMIT),
+ ("llamacpp", None, LOCAL_PROMPT_LIMIT),
+ # Compatible endpoints with unrestricted context may be local or
+ # private, so they assume the local window, not the cloud budget.
+ (
+ "openai_endpoint",
+ {"llm.openai_endpoint.url": "http://localhost:8000/v1"},
+ LOCAL_PROMPT_LIMIT,
+ ),
+ (
+ "anthropic_endpoint",
+ {"llm.anthropic_endpoint.url": "http://10.0.0.5:8080"},
+ LOCAL_PROMPT_LIMIT,
+ ),
+ # So does a provider LDR does not ship, such as a registered model.
+ ("my_registered_llm", None, LOCAL_PROMPT_LIMIT),
+ # A declared window is the one the build capped max_tokens with.
+ ("openai", RESTRICTED_32K, RESTRICTED_32K_PROMPT_LIMIT),
+ ("openai_endpoint", RESTRICTED_32K, RESTRICTED_32K_PROMPT_LIMIT),
+ # Unrestricted cloud context keeps the configured budget.
+ ("openai", None, None),
+ ("anthropic", None, None),
+ ],
+)
+def test_summary_prompt_fits_each_provider_class_window(
+ mode, provider, extra, prompt_limit
+):
+ snapshot = _snapshot(provider, extra)
+ model, _ = _built_model(provider, snapshot)
+ prompt, page_text = _summary_prompt(mode, model, snapshot, PAGE)
+ if prompt_limit is None:
+ assert page_text == PAGE[:500000]
+ else:
+ _assert_prompt_fills_limit(prompt, page_text, prompt_limit)
+
+
[email protected]("mode", ["summary_focus", "summary_focus_query"])
+def test_http_summary_prompt_fits_default_local_context_window(mode):
+ snapshot = _snapshot("ollama")
+ model, _ = _built_model("ollama", snapshot)
+ prompt, page_text = _summary_prompt(mode, model, snapshot, PAGE, "http")
+ _assert_prompt_fills_limit(prompt, page_text, LOCAL_PROMPT_LIMIT)
+
+
+ ("built_provider", "build_extra", "tool_snapshot", "prompt_limit"),
+ [
+ # A run that overrides a saved cloud provider with Ollama.
+ ("ollama", None, _snapshot("openai"), LOCAL_PROMPT_LIMIT),
+ # A run that overrides a saved local provider with a cloud one.
+ (
+ "openai",
+ None,
+ _snapshot("ollama", {LOCAL_WINDOW_KEY: 2048}),
+ None,
+ ),
+ # The window is the build's, not the tool snapshot's.
+ (
+ "ollama",
+ {LOCAL_WINDOW_KEY: 8192},
+ _snapshot("ollama", {LOCAL_WINDOW_KEY: 131072}),
+ FALLBACK_PROMPT_LIMIT,
+ ),
+ ],
+)
+def test_summary_prompt_limit_follows_the_model_actually_built(
+ built_provider, build_extra, tool_snapshot, prompt_limit
+):
+ model, _ = _built_model(
+ built_provider, _snapshot(built_provider, build_extra)
+ )
+ prompt, page_text = _summary_prompt(
+ "summary_focus", model, tool_snapshot, PAGE
+ )
+ if prompt_limit is None:
+ assert page_text == PAGE[:500000]
+ else:
+ _assert_prompt_fills_limit(prompt, page_text, prompt_limit)
+
+
+ ("built_provider", "extra", "prompt_limit"),
+ [
+ # A model get_llm did not build has no known provider, even when
+ # the tool snapshot names an unrestricted cloud one.
+ (None, None, LOCAL_PROMPT_LIMIT),
+ # Non-positive legacy windows fall back to 8192 tokens. Malformed
+ # managed rows retain main's explicit SettingsValueError instead.
+ ("ollama", {LOCAL_WINDOW_KEY: 0}, FALLBACK_PROMPT_LIMIT),
+ ("openai_endpoint", {LOCAL_WINDOW_KEY: -1}, FALLBACK_PROMPT_LIMIT),
+ ],
+)
+def test_unknown_or_unusable_windows_use_the_local_window(
+ built_provider, extra, prompt_limit
+):
+ snapshot = _snapshot(built_provider or "openai", extra)
+ if built_provider is None:
+ model = MagicMock()
+ else:
+ model, _ = _built_model(built_provider, snapshot)
+ prompt, page_text = _summary_prompt(
+ "summary_focus_query", model, snapshot, PAGE
+ )
+ _assert_prompt_fills_limit(prompt, page_text, prompt_limit)
+
+
+ ("provider", "key", "extra"),
+ [
+ (
+ "openai",
+ "llm.context_window_size",
+ {"llm.context_window_unrestricted": False},
+ ),
+ ("ollama", "llm.local_context_window_size", {}),
+ ("ollama", "llm.max_tokens", {}),
+ ],
+)
+def test_invalid_managed_model_budget_does_not_fetch_with_a_fallback(
+ provider, key, extra
+):
+ private_value = "private-invalid-config-value"
+ snapshot = _snapshot(
+ provider,
+ {**extra, key: {"value": private_value, "ui_element": "number"}},
+ )
+ model, recorder = _built_model(provider, snapshot)
+ resolver = MagicMock()
+ collector = SearchResultsCollector([])
+ fetch = build_fetch_tool(
+ "summary_focus",
+ collector,
+ model=model,
+ settings_snapshot=snapshot,
+ library_resolver=resolver,
+ )
+
+ message = fetch.invoke(
+ {"url": "/library/document/large-doc", "focus": "fact"}
+ )
+
+ assert "Invalid setting" in message
+ assert key in message
+ assert private_value not in message
+ resolver.assert_not_called()
+ recorder.invoke.assert_not_called()
+ assert collector.fetch_count == 0
+ assert collector.results == []
+
+
+def test_summary_budget_keeps_unsupported_managed_type_strict():
+ from local_deep_research.settings.exceptions import SettingsValueError
+ from local_deep_research.settings.manager import get_typed_setting_value
+
+ with pytest.raises(SettingsValueError, match="unsupported setting type"):
+ get_typed_setting_value(
+ SUMMARY_KEY, 500000, "unsupported", check_env=False
+ )
+
+
+ ("extra", "prompt_limit"),
+ [
+ # A smaller llm.max_tokens leaves 20480 - 1000 tokens.
+ ({"llm.max_tokens": 1000}, 77920),
+ # Without a positive max_tokens, the full 80% share is kept.
+ ({"llm.supports_max_tokens": False}, LOCAL_PROMPT_LIMIT),
+ ({"llm.max_tokens": 0}, LOCAL_PROMPT_LIMIT),
+ ],
+)
+def test_reply_allowance_follows_compute_max_tokens(extra, prompt_limit):
+ snapshot = _snapshot("ollama", extra)
+ model, _ = _built_model("ollama", snapshot)
+ prompt, page_text = _summary_prompt("summary_focus", model, snapshot, PAGE)
+ _assert_prompt_fills_limit(prompt, page_text, prompt_limit)
+
+
+def test_summary_prompt_limit_counts_the_title_and_url():
+ snapshot = _snapshot("ollama")
+ model, _ = _built_model("ollama", snapshot)
+ _, short_page = _summary_prompt("summary_focus", model, snapshot, PAGE)
+ title = "T" * 3000
+ url = "/library/document/" + "d" * 3000
+ model, _ = _built_model("ollama", snapshot)
+ prompt, page_text = _summary_prompt(
+ "summary_focus", model, snapshot, PAGE, title=title, url=url
+ )
+ assert len(prompt) == LOCAL_PROMPT_LIMIT
+ assert len(short_page) - len(page_text) == (len(title) - len("Page")) + (
+ len(url) - len("/library/document/large-doc")
+ )
+
+
+def test_window_too_small_for_the_prompt_keeps_one_page_character():
+ # 512 tokens keep 409 for the reply. The 412 characters left are fewer
+ # than the prompt's own text.
+ snapshot = _snapshot("ollama", {LOCAL_WINDOW_KEY: 512})
+ model, _ = _built_model("ollama", snapshot)
+ _, page_text = _summary_prompt("summary_focus", model, snapshot, PAGE)
+ assert page_text == PAGE[:1]
+
+
+def test_explicit_summary_budget_ignores_context_window():
+ page = "A" * 50000
+ snapshot = _snapshot("ollama", {LOCAL_WINDOW_KEY: 512})
+ model, _ = _built_model("ollama", snapshot)
+ _, page_text = _summary_prompt(
+ "summary_focus", model, snapshot, page, content_max_length=5000
+ )
+ assert page_text == page[:5000]
+
+
+def test_invalid_summary_budget_fails_before_context_window_lookup():
+ model = MagicMock()
+ resolver = MagicMock()
+ tool = build_fetch_tool(
+ "summary_focus_query",
+ SearchResultsCollector([]),
+ model=model,
+ overall_query="question",
+ settings_snapshot={
+ "llm.provider": "ollama",
+ LOCAL_WINDOW_KEY: 20480,
+ SUMMARY_KEY: "invalid",
+ },
+ library_resolver=resolver,
+ )
+ with (
+ patch(
+ "local_deep_research.llm.providers._helpers.get_context_window_for_provider"
+ ) as window,
+ patch("local_deep_research.content_fetcher.ContentFetcher") as fetcher,
+ ):
+ output = tool.invoke(
+ {"url": "https://example.com/page", "focus": "fact"}
+ )
+ assert ENV_VAR in output
+ assert "must be a positive integer" in output
+ window.assert_not_called()
+ fetcher.assert_not_called()
+ resolver.assert_not_called()
+ model.invoke.assert_not_called()
+
+
+def test_summary_budget_metadata_allows_values_outside_old_bounds():
+ from local_deep_research.settings.manager import (
+ SettingsManager,
+ validate_imported_setting_value,
+ )
+
+ meta = SettingsManager(db_session=None).default_settings[SUMMARY_KEY]
+ assert meta["value"] == 500000
+ assert meta["min_value"] == 1
+ assert meta["max_value"] is None
+ assert meta["step"] == 1
+ for value in (1, 1001, 600001):
+ assert validate_imported_setting_value(SUMMARY_KEY, value, meta) is None
+ for value in (0, -1, 1.5, None, "", True, "1e10000000"):
+ assert (
+ validate_imported_setting_value(SUMMARY_KEY, value, meta)
+ is not None
+ )
+
+
+ "module_name",
+ [
+ "settings.manager",
+ "web.routers.settings",
+ "web.services.settings_service",
+ ],
+)
+def test_summary_budget_validation_errors_hide_parser_details(
+ monkeypatch, module_name
+):
+ from local_deep_research.database.models import Setting
+
+ module = import_module(f"local_deep_research.{module_name}")
+
+ def fail_conversion(value):
+ raise ValueError("internal-parser-diagnostic")
+
+ monkeypatch.setattr(module, "to_positive_int", fail_conversion)
+ if module_name == "settings.manager":
+ error = module.validate_imported_setting_value(SUMMARY_KEY, 600001, {})
+ else:
+ valid, error = module.validate_setting(
+ Setting(key=SUMMARY_KEY, ui_element="number"), 600001
+ )
+ assert valid is False
+ assert error == "Value must be a positive integer"
+
+
[email protected]("value", [0, -1, 1.5, None, "", True, "1e10000000"])
+def test_summary_budget_save_validators_reject_unusable_values(value):
+ from local_deep_research.database.models import Setting
+ from local_deep_research.web.routers.settings import (
+ coerce_setting_for_write,
+ validate_setting as validate_router_setting,
+ )
+ from local_deep_research.web.services.settings_service import (
+ validate_setting,
+ )
+
+ setting = Setting(
+ key=SUMMARY_KEY,
+ ui_element="number",
+ min_value=1,
+ max_value=None,
+ step=1,
+ )
+ coerced = coerce_setting_for_write(SUMMARY_KEY, value, "number")
+ for validate in (validate_setting, validate_router_setting):
+ valid, error = validate(setting, coerced)
+ assert valid is False
+ assert "positive integer" in error
+
+
[email protected]("value", [1, 1001, 600001, "600001.0"])
+def test_summary_budget_save_validators_accept_valid_budgets(value):
+ from local_deep_research.database.models import Setting
+ from local_deep_research.web.routers.settings import (
+ coerce_setting_for_write,
+ validate_setting as validate_router_setting,
+ )
+ from local_deep_research.web.services.settings_service import (
+ validate_setting,
+ )
+
+ setting = Setting(
+ key=SUMMARY_KEY,
+ ui_element="number",
+ min_value=1,
+ max_value=None,
+ step=1,
+ )
+ coerced = coerce_setting_for_write(SUMMARY_KEY, value, "number")
+ for validate in (validate_setting, validate_router_setting):
+ assert validate(setting, coerced) == (True, None)
+ assert (
+ _read_summary_input_max_length_setting(
+ {SUMMARY_KEY: {"value": coerced, "ui_element": "number"}}
+ )
+ == coerced
+ )
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index b8e723e5da..1109ddb215 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -9345,11 +9345,11 @@
},
"search.fetch.content_max_length": {
"category": "search_parameters",
- "description": "Maximum page text (in characters) passed to the fetch_content and fetch_archive tools per URL before summarization. The fetched page (HTTP or local library document) is truncated to this length before it is returned directly ('full' mode) or sent to the LLM for focused extraction ('summary_focus' / 'summary_focus_query'). Increase for more complete context, decrease to keep small-model context clean. Default is 10000. Note: This setting applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools; pipeline strategies retrieve full page text upfront during search when search.snippets_only is disabled.",
+ "description": "Maximum page text (in characters) returned directly to the research agent per URL in 'full' fetch mode. Applies to HTTP pages and local library documents. Default is 10000, with a range of 1000 to 50000. Summary modes use Fetch Summary Input Max Length instead. Applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools.",
"editable": true,
"max_value": 50000,
"min_value": 1000,
- "name": "Fetch Content Max Length",
+ "name": "Fetch Full-Text Max Length",
"options": null,
"step": 500,
"type": "SEARCH",
@@ -9402,6 +9402,20 @@
"value": "summary_focus_query",
"visible": true
},
+ "search.fetch.summary_input_max_length": {
+ "category": "search_parameters",
+ "description": "Maximum page text (in characters) sent to the separate summarization step per URL in 'summary_focus' and 'summary_focus_query' fetch modes. Applies to HTTP pages and local library documents; the research agent receives the extracted summary. Default is 500000. Accepts any positive integer, with no fixed upper setting limit. Unless the research model uses a cloud provider with Use Unrestricted Cloud Context Window on, page text is also cut so the whole summarization prompt fits the model's context window minus its reply allowance, estimated at 4 characters per token; at least one character of page text is always kept. The reply allowance is Max Tokens, capped at 80% of the window, or the full 80% when Max Tokens is unset or not supported. For example, a 20480-token window with the default Max Tokens leaves 4096 tokens, or 16384 characters, for the prompt. The window is Local Provider Context Window Size for Ollama, LlamaCpp and LM Studio, and Cloud Provider Context Window Limit for other providers when Use Unrestricted Cloud Context Window is off. LDR sends the local window to Ollama only, so set it to the context length of your LlamaCpp or LM Studio server. With Use Unrestricted Cloud Context Window on, an OpenAI- or Anthropic-compatible endpoint, a provider LDR does not ship and a model LDR did not build use Local Provider Context Window Size instead. For compatible endpoints with Max Tokens supported and set, the summary call also caps requested output to the reserved allowance without changing the research model. Invalid managed context-window or reply settings must be corrected before fetching. Chinese, Japanese and other text that uses more tokens per character can still exceed the window. With unrestricted cloud context, this budget is sent as configured; larger inputs increase latency and cost. Full-text mode uses Fetch Full-Text Max Length instead. Applies exclusively to the langgraph-agent strategy's fetch_content and fetch_archive tools.",
+ "editable": true,
+ "max_value": null,
+ "min_value": 1,
+ "name": "Fetch Summary Input Max Length",
+ "options": null,
+ "step": 1,
+ "type": "SEARCH",
+ "ui_element": "number",
+ "value": 500000,
+ "visible": true
+ },
"search.final_max_results": {
"category": "search_parameters",
"description": "Maximum unique sources to include in the final research output. Applied in pipeline/source-based strategies once after all search iterations complete, deduplicating and filtering across all accumulated results. Note: Autonomous agent strategies (like langgraph-agent) manage context autonomously and do not cap final results.",
diff --git a/tests/utilities/test_research_cache_completeness.py b/tests/utilities/test_research_cache_completeness.py
index ef4417f9a5..ead9099820 100644
--- a/tests/utilities/test_research_cache_completeness.py
+++ b/tests/utilities/test_research_cache_completeness.py
@@ -346,16 +346,45 @@ def test_missing_library_chunk_can_be_retried():
@pytest.mark.parametrize(
- "mode", ["full", "summary_focus", "summary_focus_query"]
+ "mode,unrestricted_cloud",
+ [
+ ("full", True),
+ ("summary_focus", True),
+ ("summary_focus_query", True),
+ ("summary_focus", False),
+ ("summary_focus_query", False),
+ ],
)
@pytest.mark.parametrize("limit", [1_000, 10_000, 50_000])
-def test_repeated_tool_fetch_uses_same_limit_and_keeps_raw_text(mode, limit):
+def test_repeated_tool_fetch_uses_same_limit_and_keeps_raw_text(
+ mode, unrestricted_cloud, limit
+):
from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
SearchResultsCollector,
)
from local_deep_research.advanced_search_system.tools.fetch import (
build_fetch_tool,
)
+ from local_deep_research.config.llm_config import (
+ wrap_llm_without_think_tags,
+ )
+
+ settings = {
+ "search.fetch.content_max_length": {
+ "value": limit,
+ "ui_element": "number",
+ },
+ "search.fetch.summary_input_max_length": {
+ "value": limit,
+ "ui_element": "number",
+ },
+ "llm.provider": "openai",
+ "llm.context_window_unrestricted": True,
+ "llm.local_context_window_size": 8192,
+ "llm.max_tokens": 8192,
+ "llm.supports_max_tokens": True,
+ "rate_limiting.llm_enabled": False,
+ }
cache = ResearchContentCache()
raw = "Ω" * (limit + 2000)
@@ -366,12 +395,22 @@ def test_repeated_tool_fetch_uses_same_limit_and_keeps_raw_text(mode, limit):
downloader.get_metadata.return_value = {"title": "Paper"}
model = MagicMock()
model.invoke.return_value = SimpleNamespace(content="Selected text")
+ # Use the real wrapper's build metadata for unrestricted cloud input.
+ # An unwrapped model remains bounded even if the tool snapshot names a
+ # cloud provider, since it does not describe how that model was built.
+ tool_model = (
+ wrap_llm_without_think_tags(
+ model, provider="openai", settings_snapshot=settings
+ )
+ if unrestricted_cloud
+ else model
+ )
tool = build_fetch_tool(
mode,
SearchResultsCollector([]),
- model=model,
+ model=tool_model,
overall_query="Question",
- settings_snapshot={"search.fetch.content_max_length": {"value": limit}},
+ settings_snapshot=settings,
max_fetches=0,
content_cache=cache,
)
@@ -395,7 +434,31 @@ def test_repeated_tool_fetch_uses_same_limit_and_keeps_raw_text(mode, limit):
if mode != "full":
assert model.invoke.call_count == 2
outputs = [call.args[0] for call in model.invoke.call_args_list]
- assert [text.count("Ω") for text in outputs] == [limit] * 2
+ else:
+ model.invoke.assert_not_called()
+ expected_limit = limit
+ context_trims_page = False
+ if not unrestricted_cloud:
+ # Independent whole-prompt oracle: an 8192-token window reserves
+ # int(8192 * 0.8) = 6553 tokens for output, leaving 6556 characters.
+ # The fixed prompt occupies 1345/1381 characters in these cases.
+ page_limit = 5211 if mode == "summary_focus" else 5175
+ expected_limit = min(limit, page_limit)
+ if limit > page_limit:
+ context_trims_page = True
+ assert [len(text) for text in outputs] == [6556, 6556]
+ assert [text.count("Ω") for text in outputs] == [expected_limit] * 2
+ if mode != "full":
+ pages = [
+ text.split("Page content:\n", 1)[1].split("\n\nOutput rules:", 1)[0]
+ for text in outputs
+ ]
+ expected_page = raw[:expected_limit]
+ if not context_trims_page:
+ # Both cold and warm ContentFetcher results carry this marker;
+ # the whole-prompt context cap can remove it with the page tail.
+ expected_page += "\n\n[... content truncated ...]"
+ assert pages == [expected_page] * 2
assert cache.get(URL)["content"] == raw
assert downloader.download_with_result.call_count == 1
diff --git a/tests/web/routers/test_settings_save_validation_and_env_overlay.py b/tests/web/routers/test_settings_save_validation_and_env_overlay.py
index f0018ec16b..82fe0a69ad 100644
--- a/tests/web/routers/test_settings_save_validation_and_env_overlay.py
+++ b/tests/web/routers/test_settings_save_validation_and_env_overlay.py
@@ -139,6 +139,98 @@ SELECT_KEY = "app.theme"
# llm.temperature: ui_element="range", 0.0-1.0, default 0.7. Used as the
# "valid key in the same batch" that must still save.
VALID_KEY = "llm.temperature"
+SUMMARY_INPUT_KEY = "search.fetch.summary_input_max_length"
+
+
[email protected]("route", ["put", "bulk"])
+def test_summary_input_budget_errors_hide_parser_details(
+ auth_client, monkeypatch, route
+):
+ """Client validation errors must not depend on parser exception text."""
+ from local_deep_research.web.routers import settings
+
+ endpoint = f"/settings/api/{SUMMARY_INPUT_KEY}"
+ original = auth_client.get(endpoint).json()["value"]
+
+ def fail_conversion(value):
+ raise ValueError("internal-parser-diagnostic")
+
+ monkeypatch.setattr(settings, "to_positive_int", fail_conversion)
+ if route == "put":
+ response = auth_client.put(endpoint, json={"value": 600001})
+ else:
+ response = auth_client.post(
+ "/settings/save_all_settings",
+ json={SUMMARY_INPUT_KEY: 600001},
+ )
+
+ assert response.status_code == 400, response.text
+ if route == "put":
+ assert response.json() == {
+ "error": f"Invalid value for setting {SUMMARY_INPUT_KEY}"
+ }
+ else:
+ assert response.json()["errors"] == [
+ {
+ "key": SUMMARY_INPUT_KEY,
+ "name": "Fetch Summary Input Max Length",
+ "error": "Value must be a positive integer",
+ }
+ ]
+ assert "internal-parser-diagnostic" not in response.text
+ assert auth_client.get(endpoint).json()["value"] == original
+
+
[email protected]("route", ["put", "bulk", "form"])
[email protected]("recreate", [False, True])
+def test_summary_input_budget_saves_require_positive_integers(
+ auth_client, route, recreate
+):
+ """Rejected edits must not leave a saved value that breaks summary fetches."""
+ endpoint = f"/settings/api/{SUMMARY_INPUT_KEY}"
+ original = auth_client.get(endpoint).json()["value"]
+ if recreate:
+ deleted = auth_client.delete(endpoint)
+ assert deleted.status_code == 200, deleted.text
+
+ def save(value):
+ if route == "put":
+ return auth_client.put(endpoint, json={"value": value})
+ if route == "bulk":
+ return auth_client.post(
+ "/settings/save_all_settings", json={SUMMARY_INPUT_KEY: value}
+ )
+ csrf = auth_client.get("/auth/csrf-token").json()["csrf_token"]
+ return auth_client.post(
+ "/settings/save_settings",
+ data={
+ SUMMARY_INPUT_KEY: "" if value is None else str(value),
+ "csrf_token": csrf,
+ },
+ follow_redirects=False,
+ )
+
+ try:
+ for value in (1.5, None):
+ response = save(value)
+ if route == "form":
+ assert response.status_code in (302, 303), response.text
+ else:
+ assert response.status_code == 400, response.text
+ current = auth_client.get(endpoint)
+ # Defaults may be materialized again on a read after DELETE.
+ if current.status_code == 200:
+ assert current.json()["value"] == original
+ else:
+ assert recreate and current.status_code == 404, current.text
+
+ response = save(600001)
+ expected_statuses = (302, 303) if route == "form" else (200, 201)
+ assert response.status_code in expected_statuses, response.text
+ assert auth_client.get(endpoint).json()["value"] == 600001
+ finally:
+ restored = auth_client.put(endpoint, json={"value": original})
+ assert restored.status_code in (200, 201), restored.text
@pytest.mark.timeout(120)