~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: Reduce repetition in detailed reports by passing previous section context (#1542)
LearningCircuit77d3af5792f9
diff --git a/src/local_deep_research/api/research_functions.py b/src/local_deep_research/api/research_functions.pyindex a333ff89fd..819e3aa072 100644--- a/src/local_deep_research/api/research_functions.py+++ b/src/local_deep_research/api/research_functions.py@@ -422,6 +422,7 @@ def generate_report(search_system=system,llm=system.model,searches_per_section=searches_per_section,+ settings_snapshot=kwargs.get("settings_snapshot"),)report = report_generator.generate_report(initial_findings, query)diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex 2ef92ff44e..adfcf3352b 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -711,6 +711,34 @@"value": false,"visible": true},+ "report.max_context_sections": {+ "category": "report_parameters",+ "description": "Number of previous sections to include as context when generating new sections (helps reduce repetition in detailed reports)",+ "editable": true,+ "max_value": 10,+ "min_value": 1,+ "name": "Max Context Sections",+ "options": null,+ "step": 1,+ "type": "REPORT",+ "ui_element": "number",+ "value": 3,+ "visible": true+ },+ "report.max_context_chars": {+ "category": "report_parameters",+ "description": "Maximum characters for context when generating sections (lower values are safer for smaller local models)",+ "editable": true,+ "max_value": 50000,+ "min_value": 1000,+ "name": "Max Context Characters",+ "options": null,+ "step": 500,+ "type": "REPORT",+ "ui_element": "number",+ "value": 4000,+ "visible": true+ },"search.iterations": {"category": null,"description": "Maximum number of sequential search cycles to perform. Each iteration generates new follow-up questions based on previous results to progressively expand and refine the research.",diff --git a/src/local_deep_research/report_generator.py b/src/local_deep_research/report_generator.pyindex d1886e0205..ed33fc68c3 100644--- a/src/local_deep_research/report_generator.py+++ b/src/local_deep_research/report_generator.py@@ -1,5 +1,5 @@import importlib-from typing import Dict, List+from typing import Dict, List, Optionalfrom datetime import datetime, UTCfrom langchain_core.language_models import BaseChatModel@@ -7,9 +7,19 @@ from loguru import logger# Fix circular import by importing directly from source modulesfrom .config.llm_config import get_llm+from .config.thread_settings import get_setting_from_snapshotfrom .search_system import AdvancedSearchSystemfrom .utilities import search_utilities+# Default constants for context accumulation to avoid repetition+# These are used as fallbacks when settings are not available+DEFAULT_MAX_CONTEXT_SECTIONS = (+ 3 # Number of previous sections to include as context+)+DEFAULT_MAX_CONTEXT_CHARS = (+ 4000 # Max characters for context (safe for smaller local models)+)+def get_report_generator(search_system=None):"""Return an instance of the report generator with default settings.@@ -26,6 +36,7 @@ class IntegratedReportGenerator:searches_per_section: int = 2,search_system=None,llm: BaseChatModel | None = None,+ settings_snapshot: Optional[Dict] = None,):"""Args:@@ -34,6 +45,7 @@ class IntegratedReportGenerator:search_system: Custom search system to use, otherwise just usesthe default.llm: Custom LLM to use. Required if search_system is not provided.+ settings_snapshot: Optional settings snapshot for configurable values."""# If search_system is provided, use its LLM; otherwise use the provided LLM@@ -52,6 +64,18 @@ class IntegratedReportGenerator:searches_per_section # Control search depth per section)+ # Load context settings from snapshot or use defaults+ self.max_context_sections = get_setting_from_snapshot(+ "report.max_context_sections",+ default=DEFAULT_MAX_CONTEXT_SECTIONS,+ settings_snapshot=settings_snapshot,+ )+ self.max_context_chars = get_setting_from_snapshot(+ "report.max_context_chars",+ default=DEFAULT_MAX_CONTEXT_CHARS,+ settings_snapshot=settings_snapshot,+ )+def generate_report(self, initial_findings: Dict, query: str) -> Dict:"""Generate a complete research report with section-specific research."""@@ -155,15 +179,114 @@ class IntegratedReportGenerator:return structure+ def _truncate_at_sentence_boundary(self, text: str, max_chars: int) -> str:+ """Truncate text at a sentence boundary to preserve readability.++ Attempts to cut at the last sentence-ending punctuation (.!?) before+ the limit. If no suitable boundary is found within 80% of the limit,+ falls back to hard truncation.++ Args:+ text: The text to truncate+ max_chars: Maximum characters allowed++ Returns:+ Truncated text with [...truncated] marker if truncation occurred+ """+ if len(text) <= max_chars:+ return text++ truncated = text[:max_chars]++ # Look for sentence boundaries (. ! ?) followed by space or newline+ # Search backwards from the end for the last complete sentence+ last_sentence_end = -1+ for i in range(len(truncated) - 1, -1, -1):+ if truncated[i] in ".!?" and (+ i + 1 >= len(truncated) or truncated[i + 1] in " \n"+ ):+ last_sentence_end = i + 1+ break++ # Only use sentence boundary if it preserves at least 80% of content+ min_acceptable = int(max_chars * 0.8)+ if last_sentence_end > min_acceptable:+ return truncated[:last_sentence_end] + "\n[...truncated]"++ # Fallback to hard truncation+ return truncated + "\n[...truncated]"++ def _build_previous_context(self, accumulated_findings: List[str]) -> str:+ """Build context block from previously generated sections.++ Creates a formatted context block containing content from the last+ N sections (defined by self.max_context_sections) with explicit instructions+ not to repeat this content. Context is truncated if it exceeds+ self.max_context_chars to stay safe for smaller local models.++ Args:+ accumulated_findings: List of previously generated section content,+ each formatted as "[Section > Subsection]\\n{content}"++ Returns:+ Formatted context block with delimiters, or empty string if no+ previous findings exist+ """+ if not accumulated_findings:+ return ""++ recent_findings = accumulated_findings[-self.max_context_sections :]+ previous_context = "\n\n---\n\n".join(recent_findings)++ # Truncate at sentence boundary if too long+ if len(previous_context) > self.max_context_chars:+ previous_context = self._truncate_at_sentence_boundary(+ previous_context, self.max_context_chars+ )++ return (+ f"\n\n=== CONTENT ALREADY WRITTEN (DO NOT REPEAT) ===\n"+ f"{previous_context}\n"+ f"=== END OF PREVIOUS CONTENT ===\n\n"+ f"CRITICAL: The above content has already been written. Do NOT repeat "+ f"these points, examples, or explanations. Focus on NEW information "+ f"not covered above.\n"+ )+def _research_and_generate_sections(self,initial_findings: Dict,structure: List[Dict],query: str,) -> Dict[str, str]:- """Research and generate content for each section in one step."""+ """Research and generate content for each section in one step.++ This method processes sections sequentially, accumulating generated+ content as it goes. For each new section/subsection, it passes context+ from the last few previously generated sections to help the LLM avoid+ repetition.++ The context accumulation mechanism:+ - Tracks all generated content in accumulated_findings list+ - Before generating each section, builds context from recent findings+ - Uses self.max_context_sections (configurable, default: 3) to limit context size+ - Truncates context to self.max_context_chars (configurable, default: 4000) for safety+ - Includes explicit "DO NOT REPEAT" instructions with actual content++ Args:+ initial_findings: Results from initial research phase, may contain+ questions_by_iteration to preserve search continuity+ structure: List of section definitions, each with name and subsections+ query: Original user query for context++ Returns:+ Dict mapping section names to their generated markdown content+ """sections = {}+ # Accumulate content from previous sections to avoid repetition+ accumulated_findings: List[str] = []+# Preserve questions from initial research to avoid repetition# This follows the same pattern as citation tracking (all_links_of_system)existing_questions = initial_findings.get("questions_by_iteration", {})@@ -240,6 +363,11 @@ class IntegratedReportGenerator:# Check if this is actually a section-level content (only one subsection, likely auto-created)is_section_level = len(section["subsections"]) == 1+ # Build context from previously generated sections to avoid repetition+ previous_context_section = self._build_previous_context(+ accumulated_findings+ )+# Generate appropriate search queryif is_section_level:# Section-level prompt - more comprehensive@@ -248,7 +376,7 @@ class IntegratedReportGenerator:f"Section purpose: {subsection['purpose']} "f"\n"f"Other sections in the report:\n{other_sections_text}\n"- f"\n"+ f"{previous_context_section}"f"This is a standalone section requiring comprehensive coverage of its topic. "f"Provide a thorough exploration that may include synthesis of information from previous sections where relevant. "f"Include unique insights, specific examples, and concrete data. "@@ -266,7 +394,7 @@ class IntegratedReportGenerator:f"Other sections in the report:\n{other_sections_text}\n"f"\n"f"Other subsections in this section will cover:\n{other_subsections_text}\n"- f"\n"+ f"{previous_context_section}"f"Focus ONLY on information specific to your subsection's purpose. "f"Include unique details, specific examples, and concrete data. "f"Use tables to organize information where applicable. "@@ -292,8 +420,11 @@ class IntegratedReportGenerator:# Add the researched content for this subsectionif subsection_results.get("current_knowledge"):- section_content.append(- subsection_results["current_knowledge"]+ generated_content = subsection_results["current_knowledge"]+ section_content.append(generated_content)+ # Accumulate for context in subsequent sections+ accumulated_findings.append(+ f"[{section['name']} > {subsection['name']}]\n{generated_content}")else:section_content.append(diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 6eb44cb988..7b5bde6c77 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -1232,7 +1232,8 @@ def run_research_process(# Pass the existing search system to maintain citation indicesreport_generator = IntegratedReportGenerator(- search_system=search_system+ search_system=search_system,+ settings_snapshot=settings_snapshot,)final_report = report_generator.generate_report(results, query)diff --git a/tests/test_report_generator.py b/tests/test_report_generator.pyindex e9c5a2259b..6b2deb8d9a 100644--- a/tests/test_report_generator.py+++ b/tests/test_report_generator.py@@ -305,3 +305,711 @@ def test_generate_error_report(report_generator):assert "Test query" in error_reportassert "Error message" in error_report+++def test_context_accumulation_across_sections(report_generator):+ """Test that previous section content is passed to subsequent sections."""+ # Define a structure with multiple sections+ structure = [+ {+ "name": "Section A",+ "subsections": [{"name": "Part 1", "purpose": "First part"}],+ },+ {+ "name": "Section B",+ "subsections": [{"name": "Part 2", "purpose": "Second part"}],+ },+ {+ "name": "Section C",+ "subsections": [{"name": "Part 3", "purpose": "Third part"}],+ },+ ]++ # Track the queries passed to analyze_topic+ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {"current_knowledge": f"Content for query about {query[:50]}"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ # Generate sections+ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial findings"}, structure, "Test query"+ )++ # Verify that analyze_topic was called 3 times+ assert len(captured_queries) == 3++ # First section should NOT have previous context+ assert "CONTENT ALREADY WRITTEN" not in captured_queries[0]++ # Second section SHOULD have previous context from first section+ assert "CONTENT ALREADY WRITTEN" in captured_queries[1]+ assert "Section A" in captured_queries[1]++ # Third section SHOULD have previous context from first and second sections+ assert "CONTENT ALREADY WRITTEN" in captured_queries[2]+ assert "Section A" in captured_queries[2]+ assert "Section B" in captured_queries[2]+++def test_context_accumulation_limits_to_last_3_sections(report_generator):+ """Test that only the last 3 sections are included in context."""+ # Define a structure with 5 sections+ structure = [+ {+ "name": f"Section {i}",+ "subsections": [{"name": f"Part {i}", "purpose": f"Purpose {i}"}],+ }+ for i in range(1, 6)+ ]++ # Track the queries+ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {+ "current_knowledge": f"Content for section {len(captured_queries)}"+ }++ report_generator.search_system.analyze_topic.side_effect = capture_query++ # Generate sections+ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial findings"}, structure, "Test query"+ )++ # The 5th section should only have context from sections 2, 3, 4 (last 3)+ # Section 1 content should NOT be in the 5th query+ fifth_query = captured_queries[4]++ # Count how many section references are in the context+ # Sections 2, 3, 4 should be present, Section 1 should not+ assert "Section 2" in fifth_query+ assert "Section 3" in fifth_query+ assert "Section 4" in fifth_query+ # Section 1 should have been dropped (only last 3 kept)+ # Check that the context section exists but Section 1 is not in it+ assert "CONTENT ALREADY WRITTEN" in fifth_query+++def test_context_truncation_for_large_content(report_generator):+ """Test that context is truncated when it exceeds 4000 characters."""+ # Define structure with sections that will generate large content+ structure = [+ {+ "name": "Section A",+ "subsections": [+ {"name": "Large Part", "purpose": "Generate large content"}+ ],+ },+ {+ "name": "Section B",+ "subsections": [+ {"name": "Next Part", "purpose": "Should see truncated context"}+ ],+ },+ ]++ # Track queries+ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ # Return large content for first section (over 4000 chars)+ if len(captured_queries) == 1:+ return {"current_knowledge": "X" * 5000} # 5000 chars+ return {"current_knowledge": "Normal content"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ # Generate sections+ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial findings"}, structure, "Test query"+ )++ # Second query should have truncated context+ second_query = captured_queries[1]+ assert "CONTENT ALREADY WRITTEN" in second_query+ assert "[...truncated]" in second_query+++def test_context_includes_section_labels(report_generator):+ """Test that accumulated content includes section/subsection labels."""+ structure = [+ {+ "name": "Introduction",+ "subsections": [+ {"name": "Overview", "purpose": "Provide overview"}+ ],+ },+ {+ "name": "Details",+ "subsections": [+ {"name": "Specifics", "purpose": "Provide details"}+ ],+ },+ ]++ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {"current_knowledge": "Some content here"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Second query should have labeled content from first section+ second_query = captured_queries[1]+ assert "[Introduction > Overview]" in second_query+++def test_no_context_for_first_section(report_generator):+ """Test that the first section has no previous context."""+ structure = [+ {+ "name": "First Section",+ "subsections": [{"name": "First Part", "purpose": "First purpose"}],+ },+ ]++ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {"current_knowledge": "Content"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # First (and only) query should not have previous context markers+ assert "CONTENT ALREADY WRITTEN" not in captured_queries[0]+ assert "DO NOT REPEAT" not in captured_queries[0]+++def test_context_accumulation_with_multiple_subsections(report_generator):+ """Test that context accumulates correctly across multiple subsections within a section."""+ structure = [+ {+ "name": "Main Section",+ "subsections": [+ {"name": "Sub A", "purpose": "First subsection"},+ {"name": "Sub B", "purpose": "Second subsection"},+ {"name": "Sub C", "purpose": "Third subsection"},+ ],+ },+ ]++ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {+ "current_knowledge": f"Content from subsection {len(captured_queries)}"+ }++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Should have 3 queries (one per subsection)+ assert len(captured_queries) == 3++ # First subsection: no context+ assert "CONTENT ALREADY WRITTEN" not in captured_queries[0]++ # Second subsection: should have Sub A content+ assert "CONTENT ALREADY WRITTEN" in captured_queries[1]+ assert "Sub A" in captured_queries[1]++ # Third subsection: should have Sub A and Sub B content+ assert "CONTENT ALREADY WRITTEN" in captured_queries[2]+ assert "Sub A" in captured_queries[2]+ assert "Sub B" in captured_queries[2]+++def test_context_includes_critical_instruction(report_generator):+ """Test that the CRITICAL instruction is included in prompts with context."""+ structure = [+ {+ "name": "Section 1",+ "subsections": [{"name": "Part 1", "purpose": "Purpose 1"}],+ },+ {+ "name": "Section 2",+ "subsections": [{"name": "Part 2", "purpose": "Purpose 2"}],+ },+ ]++ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {"current_knowledge": "Some content"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Second query should have the CRITICAL instruction+ second_query = captured_queries[1]+ assert "CRITICAL" in second_query+ assert "Do NOT repeat" in second_query+ assert "Focus on NEW information" in second_query+++def test_context_with_empty_subsection_content(report_generator):+ """Test that empty subsection results don't break context accumulation."""+ structure = [+ {+ "name": "Section 1",+ "subsections": [+ {"name": "Empty Part", "purpose": "Returns nothing"}+ ],+ },+ {+ "name": "Section 2",+ "subsections": [+ {"name": "Normal Part", "purpose": "Returns content"}+ ],+ },+ {+ "name": "Section 3",+ "subsections": [{"name": "Final Part", "purpose": "Should work"}],+ },+ ]++ call_count = [0]++ def capture_query(query):+ call_count[0] += 1+ if call_count[0] == 1:+ # First subsection returns no content+ return {"current_knowledge": None}+ return {"current_knowledge": f"Content {call_count[0]}"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ # Should not raise an error+ sections = report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Sections should still be generated+ assert "Section 1" in sections+ assert "Section 2" in sections+ assert "Section 3" in sections+++def test_context_format_has_clear_delimiters(report_generator):+ """Test that context block has clear start and end delimiters."""+ structure = [+ {+ "name": "First",+ "subsections": [{"name": "A", "purpose": "First"}],+ },+ {+ "name": "Second",+ "subsections": [{"name": "B", "purpose": "Second"}],+ },+ ]++ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {"current_knowledge": "Content here"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ second_query = captured_queries[1]++ # Check for clear delimiters+ assert "=== CONTENT ALREADY WRITTEN (DO NOT REPEAT) ===" in second_query+ assert "=== END OF PREVIOUS CONTENT ===" in second_query++ # Verify delimiters appear in correct order+ start_pos = second_query.find("=== CONTENT ALREADY WRITTEN")+ end_pos = second_query.find("=== END OF PREVIOUS CONTENT")+ assert start_pos < end_pos+++def test_section_level_vs_subsection_level_prompts(report_generator):+ """Test that both section-level (single subsection) and subsection-level prompts get context."""+ structure = [+ {+ "name": "Standalone Section",+ "subsections": [+ {"name": "Only Part", "purpose": "Single subsection"}+ ],+ },+ {+ "name": "Multi Section",+ "subsections": [+ {"name": "Part A", "purpose": "First of multiple"},+ {"name": "Part B", "purpose": "Second of multiple"},+ ],+ },+ ]++ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {"current_knowledge": f"Content {len(captured_queries)}"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Query 0: Standalone section (section-level, no context)+ assert "CONTENT ALREADY WRITTEN" not in captured_queries[0]++ # Query 1: First part of multi-section (subsection-level, has context)+ assert "CONTENT ALREADY WRITTEN" in captured_queries[1]+ assert "Standalone Section" in captured_queries[1]++ # Query 2: Second part of multi-section (subsection-level, has context)+ assert "CONTENT ALREADY WRITTEN" in captured_queries[2]+++def test_context_preserves_content_integrity(report_generator):+ """Test that the actual content is preserved in context, not just labels."""+ structure = [+ {+ "name": "Section A",+ "subsections": [{"name": "Part 1", "purpose": "First"}],+ },+ {+ "name": "Section B",+ "subsections": [{"name": "Part 2", "purpose": "Second"}],+ },+ ]++ unique_content = "UNIQUE_MARKER_12345_THIS_SHOULD_APPEAR_IN_CONTEXT"+ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ if len(captured_queries) == 1:+ return {"current_knowledge": unique_content}+ return {"current_knowledge": "Other content"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # The unique content from section 1 should appear in section 2's query+ assert unique_content in captured_queries[1]+++def test_context_with_special_characters(report_generator):+ """Test that content with special characters doesn't break context."""+ structure = [+ {+ "name": "Section 1",+ "subsections": [{"name": "Part 1", "purpose": "First"}],+ },+ {+ "name": "Section 2",+ "subsections": [{"name": "Part 2", "purpose": "Second"}],+ },+ ]++ special_content = "Content with 'quotes', \"double quotes\", {braces}, [brackets], and $pecial ch@rs!"+ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ if len(captured_queries) == 1:+ return {"current_knowledge": special_content}+ return {"current_knowledge": "Normal"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ # Should not raise any errors+ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Special content should be in second query's context+ assert special_content in captured_queries[1]+++def test_accumulated_findings_count_matches_subsections(report_generator):+ """Test that the number of accumulated findings matches successful subsections."""+ structure = [+ {+ "name": "Section 1",+ "subsections": [+ {"name": "Sub 1", "purpose": "P1"},+ {"name": "Sub 2", "purpose": "P2"},+ ],+ },+ {+ "name": "Section 2",+ "subsections": [+ {"name": "Sub 3", "purpose": "P3"},+ ],+ },+ ]++ call_count = [0]++ def capture_query(query):+ call_count[0] += 1+ return {"current_knowledge": f"Content {call_count[0]}"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Should have called analyze_topic 3 times (once per subsection)+ assert call_count[0] == 3+++def test_context_separator_between_sections(report_generator):+ """Test that sections in context are separated by the correct delimiter."""+ structure = [+ {+ "name": f"Section {i}",+ "subsections": [{"name": f"Part {i}", "purpose": f"P{i}"}],+ }+ for i in range(1, 4)+ ]++ captured_queries = []++ def capture_query(query):+ captured_queries.append(query)+ return {"current_knowledge": f"Content {len(captured_queries)}"}++ report_generator.search_system.analyze_topic.side_effect = capture_query++ report_generator._research_and_generate_sections(+ {"current_knowledge": "Initial"}, structure, "Query"+ )++ # Third query should have separator between Section 1 and Section 2 content+ third_query = captured_queries[2]+ assert "---" in third_query # The separator used between sections+++def test_truncate_at_sentence_boundary_no_truncation(report_generator):+ """Test that short text is not truncated."""+ text = "This is short. It should not be truncated."+ result = report_generator._truncate_at_sentence_boundary(text, 1000)+ assert result == text+ assert "[...truncated]" not in result+++def test_truncate_at_sentence_boundary_at_sentence(report_generator):+ """Test that truncation happens at sentence boundary when possible."""+ # Use a longer limit so sentence boundary falls within 80% threshold+ text = "First sentence. Second sentence. Third sentence that is very long and goes beyond the limit here."+ result = report_generator._truncate_at_sentence_boundary(text, 40)+ # "First sentence. Second sentence." = 33 chars, which is > 80% of 40 (32)+ # So it should truncate at the sentence boundary+ assert result.startswith("First sentence. Second sentence.")+ assert "[...truncated]" in result+ assert "Third sentence" not in result+++def test_truncate_at_sentence_boundary_fallback(report_generator):+ """Test that truncation falls back to hard cut when no good boundary exists."""+ # No sentence boundaries in the first 80% of the limit+ text = "A" * 100 # No sentence boundaries+ result = report_generator._truncate_at_sentence_boundary(text, 50)+ # Should hard truncate at 50 chars+ assert len(result) == 50 + len("\n[...truncated]")+ assert result.startswith("A" * 50)+ assert "[...truncated]" in result+++def test_truncate_at_sentence_boundary_with_question_mark(report_generator):+ """Test that question marks are recognized as sentence boundaries."""+ text = "Is this a question? Yes it is. More content that exceeds the limit."+ result = report_generator._truncate_at_sentence_boundary(text, 35)+ assert "Is this a question?" in result+ assert "[...truncated]" in result+++def test_truncate_at_sentence_boundary_with_exclamation(report_generator):+ """Test that exclamation marks are recognized as sentence boundaries."""+ text = "Wow! Amazing! This is great content that exceeds the limit significantly."+ result = report_generator._truncate_at_sentence_boundary(text, 20)+ assert "Amazing!" in result or "Wow!" in result+ assert "[...truncated]" in result+++def test_build_previous_context_empty(report_generator):+ """Test that empty accumulated findings returns empty string."""+ result = report_generator._build_previous_context([])+ assert result == ""+++def test_build_previous_context_single_section(report_generator):+ """Test context building with a single section."""+ accumulated = ["[Section A > Part 1]\nContent for section A"]+ result = report_generator._build_previous_context(accumulated)+ assert "CONTENT ALREADY WRITTEN" in result+ assert "Section A" in result+ assert "CRITICAL" in result+ assert "END OF PREVIOUS CONTENT" in result+++def test_build_previous_context_respects_max_sections(report_generator):+ """Test that only max_context_sections sections are included."""+ # Use the instance's max_context_sections (defaults to DEFAULT_MAX_CONTEXT_SECTIONS)+ max_sections = report_generator.max_context_sections++ # Create more sections than the limit+ accumulated = [f"[Section {i}]\nContent {i}" for i in range(10)]+ result = report_generator._build_previous_context(accumulated)++ # Should only include the last max_sections+ for i in range(10 - max_sections):+ # Earlier sections should NOT be in the context+ if f"Section {i}" in result:+ # Check it's not just a coincidental match+ assert f"[Section {i}]" not in result or i >= 10 - max_sections++ # Last sections SHOULD be present+ assert f"Section {10 - 1}" in result # Last section+++def test_build_previous_context_truncates_long_content(report_generator):+ """Test that very long content is truncated."""++ # Create content that exceeds max_context_chars (default 4000)+ long_content = "This is a sentence. " * 500 # ~10000 chars+ accumulated = [f"[Section A]\n{long_content}"]+ result = report_generator._build_previous_context(accumulated)++ # Result should contain truncation marker+ assert "[...truncated]" in result+ # Total context (excluding delimiters) should be around max_context_chars+ # The result includes delimiters so it will be larger+++def test_configurable_max_context_sections(+ mock_llm, mock_search_system, monkeypatch+):+ """Test that max_context_sections can be configured via settings_snapshot."""+ monkeypatch.setattr(+ "local_deep_research.report_generator.get_llm", lambda: mock_llm+ )++ # Create generator with custom settings+ settings_snapshot = {+ "report.max_context_sections": 5,+ "report.max_context_chars": 8000,+ }+ generator = IntegratedReportGenerator(+ search_system=mock_search_system,+ settings_snapshot=settings_snapshot,+ )++ # Verify settings were applied+ assert generator.max_context_sections == 5+ assert generator.max_context_chars == 8000+++def test_configurable_max_context_sections_affects_context_building(+ mock_llm, mock_search_system, monkeypatch+):+ """Test that custom max_context_sections affects _build_previous_context."""+ monkeypatch.setattr(+ "local_deep_research.report_generator.get_llm", lambda: mock_llm+ )++ # Create generator with only 2 sections in context+ settings_snapshot = {+ "report.max_context_sections": 2,+ }+ generator = IntegratedReportGenerator(+ search_system=mock_search_system,+ settings_snapshot=settings_snapshot,+ )++ # Create 5 sections+ accumulated = [f"[Section {i}]\nContent {i}" for i in range(5)]+ result = generator._build_previous_context(accumulated)++ # Should only include Section 3 and Section 4 (last 2)+ assert "[Section 3]" in result+ assert "[Section 4]" in result+ # Section 0, 1, 2 should NOT be in context (only last 2 kept)+ assert "[Section 0]" not in result+ assert "[Section 1]" not in result+ assert "[Section 2]" not in result+++def test_configurable_max_context_chars_affects_truncation(+ mock_llm, mock_search_system, monkeypatch+):+ """Test that custom max_context_chars affects truncation behavior."""+ monkeypatch.setattr(+ "local_deep_research.report_generator.get_llm", lambda: mock_llm+ )++ # Create generator with small context limit+ settings_snapshot = {+ "report.max_context_chars": 100,+ }+ generator = IntegratedReportGenerator(+ search_system=mock_search_system,+ settings_snapshot=settings_snapshot,+ )++ # Create content that exceeds 100 chars but is under default 4000+ content = "This is a sentence. " * 20 # ~400 chars+ accumulated = [f"[Section A]\n{content}"]+ result = generator._build_previous_context(accumulated)++ # Should be truncated due to small limit+ assert "[...truncated]" in result+++def test_default_context_settings_when_no_snapshot(+ mock_llm, mock_search_system, monkeypatch+):+ """Test that default values are used when no settings_snapshot is provided."""+ from local_deep_research.report_generator import (+ DEFAULT_MAX_CONTEXT_SECTIONS,+ DEFAULT_MAX_CONTEXT_CHARS,+ )++ monkeypatch.setattr(+ "local_deep_research.report_generator.get_llm", lambda: mock_llm+ )++ generator = IntegratedReportGenerator(search_system=mock_search_system)++ # Should use defaults+ assert generator.max_context_sections == DEFAULT_MAX_CONTEXT_SECTIONS+ assert generator.max_context_chars == DEFAULT_MAX_CONTEXT_CHARS