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: add TopicOrganizationStrategy for clustering search results

LearningCircuit9fb1427ef513
diff --git a/src/local_deep_research/advanced_search_system/findings/topic.py b/src/local_deep_research/advanced_search_system/findings/topic.py
new file mode 100644
index 0000000000..105edb8128
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/findings/topic.py
@@ -0,0 +1,194 @@
+from typing import List, Dict, Optional, Any
+from dataclasses import dataclass, field
+from datetime import datetime
+
+
+@dataclass
+class Topic:
+ """
+ Represents a topic cluster of related sources with a lead text.
+
+ A topic groups multiple search results around a central theme,
+ with one source selected as the "lead" that best represents the topic.
+ """
+
+ id: str
+ title: str
+ lead_source: Dict[str, Any] # The main source that represents this topic
+ supporting_sources: List[Dict[str, Any]] = field(default_factory=list)
+ rejected_sources: List[Dict[str, Any]] = field(default_factory=list)
+
+ # Metadata
+ confidence_score: float = 0.0
+ keywords: List[str] = field(default_factory=list)
+ created_at: datetime = field(default_factory=datetime.now)
+
+ # Relationships to other topics
+ related_topic_ids: List[str] = field(default_factory=list)
+ parent_topic_id: Optional[str] = None
+ child_topic_ids: List[str] = field(default_factory=list)
+
+ def add_supporting_source(self, source: Dict[str, Any]) -> None:
+ """Add a source that supports this topic."""
+ if source not in self.supporting_sources:
+ self.supporting_sources.append(source)
+
+ def reject_source(self, source: Dict[str, Any]) -> None:
+ """Move a source to the rejected list."""
+ if source in self.supporting_sources:
+ self.supporting_sources.remove(source)
+ if source not in self.rejected_sources:
+ self.rejected_sources.append(source)
+
+ def update_lead_source(self, new_lead: Dict[str, Any]) -> None:
+ """
+ Change the lead source for this topic.
+ The old lead becomes a supporting source.
+ """
+ if self.lead_source:
+ self.supporting_sources.append(self.lead_source)
+ self.lead_source = new_lead
+ # Remove new lead from supporting if it was there
+ if new_lead in self.supporting_sources:
+ self.supporting_sources.remove(new_lead)
+
+ def get_all_sources(self) -> List[Dict[str, Any]]:
+ """Get all sources (lead + supporting) for this topic."""
+ return [self.lead_source] + self.supporting_sources
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert topic to dictionary for serialization."""
+ return {
+ "id": self.id,
+ "title": self.title,
+ "lead_source": self.lead_source,
+ "supporting_sources": self.supporting_sources,
+ "rejected_sources": self.rejected_sources,
+ "confidence_score": self.confidence_score,
+ "keywords": self.keywords,
+ "created_at": self.created_at.isoformat(),
+ "related_topic_ids": self.related_topic_ids,
+ "parent_topic_id": self.parent_topic_id,
+ "child_topic_ids": self.child_topic_ids,
+ }
+
+
+@dataclass
+class TopicGraph:
+ """
+ Manages the collection of topics and their relationships.
+ Provides methods for traversing and organizing topics.
+ """
+
+ topics: Dict[str, Topic] = field(default_factory=dict)
+
+ def add_topic(self, topic: Topic) -> None:
+ """Add a topic to the graph."""
+ self.topics[topic.id] = topic
+
+ def get_topic(self, topic_id: str) -> Optional[Topic]:
+ """Get a topic by ID."""
+ return self.topics.get(topic_id)
+
+ def link_topics(self, topic1_id: str, topic2_id: str) -> None:
+ """Create a bidirectional relationship between two topics."""
+ topic1 = self.get_topic(topic1_id)
+ topic2 = self.get_topic(topic2_id)
+
+ if topic1 and topic2:
+ if topic2_id not in topic1.related_topic_ids:
+ topic1.related_topic_ids.append(topic2_id)
+ if topic1_id not in topic2.related_topic_ids:
+ topic2.related_topic_ids.append(topic1_id)
+
+ def set_parent_child(self, parent_id: str, child_id: str) -> None:
+ """Set a parent-child relationship between topics."""
+ parent = self.get_topic(parent_id)
+ child = self.get_topic(child_id)
+
+ if parent and child:
+ if child_id not in parent.child_topic_ids:
+ parent.child_topic_ids.append(child_id)
+ child.parent_topic_id = parent_id
+
+ def get_root_topics(self) -> List[Topic]:
+ """Get all topics that have no parent."""
+ return [
+ topic
+ for topic in self.topics.values()
+ if topic.parent_topic_id is None
+ ]
+
+ def get_related_topics(self, topic_id: str) -> List[Topic]:
+ """Get all topics related to a given topic."""
+ topic = self.get_topic(topic_id)
+ if not topic:
+ return []
+
+ related = []
+ for related_id in topic.related_topic_ids:
+ related_topic = self.get_topic(related_id)
+ if related_topic:
+ related.append(related_topic)
+ return related
+
+ def merge_topics(
+ self, topic1_id: str, topic2_id: str, new_title: str = None
+ ) -> Optional[Topic]:
+ """
+ Merge two topics into one, combining their sources.
+ Returns the merged topic or None if merge failed.
+ """
+ topic1 = self.get_topic(topic1_id)
+ topic2 = self.get_topic(topic2_id)
+
+ if not topic1 or not topic2:
+ return None
+
+ # Use topic1 as the base, update title if provided
+ if new_title:
+ topic1.title = new_title
+
+ # Add topic2's sources to topic1
+ for source in topic2.supporting_sources:
+ topic1.add_supporting_source(source)
+
+ for source in topic2.rejected_sources:
+ if source not in topic1.rejected_sources:
+ topic1.rejected_sources.append(source)
+
+ # Merge keywords
+ topic1.keywords = list(set(topic1.keywords + topic2.keywords))
+
+ # Update relationships
+ for related_id in topic2.related_topic_ids:
+ if (
+ related_id != topic1_id
+ and related_id not in topic1.related_topic_ids
+ ):
+ topic1.related_topic_ids.append(related_id)
+
+ # Update child relationships
+ for child_id in topic2.child_topic_ids:
+ self.set_parent_child(topic1_id, child_id)
+
+ # Remove topic2 from the graph
+ del self.topics[topic2_id]
+
+ # Update any references to topic2 in other topics
+ for topic in self.topics.values():
+ if topic2_id in topic.related_topic_ids:
+ topic.related_topic_ids.remove(topic2_id)
+ if topic1_id not in topic.related_topic_ids:
+ topic.related_topic_ids.append(topic1_id)
+
+ if topic.parent_topic_id == topic2_id:
+ topic.parent_topic_id = topic1_id
+
+ return topic1
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert the entire graph to a dictionary."""
+ return {
+ topic_id: topic.to_dict() for topic_id, topic in self.topics.items()
+ }
diff --git a/src/local_deep_research/advanced_search_system/strategies/topic_clustering.py b/src/local_deep_research/advanced_search_system/strategies/topic_clustering.py
new file mode 100644
index 0000000000..5c43a79d0d
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/topic_clustering.py
@@ -0,0 +1,341 @@
+import re
+from typing import List, Dict, Tuple, Any
+from collections import Counter
+
+
+class TopicClusterer:
+ """
+ Handles clustering of sources into topics using lightweight methods
+ suitable for local models.
+ """
+
+ def __init__(self, similarity_threshold: float = 0.3):
+ self.similarity_threshold = similarity_threshold
+
+ def extract_keywords(self, text: str, top_n: int = 10) -> List[str]:
+ """
+ Extract keywords from text using simple frequency analysis.
+ """
+ # Simple tokenization and normalization
+ text = text.lower()
+ # Remove URLs
+ text = re.sub(
+ r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+",
+ "",
+ text,
+ )
+ # Keep only alphanumeric and spaces
+ text = re.sub(r"[^a-zA-Z0-9\s]", " ", text)
+
+ # Split into words
+ words = text.split()
+
+ # Filter out common stop words (minimal set for efficiency)
+ stop_words = {
+ "the",
+ "be",
+ "to",
+ "of",
+ "and",
+ "a",
+ "in",
+ "that",
+ "have",
+ "i",
+ "it",
+ "for",
+ "not",
+ "on",
+ "with",
+ "he",
+ "as",
+ "you",
+ "do",
+ "at",
+ "this",
+ "but",
+ "his",
+ "by",
+ "from",
+ "they",
+ "we",
+ "say",
+ "her",
+ "she",
+ "or",
+ "an",
+ "will",
+ "my",
+ "one",
+ "all",
+ "would",
+ "there",
+ "their",
+ "what",
+ "so",
+ "up",
+ "out",
+ "if",
+ "about",
+ "who",
+ "get",
+ "which",
+ "go",
+ "me",
+ "when",
+ "make",
+ "can",
+ "like",
+ "time",
+ "no",
+ "just",
+ "him",
+ "know",
+ "take",
+ "people",
+ "into",
+ "year",
+ "your",
+ "good",
+ "some",
+ "could",
+ "them",
+ "see",
+ "other",
+ "than",
+ "then",
+ "now",
+ "look",
+ "only",
+ "come",
+ "its",
+ "over",
+ "think",
+ "also",
+ "back",
+ "after",
+ "use",
+ "two",
+ "how",
+ "our",
+ "work",
+ "first",
+ "well",
+ "way",
+ "even",
+ "new",
+ "want",
+ "because",
+ "any",
+ "these",
+ "give",
+ "day",
+ "most",
+ "us",
+ "is",
+ "are",
+ "was",
+ "were",
+ "been",
+ "has",
+ "had",
+ "may",
+ "might",
+ "must",
+ "shall",
+ "should",
+ "could",
+ "would",
+ "am",
+ "does",
+ "did",
+ "doing",
+ }
+
+ # Filter words
+ filtered_words = [
+ word for word in words if len(word) > 2 and word not in stop_words
+ ]
+
+ # Count frequencies
+ word_freq = Counter(filtered_words)
+
+ # Get top keywords
+ return [word for word, _ in word_freq.most_common(top_n)]
+
+ def calculate_similarity(
+ self, source1: Dict[str, Any], source2: Dict[str, Any]
+ ) -> float:
+ """
+ Calculate similarity between two sources based on title and snippet.
+ """
+ # Extract text from sources
+ text1 = f"{source1.get('title', '')} {source1.get('snippet', '')}"
+ text2 = f"{source2.get('title', '')} {source2.get('snippet', '')}"
+
+ # Extract keywords
+ keywords1 = set(self.extract_keywords(text1, 20))
+ keywords2 = set(self.extract_keywords(text2, 20))
+
+ if not keywords1 or not keywords2:
+ return 0.0
+
+ # Jaccard similarity
+ intersection = len(keywords1 & keywords2)
+ union = len(keywords1 | keywords2)
+
+ if union == 0:
+ return 0.0
+
+ return intersection / union
+
+ def cluster_sources(
+ self, sources: List[Dict[str, Any]], max_clusters: int = 5
+ ) -> List[List[int]]:
+ """
+ Cluster sources into groups based on similarity.
+ Returns a list of clusters, where each cluster is a list of source indices.
+ """
+ if not sources:
+ return []
+
+ n = len(sources)
+ if n == 1:
+ return [[0]]
+
+ # Build similarity matrix
+ similarities = {}
+ for i in range(n):
+ for j in range(i + 1, n):
+ sim = self.calculate_similarity(sources[i], sources[j])
+ if sim >= self.similarity_threshold:
+ similarities[(i, j)] = sim
+
+ # Greedy clustering
+ clusters = []
+ unclustered = set(range(n))
+
+ while unclustered and len(clusters) < max_clusters:
+ # Start a new cluster with an unclustered source
+ seed = unclustered.pop()
+ cluster = [seed]
+ cluster_members = {seed}
+
+ # Find similar sources
+ changed = True
+ while changed:
+ changed = False
+ for idx in list(unclustered):
+ # Check similarity with cluster members
+ max_sim = 0.0
+ for member in cluster_members:
+ pair = (min(idx, member), max(idx, member))
+ if pair in similarities:
+ max_sim = max(max_sim, similarities[pair])
+
+ if max_sim >= self.similarity_threshold:
+ cluster.append(idx)
+ cluster_members.add(idx)
+ unclustered.remove(idx)
+ changed = True
+
+ clusters.append(cluster)
+
+ # Add remaining unclustered sources as single-item clusters
+ for idx in unclustered:
+ clusters.append([idx])
+
+ return clusters
+
+ def select_lead_source(
+ self, sources: List[Dict[str, Any]], indices: List[int]
+ ) -> int:
+ """
+ Select the best source to be the lead for a cluster.
+ Returns the index of the lead source.
+ """
+ if not indices:
+ return -1
+
+ if len(indices) == 1:
+ return indices[0]
+
+ # Score each source based on:
+ # 1. Length of snippet (more informative)
+ # 2. Title quality (not too short, not too long)
+ # 3. Centrality (similarity to other sources in cluster)
+
+ best_score = -1
+ best_idx = indices[0]
+
+ for idx in indices:
+ source = sources[idx]
+ score = 0.0
+
+ # Snippet length score
+ snippet_len = len(source.get("snippet", ""))
+ score += min(snippet_len / 500, 1.0) # Normalize to [0, 1]
+
+ # Title quality score
+ title = source.get("title", "")
+ title_len = len(title)
+ if 20 <= title_len <= 100:
+ score += 1.0
+ elif title_len < 20:
+ score += title_len / 20
+ else:
+ score += max(0, 1 - (title_len - 100) / 100)
+
+ # Centrality score
+ total_similarity = 0.0
+ for other_idx in indices:
+ if other_idx != idx:
+ sim = self.calculate_similarity(
+ sources[idx], sources[other_idx]
+ )
+ total_similarity += sim
+
+ if len(indices) > 1:
+ avg_similarity = total_similarity / (len(indices) - 1)
+ score += avg_similarity
+
+ if score > best_score:
+ best_score = score
+ best_idx = idx
+
+ return best_idx
+
+ def generate_cluster_title(
+ self, sources: List[Dict[str, Any]], indices: List[int]
+ ) -> Tuple[str, List[str]]:
+ """
+ Generate a title and keywords for a cluster of sources.
+ Returns (title, keywords).
+ """
+ if not indices:
+ return ("Unknown Topic", [])
+
+ # Combine text from all sources in cluster
+ combined_text = ""
+ titles = []
+ for idx in indices:
+ source = sources[idx]
+ title = source.get("title", "")
+ snippet = source.get("snippet", "")
+ combined_text += f" {title} {snippet}"
+ if title:
+ titles.append(title)
+
+ # Extract keywords from combined text
+ keywords = self.extract_keywords(combined_text, 15)
+
+ # Generate title from most common keywords
+ if keywords:
+ # Use top 3-5 keywords for title
+ title_words = keywords[: min(5, len(keywords))]
+ title = " ".join([word.capitalize() for word in title_words[:3]])
+ else:
+ # Fallback to shortest title
+ title = min(titles, key=len) if titles else "Unknown Topic"
+
+ return (title, keywords[:10]) # Return top 10 keywords
diff --git a/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
new file mode 100644
index 0000000000..b96e5dcbcd
--- /dev/null
+++ b/src/local_deep_research/advanced_search_system/strategies/topic_organization_strategy.py
@@ -0,0 +1,579 @@
+import uuid
+from typing import Dict, List, Any
+
+from loguru import logger
+
+from .base_strategy import BaseSearchStrategy
+from .source_based_strategy import SourceBasedSearchStrategy
+from ..findings.topic import Topic, TopicGraph
+
+
+class TopicOrganizationStrategy(BaseSearchStrategy):
+ """
+ Strategy that organizes search results into topics with lead sources.
+
+ This strategy reuses SourceBasedSearchStrategy to gather sources,
+ then organizes them into topic clusters without generating full text.
+ Each topic has a lead source and supporting sources that can be validated.
+ """
+
+ def __init__(
+ self,
+ search,
+ model,
+ citation_handler=None,
+ use_cross_engine_filter: bool = True,
+ filter_reorder: bool = True,
+ filter_reindex: bool = True,
+ cross_engine_max_results: int = None,
+ all_links_of_system=None,
+ settings_snapshot=None,
+ search_original_query: bool = True,
+ min_sources_per_topic: int = 2,
+ max_topics: int = 5,
+ similarity_threshold: float = 0.7,
+ ):
+ """Initialize the topic organization strategy."""
+ super().__init__(
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ search_original_query=search_original_query,
+ )
+
+ self.model = model
+ self.search = search
+ self.citation_handler = citation_handler
+
+ # Topic organization parameters
+ self.min_sources_per_topic = min_sources_per_topic
+ self.max_topics = max_topics
+ self.similarity_threshold = similarity_threshold
+
+ # Create a no-op citation handler to skip text generation
+ class NoTextCitationHandler:
+ def analyze_followup(
+ self, query, results, previous_knowledge, nr_of_links
+ ):
+ return {"content": "", "documents": []}
+
+ # Initialize source-based strategy without text generation
+ self.source_strategy = SourceBasedSearchStrategy(
+ search=search,
+ model=model,
+ citation_handler=NoTextCitationHandler(), # Use no-op handler to skip text generation
+ include_text_content=False, # Also disable text content retrieval
+ use_cross_engine_filter=use_cross_engine_filter,
+ filter_reorder=filter_reorder,
+ filter_reindex=filter_reindex,
+ cross_engine_max_results=cross_engine_max_results,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ search_original_query=search_original_query,
+ )
+
+ # Topic graph to store organized topics
+ self.topic_graph = TopicGraph()
+
+ def _extract_topics_from_sources(
+ self, sources: List[Dict[str, Any]], query: str
+ ) -> List[Topic]:
+ """
+ Use LLM to identify topics from search results and select lead sources.
+ """
+ if not sources:
+ return []
+
+ # Format sources for LLM analysis
+ source_texts = []
+ for i, source in enumerate(
+ sources[:30]
+ ): # Limit to prevent context overflow
+ title = source.get("title", "Untitled")
+ snippet = source.get("snippet", "")
+ url = source.get("link", "")
+ source_texts.append(
+ f"Source {i + 1}:\nTitle: {title}\nURL: {url}\nSnippet: {snippet[:500]}"
+ )
+
+ sources_context = "\n\n".join(source_texts)
+
+ # Prompt for topic identification
+ topic_prompt = f"""
+Analyze these search results for the query: "{query}"
+
+Sources:
+{sources_context}
+
+Identify up to {self.max_topics} distinct topics from these sources.
+For each topic:
+1. Provide a clear, descriptive title
+2. Select the source number that best represents this topic (lead source)
+3. List other source numbers that support this topic
+4. Provide 3-5 keywords
+
+Format your response as a JSON list:
+[
+ {{
+ "title": "Topic Title",
+ "lead_source_index": 0,
+ "supporting_source_indices": [1, 2, 3],
+ "keywords": ["keyword1", "keyword2", "keyword3"]
+ }}
+]
+
+Important:
+- Each source should belong to at most one topic
+- Only include topics with at least {self.min_sources_per_topic} sources
+- Select the most informative source as the lead
+"""
+
+ try:
+ # Use LangChain's invoke method
+ from langchain_core.messages import HumanMessage
+
+ response = self.model.invoke([HumanMessage(content=topic_prompt)])
+
+ # Extract content from response
+ response_text = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+
+ # Parse JSON response
+ import json
+
+ # Try to extract JSON from the response
+ import re
+
+ json_match = re.search(r"\[.*\]", response_text, re.DOTALL)
+ if json_match:
+ topic_data = json.loads(json_match.group())
+ else:
+ topic_data = json.loads(response_text)
+
+ topics = []
+ used_indices = set()
+
+ for i, topic_info in enumerate(topic_data[: self.max_topics]):
+ lead_idx = topic_info.get("lead_source_index")
+ supporting_indices = topic_info.get(
+ "supporting_source_indices", []
+ )
+
+ # Skip if lead source already used
+ if lead_idx in used_indices or lead_idx >= len(sources):
+ continue
+
+ # Create topic
+ topic = Topic(
+ id=str(uuid.uuid4()),
+ title=topic_info.get("title", f"Topic {i + 1}"),
+ lead_source=sources[lead_idx],
+ keywords=topic_info.get("keywords", []),
+ )
+
+ used_indices.add(lead_idx)
+
+ # Add supporting sources
+ for idx in supporting_indices:
+ if idx not in used_indices and idx < len(sources):
+ topic.add_supporting_source(sources[idx])
+ used_indices.add(idx)
+
+ # Only add topic if it has enough sources
+ if len(topic.get_all_sources()) >= self.min_sources_per_topic:
+ topics.append(topic)
+
+ return topics
+
+ except Exception:
+ logger.exception("Error extracting topics")
+ return []
+
+ def _validate_topic_coherence(self, topic: Topic) -> float:
+ """
+ Validate that sources in a topic are coherent and related.
+ Returns a confidence score between 0 and 1.
+ """
+ if len(topic.get_all_sources()) < 2:
+ return 0.0
+
+ # Format topic for validation
+ lead_title = topic.lead_source.get("title", "")
+ lead_snippet = topic.lead_source.get("snippet", "")[:500]
+
+ supporting_texts = []
+ for source in topic.supporting_sources[:5]: # Limit for context
+ title = source.get("title", "")
+ snippet = source.get("snippet", "")[:300]
+ supporting_texts.append(f"- {title}: {snippet}")
+
+ validation_prompt = f"""
+Evaluate the coherence of this topic cluster:
+
+Topic: {topic.title}
+Keywords: {", ".join(topic.keywords)}
+
+Lead Source:
+Title: {lead_title}
+Snippet: {lead_snippet}
+
+Supporting Sources:
+{chr(10).join(supporting_texts)}
+
+Rate the coherence from 0.0 to 1.0 based on:
+1. How well the supporting sources relate to the lead source
+2. Whether all sources discuss the same topic
+3. The relevance of the keywords
+
+Respond with just a number between 0.0 and 1.0.
+"""
+
+ try:
+ # Use LangChain's invoke method
+ from langchain_core.messages import HumanMessage
+
+ response = self.model.invoke(
+ [HumanMessage(content=validation_prompt)]
+ )
+
+ # Extract content from response
+ response_text = (
+ response.content
+ if hasattr(response, "content")
+ else str(response)
+ )
+ score = float(response_text.strip())
+ return min(max(score, 0.0), 1.0) # Clamp to [0, 1]
+ except Exception as e:
+ logger.warning(f"Error validating topic coherence: {e}")
+ return 0.5 # Default middle score on error
+
+ def _find_topic_relationships(self, topics: List[Topic]) -> None:
+ """
+ Identify relationships between topics and update the topic graph.
+ """
+ if len(topics) < 2:
+ return
+
+ for i, topic1 in enumerate(topics):
+ for topic2 in topics[i + 1 :]:
+ # Check keyword overlap
+ common_keywords = set(topic1.keywords) & set(topic2.keywords)
+ if len(common_keywords) >= 2:
+ self.topic_graph.link_topics(topic1.id, topic2.id)
+
+ def analyze_topic(self, query: str) -> Dict:
+ """
+ Analyze a topic by organizing search results into topic clusters.
+ """
+ logger.info(f"Starting topic organization for: {query}")
+
+ self._update_progress(
+ "Gathering sources using source-based strategy",
+ 10,
+ {"phase": "source_gathering"},
+ )
+
+ # Use source-based strategy to gather sources
+ source_results = self.source_strategy.analyze_topic(query)
+
+ # Extract sources from results - the strategy returns all sources in all_links_of_system
+ all_sources = source_results.get("all_links_of_system", [])
+
+ if not all_sources:
+ logger.warning("No sources found to organize into topics")
+ return {
+ # Standard fields
+ "findings": [],
+ "iterations": source_results.get("iterations", 0),
+ "questions_by_iteration": source_results.get(
+ "questions_by_iteration", {}
+ ),
+ "formatted_findings": "No sources found to organize into topics.",
+ "current_knowledge": "",
+ "all_links_of_system": self.all_links_of_system,
+ # Topic-specific fields
+ "topics": [],
+ "topic_graph": self.topic_graph.to_dict(),
+ "source_count": 0,
+ }
+
+ self._update_progress(
+ f"Organizing {len(all_sources)} sources into topics",
+ 40,
+ {"phase": "topic_extraction", "source_count": len(all_sources)},
+ )
+
+ # Extract topics from sources
+ topics = self._extract_topics_from_sources(all_sources, query)
+
+ if not topics:
+ logger.warning("Could not extract topics from sources")
+ return {
+ # Standard fields
+ "findings": [],
+ "iterations": source_results.get("iterations", 0),
+ "questions_by_iteration": source_results.get(
+ "questions_by_iteration", {}
+ ),
+ "formatted_findings": "Could not identify distinct topics from sources.",
+ "current_knowledge": "",
+ "all_links_of_system": self.all_links_of_system,
+ # Topic-specific fields
+ "topics": [],
+ "topic_graph": self.topic_graph.to_dict(),
+ "source_count": len(all_sources),
+ }
+
+ self._update_progress(
+ f"Validating {len(topics)} topics",
+ 60,
+ {"phase": "validation", "topic_count": len(topics)},
+ )
+
+ # Validate and score each topic
+ validated_topics = []
+ for topic in topics:
+ # Primary validation: number of sources
+ source_count = len(topic.get_all_sources())
+
+ # Only use LLM validation as a secondary score, not a filter
+ confidence = self._validate_topic_coherence(topic)
+ topic.confidence_score = confidence
+
+ # Accept topics with enough sources regardless of LLM confidence
+ if source_count >= self.min_sources_per_topic:
+ validated_topics.append(topic)
+ self.topic_graph.add_topic(topic)
+ logger.info(
+ f"Topic '{topic.title}' accepted with {source_count} sources (confidence {confidence:.2f})"
+ )
+ else:
+ logger.info(
+ f"Topic '{topic.title}' rejected with only {source_count} sources"
+ )
+
+ self._update_progress(
+ "Finding topic relationships", 80, {"phase": "relationship_mapping"}
+ )
+
+ # Find relationships between topics
+ self._find_topic_relationships(validated_topics)
+
+ # Format findings
+ formatted_findings = self._format_topic_findings(
+ validated_topics, query
+ )
+
+ self._update_progress(
+ "Topic organization complete",
+ 100,
+ {"phase": "complete", "final_topic_count": len(validated_topics)},
+ )
+
+ # Collect all sources from validated topics
+ topic_sources = []
+ for topic in validated_topics:
+ topic_sources.extend(topic.get_all_sources())
+
+ # Add all topic sources to all_links_of_system (deduplicated)
+ for source in topic_sources:
+ if source not in self.all_links_of_system:
+ self.all_links_of_system.append(source)
+
+ # Format the topic graph as a structured knowledge representation
+ topic_graph_str = self._format_topic_graph_as_knowledge(
+ validated_topics, query
+ )
+
+ # Create findings with sources included in content
+ findings = []
+
+ # Add a main finding with the topic graph
+ main_finding = {
+ "phase": "Topic Organization Overview",
+ "content": topic_graph_str,
+ "question": query,
+ "documents": topic_sources, # All sources from validated topics
+ "topics": [topic.to_dict() for topic in validated_topics],
+ }
+ findings.append(main_finding)
+
+ # Add individual findings for each topic with their sources
+ for i, topic in enumerate(validated_topics, 1):
+ topic_finding = {
+ "phase": f"Topic {i}: {topic.title}",
+ "content": self._format_single_topic_with_sources(topic),
+ "question": query,
+ "documents": topic.get_all_sources(),
+ }
+ findings.append(topic_finding)
+
+ return {
+ # Standard fields expected by the system
+ "findings": findings,
+ "iterations": source_results.get("iterations", 0),
+ "questions_by_iteration": source_results.get(
+ "questions_by_iteration", {}
+ ),
+ "formatted_findings": formatted_findings,
+ "current_knowledge": topic_graph_str, # The topic graph structure as knowledge
+ "all_links_of_system": self.all_links_of_system,
+ # Topic-specific fields
+ "topics": [topic.to_dict() for topic in validated_topics],
+ "topic_graph": self.topic_graph.to_dict(),
+ "source_count": len(topic_sources),
+ }
+
+ def _format_single_topic_with_sources(self, topic: Topic) -> str:
+ """
+ Format a single topic with all its sources listed.
+ """
+ lines = [
+ f"**Confidence:** {topic.confidence_score:.2%}",
+ f"**Keywords:** {', '.join(topic.keywords[:7])}",
+ f"**Total Sources:** {len(topic.get_all_sources())}",
+ "",
+ "**Lead Source:**",
+ f"- [{topic.lead_source.get('title', 'Untitled')}]({topic.lead_source.get('link', '')})",
+ ]
+
+ # Add snippet from lead source if available
+ if topic.lead_source.get("snippet"):
+ lines.append(f" > {topic.lead_source.get('snippet', '')[:300]}...")
+
+ if topic.supporting_sources:
+ lines.append("")
+ lines.append(
+ f"**Supporting Sources ({len(topic.supporting_sources)}):**"
+ )
+ for source in topic.supporting_sources:
+ title = source.get("title", "Untitled")
+ link = source.get("link", "")
+ lines.append(f"- [{title}]({link})")
+ # Add snippet for supporting sources too
+ if source.get("snippet"):
+ lines.append(f" > {source.get('snippet', '')[:200]}...")
+
+ return "\n".join(lines)
+
+ def _format_topic_graph_as_knowledge(
+ self, topics: List[Topic], query: str
+ ) -> str:
+ """
+ Format the topic graph as a structured knowledge representation.
+ This becomes the main knowledge output of the strategy.
+ """
+ if not topics:
+ return "No topics identified."
+
+ lines = [
+ f"# Topic Graph for: {query}",
+ "\n## Overview",
+ f"Identified {len(topics)} distinct topic clusters from {sum(len(t.get_all_sources()) for t in topics)} sources.\n",
+ "## Topic Structure\n",
+ ]
+
+ # Build the graph structure
+ for i, topic in enumerate(topics, 1):
+ lines.append(f"### Topic {i}: {topic.title}")
+ lines.append(f"**Confidence:** {topic.confidence_score:.2%}")
+ lines.append(f"**Keywords:** {', '.join(topic.keywords[:5])}")
+ lines.append(f"**Sources:** {len(topic.get_all_sources())}")
+
+ # Lead source details
+ lead = topic.lead_source
+ lines.append("\n**Lead Source:**")
+ lines.append(
+ f"[{lead.get('title', 'Untitled')}]({lead.get('link', '')})"
+ )
+ if lead.get("snippet"):
+ lines.append(f"> {lead.get('snippet', '')[:200]}...")
+
+ # Relationships
+ if topic.related_topic_ids:
+ lines.append("\n**Related Topics:** ")
+ for related_id in topic.related_topic_ids:
+ related_topic = self.topic_graph.get_topic(related_id)
+ if related_topic:
+ lines.append(f"- {related_topic.title}")
+
+ lines.append("") # Blank line between topics
+
+ # Add graph relationships summary
+ if len(topics) > 1:
+ lines.append("\n## Topic Relationships\n")
+ relationships = []
+ for topic in topics:
+ for related_id in topic.related_topic_ids:
+ related = self.topic_graph.get_topic(related_id)
+ if (
+ related
+ and (related.title, topic.title) not in relationships
+ ):
+ relationships.append((topic.title, related.title))
+
+ if relationships:
+ for t1, t2 in relationships:
+ lines.append(f"- **{t1}** ↔ **{t2}**")
+
+ return "\n".join(lines)
+
+ def _format_topic_findings(self, topics: List[Topic], query: str) -> str:
+ """
+ Format topic organization results for display with full source listings.
+ """
+ if not topics:
+ return "No topics identified."
+
+ lines = [
+ f"# Topic Organization for: {query}",
+ f"\nIdentified {len(topics)} distinct topics:\n",
+ ]
+
+ for i, topic in enumerate(topics, 1):
+ lines.append(f"## Topic {i}: {topic.title}")
+ lines.append(f"Confidence: {topic.confidence_score:.2%}")
+ lines.append(f"Keywords: {', '.join(topic.keywords)}")
+ lines.append(
+ f"Sources: {len(topic.get_all_sources())} (1 lead + {len(topic.supporting_sources)} supporting)"
+ )
+
+ # Lead source with link
+ lead = topic.lead_source
+ lines.append("\n**Lead Source:**")
+ lines.append(
+ f"- [{lead.get('title', 'Untitled')}]({lead.get('link', '')})"
+ )
+
+ # All supporting sources with links
+ if topic.supporting_sources:
+ lines.append(
+ f"\n**Supporting Sources ({len(topic.supporting_sources)}):**"
+ )
+ for source in topic.supporting_sources:
+ lines.append(
+ f"- [{source.get('title', 'Untitled')}]({source.get('link', '')})"
+ )
+
+ # Related topics
+ if topic.related_topic_ids:
+ related_titles = []
+ for related_id in topic.related_topic_ids:
+ related = self.topic_graph.get_topic(related_id)
+ if related:
+ related_titles.append(related.title)
+ if related_titles:
+ lines.append(
+ f"\n**Related Topics:** {', '.join(related_titles)}"
+ )
+
+ lines.append("") # Blank line between topics
+
+ # Add source summary at the end
+ total_sources = sum(len(topic.get_all_sources()) for topic in topics)
+ lines.append(f"\n---\n**Total Sources Organized:** {total_sources}")
+
+ return "\n".join(lines)
diff --git a/src/local_deep_research/search_system_factory.py b/src/local_deep_research/search_system_factory.py
index dbcc403ea9..a4311ddf90 100644
--- a/src/local_deep_research/search_system_factory.py
+++ b/src/local_deep_research/search_system_factory.py
@@ -615,6 +615,33 @@ def create_strategy(
all_links_of_system=all_links_of_system,
)
+ # Topic organization strategy
+ elif strategy_name_lower in [
+ "topic-organization",
+ "topic_organization",
+ "topic",
+ ]:
+ from .advanced_search_system.strategies.topic_organization_strategy import (
+ TopicOrganizationStrategy,
+ )
+
+ return TopicOrganizationStrategy(
+ model=model,
+ search=search,
+ all_links_of_system=all_links_of_system,
+ settings_snapshot=settings_snapshot,
+ use_cross_engine_filter=kwargs.get("use_cross_engine_filter", True),
+ filter_reorder=kwargs.get("filter_reorder", True),
+ filter_reindex=kwargs.get("filter_reindex", True),
+ cross_engine_max_results=kwargs.get(
+ "cross_engine_max_results", None
+ ),
+ search_original_query=kwargs.get("search_original_query", True),
+ min_sources_per_topic=kwargs.get("min_sources_per_topic", 2),
+ max_topics=kwargs.get("max_topics", 5),
+ similarity_threshold=kwargs.get("similarity_threshold", 0.3),
+ )
+
# Iterative refinement strategy
elif strategy_name_lower in [
"iterative-refinement",
diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.html
index 5602ac6c11..f2770cb9de 100644
--- a/src/local_deep_research/web/templates/pages/research.html
+++ b/src/local_deep_research/web/templates/pages/research.html
@@ -150,6 +150,7 @@
<option value="source-based" {% if settings.search_strategy == 'source-based' %}selected{% endif %}>Source-Based (~70% SimpleQA, Comprehensive Research & Text Creation)</option>
<option value="focused-iteration" {% if settings.search_strategy == 'focused-iteration' %}selected{% endif %}>Focused Iteration (~95% SimpleQA, Fast & Precise Q&A)</option>
<option value="iterative-refinement" {% if settings.search_strategy == 'iterative-refinement' %}selected{% endif %}>Iterative Refinement (LLM-guided progressive refinement)</option>
+ <option value="topic-organization" {% if settings.search_strategy == 'topic-organization' %}selected{% endif %}>Topic Organization (Clusters sources into topics with lead texts)</option>
</select>
<span class="ldr-input-help">Source-Based: Proven strategy for detailed research. Focused Iteration: 2x faster for direct answers. Iterative Refinement: Automatically refines results until comprehensive. Performance varies with LLM and configuration.</span>
</div>