~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(research): tolerate JSON-typed follow-up context values (#7610)
Lukas6d73b029aa5f
diff --git a/changelog.d/7610.bugfix.md b/changelog.d/7610.bugfix.mdnew file mode 100644index 0000000000..ad6053fd3e--- /dev/null+++ b/changelog.d/7610.bugfix.md@@ -0,0 +1 @@+Follow-up research and multi-turn chat no longer crash when a stored strategy name, research context, source list or prior findings value has an unexpected type; the value is ignored and the default is used.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.pyindex 166ce0d5d4..00c99df642 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@@ -15,6 +15,18 @@ from ...utilities.json_utils import get_llm_response_textfrom ...utilities.llm_utils import invoke_llm_sync+def source_entries(value: Any) -> List[Dict]:+ """+ Return the source dicts held by a research-context field.++ Read back from JSON, a field may hold any type; only a list of source+ dicts names sources, so anything else contributes none.+ """+ if not isinstance(value, list):+ return []+ return [source for source in value if isinstance(source, dict)]++class FollowUpContextHandler:"""Manages past research context for follow-up research.@@ -82,11 +94,17 @@ class FollowUpContextHandler:"""findings_parts = []+ def text(field: str) -> str:+ # Read back from JSON, a field may hold any type; only a string+ # is findings text.+ value = research_data.get(field)+ return value if isinstance(value, str) else ""+# Check various possible locations for findings- if formatted := research_data.get("formatted_findings"):+ if formatted := text("formatted_findings"):findings_parts.append(formatted)- if report := research_data.get("report_content"):+ if report := text("report_content"):# Take first part of report if no formatted findingsif not findings_parts:findings_parts.append(report[:2000])@@ -97,7 +115,7 @@ class FollowUpContextHandler:# 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"):+ if past_findings := text("past_findings"):return past_findingsreturn "No previous findings available"@@ -118,16 +136,15 @@ class FollowUpContextHandler:# Check all possible source fieldsfor field in ["resources", "all_links_of_system", "past_links"]:- if field_sources := research_data.get(field, []):- for source in field_sources:- url = source.get("url", "")- # Avoid duplicates by URL- if url and url not in seen_urls:- sources.append(source)- seen_urls.add(url)- elif not url:- # Include sources without URLs (shouldn't happen but be safe)- sources.append(source)+ for source in source_entries(research_data.get(field)):+ url = source.get("url", "")+ # Avoid duplicates by URL+ if url and url not in seen_urls:+ sources.append(source)+ seen_urls.add(url)+ elif not url:+ # Include sources without URLs (shouldn't happen but be safe)+ sources.append(source)return sourcesdiff --git a/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.pyindex 4c00b6c34b..6fb73c5d09 100644--- a/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py+++ b/src/local_deep_research/advanced_search_system/strategies/followup/enhanced_contextual_followup.py@@ -13,7 +13,10 @@ from ..base_strategy import (CHECK_CONTEXT_ENTRY,)from ...filters.followup_relevance_filter import FollowUpRelevanceFilter-from ...knowledge.followup_context_manager import FollowUpContextHandler+from ...knowledge.followup_context_manager import (+ FollowUpContextHandler,+ source_entries,+)from ...questions.followup.simple_followup_question import (SimpleFollowUpQuestionGenerator,)@@ -107,17 +110,16 @@ class EnhancedContextualFollowUpStrategy(BaseSearchStrategy):# Try to get from various fields in research_contextsources = []for field in ["resources", "all_links_of_system", "past_links"]:- if (- field in self.research_context- and self.research_context[field]- ):- sources.extend(self.research_context[field])+ sources.extend(+ source_entries(self.research_context.get(field))+ )context["past_sources"] = sources# Ensure we have the findingsif "past_findings" not in context or not context["past_findings"]:- context["past_findings"] = self.research_context.get(- "past_findings", ""+ past_findings = self.research_context.get("past_findings", "")+ context["past_findings"] = (+ past_findings if isinstance(past_findings, str) else "")# Ensure we have the original querydiff --git a/src/local_deep_research/search_system.py b/src/local_deep_research/search_system.pyindex af8b802976..f7c98f21c1 100644--- a/src/local_deep_research/search_system.py+++ b/src/local_deep_research/search_system.py@@ -130,6 +130,23 @@ class AdvancedSearchSystem:prompts to search engines."""+ # Both can come from settings or a replayed queue row, read back from+ # JSON, so either may hold any JSON type.+ if not isinstance(strategy_name, str):+ logger.warning(+ f"Ignoring non-string strategy_name "+ f"{type(strategy_name).__name__}; using source-based"+ )+ strategy_name = "source-based"+ if research_context is not None and not isinstance(+ research_context, dict+ ):+ logger.warning(+ f"Ignoring non-dict research_context "+ f"{type(research_context).__name__}"+ )+ research_context = None+# Store research context for strategiesself.research_id = research_idself.research_context = research_contextdiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 5aa987074d..2e9f3e89fe 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1384,12 +1384,24 @@ def run_research_process(research_id, query, mode, **kwargs):"chat_session_id": kwargs.get("chat_session_id"),}- # If this is a follow-up research, include the parent context- if "research_context" in kwargs and kwargs["research_context"]:+ # If this is a follow-up research, include the parent context. It is+ # read back from JSON, so the context and its findings may be of any+ # JSON type.+ parent_context = kwargs.get("research_context")+ if isinstance(parent_context, dict) and parent_context:+ past_findings = parent_context.get("past_findings", "")+ findings_chars = (+ len(past_findings) if isinstance(past_findings, str) else 0+ )logger.info(- f"Adding parent research context with {len(kwargs['research_context'].get('past_findings', ''))} chars of findings"+ f"Adding parent research context with {findings_chars} chars of findings"+ )+ shared_research_context.update(parent_context)+ elif parent_context:+ logger.warning(+ f"Ignoring non-dict research_context "+ f"{type(parent_context).__name__}")- shared_research_context.update(kwargs["research_context"])# Do not log context keys as they may contain sensitive informationlogger.info(f"Created shared_research_context for user: {username}")diff --git a/tests/advanced_search_system/knowledge/test_followup_context_manager.py b/tests/advanced_search_system/knowledge/test_followup_context_manager.pyindex 85fd0d9e1c..e117a455be 100644--- a/tests/advanced_search_system/knowledge/test_followup_context_manager.py+++ b/tests/advanced_search_system/knowledge/test_followup_context_manager.py@@ -221,6 +221,21 @@ class TestExtractFindings:result = handler._extract_findings(data)assert "Formatted text" in result+ @pytest.mark.parametrize(+ "field", ["formatted_findings", "report_content", "past_findings"]+ )+ @pytest.mark.parametrize("value", [42, ["text"], {"text": "x"}])+ def test_a_field_that_is_not_text_is_no_findings(+ self, handler, field, value+ ):+ """Read back from JSON, a findings field may hold any type."""+ result = handler._extract_findings({field: value})+ assert result == "No previous findings available"++ def test_text_findings_still_win_over_a_malformed_field(self, handler):+ data = {"formatted_findings": 42, "report_content": "Report text"}+ assert handler._extract_findings(data) == "Report text"+class TestExtractSources:"""Tests for _extract_sources method."""@@ -264,6 +279,25 @@ class TestExtractSources:result = handler._extract_sources(data)assert len(result) == 1+ @pytest.mark.parametrize(+ "value", ["just-a-string", 7, {"url": "https://a.com"}]+ )+ def test_a_field_that_is_not_a_list_names_no_sources(self, handler, value):+ """Read back from JSON, a source field may hold any type."""+ assert handler._extract_sources({"resources": value}) == []++ def test_entries_that_are_not_dicts_are_skipped(self, handler):+ data = {+ "resources": [+ "https://a.com",+ None,+ {"url": "https://b.com", "title": "B"},+ ]+ }+ assert handler._extract_sources(data) == [+ {"url": "https://b.com", "title": "B"}+ ]+def test_combines_all_source_fields(self, handler):"""Combines sources from all fields."""data = {diff --git a/tests/advanced_search_system/strategies/followup/test_enhanced_followup_high_value.py b/tests/advanced_search_system/strategies/followup/test_enhanced_followup_high_value.pyindex 36805b4c73..16df55e3e0 100644--- a/tests/advanced_search_system/strategies/followup/test_enhanced_followup_high_value.py+++ b/tests/advanced_search_system/strategies/followup/test_enhanced_followup_high_value.py@@ -91,6 +91,22 @@ class TestBuildFullContext:s.full_context = s._build_full_context()assert len(s.full_context["past_sources"]) >= 1+ def test_field_fallback_keeps_only_source_dicts(self, make_strategy):+ s = make_strategy(+ research_context={+ "resources": 7,+ "past_links": ["http://c.com"],+ "all_links_of_system": [{"url": "http://b.com"}, "x"],+ }+ )+ s.full_context = s._build_full_context()+ assert s.full_context["past_sources"] == [{"url": "http://b.com"}]++ def test_findings_fallback_ignores_a_non_string(self, make_strategy):+ s = make_strategy(research_context={"past_findings": 42})+ s.full_context = s._build_full_context()+ assert s.full_context["past_findings"] == ""+def test_past_findings_extracted(self, make_strategy):s = make_strategy(research_context={diff --git a/tests/advanced_search_system/test_strategy_contracts.py b/tests/advanced_search_system/test_strategy_contracts.pyindex a6485c9030..4e06b931af 100644--- a/tests/advanced_search_system/test_strategy_contracts.py+++ b/tests/advanced_search_system/test_strategy_contracts.py@@ -304,6 +304,72 @@ class TestStrategyDispatch:system.strategy.delegate_strategy, SourceBasedSearchStrategy)+ @pytest.mark.parametrize("name", [123, None, ["source-based"]])+ def test_non_string_strategy_name_degrades_rather_than_crashing(self, name):+ """A settings value or replayed queue row can hold any JSON type."""+ system = AdvancedSearchSystem(+ llm=MagicMock(), search=MagicMock(), strategy_name=name+ )+ assert isinstance(system.strategy, SourceBasedSearchStrategy)++ @pytest.mark.parametrize(+ "research_context", [["focused-iteration"], "text", 7]+ )+ def test_non_dict_research_context_degrades_rather_than_crashing(+ self, research_context+ ):+ system = AdvancedSearchSystem(+ llm=MagicMock(),+ search=MagicMock(),+ strategy_name="contextual-followup",+ research_context=research_context,+ )+ assert system.research_context is None+ assert isinstance(+ system.strategy.delegate_strategy, SourceBasedSearchStrategy+ )++ @pytest.mark.parametrize(+ "research_context",+ [+ {"past_findings": 42},+ {"formatted_findings": 42},+ {"report_content": ["text"]},+ {"resources": 7},+ {"resources": "https://example.com"},+ {"past_links": ["https://example.com"]},+ ],+ )+ def test_malformed_follow_up_fields_do_not_break_construction(+ self, research_context+ ):+ """The real follow-up constructor, with every consumer of the+ findings and sources fields, accepts a JSON value of any type."""+ system = AdvancedSearchSystem(+ llm=MagicMock(),+ search=MagicMock(),+ strategy_name="contextual-followup",+ research_context=research_context,+ )+ context = system.strategy.full_context+ assert context["past_sources"] == []+ assert context["past_findings"] == "No previous findings available"++ def test_well_formed_follow_up_fields_survive_construction(self):+ source = {"url": "https://a.example", "title": "A"}+ system = AdvancedSearchSystem(+ llm=MagicMock(),+ search=MagicMock(),+ strategy_name="contextual-followup",+ research_context={+ "resources": [source, "https://b.example"],+ "past_findings": "Earlier result.",+ },+ )+ context = system.strategy.full_context+ assert context["past_sources"] == [source]+ assert context["past_findings"] == "Earlier result."+@pytest.mark.parametrize("delegate", [123, None, ["focused-iteration"]])def test_non_string_delegate_degrades_rather_than_crashing(self, delegate):system = AdvancedSearchSystem(diff --git a/tests/web/services/test_research_service_coverage_main_port.py b/tests/web/services/test_research_service_coverage_main_port.pyindex 9deaf22b43..aa44dde664 100644--- a/tests/web/services/test_research_service_coverage_main_port.py+++ b/tests/web/services/test_research_service_coverage_main_port.py@@ -33,6 +33,8 @@ from contextlib import contextmanager, ExitStackfrom datetime import datetime, UTCfrom unittest.mock import create_autospec, MagicMock, patch+import pytest+from loguru import loggerfrom local_deep_research.web.services import research_service@@ -1166,7 +1168,18 @@ class TestRunResearchProcessResearchContext:stayed green."""- def test_follow_up_research_context(self):+ @pytest.mark.parametrize(+ "research_context",+ [+ {"past_findings": "previous research data" * 100},+ # Read back from JSON, the context and its findings may be of+ # any JSON type.+ {"past_findings": 42},+ ["not", "a", "dict"],+ ],+ ids=["findings", "numeric-findings", "non-dict-context"],+ )+ def test_follow_up_research_context(self, research_context):mock_session = MagicMock()research = _make_research_mock()mock_session.query.return_value.filter_by.return_value.first.return_value = research@@ -1203,9 +1216,7 @@ class TestRunResearchProcessResearchContext:settings_snapshot={"search.tool": "searxng"},model="m",search_engine="s",- research_context={- "past_findings": "previous research data" * 100- },+ research_context=research_context,)assert research.status == "completed"