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.

Update report_generator.py

LearningCircuitd0a625da0f96
diff --git a/report_generator.py b/report_generator.py
index 45eb0611e4..f04e230e30 100644
--- a/report_generator.py
+++ b/report_generator.py
@@ -1,137 +1,268 @@
-from typing import Dict, List
+from typing import Dict, List, Optional
from langchain_ollama import ChatOllama
+import re
+from datetime import datetime
+from search_system import AdvancedSearchSystem
-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], query : str) -> Dict:
- """Generate a complete research report from findings"""
- return {
- "executive_summary": self._generate_executive_summary(findings, query),
- "main_findings": self._generate_main_findings(findings, query),
- "detailed_analysis": self._generate_detailed_analysis(findings, query),
- "confidence_scores": self._generate_confidence_scores(findings, query),
- "recommendations": self._generate_recommendations(findings, query)
- }
+class IntegratedReportGenerator:
+ def __init__(self, model_name: str = "deepseek-r1:14b", temperature: float = 0.7,
+ searches_per_section: int = 3):
+ self.model = ChatOllama(model=model_name, temperature=temperature)
+ self.search_system = AdvancedSearchSystem()
+ 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()
- def _generate_executive_summary(self, findings: List[Dict], query : str) -> str:
- all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
+ 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)
+
+ # Step 4: Format final report
+ report_content = self._format_final_report(sections, structure, section_research)
+
+ 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))
+ 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"""
- Relate to the user query: {query}
+ Analyze this research content about: {query}
- 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()
+ Content Summary:
+ {combined_content[:1000]}... [truncated]
- def _generate_main_findings(self, findings: List[Dict], query : str) -> List[str]:
- all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
- prompt = f"""
- Relate to the user query: {query}
+ Determine the most appropriate report structure by:
+ 1. Analyzing the type of content (technical, business, academic, etc.)
+ 2. Identifying main themes and logical groupings
+ 3. Considering the depth and breadth of the research
+
+ Return a table of contents structure in this exact format:
+ STRUCTURE
+ 1. [Section Name]
+ - [Subsection] | [purpose]
+ 2. [Section Name]
+ - [Subsection] | [purpose]
+ ...
+ END_STRUCTURE
- List the 5 most important main findings from this research:
+ Make the structure specific to the content, not generic.
+ Each subsection must include its purpose after the | symbol.
+ """
- {all_content}
+ response = self._remove_think_tags(self.model.invoke(prompt).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], query : str) -> Dict:
- all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
- prompt = f"""
- Relate to the user query: {query}
-
- Analyze these research findings in detail:
+ # Parse the structure
+ structure = []
+ current_section = None
- {all_content}
+ for line in response.split('\n'):
+ if line.strip() in ['STRUCTURE', 'END_STRUCTURE']:
+ continue
+
+ if line.strip().startswith(tuple('123456789')):
+ # Main section
+ section_name = line.split('.')[1].strip()
+ current_section = {
+ 'name': section_name,
+ 'subsections': []
+ }
+ structure.append(current_section)
+ elif line.strip().startswith('-') and current_section:
+ # Subsection with purpose
+ parts = line.strip('- ').split('|')
+ if len(parts) == 2:
+ current_section['subsections'].append({
+ 'name': parts[0].strip(),
+ 'purpose': parts[1].strip()
+ })
- 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: ")
+ return structure
+ def _research_sections(self, structure: List[Dict], main_query: str) -> Dict[str, List[Dict]]:
+ """Research each section using the AdvancedSearchSystem."""
+ section_research = {}
- Limit each list to 3-5 items.
- """
- response = self.model.invoke(prompt)
- content = remove_think_tags(response.content)
+ 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 = 1
+ 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]:
+ sections = {}
+ accumulated_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]
- }
+ for section in structure:
+ 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: {section['name']}
+
+ Previous Content: {accumulated_content[:1000] if accumulated_content else "None yet"}
+
+ General Research:
+ {self._combine_findings(initial_findings)}
+
+ 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
+ sections[section['name']] = '\n'.join(section_content)
+
+ return sections
- def _generate_confidence_scores(self, findings: List[Dict], query : str) -> Dict:
- all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
- prompt = f"""
- Relate to the user query: {query}
- Evaluate the confidence scores for these research findings:
+ 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
- {all_content}
+ # 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):
+ toc.append(f" - {subsection['name']} | _{subsection['purpose']}_")
- 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)
+ # Combine TOC and sections
+ report_parts = ['\n'.join(toc), ""]
- scores = {
- "data_quality": 0.0,
- "source_reliability": 0.0,
- "conclusion_strength": 0.0
- }
+ # Add research summary
+ summary_header = "# Research Summary"
+ seen_headers.add(summary_header)
+ report_parts.append(summary_header)
- 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
+ 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)}")
+ 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')
+ filtered_lines = []
- return scores
-
- def _generate_recommendations(self, findings: List[Dict], query : str) -> List[str]:
- all_content = "\n\n".join([f"{f['phase']}: {f['content']}" for f in findings])
- prompt = f"""
- Relate to the user query: {query}
+ 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])
- 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]
+ 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"
+ }
+ }