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(chat): configurable prior-context for follow-up research (#4351)

LearningCircuit124b07fd95cb
diff --git a/changelog.d/+chat-llm-context-summarization.feature.md b/changelog.d/+chat-llm-context-summarization.feature.md
new file mode 100644
index 0000000000..3474cae673
--- /dev/null
+++ b/changelog.d/+chat-llm-context-summarization.feature.md
@@ -0,0 +1,8 @@
+**Configurable follow-up context in Chat Mode** — Follow-up questions now build on the earlier conversation instead of starting cold. By default, the prior conversation is condensed into a short summary focused on your new question (using your configured LLM) and passed to the follow-up research as its "previous findings", keeping multi-turn research on-topic and within context limits. You can change this with the new **Follow-up Context Mode** setting (`chat.followup_context_mode`):
+
+- `summary` (default) — an LLM summary of the conversation, focused on your new question
+- `raw` — the most recent research findings, truncated
+- `full` — the entire conversation transcript
+- `none` — no prior context (just your new question and the original topic)
+
+Only `summary` makes an extra LLM call per follow-up; the other modes add no model cost.
diff --git a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
index 381b7271a0..2e9c7d507c 100644
--- a/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
+++ b/src/local_deep_research/advanced_search_system/knowledge/followup_context_manager.py
@@ -90,6 +90,13 @@ class FollowUpContextHandler:
findings_parts.append(report[:2000])
if not findings_parts:
+ # Multi-turn chat supplies its condensed prior findings under the
+ # "past_findings" key (it has no formatted_findings/report_content
+ # of its own). Honor it before declaring nothing available —
+ # otherwise the chat-built summary is silently dropped and the
+ # follow-up prompt sees "No previous findings available".
+ if past_findings := research_data.get("past_findings"):
+ return past_findings
return "No previous findings available"
return "\n\n".join(findings_parts)
diff --git a/src/local_deep_research/advanced_search_system/summarization/__init__.py b/src/local_deep_research/advanced_search_system/summarization/__init__.py
new file mode 100644
index 0000000000..f6d73d4171
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/summarization/__init__.py
@@ -0,0 +1,14 @@
+"""LLM-based summarization utilities used across the advanced search system.
+
+The base class encapsulates the common machinery (prompt invocation, error
+handling, think-tag removal, length truncation). Subclasses implement
+``_build_prompt`` to produce different summary shapes.
+"""
+
+from .base import BaseSummarizer
+from .focused import FocusedSummarizer
+
+__all__ = [
+ "BaseSummarizer",
+ "FocusedSummarizer",
+]
diff --git a/src/local_deep_research/advanced_search_system/summarization/base.py b/src/local_deep_research/advanced_search_system/summarization/base.py
new file mode 100644
index 0000000000..7958752185
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/summarization/base.py
@@ -0,0 +1,57 @@
+"""Abstract base for LLM-driven summarizers."""
+
+from abc import ABC, abstractmethod
+
+from langchain_core.language_models.chat_models import BaseChatModel
+from loguru import logger
+
+from ...utilities.search_utilities import remove_think_tags
+
+
+class BaseSummarizer(ABC):
+ """Common machinery for invoking an LLM to summarize text.
+
+ Subclasses provide the prompt via :meth:`_build_prompt`. The base class
+ handles the model invocation, think-tag stripping, and length truncation.
+
+ On LLM-invocation failure (network error, rate limit, malformed response)
+ :meth:`summarize` returns an empty string. This is a deliberate choice for
+ callers that aggregate the summary into a larger context update — losing
+ one summary turn should not abort the rest of the update.
+ """
+
+ INPUT_TRUNCATE_CHARS = 8000
+
+ def __init__(
+ self,
+ model: BaseChatModel,
+ max_sentences: int = 3,
+ max_chars: int = 300,
+ ):
+ self.model = model
+ self.max_sentences = max_sentences
+ self.max_chars = max_chars
+
+ def summarize(self, content: str) -> str:
+ if not content:
+ return ""
+
+ prompt = self._build_prompt(content[: self.INPUT_TRUNCATE_CHARS])
+
+ try:
+ response = self.model.invoke(prompt)
+ except Exception:
+ logger.opt(exception=True).debug("LLM summarization failed")
+ return ""
+
+ summary = remove_think_tags(str(response.content)).strip()
+ return self._truncate(summary)
+
+ @abstractmethod
+ def _build_prompt(self, content: str) -> str:
+ """Return the prompt sent to the LLM for ``content``."""
+
+ def _truncate(self, summary: str) -> str:
+ if len(summary) > self.max_chars:
+ return summary[: self.max_chars].rstrip() + "..."
+ return summary
diff --git a/src/local_deep_research/advanced_search_system/summarization/focused.py b/src/local_deep_research/advanced_search_system/summarization/focused.py
new file mode 100644
index 0000000000..41448fdc56
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/summarization/focused.py
@@ -0,0 +1,29 @@
+"""LLM summarizer biased toward a focus query."""
+
+from langchain_core.language_models.chat_models import BaseChatModel
+
+from .base import BaseSummarizer
+
+
+class FocusedSummarizer(BaseSummarizer):
+ """Produces a summary biased toward aspects relevant to a focus query."""
+
+ def __init__(
+ self,
+ model: BaseChatModel,
+ focus_query: str,
+ max_sentences: int = 3,
+ max_chars: int = 300,
+ ):
+ super().__init__(
+ model, max_sentences=max_sentences, max_chars=max_chars
+ )
+ self.focus_query = focus_query
+
+ def _build_prompt(self, content: str) -> str:
+ return (
+ f"Summarize the following text in {self.max_sentences} sentence(s), "
+ f"focusing on aspects relevant to: {self.focus_query!r}. "
+ "Return ONLY the summary text, no preamble or explanation.\n\n"
+ f"Text:\n{content}"
+ )
diff --git a/src/local_deep_research/chat/context.py b/src/local_deep_research/chat/context.py
index 49d57c602c..cd73429b02 100644
--- a/src/local_deep_research/chat/context.py
+++ b/src/local_deep_research/chat/context.py
@@ -11,6 +11,8 @@ Multi-turn chat requires:
from typing import Dict, Any, List, Optional
+from loguru import logger
+
from ..config.thread_settings import get_setting_from_snapshot
@@ -25,6 +27,19 @@ class ChatContextManager:
MAX_CONTEXT_MESSAGES = 10 # Recent messages to include fully
MAX_FINDINGS_TO_INCLUDE = 5 # Recent findings to include
+ # Limits for the query-focused conversation summary that becomes the
+ # follow-up prompt's "previous findings" block.
+ CONTEXT_SUMMARY_MAX_SENTENCES = 8
+ CONTEXT_SUMMARY_MAX_CHARS = 2000
+ # Transcript char budget kept below BaseSummarizer.INPUT_TRUNCATE_CHARS
+ # (8000) so the summarizer's own truncation never has to drop the most
+ # recent turns — we trim oldest-first ourselves below.
+ CONTEXT_INPUT_CHAR_BUDGET = 7500
+
+ # Default for the chat.followup_context_mode setting (summary | raw |
+ # full | none) — what prior context a follow-up turn receives.
+ DEFAULT_FOLLOWUP_CONTEXT_MODE = "summary"
+
def __init__(
self,
session_id: str,
@@ -52,6 +67,9 @@ class ChatContextManager:
if isinstance(msg, dict) and msg.get("message_type") != "step"
]
self.accumulated_context = accumulated_context or {}
+ # Used by build_research_context to construct the LLM that produces
+ # the query-focused conversation summary.
+ self.settings_snapshot = settings_snapshot
# Override class defaults from settings if provided.
# Note: settings_snapshot is the 4th keyword arg; passing it positionally
@@ -68,20 +86,26 @@ class ChatContextManager:
settings_snapshot=settings_snapshot,
)
- def build_research_context(self) -> Dict[str, Any]:
+ def build_research_context(self, current_query: str = "") -> Dict[str, Any]:
"""
Build context for the next research query.
+ Args:
+ current_query: The user's new message. On a follow-up turn it is
+ used to focus a summary of the whole prior conversation, which
+ becomes the follow-up prompt's "previous findings". On the
+ first turn there is no prior work to summarize.
+
Returns dict with:
- session_id: Current session
- conversation_history: Recent messages
- - accumulated_findings: Key findings from previous research
+ - accumulated_findings / past_findings: Prior work for the follow-up
+ (query-focused summary on follow-ups; empty on the first turn)
- accumulated_sources: Deduplicated sources
- key_entities: Important entities mentioned
- topics: Topics discussed
- is_multi_turn: Whether this is a follow-up
"""
- findings = self._extract_findings_from_history()
# The follow-up strategy reads "original_query" to anchor the prompt on
# the topic that started the conversation; without it the contextual
# follow-up loses the original question. Use the session's first user
@@ -94,6 +118,14 @@ class ChatContextManager:
),
"",
)
+
+ is_multi_turn = any(
+ isinstance(m, dict) and m.get("role") == "assistant"
+ for m in self.messages
+ )
+
+ findings = self._select_prior_findings(current_query, is_multi_turn)
+
return {
"session_id": self.session_id,
"original_query": original_query,
@@ -103,13 +135,109 @@ class ChatContextManager:
"accumulated_sources": self._extract_sources_from_history(),
"key_entities": self._get_key_entities(),
"topics": self._get_topics(),
- "is_multi_turn": any(
- isinstance(m, dict) and m.get("role") == "assistant"
- for m in self.messages
- ),
+ "is_multi_turn": is_multi_turn,
"turn_count": len(self.messages),
}
+ def _select_prior_findings(
+ self, current_query: str, is_multi_turn: bool
+ ) -> str:
+ """Pick the follow-up's "previous findings" per chat.followup_context_mode.
+
+ Modes:
+ - ``summary`` (default): query-focused LLM summary of the conversation
+ - ``raw``: recent research findings, truncated
+ - ``full``: the entire conversation transcript
+ - ``none``: no prior findings
+
+ Only follow-up turns carry prior work; the first turn returns "".
+ """
+ if not is_multi_turn:
+ return ""
+
+ mode = self.DEFAULT_FOLLOWUP_CONTEXT_MODE
+ if self.settings_snapshot:
+ mode = get_setting_from_snapshot(
+ "chat.followup_context_mode",
+ mode,
+ settings_snapshot=self.settings_snapshot,
+ )
+
+ if mode == "none":
+ return ""
+ if mode == "raw":
+ return self._extract_findings_from_history()
+ if mode == "full":
+ return self._build_conversation_text()
+ # "summary": needs the new question to focus on; without one (e.g. a
+ # no-arg build_research_context call) fall back to raw recent findings.
+ if current_query:
+ return self._summarize_prior_work(current_query)
+ return self._extract_findings_from_history()
+
+ def _build_conversation_text(self) -> str:
+ """Render the prior conversation (both roles) as a plain transcript.
+
+ Trims oldest-first to ``CONTEXT_INPUT_CHAR_BUDGET`` so the most recent
+ turns survive and the summarizer's input cap never has to truncate.
+ """
+ lines: List[str] = []
+ used = 0
+ for msg in reversed(self.messages):
+ if not isinstance(msg, dict):
+ continue
+ content = (msg.get("content") or "").strip()
+ if not content:
+ continue
+ role = (msg.get("role") or "unknown").capitalize()
+ line = f"{role}: {content}"
+ remaining = self.CONTEXT_INPUT_CHAR_BUDGET - used
+ if remaining <= 0:
+ break
+ if len(line) > remaining:
+ if lines:
+ # Budget already spent on more recent turns — stop rather
+ # than partially including an older one.
+ break
+ # The most recent turn alone exceeds the budget: keep its head
+ # so the transcript still fits the summarizer's input cap.
+ line = line[:remaining]
+ lines.append(line)
+ used += len(line)
+ lines.reverse()
+ return "\n\n".join(lines)
+
+ def _summarize_prior_work(self, current_query: str) -> str:
+ """Summarize the prior conversation, focused on ``current_query``.
+
+ Returns an empty string when there is no prior conversation, the LLM
+ cannot be constructed (e.g. a misconfigured provider), or the LLM call
+ itself fails. The summary is additive context, so a failure here must
+ not crash the follow-up request — the research dispatch that follows
+ surfaces a genuinely-broken LLM through its own error handling.
+ """
+ transcript = self._build_conversation_text()
+ if not transcript:
+ return ""
+
+ from ..config.llm_config import get_llm
+ from ..advanced_search_system.summarization import FocusedSummarizer
+
+ try:
+ llm = get_llm(settings_snapshot=self.settings_snapshot)
+ except Exception:
+ logger.opt(exception=True).debug(
+ "Could not build LLM for chat context summary; skipping"
+ )
+ return ""
+
+ return FocusedSummarizer(
+ llm,
+ focus_query=current_query,
+ max_sentences=self.CONTEXT_SUMMARY_MAX_SENTENCES,
+ max_chars=self.CONTEXT_SUMMARY_MAX_CHARS,
+ ).summarize(transcript)
+
def build_prompt_context(self) -> str:
"""
Build a text context string suitable for including in prompts.
diff --git a/src/local_deep_research/chat/routes.py b/src/local_deep_research/chat/routes.py
index d8a843368c..84c93e96c3 100644
--- a/src/local_deep_research/chat/routes.py
+++ b/src/local_deep_research/chat/routes.py
@@ -961,7 +961,12 @@ def send_message(session_id):
session_data.get("accumulated_context"),
settings_snapshot=settings_snapshot,
)
- research_context = context_manager.build_research_context()
+ # Pass the new user message so prior conversation is condensed
+ # into a summary focused on this question (used as the follow-up
+ # prompt's "previous findings").
+ research_context = context_manager.build_research_context(
+ current_query=content
+ )
research_id = str(uuid.uuid4())
# Parse numeric search settings up-front. A malformed value
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index eac102a616..fbc530d51e 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -338,6 +338,25 @@
"value": true,
"visible": false
},
+ "chat.followup_context_mode": {
+ "category": "chat",
+ "description": "What prior conversation context a follow-up research turn receives as its 'previous findings'. 'Focused summary' uses the LLM to summarize the whole conversation toward the new question (one extra LLM call per follow-up); 'Raw recent findings' reuses recent answers truncated; 'Full transcript' sends the entire conversation; 'None' sends no prior findings.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Follow-up Context Mode",
+ "options": [
+ {"label": "Focused summary (LLM)", "value": "summary"},
+ {"label": "Raw recent findings", "value": "raw"},
+ {"label": "Full conversation transcript", "value": "full"},
+ {"label": "None", "value": "none"}
+ ],
+ "step": null,
+ "type": "CHAT",
+ "ui_element": "select",
+ "value": "summary",
+ "visible": true
+ },
"chat.llm_title_generation": {
"category": "chat",
"description": "Use LLM to generate descriptive chat session titles instead of simple query truncation. When disabled, titles are the first 100 characters of the query.",
diff --git a/tests/advanced_search_system/knowledge/test_followup_context_manager.py b/tests/advanced_search_system/knowledge/test_followup_context_manager.py
index 9e4ff53174..85fd0d9e1c 100644
--- a/tests/advanced_search_system/knowledge/test_followup_context_manager.py
+++ b/tests/advanced_search_system/knowledge/test_followup_context_manager.py
@@ -95,6 +95,22 @@ class TestBuildContext:
)
assert isinstance(result, dict)
+ def test_build_context_surfaces_chat_past_findings(self, handler):
+ """End-to-end of the fix: a chat-style context (only past_findings,
+ no formatted_findings/report_content) surfaces its summary as
+ past_findings, so it reaches generate_contextualized_query instead of
+ being replaced by the 'No previous findings available' sentinel."""
+ chat_context = {
+ "research_id": "r1",
+ "original_query": "What is machine learning?",
+ "past_findings": "Summary of the conversation, focused on cost.",
+ }
+ result = handler.build_context(chat_context, "How much does it cost?")
+ assert (
+ result["past_findings"]
+ == "Summary of the conversation, focused on cost."
+ )
+
def test_build_context_includes_parent_research_id(
self, handler, sample_research_data
):
@@ -177,6 +193,25 @@ class TestExtractFindings:
result = handler._extract_findings(data)
assert result == "No previous findings available"
+ def test_honors_chat_past_findings_when_no_report(self, handler):
+ """Multi-turn chat supplies prior findings under ``past_findings``
+ (it has no formatted_findings/report_content); that must be used as
+ the findings rather than the "nothing available" sentinel."""
+ data = {"past_findings": "Condensed summary of the conversation."}
+ result = handler._extract_findings(data)
+ assert result == "Condensed summary of the conversation."
+
+ def test_report_content_takes_precedence_over_past_findings(self, handler):
+ """Non-chat callers populate report_content; past_findings must not
+ override it (keeps the standalone follow-up path unchanged)."""
+ data = {
+ "report_content": "Full parent report.",
+ "past_findings": "should not be used",
+ }
+ result = handler._extract_findings(data)
+ assert "Full parent report." in result
+ assert "should not be used" not in result
+
def test_prefers_formatted_over_report(self, handler):
"""Prefers formatted_findings over report_content."""
data = {
diff --git a/tests/advanced_search_system/summarization/__init__.py b/tests/advanced_search_system/summarization/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/advanced_search_system/summarization/test_summarizers.py b/tests/advanced_search_system/summarization/test_summarizers.py
new file mode 100644
index 0000000000..fc0acbbcea
--- /dev/null
+++ b/tests/advanced_search_system/summarization/test_summarizers.py
@@ -0,0 +1,84 @@
+"""Unit tests for the summarization module.
+
+Covers BaseSummarizer machinery (input cap, truncation, think-tag stripping,
+error handling) and the FocusedSummarizer prompt via a concrete summarizer.
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.advanced_search_system.summarization import (
+ FocusedSummarizer,
+)
+
+
+def _fake_model(content: str) -> Mock:
+ model = Mock()
+ model.invoke.return_value = Mock(content=content)
+ return model
+
+
+class TestFocusedSummarizer:
+ def test_returns_llm_output_when_under_limit(self):
+ model = _fake_model("Short summary.")
+ result = FocusedSummarizer(model, focus_query="q").summarize(
+ "some long content here"
+ )
+
+ assert result == "Short summary."
+ model.invoke.assert_called_once()
+
+ def test_empty_content_skips_llm_call(self):
+ model = _fake_model("never used")
+ result = FocusedSummarizer(model, focus_query="q").summarize("")
+
+ assert result == ""
+ model.invoke.assert_not_called()
+
+ def test_truncates_summary_above_max_chars(self):
+ long_text = "X" * 500
+ model = _fake_model(long_text)
+ result = FocusedSummarizer(
+ model, focus_query="q", max_chars=100
+ ).summarize("input")
+
+ assert len(result) == 103 # 100 chars + "..."
+ assert result.endswith("...")
+
+ def test_strips_think_tags_from_response(self):
+ model = _fake_model(
+ "<think>internal reasoning</think>Actual summary content."
+ )
+ result = FocusedSummarizer(model, focus_query="q").summarize("input")
+
+ assert "internal reasoning" not in result
+ assert "Actual summary content." in result
+
+ def test_returns_empty_string_on_llm_exception(self):
+ model = Mock()
+ model.invoke.side_effect = RuntimeError("rate limited")
+
+ result = FocusedSummarizer(model, focus_query="q").summarize(
+ "some content"
+ )
+
+ assert result == ""
+
+ def test_truncates_oversized_input_before_prompting(self):
+ model = _fake_model("ok")
+ oversize_input = "A" * 50000
+ FocusedSummarizer(model, focus_query="q").summarize(oversize_input)
+
+ prompt = model.invoke.call_args.args[0]
+ # The base class caps input at INPUT_TRUNCATE_CHARS so the LLM call
+ # stays bounded rather than carrying the entire 50k input.
+ assert len(prompt) < 50000
+
+ def test_focus_query_and_max_sentences_in_prompt(self):
+ model = _fake_model("ok")
+ FocusedSummarizer(
+ model, focus_query="What about cost?", max_sentences=7
+ ).summarize("hello")
+
+ prompt = model.invoke.call_args.args[0]
+ assert "7 sentence" in prompt
+ assert "What about cost?" in prompt
diff --git a/tests/chat/conftest.py b/tests/chat/conftest.py
index 776def1ac0..3d4759dfd8 100644
--- a/tests/chat/conftest.py
+++ b/tests/chat/conftest.py
@@ -7,6 +7,28 @@ from contextlib import contextmanager
from datetime import datetime
[email protected](autouse=True)
+def _stub_request_path_llm():
+ """Keep the send-message request path from making real LLM calls.
+
+ build_research_context() condenses prior turns into a query-focused
+ summary via get_llm() before research is dispatched. Most chat tests
+ don't exercise that summary (they mock the research worker), so stub the
+ LLM to keep them fast and deterministic regardless of provider
+ availability. Tests that assert on the summary patch get_llm themselves,
+ which overrides this stub within their own context.
+ """
+ fake_llm = MagicMock()
+ fake_llm.invoke.return_value = MagicMock(
+ content="stub conversation summary"
+ )
+ with patch(
+ "local_deep_research.config.llm_config.get_llm",
+ return_value=fake_llm,
+ ):
+ yield
+
+
def generate_unique_test_username():
"""Generate a unique test username to avoid conflicts in parallel tests."""
return f"test_user_{uuid.uuid4().hex[:8]}"
diff --git a/tests/chat/test_chat_context_manager.py b/tests/chat/test_chat_context_manager.py
index d012aeccbd..05bb732dab 100644
--- a/tests/chat/test_chat_context_manager.py
+++ b/tests/chat/test_chat_context_manager.py
@@ -457,3 +457,163 @@ class TestChatContextManagerKeyEntitiesAndTopics:
assert "topics" in result
assert isinstance(result["topics"], list)
assert len(result["topics"]) <= 10
+
+
+class TestBuildResearchContextFocusedSummary:
+ """build_research_context condenses prior turns into a query-focused summary."""
+
+ def _conversation(self):
+ return [
+ {
+ "role": "user",
+ "content": "What is quantum computing?",
+ "message_type": "query",
+ },
+ {
+ "role": "assistant",
+ "content": "Quantum computing uses qubits and superposition.",
+ "message_type": "response",
+ "research_id": "r1",
+ },
+ ]
+
+ def test_focused_summary_used_as_past_findings(self, mocker):
+ """With a query + snapshot, past_findings is the focused LLM summary."""
+ from src.local_deep_research.chat.context import ChatContextManager
+
+ fake_llm = mocker.Mock()
+ fake_llm.invoke.return_value = mocker.Mock(
+ content="Prior work, focused on cost."
+ )
+ get_llm = mocker.patch(
+ "src.local_deep_research.config.llm_config.get_llm",
+ return_value=fake_llm,
+ )
+
+ manager = ChatContextManager(
+ session_id="s1",
+ messages=self._conversation(),
+ accumulated_context={},
+ settings_snapshot={"llm.provider": "ollama"},
+ )
+ result = manager.build_research_context(
+ current_query="How much does it cost?"
+ )
+
+ assert result["past_findings"] == "Prior work, focused on cost."
+ assert result["accumulated_findings"] == "Prior work, focused on cost."
+ get_llm.assert_called_once()
+ # The new question must drive the focus of the summary prompt.
+ prompt = fake_llm.invoke.call_args.args[0]
+ assert "How much does it cost?" in prompt
+ # The transcript fed to the summarizer includes both roles.
+ assert "User:" in prompt and "Assistant:" in prompt
+
+ def test_no_current_query_uses_raw_findings(self, mocker):
+ """A no-arg call (no focus question) makes no LLM call."""
+ from src.local_deep_research.chat.context import ChatContextManager
+
+ get_llm = mocker.patch(
+ "src.local_deep_research.config.llm_config.get_llm"
+ )
+ manager = ChatContextManager(
+ session_id="s1",
+ messages=self._conversation(),
+ accumulated_context={},
+ settings_snapshot={"llm.provider": "ollama"},
+ )
+ result = manager.build_research_context()
+
+ get_llm.assert_not_called()
+ assert "qubits" in result["past_findings"].lower()
+
+
+class TestFollowupContextModes:
+ """chat.followup_context_mode selects what prior context a follow-up gets."""
+
+ def _conversation(self):
+ return [
+ {
+ "role": "user",
+ "content": "What is quantum computing?",
+ "message_type": "query",
+ },
+ {
+ "role": "assistant",
+ "content": "Quantum computing uses qubits and superposition.",
+ "message_type": "response",
+ "research_id": "r1",
+ },
+ ]
+
+ def _manager(self, mode):
+ from src.local_deep_research.chat.context import ChatContextManager
+
+ return ChatContextManager(
+ session_id="s1",
+ messages=self._conversation(),
+ accumulated_context={},
+ settings_snapshot={"chat.followup_context_mode": mode},
+ )
+
+ def test_raw_mode_uses_recent_findings_no_llm(self, mocker):
+ get_llm = mocker.patch(
+ "src.local_deep_research.config.llm_config.get_llm"
+ )
+ result = self._manager("raw").build_research_context(
+ current_query="cost?"
+ )
+
+ get_llm.assert_not_called()
+ assert "qubits" in result["past_findings"].lower()
+
+ def test_full_mode_sends_whole_transcript_no_llm(self, mocker):
+ get_llm = mocker.patch(
+ "src.local_deep_research.config.llm_config.get_llm"
+ )
+ result = self._manager("full").build_research_context(
+ current_query="cost?"
+ )
+
+ get_llm.assert_not_called()
+ past = result["past_findings"]
+ assert "User:" in past and "Assistant:" in past
+ assert "What is quantum computing?" in past
+
+ def test_none_mode_sends_no_prior_findings_no_llm(self, mocker):
+ get_llm = mocker.patch(
+ "src.local_deep_research.config.llm_config.get_llm"
+ )
+ result = self._manager("none").build_research_context(
+ current_query="cost?"
+ )
+
+ get_llm.assert_not_called()
+ assert result["past_findings"] == ""
+
+ def test_summary_mode_invokes_llm(self, mocker):
+ fake_llm = mocker.Mock()
+ fake_llm.invoke.return_value = mocker.Mock(content="Focused summary.")
+ mocker.patch(
+ "src.local_deep_research.config.llm_config.get_llm",
+ return_value=fake_llm,
+ )
+ result = self._manager("summary").build_research_context(
+ current_query="cost?"
+ )
+
+ assert result["past_findings"] == "Focused summary."
+ fake_llm.invoke.assert_called_once()
+
+ def test_summary_mode_empty_when_llm_cannot_be_built(self, mocker):
+ """A get_llm() failure (e.g. misconfigured provider) degrades the
+ summary to empty rather than crashing the follow-up request."""
+ mocker.patch(
+ "src.local_deep_research.config.llm_config.get_llm",
+ side_effect=RuntimeError("no provider configured"),
+ )
+ result = self._manager("summary").build_research_context(
+ current_query="cost?"
+ )
+
+ assert result["past_findings"] == ""
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index a580f6ec25..94d5584698 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -583,6 +583,37 @@
"value": 0,
"visible": true
},
+ "chat.followup_context_mode": {
+ "category": "chat",
+ "description": "What prior conversation context a follow-up research turn receives as its 'previous findings'. 'Focused summary' uses the LLM to summarize the whole conversation toward the new question (one extra LLM call per follow-up); 'Raw recent findings' reuses recent answers truncated; 'Full transcript' sends the entire conversation; 'None' sends no prior findings.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Follow-up Context Mode",
+ "options": [
+ {
+ "label": "Focused summary (LLM)",
+ "value": "summary"
+ },
+ {
+ "label": "Raw recent findings",
+ "value": "raw"
+ },
+ {
+ "label": "Full conversation transcript",
+ "value": "full"
+ },
+ {
+ "label": "None",
+ "value": "none"
+ }
+ ],
+ "step": null,
+ "type": "CHAT",
+ "ui_element": "select",
+ "value": "summary",
+ "visible": true
+ },
"chat.llm_title_generation": {
"category": "chat",
"description": "Use LLM to generate descriptive chat session titles instead of simple query truncation. When disabled, titles are the first 100 characters of the query.",