~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
decent version
LearningCircuit55862cfed29c
diff --git a/app.py b/app.pyindex bb93b9d711..0778258b47 100644--- a/app.py+++ b/app.py@@ -598,7 +598,7 @@ def run_research_process(research_id, query, mode):# Full Reportprogress_callback("Generating detailed report...", 85, {"phase": "report_generation"})report_generator = IntegratedReportGenerator()- final_report = report_generator.generate_report(results['findings'], query)+ final_report = report_generator.generate_report(results['current_knowledge'], query)progress_callback("Report generation complete", 95, {"phase": "report_complete"})# Save as markdown filediff --git a/citation_handler.py b/citation_handler.pyindex cf2a0d53f4..70ed8b03b6 100644--- a/citation_handler.py+++ b/citation_handler.py@@ -11,15 +11,18 @@ class CitationHandler:self.llm = llmdef _create_documents(- self, search_results: Union[str, List[Dict]]+ self, search_results: Union[str, List[Dict]], nr_of_links: int = 0) -> List[Document]:- """Convert search results to LangChain documents format."""+ """Convert search results to LangChain documents format and add index to original search results."""documents = []if isinstance(search_results, str):return documentsfor i, result in enumerate(search_results):if isinstance(result, dict):+ # Add index to the original search result dictionary+ result["index"] = str(i + nr_of_links + 1)+content = result.get("full_content", result.get("snippet", ""))documents.append(Document(@@ -27,7 +30,7 @@ class CitationHandler:metadata={"source": result.get("link", f"source_{i+1}"),"title": result.get("title", f"Source {i+1}"),- "index": i + 1,+ "index": i + nr_of_links + 1,},))@@ -67,9 +70,10 @@ Provide a detailed analysis with citations and always keep URLS. Never make up squestion: str,search_results: Union[str, List[Dict]],previous_knowledge: str,+ nr_of_links : int) -> Dict[str, Any]:"""Process follow-up analysis with citations."""- documents = self._create_documents(search_results)+ documents = self._create_documents(search_results, nr_of_links=nr_of_links)formatted_sources = self._format_sources(documents)print(formatted_sources)# Add fact-checking step@@ -106,4 +110,4 @@ Provide a detailed analysis with citations and always keep URLS. Never make up sresponse = self.llm.invoke(prompt)- return {"content": remove_think_tags(response.content), "documents": documents}+ return {"content": remove_think_tags(response.content), "documents": documents}\ No newline at end of filediff --git a/config.py b/config.pyindex 45ae9dc9ca..c7520355c1 100644--- a/config.py+++ b/config.py@@ -55,14 +55,16 @@ load_dotenv()# Choose search tool: "serp" or "duckduckgo" (serp requires API key)search_tool = "auto" # Change this variable to switch between search tools; for only local search "local-all"-KNOWLEDGE_ACCUMULATION = KnowledgeAccumulationApproach.QUESTION # None doesnt work with detailed report. It basically means the questions are seperate on the topic.+KNOWLEDGE_ACCUMULATION = KnowledgeAccumulationApproach.ITERATION # None doesnt work with detailed report. It basically means the questions are seperate on the topic.+KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT = 2000000+# LLM Configuration-OPENAIENDPOINT=False # True + URL + Model Name+OPENAIENDPOINT=True # True + URL + Model NameOPENROUTER_BASE_URL= "https://openrouter.ai/api/v1"-DEFAULT_MODEL = "mistral" # try to use the largest model that fits into your GPU memory+DEFAULT_MODEL = "google/gemini-2.0-flash-001" # try to use the largest model that fits into your GPU memoryDEFAULT_TEMPERATURE = 0.7-MAX_TOKENS = 15000+MAX_TOKENS = 30000# VLLM ConfigurationVLLM_MAX_NEW_TOKENS = 128@@ -71,12 +73,12 @@ VLLM_TOP_P = 0.95VLLM_TEMPERATURE = 0.8# Search System Settings-SEARCH_ITERATIONS = 3-QUESTIONS_PER_ITERATION = 3+SEARCH_ITERATIONS = 2+QUESTIONS_PER_ITERATION = 2# Report settings-SEARCHES_PER_SECTION = 3-CONTEXT_CUT_OFF = 10000+SEARCHES_PER_SECTION = 2+#CONTEXT_CUT_OFF = 10000# citation handlerENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better with larger LLMs?diff --git a/main.py b/main.pyindex 248ec680e9..8a71377885 100644--- a/main.py+++ b/main.py@@ -27,16 +27,7 @@ def print_report(report: Dict):# Write metadata at the end of the filemarkdown_file.write("\n\n---\n\n")markdown_file.write("## Report Metadata\n")- markdown_file.write(f"- Generated at: {report['metadata']['generated_at']}\n")- markdown_file.write(- f"- Initial sources: {report['metadata']['initial_sources']}\n"- )- markdown_file.write(- f"- Sections researched: {report['metadata']['sections_researched']}\n"- )- markdown_file.write(- f"- Searches per section: {report['metadata']['searches_per_section']}\n"- )+markdown_file.write(f"- Query: {report['metadata']['query']}\n")print(f"\nReport has been saved to report.md")@@ -95,7 +86,7 @@ def main():else:# Full Reportfinal_report = report_generator.generate_report(- results["findings"], query+ results, query)print("\n=== RESEARCH REPORT ===")print_report(final_report)diff --git a/report_generator.py b/report_generator.pyindex 321f28b970..df3717649a 100644--- a/report_generator.py+++ b/report_generator.py@@ -3,7 +3,9 @@ from config import get_llmimport refrom datetime import datetimefrom search_system import AdvancedSearchSystem-+import config+import utilties+import utilties.search_utilitiesclass IntegratedReportGenerator:def __init__(self, searches_per_section: int = 2):@@ -17,46 +19,26 @@ class IntegratedReportGenerator:print(text)return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()- def generate_report(self, initial_findings: List[Dict], query: str) -> Dict:+ def generate_report(self, initial_findings: Dict, query: str) -> str:"""Generate a complete research report with section-specific research."""- try:- # Step 1: Determine structure- structure = self._determine_report_structure(initial_findings, query)- # Step 2: Research each section using AdvancedSearchSystem- section_research = self._research_sections(structure, query)+ # Step 1: Determine structure+ structure = self._determine_report_structure(initial_findings, query)- # Step 3: Generate content with all research- sections = self._generate_sections(- initial_findings, section_research, structure, query- )+ # Step 2: Research and generate content for each section in one step+ sections = self._research_and_generate_sections(initial_findings, structure, query)- # Step 4: Format final report- report_content = self._format_final_report(- sections, structure, section_research- )+ # Step 3: Format final report+ report_content = self._format_final_report(sections, structure)- return {- "content": report_content,- "metadata": {- "generated_at": datetime.now().isoformat(),- "initial_sources": len(initial_findings),- "sections_researched": len(section_research),- "searches_per_section": self.searches_per_section,- "query": query,- "structure": structure,- },- }- except Exception as e:- print(f"Error generating report: {str(e)}")- return self._generate_error_report(query, str(e))+ return report_contentdef _determine_report_structure(- self, findings: List[Dict], query: str+ self, findings: Dict, query: str) -> List[Dict]:+"""Analyze content and determine optimal report structure."""- combined_content = "\n\n".join([f["content"] for f in findings])-+ combined_content = findings["current_knowledge"]prompt = f"""Analyze this research content about: {query}@@ -106,185 +88,104 @@ class IntegratedReportGenerator:return structure- def _research_sections(- self, structure: List[Dict], main_query: str- ) -> Dict[str, List[Dict]]:- """Research each section using the AdvancedSearchSystem."""- section_research = {}-- for section in structure:- # Generate a focused query for this section- section_query_prompt = f"""- For a report section titled "{section['name']}" about {main_query},- generate {self.searches_per_section} specific research questions.- The section covers:- {chr(10).join([f"- {sub['name']} | {sub['purpose']}" for sub in section['subsections']])}-- Return only the questions, one per line, starting with Q:- """-- response = self._remove_think_tags(- self.model.invoke(section_query_prompt).content- )- questions = [- line.replace("Q:", "").strip()- for line in response.split("\n")- if line.strip().startswith("Q:")- ]-- # Use existing search system for each question- section_findings = []- for question in questions[: self.searches_per_section]:- # Modify max_iterations to 1 for focused search- self.search_system.max_iterations = 2- search_results = self.search_system.analyze_topic(- f"{question} {main_query}"- )-- if search_results and "findings" in search_results:- section_findings.extend(search_results["findings"])-- section_research[section["name"]] = section_findings-- return section_research-- def _generate_sections(+ def _research_and_generate_sections(self,- initial_findings: List[Dict],- section_research: Dict[str, List[Dict]],+ initial_findings: Dict,structure: List[Dict],query: str,) -> Dict[str, str]:+ """Research and generate content for each section in one step."""sections = {}- accumulated_content = ""-+for section in structure:+ print(f"Processing section: {section['name']}")section_content = []-- # Get section-specific research- section_findings = section_research.get(section["name"], [])- research_content = "\n\n".join([f["content"] for f in section_findings])-- if not section["subsections"]:- # Generate content for sections without subsections- prompt = f"""- Research Query: {query}+ section_content.append(f"# {section['name']}\n")++ # Process each subsection by directly researching it+ for subsection in section["subsections"]:+ # Add subsection header+ section_content.append(f"## {subsection['name']}\n")+ section_content.append(f"_{subsection['purpose']}_\n\n")- Section: {section['name']}+ # Generate a specific search query for this subsection+ subsection_query = f"{query} {section['name']} {subsection['name']} {subsection['purpose']}"- Previous Content: {accumulated_content[:1000] if accumulated_content else "None yet"}+ print(f"Researching subsection: {subsection['name']} with query: {subsection_query}")- General Research:- {self._combine_findings(initial_findings)}+ # Configure search system for focused search+ original_max_iterations = self.search_system.max_iterations+ self.search_system.max_iterations = 1 # Keep search focused- Generate comprehensive content for this section that:- 1. Addresses the section's main topic- 2. Integrates available research- 3. Maintains flow with previous content- 4. Uses appropriate formatting- """-- response = self._remove_think_tags(self.model.invoke(prompt).content)- section_content.append(response)- accumulated_content += f"\n{response}"- else:- for subsection in section["subsections"]:- prompt = f"""- Research Query: {query}- Section: {section['name']}- Subsection: {subsection['name']}- Purpose: {subsection['purpose']}- Previous Content: {accumulated_content[:1000] if accumulated_content else "None yet"}- General Research:- {self._combine_findings(initial_findings)}- Section-Specific Research:- {research_content}- Generate content that:- 1. Fulfills the stated purpose- 2. Integrates both general and section-specific research- 3. Cites specific sources when possible- 4. Builds upon previous content- 5. Uses appropriate formatting- """-- response = self._remove_think_tags(- self.model.invoke(prompt).content- )- section_content.append(f"### {subsection['name']}\n\n{response}\n")- accumulated_content += f"\n{response}"-- # FIXED: Move this outside the else block so it happens for all sections+ # Perform search for this subsection+ subsection_results = self.search_system.analyze_topic(subsection_query)++ # Restore original iterations setting+ self.search_system.max_iterations = original_max_iterations++ # Add the researched content for this subsection+ if "current_knowledge" in subsection_results and subsection_results["current_knowledge"]:+ section_content.append(subsection_results["current_knowledge"])+ else:+ section_content.append("*Limited information was found for this subsection.*\n")++ section_content.append("\n\n")++ # Combine all content for this sectionsections[section["name"]] = "\n".join(section_content)-+return sections+ def _generate_sections(+ self,+ initial_findings: Dict,+ section_research: Dict[str, List[Dict]],+ structure: List[Dict],+ query: str,+ ) -> Dict[str, str]:+ """+ This method is kept for compatibility but no longer used.+ The functionality has been moved to _research_and_generate_sections.+ """+ return {}+def _format_final_report(self,sections: Dict[str, str],structure: List[Dict],- section_research: Dict[str, List[Dict]],) -> str:- """Format the final report with table of contents and research summary."""- seen_headers = set() # Track seen headers-+ """Format the final report with table of contents and sections."""# Generate TOCtoc = ["# Table of Contents\n"]for i, section in enumerate(structure, 1):toc.append(f"{i}. **{section['name']}**")for j, subsection in enumerate(section["subsections"], 1):- toc.append(f" - {subsection['name']} | _{subsection['purpose']}_")+ toc.append(f" {i}.{j} {subsection['name']} | _{subsection['purpose']}_")# Combine TOC and sectionsreport_parts = ["\n".join(toc), ""]-- # Add research summary- summary_header = "# Research Summary"- seen_headers.add(summary_header)- report_parts.append(summary_header)-- for section_name, findings in section_research.items():- research_header = f"\n## Research for {section_name}"- if research_header not in seen_headers:- seen_headers.add(research_header)- report_parts.append(research_header)- report_parts.append(f"Number of focused searches: {len(findings)}")++ # Add a summary of the research+ report_parts.append("# Research Summary")+ report_parts.append(f"This report was researched using an advanced search system.")+ report_parts.append(f"Research included targeted searches for each section and subsection.")report_parts.append("\n---\n")- # Process section content to remove duplicate headers+ # Add each section's contentfor section in structure:- section_header = f"# {section['name']}"- if section_header not in seen_headers:- seen_headers.add(section_header)- report_parts.append(section_header)-- # Split content into lines and filter duplicates- if section["name"] in sections:- content_lines = sections[section["name"]].split("\n")- filtered_lines = []-- for line in content_lines:- if line.strip().startswith("#"):- header = line.strip()- if header not in seen_headers:- seen_headers.add(header)- filtered_lines.append(line)- else:- filtered_lines.append(line)-- report_parts.append("\n".join(filtered_lines))- report_parts.append("")-- return "\n\n".join(report_parts)-- def _combine_findings(self, findings: List[Dict]) -> str:- return "\n\n".join([f["content"] for f in findings])-- def _generate_error_report(self, query: str, error_msg: str) -> Dict:- return {- "content": f"=== ERROR REPORT ===\nQuery: {query}\nError: {error_msg}",- "metadata": {- "error": error_msg,- "generated_at": datetime.now().isoformat(),- "status": "failed",- },- }+ if section["name"] in sections:+ report_parts.append(sections[section["name"]])+ report_parts.append("")++ # Format links from search system+ formatted_all_links = utilties.search_utilities.format_links(links=self.search_system.all_links_of_system)++ # Create final report with all parts+ final_report = "\n\n".join(report_parts)+ final_report = final_report + "\n\n## Sources\n\n" + formatted_all_links++ return final_report++ def _generate_error_report(self, query: str, error_msg: str) -> str:+ error_report = f"=== ERROR REPORT ===\nQuery: {query}\nError: {error_msg}"+ return error_report\ No newline at end of filediff --git a/search_system.py b/search_system.pyindex 8e2cc5cdef..28f5549e69 100644--- a/search_system.py+++ b/search_system.py@@ -1,6 +1,6 @@from typing import Dict, List, Optional, Callablefrom datetime import datetime-from utilties.search_utilities import remove_think_tags, format_findings_to_text, print_search_results+from utilties.search_utilities import remove_think_tags, format_findings_to_text, print_search_results, format_linksimport osfrom utilties.enums import KnowledgeAccumulationApproachfrom config import get_llm, get_search, SEARCH_ITERATIONS, QUESTIONS_PER_ITERATION@@ -15,10 +15,11 @@ class AdvancedSearchSystem:self.model = get_llm()self.max_iterations = SEARCH_ITERATIONSself.questions_per_iteration = QUESTIONS_PER_ITERATION- self.context_limit = 5000+ self.context_limit = config.KNOWLEDGE_ACCUMULATION_CONTEXT_LIMITself.questions_by_iteration = {}self.citation_handler = CitationHandler(self.model)self.progress_callback = None+ self.all_links_of_system = list()def set_progress_callback(self, callback: Callable[[str, int, dict], None]) -> None:"""Set a callback function to receive progress updates.@@ -71,27 +72,32 @@ class AdvancedSearchSystem:return questions- def _compress_knowledge(self, current_knowledge: str, query: str) -> List[str]:+ def _compress_knowledge(self, current_knowledge: str, query: str, section_links) -> List[str]:self._update_progress("Compressing and summarizing knowledge...", None)-+now = datetime.now()current_time = now.strftime("%Y-%m-%d")+ formatted_links = format_links(links=section_links)if self.questions_by_iteration:- prompt = f"""First provide a high-quality 1 page explanation based on sources (Date today: {current_time}). Keep citations and source link directly in text position. Never make up sources. Than provide a exact high-quality one sentence-long answer to the query.+ prompt = f"""First provide a high-quality 1 page explanation with IEEE Referencing Style e.g. [1,2]. Never make up sources. Than provide a exact high-quality one sentence-long answer to the query.Knowledge: {current_knowledge}Query: {query}- \n\n\nFormat: text summary\n\n"""+ I will append following text to your output for the sources (dont repeat it):\n\n {formatted_links}"""response = self.model.invoke(prompt)self._update_progress("Knowledge compression complete", None)- return remove_think_tags(response.content)+ response = remove_think_tags(response.content)+ response = str(response) + "\n\n" + str(formatted_links)+ print(response)+ return responsedef analyze_topic(self, query: str) -> Dict:findings = []current_knowledge = ""iteration = 0total_iterations = self.max_iterations+ section_links =list()self._update_progress("Initializing research system", 5, {"phase": "init",@@ -117,11 +123,10 @@ class AdvancedSearchSystem:{"phase": "search", "iteration": iteration + 1, "question_index": q_idx + 1})search_results = self.search.run(question)- limited_knowledge = (- current_knowledge[-self.context_limit :]- if len(current_knowledge) > self.context_limit- else current_knowledge- )++++self._update_progress(f"Found {len(search_results)} results for question: {question}",int(question_progress_base + 2),@@ -132,30 +137,36 @@ class AdvancedSearchSystem:if len(search_results) == 0:continue- print_search_results(search_results) # only links+self._update_progress(f"Analyzing results for: {question}",int(question_progress_base + 5),{"phase": "analysis"})-+ print("NR OF SOURCES: ", len(self.all_links_of_system))result = self.citation_handler.analyze_followup(- question, search_results, limited_knowledge+ question, search_results, current_knowledge, nr_of_links=len(self.all_links_of_system))-+ links = extract_links_from_search_results(search_results)+ self.all_links_of_system.extend(links)+ section_links.extend(links)+ formatted_links = ""+ if links:+ formatted_links=format_links(links=links)+ results_with_links = str(result["content"]) #+ "\n" + str(formatted_links)if result is not None:findings.append({"phase": f"Follow-up {iteration}.{questions.index(question) + 1}",- "content": result["content"],+ "content": results_with_links,"question": question,"search_results": search_results,"documents": result["documents"],})- links = extract_links_from_search_results(search_results)- results_with_links = str(result) + "\n" + str(links)- if config.KNOWLEDGE_ACCUMULATION != KnowledgeAccumulationApproach.NONE:+++ if config.KNOWLEDGE_ACCUMULATION != KnowledgeAccumulationApproach.NO_KNOWLEDGE:current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_linksprint(current_knowledge)@@ -163,7 +174,7 @@ class AdvancedSearchSystem:self._update_progress(f"Compress Knowledge for: {question}",int(question_progress_base + 0),{"phase": "analysis"})- current_knowledge = self._compress_knowledge(current_knowledge , query)+ current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)self._update_progress(f"Analysis complete for question: {question}",int(question_progress_base + 10),@@ -175,7 +186,7 @@ class AdvancedSearchSystem:int((iteration / total_iterations) * 100 - 5),{"phase": "knowledge_compression"})if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.ITERATION:- current_knowledge = self._compress_knowledge(current_knowledge , query)+ current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)self._update_progress(f"Iteration {iteration} complete",@@ -191,6 +202,7 @@ class AdvancedSearchSystem:"iterations": iteration,"questions": self.questions_by_iteration,"formatted_findings": formatted_findings,+ "current_knowledge": current_knowledge}def _save_findings(self, findings: List[Dict], current_knowledge: str, query: str):diff --git a/utilties/enums.py b/utilties/enums.pyindex f671a65126..e082679096 100644--- a/utilties/enums.py+++ b/utilties/enums.py@@ -4,5 +4,6 @@ from enum import Enum, autoclass KnowledgeAccumulationApproach(Enum):QUESTION = auto()ITERATION = auto()- NONE = auto()+ NO_KNOWLEDGE = auto()+ MAX_NR_OF_CHARACTERS = auto()diff --git a/utilties/search_utilities.py b/utilties/search_utilities.pyindex b0cbadca24..126c9cff43 100644--- a/utilties/search_utilities.py+++ b/utilties/search_utilities.py@@ -17,16 +17,26 @@ def extract_links_from_search_results(search_results: list) -> list:"""links = []for result in search_results:+ #print(result)try:+title = result.get("title", "").strip()url = result.get("link", "").strip()+ index = result.get("index", "").strip()+ print("INDEX:",index)if title and url:- links.append({"title": title, "url": url})+ links.append({"title": title, "url": url, "index": index})except Exception:continuereturn links- return links+def format_links(links):+ formatted_links =""+ formatted_links += "SOURCES:\n"+ for i, link in enumerate(links, 1):+ formatted_links += f"{link['index']}. {link['title']}\n URL: {link['url']}\n"+ formatted_links += "\n"+ return formatted_linksdef format_findings_to_text(findings_list, current_knowledge, questions_by_iteration):@@ -100,8 +110,6 @@ def print_search_results(search_results):formatted_text=""links = extract_links_from_search_results(search_results)if links:- formatted_text += "SOURCES USED IN THIS SECTION:\n"- for i, link in enumerate(links, 1):- formatted_text += f"{i}. {link['title']}\n URL: {link['url']}\n"- formatted_text += "\n"+ formatted_text=format_links(links=links)print(formatted_text)+