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.

inline sources partly working

LearningCircuit1a8cf0da7bf7
diff --git a/citation_handler.py b/citation_handler.py
new file mode 100644
index 0000000000..f7865aba1d
--- /dev/null
+++ b/citation_handler.py
@@ -0,0 +1,90 @@
+# citation_handler.py
+
+from langchain_core.documents import Document
+from typing import Dict, List, Union, Any
+import re
+from utilities import remove_think_tags
+
+
+class CitationHandler:
+ def __init__(self, llm):
+ self.llm = llm
+
+ def _create_documents(
+ self, search_results: Union[str, List[Dict]]
+ ) -> List[Document]:
+ """Convert search results to LangChain documents format."""
+ documents = []
+ if isinstance(search_results, str):
+ return documents
+
+ for i, result in enumerate(search_results):
+ if isinstance(result, dict):
+ content = result.get("full_content", result.get("snippet", ""))
+ documents.append(
+ Document(
+ page_content=content,
+ metadata={
+ "source": result.get("link", f"source_{i+1}"),
+ "title": result.get("title", f"Source {i+1}"),
+ "index": i+1,
+ },
+ )
+ )
+ return documents
+
+ def _format_sources(self, documents: List[Document]) -> str:
+ """Format sources with numbers for citation."""
+ sources = []
+ for doc in documents:
+ source_id = doc.metadata["index"]
+ sources.append(f"[{source_id}] {doc.page_content}")
+ return "\n\n".join(sources)
+
+ def analyze_initial(
+ self, query: str, search_results: Union[str, List[Dict]]
+ ) -> Dict[str, Any]:
+
+ documents = self._create_documents(search_results)
+ formatted_sources = self._format_sources(documents)
+
+ prompt = f"""Analyze the following information concerning the question and include citations using numbers in square brackets [1], [2], etc. When citing, use the source number provided at the start of each source.
+
+Question: {query}
+
+Sources:
+{formatted_sources}
+
+Provide a detailed analysis with citations and always keep URLS. Example format: "According to the research [1], ..."
+"""
+
+ response = self.llm.invoke(prompt)
+
+ return {"content": response.content, "documents": documents}
+
+ def analyze_followup(
+ self,
+ question: str,
+ search_results: Union[str, List[Dict]],
+ previous_knowledge: str,
+ ) -> Dict[str, Any]:
+ """Process follow-up analysis with citations."""
+ documents = self._create_documents(search_results)
+ formatted_sources = self._format_sources(documents)
+
+ prompt = f"""Using the previous knowledge and new sources, answer the question. Include citations using numbers in square brackets [1], [2], etc. When citing, use the source number provided at the start of each source. Always keep URLS.
+
+Previous Knowledge:
+{previous_knowledge}
+
+Question: {question}
+
+New Sources:
+{formatted_sources}
+
+Provide a detailed answer with citations. Example format: "According to [1], ..."
+"""
+
+ response = self.llm.invoke(prompt)
+
+ return {"content": remove_think_tags(response.content), "documents": documents}
diff --git a/config.py b/config.py
index 1d8c9cfe6a..1d4eeddf1d 100644
--- a/config.py
+++ b/config.py
@@ -15,12 +15,16 @@ DEFAULT_MODEL = "deepseek-r1:14b"
DEFAULT_TEMPERATURE = 0.7
MAX_TOKENS = 2000
+# Search System Settings
+SEARCH_ITERATIONS=3
+QUESTIONS_PER_ITERATION=2
+
# Search Configuration
-MAX_SEARCH_RESULTS = 3 # carefull if snippets are turned of it loads all full pages into your LLM context. = slow
+MAX_SEARCH_RESULTS = 40 # DuckDuckGoSearch seems to return only 4 results anyways.
SEARCH_REGION = "us-en"
TIME_PERIOD = "y"
SAFE_SEARCH = True
-SEARCH_SNIPPETS_ONLY=False # both have advantages and disadvantages
+SEARCH_SNIPPETS_ONLY = False # both have advantages and disadvantages
# Output Configuration
@@ -29,37 +33,29 @@ OUTPUT_DIR = "research_outputs"
def get_llm(model_name=DEFAULT_MODEL, temperature=DEFAULT_TEMPERATURE):
"""Get LLM instance - easy to switch between models"""
-
+
common_params = {
"temperature": temperature,
"max_tokens": MAX_TOKENS,
}
-
+
if "claude" in model_name:
- api_key = os.getenv('ANTHROPIC_API_KEY')
+ api_key = os.getenv("ANTHROPIC_API_KEY")
if not api_key:
raise ValueError("ANTHROPIC_API_KEY not found in environment variables")
return ChatAnthropic(
- model=model_name,
- anthropic_api_key=api_key,
- **common_params
+ model=model_name, anthropic_api_key=api_key, **common_params
)
-
+
elif "gpt" in model_name:
- api_key = os.getenv('OPENAI_API_KEY')
+ api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise ValueError("OPENAI_API_KEY not found in environment variables")
- return ChatOpenAI(
- model=model_name,
- api_key=api_key,
- **common_params
- )
-
+ return ChatOpenAI(model=model_name, api_key=api_key, **common_params)
+
else:
- return ChatOllama(
- model=model_name,
- **common_params
- )
+ return ChatOllama(model=model_name, **common_params)
+
def get_search():
if SEARCH_SNIPPETS_ONLY:
@@ -68,11 +64,13 @@ def get_search():
max_results=MAX_SEARCH_RESULTS,
region=SEARCH_REGION,
time=TIME_PERIOD,
- safesearch=SAFE_SEARCH
+ safesearch=SAFE_SEARCH,
)
else:
- return FullDuckDuckGoSearchResults(max_results=MAX_SEARCH_RESULTS,
+ return FullDuckDuckGoSearchResults(
+ max_results=MAX_SEARCH_RESULTS,
region=SEARCH_REGION,
time=TIME_PERIOD,
- safesearch=SAFE_SEARCH)
-
+ safesearch=SAFE_SEARCH,
+ llm=get_llm(),
+ )
diff --git a/full_duck_duck_go_search_results.py b/full_duck_duck_go_search_results.py
index f31607d978..55ad781f8d 100644
--- a/full_duck_duck_go_search_results.py
+++ b/full_duck_duck_go_search_results.py
@@ -2,104 +2,132 @@ import justext
from langchain_community.tools import DuckDuckGoSearchResults
from langchain.document_loaders import AsyncChromiumLoader
from langchain.document_transformers import BeautifulSoupTransformer
+from langchain_core.language_models import BaseLLM
+from typing import List, Dict
+import json, os
+from utilities import remove_think_tags
+from datetime import datetime
class FullDuckDuckGoSearchResults:
- """
- A wrapper class that mimics the DuckDuckGoSearchResults interface.
-
- Internally, it:
- 1. Uses DuckDuckGoSearchResults to get search results (with URLs).
- 2. Downloads the full HTML content for those URLs using AsyncChromiumLoader.
- 3. Processes the HTML using BeautifulSoupTransformer.
- 4. Applies justext to remove boilerplate from the extracted HTML.
-
- Additional parameters:
- - max_results: maximum number of search results to retrieve.
- - region: search region (e.g., "us-en").
- - time: time period filter (e.g., "d" for daily).
- - safesearch: safe search setting (e.g., "Moderate").
-
- From the outside, you simply call .invoke(query) (or use the instance as a callable)
- to get a list of search result dictionaries augmented with a "full_content" field.
- """
-
def __init__(
self,
+ llm: BaseLLM, # Add LLM parameter
output_format: str = "list",
language: str = "English",
max_results: int = 10,
region: str = "us-en",
time: str = "d",
- safesearch: str = "Moderate"
+ safesearch: str = "Moderate",
):
+ self.llm = llm
self.output_format = output_format
self.language = language
-
- # Additional parameters for DuckDuckGo search
self.max_results = max_results
self.region = region
self.time = time
self.safesearch = safesearch
-
- # Instantiate the DuckDuckGo search tool with extra parameters.
+ os.environ["USER_AGENT"] = "Local Deep Research/1.0"
+
+
self.ddg_search = DuckDuckGoSearchResults(
output_format=output_format,
max_results=self.max_results,
region=self.region,
time=self.time,
- safesearch=self.safesearch
+ safesearch=self.safesearch,
)
- # Instantiate the BeautifulSoup transformer (no parameters needed here)
self.bs_transformer = BeautifulSoupTransformer()
- # Store the tags to extract to be used later in transform_documents.
self.tags_to_extract = ["p", "div", "span"]
-
+
+ def check_urls(self, results: List[Dict], query: str) -> List[Dict]:
+ if not results:
+ return results
+
+ # Prepare the prompt for URL evaluation
+ urls_text = "\n".join(
+ [
+ f"URL: {r.get('link', '')}\n"
+ f"Title: {r.get('title', '')}\n"
+ f"Snippet: {r.get('snippet', '')}\n"
+ for r in results
+ ]
+ )
+
+
+ now = datetime.now()
+ current_time = now.strftime("%Y-%m-%d")
+ prompt = f"""ONLY Return a JSON array. The response contains no letters. Be very strict. Evaluate these URLs and their content for timeliness (today: {current_time}) known reliable near-academic sources (e.g., academic or government sources) and query relevance. query: {query}
+
+URLs to evaluate:
+{urls_text}
+
+ONLY Return a JSON array of indices (0-based) and nothing else. No letters.
+Example response: \n[0, 2, 4]\n\n"""
+
+ try:
+ # Get LLM's evaluation
+ response = self.llm.invoke(prompt)
+ #print(response)
+ good_indices = json.loads(remove_think_tags(response.content))
+
+ # Return only the results with good URLs
+ return [r for i, r in enumerate(results) if i in good_indices]
+ except Exception as e:
+ print(f"URL filtering error: {e}")
+ return results # Return original results if filtering fails
+
def remove_boilerplate(self, html: str) -> str:
- """
- Uses justext to remove boilerplate from the given HTML.
- Returns the cleaned text content.
- """
if not html or not html.strip():
return ""
paragraphs = justext.justext(html, justext.get_stoplist(self.language))
cleaned = "\n".join([p.text for p in paragraphs if not p.is_boilerplate])
return cleaned
-
+
def run(self, query: str):
- # Step 1: Get search results from DuckDuckGo.
+ nr_full_text=0
+ # Step 1: Get search results from DuckDuckGo
search_results = self.ddg_search.invoke(query)
if not isinstance(search_results, list):
raise ValueError("Expected the search results in list format.")
-
- # Extract URLs from the search results.
- urls = [result.get("link") for result in search_results if result.get("link")]
+
+ # Step 2: Filter URLs using LLM
+ filtered_results = self.check_urls(search_results, query)
+
+ # Extract URLs from filtered results
+ urls = [result.get("link") for result in filtered_results if result.get("link")]
if not urls:
- print("\n === NO LINKS===\n")
- return search_results # Return as is if no URLs are found.
-
- # Step 2: Download the full HTML pages for these URLs.
+ print("\n === NO VALID LINKS ===\n")
+ return filtered_results
+
+ # Step 3: Download the full HTML pages for filtered URLs
loader = AsyncChromiumLoader(urls)
- html_docs = loader.load() # Load HTML content synchronously.
-
- # Step 3: Process the HTML using BeautifulSoupTransformer.
- # Here we pass the tags_to_extract parameter.
- full_docs = self.bs_transformer.transform_documents(html_docs, tags_to_extract=self.tags_to_extract)
-
- # Step 4: Remove boilerplate from each document using justext.
+ html_docs = loader.load()
+
+ # Step 4: Process the HTML using BeautifulSoupTransformer
+ full_docs = self.bs_transformer.transform_documents(
+ html_docs, tags_to_extract=self.tags_to_extract
+ )
+
+ # Step 5: Remove boilerplate from each document
url_to_content = {}
for doc in full_docs:
+ nr_full_text = nr_full_text + 1
source = doc.metadata.get("source")
if source:
cleaned_text = self.remove_boilerplate(doc.page_content)
url_to_content[source] = cleaned_text
-
- # Attach the cleaned full content to each search result.
- for result in search_results:
+
+ # Attach the cleaned full content to each filtered result
+ for result in filtered_results:
link = result.get("link")
result["full_content"] = url_to_content.get(link, None)
- print("FULL SEARCH")
- return search_results
-
+
+ print("FULL SEARCH WITH FILTERED URLS")
+ print("Full text retrieved: ", nr_full_text)
+ return filtered_results
+
+ def invoke(self, query: str):
+ return self.run(query)
+
def __call__(self, query: str):
return self.invoke(query)
-
diff --git a/main.py b/main.py
index 5b1009eead..1405dc9172 100644
--- a/main.py
+++ b/main.py
@@ -1,15 +1,16 @@
from search_system import AdvancedSearchSystem
from typing import Dict
+
def print_report(report: Dict):
"""Print and save the report in a readable format"""
-
+
# Print to console in readable format
print("\n=== GENERATED REPORT ===\n")
-
+
# Print content
- print(report['content'])
-
+ print(report["content"])
+
# Print metadata in a clean format
print("\n=== METADATA ===")
print(f"Generated at: {report['metadata']['generated_at']}")
@@ -17,73 +18,92 @@ def print_report(report: Dict):
print(f"Sections researched: {report['metadata']['sections_researched']}")
print(f"Searches per section: {report['metadata']['searches_per_section']}")
print(f"Query: {report['metadata']['query']}")
-
+
# Save to file in markdown format
- with open("report.md", "w", encoding='utf-8') as markdown_file:
+ with open("report.md", "w", encoding="utf-8") as markdown_file:
# Write content
- markdown_file.write(report['content'])
-
+ markdown_file.write(report["content"])
+
# Write metadata at the end of the file
markdown_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"- 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")
+
from report_generator import IntegratedReportGenerator
+
report_generator = IntegratedReportGenerator()
+
+
def main():
system = AdvancedSearchSystem()
-
+
print("Welcome to the Advanced Research System")
print("Type 'quit' to exit")
-
+
while True:
print("\nSelect output type:")
print("1) Quick Summary (Generated in a few minutes)")
- print("2) Detailed Research Report (Recommended for deeper analysis - may take several hours)")
+ print(
+ "2) Detailed Research Report (Recommended for deeper analysis - may take several hours)"
+ )
choice = input("Enter number (1 or 2): ").strip()
-
+
while choice not in ["1", "2"]:
print("\nInvalid input. Please enter 1 or 2:")
print("1) Quick Summary (Generated in a few minutes)")
- print("2) Detailed Research Report (Recommended for deeper analysis - may take several hours)")
+ print(
+ "2) Detailed Research Report (Recommended for deeper analysis - may take several hours)"
+ )
choice = input("Enter number (1 or 2): ").strip()
-
+
query = input("\nEnter your research query: ").strip()
- if query.lower() == 'quit':
+ if query.lower() == "quit":
break
-
+
if choice == "1":
print("\nResearching... This may take a few minutes.\n")
else:
- print("\nGenerating detailed report... This may take several hours. Please be patient as this enables deeper analysis.\n")
-
+ print(
+ "\nGenerating detailed report... This may take several hours. Please be patient as this enables deeper analysis.\n"
+ )
+
results = system.analyze_topic(query)
if results:
if choice == "1":
# Quick Summary
print("\n=== QUICK SUMMARY ===")
- if results['findings'] and len(results['findings']) > 0:
- initial_analysis = results['findings'][0]['content']
+ if results["findings"] and len(results["findings"]) > 0:
+ initial_analysis = [finding["content"] for finding in results["findings"]]
print(initial_analysis)
- print(f"\nNumber of sources analyzed: {len(results['findings'])}")
+
else:
# Full Report
- final_report = report_generator.generate_report(results["findings"], query)
+ final_report = report_generator.generate_report(
+ results["findings"], query
+ )
print("\n=== RESEARCH REPORT ===")
print_report(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/report_generator.py b/report_generator.py
index ad1798159e..321f28b970 100644
--- a/report_generator.py
+++ b/report_generator.py
@@ -4,31 +4,38 @@ import re
from datetime import datetime
from search_system import AdvancedSearchSystem
+
class IntegratedReportGenerator:
- def __init__(self, searches_per_section: int = 2):
+ def __init__(self, searches_per_section: int = 2):
self.model = get_llm()
self.search_system = AdvancedSearchSystem()
- self.searches_per_section = searches_per_section # Control search depth per section
-
+ self.searches_per_section = (
+ searches_per_section # Control search depth per section
+ )
+
def _remove_think_tags(self, text: str) -> str:
print(text)
- return re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
+ return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
def generate_report(self, initial_findings: List[Dict], query: str) -> Dict:
"""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 3: Generate content with all research
- sections = self._generate_sections(initial_findings, section_research, structure, query)
-
+ sections = self._generate_sections(
+ initial_findings, section_research, structure, query
+ )
+
# Step 4: Format final report
- report_content = self._format_final_report(sections, structure, section_research)
-
+ report_content = self._format_final_report(
+ sections, structure, section_research
+ )
+
return {
"content": report_content,
"metadata": {
@@ -37,16 +44,19 @@ class IntegratedReportGenerator:
"sections_researched": len(section_research),
"searches_per_section": self.searches_per_section,
"query": query,
- "structure": structure
- }
+ "structure": structure,
+ },
}
except Exception as e:
print(f"Error generating report: {str(e)}")
return self._generate_error_report(query, str(e))
- def _determine_report_structure(self, findings: List[Dict], query: str) -> List[Dict]:
+
+ def _determine_report_structure(
+ self, findings: List[Dict], query: str
+ ) -> List[Dict]:
"""Analyze content and determine optimal report structure."""
combined_content = "\n\n".join([f["content"] for f in findings])
-
+
prompt = f"""
Analyze this research content about: {query}
@@ -70,39 +80,38 @@ class IntegratedReportGenerator:
Make the structure specific to the content, not generic.
Each subsection must include its purpose after the | symbol.
"""
-
+
response = self._remove_think_tags(self.model.invoke(prompt).content)
-
+
# Parse the structure
structure = []
current_section = None
-
- for line in response.split('\n'):
- if line.strip() in ['STRUCTURE', 'END_STRUCTURE']:
+
+ for line in response.split("\n"):
+ if line.strip() in ["STRUCTURE", "END_STRUCTURE"]:
continue
-
- if line.strip().startswith(tuple('123456789')):
+
+ if line.strip().startswith(tuple("123456789")):
# Main section
- section_name = line.split('.')[1].strip()
- current_section = {
- 'name': section_name,
- 'subsections': []
- }
+ section_name = line.split(".")[1].strip()
+ current_section = {"name": section_name, "subsections": []}
structure.append(current_section)
- elif line.strip().startswith('-') and current_section:
+ elif line.strip().startswith("-") and current_section:
# Subsection with purpose
- parts = line.strip('- ').split('|')
+ parts = line.strip("- ").split("|")
if len(parts) == 2:
- current_section['subsections'].append({
- 'name': parts[0].strip(),
- 'purpose': parts[1].strip()
- })
-
+ current_section["subsections"].append(
+ {"name": parts[0].strip(), "purpose": parts[1].strip()}
+ )
+
return structure
- def _research_sections(self, structure: List[Dict], main_query: str) -> Dict[str, List[Dict]]:
+
+ 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"""
@@ -113,40 +122,50 @@ class IntegratedReportGenerator:
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:')]
-
+
+ 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]:
+ 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
-
+ 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(self, initial_findings: List[Dict],
- section_research: Dict[str, List[Dict]],
- structure: List[Dict], query: str) -> Dict[str, str]:
+ def _generate_sections(
+ self,
+ initial_findings: List[Dict],
+ section_research: Dict[str, List[Dict]],
+ structure: List[Dict],
+ query: str,
+ ) -> Dict[str, str]:
sections = {}
accumulated_content = ""
-
+
for section in structure:
section_content = []
-
+
# Get section-specific research
- section_findings = section_research.get(section['name'], [])
+ section_findings = section_research.get(section["name"], [])
research_content = "\n\n".join([f["content"] for f in section_findings])
-
- if not section['subsections']:
+
+ if not section["subsections"]:
# Generate content for sections without subsections
prompt = f"""
Research Query: {query}
@@ -164,12 +183,12 @@ class IntegratedReportGenerator:
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']:
+ for subsection in section["subsections"]:
prompt = f"""
Research Query: {query}
Section: {section['name']}
@@ -187,38 +206,42 @@ class IntegratedReportGenerator:
4. Builds upon previous content
5. Uses appropriate formatting
"""
-
- response = self._remove_think_tags(self.model.invoke(prompt).content)
+
+ 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
- sections[section['name']] = '\n'.join(section_content)
-
- return sections
+ sections[section["name"]] = "\n".join(section_content)
+ return sections
- def _format_final_report(self, sections: Dict[str, str],
- structure: List[Dict],
- section_research: Dict[str, List[Dict]]) -> str:
+ 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
-
+
# Generate TOC
toc = ["# 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):
+ for j, subsection in enumerate(section["subsections"], 1):
toc.append(f" - {subsection['name']} | _{subsection['purpose']}_")
-
+
# Combine TOC and sections
- report_parts = ['\n'.join(toc), ""]
-
+ report_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:
@@ -226,32 +249,32 @@ class IntegratedReportGenerator:
report_parts.append(research_header)
report_parts.append(f"Number of focused searches: {len(findings)}")
report_parts.append("\n---\n")
-
+
# Process section content to remove duplicate headers
for 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')
+ if section["name"] in sections:
+ content_lines = sections[section["name"]].split("\n")
filtered_lines = []
-
+
for line in content_lines:
- if line.strip().startswith('#'):
+ 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("\n".join(filtered_lines))
report_parts.append("")
-
- return '\n\n'.join(report_parts)
+
+ return "\n\n".join(report_parts)
def _combine_findings(self, findings: List[Dict]) -> str:
return "\n\n".join([f["content"] for f in findings])
@@ -262,6 +285,6 @@ class IntegratedReportGenerator:
"metadata": {
"error": error_msg,
"generated_at": datetime.now().isoformat(),
- "status": "failed"
- }
+ "status": "failed",
+ },
}
diff --git a/search_system.py b/search_system.py
index 92262aa40c..4885ecaeba 100644
--- a/search_system.py
+++ b/search_system.py
@@ -2,98 +2,111 @@ from typing import Dict, List
from datetime import datetime
from utilities import remove_think_tags, format_findings_to_text
import os
-from config import get_llm, get_search
+from config import get_llm, get_search, SEARCH_ITERATIONS, QUESTIONS_PER_ITERATION
+from citation_handler import CitationHandler
+from datetime import datetime
+
class AdvancedSearchSystem:
def __init__(self):
self.search = get_search()
self.model = get_llm()
- self.max_iterations = 2
+ self.max_iterations = SEARCH_ITERATIONS
+ self.questions_per_iteration = QUESTIONS_PER_ITERATION
self.context_limit = 5000
self.questions_by_iteration = {}
-
- def _get_initial_questions(self, query: str) -> List[str]:
- prompt = f"Generate 3 essential research questions to investigate: {query}\nFormat: One question per line starting with Q:"
- response = self.model.invoke(prompt)
- return [q.replace('Q:', '').strip()
- for q in remove_think_tags(response.content).split('\n')
- if q.strip().startswith('Q:')][:3]
+ self.citation_handler = CitationHandler(self.model)
def _get_follow_up_questions(self, current_knowledge: str, query: str) -> List[str]:
- limited_knowledge = current_knowledge[-self.context_limit:] if len(current_knowledge) > self.context_limit else current_knowledge
- prompt = f"""Based on current knowledge, what critical questions remain unanswered?
-Query: {query}
-Past questions: {str(self.questions_by_iteration)}
-Knowledge: {limited_knowledge}
-Format: One question per line starting with Q:"""
- response = self.model.invoke(prompt)
- return [q.replace('Q:', '').strip()
- for q in remove_think_tags(response.content).split('\n')
- if q.strip().startswith('Q:')][:3]
+ now = datetime.now()
+ current_time = now.strftime("%Y-%m-%d")
+ if self.questions_by_iteration:
+ prompt = f"""Critically reflect current knowledge (e.g., timeliness), what {self.questions_per_iteration} high-quality internet search questions remain unanswered to exactly answer the query?
+ Query: {query}
+ Today: {current_time}
+ Past questions: {str(self.questions_by_iteration)}
+ Knowledge: {current_knowledge}
+ Include questions that critically reflect current knowledge.
+ \n\n\nFormat: One question per line, e.g. \n Q: question1\n\n"""
+ else:
+ prompt = f" You will have follow up questions. First, identify if your knowledge is outdated (high chance). Today: {current_time}. Generate {self.questions_per_iteration} high-quality internet search questions to exactly answer: {query}\n\n\nFormat: One question per line, e.g. \n Q: question1\n\n"
+ response = self.model.invoke(prompt)
+ return [
+ q.replace("Q:", "").strip()
+ for q in remove_think_tags(response.content).split("\n")
+ if q.strip().startswith("Q:")
+ ][:self.questions_per_iteration]
+ def _compress_knowledge(self, current_knowledge: str, query: str) -> List[str]:
+ now = datetime.now()
+ current_time = now.strftime("%Y-%m-%d")
+ if self.questions_by_iteration:
+ prompt = f"""First provide a exact high-quality one sentence-long answer to the query (Date today: {current_time}). Than provide a high-quality long explanation based on sources. Keep citations and provide literature section. Never make up sources.
+ Past questions: {str(self.questions_by_iteration)}
+ Knowledge: {current_knowledge}
+ Query: {query}
+ \n\n\nFormat: text summary\n\n"""
+ response = self.model.invoke(prompt)
+ return remove_think_tags(response.content)
+
def analyze_topic(self, query: str) -> Dict:
findings = []
current_knowledge = ""
iteration = 0
while iteration < self.max_iterations:
- if iteration == 0:
- initial_questions = self._get_initial_questions(query)
- self.questions_by_iteration[0] = initial_questions
-
- # Store results differently for initial analysis
- all_search_results = ""
- for question in initial_questions:
- search_results = self.search.run(question)
- all_search_results += f"Question: {question}\n{search_results}\n\n"
-
- initial_analysis = self.model.invoke(
- f"Analyze findings for: {query}\n{all_search_results}"
+ questions = self._get_follow_up_questions(current_knowledge, query)
+ self.questions_by_iteration[iteration] = questions
+ for question in questions:
+ search_results = self.search.run(question)
+ limited_knowledge = (
+ current_knowledge[-self.context_limit :]
+ if len(current_knowledge) > self.context_limit
+ else current_knowledge
+ )
+ print("len search", len(search_results))
+ #print(search_results)
+ if len(search_results) ==0:
+ continue
+
+
+ result = self.citation_handler.analyze_followup(
+ question, search_results, limited_knowledge
)
- findings.append({
- "phase": "Initial Analysis",
- "content": remove_think_tags(initial_analysis.content),
- "questions": initial_questions,
- "search_results": all_search_results
- })
- current_knowledge = remove_think_tags(initial_analysis.content)
- else:
- questions = self._get_follow_up_questions(current_knowledge, query)
- self.questions_by_iteration[iteration] = questions
- for question in questions:
- search_results = self.search.run(question)
- limited_knowledge = current_knowledge[-self.context_limit:] if len(current_knowledge) > self.context_limit else current_knowledge
-
- analysis = self.model.invoke(
- f"Question: {question}\nResults: {search_results}\nKnowledge: {limited_knowledge}\nExtend knowledge and conclude on question."
- )
- findings.append({
+ findings.append(
+ {
"phase": f"Follow-up {iteration}.{questions.index(question) + 1}",
- "content": remove_think_tags(analysis.content),
+ "content": result["content"],
"question": question,
- "search_results": search_results
- })
- current_knowledge += f"\n\n{remove_think_tags(analysis.content)}"
-
+ "search_results": search_results,
+ "documents": result["documents"],
+ }
+ )
+ current_knowledge += f"\n\n{result['content']}"
+
iteration += 1
+ current_knowledge = self._compress_knowledge(current_knowledge, query)
self._save_findings(findings, current_knowledge, query)
return {
"findings": findings,
"iterations": iteration,
- "questions": self.questions_by_iteration
+ "questions": self.questions_by_iteration,
}
def _save_findings(self, findings: List[Dict], current_knowledge: str, query: str):
- formatted_findings = format_findings_to_text(findings, current_knowledge, self.questions_by_iteration)
- safe_query = "".join(x for x in query if x.isalnum() or x in [' ', '-', '_'])[:50]
- safe_query = safe_query.replace(' ', '_').lower()
+ formatted_findings = format_findings_to_text(
+ findings, current_knowledge, self.questions_by_iteration
+ )
+ safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[
+ :50
+ ]
+ safe_query = safe_query.replace(" ", "_").lower()
-
output_dir = "research_outputs"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
-
+
filename = os.path.join(output_dir, f"formatted_output_{safe_query}.txt")
-
- with open(filename, "w", encoding='utf-8') as text_file:
+
+ with open(filename, "w", encoding="utf-8") as text_file:
text_file.write(formatted_findings)
diff --git a/utilities.py b/utilities.py
index bf460f71f2..afc07da4c5 100644
--- a/utilities.py
+++ b/utilities.py
@@ -1,16 +1,18 @@
import re
-def remove_think_tags(text: str) -> str:
- print(text)
- return re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
+def remove_think_tags(text: str) -> str:
+ text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
+ print(text)
+ return text
+
def extract_links_from_search_results(search_results: list) -> list:
"""
Extracts links and titles from a list of search result dictionaries.
-
+
Each dictionary is expected to have at least the keys "title" and "link".
-
+
Returns a list of dictionaries with 'title' and 'url' keys.
"""
links = []
@@ -19,24 +21,22 @@ def extract_links_from_search_results(search_results: list) -> list:
title = result.get("title", "").strip()
url = result.get("link", "").strip()
if title and url:
- links.append({
- "title": title,
- "url": url
- })
+ links.append({"title": title, "url": url})
except Exception:
continue
return links
-
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"
-
+ 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():
@@ -44,52 +44,54 @@ def format_findings_to_text(findings_list, current_knowledge, questions_by_itera
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]):
+ 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"
-
+ 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'])
+ 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:
+ if link["url"] not in seen_urls:
formatted_text += f"{i}. {link['title']}\n URL: {link['url']}\n"
- seen_urls.add(link['url'])
+ seen_urls.add(link["url"])
formatted_text += "\n" + "=" * 80 + "\n"
-
+
return formatted_text