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.

Add files via upload

LearningCircuitcd5b9b218368
diff --git a/license.md b/license.md
new file mode 100644
index 0000000000..dc0956742e
--- /dev/null
+++ b/license.md
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2024 Local Deep Research
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/main.py b/main.py
new file mode 100644
index 0000000000..cc2acc473e
--- /dev/null
+++ b/main.py
@@ -0,0 +1,61 @@
+from search_system import AdvancedSearchSystem
+from typing import Dict
+
+def print_report(report: Dict):
+ print("\n=== EXECUTIVE SUMMARY ===")
+ print(report["executive_summary"])
+
+ print("\n=== MAIN FINDINGS ===")
+ for i, finding in enumerate(report["main_findings"], 1):
+ print(f"{i}. {finding}")
+
+ print("\n=== DETAILED ANALYSIS ===")
+ print("\nKey Points:")
+ for i, point in enumerate(report["detailed_analysis"]["key_points"], 1):
+ print(f"{i}. {point}")
+
+ print("\nEvidence:")
+ for i, evidence in enumerate(report["detailed_analysis"]["evidence"], 1):
+ print(f"{i}. {evidence}")
+
+ print("\nUncertainties:")
+ for i, uncertainty in enumerate(report["detailed_analysis"]["uncertainties"], 1):
+ print(f"{i}. {uncertainty}")
+
+ print("\n=== CONFIDENCE SCORES ===")
+ for metric, score in report["confidence_scores"].items():
+ print(f"{metric.replace('_', ' ').title()}: {float(score):.2f}")
+
+ print("\n=== RECOMMENDATIONS ===")
+ for i, rec in enumerate(report["recommendations"], 1):
+ print(f"{i}. {rec}")
+
+def main():
+ system = AdvancedSearchSystem()
+
+ print("Welcome to the Advanced Research System")
+ print("Type 'quit' to exit")
+
+ while True:
+ query = input("\nEnter your research query: ").strip()
+
+ if query.lower() == 'quit':
+ break
+
+ print("\nResearching... This may take a few minutes.\n")
+
+ results = system.analyze_topic(query)
+
+ if results:
+ # Print console report
+ print("\n=== RESEARCH REPORT ===")
+ print_report(results["final_report"])
+
+ print("\n=== RESEARCH METRICS ===")
+ print(f"Search Iterations: {results['iterations']}")
+
+ else:
+ print("Research failed. Please try again.")
+
+if __name__ == "__main__":
+ main()
diff --git a/readme.md b/readme.md
new file mode 100644
index 0000000000..c4e0dbc544
--- /dev/null
+++ b/readme.md
@@ -0,0 +1,97 @@
+# Local Deep Research
+
+A powerful local research tool that performs deep, iterative analysis using AI and web searches, running entirely on your machine.
+
+## Features
+
+- 🔍 Automated deep research with intelligent follow-up questions
+- 🤖 Local AI processing - choose models based on your hardware
+- 📊 Comprehensive research findings in formatted_output.txt (main output)
+- 🔄 Iterative analysis with tracked sources and citations
+- 📝 Additional report formats (work in progress)
+- 🔒 Complete privacy: runs entirely on your machine
+
+## Research Document Example
+
+The tool generates a comprehensive research document (`formatted_output.txt`) structured like this:
+
+```
+SEARCH QUESTIONS BY ITERATION:
+
+Iteration 1:
+1. What are the key foundational advancements in neural networks and algorithms that are driving current AI innovation?
+2. How can ethical considerations and transparency be effectively integrated into AI systems?
+3. What are the most transformative industry applications of AI?
+
+DETAILED FINDINGS:
+================================================================================
+PHASE: Initial Analysis
+================================================================================
+
+CONTENT:
+The analysis of current AI innovations highlights several key areas:
+
+1. Machine Learning and Deep Learning: These form the backbone of many AI
+ applications, enabling machines to learn from data without explicit programming.
+
+2. Natural Language Processing (NLP): Advances like GPT-3 have transformed
+ human-AI interactions, making NLP a pivotal area due to its widespread
+ applications in chatbots and virtual assistants.
+
+[Additional findings...]
+
+SOURCES USED IN THIS SECTION:
+1. Top Foundations and Trends in Machine Learning for 2024
+ URL: https://example.com/source1
+2. Neural Network Development Trends
+ URL: https://example.com/source2
+```
+
+## Installation
+
+1. Clone the repository:
+```bash
+git clone https://github.com/yourusername/local-deep-research.git
+cd local-deep-research
+```
+
+2. Install dependencies:
+```bash
+pip install -r requirements.txt
+```
+
+3. Install Ollama and choose your model based on your hardware:
+```bash
+# Install Ollama from https://ollama.ai
+ollama pull deepseek-r1:14b # Or mistral:7b for lighter hardware
+```
+
+## Quick Start
+
+Run the research tool:
+```bash
+python main.py
+```
+
+Enter your research query when prompted. The system will generate detailed research findings in `formatted_output.txt`.
+
+## Model Options
+
+Choose your model based on available computing power:
+```python
+# Lightweight option
+self.model = ChatOllama(model="mistral:7b", temperature=0.7)
+
+# More powerful (default)
+self.model = ChatOllama(model="deepseek-r1:14b", temperature=0.7)
+```
+
+## License
+
+This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
+
+## Acknowledgments
+
+- Built with [Ollama](https://ollama.ai)
+- Search powered by DuckDuckGo
+- Built on [LangChain](https://github.com/hwchase17/langchain) framework
diff --git a/report_generator.py b/report_generator.py
new file mode 100644
index 0000000000..6c89e9c832
--- /dev/null
+++ b/report_generator.py
@@ -0,0 +1,126 @@
+from typing import Dict, List
+from langchain_ollama import ChatOllama
+
+def remove_think_tags(text):
+ import re
+ text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)
+ print(text)
+ return text
+
+class ResearchReportGenerator:
+ def __init__(self):
+ self.model = ChatOllama(model="deepseek-r1:14b", temperature=0.7)
+
+ def generate_report(self, findings: List[Dict]) -> Dict:
+ """Generate a complete research report from findings"""
+ return {
+ "executive_summary": self._generate_executive_summary(findings),
+ "main_findings": self._generate_main_findings(findings),
+ "detailed_analysis": self._generate_detailed_analysis(findings),
+ "confidence_scores": self._generate_confidence_scores(findings),
+ "recommendations": self._generate_recommendations(findings)
+ }
+
+ def _generate_executive_summary(self, findings: List[Dict]) -> str:
+ all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
+ prompt = f"""
+ Create a concise executive summary of these research findings:
+
+ {all_content}
+
+ Provide a clear, high-level overview of the key discoveries and implications.
+ Keep the summary under 200 words and focus on the most important points.
+ """
+ response = self.model.invoke(prompt)
+ return remove_think_tags(response.content).strip()
+
+ def _generate_main_findings(self, findings: List[Dict]) -> List[str]:
+ all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
+ prompt = f"""
+ List the 5 most important main findings from this research:
+
+ {all_content}
+
+ Format each finding as a clear, complete sentence on its own line.
+ Start each line with "- "
+ """
+ response = self.model.invoke(prompt)
+ findings_list = [
+ line[2:] for line in remove_think_tags(response.content).split('\n')
+ if line.strip().startswith('- ')
+ ]
+ return findings_list[:5]
+
+ def _generate_detailed_analysis(self, findings: List[Dict]) -> Dict:
+ all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
+ prompt = f"""
+ Analyze these research findings in detail:
+
+ {all_content}
+
+ Provide three separate lists:
+ 1. Key Points (start each with "KEY: ")
+ 2. Supporting Evidence (start each with "EVIDENCE: ")
+ 3. Uncertainties or Limitations (start each with "UNCERTAINTY: ")
+
+ Limit each list to 3-5 items.
+ """
+ response = self.model.invoke(prompt)
+ content = remove_think_tags(response.content)
+
+ return {
+ "key_points": [line[5:] for line in content.split('\n') if line.strip().startswith('KEY: ')][:5],
+ "evidence": [line[10:] for line in content.split('\n') if line.strip().startswith('EVIDENCE: ')][:5],
+ "uncertainties": [line[12:] for line in content.split('\n') if line.strip().startswith('UNCERTAINTY: ')][:5]
+ }
+
+ def _generate_confidence_scores(self, findings: List[Dict]) -> Dict:
+ all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
+ prompt = f"""
+ Evaluate the confidence scores for these research findings:
+
+ {all_content}
+
+ Provide three scores between 0 and 1 in this exact format:
+ DATA_QUALITY: [score]
+ SOURCE_RELIABILITY: [score]
+ CONCLUSION_STRENGTH: [score]
+ """
+ response = self.model.invoke(prompt)
+ content = remove_think_tags(response.content)
+
+ scores = {
+ "data_quality": 0.0,
+ "source_reliability": 0.0,
+ "conclusion_strength": 0.0
+ }
+
+ for line in content.split('\n'):
+ if ':' in line:
+ key, value = line.split(':')
+ key = key.strip().lower().replace(' ', '_')
+ try:
+ value = float(value.strip('[] '))
+ if key in scores:
+ scores[key] = min(max(value, 0.0), 1.0)
+ except ValueError:
+ continue
+
+ return scores
+
+ def _generate_recommendations(self, findings: List[Dict]) -> List[str]:
+ all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
+ prompt = f"""
+ Based on these research findings, provide key recommendations:
+
+ {all_content}
+
+ List 3-5 specific, actionable recommendations.
+ Start each with "REC: "
+ """
+ response = self.model.invoke(prompt)
+ recommendations = [
+ line[5:] for line in remove_think_tags(response.content).split('\n')
+ if line.strip().startswith('REC: ')
+ ]
+ return recommendations[:5]
diff --git a/requirements.txt b/requirements.txt
new file mode 100644
index 0000000000..82323ca584
--- /dev/null
+++ b/requirements.txt
@@ -0,0 +1,7 @@
+langchain==0.3.18
+langchain-community>=0.3.17
+langchain-core>=0.3.34
+langchain-ollama>=0.2.3
+duckduckgo_search>=7.3.2
+python-dateutil>=2.9.0
+typing_extensions>=4.12.2
diff --git a/search_system.py b/search_system.py
new file mode 100644
index 0000000000..28c02c7fe4
--- /dev/null
+++ b/search_system.py
@@ -0,0 +1,103 @@
+from langchain_community.tools import DuckDuckGoSearchResults
+from langchain_ollama import ChatOllama
+from typing import Dict, List
+from datetime import datetime
+from report_generator import ResearchReportGenerator, remove_think_tags
+
+class AdvancedSearchSystem:
+ def __init__(self):
+ self.search = DuckDuckGoSearchResults(max_results=40)
+ self.model = ChatOllama(model="deepseek-r1:14b", temperature=0.7)
+ self.report_generator = ResearchReportGenerator()
+ self.max_iterations = 10
+ self.context_limit = 5000 # Maximum characters to keep as context
+ self.questions_by_iteration = {} # New: track questions
+
+ def _get_follow_up_questions(self, current_knowledge: str, query: str) -> List[str]:
+ # Limit the context for the model
+ limited_knowledge = current_knowledge[-self.context_limit:] if len(current_knowledge) > self.context_limit else current_knowledge
+
+ prompt = f"""
+ Based on our current knowledge, what are the most important questions we still need to answer concerning the user query?
+ query: {query}
+ Past questions:
+ {str(self.questions_by_iteration)}
+ Recent Knowledge:
+ {limited_knowledge}
+
+ List only the top 3 most critical questions that would help fill in gaps or resolve uncertainties. Do not repeat questions.
+ Format: One question per line, starting with 'Q: '
+ """
+ response = self.model.invoke(prompt)
+ questions = [q.replace('Q: ', '').strip()
+ for q in remove_think_tags(response.content).split('\n')
+ if q.strip().startswith('Q: ')]
+ print(questions)
+ return questions[:3]
+
+ def analyze_topic(self, query: str) -> Dict:
+ findings = []
+ current_knowledge = ""
+ iteration = 0
+
+ while iteration < self.max_iterations:
+ if iteration == 0:
+ search_results = " - Ask questions about this topic."
+ initial_analysis = self.model.invoke(
+ f"Analyze these results about: {query}\n\nResults: {search_results}"
+ )
+ findings.append({
+ "phase": "Initial Analysis",
+ "content": remove_think_tags(initial_analysis.content)
+ })
+ current_knowledge = remove_think_tags(initial_analysis.content)
+
+ else:
+ questions = self._get_follow_up_questions(current_knowledge, query)
+ self.questions_by_iteration[iteration] = questions # Store questions
+ for question in questions:
+ search_results = self.search.run(question)
+ print(search_results)
+
+ limited_knowledge = current_knowledge[-self.context_limit:] if len(current_knowledge) > self.context_limit else current_knowledge
+
+ analysis_prompt = f"""
+ Question: {question}
+
+ Results: {search_results}
+
+ Knowledge:
+ {limited_knowledge}
+
+ Extend current knowledge on question and provide a conclusion on question.
+ """
+ analysis = self.model.invoke(analysis_prompt)
+ findings.append({
+ "phase": f"Follow-up {iteration}.{questions.index(question) + 1}",
+ "content": remove_think_tags(analysis.content),
+ "question": question, # New: store question
+ "search_results": search_results
+ })
+ current_knowledge += f"\n\n\n{remove_think_tags(analysis.content)}"
+ iteration += 1
+ print("Research iteration ", iteration)
+ # Add encoding='utf-8' to all file operations
+ with open("temp_output.txt", "w", encoding='utf-8') as text_file:
+ text_file.write(str(current_knowledge))
+ with open("temp_output_findings.txt", "w", encoding='utf-8') as text_file:
+ text_file.write(str(findings))
+ from utilities import format_findings_to_text
+ formatted_findings = format_findings_to_text(findings, current_knowledge, self.questions_by_iteration)
+ with open("formatted_output.txt", "w", encoding='utf-8') as text_file:
+ text_file.write(formatted_findings)
+ with open("Output.txt", "w", encoding='utf-8') as text_file:
+ text_file.write(str(findings))
+
+ final_report = self.report_generator.generate_report(findings)
+
+ return {
+ "findings": findings,
+ "final_report": final_report,
+ "iterations": iteration,
+ "questions": self.questions_by_iteration # New: return questions
+ }
diff --git a/utilities.py b/utilities.py
new file mode 100644
index 0000000000..f36014cab8
--- /dev/null
+++ b/utilities.py
@@ -0,0 +1,83 @@
+
+def extract_links_from_search_results(search_results_str: str) -> list:
+ """Extract links and titles from search results string"""
+ links = []
+ # Split the string by 'title:' and 'link:'
+ parts = search_results_str.split("title: ")
+
+ for part in parts[1:]: # Skip first part before first 'title:'
+ try:
+ title = part.split(", link: ")[0]
+ link = part.split(", link: ")[1].split(", snippet:")[0]
+ links.append({
+ "title": title.strip(),
+ "url": link.strip()
+ })
+ except:
+ continue
+
+ return links
+def format_findings_to_text(findings_list, current_knowledge, questions_by_iteration):
+ formatted_text = "COMPLETE RESEARCH OUTPUT\n\n"
+
+ # Store the full current knowledge
+ #formatted_text += "FULL ACCUMULATED KNOWLEDGE:\n"
+ #formatted_text += f"{current_knowledge}\n\n"
+ #formatted_text += "=" * 80 + "\n\n"
+
+ # Store questions by iteration
+ formatted_text += "SEARCH QUESTIONS BY ITERATION:\n"
+ for iter_num, questions in questions_by_iteration.items():
+ formatted_text += f"\nIteration {iter_num}:\n"
+ for i, q in enumerate(questions, 1):
+ formatted_text += f"{i}. {q}\n"
+ formatted_text += "\n" + "=" * 80 + "\n\n"
+
+ # Store detailed findings
+ formatted_text += "DETAILED FINDINGS:\n\n"
+ all_links = [] # To collect all sources
+
+ for finding in findings_list:
+ # Phase header
+ formatted_text += f"{'='*80}\n"
+ formatted_text += f"PHASE: {finding['phase']}\n"
+ formatted_text += f"{'='*80}\n\n"
+
+ # If this is a follow-up phase, show the corresponding question
+ if finding['phase'].startswith('Follow-up'):
+ iteration = int(finding['phase'].split('.')[0].split()[-1])
+ question_index = int(finding['phase'].split('.')[-1]) - 1
+ if iteration in questions_by_iteration and question_index < len(questions_by_iteration[iteration]):
+ formatted_text += f"SEARCH QUESTION:\n{questions_by_iteration[iteration][question_index]}\n\n"
+
+ # Content
+ formatted_text += f"CONTENT:\n{finding['content']}\n\n"
+
+ # Search results if they exist
+ if 'search_results' in finding:
+ formatted_text += "SEARCH RESULTS:\n"
+ formatted_text += f"{finding['search_results']}\n\n"
+
+ # Extract and format links for this finding
+ links = extract_links_from_search_results(finding['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"
+ all_links.extend(links)
+
+ formatted_text += f"{'_'*80}\n\n"
+
+ # Add summary of all sources at the end
+ if all_links:
+ formatted_text += "\nALL SOURCES USED IN RESEARCH:\n"
+ formatted_text += "=" * 80 + "\n\n"
+ seen_urls = set() # To prevent duplicates
+ for i, link in enumerate(all_links, 1):
+ if link['url'] not in seen_urls:
+ formatted_text += f"{i}. {link['title']}\n URL: {link['url']}\n"
+ seen_urls.add(link['url'])
+ formatted_text += "\n" + "=" * 80 + "\n"
+
+ return formatted_text
\ No newline at end of file