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(langgraph): add search.fetch.mode setting (full | summary | disabled) (#3680)

LearningCircuit69cf6f3885b3
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 87abbe522d..497ae3d816 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -24,6 +24,7 @@ from ...utilities.search_utilities import (
extract_links_from_search_results,
format_links_to_markdown,
)
+from ..tools.fetch import FETCH_MODES, build_fetch_tool
from .base_strategy import BaseSearchStrategy
# ---------------------------------------------------------------------------
@@ -37,8 +38,8 @@ MIN_ITERATIONS = 10 # below this the agent can barely do anything useful
SUBAGENT_TIMEOUT_SECONDS = 1800 # 30 minutes per subagent
MAX_SUBTOPICS = 8
MAX_SUBAGENT_WORKERS = 4
-CONTENT_FETCH_TIMEOUT = 30
-CONTENT_MAX_LENGTH = 10_000
+# CONTENT_FETCH_TIMEOUT and CONTENT_MAX_LENGTH live alongside the fetch
+# tool builders in advanced_search_system/tools/fetch/.
# ---------------------------------------------------------------------------
@@ -186,44 +187,8 @@ def _make_web_search_tool(
return web_search
-def _make_fetch_content_tool(collector: SearchResultsCollector):
- """Create a ``fetch_content`` tool using ContentFetcher."""
-
- @tool
- def fetch_content(url: str) -> str:
- """Download and read the full text content from a URL. Use when search snippets aren't detailed enough."""
- from local_deep_research.content_fetcher import ContentFetcher
-
- try:
- with ContentFetcher(timeout=CONTENT_FETCH_TIMEOUT) as fetcher:
- result = fetcher.fetch(url, max_length=CONTENT_MAX_LENGTH)
- if result.get("status") == "success":
- title = result.get("title", "")
- content = result.get("content", "")
-
- # Register in collector for citation tracking.
- existing_idx = collector.find_by_url(url)
- if existing_idx is not None:
- cite_idx = existing_idx
- else:
- snippet = content[:200].strip()
- if len(content) > 200:
- snippet += "..."
- start = collector.add_results(
- [{"title": title, "link": url, "snippet": snippet}],
- engine_name="fetch",
- )
- cite_idx = start + 1 # 1-based
-
- return (
- f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{content}"
- )
- return f"Failed to fetch {url}: {result.get('error', 'unknown error')}"
- except Exception as exc:
- logger.exception("fetch_content tool error")
- return f"Error fetching {url}: {exc}"
-
- return fetch_content
+# Fetch tool builders (full / summary_focus / summary_focus_query / disabled)
+# live in ``advanced_search_system.tools.fetch``; see ``build_fetch_tool``.
def _make_specialized_search_tool(
@@ -278,8 +243,16 @@ def _make_research_subtopic_tool(
max_sub_iterations: int,
progress_callback=None,
programmatic_mode: bool = False,
+ fetch_mode: str = "full",
+ overall_query: str = "",
):
- """Create the ``research_subtopic`` tool that spawns parallel subagents."""
+ """Create the ``research_subtopic`` tool that spawns parallel subagents.
+
+ ``overall_query`` is the original user query passed by the lead agent's
+ strategy; it's forwarded to summary-mode fetch tools so the per-page
+ extractor sees both the agent's per-fetch focus and the original
+ research question.
+ """
@tool
def research_subtopic(subtopics: list[str]) -> str:
@@ -321,11 +294,19 @@ def _make_research_subtopic_tool(
collector,
programmatic_mode=programmatic_mode,
)
- sub_fetch = _make_fetch_content_tool(collector)
+ sub_tools = [sub_web_search]
+ sub_fetch = build_fetch_tool(
+ fetch_mode,
+ collector,
+ model=model,
+ overall_query=overall_query,
+ )
+ if sub_fetch is not None:
+ sub_tools.append(sub_fetch)
try:
agent = create_agent(
model=model,
- tools=[sub_web_search, sub_fetch],
+ tools=sub_tools,
system_prompt=subagent_prompt,
)
result = agent.invoke(
@@ -445,6 +426,16 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
)
self.collector = SearchResultsCollector(self.all_links_of_system)
+ fetch_mode = self.get_setting("search.fetch.mode", "full")
+ if fetch_mode not in FETCH_MODES:
+ logger.warning(
+ f"Unknown search.fetch.mode={fetch_mode!r}, falling back to 'full'. "
+ f"Valid modes: {FETCH_MODES}"
+ )
+ fetch_mode = "full"
+ self.fetch_mode = fetch_mode
+ logger.info(f"LangGraph agent fetch_mode={self.fetch_mode}")
+
# Derive the search engine name for creating fresh instances
self._search_engine_name = self._resolve_engine_name()
@@ -471,8 +462,13 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
logger.debug("Could not extract engine name from class")
return ""
- def _build_tools(self) -> list:
- """Build the LangChain tool list for the lead agent."""
+ def _build_tools(self, overall_query: str = "") -> list:
+ """Build the LangChain tool list for the lead agent.
+
+ ``overall_query`` is the original user query; it's threaded into
+ summary-mode fetch tools so the per-page extractor sees both the
+ agent's per-fetch focus and the original research question.
+ """
tools = []
# Web search (always present if we have a search engine)
@@ -487,8 +483,15 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
)
)
- # Content fetcher
- tools.append(_make_fetch_content_tool(self.collector))
+ # Content fetcher (returns None when fetch_mode == 'disabled')
+ fetch = build_fetch_tool(
+ self.fetch_mode,
+ self.collector,
+ model=self.model,
+ overall_query=overall_query,
+ )
+ if fetch is not None:
+ tools.append(fetch)
# Specialized search engines
try:
@@ -533,6 +536,8 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
self.max_sub_iterations,
progress_callback=self.progress_callback,
programmatic_mode=self.programmatic_mode,
+ fetch_mode=self.fetch_mode,
+ overall_query=overall_query,
)
)
@@ -556,13 +561,27 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
)
self.check_termination()
- # Build tools
- tools = self._build_tools()
+ # Build tools (overall_query feeds summary-mode fetch tools)
+ tools = self._build_tools(overall_query=query)
if not tools:
return self._error_result("No tools available")
- # Build system prompt
+ # Build system prompt — fetch_line wording mirrors the active mode
+ # so the agent isn't told to use a tool that doesn't exist.
current_date = datetime.now(UTC).strftime("%Y-%m-%d")
+ if self.fetch_mode == "disabled":
+ fetch_line = (
+ "3. Rely on search snippets — full-page fetching is disabled "
+ "for this run.\n"
+ )
+ elif self.fetch_mode in ("summary_focus", "summary_focus_query"):
+ fetch_line = (
+ "3. Use fetch_content(url, focus) when snippets aren't enough; "
+ "always pass the specific question or claim you want answered "
+ "as ``focus`` so the tool returns only the relevant facts.\n"
+ )
+ else: # full
+ fetch_line = "3. Use fetch_content to read full pages when snippets aren't enough.\n"
system_prompt = (
f"You are a research assistant writing a research report. Today's date: {current_date}.\n"
"This is NOT a chat conversation. Your only job is to research the "
@@ -574,7 +593,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
"1. Start with web_search for initial exploration.\n"
"2. For complex multi-faceted questions, use research_subtopic to "
"investigate specific aspects in parallel (pass 2-5 focused questions).\n"
- "3. Use fetch_content to read full pages when snippets aren't enough.\n"
+ f"{fetch_line}"
"4. Use search_[engine] tools for domain-specific searches "
"(search_arxiv for science, search_pubmed for medical, etc.).\n"
"5. When you have enough information, provide a comprehensive answer "
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
new file mode 100644
index 0000000000..ba4bf4a1f5
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
@@ -0,0 +1,219 @@
+"""Agent-facing ``fetch_content`` tool builders.
+
+Public API:
+ FETCH_MODES — tuple of valid mode strings.
+ build_fetch_tool() — returns a LangChain ``@tool`` (or ``None`` when
+ mode == "disabled" so the caller can skip
+ registration).
+
+Modes:
+ disabled — fetch tool is not registered with the agent.
+ full — return the full extracted page text (legacy
+ behavior; can flood small-model context with
+ boilerplate / metadata enrichment).
+ summary_focus — LLM extracts only spans relevant to a focus
+ question the agent supplies per call.
+ summary_focus_query — same as above, but the prompt also includes
+ the original research query (passed in
+ programmatically by the strategy) so the
+ extractor can disambiguate vague focuses.
+
+Each tool registers fetched URLs in the strategy's
+``SearchResultsCollector`` for citation tracking, returning the result as
+``[N] Title: ...\\nURL: ...\\n\\n<body>`` exactly like the original
+in-strategy implementation, so downstream prompt formatting is unchanged.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from langchain_core.language_models import BaseChatModel
+from langchain_core.tools import tool
+from loguru import logger
+
+from .prompts import SUMMARY_FOCUS_PROMPT, SUMMARY_FOCUS_QUERY_PROMPT
+
+# Per-call timeouts and caps. Kept here rather than in the strategy file
+# because they are properties of the fetch tool, not of agent
+# orchestration.
+CONTENT_FETCH_TIMEOUT = 30
+CONTENT_MAX_LENGTH = 10_000
+
+FETCH_MODES = (
+ "disabled",
+ "full",
+ "summary_focus",
+ "summary_focus_query",
+)
+
+
+def _register_in_collector(
+ collector: Any,
+ url: str,
+ title: str,
+ snippet_source: str,
+) -> int:
+ """Register a fetched URL in the collector and return its 1-based citation index.
+
+ If the URL was already tracked (via a prior search hit) the existing
+ index is reused so the agent sees a stable citation per URL.
+ """
+ existing_idx = collector.find_by_url(url)
+ if existing_idx is not None:
+ return existing_idx
+ snippet = snippet_source[:200].strip()
+ if len(snippet_source) > 200:
+ snippet += "..."
+ start = collector.add_results(
+ [{"title": title, "link": url, "snippet": snippet}],
+ engine_name="fetch",
+ )
+ return start + 1
+
+
+def _make_full_fetch_tool(collector: Any):
+ @tool
+ def fetch_content(url: str) -> str:
+ """Download and read the full text content from a URL. Use when search snippets aren't detailed enough."""
+ from local_deep_research.content_fetcher import ContentFetcher
+
+ try:
+ with ContentFetcher(timeout=CONTENT_FETCH_TIMEOUT) as fetcher:
+ result = fetcher.fetch(url, max_length=CONTENT_MAX_LENGTH)
+ if result.get("status") == "success":
+ title = result.get("title", "")
+ content = result.get("content", "")
+ cite_idx = _register_in_collector(
+ collector, url, title, content
+ )
+ return (
+ f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{content}"
+ )
+ return f"Failed to fetch {url}: {result.get('error', 'unknown error')}"
+ except Exception as exc:
+ logger.exception("fetch_content tool error")
+ return f"Error fetching {url}: {exc}"
+
+ return fetch_content
+
+
+def _make_summary_fetch_tool(
+ collector: Any,
+ model: BaseChatModel,
+ overall_query: str | None,
+):
+ """Build the summary-mode fetch tool.
+
+ overall_query=None → focus-only prompt (``summary_focus`` mode).
+ overall_query=str → focus + overall-query prompt (``summary_focus_query``).
+ """
+ use_query = bool(overall_query)
+ template = SUMMARY_FOCUS_QUERY_PROMPT if use_query else SUMMARY_FOCUS_PROMPT
+
+ mode_label = "summary_focus_query" if use_query else "summary_focus"
+
+ @tool
+ def fetch_content(url: str, focus: str) -> str:
+ """Fetch a URL and return only the spans of text relevant to ``focus``.
+ Pass the specific question or claim you want answered as ``focus`` — the
+ tool will quote relevant facts verbatim and discard unrelated content.
+ """
+ from local_deep_research.content_fetcher import ContentFetcher
+
+ try:
+ with ContentFetcher(timeout=CONTENT_FETCH_TIMEOUT) as fetcher:
+ result = fetcher.fetch(url, max_length=CONTENT_MAX_LENGTH)
+ if result.get("status") != "success":
+ return f"Failed to fetch {url}: {result.get('error', 'unknown error')}"
+
+ title = result.get("title", "")
+ content = result.get("content", "")
+
+ fmt_kwargs = {
+ "focus": focus,
+ "title": title,
+ "url": url,
+ "content": content,
+ }
+ if use_query:
+ fmt_kwargs["overall_query"] = overall_query
+ prompt = template.format(**fmt_kwargs)
+
+ try:
+ summary_msg = model.invoke(prompt)
+ summary = getattr(
+ summary_msg, "content", str(summary_msg)
+ ).strip()
+ except Exception as exc:
+ logger.exception("fetch_content summary LLM error")
+ return f"Error summarizing {url}: {exc}"
+
+ # Diagnostic log: per-fetch input/output for evaluating the
+ # summariser. Single multi-line block so it's atomic per call
+ # and easy to grep with ``grep -A1000 "[FETCH] mode="``.
+ log_lines = [
+ f"[FETCH] mode={mode_label} url={url}",
+ f"[FETCH] focus: {focus}",
+ ]
+ if use_query:
+ log_lines.append(f"[FETCH] overall_query: {overall_query}")
+ log_lines.extend(
+ [
+ f"[FETCH] title: {title}",
+ f"[FETCH] page_text ({len(content)} chars):",
+ content,
+ f"[FETCH] summary returned ({len(summary)} chars):",
+ summary or "(empty)",
+ "[FETCH] ---",
+ ]
+ )
+ logger.info("\n".join(log_lines))
+
+ cite_idx = _register_in_collector(
+ collector, url, title, summary or content
+ )
+ return f"[{cite_idx}] Title: {title}\nURL: {url}\n\n{summary}"
+ except Exception as exc:
+ logger.exception("fetch_content tool error")
+ return f"Error fetching {url}: {exc}"
+
+ return fetch_content
+
+
+def build_fetch_tool(
+ mode: str,
+ collector: Any,
+ *,
+ model: BaseChatModel | None = None,
+ overall_query: str = "",
+):
+ """Build the agent-facing ``fetch_content`` tool for *mode*.
+
+ Returns ``None`` when ``mode == 'disabled'``; the caller should not
+ register the tool with the agent in that case (and the system prompt
+ should also drop the corresponding instruction line so the agent
+ isn't told to use a tool that doesn't exist).
+ """
+ if mode == "disabled":
+ return None
+ if mode == "full":
+ return _make_full_fetch_tool(collector)
+ if mode == "summary_focus":
+ if model is None:
+ raise ValueError("summary_focus fetch mode requires a model")
+ return _make_summary_fetch_tool(collector, model, overall_query=None)
+ if mode == "summary_focus_query":
+ if model is None:
+ raise ValueError("summary_focus_query fetch mode requires a model")
+ # Empty overall_query falls back to focus-only behaviour at format
+ # time; we keep the *_query mode label so logs stay diagnostic.
+ return _make_summary_fetch_tool(
+ collector, model, overall_query=overall_query or None
+ )
+ raise ValueError(
+ f"Unknown fetch mode {mode!r}; expected one of {FETCH_MODES}"
+ )
+
+
+__all__ = ["FETCH_MODES", "build_fetch_tool"]
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/prompts.py b/src/local_deep_research/advanced_search_system/tools/fetch/prompts.py
new file mode 100644
index 0000000000..a64575eee3
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/prompts.py
@@ -0,0 +1,61 @@
+"""Prompts used by summary-mode fetch tools.
+
+Kept separate from builder code so the wording can be tuned without
+touching the wiring. Both prompts share the same role-framing block —
+small local models (qwen3, gpt-oss) calibrate measurably better when
+told what's downstream of their output.
+"""
+
+# Role-framing block included by every summary prompt.
+_ROLE = (
+ "You are a content-extraction step inside a multi-step research agent.\n\n"
+ "Your role in the pipeline:\n"
+ "- The agent has already run web searches and decided this specific "
+ "page is worth reading more carefully than its snippet allowed.\n"
+ "- Your output is returned to the agent as a tool result. The agent — "
+ "not you — will combine your output with other sources and write the "
+ "final cited answer.\n"
+ "- Therefore you are an extractor, NOT an answerer. Do not interpret, "
+ "conclude, or compose. Just pull the relevant raw text out of the page."
+)
+
+# Output rules, identical for both variants.
+_RULES = (
+ "Output rules:\n"
+ "- Output ONLY verbatim quotes from the page. Copy numbers, names, "
+ "dates, and proper nouns exactly as written — never paraphrase facts.\n"
+ "- One quote per line. No bullets, no numbering, no section headers.\n"
+ "- Omit navigation, ads, cookie/subscription banners, related-article "
+ "lists, author bios, comments, and anything off-topic.\n"
+ "- If nothing on the page helps, reply with exactly: NOT RELEVANT\n"
+ "- Do NOT include introductions ('Here is the relevant information:'), "
+ "conclusions ('In summary...'), explanations of what you kept or "
+ "skipped, or commentary on the source's quality, bias, or relevance.\n"
+ "- Maximum 1500 characters. Quality over quantity — fewer precise "
+ "quotes beat many borderline ones."
+)
+
+
+# Focus-only variant: the agent declares what it's looking for on this page.
+SUMMARY_FOCUS_PROMPT = (
+ f"{_ROLE}\n\n"
+ "Why this page was fetched: {focus}\n\n"
+ "Page title: {title}\n"
+ "Page URL: {url}\n"
+ "Page content:\n{content}\n\n"
+ f"{_RULES}"
+)
+
+
+# Focus + overall-query variant: agent's focus PLUS the original research
+# question, so the extractor can disambiguate vague focus phrasings
+# ("publication year" vs "publication year of Liepmann's Prandtl-Ring award").
+SUMMARY_FOCUS_QUERY_PROMPT = (
+ f"{_ROLE}\n\n"
+ "Overall research question: {overall_query}\n"
+ "Why this page was fetched: {focus}\n\n"
+ "Page title: {title}\n"
+ "Page URL: {url}\n"
+ "Page content:\n{content}\n\n"
+ f"{_RULES}"
+)
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 28d5bdc7eb..f0a925fb49 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -785,6 +785,37 @@
"value": 4000,
"visible": true
},
+ "search.fetch.mode": {
+ "category": "search_parameters",
+ "description": "Controls the LangGraph agent's fetch_content tool. 'full' returns the entire extracted page text (current behavior; can flood small-model context with boilerplate/metadata). 'summary_focus' makes the tool ask the LLM to extract only spans relevant to a focus question the agent supplies per call. 'summary_focus_query' is the same but also includes the original research query in the extraction prompt, so a vague focus can be disambiguated. 'disabled' removes the tool entirely so the agent works from search snippets only — useful for diagnosing whether full-page fetching is hurting accuracy.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Fetch Content Mode",
+ "options": [
+ {
+ "label": "Full Page Text",
+ "value": "full"
+ },
+ {
+ "label": "Focused Summary (Page-Specific Question Only)",
+ "value": "summary_focus"
+ },
+ {
+ "label": "Focused Summary (Page-Specific Question + Overall Query)",
+ "value": "summary_focus_query"
+ },
+ {
+ "label": "Disabled (Snippets Only)",
+ "value": "disabled"
+ }
+ ],
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "select",
+ "value": "full",
+ "visible": true
+ },
"search.iterations": {
"category": null,
"description": "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.",
diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.py
new file mode 100644
index 0000000000..d29c48c3da
--- /dev/null
+++ b/tests/advanced_search_system/tools/test_fetch_modes.py
@@ -0,0 +1,148 @@
+"""Unit tests for ``advanced_search_system.tools.fetch.build_fetch_tool``.
+
+Pins the mode dispatch and the prompt-content contract for the two
+summary variants (focus-only vs focus + overall query). Avoids any real
+HTTP — patches ``ContentFetcher`` and the model.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+)
+from local_deep_research.advanced_search_system.tools.fetch import (
+ FETCH_MODES,
+ build_fetch_tool,
+)
+
+
+def _fetcher_cm(*, status="success", title="Page", content="Body text"):
+ fetcher = MagicMock()
+ fetcher.fetch.return_value = {
+ "status": status,
+ "title": title,
+ "content": content,
+ }
+ cm = MagicMock()
+ cm.__enter__.return_value = fetcher
+ cm.__exit__.return_value = False
+ return cm
+
+
+def _model_returning(text: str):
+ """A model whose ``invoke`` returns an object with ``.content == text``."""
+ msg = MagicMock()
+ msg.content = text
+ model = MagicMock()
+ model.invoke.return_value = msg
+ return model
+
+
+def test_fetch_modes_constant_lists_all_supported_values():
+ assert FETCH_MODES == (
+ "disabled",
+ "full",
+ "summary_focus",
+ "summary_focus_query",
+ )
+
+
+def test_disabled_mode_returns_none():
+ assert build_fetch_tool("disabled", SearchResultsCollector([])) is None
+
+
+def test_full_mode_returns_tool_with_url_only_signature():
+ tool = build_fetch_tool("full", SearchResultsCollector([]))
+ assert tool is not None
+ assert "url" in tool.args
+ assert "focus" not in tool.args
+
+
+def test_summary_focus_requires_model():
+ with pytest.raises(ValueError, match="summary_focus"):
+ build_fetch_tool("summary_focus", SearchResultsCollector([]))
+
+
+def test_summary_focus_query_requires_model():
+ with pytest.raises(ValueError, match="summary_focus_query"):
+ build_fetch_tool("summary_focus_query", SearchResultsCollector([]))
+
+
+def test_summary_focus_tool_calls_model_with_focus_only_prompt():
+ collector = SearchResultsCollector([])
+ model = _model_returning("relevant fact 1")
+ tool = build_fetch_tool(
+ "summary_focus",
+ collector,
+ model=model,
+ overall_query="should not appear",
+ )
+ assert tool is not None
+ assert "focus" in tool.args
+
+ cm = _fetcher_cm(title="T", content="page body")
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm
+ ):
+ out = tool.invoke({"url": "http://example.com/", "focus": "year of X"})
+
+ model.invoke.assert_called_once()
+ prompt = model.invoke.call_args[0][0]
+ # focus-only mode must NOT mention the overall query, even if one was passed
+ assert "Why this page was fetched: year of X" in prompt
+ assert "Overall research question" not in prompt
+ # Output is prefixed with citation index so the agent can cite consistently
+ assert out.startswith("[1] ")
+ assert "relevant fact 1" in out
+
+
+def test_summary_focus_query_includes_overall_query_in_prompt():
+ collector = SearchResultsCollector([])
+ model = _model_returning("relevant fact 2")
+ tool = build_fetch_tool(
+ "summary_focus_query",
+ collector,
+ model=model,
+ overall_query="When did Liepmann receive the Prandtl-Ring Award?",
+ )
+ cm = _fetcher_cm(title="T", content="page body")
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm
+ ):
+ tool.invoke({"url": "http://example.com/", "focus": "year"})
+
+ prompt = model.invoke.call_args[0][0]
+ assert (
+ "Overall research question: When did Liepmann receive the Prandtl-Ring Award?"
+ in prompt
+ )
+ assert "Why this page was fetched: year" in prompt
+
+
+def test_summary_focus_query_with_empty_overall_query_falls_back_to_focus_only():
+ """An empty overall_query should not produce a stale 'Overall research question:' line."""
+ collector = SearchResultsCollector([])
+ model = _model_returning("ok")
+ tool = build_fetch_tool(
+ "summary_focus_query",
+ collector,
+ model=model,
+ overall_query="", # empty
+ )
+ cm = _fetcher_cm()
+ with patch(
+ "local_deep_research.content_fetcher.ContentFetcher", return_value=cm
+ ):
+ tool.invoke({"url": "http://example.com/", "focus": "x"})
+
+ prompt = model.invoke.call_args[0][0]
+ assert "Overall research question" not in prompt
+
+
+def test_unknown_mode_raises_with_valid_modes_listed():
+ with pytest.raises(ValueError, match="Unknown fetch mode"):
+ build_fetch_tool("magic", SearchResultsCollector([]))
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 917994c65f..746c334938 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -7236,6 +7236,37 @@
],
"visible": true
},
+ "search.fetch.mode": {
+ "category": "search_parameters",
+ "description": "Controls the LangGraph agent's fetch_content tool. 'full' returns the entire extracted page text (current behavior; can flood small-model context with boilerplate/metadata). 'summary_focus' makes the tool ask the LLM to extract only spans relevant to a focus question the agent supplies per call. 'summary_focus_query' is the same but also includes the original research query in the extraction prompt, so a vague focus can be disambiguated. 'disabled' removes the tool entirely so the agent works from search snippets only — useful for diagnosing whether full-page fetching is hurting accuracy.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Fetch Content Mode",
+ "options": [
+ {
+ "label": "Full Page Text",
+ "value": "full"
+ },
+ {
+ "label": "Focused Summary (Page-Specific Question Only)",
+ "value": "summary_focus"
+ },
+ {
+ "label": "Focused Summary (Page-Specific Question + Overall Query)",
+ "value": "summary_focus_query"
+ },
+ {
+ "label": "Disabled (Snippets Only)",
+ "value": "disabled"
+ }
+ ],
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "select",
+ "value": "full",
+ "visible": true
+ },
"search.final_max_results": {
"category": "search_parameters",
"description": "Maximum unique sources to include in the final research output. Applied once after all search iterations complete, deduplicating and filtering across all accumulated results.",
diff --git a/tests/strategies/test_langgraph_agent_strategy.py b/tests/strategies/test_langgraph_agent_strategy.py
index 44c204fa0f..c4f701961e 100644
--- a/tests/strategies/test_langgraph_agent_strategy.py
+++ b/tests/strategies/test_langgraph_agent_strategy.py
@@ -544,11 +544,11 @@ class TestFetchContentCollectorRegistration:
return cm
def _make_tool(self, collector):
- from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
- _make_fetch_content_tool,
+ from local_deep_research.advanced_search_system.tools.fetch import (
+ build_fetch_tool,
)
- return _make_fetch_content_tool(collector)
+ return build_fetch_tool("full", collector)
def test_successful_fetch_registers_url_in_collector(self):
collector = self._make_collector()