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.

Working on package

LearningCircuitae6c52001ac4
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000000..11221a8d1d
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,5 @@
+include LICENSE
+include README.md
+include requirements.txt
+recursive-include src/local_deep_research/web/templates *
+recursive-include src/local_deep_research/web/static *
diff --git a/app.py b/app.py
deleted file mode 100644
index 544052940d..0000000000
--- a/app.py
+++ /dev/null
@@ -1,865 +0,0 @@
-import os
-import json
-import time
-import sqlite3
-import threading
-from datetime import datetime
-from flask import Flask, render_template, request, jsonify, send_from_directory, Response, make_response, current_app, Blueprint, redirect, url_for
-from flask_socketio import SocketIO, emit
-from search_system import AdvancedSearchSystem
-from report_generator import IntegratedReportGenerator
-# Move this import up to ensure it's available globally
-from dateutil import parser
-import traceback
-
-# Set flag for tracking OpenAI availability - we'll check it only when needed
-OPENAI_AVAILABLE = False
-
-# Initialize Flask app
-app = Flask(__name__, static_folder=os.path.abspath('static'))
-app.config['SECRET_KEY'] = 'deep-research-secret-key'
-
-# Create a Blueprint for the research application
-research_bp = Blueprint('research', __name__, url_prefix='/research')
-
-# Add improved Socket.IO configuration with better error handling
-socketio = SocketIO(
- app,
- cors_allowed_origins="*",
- async_mode='threading',
- path='/research/socket.io',
- logger=True,
- engineio_logger=True,
- ping_timeout=20,
- ping_interval=5
-)
-
-# Active research processes and socket subscriptions
-active_research = {}
-socket_subscriptions = {}
-
-# Add termination flags dictionary
-termination_flags = {}
-
-# Database setup
-DB_PATH = 'research_history.db'
-
-# Add Content Security Policy headers to allow Socket.IO to function
-def add_security_headers(response):
- # Define a permissive CSP for development that allows Socket.IO to function
- csp = (
- "default-src 'self'; "
- "connect-src 'self' ws: wss: http: https:; "
- "script-src 'self' 'unsafe-inline' 'unsafe-eval' cdnjs.cloudflare.com cdn.jsdelivr.net unpkg.com; "
- "style-src 'self' 'unsafe-inline' cdnjs.cloudflare.com; "
- "font-src 'self' cdnjs.cloudflare.com; "
- "img-src 'self' data:; "
- "worker-src blob:; "
- "frame-src 'self';"
- )
-
- response.headers['Content-Security-Policy'] = csp
- response.headers['X-Content-Security-Policy'] = csp
-
- # Add CORS headers for API requests
- if request.path.startswith('/api/'):
- response.headers['Access-Control-Allow-Origin'] = '*'
- response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, OPTIONS'
- response.headers['Access-Control-Allow-Headers'] = 'Content-Type'
-
- return response
-
-# Add a middleware layer to handle abrupt disconnections
-def handle_websocket_requests():
- if request.path.startswith('/research/socket.io'):
- try:
- if not request.environ.get('werkzeug.socket'):
- return
- except Exception as e:
- print(f"WebSocket preprocessing error: {e}")
- # Return empty response to prevent further processing
- return '', 200
-
-# Initialize the database
-def init_db():
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
-
- # Create the table if it doesn't exist
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS research_history (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- query TEXT NOT NULL,
- mode TEXT NOT NULL,
- status TEXT NOT NULL,
- created_at TEXT NOT NULL,
- completed_at TEXT,
- duration_seconds INTEGER,
- report_path TEXT,
- metadata TEXT,
- progress_log TEXT
- )
- ''')
-
- # Check if the duration_seconds column exists, add it if missing
- cursor.execute('PRAGMA table_info(research_history)')
- columns = [column[1] for column in cursor.fetchall()]
-
- if 'duration_seconds' not in columns:
- print("Adding missing 'duration_seconds' column to research_history table")
- cursor.execute('ALTER TABLE research_history ADD COLUMN duration_seconds INTEGER')
-
- conn.commit()
- conn.close()
-
-# Helper function to calculate duration between created_at and completed_at timestamps
-def calculate_duration(created_at_str):
- """
- Calculate duration in seconds between created_at timestamp and now.
- Handles various timestamp formats and returns None if calculation fails.
- """
- if not created_at_str:
- return None
-
- now = datetime.utcnow()
- duration_seconds = None
-
- try:
- # Proper parsing of ISO format
- if 'T' in created_at_str: # ISO format with T separator
- start_time = datetime.fromisoformat(created_at_str)
- else: # Older format without T
- # Try different formats
- try:
- start_time = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S.%f')
- except ValueError:
- try:
- start_time = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
- except ValueError:
- # Last resort fallback
- start_time = datetime.fromisoformat(created_at_str.replace(' ', 'T'))
-
- # Ensure we're comparing UTC times
- duration_seconds = int((now - start_time).total_seconds())
- except Exception as e:
- print(f"Error calculating duration: {str(e)}")
- # Fallback method if parsing fails
- try:
- start_time_fallback = parser.parse(created_at_str)
- duration_seconds = int((now - start_time_fallback).total_seconds())
- except:
- print(f"Fallback duration calculation also failed for timestamp: {created_at_str}")
-
- return duration_seconds
-
-# Initialize the database on startup
-# @app.before_first_request # This is deprecated in newer Flask versions
-def initialize():
- init_db()
-
-# Call initialize immediately when app is created
-initialize()
-
-# Route for index page - keep this at root level for easy access
-def root_index():
- return redirect(url_for('research.index'))
-
-# Update all routes with the research prefix
-@research_bp.route('/')
-def index():
- return render_template('index.html')
-
-@research_bp.route('/static/<path:path>')
-def serve_static(path):
- try:
- print(f"Serving static file: {path}")
- print(f"Static folder path: {app.static_folder}")
- return send_from_directory(app.static_folder, path)
- except Exception as e:
- print(f"Error serving static file {path}: {str(e)}")
- return f"Error serving file: {str(e)}", 404
-
-@research_bp.route('/api/history', methods=['GET'])
-def get_history():
- """Get the research history"""
- try:
- conn = sqlite3.connect(DB_PATH)
- conn.row_factory = sqlite3.Row
- cursor = conn.cursor()
-
- # Get all history records ordered by latest first
- cursor.execute('SELECT * FROM research_history ORDER BY created_at DESC')
- results = cursor.fetchall()
- conn.close()
-
- # Convert to list of dicts
- history = []
- for result in results:
- item = dict(result)
-
- # Ensure all keys exist with default values
- if 'id' not in item:
- item['id'] = None
- if 'query' not in item:
- item['query'] = 'Untitled Research'
- if 'mode' not in item:
- item['mode'] = 'quick'
- if 'status' not in item:
- item['status'] = 'unknown'
- if 'created_at' not in item:
- item['created_at'] = None
- if 'completed_at' not in item:
- item['completed_at'] = None
- if 'duration_seconds' not in item:
- item['duration_seconds'] = None
- if 'report_path' not in item:
- item['report_path'] = None
- if 'metadata' not in item:
- item['metadata'] = '{}'
- if 'progress_log' not in item:
- item['progress_log'] = '[]'
-
- # Ensure timestamps are in ISO format
- if item['created_at'] and 'T' not in item['created_at']:
- try:
- # Convert to ISO format if it's not already
- dt = parser.parse(item['created_at'])
- item['created_at'] = dt.isoformat()
- except:
- pass
-
- if item['completed_at'] and 'T' not in item['completed_at']:
- try:
- # Convert to ISO format if it's not already
- dt = parser.parse(item['completed_at'])
- item['completed_at'] = dt.isoformat()
- except:
- pass
-
- # Recalculate duration based on timestamps if it's null but both timestamps exist
- if item['duration_seconds'] is None and item['created_at'] and item['completed_at']:
- try:
- start_time = parser.parse(item['created_at'])
- end_time = parser.parse(item['completed_at'])
- item['duration_seconds'] = int((end_time - start_time).total_seconds())
- except Exception as e:
- print(f"Error recalculating duration: {str(e)}")
-
- history.append(item)
-
- # Add CORS headers
- response = make_response(jsonify(history))
- response.headers.add('Access-Control-Allow-Origin', '*')
- response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
- response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
- return response
- except Exception as e:
- print(f"Error getting history: {str(e)}")
- print(traceback.format_exc())
- # Return empty array with CORS headers
- response = make_response(jsonify([]))
- response.headers.add('Access-Control-Allow-Origin', '*')
- response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
- response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
- return response
-
-@research_bp.route('/api/start_research', methods=['POST'])
-def start_research():
- data = request.json
- query = data.get('query')
- mode = data.get('mode', 'quick')
-
- if not query:
- return jsonify({'status': 'error', 'message': 'Query is required'}), 400
-
- # Check if there's any active research
- if active_research:
- return jsonify({
- 'status': 'error',
- 'message': 'Another research is already in progress. Please wait for it to complete.'
- }), 409
-
- # Create a record in the database with explicit UTC timestamp
- created_at = datetime.utcnow().isoformat()
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
- cursor.execute(
- 'INSERT INTO research_history (query, mode, status, created_at, progress_log) VALUES (?, ?, ?, ?, ?)',
- (query, mode, 'in_progress', created_at, json.dumps([{"time": created_at, "message": "Research started", "progress": 0}]))
- )
- research_id = cursor.lastrowid
- conn.commit()
- conn.close()
-
- # Start research process in a background thread
- thread = threading.Thread(
- target=run_research_process,
- args=(research_id, query, mode)
- )
- thread.daemon = True
- thread.start()
-
- active_research[research_id] = {
- 'thread': thread,
- 'progress': 0,
- 'status': 'in_progress',
- 'log': [{"time": created_at, "message": "Research started", "progress": 0}]
- }
-
- return jsonify({
- 'status': 'success',
- 'research_id': research_id
- })
-
-@research_bp.route('/api/research/<int:research_id>')
-def get_research_status(research_id):
- conn = sqlite3.connect(DB_PATH)
- conn.row_factory = sqlite3.Row
- cursor = conn.cursor()
- cursor.execute('SELECT * FROM research_history WHERE id = ?', (research_id,))
- result = dict(cursor.fetchone() or {})
- conn.close()
-
- if not result:
- return jsonify({'status': 'error', 'message': 'Research not found'}), 404
-
- # Add progress information
- if research_id in active_research:
- result['progress'] = active_research[research_id]['progress']
- result['log'] = active_research[research_id]['log']
- elif result.get('status') == 'completed':
- result['progress'] = 100
- try:
- result['log'] = json.loads(result.get('progress_log', '[]'))
- except:
- result['log'] = []
- else:
- result['progress'] = 0
- try:
- result['log'] = json.loads(result.get('progress_log', '[]'))
- except:
- result['log'] = []
-
- return jsonify(result)
-
-@research_bp.route('/api/research/<int:research_id>/details')
-def get_research_details(research_id):
- """Get detailed progress log for a specific research"""
- conn = sqlite3.connect(DB_PATH)
- conn.row_factory = sqlite3.Row
- cursor = conn.cursor()
- cursor.execute('SELECT * FROM research_history WHERE id = ?', (research_id,))
- result = dict(cursor.fetchone() or {})
- conn.close()
-
- if not result:
- return jsonify({'status': 'error', 'message': 'Research not found'}), 404
-
- try:
- # Get the progress log
- progress_log = json.loads(result.get('progress_log', '[]'))
- except:
- progress_log = []
-
- # If this is an active research, get the latest log
- if research_id in active_research:
- progress_log = active_research[research_id]['log']
-
- return jsonify({
- 'status': 'success',
- 'research_id': research_id,
- 'query': result.get('query'),
- 'mode': result.get('mode'),
- 'status': result.get('status'),
- 'progress': active_research.get(research_id, {}).get('progress', 100 if result.get('status') == 'completed' else 0),
- 'created_at': result.get('created_at'),
- 'completed_at': result.get('completed_at'),
- 'log': progress_log
- })
-
-@research_bp.route('/api/report/<int:research_id>')
-def get_report(research_id):
- conn = sqlite3.connect(DB_PATH)
- conn.row_factory = sqlite3.Row
- cursor = conn.cursor()
- cursor.execute('SELECT * FROM research_history WHERE id = ?', (research_id,))
- result = dict(cursor.fetchone() or {})
- conn.close()
-
- if not result or not result.get('report_path'):
- return jsonify({'status': 'error', 'message': 'Report not found'}), 404
-
- try:
- with open(result['report_path'], 'r', encoding='utf-8') as f:
- content = f.read()
- return jsonify({
- 'status': 'success',
- 'content': content,
- 'metadata': json.loads(result.get('metadata', '{}'))
- })
- except Exception as e:
- return jsonify({'status': 'error', 'message': str(e)}), 500
-
-@research_bp.route('/research/details/<int:research_id>')
-def research_details_page(research_id):
- """Render the research details page"""
- return render_template('index.html')
-
-def handle_connect():
- print(f"Client connected: {request.sid}")
-
[email protected]('disconnect')
-def handle_disconnect():
- try:
- print(f"Client disconnected: {request.sid}")
- # Clean up subscriptions for this client
- for research_id, subscribers in list(socket_subscriptions.items()):
- if request.sid in subscribers:
- subscribers.remove(request.sid)
- if not subscribers:
- socket_subscriptions.pop(research_id, None)
- except Exception as e:
- print(f"Error handling disconnect: {e}")
-
[email protected]('subscribe_to_research')
-def handle_subscribe(data):
- research_id = data.get('research_id')
- if research_id:
- if research_id not in socket_subscriptions:
- socket_subscriptions[research_id] = set()
- socket_subscriptions[research_id].add(request.sid)
- print(f"Client {request.sid} subscribed to research {research_id}")
-
- # Send current status immediately if available
- if research_id in active_research:
- progress = active_research[research_id]['progress']
- latest_log = active_research[research_id]['log'][-1] if active_research[research_id]['log'] else None
-
- if latest_log:
- emit(f'research_progress_{research_id}', {
- 'progress': progress,
- 'message': latest_log.get('message', 'Processing...'),
- 'status': 'in_progress',
- 'log_entry': latest_log
- })
-
-def handle_socket_error(e):
- print(f"Socket.IO error: {str(e)}")
- # Don't propagate exceptions to avoid crashing the server
- return False
-
[email protected]_error_default
-def handle_default_error(e):
- print(f"Unhandled Socket.IO error: {str(e)}")
- # Don't propagate exceptions to avoid crashing the server
- return False
-
-def run_research_process(research_id, query, mode):
- try:
- system = AdvancedSearchSystem()
-
- # Set up progress callback
- def progress_callback(message, progress_percent, metadata):
- timestamp = datetime.utcnow().isoformat()
- log_entry = {
- "time": timestamp,
- "message": message,
- "progress": progress_percent,
- "metadata": metadata
- }
-
- # Check if termination was requested
- if research_id in termination_flags and termination_flags[research_id]:
- # Clean up and exit
- raise Exception("Research was terminated by user")
-
- # Update active research record
- if research_id in active_research:
- active_research[research_id]['log'].append(log_entry)
- if progress_percent is not None:
- active_research[research_id]['progress'] = progress_percent
-
- # Save to database (but not too frequently)
- if progress_percent is None or progress_percent % 10 == 0 or metadata.get('phase') in ['complete', 'iteration_complete']:
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
- cursor.execute(
- 'SELECT progress_log FROM research_history WHERE id = ?',
- (research_id,)
- )
- result = cursor.fetchone()
- if result:
- try:
- current_log = json.loads(result[0])
- except:
- current_log = []
- current_log.append(log_entry)
- cursor.execute(
- 'UPDATE research_history SET progress_log = ? WHERE id = ?',
- (json.dumps(current_log), research_id)
- )
- conn.commit()
- conn.close()
-
- # Emit socket event with try/except block to handle connection issues
- try:
- event_data = {
- 'progress': progress_percent,
- 'message': message,
- 'status': 'in_progress',
- 'log_entry': log_entry
- }
-
- # Emit to the specific research channel
- socketio.emit(f'research_progress_{research_id}', event_data)
-
- # Also emit to specific subscribers if available
- if research_id in socket_subscriptions and socket_subscriptions[research_id]:
- for sid in socket_subscriptions[research_id]:
- try:
- socketio.emit(
- f'research_progress_{research_id}',
- event_data,
- room=sid
- )
- except Exception as sub_err:
- print(f"Error emitting to subscriber {sid}: {str(sub_err)}")
-
- except Exception as socket_error:
- # Log socket error but continue with the research process
- print(f"Socket emit error (non-critical): {str(socket_error)}")
-
- # Set the progress callback in the system
- system.set_progress_callback(progress_callback)
-
- # Run the search
- progress_callback("Starting research process", 5, {"phase": "init"})
- results = system.analyze_topic(query)
- progress_callback("Search complete, generating output", 80, {"phase": "output_generation"})
-
- # Generate output based on mode
- if mode == 'quick':
- # Quick Summary
- if results.get('findings'):
- #initial_analysis = [finding['content'] for finding in results['findings']]
- summary = ""
- summary = summary + results['formatted_findings']
- # Save as markdown file
- output_dir = "research_outputs"
- if not os.path.exists(output_dir):
- os.makedirs(output_dir)
-
- safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[:50]
- safe_query = safe_query.replace(" ", "_").lower()
- report_path = os.path.join(output_dir, f"quick_summary_{safe_query}.md")
-
- with open(report_path, "w", encoding="utf-8") as f:
- f.write("# Quick Research Summary\n\n")
- f.write(f"Query: {query}\n\n")
- f.write(summary)
- f.write("\n\n## Research Metrics\n")
- f.write(f"- Search Iterations: {results['iterations']}\n")
- f.write(f"- Generated at: {datetime.utcnow().isoformat()}\n")
-
- # Update database
- metadata = {
- 'iterations': results['iterations'],
- 'generated_at': datetime.utcnow().isoformat()
- }
-
- # Calculate duration in seconds - using UTC consistently
- now = datetime.utcnow()
- completed_at = now.isoformat()
-
- # Get the start time from the database
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
- cursor.execute('SELECT created_at FROM research_history WHERE id = ?', (research_id,))
- result = cursor.fetchone()
-
- # Use the helper function for consistent duration calculation
- duration_seconds = calculate_duration(result[0])
-
- # Update the record
- cursor.execute(
- 'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, report_path = ?, metadata = ? WHERE id = ?',
- ('completed', completed_at, duration_seconds, report_path, json.dumps(metadata), research_id)
- )
- conn.commit()
- conn.close()
-
- progress_callback("Research completed successfully", 100, {"phase": "complete", "report_path": report_path})
- else:
- # Full Report
- progress_callback("Generating detailed report...", 85, {"phase": "report_generation"})
- report_generator = IntegratedReportGenerator()
- final_report = report_generator.generate_report(results, query)
- progress_callback("Report generation complete", 95, {"phase": "report_complete"})
-
- # Save as markdown file
- output_dir = "research_outputs"
- if not os.path.exists(output_dir):
- os.makedirs(output_dir)
-
- safe_query = "".join(x for x in query if x.isalnum() or x in [" ", "-", "_"])[:50]
- safe_query = safe_query.replace(" ", "_").lower()
- report_path = os.path.join(output_dir, f"detailed_report_{safe_query}.md")
-
- with open(report_path, "w", encoding="utf-8") as f:
- f.write(final_report['content'])
-
- # Update database
- metadata = final_report['metadata']
- metadata['iterations'] = results['iterations']
-
- # Calculate duration in seconds - using UTC consistently
- now = datetime.utcnow()
- completed_at = now.isoformat()
-
- # Get the start time from the database
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
- cursor.execute('SELECT created_at FROM research_history WHERE id = ?', (research_id,))
- result = cursor.fetchone()
-
- # Use the helper function for consistent duration calculation
- duration_seconds = calculate_duration(result[0])
-
- cursor.execute(
- 'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, report_path = ?, metadata = ? WHERE id = ?',
- ('completed', completed_at, duration_seconds, report_path, json.dumps(metadata), research_id)
- )
- conn.commit()
- conn.close()
-
- progress_callback("Research completed successfully", 100, {"phase": "complete", "report_path": report_path})
-
- # Clean up
- if research_id in active_research:
- del active_research[research_id]
-
- except Exception as e:
- # Handle error
- error_message = f"Research failed: {str(e)}"
- print(f"Research error: {error_message}")
- try:
- progress_callback(error_message, None, {"phase": "error", "error": str(e)})
-
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
-
- # If termination was requested, mark as suspended instead of failed
- status = 'suspended' if (research_id in termination_flags and termination_flags[research_id]) else 'failed'
- message = "Research was terminated by user" if status == 'suspended' else str(e)
-
- # Calculate duration up to termination point - using UTC consistently
- now = datetime.utcnow()
- completed_at = now.isoformat()
-
- # Get the start time from the database
- duration_seconds = None
- cursor.execute('SELECT created_at FROM research_history WHERE id = ?', (research_id,))
- result = cursor.fetchone()
-
- # Use the helper function for consistent duration calculation
- if result and result[0]:
- duration_seconds = calculate_duration(result[0])
-
- cursor.execute(
- 'UPDATE research_history SET status = ?, completed_at = ?, duration_seconds = ?, metadata = ? WHERE id = ?',
- (status, completed_at, duration_seconds, json.dumps({'error': message}), research_id)
- )
- conn.commit()
- conn.close()
-
- try:
- socketio.emit(f'research_progress_{research_id}', {
- 'status': status,
- 'error': message
- })
-
- # Also notify specific subscribers
- if research_id in socket_subscriptions and socket_subscriptions[research_id]:
- for sid in socket_subscriptions[research_id]:
- try:
- socketio.emit(
- f'research_progress_{research_id}',
- {'status': status, 'error': message},
- room=sid
- )
- except Exception as sub_err:
- print(f"Error emitting to subscriber {sid}: {str(sub_err)}")
-
- except Exception as socket_error:
- print(f"Failed to emit error via socket: {str(socket_error)}")
- except Exception as inner_e:
- print(f"Error in error handler: {str(inner_e)}")
-
- # Clean up resources
- if research_id in active_research:
- del active_research[research_id]
- if research_id in termination_flags:
- del termination_flags[research_id]
-
-@research_bp.route('/api/research/<int:research_id>/terminate', methods=['POST'])
-def terminate_research(research_id):
- """Terminate an in-progress research process"""
-
- # Check if the research exists and is in progress
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
- cursor.execute('SELECT status FROM research_history WHERE id = ?', (research_id,))
- result = cursor.fetchone()
-
- if not result:
- conn.close()
- return jsonify({'status': 'error', 'message': 'Research not found'}), 404
-
- status = result[0]
-
- # If it's not in progress, return an error
- if status != 'in_progress':
- conn.close()
- return jsonify({'status': 'error', 'message': 'Research is not in progress'}), 400
-
- # Check if it's in the active_research dict
- if research_id not in active_research:
- # Update the status in the database
- cursor.execute('UPDATE research_history SET status = ? WHERE id = ?', ('suspended', research_id))
- conn.commit()
- conn.close()
- return jsonify({'status': 'success', 'message': 'Research terminated'})
-
- # Set the termination flag
- termination_flags[research_id] = True
-
- # Log the termination request - using UTC timestamp
- timestamp = datetime.utcnow().isoformat()
- log_entry = {
- "time": timestamp,
- "message": "Research termination requested by user",
- "progress": active_research[research_id]['progress'],
- "metadata": {"phase": "termination"}
- }
-
- active_research[research_id]['log'].append(log_entry)
-
- # Update the log in the database
- cursor.execute('SELECT progress_log FROM research_history WHERE id = ?', (research_id,))
- log_result = cursor.fetchone()
- if log_result:
- try:
- current_log = json.loads(log_result[0])
- except:
- current_log = []
- current_log.append(log_entry)
- cursor.execute(
- 'UPDATE research_history SET progress_log = ? WHERE id = ?',
- (json.dumps(current_log), research_id)
- )
-
- conn.commit()
- conn.close()
-
- # Emit a socket event for the termination request
- try:
- event_data = {
- 'status': 'terminating',
- 'message': 'Research termination requested by user'
- }
-
- socketio.emit(f'research_progress_{research_id}', event_data)
-
- if research_id in socket_subscriptions and socket_subscriptions[research_id]:
- for sid in socket_subscriptions[research_id]:
- try:
- socketio.emit(
- f'research_progress_{research_id}',
- event_data,
- room=sid
- )
- except Exception as err:
- print(f"Error emitting to subscriber {sid}: {str(err)}")
-
- except Exception as socket_error:
- print(f"Socket emit error (non-critical): {str(socket_error)}")
-
- return jsonify({'status': 'success', 'message': 'Research termination requested'})
-
-@research_bp.route('/api/research/<int:research_id>/delete', methods=['DELETE'])
-def delete_research(research_id):
- """Delete a research record"""
- conn = sqlite3.connect(DB_PATH)
- cursor = conn.cursor()
-
- # First check if the research exists and is not in progress
- cursor.execute('SELECT status, report_path FROM research_history WHERE id = ?', (research_id,))
- result = cursor.fetchone()
-
- if not result:
- conn.close()
- return jsonify({'status': 'error', 'message': 'Research not found'}), 404
-
- status, report_path = result
-
- # Don't allow deleting research in progress
- if status == 'in_progress' and research_id in active_research:
- conn.close()
- return jsonify({
- 'status': 'error',
- 'message': 'Cannot delete research that is in progress'
- }), 400
-
- # Delete report file if it exists
- if report_path and os.path.exists(report_path):
- try:
- os.remove(report_path)
- except Exception as e:
- print(f"Error removing report file: {str(e)}")
-
- # Delete the database record
- cursor.execute('DELETE FROM research_history WHERE id = ?', (research_id,))
- conn.commit()
- conn.close()
-
- return jsonify({'status': 'success'})
-
-# Register the blueprint
-app.register_blueprint(research_bp)
-
-# Also add the static route at the app level for compatibility
[email protected]('/static/<path:path>')
-def app_serve_static(path):
- return send_from_directory(app.static_folder, path)
-
-# Add favicon route to prevent 404 errors
[email protected]('/favicon.ico')
-def favicon():
- return send_from_directory(app.static_folder, 'favicon.ico', mimetype='image/x-icon')
-
-if __name__ == '__main__':
- # Check for OpenAI availability but don't import it unless necessary
- try:
- import os
- api_key = os.environ.get("OPENAI_API_KEY")
- if api_key:
- try:
- # Only try to import if we have an API key
- import openai
- openai.api_key = api_key
- OPENAI_AVAILABLE = True
- print("OpenAI integration is available")
- except ImportError:
- print("OpenAI package not installed, integration disabled")
- else:
- print("OPENAI_API_KEY not found in environment variables, OpenAI integration disabled")
- except Exception as e:
- print(f"Error checking OpenAI availability: {e}")
-
- # Run with threading (more stable than eventlet with complex dependencies)
- socketio.run(app, debug=True, host='0.0.0.0', port=5000, allow_unsafe_werkzeug=False)
\ No newline at end of file
diff --git a/citation_handler.py b/citation_handler.py
deleted file mode 100644
index 70ed8b03b6..0000000000
--- a/citation_handler.py
+++ /dev/null
@@ -1,113 +0,0 @@
-# citation_handler.py
-
-from langchain_core.documents import Document
-from typing import Dict, List, Union, Any
-import re
-from utilties.search_utilities import remove_think_tags
-import config
-
-class CitationHandler:
- def __init__(self, llm):
- self.llm = llm
-
- def _create_documents(
- self, search_results: Union[str, List[Dict]], nr_of_links: int = 0
- ) -> List[Document]:
- """Convert search results to LangChain documents format and add index to original search results."""
- documents = []
- if isinstance(search_results, str):
- return documents
-
- for 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(
- page_content=content,
- metadata={
- "source": result.get("link", f"source_{i+1}"),
- "title": result.get("title", f"Source {i+1}"),
- "index": i + nr_of_links + 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)
- print(formatted_sources)
- 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. Never make up sources. Example format: "According to the research [1], ..."
-"""
-
- response = self.llm.invoke(prompt)
-
- return {"content": remove_think_tags(response.content), "documents": documents}
-
- def analyze_followup(
- self,
- question: 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, nr_of_links=nr_of_links)
- formatted_sources = self._format_sources(documents)
- print(formatted_sources)
- # Add fact-checking step
- fact_check_prompt = f"""Analyze these sources for factual consistency:
- 1. Cross-reference major claims between sources
- 2. Identify and flag any contradictions
- 3. Verify basic facts (dates, company names, ownership)
- 4. Note when sources disagree
-
- Previous Knowledge:
- {previous_knowledge}
-
- New Sources:
- {formatted_sources}
-
- Return any inconsistencies or conflicts found."""
- if config.ENABLE_FACT_CHECKING:
- fact_check_response = remove_think_tags(self.llm.invoke(fact_check_prompt).content)
- else:
- fact_check_response = ""
-
- 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. Reflect information from sources critically.
-
- Previous Knowledge:
- {previous_knowledge}
-
- Question: {question}
-
- New Sources:
- {formatted_sources}
- Reflect information from sources critically based on: {fact_check_response}. Never invent 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}
\ No newline at end of file
diff --git a/config.py b/config.py
deleted file mode 100644
index e54f83378a..0000000000
--- a/config.py
+++ /dev/null
@@ -1,262 +0,0 @@
-"""
-Local Deep Research Configuration Guide
-
-This configuration file controls the behavior of the research system.
-
-MAIN SETTINGS:
-- search_tool (str): Choose which search engine to use
- - "auto": Intelligent selection based on query content (recommended)
- - "local_all": Search only local document collections
- - "wikipedia": General knowledge and facts
- - "arxiv": Scientific papers and research
- - "duckduckgo": General web search (no API key needed)
- - "serp": Google search via SerpAPI (requires API key)
- - "google_pse": Google Programmable Search Engine for custom search experiences (requires API key)
- - "guardian": News articles (requires API key)
- - Any collection name from your local_collections.py
-
-- DEFAULT_MODEL (str): LLM to use for analysis
- - "mistral": Default local model via Ollama
- - "deepseek-r1:14b": Alternative larger model
- - "claude-3-5-sonnet-latest": Claude model (requires API key)
- - "gpt-4o": OpenAI model (requires API key)
- - "mpt-7b": MPT model via VLLM
-
-API KEYS:
-For search engines requiring API keys, set these in your .env file:
-- SERP_API_KEY: For Google search via SerpAPI
-- GUARDIAN_API_KEY: For The Guardian news search
-- GOOGLE_PSE_API_KEY: For Google Programmable Search Engine
-- GOOGLE_PSE_ENGINE_ID: Search Engine ID from Google PSE Control Panel
-
-RESEARCH SETTINGS:
-- SEARCH_ITERATIONS (int): Number of research cycles
-- QUESTIONS_PER_ITERATION (int): Questions per cycle
-- SEARCHES_PER_SECTION (int): Searches per report section
-- MAX_SEARCH_RESULTS (int): Results per search query
-- MAX_FILTERED_RESULTS (int): Results after relevance filtering
-
-For full documentation, see the README.md
-"""
-
-from langchain_anthropic import ChatAnthropic
-from langchain_openai import ChatOpenAI
-from langchain_ollama import ChatOllama
-from langchain_community.llms import VLLM # Added VLLM import
-from dotenv import load_dotenv
-from utilties.enums import KnowledgeAccumulationApproach
-
-import os
-import re
-from typing import Dict, List, Any, Optional, Callable
-
-# Load environment variables
-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.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
-OPENROUTER_BASE_URL= "https://openrouter.ai/api/v1"
-
-DEFAULT_MODEL = "mistral" # try to use the largest model that fits into your GPU memory
-DEFAULT_TEMPERATURE = 0.7
-MAX_TOKENS = 30000
-
-# VLLM Configuration
-VLLM_MAX_NEW_TOKENS = 128
-VLLM_TOP_K = 10
-VLLM_TOP_P = 0.95
-VLLM_TEMPERATURE = 0.8
-
-# Search System Settings
-SEARCH_ITERATIONS = 2
-QUESTIONS_PER_ITERATION = 2
-
-# Report settings
-SEARCHES_PER_SECTION = 2
-#CONTEXT_CUT_OFF = 10000
-
-# citation handler
-ENABLE_FACT_CHECKING = False # comes with pros and cons. Maybe works better with larger LLMs?
-
-# URL Quality Check (applies to both DDG and SerpAPI)
-QUALITY_CHECK_DDG_URLS = True # Keep True for better quality results.
-
-SEARCH_SNIPPETS_ONLY = False
-SKIP_RELEVANCE_FILTER = False
-
-# Search Configuration (applies to both DDG and SerpAPI)
-MAX_SEARCH_RESULTS = 50
-MAX_FILTERED_RESULTS = 5
-SEARCH_REGION = "us"
-TIME_PERIOD = "y"
-SAFE_SEARCH = True
-SEARCH_LANGUAGE = "English"
-
-# Output Configuration
-OUTPUT_DIR = "research_outputs"
-
-# Make OpenAI integration optional with lazy loading
-def is_openai_available():
- """Check if OpenAI is available without importing it at module level"""
- try:
- # Only import when checking
- import os
- api_key = os.environ.get("OPENAI_API_KEY")
- if not api_key:
- return False
-
- # Only try to import if we have an API key
- try:
- from langchain_openai import ChatOpenAI
- return True
- except ImportError:
- return False
- except:
- return False
-
-# Models map
-MODELS = {
- # Local models
- "ollama-llama3": "Local Llama3 model (requires Ollama)",
- "ollama-mixtral": "Local Mixtral model (requires Ollama)",
- "ollama-mistral": "Local Mistral model (requires Ollama)",
-
- # API-based models
- "gpt-4o": "OpenAI model (requires API key)",
- "gpt-3.5-turbo": "OpenAI model (requires API key)",
-}
-
-# Available model providers
-MODEL_PROVIDERS = ["local", "openai"]
-
-def get_model(model_name: str, **kwargs):
- """Get model instance based on the model name"""
- # Common parameters for all models
- common_params = {
- "temperature": kwargs.get("temperature", 0.0),
- "verbose": kwargs.get("verbose", False),
- }
-
- # Ollama models (local)
- if model_name.startswith("ollama-"):
- try:
- from langchain_community.llms import Ollama
- base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
- return Ollama(model=model_name.replace("ollama-", ""), base_url=base_url, **common_params)
- except ImportError:
- raise ValueError("Langchain Ollama integration not available. Please install it with: pip install langchain-community")
-
- # OpenAI models
- elif model_name in ["gpt-4o", "gpt-3.5-turbo"]:
- if not is_openai_available():
- raise ValueError("OpenAI integration not available. Please install langchain-openai and set OPENAI_API_KEY environment variable.")
-
- 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)
-
- else:
- raise ValueError(f"Unsupported model: {model_name}")
-
-def get_available_models() -> Dict[str, str]:
- """Return available models based on installed packages and environment variables"""
- available_models = {}
-
- # Check Ollama models
- try:
- import langchain_community
- # Check if Ollama is running
- ollama_running = False
- try:
- import requests
- base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
- requests.get(f"{base_url}/api/tags", timeout=2)
- ollama_running = True
- except:
- pass
-
- if ollama_running:
- for model in [k for k in MODELS.keys() if k.startswith("ollama-")]:
- available_models[model] = MODELS[model]
- except ImportError:
- pass
-
- # Check OpenAI models
- if is_openai_available():
- for model in ["gpt-4o", "gpt-3.5-turbo"]:
- available_models[model] = MODELS[model]
-
- return available_models
-
-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")
- 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
- )
- elif OPENAIENDPOINT:
- api_key = os.getenv("OPENAI_ENDPOINT_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,openai_api_base=OPENROUTER_BASE_URL, **common_params)
-
- elif "gpt" in model_name:
- if not is_openai_available():
- raise ValueError("OpenAI integration not available or API key not set. Please install langchain-openai and set 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)
-
- elif model_name == "mpt-7b":
- # VLLM configuration for the MPT model
- return VLLM(
- model="mosaicml/mpt-7b",
- trust_remote_code=True, # mandatory for hf models
- max_new_tokens=VLLM_MAX_NEW_TOKENS,
- top_k=VLLM_TOP_K,
- top_p=VLLM_TOP_P,
- temperature=VLLM_TEMPERATURE,
- )
-
- else:
- return ChatOllama(model=model_name, base_url="http://localhost:11434", **common_params)
-
-
-def get_search():
- """Get search tool instance based on config settings"""
- # Import here to avoid circular import
- from web_search_engines.search_engine_factory import get_search as factory_get_search
-
- print(f"Creating search engine with tool: {search_tool}")
- engine = factory_get_search(
- search_tool=search_tool,
- llm_instance=get_llm(),
- max_results=MAX_SEARCH_RESULTS,
- region=SEARCH_REGION,
- time_period=TIME_PERIOD,
- safe_search=SAFE_SEARCH,
- search_snippets_only=SEARCH_SNIPPETS_ONLY,
- search_language=SEARCH_LANGUAGE,
- max_filtered_results=MAX_FILTERED_RESULTS
- )
-
- if engine is None:
- print(f"Failed to create search engine with tool: {search_tool}")
-
- return engine
diff --git a/local_collections.py b/local_collections.py
deleted file mode 100644
index e8ed7b9107..0000000000
--- a/local_collections.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# local_collections.py
-"""
-Configuration file for local document collections.
-Each collection functions as an independent search engine.
-"""
-
-import os
-from typing import Dict, Any
-
-# Registry of local document collections
-# Each collection appears as a separate search engine in the main configuration
-LOCAL_COLLECTIONS = {
- # Project Documents Collection
- "project_docs": {
- "name": "Project Documents",
- "description": "Project documentation and specifications",
- "paths": [os.path.abspath("./local_search_files/project_documents")],
- "enabled": True,
- "embedding_model": "all-MiniLM-L6-v2",
- "embedding_device": "cpu",
- "embedding_model_type": "sentence_transformers",
- "max_results": 20,
- "max_filtered_results": 5,
- "chunk_size": 1000,
- "chunk_overlap": 200,
- "cache_dir": ".cache/local_search/project_docs"
- },
-
- # Research Papers Collection
- "research_papers": {
- "name": "Research Papers",
- "description": "Academic research papers and articles",
- "paths": [os.path.abspath("local_search_files/research_papers")],
- "enabled": True,
- "embedding_model": "all-MiniLM-L6-v2",
- "embedding_device": "cpu",
- "embedding_model_type": "sentence_transformers",
- "max_results": 20,
- "max_filtered_results": 5,
- "chunk_size": 800, # Smaller chunks for academic content
- "chunk_overlap": 150,
- "cache_dir": ".cache/local_search/research_papers"
- },
-
- # Personal Notes Collection
- "personal_notes": {
- "name": "Personal Notes",
- "description": "Personal notes and documents",
- "paths": [os.path.abspath("./local_search_files/personal_notes")],
- "enabled": True,
- "embedding_model": "all-MiniLM-L6-v2",
- "embedding_device": "cpu",
- "embedding_model_type": "sentence_transformers",
- "max_results": 30,
- "max_filtered_results": 10,
- "chunk_size": 500, # Smaller chunks for notes
- "chunk_overlap": 100,
- "cache_dir": ".cache/local_search/personal_notes"
- }
-}
-
-# Configuration for local search integration
-LOCAL_SEARCH_CONFIG = {
- # General embedding options
- "DEFAULT_EMBEDDING_MODEL": "all-MiniLM-L6-v2",
- "DEFAULT_EMBEDDING_DEVICE": "cpu", # "cpu" or "cuda" for GPU acceleration
- "DEFAULT_EMBEDDING_MODEL_TYPE": "sentence_transformers", # or "ollama"
-
- # Ollama settings (only used if model type is "ollama")
- # Note: You must run 'ollama pull nomic-embed-text' first if using Ollama for embeddings
- "OLLAMA_BASE_URL": "http://localhost:11434",
- "OLLAMA_EMBEDDING_MODEL": "nomic-embed-text",
-
- # Default indexing options
- "FORCE_REINDEX": True, # Force reindexing on startup
- "CACHE_DIR": ".cache/local_search", # Base directory for cache
-}
-
-def register_local_collections(search_engines_dict: Dict[str, Any]) -> None:
- """
- Register all enabled local collections as search engines.
-
- Args:
- search_engines_dict: The main search engines dictionary to update
- """
- for collection_id, collection in LOCAL_COLLECTIONS.items():
- print(collection_id, collection)
- if collection.get("enabled", True):
- # Skip if already defined (don't override)
- if collection_id in search_engines_dict:
- continue
-
- # Validate paths exist
- paths = collection.get("paths", [])
- valid_paths = []
- for path in paths:
- if os.path.exists(path) and os.path.isdir(path):
- valid_paths.append(path)
- else:
- print(f"Warning: Collection '{collection_id}' contains non-existent folder: {path}")
-
- # Log warning if no valid paths
- if not valid_paths and paths:
- print(f"Warning: Collection '{collection_id}' has no valid folders. It will be registered but won't return results.")
-
- # Create a search engine entry for this collection
- search_engines_dict[collection_id] = {
- "module_path": "web_search_engines.engines.search_engine_local",
- "class_name": "LocalSearchEngine",
- "requires_api_key": False,
- "reliability": 0.9, # High reliability for local documents
- "strengths": ["personal documents", "offline access",
- collection.get("description", "local documents")],
- "weaknesses": ["requires indexing", "limited to specific folders"],
- "default_params": {
- "folder_paths": collection.get("paths", []),
- "embedding_model": collection.get(
- "embedding_model",
- LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_MODEL"]
- ),
- "embedding_device": collection.get(
- "embedding_device",
- LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_DEVICE"]
- ),
- "embedding_model_type": collection.get(
- "embedding_model_type",
- LOCAL_SEARCH_CONFIG["DEFAULT_EMBEDDING_MODEL_TYPE"]
- ),
- "chunk_size": collection.get("chunk_size", 1000),
- "chunk_overlap": collection.get("chunk_overlap", 200),
- "cache_dir": collection.get(
- "cache_dir",
- f"{LOCAL_SEARCH_CONFIG['CACHE_DIR']}/{collection_id}"
- ),
- "max_results": collection.get("max_results", 20),
- "max_filtered_results": collection.get("max_filtered_results", 5),
- "collection_name": collection.get("name", collection_id),
- "collection_description": collection.get("description", "")
- },
- "requires_llm": True
- }
\ No newline at end of file
diff --git a/main.py b/main.py
deleted file mode 100644
index 4c2380d576..0000000000
--- a/main.py
+++ /dev/null
@@ -1,96 +0,0 @@
-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"])
-
-
-
- # Save to file in markdown format
- with open("report.md", "w", encoding="utf-8") as markdown_file:
- # Write 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"- 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)"
- )
- 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)"
- )
- choice = input("Enter number (1 or 2): ").strip()
-
- query = input("\nEnter your research query: ").strip()
-
- 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"
- )
-
- 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 = [
- finding["content"] for finding in results["findings"]
- ]
- print(initial_analysis)
-
- else:
- # Full Report
- final_report = report_generator.generate_report(
- results, 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/pyproject.toml b/pyproject.toml
new file mode 100644
index 0000000000..3356a516f6
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,50 @@
+[build-system]
+requires = ["setuptools>=42", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "local-deep-research"
+version = "0.1.0"
+description = "AI-powered research assistant with deep, iterative analysis using LLMs and web searches"
+readme = "README.md"
+requires-python = ">=3.8"
+license = {file = "LICENSE"}
+authors = [
+ {name = "Your Name", email = "[email protected]"}
+]
+classifiers = [
+ "Programming Language :: Python :: 3",
+ "License :: OSI Approved :: MIT License",
+ "Operating System :: OS Independent",
+]
+dependencies = [
+ "langchain>=0.3.18",
+ "langchain-community>=0.3.17",
+ "langchain-core>=0.3.34",
+ "langchain-ollama>=0.2.3",
+ "langchain-openai>=0.3.5",
+ "langchain_anthropic>=0.3.7",
+ "duckduckgo_search>=7.3.2",
+ "python-dateutil>=2.9.0",
+ "typing_extensions>=4.12.2",
+ "justext",
+ "playwright",
+ "beautifulsoup4",
+ "flask>=2.0.1",
+ "flask-cors>=3.0.10",
+ "flask-socketio>=5.1.1",
+ "sqlalchemy>=1.4.23",
+ "wikipedia",
+ "arxiv>=1.4.3",
+ "PyPDF2>=2.0.0",
+ "sentence-transformers",
+ "faiss-cpu",
+]
+
+[project.urls]
+"Homepage" = "https://github.com/yourusername/local-deep-research"
+"Bug Tracker" = "https://github.com/yourusername/local-deep-research/issues"
+
+[project.scripts]
+ldr = "local_deep_research.main:main"
+ldr-web = "local_deep_research.web.app:main"
diff --git a/report_generator.py b/report_generator.py
deleted file mode 100644
index a59f97d652..0000000000
--- a/report_generator.py
+++ /dev/null
@@ -1,206 +0,0 @@
-from typing import Dict, List, Optional
-from config import get_llm
-import re
-from datetime import datetime
-from search_system import AdvancedSearchSystem
-import config
-import utilties
-import utilties.search_utilities
-
-class IntegratedReportGenerator:
- 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
- )
-
- def _remove_think_tags(self, text: str) -> str:
- print(text)
- return re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
-
- def generate_report(self, initial_findings: Dict, query: str) -> Dict:
- """Generate a complete research report with section-specific research."""
-
- # Step 1: Determine structure
- structure = self._determine_report_structure(initial_findings, query)
-
- # Step 2: Research and generate content for each section in one step
- sections = self._research_and_generate_sections(initial_findings, structure, query)
-
- # Step 3: Format final report
- report = self._format_final_report(sections, structure, query)
-
- return report
-
- def _determine_report_structure(
- self, findings: Dict, query: str
- ) -> List[Dict]:
-
- """Analyze content and determine optimal report structure."""
- combined_content = findings["current_knowledge"]
- prompt = f"""
- Analyze this research content about: {query}
-
- Content Summary:
- {combined_content[:1000]}... [truncated]
-
- 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
-
- 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"]:
- 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()}
- )
-
- return structure
-
- def _research_and_generate_sections(
- self,
- initial_findings: Dict,
- structure: List[Dict],
- query: str,
- ) -> Dict[str, str]:
- """Research and generate content for each section in one step."""
- sections = {}
-
- for section in structure:
- print(f"Processing section: {section['name']}")
- section_content = []
- 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")
-
- # Generate a specific search query for this subsection
- subsection_query = f"{query} {section['name']} {subsection['name']} {subsection['purpose']}"
-
- print(f"Researching subsection: {subsection['name']} with query: {subsection_query}")
-
- # Configure search system for focused search
- original_max_iterations = self.search_system.max_iterations
- self.search_system.max_iterations = 1 # Keep search focused
-
- # 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 section
- sections[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],
- query: str,
- ) -> Dict:
- """Format the final report with table of contents and sections."""
- # 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" {i}.{j} {subsection['name']} | _{subsection['purpose']}_")
-
- # Combine TOC and sections
- report_parts = ["\n".join(toc), ""]
-
- # 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")
-
- # Add each section's content
- for section in structure:
- 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_content = "\n\n".join(report_parts)
- final_report_content = final_report_content + "\n\n## Sources\n\n" + formatted_all_links
-
- # Create metadata dictionary
- from datetime import datetime
- metadata = {
- "generated_at": datetime.utcnow().isoformat(),
- "initial_sources": len(self.search_system.all_links_of_system),
- "sections_researched": len(structure),
- "searches_per_section": self.searches_per_section,
- "query": query
- }
-
- # Return both content and metadata
- return {
- "content": final_report_content,
- "metadata": metadata
- }
-
- 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 file
diff --git a/search_system.py b/search_system.py
deleted file mode 100644
index 42a1124977..0000000000
--- a/search_system.py
+++ /dev/null
@@ -1,229 +0,0 @@
-from typing import Dict, List, Optional, Callable
-from datetime import datetime
-from utilties.search_utilities import remove_think_tags, format_findings_to_text, print_search_results, format_links
-import os
-from utilties.enums import KnowledgeAccumulationApproach
-from config import get_llm, get_search, SEARCH_ITERATIONS, QUESTIONS_PER_ITERATION
-import config
-from citation_handler import CitationHandler
-from datetime import datetime
-from utilties.search_utilities import extract_links_from_search_results
-
-class AdvancedSearchSystem:
- def __init__(self):
- self.search = get_search()
- self.model = get_llm()
- self.max_iterations = SEARCH_ITERATIONS
- self.questions_per_iteration = QUESTIONS_PER_ITERATION
- self.context_limit = config.KNOWLEDGE_ACCUMULATION_CONTEXT_LIMIT
- self.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.
-
- Args:
- callback: Function that takes (message, progress_percent, metadata)
- """
- self.progress_callback = callback
-
- def _update_progress(self, message: str, progress_percent: int = None, metadata: dict = None) -> None:
- """Send a progress update via the callback if available.
-
- Args:
- message: Description of the current progress state
- progress_percent: Progress percentage (0-100), if applicable
- metadata: Additional data about the progress state
- """
- if self.progress_callback:
- self.progress_callback(message, progress_percent, metadata or {})
-
- def _get_follow_up_questions(self, current_knowledge: str, query: str) -> List[str]:
- now = datetime.now()
- current_time = now.strftime("%Y-%m-%d")
-
- self._update_progress("Generating follow-up questions...", None, {"iteration": len(self.questions_by_iteration)})
-
- 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 Q: question2\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 Q: question2\n\n"
-
- 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:")
- ][: self.questions_per_iteration]
-
- self._update_progress(
- f"Generated {len(questions)} follow-up questions",
- None,
- {"questions": questions}
- )
-
- return questions
-
- 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 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}
- 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)
- response = remove_think_tags(response.content)
- response = str(response) #+ "\n\n" + str(formatted_links)
- print(response)
- return response
-
- def analyze_topic(self, query: str) -> Dict:
- findings = []
- current_knowledge = ""
- iteration = 0
- total_iterations = self.max_iterations
- section_links =list()
-
- self._update_progress("Initializing research system", 5, {
- "phase": "init",
- "iterations_planned": total_iterations
- })
-
- while iteration < self.max_iterations:
- iteration_progress_base = (iteration / total_iterations) * 100
- self._update_progress(f"Starting iteration {iteration + 1} of {total_iterations}",
- int(iteration_progress_base),
- {"phase": "iteration_start", "iteration": iteration + 1})
-
- # Generate questions for this iteration
- questions = self._get_follow_up_questions(current_knowledge, query)
- self.questions_by_iteration[iteration] = questions
-
- question_count = len(questions)
- for q_idx, question in enumerate(questions):
- question_progress_base = iteration_progress_base + (((q_idx+1) / question_count) * (100/total_iterations) * 0.5)
-
- self._update_progress(f"Searching for: {question}",
- int(question_progress_base),
- {"phase": "search", "iteration": iteration + 1, "question_index": q_idx + 1})
-
- search_results = self.search.run(question)
-
-
-
-
-
- self._update_progress(f"Found {len(search_results)} results for question: {question}",
- int(question_progress_base + 2),
- {"phase": "search_complete", "result_count": len(search_results)})
-
- print("len search", len(search_results))
-
- if len(search_results) == 0:
- continue
-
-
-
- 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, 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": results_with_links,
- "question": question,
- "search_results": search_results,
- "documents": result["documents"],
- }
- )
-
-
-
- if config.KNOWLEDGE_ACCUMULATION != KnowledgeAccumulationApproach.NO_KNOWLEDGE:
- current_knowledge = current_knowledge + "\n\n\n New: \n" + results_with_links
-
- print(current_knowledge)
- if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.QUESTION:
- self._update_progress(f"Compress Knowledge for: {question}",
- int(question_progress_base + 0),
- {"phase": "analysis"})
- current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
-
- self._update_progress(f"Analysis complete for question: {question}",
- int(question_progress_base + 10),
- {"phase": "analysis_complete"})
-
- iteration += 1
-
- self._update_progress(f"Compressing knowledge after iteration {iteration}",
- int((iteration / total_iterations) * 100 - 5),
- {"phase": "knowledge_compression"})
- if config.KNOWLEDGE_ACCUMULATION == KnowledgeAccumulationApproach.ITERATION:
- current_knowledge = self._compress_knowledge(current_knowledge , query, section_links)
-
-
- self._update_progress(f"Iteration {iteration} complete",
- int((iteration / total_iterations) * 100),
- {"phase": "iteration_complete", "iteration": iteration})
-
- formatted_findings = self._save_findings(findings, current_knowledge, query)
-
- self._update_progress("Research complete", 95, {"phase": "complete"})
-
- return {
- "findings": findings,
- "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):
- self._update_progress("Saving research findings...", None)
-
- 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:
- text_file.write(formatted_findings)
-
- self._update_progress("Research findings saved", None, {"filename": filename})
- return formatted_findings
\ No newline at end of file
diff --git a/static/css/styles.css b/static/css/styles.css
deleted file mode 100644
index 218f7898d3..0000000000
--- a/static/css/styles.css
+++ /dev/null
@@ -1,983 +0,0 @@
-/* Modern AI-themed dark interface */
-:root {
- --bg-primary: #121212;
- --bg-secondary: #1e1e2d;
- --bg-tertiary: #2a2a3a;
- --accent-primary: #6e4ff6;
- --accent-secondary: #9179f0;
- --accent-tertiary: #40bfff;
- --text-primary: #f5f5f5;
- --text-secondary: #c0c0cc;
- --text-muted: #8a8aa0;
- --border-color: #343452;
- --success-color: #0acf97;
- --warning-color: #f9bc0b;
- --error-color: #fa5c7c;
- --card-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
- --glow-effect: 0 0 15px rgba(110, 79, 246, 0.3);
- --gradient-bg: linear-gradient(135deg, #2a2a3a 0%, #1e1e2d 100%);
-}
-
-/* Reset and Base Styles */
-* {
- margin: 0;
- padding: 0;
- box-sizing: border-box;
-}
-
-body {
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
- background-color: var(--bg-primary);
- color: var(--text-primary);
- line-height: 1.6;
- overflow-x: hidden;
-}
-
-a {
- color: var(--accent-tertiary);
- text-decoration: none;
- transition: color 0.2s;
-}
-
-a:hover {
- color: var(--accent-secondary);
-}
-
-/* Layout */
-.app-container {
- display: flex;
- min-height: 100vh;
-}
-
-/* Sidebar */
-.sidebar {
- width: 240px;
- background-color: var(--bg-secondary);
- border-right: 1px solid var(--border-color);
- display: flex;
- flex-direction: column;
- position: fixed;
- height: 100vh;
- z-index: 10;
-}
-
-.sidebar-header {
- padding: 1.5rem;
- border-bottom: 1px solid var(--border-color);
-}
-
-.sidebar-header h2 {
- display: flex;
- align-items: center;
- font-weight: 600;
- font-size: 1.25rem;
- gap: 0.5rem;
- color: var(--accent-secondary);
-}
-
-.sidebar-header h2 i {
- color: var(--accent-primary);
-}
-
-.sidebar-nav {
- flex: 1;
- padding: 1rem 0;
-}
-
-.sidebar-nav ul {
- list-style: none;
-}
-
-.sidebar-nav li {
- padding: 0.75rem 1.5rem;
- margin-bottom: 0.25rem;
- cursor: pointer;
- display: flex;
- align-items: center;
- gap: 0.75rem;
- color: var(--text-secondary);
- border-left: 3px solid transparent;
- transition: all 0.2s;
-}
-
-.sidebar-nav li i {
- width: 20px;
-}
-
-.sidebar-nav li:hover {
- background-color: var(--bg-tertiary);
- color: var(--text-primary);
-}
-
-.sidebar-nav li.active {
- color: var(--accent-primary);
- background-color: rgba(110, 79, 246, 0.1);
- border-left-color: var(--accent-primary);
-}
-
-.sidebar-footer {
- padding: 1rem 1.5rem;
- border-top: 1px solid var(--border-color);
- color: var(--text-muted);
- font-size: 0.875rem;
- display: flex;
- justify-content: center;
-}
-
-/* Main Content */
-.main-content {
- flex: 1;
- padding: 1.0rem 2rem 2rem 2rem;
- margin-left: 240px;
- width: calc(100% - 240px);
-}
-
-.page {
- display: none;
-}
-
-.page.active {
- display: block;
- animation: fadeIn 0.3s ease;
-}
-
-@keyframes fadeIn {
- from { opacity: 0; }
- to { opacity: 1; }
-}
-
-.page-header {
- margin-bottom: 1.5rem;
-}
-
-.page-header h1 {
- font-weight: 600;
- font-size: 1.75rem;
- color: var(--text-primary);
-}
-
-/* Cards */
-.card {
- background-color: var(--bg-secondary);
- border-radius: 12px;
- box-shadow: var(--card-shadow);
- margin-bottom: 1.5rem;
- overflow: hidden;
- border: 1px solid var(--border-color);
-}
-
-.card-content {
- padding: 1.5rem;
-}
-
-/* Form Elements */
-.form-group {
- margin-bottom: 1.5rem;
-}
-
-.form-group label {
- display: block;
- margin-bottom: 0.5rem;
- font-weight: 500;
- color: var(--text-secondary);
-}
-
-textarea, input[type="text"] {
- width: 100%;
- padding: 0.75rem;
- border-radius: 8px;
- border: 1px solid var(--border-color);
- background-color: var(--bg-tertiary);
- color: var(--text-primary);
- font-family: inherit;
- font-size: 0.95rem;
- resize: vertical;
- transition: border-color 0.2s, box-shadow 0.2s;
-}
-
-textarea:focus, input[type="text"]:focus {
- outline: none;
- border-color: var(--accent-primary);
- box-shadow: 0 0 0 3px rgba(110, 79, 246, 0.2);
-}
-
-.btn {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 0.5rem;
- padding: 0.75rem 1.25rem;
- border-radius: 8px;
- font-weight: 500;
- font-size: 0.95rem;
- cursor: pointer;
- transition: all 0.2s;
- border: none;
-}
-
-.btn-sm {
- padding: 0.5rem 1rem;
- font-size: 0.85rem;
-}
-
-.btn-primary {
- background-color: var(--accent-primary);
- color: white;
-}
-
-.btn-primary:hover {
- background-color: var(--accent-secondary);
- box-shadow: var(--glow-effect);
-}
-
-.btn-outline {
- background-color: transparent;
- color: var(--accent-tertiary);
- border: 1px solid var(--accent-tertiary);
-}
-
-.btn-outline:hover {
- background-color: rgba(64, 191, 255, 0.1);
-}
-
-.delete-btn {
- color: var(--error-color);
- border-color: var(--error-color);
-}
-
-.delete-btn:hover {
- background-color: rgba(250, 92, 124, 0.1);
-}
-
-.terminate-btn {
- color: #e74c3c;
- border-color: #e74c3c;
-}
-
-.terminate-btn:hover {
- background-color: rgba(231, 76, 60, 0.1);
-}
-
-.btn:disabled {
- opacity: 0.6;
- cursor: not-allowed;
- pointer-events: none;
-}
-
-.form-actions {
- display: flex;
- justify-content: flex-end;
-}
-
-/* Mode Selection */
-.mode-selection {
- display: flex;
- gap: 1rem;
-}
-
-.mode-option {
- flex: 1;
- background-color: var(--bg-tertiary);
- border-radius: 8px;
- padding: 1.25rem;
- border: 2px solid transparent;
- cursor: pointer;
- transition: all 0.2s;
- display: flex;
- align-items: center;
- gap: 1rem;
-}
-
-.mode-option:hover {
- background-color: var(--bg-primary);
-}
-
-.mode-option.active {
- border-color: var (--accent-primary);
- background-color: rgba(110, 79, 246, 0.1);
-}
-
-.mode-icon {
- width: 40px;
- height: 40px;
- background-color: var(--accent-primary);
- color: white;
- border-radius: 50%;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 1.2rem;
-}
-
-.mode-option.active .mode-icon {
- background-color: var(--accent-secondary);
- box-shadow: var(--glow-effect);
-}
-
-.mode-info h3 {
- margin-bottom: 0.25rem;
- color: var(--text-primary);
-}
-
-.mode-info p {
- color: var(--text-muted);
- font-size: 0.85rem;
-}
-
-/* Progress Bar */
-.progress-container {
- margin: 1.5rem 0;
- display: flex;
- align-items: center;
- gap: 1rem;
-}
-
-.progress-bar {
- flex: 1;
- height: 12px;
- background-color: var(--bg-tertiary);
- border-radius: 6px;
- overflow: hidden;
-}
-
-.progress-fill {
- height: 100%;
- width: 0%;
- background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));
- border-radius: 6px;
- transition: width 0.5s ease;
-}
-
-.progress-text {
- width: 60px;
- text-align: right;
- font-weight: 600;
- color: var(--accent-secondary);
-}
-
-.query-display {
- margin-bottom: 1.5rem;
-}
-
-.query-display h3 {
- color: var(--text-secondary);
- font-size: 1rem;
- margin-bottom: 0.5rem;
-}
-
-.query-display p {
- color: var(--text-primary);
- font-weight: 500;
-}
-
-.progress-info {
- color: var(--text-secondary);
- font-size: 0.9rem;
-}
-
-/* History List */
-.history-list {
- display: flex;
- flex-direction: column;
- gap: 1rem;
-}
-
-.history-item {
- background-color: var(--bg-tertiary);
- border-radius: 8px;
- padding: 1rem;
- border: 1px solid var(--border-color);
- transition: all 0.2s;
- cursor: pointer;
- position: relative;
-}
-
-.history-item:hover {
- border-color: var(--accent-tertiary);
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
-}
-
-.history-item-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-bottom: 0.5rem;
-}
-
-.history-item-title {
- font-weight: 500;
- color: var(--text-primary);
-}
-
-.history-item-status {
- font-size: 0.8rem;
- padding: 0.25rem 0.5rem;
- border-radius: 4px;
- font-weight: 500;
-}
-
-.status-completed {
- background-color: rgba(10, 207, 151, 0.15);
- color: var(--success-color);
-}
-
-.status-in-progress {
- background-color: rgba(249, 188, 11, 0.15);
- color: var(--warning-color);
-}
-
-.status-failed {
- background-color: rgba(250, 92, 124, 0.15);
- color: var(--error-color);
-}
-
-.status-suspended {
- color: #f39c12;
-}
-
-.status-terminating {
- background-color: rgba(231, 76, 60, 0.15);
- color: #e74c3c;
- animation: pulse 1.5s infinite;
-}
-
-@keyframes pulse {
- 0% { opacity: 0.7; }
- 50% { opacity: 1; }
- 100% { opacity: 0.7; }
-}
-
-.history-item-meta {
- display: flex;
- color: var(--text-muted);
- font-size: 0.85rem;
- margin-bottom: 0.75rem;
-}
-
-.history-item-date {
- margin-right: 1rem;
-}
-
-.history-item-mode {
- display: flex;
- align-items: center;
- gap: 0.25rem;
-}
-
-.history-item-actions {
- display: flex;
- justify-content: flex-end;
- gap: 0.5rem;
- position: relative;
- z-index: 5;
-}
-
-.history-item-actions button {
- position: relative;
- z-index: 10;
-}
-
-/* Results Page */
-.results-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
-}
-
-.results-metadata {
- display: flex;
- flex-wrap: wrap;
- gap: 1rem;
- margin-bottom: 1.5rem;
- padding-bottom: 1rem;
- border-bottom: 1px solid var(--border-color);
-}
-
-.metadata-item {
- display: flex;
- flex-direction: column;
-}
-
-.metadata-label {
- font-size: 0.85rem;
- color: var(--text-muted);
- margin-bottom: 0.25rem;
-}
-
-.metadata-value {
- color: var(--text-primary);
- font-weight: 500;
-}
-
-.results-content {
- line-height: 1.7;
-}
-
-.results-content h1 {
- font-size: 1.75rem;
- margin: 1.5rem 0 1rem;
- color: var(--text-primary);
-}
-
-.results-content h2 {
- font-size: 1.5rem;
- margin: 1.25rem 0 0.75rem;
- color: var(--accent-tertiary);
-}
-
-.results-content h3 {
- font-size: 1.25rem;
- margin: 1rem 0 0.5rem;
- color: var(--accent-secondary);
-}
-
-.results-content p {
- margin-bottom: 1rem;
- color: var(--text-secondary);
-}
-
-.results-content ul,
-.results-content ol {
- margin-bottom: 1rem;
- padding-left: 1.5rem;
- color: var(--text-secondary);
-}
-
-.results-content li {
- margin-bottom: 0.5rem;
-}
-
-.results-content code {
- background-color: var(--bg-tertiary);
- padding: 0.15rem 0.3rem;
- border-radius: 4px;
- font-family: 'SF Mono', 'Menlo', 'Monaco', 'Courier New', monospace;
- font-size: 0.9em;
-}
-
-.results-content pre {
- background-color: var(--bg-tertiary);
- border-radius: 8px;
- padding: 1rem;
- margin-bottom: 1rem;
- overflow-x: auto;
-}
-
-.results-content blockquote {
- border-left: 3px solid var(--accent-primary);
- padding-left: 1rem;
- margin-left: 0;
- margin-bottom: 1rem;
- color: var(--text-muted);
-}
-
-.results-content table {
- width: 100%;
- border-collapse: collapse;
- margin-bottom: 1rem;
-}
-
-.results-content th {
- background-color: var(--bg-tertiary);
- text-align: left;
- padding: 0.75rem;
- border-bottom: 2px solid var(--border-color);
- color: var(--accent-tertiary);
-}
-
-.results-content td {
- padding: 0.75rem;
- border-bottom: 1px solid var(--border-color);
- color: var(--text-secondary);
-}
-
-/* Research Details Page */
-.research-metadata {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
- gap: 1.5rem;
- margin-bottom: 1.5rem;
- padding-bottom: 1rem;
- border-bottom: 1px solid var(--border-color);
-}
-
-.detail-progress-container {
- display: flex;
- align-items: center;
- gap: 0.75rem;
-}
-
-.detail-progress-bar {
- flex: 1;
- height: 8px;
- background-color: var(--bg-tertiary);
- border-radius: 4px;
- overflow: hidden;
-}
-
-.detail-progress-fill {
- height: 100%;
- width: 0%;
- background: linear-gradient(90deg, var(--accent-primary), var(--accent-secondary));
- border-radius: 4px;
- transition: width 0.5s ease;
-}
-
-.research-log-container {
- margin-top: 1.5rem;
-}
-
-.research-log-container h3 {
- margin-bottom: 1rem;
- color: var(--text-secondary);
- font-size: 1.1rem;
- font-weight: 500;
-}
-
-.research-log {
- max-height: 500px;
- overflow-y: auto;
- padding: 1rem;
- background-color: var(--bg-tertiary);
- border-radius: 8px;
- border: 1px solid var(--border-color);
-}
-
-.log-entry {
- padding: 0.75rem;
- border-bottom: 1px solid var(--border-color);
- display: flex;
- gap: 1rem;
-}
-
-.log-entry:last-child {
- border-bottom: none;
-}
-
-.log-entry-time {
- font-size: 0.8rem;
- color: var(--text-muted);
- min-width: 80px;
-}
-
-.log-entry-content {
- flex: 1;
-}
-
-.log-entry-message {
- color: var(--text-secondary);
- margin-bottom: 0.25rem;
-}
-
-.log-entry-progress {
- font-size: 0.85rem;
- color: var(--accent-secondary);
- font-weight: 500;
-}
-
-.detail-actions {
- margin-top: 1.5rem;
- display: flex;
- justify-content: center;
- gap: 1rem;
-}
-
-.phase-highlight {
- color: var(--accent-tertiary);
- font-weight: 500;
-}
-
-.phase-init {
- color: var(--accent-tertiary);
-}
-
-.phase-search {
- color: var(--accent-secondary);
-}
-
-.phase-analysis {
- color: var(--warning-color);
-}
-
-.phase-complete {
- color: var(--success-color);
-}
-
-.phase-error {
- color: var(--error-color);
-}
-
-.phase-termination {
- color: #e74c3c;
- font-weight: bold;
-}
-
-.empty-state {
- padding: 2rem;
- text-align: center;
- color: var(--text-muted);
- font-style: italic;
-}
-
-.error-message {
- padding: 1rem;
- background-color: rgba(250, 92, 124, 0.1);
- border: 1px solid var(--error-color);
- border-radius: 8px;
- color: var(--error-color);
- margin: 1rem 0;
- font-size: 0.9rem;
-}
-
-/* Loading Spinner */
-.loading-spinner {
- padding: 2rem 0;
-}
-
-.loading-spinner.centered {
- display: flex;
- justify-content: center;
- align-items: center;
-}
-
-.spinner {
- width: 40px;
- height: 40px;
- border: 4px solid rgba(110, 79, 246, 0.2);
- border-left-color: var(--accent-primary);
- border-radius: 50%;
- animation: spin 1s linear infinite;
-}
-
-@keyframes spin {
- to { transform: rotate(360deg); }
-}
-
-/* Mobile Tab Bar */
-.mobile-tab-bar {
- display: none; /* Hidden by default */
- position: fixed;
- bottom: 0;
- left: 0;
- right: 0;
- height: 60px;
- background-color: var(--bg-secondary);
- border-top: 1px solid var(--border-color);
- z-index: 1000;
- box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.2);
-}
-
-.mobile-tab-bar ul {
- display: flex;
- height: 100%;
- list-style: none;
- padding: 0;
- margin: 0;
- width: 100%;
-}
-
-.mobile-tab-bar li {
- flex: 1;
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- cursor: pointer;
- color: var(--text-secondary);
- transition: all 0.2s;
- padding: 0.5rem 0;
- min-width: 90px;
-}
-
-.mobile-tab-bar li i {
- font-size: 1.3rem;
- margin-bottom: 8px;
-}
-
-.mobile-tab-bar li span {
- font-size: 0.75rem;
- text-align: center;
- width: 100%;
-}
-
-.mobile-tab-bar li.active {
- color: var(--accent-primary);
-}
-
-.mobile-tab-bar li:hover {
- color: var(--text-primary);
-}
-
-/* External link styling for sidebar and mobile navigation - more subtle */
-.sidebar-nav ul li.external-link {
- color: var(--text-primary);
- border-left: 3px solid #607d8b;
- margin-bottom: 10px;
- padding-left: 17px;
- opacity: 0.75;
-}
-
-.sidebar-nav ul li.external-link:hover {
- background-color: rgba(96, 125, 139, 0.1);
- opacity: 1;
- cursor: pointer;
-}
-
-.mobile-tab-bar ul li.external-link {
- color: var(--text-primary);
- opacity: 0.75;
-}
-
-.mobile-tab-bar ul li.external-link i {
- color: var(--text-primary);
-}
-
-.mobile-tab-bar ul li.external-link:hover {
- opacity: 1;
-}
-
-/* Responsive */
-@media (max-width: 991px) {
- .sidebar {
- width: 60px;
- overflow: hidden;
- }
-
- /* Hide all text in the logo and center icon */
- .sidebar-header {
- padding: 1rem 0;
- text-align: center;
- display: flex;
- align-items: center;
- justify-content: center;
- height: 60px;
- }
-
- .sidebar-header h2 {
- font-size: 0;
- display: flex;
- justify-content: center;
- width: 100%;
- }
-
- .sidebar-header h2 i {
- font-size: 1.4rem;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- /* Hide all text in nav items and center icons */
- .sidebar-nav {
- display: flex;
- flex-direction: column;
- padding-top: 0.5rem;
- }
-
- .sidebar-nav ul {
- width: 100%;
- }
-
- .sidebar-nav li {
- text-indent: -9999px;
- white-space: nowrap;
- padding: 1rem 0;
- text-align: center;
- height: 60px;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- .sidebar-nav li i {
- text-indent: 0;
- margin: 0;
- font-size: 1.3rem;
- display: flex;
- align-items: center;
- justify-content: center;
- }
-
- /* Active state fix for icon view */
- .sidebar-nav li.active {
- border-left-width: 3px;
- }
-
- /* Hide footer */
- .sidebar-footer {
- display: none;
- }
-
- /* Adjust main content */
- .main-content {
- margin-left: 60px;
- width: calc(100% - 60px);
- }
-
- .mode-selection {
- flex-direction: column;
- }
-}
-
-@media (max-width: 767px) {
- body {
- padding-bottom: 60px; /* Add padding to body for the tab bar */
- }
-
- .main-content {
- padding: 1rem;
- padding-bottom: 70px; /* Add padding for the tab bar */
- margin-left: 0;
- width: 100%;
- }
-
- .sidebar {
- width: 0;
- transform: translateX(-100%);
- }
-
- .sidebar.active {
- width: 240px;
- transform: translateX(0);
- }
-
- /* Restore text in logo when sidebar is active on mobile */
- .sidebar.active .sidebar-header h2 {
- font-size: 1.25rem;
- }
-
- /* Restore text in nav items when sidebar is active on mobile */
- .sidebar.active .sidebar-nav li {
- text-indent: 0;
- padding: 0.75rem 1.5rem;
- text-align: left;
- }
-
- .sidebar.active .sidebar-nav li i {
- display: inline;
- width: 20px;
- margin-right: 0.75rem;
- font-size: 1rem;
- }
-
- .sidebar.active .sidebar-footer {
- display: flex;
- }
-
- /* Show mobile tab bar */
- .mobile-tab-bar {
- display: flex !important; /* Use !important to ensure it displays */
- }
-}
-
-.progress-status {
- margin-bottom: 1.25rem;
- padding: 0.5rem 0;
- font-weight: 500;
-}
-
-.progress-actions {
- display: flex;
- justify-content: center;
- margin-top: 1rem;
-}
\ No newline at end of file
diff --git a/static/js/app.js b/static/js/app.js
deleted file mode 100644
index 22ddaf4ea9..0000000000
--- a/static/js/app.js
+++ /dev/null
@@ -1,1620 +0,0 @@
-// Main application functionality
-document.addEventListener('DOMContentLoaded', () => {
- // Global socket variable - initialize as null
- let socket = null;
- let socketConnected = false;
-
- // Global state variables
- let isResearchInProgress = false;
- let currentResearchId = null;
- window.currentResearchId = null;
-
- // Initialize socket only when needed with a timeout for safety
- function initializeSocket() {
- if (socket) return socket; // Return existing socket if already initialized
-
- console.log('Initializing socket connection...');
- // Create new socket connection with optimized settings for threading mode
- socket = io({
- path: '/research/socket.io',
- transports: ['websocket', 'polling'],
- reconnection: true,
- reconnectionAttempts: 3,
- reconnectionDelay: 1000,
- timeout: 5000,
- autoConnect: true,
- forceNew: true
- });
-
- // Add event handlers
- socket.on('connect', () => {
- console.log('Socket connected');
- socketConnected = true;
- });
-
- socket.on('disconnect', () => {
- console.log('Socket disconnected');
- socketConnected = false;
- });
-
- socket.on('connect_error', (error) => {
- console.error('Socket connection error:', error);
- socketConnected = false;
- });
-
- // Set a timeout to detect hanging connections
- setTimeout(() => {
- if (!socketConnected) {
- console.log('Socket connection timeout - forcing reconnect');
- try {
- socket.disconnect();
- socket.connect();
- } catch (e) {
- console.error('Error during forced reconnect:', e);
- }
- }
- }, 5000);
-
- return socket;
- }
-
- // Function to safely disconnect socket
- window.disconnectSocket = function() {
- try {
- if (socket) {
- console.log('Manually disconnecting socket');
- socket.removeAllListeners();
- socket.disconnect();
- socket = null;
- socketConnected = false;
- }
- } catch (e) {
- console.error('Error disconnecting socket:', e);
- }
- };
-
- // Helper function to connect to research updates
- window.connectToResearchSocket = function(researchId) {
- try {
- // Initialize socket if needed
- if (!socket) {
- socket = initializeSocket();
- }
-
- // Subscribe to research updates
- socket.emit('subscribe_to_research', { research_id: researchId });
-
- // Set up event listener for research progress
- const progressEventName = `research_progress_${researchId}`;
-
- // Remove existing listeners to prevent duplicates
- socket.off(progressEventName);
-
- // Add new listener
- socket.on(progressEventName, (data) => {
- console.log('Received research progress update:', data);
- updateProgressUI(data.progress, data.status, data.message);
-
- // If research is complete, show the completion buttons
- if (data.status === 'completed' || data.status === 'terminated' || data.status === 'failed') {
- updateNavigationBasedOnResearchStatus();
- }
-
- // Update the detailed log if on details page
- if (data.log_entry && document.getElementById('research-log')) {
- updateDetailLogEntry(data.log_entry);
- }
- });
-
- return true;
- } catch (e) {
- console.error('Error connecting to research socket:', e);
- return false;
- }
- };
-
- // Check for active research on page load
- async function checkActiveResearch() {
- try {
- const response = await fetch(getApiUrl('/api/history'));
- const history = await response.json();
-
- // Find in-progress research
- const activeResearch = history.find(item => item.status === 'in_progress');
-
- if (activeResearch) {
- isResearchInProgress = true;
- currentResearchId = activeResearch.id;
- window.currentResearchId = currentResearchId;
-
- // Check if we're on the new research page and redirect to progress
- const currentPage = document.querySelector('.page.active');
-
- if (currentPage && currentPage.id === 'new-research') {
- // Navigate to progress page
- switchPage('research-progress');
-
- // Connect to socket for this research
- window.connectToResearchSocket(currentResearchId);
-
- // Start polling for updates
- pollResearchStatus(currentResearchId);
- }
- }
- } catch (error) {
- console.error('Error checking for active research:', error);
- }
- }
-
- // Add unload event listener
- window.addEventListener('beforeunload', function() {
- window.disconnectSocket();
- });
-
- // Function to start research
- async function startResearch(query, mode) {
- // Check if research is already in progress
- if (isResearchInProgress) {
- alert('Another research is already in progress. Please wait for it to complete or check its status in the history tab.');
- return;
- }
-
- // Get the start button
- const startResearchBtn = document.getElementById('start-research-btn');
- if (!startResearchBtn) return;
-
- // Disable the start button while we attempt to start the research
- startResearchBtn.disabled = true;
- startResearchBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Starting...';
-
- try {
- const response = await fetch(getApiUrl('/api/start_research'), {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- query: query,
- mode: mode
- })
- });
-
- const data = await response.json();
-
- if (data.status === 'success') {
- isResearchInProgress = true;
- currentResearchId = data.research_id;
-
- // Also update the window object
- window.currentResearchId = data.research_id;
-
- // Update the navigation to show Research in Progress
- updateNavigationBasedOnResearchStatus();
-
- // Update progress page
- document.getElementById('current-query').textContent = query;
- document.getElementById('progress-fill').style.width = '0%';
- document.getElementById('progress-percentage').textContent = '0%';
- document.getElementById('progress-status').textContent = 'Initializing research process...';
-
- // Navigate to progress page
- switchPage('research-progress');
-
- // Connect to socket for this research
- window.connectToResearchSocket(data.research_id);
-
- // Start polling for status
- pollResearchStatus(data.research_id);
-
- // Show the terminate button
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- terminateBtn.style.display = 'inline-flex';
- terminateBtn.disabled = false;
- }
- } else {
- alert('Error starting research: ' + (data.message || 'Unknown error'));
- startResearchBtn.disabled = false;
- startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
- }
- } catch (error) {
- console.error('Error:', error);
- alert('An error occurred while starting the research. Please try again.');
- startResearchBtn.disabled = false;
- startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
- }
- }
-
- // Function to poll research status (as a backup to socket.io)
- function pollResearchStatus(researchId) {
- const interval = setInterval(async () => {
- try {
- const response = await fetch(getApiUrl(`/api/research/${researchId}`));
- const data = await response.json();
-
- if (data.status === 'completed' || data.status === 'failed' || data.status === 'suspended') {
- clearInterval(interval);
- isResearchInProgress = false;
- currentResearchId = null;
-
- // Always update the start research button state
- const startResearchBtn = document.getElementById('start-research-btn');
- if (startResearchBtn) {
- startResearchBtn.disabled = false;
- startResearchBtn.innerHTML = '<i class="fas fa-rocket"></i> Start Research';
- }
-
- // Update navigation when research completes or is suspended
- updateNavigationBasedOnResearchStatus();
-
- // If history page is active, update the specific item in place
- if (document.getElementById('history').classList.contains('active')) {
- updateHistoryItemStatus(researchId, data.status);
- // Full refresh may still be needed to update duration info
- setTimeout(() => loadResearchHistory(), 500);
- }
-
- if (data.status === 'completed') {
- loadResearch(researchId);
- } else if (data.status === 'failed' || data.status === 'suspended') {
- const statusMessage = data.status === 'suspended' ?
- 'Research was terminated by user' :
- (data.metadata ? JSON.parse(data.metadata).error : 'Research failed');
- updateProgressUI(100, data.status, statusMessage);
- }
- } else {
- updateProgressUI(data.progress || 0, data.status);
- }
- } catch (error) {
- console.error('Error polling status:', error);
- }
- }, 3000); // Poll every 3 seconds
- }
-
- // Main initialization function
- function initializeApp() {
- console.log('Initializing application...');
-
- // Get navigation elements
- const navItems = document.querySelectorAll('.sidebar-nav li');
- const mobileNavItems = document.querySelectorAll('.mobile-tab-bar li');
- const pages = document.querySelectorAll('.page');
- const mobileTabBar = document.querySelector('.mobile-tab-bar');
-
- // Handle responsive navigation based on screen size
- function handleResponsiveNavigation() {
- // Mobile tab bar should only be visible on small screens
- if (window.innerWidth <= 767) {
- if (mobileTabBar) {
- mobileTabBar.style.display = 'flex';
- }
- } else {
- if (mobileTabBar) {
- mobileTabBar.style.display = 'none';
- }
- }
- }
-
- // Call on initial load
- handleResponsiveNavigation();
-
- // Add resize listener for responsive design
- window.addEventListener('resize', handleResponsiveNavigation);
-
- // Setup navigation click handlers
- navItems.forEach(item => {
- if (!item.classList.contains('external-link')) {
- item.addEventListener('click', function() {
- const pageId = this.dataset.page;
- if (pageId) {
- switchPage(pageId);
- }
- });
- }
- });
-
- mobileNavItems.forEach(item => {
- if (!item.classList.contains('external-link')) {
- item.addEventListener('click', function() {
- const pageId = this.dataset.page;
- if (pageId) {
- switchPage(pageId);
- }
- });
- }
- });
-
- // Setup form submission
- const researchForm = document.getElementById('research-form');
- if (researchForm) {
- researchForm.addEventListener('submit', function(e) {
- e.preventDefault();
- const query = document.getElementById('query').value.trim();
- if (!query) {
- alert('Please enter a research query');
- return;
- }
-
- const mode = document.querySelector('.mode-option.active')?.dataset.mode || 'quick';
- startResearch(query, mode);
- });
- }
-
- // Initialize research mode selection
- const modeOptions = document.querySelectorAll('.mode-option');
- modeOptions.forEach(option => {
- option.addEventListener('click', function() {
- modeOptions.forEach(opt => opt.classList.remove('active'));
- this.classList.add('active');
- });
- });
-
- // Load research history initially
- if (document.getElementById('history-list')) {
- loadResearchHistory();
- }
-
- // Check for active research
- checkActiveResearch();
-
- console.log('Application initialized');
- }
-
- // Initialize the app
- initializeApp();
-
- // Function to switch between pages
- function switchPage(pageId) {
- // Get elements directly from the DOM
- const pages = document.querySelectorAll('.page');
- const navItems = document.querySelectorAll('.sidebar-nav li');
- const mobileNavItems = document.querySelectorAll('.mobile-tab-bar li');
-
- // Remove active class from all pages
- pages.forEach(page => {
- page.classList.remove('active');
- });
-
- // Add active class to target page
- const targetPage = document.getElementById(pageId);
- if (targetPage) {
- targetPage.classList.add('active');
- }
-
- // Update sidebar navigation active states
- navItems.forEach(item => {
- if (item.getAttribute('data-page') === pageId) {
- item.classList.add('active');
- } else {
- item.classList.remove('active');
- }
- });
-
- // Update mobile tab bar active states
- mobileNavItems.forEach(item => {
- if (item.getAttribute('data-page') === pageId) {
- item.classList.add('active');
- } else {
- item.classList.remove('active');
- }
- });
-
- // Special handling for history page
- if (pageId === 'history') {
- loadResearchHistory();
- }
- }
-
- // Track termination status
- let isTerminating = false;
-
- // Check if we're on the history page and load history if needed
- const historyPage = document.getElementById('history');
- if (historyPage && historyPage.classList.contains('active')) {
- // Use setTimeout to ensure the DOM is fully loaded
- setTimeout(() => loadResearchHistory(), 100);
- }
-
- // Add a prefix helper function at the top of the file
- function getApiUrl(path) {
- // This function adds the /research prefix to all API URLs
- return `/research${path}`;
- }
-
- // Function to terminate research - exposed to window object
- async function terminateResearch(researchId) {
- if (!researchId) {
- console.error('No research ID provided for termination');
- return;
- }
-
- // Prevent multiple termination requests
- if (isTerminating) {
- console.log('Termination already in progress');
- return;
- }
-
- // Confirm with the user
- if (!confirm('Are you sure you want to terminate this research? This action cannot be undone.')) {
- return;
- }
-
- try {
- // Set terminating flag
- isTerminating = true;
-
- // Update UI to show we're processing
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- terminateBtn.disabled = true;
- terminateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Terminating...';
- }
-
- // Find all terminate buttons in history items and disable them
- const allTerminateBtns = document.querySelectorAll('.terminate-btn');
- allTerminateBtns.forEach(btn => {
- if (btn !== terminateBtn) {
- btn.disabled = true;
- btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Terminating...';
- }
- });
-
- // Call the terminate API
- const response = await fetch(getApiUrl(`/api/research/${researchId}/terminate`), {
- method: 'POST'
- });
-
- const data = await response.json();
-
- if (data.status === 'success') {
- // The UI will be updated via socket events or polling
- console.log('Termination request sent successfully');
-
- // If we're on the history page, update the status of this item
- if (document.getElementById('history').classList.contains('active')) {
- updateHistoryItemStatus(researchId, 'terminating', 'Terminating...');
- }
- } else {
- console.error('Termination request failed:', data.message);
- alert(`Failed to terminate research: ${data.message}`);
-
- // Reset the terminating flag
- isTerminating = false;
-
- // Reset the button
- if (terminateBtn) {
- terminateBtn.disabled = false;
- terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
- }
-
- // Reset history button states
- const allTerminateBtns = document.querySelectorAll('.terminate-btn');
- allTerminateBtns.forEach(btn => {
- if (btn !== terminateBtn) {
- btn.disabled = false;
- btn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate';
- }
- });
- }
- } catch (error) {
- console.error('Error terminating research:', error);
- alert('An error occurred while trying to terminate the research.');
-
- // Reset the terminating flag
- isTerminating = false;
-
- // Reset the button
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- terminateBtn.disabled = false;
- terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
- }
-
- // Reset history button states
- const allTerminateBtns = document.querySelectorAll('.terminate-btn');
- allTerminateBtns.forEach(btn => {
- if (btn !== terminateBtn) {
- btn.disabled = false;
- btn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate';
- }
- });
- }
- }
-
- // Expose the terminate function to the window object
- window.terminateResearch = terminateResearch;
-
- // Function to update the progress UI
- function updateProgressUI(progress, status, message) {
- const progressFill = document.getElementById('progress-fill');
- const progressPercentage = document.getElementById('progress-percentage');
- const progressStatus = document.getElementById('progress-status');
-
- if (progressFill && progressPercentage) {
- progressFill.style.width = `${progress}%`;
- progressPercentage.textContent = `${progress}%`;
- }
-
- if (progressStatus && message) {
- progressStatus.textContent = message;
-
- // Update status class
- progressStatus.className = 'progress-status';
- if (status) {
- progressStatus.classList.add(`status-${status}`);
- }
- }
-
- // Show/hide terminate button based on status
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- if (status === 'in_progress') {
- terminateBtn.style.display = 'inline-flex';
- terminateBtn.disabled = false;
- terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
- } else if (status === 'terminating') {
- terminateBtn.style.display = 'inline-flex';
- terminateBtn.disabled = true;
- terminateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Terminating...';
- } else {
- terminateBtn.style.display = 'none';
- }
- }
- }
-
- // Completely rewritten function to ensure reliable history loading
- async function loadResearchHistory() {
- const historyList = document.getElementById('history-list');
-
- // Make sure we have the history list element
- if (!historyList) {
- console.error('History list element not found');
- return;
- }
-
- historyList.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';
-
- try {
- const response = await fetch(getApiUrl('/api/history'));
-
- if (!response.ok) {
- throw new Error(`Server returned ${response.status}`);
- }
-
- const data = await response.json();
-
- // Clear the loading spinner
- historyList.innerHTML = '';
-
- // Handle empty data
- if (!data || !Array.isArray(data) || data.length === 0) {
- historyList.innerHTML = '<div class="empty-state">No research history found. Start a new research project!</div>';
- return;
- }
-
- // Check if any research is in progress
- const inProgressResearch = data.find(item => item.status === 'in_progress');
-
- // Get the start research button
- const startResearchBtn = document.getElementById('start-research-btn');
-
- if (inProgressResearch) {
- isResearchInProgress = true;
- currentResearchId = inProgressResearch.id;
- if (startResearchBtn) {
- startResearchBtn.disabled = true;
- }
- } else {
- isResearchInProgress = false;
- if (startResearchBtn) {
- startResearchBtn.disabled = false;
- }
- }
-
- // Display each history item
- data.forEach(item => {
- try {
- // Skip if item is invalid
- if (!item || !item.id) {
- return;
- }
-
- // Create container
- const historyItem = document.createElement('div');
- historyItem.className = 'history-item';
- historyItem.dataset.researchId = item.id;
-
- // Create header with title and status
- const header = document.createElement('div');
- header.className = 'history-item-header';
-
- const title = document.createElement('div');
- title.className = 'history-item-title';
- title.textContent = item.query || 'Untitled Research';
-
- const status = document.createElement('div');
- status.className = `history-item-status status-${item.status || 'unknown'}`;
- status.textContent = item.status ? (item.status.charAt(0).toUpperCase() + item.status.slice(1)) : 'Unknown';
-
- header.appendChild(title);
- header.appendChild(status);
- historyItem.appendChild(header);
-
- // Create meta section
- const meta = document.createElement('div');
- meta.className = 'history-item-meta';
-
- const date = document.createElement('div');
- date.className = 'history-item-date';
- try {
- // Use completed_at if available, fall back to created_at if not
- const dateToUse = item.completed_at || item.created_at;
- date.textContent = dateToUse ? formatDate(new Date(dateToUse)) : 'Unknown date';
- } catch (e) {
- date.textContent = item.completed_at || item.created_at || 'Unknown date';
- }
-
- const mode = document.createElement('div');
- mode.className = 'history-item-mode';
- const modeIcon = item.mode === 'quick' ? 'bolt' : 'microscope';
- const modeText = item.mode === 'quick' ? 'Quick Summary' : 'Detailed Report';
- mode.innerHTML = `<i class="fas fa-${modeIcon}"></i> ${modeText}`;
-
- meta.appendChild(date);
- meta.appendChild(mode);
- historyItem.appendChild(meta);
-
- // Create actions section
- const actions = document.createElement('div');
- actions.className = 'history-item-actions';
-
- // View button
- const viewBtn = document.createElement('button');
- viewBtn.className = 'btn btn-sm btn-outline view-btn';
-
- if (item.status === 'completed') {
- viewBtn.innerHTML = '<i class="fas fa-eye"></i> View';
- viewBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- loadResearch(item.id);
- });
-
- // PDF button for completed research
- const pdfBtn = document.createElement('button');
- pdfBtn.className = 'btn btn-sm btn-outline pdf-btn';
- pdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> PDF';
- pdfBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- generatePdfFromResearch(item.id);
- });
- actions.appendChild(pdfBtn);
- } else if (item.status === 'in_progress') {
- viewBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> In Progress';
- viewBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- navigateToResearchProgress({id: item.id, query: item.query, progress: 0});
- });
- } else {
- viewBtn.innerHTML = '<i class="fas fa-eye"></i> View';
- viewBtn.disabled = true;
- }
-
- actions.appendChild(viewBtn);
-
- // Delete button
- const deleteBtn = document.createElement('button');
- deleteBtn.className = 'btn btn-sm btn-outline delete-btn';
- deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete';
- deleteBtn.addEventListener('click', (e) => {
- e.stopPropagation();
- if (confirm(`Are you sure you want to delete this research: "${item.query}"?`)) {
- deleteResearch(item.id);
- }
- });
- actions.appendChild(deleteBtn);
-
- historyItem.appendChild(actions);
-
- // Add click handler for the entire item
- historyItem.addEventListener('click', (e) => {
- // Skip if clicking on a button
- if (e.target.closest('button')) {
- return;
- }
-
- if (item.status === 'completed') {
- loadResearch(item.id);
- } else if (item.status === 'in_progress') {
- navigateToResearchProgress({id: item.id, query: item.query, progress: 0});
- }
- });
-
- // Add to the history list
- historyList.appendChild(historyItem);
- } catch (itemError) {
- console.error('Error processing history item:', itemError, item);
- }
- });
-
- } catch (error) {
- console.error('Error loading history:', error);
- historyList.innerHTML = `
- <div class="error-message">
- Error loading history: ${error.message}
- </div>
- <div style="text-align: center; margin-top: 1rem;">
- <button id="retry-history-btn" class="btn btn-primary">
- <i class="fas fa-sync"></i> Retry
- </button>
- </div>`;
-
- const retryBtn = document.getElementById('retry-history-btn');
- if (retryBtn) {
- retryBtn.addEventListener('click', () => {
- loadResearchHistory();
- });
- }
- }
-
- // Add a fallback in case something goes wrong and the history list is still empty
- setTimeout(() => {
- if (historyList.innerHTML === '' || historyList.innerHTML.includes('loading-spinner')) {
- console.warn('History list is still empty or showing spinner after load attempt - applying fallback');
- historyList.innerHTML = `
- <div class="error-message">
- Something went wrong while loading the history.
- </div>
- <div style="text-align: center; margin-top: 1rem;">
- <button id="fallback-retry-btn" class="btn btn-primary">
- <i class="fas fa-sync"></i> Retry
- </button>
- </div>`;
-
- const fallbackRetryBtn = document.getElementById('fallback-retry-btn');
- if (fallbackRetryBtn) {
- fallbackRetryBtn.addEventListener('click', () => {
- loadResearchHistory();
- });
- }
- }
- }, 5000); // Check after 5 seconds
- }
-
- // Function to navigate to research progress
- function navigateToResearchProgress(research) {
- document.getElementById('current-query').textContent = research.query;
- document.getElementById('progress-fill').style.width = `${research.progress || 0}%`;
- document.getElementById('progress-percentage').textContent = `${research.progress || 0}%`;
-
- // Navigate to progress page
- switchPage('research-progress');
-
- // Connect to socket for this research
- window.connectToResearchSocket(research.id);
-
- // Start polling for status
- pollResearchStatus(research.id);
- }
-
- // Function to delete a research record
- async function deleteResearch(researchId) {
- try {
- const response = await fetch(getApiUrl(`/api/research/${researchId}/delete`), {
- method: 'DELETE'
- });
-
- if (response.ok) {
- // Reload the history
- loadResearchHistory();
- } else {
- alert('Failed to delete research. Please try again.');
- }
- } catch (error) {
- console.error('Error deleting research:', error);
- alert('An error occurred while deleting the research.');
- }
- }
-
- // Function to load a specific research result
- async function loadResearch(researchId) {
- // Navigate to results page
- switchPage('research-results');
-
- const resultsContent = document.getElementById('results-content');
- resultsContent.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';
-
- try {
- // Load research details
- const detailsResponse = await fetch(getApiUrl(`/api/research/${researchId}`));
- const details = await detailsResponse.json();
-
- // Display metadata
- document.getElementById('result-query').textContent = details.query;
-
- // Format date with duration if available
- let dateText = formatDate(new Date(details.completed_at || details.created_at));
- if (details.duration_seconds) {
- // Format duration
- let durationText = '';
- const duration = parseInt(details.duration_seconds);
-
- if (duration < 60) { // less than a minute
- durationText = `${duration}s`;
- } else if (duration < 3600) { // less than an hour
- durationText = `${Math.floor(duration / 60)}m ${duration % 60}s`;
- } else { // hours
- durationText = `${Math.floor(duration / 3600)}h ${Math.floor((duration % 3600) / 60)}m`;
- }
-
- dateText += ` (Duration: ${durationText})`;
- }
- document.getElementById('result-date').textContent = dateText;
-
- document.getElementById('result-mode').textContent = details.mode === 'quick' ? 'Quick Summary' : 'Detailed Report';
-
- // Load the report content
- const reportResponse = await fetch(getApiUrl(`/api/report/${researchId}`));
- const reportData = await reportResponse.json();
-
- if (reportData.status === 'success') {
- // Render markdown
- const renderedContent = marked.parse(reportData.content);
- resultsContent.innerHTML = renderedContent;
-
- // Apply syntax highlighting
- document.querySelectorAll('pre code').forEach((block) => {
- hljs.highlightElement(block);
- });
- } else {
- resultsContent.innerHTML = '<div class="error-message">Error loading report. Please try again later.</div>';
- }
- } catch (error) {
- console.error('Error loading research:', error);
- resultsContent.innerHTML = '<div class="error-message">Error loading research results. Please try again later.</div>';
- }
- }
-
- // Function to load research details page
- async function loadResearchDetails(researchId) {
- // Navigate to details page
- switchPage('research-details');
-
- // Initialize the research log area
- const researchLog = document.getElementById('research-log');
- researchLog.innerHTML = '<div class="loading-spinner centered"><div class="spinner"></div></div>';
-
- try {
- // Load research details
- const response = await fetch(getApiUrl(`/api/research/${researchId}/details`));
- console.log('Research details API response status:', response.status);
-
- if (!response.ok) {
- console.error('API error:', response.status, response.statusText);
- researchLog.innerHTML = `<div class="error-message">Error loading research details. Status: ${response.status}</div>`;
- return;
- }
-
- const data = await response.json();
- console.log('Research details data:', data);
-
- if (data.status !== 'success') {
- researchLog.innerHTML = `<div class="error-message">Error loading research details: ${data.message || 'Unknown error'}</div>`;
- return;
- }
-
- // Display metadata
- document.getElementById('detail-query').textContent = data.query || 'N/A';
- document.getElementById('detail-status').textContent = capitalizeFirstLetter(data.status || 'unknown');
- document.getElementById('detail-status').className = `metadata-value status-${data.status || 'unknown'}`;
- document.getElementById('detail-mode').textContent = (data.mode === 'quick' ? 'Quick Summary' : 'Detailed Report') || 'N/A';
-
- // Update progress bar
- const progress = data.progress || 0;
- document.getElementById('detail-progress-fill').style.width = `${progress}%`;
- document.getElementById('detail-progress-percentage').textContent = `${progress}%`;
-
- // Render log entries
- renderLogEntries(data.log || []);
-
- // Connect to socket for real-time updates
- window.connectToResearchSocket(researchId);
-
- // Add appropriate actions based on research status
- const detailActions = document.getElementById('detail-actions');
- detailActions.innerHTML = '';
-
- if (data.status === 'completed') {
- const viewResultsBtn = document.createElement('button');
- viewResultsBtn.className = 'btn btn-primary';
- viewResultsBtn.innerHTML = '<i class="fas fa-eye"></i> View Results';
- viewResultsBtn.addEventListener('click', () => loadResearch(researchId));
- detailActions.appendChild(viewResultsBtn);
-
- // Add download PDF button
- const downloadPdfBtn = document.createElement('button');
- downloadPdfBtn.className = 'btn btn-outline';
- downloadPdfBtn.innerHTML = '<i class="fas fa-file-pdf"></i> Download PDF';
- downloadPdfBtn.addEventListener('click', () => generatePdfFromResearch(researchId));
- detailActions.appendChild(downloadPdfBtn);
- } else if (data.status === 'in_progress') {
- const viewProgressBtn = document.createElement('button');
- viewProgressBtn.className = 'btn btn-primary';
- viewProgressBtn.innerHTML = '<i class="fas fa-sync"></i> View Live Progress';
- viewProgressBtn.addEventListener('click', () => {
- document.getElementById('current-query').textContent = data.query || '';
-
- // Navigate to progress page
- switchPage('research-progress');
-
- // Connect to socket
- window.connectToResearchSocket(researchId);
- });
- detailActions.appendChild(viewProgressBtn);
- }
- } catch (error) {
- console.error('Error loading research details:', error);
- researchLog.innerHTML = `<div class="error-message">Error loading research details: ${error.message}</div>`;
- }
- }
-
- // Function to render log entries
- function renderLogEntries(logEntries) {
- const researchLog = document.getElementById('research-log');
- researchLog.innerHTML = '';
-
- if (!logEntries || logEntries.length === 0) {
- researchLog.innerHTML = '<div class="empty-state">No log entries available.</div>';
- return;
- }
-
- try {
- // Use a document fragment for better performance
- const fragment = document.createDocumentFragment();
- const template = document.getElementById('log-entry-template');
-
- if (!template) {
- console.error('Log entry template not found');
- researchLog.innerHTML = '<div class="error-message">Error rendering log entries: Template not found</div>';
- return;
- }
-
- logEntries.forEach(entry => {
- if (!entry) return; // Skip invalid entries
-
- try {
- const clone = document.importNode(template.content, true);
-
- // Format the timestamp
- let timeStr = 'N/A';
- try {
- if (entry.time) {
- const time = new Date(entry.time);
- timeStr = time.toLocaleTimeString();
- }
- } catch (timeErr) {
- console.warn('Error formatting time:', timeErr);
- }
-
- const timeEl = clone.querySelector('.log-entry-time');
- if (timeEl) timeEl.textContent = timeStr;
-
- // Add message with phase highlighting if available
- const messageEl = clone.querySelector('.log-entry-message');
- if (messageEl) {
- let phaseClass = '';
- if (entry.metadata && entry.metadata.phase) {
- phaseClass = `phase-${entry.metadata.phase}`;
- }
- messageEl.textContent = entry.message || 'No message';
- messageEl.classList.add(phaseClass);
- }
-
- // Add progress information if available
- const progressEl = clone.querySelector('.log-entry-progress');
- if (progressEl) {
- if (entry.progress !== null && entry.progress !== undefined) {
- progressEl.textContent = `Progress: ${entry.progress}%`;
- } else {
- progressEl.textContent = '';
- }
- }
-
- fragment.appendChild(clone);
- } catch (entryError) {
- console.error('Error processing log entry:', entryError, entry);
- // Continue with other entries
- }
- });
-
- researchLog.appendChild(fragment);
-
- // Scroll to the bottom
- researchLog.scrollTop = researchLog.scrollHeight;
- } catch (error) {
- console.error('Error rendering log entries:', error);
- researchLog.innerHTML = '<div class="error-message">Error rendering log entries. Please try again later.</div>';
- }
-
- // Connect to socket for updates if this is an in-progress research
- if (research && research.status === 'in_progress') {
- window.connectToResearchSocket(researchId);
- }
- }
-
- // Function to update detail log with a new entry
- function updateDetailLogEntry(logEntry) {
- if (!logEntry || !document.getElementById('research-details').classList.contains('active')) {
- return;
- }
-
- const researchLog = document.getElementById('research-log');
- const template = document.getElementById('log-entry-template');
- const clone = document.importNode(template.content, true);
-
- // Format the timestamp
- const time = new Date(logEntry.time);
- clone.querySelector('.log-entry-time').textContent = time.toLocaleTimeString();
-
- // Add message with phase highlighting if available
- const messageEl = clone.querySelector('.log-entry-message');
- let phaseClass = '';
- if (logEntry.metadata && logEntry.metadata.phase) {
- phaseClass = `phase-${logEntry.metadata.phase}`;
- }
- messageEl.textContent = logEntry.message;
- messageEl.classList.add(phaseClass);
-
- // Add progress information if available
- const progressEl = clone.querySelector('.log-entry-progress');
- if (logEntry.progress !== null && logEntry.progress !== undefined) {
- progressEl.textContent = `Progress: ${logEntry.progress}%`;
-
- // Also update the progress bar in the details view
- document.getElementById('detail-progress-fill').style.width = `${logEntry.progress}%`;
- document.getElementById('detail-progress-percentage').textContent = `${logEntry.progress}%`;
- } else {
- progressEl.textContent = '';
- }
-
- researchLog.appendChild(clone);
-
- // Scroll to the bottom
- researchLog.scrollTop = researchLog.scrollHeight;
- }
-
- // Back to history button handlers
- document.getElementById('back-to-history').addEventListener('click', () => {
- const historyNav = Array.from(navItems).find(item => item.getAttribute('data-page') === 'history');
- historyNav.click();
- });
-
- document.getElementById('back-to-history-from-details').addEventListener('click', () => {
- const historyNav = Array.from(navItems).find(item => item.getAttribute('data-page') === 'history');
- historyNav.click();
- });
-
- // Helper functions
- function capitalizeFirstLetter(string) {
- return string.charAt(0).toUpperCase() + string.slice(1);
- }
-
- function formatDate(date) {
- // Ensure we're handling the date properly
- if (!(date instanceof Date) || isNaN(date)) {
- console.warn('Invalid date provided to formatDate:', date);
- return 'Invalid date';
- }
-
- // Get current year to compare with date year
- const currentYear = new Date().getFullYear();
- const dateYear = date.getFullYear();
-
- // Get month name, day, and time
- const month = date.toLocaleString('en-US', { month: 'short' });
- const day = date.getDate();
- const hours = date.getHours().toString().padStart(2, '0');
- const minutes = date.getMinutes().toString().padStart(2, '0');
-
- // Format like "Feb 25, 08:09" or "Feb 25, 2022, 08:09" if not current year
- if (dateYear === currentYear) {
- return `${month} ${day}, ${hours}:${minutes}`;
- } else {
- return `${month} ${day}, ${dateYear}, ${hours}:${minutes}`;
- }
- }
-
- // Function to update progress UI from current research
- function updateProgressFromCurrentResearch() {
- if (!isResearchInProgress || !currentResearchId) return;
-
- // Fetch current status
- fetch(getApiUrl(`/api/research/${currentResearchId}`))
- .then(response => response.json())
- .then(data => {
- document.getElementById('current-query').textContent = data.query || '';
- document.getElementById('progress-fill').style.width = `${data.progress || 0}%`;
- document.getElementById('progress-percentage').textContent = `${data.progress || 0}%`;
-
- // Connect to socket for this research
- window.connectToResearchSocket(currentResearchId);
- })
- .catch(error => {
- console.error('Error fetching research status:', error);
- });
- }
-
- // Function to update the sidebar navigation based on research status
- function updateNavigationBasedOnResearchStatus() {
- // Get nav items for each update to ensure we have fresh references
- const navItems = document.querySelectorAll('.sidebar-nav li');
- const mobileNavItems = document.querySelectorAll('.mobile-tab-bar li');
- // Get all pages
- const pages = document.querySelectorAll('.page');
-
- const newResearchNav = Array.from(navItems).find(item =>
- item.getAttribute('data-page') === 'new-research' ||
- (item.getAttribute('data-original-page') === 'new-research' &&
- item.getAttribute('data-page') === 'research-progress')
- );
-
- if (newResearchNav) {
- if (isResearchInProgress) {
- // Change text to "Research in Progress"
- newResearchNav.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Research in Progress';
-
- // Also update the listener to navigate to progress page
- if (newResearchNav.getAttribute('data-page') !== 'research-progress') {
- newResearchNav.setAttribute('data-original-page', 'new-research');
- newResearchNav.setAttribute('data-page', 'research-progress');
- }
-
- // If on new-research page, redirect to research-progress
- if (document.getElementById('new-research').classList.contains('active')) {
- pages.forEach(page => page.classList.remove('active'));
- document.getElementById('research-progress').classList.add('active');
-
- // Update the research progress page
- updateProgressFromCurrentResearch();
- }
- } else {
- // Reset to "New Research" if there's no active research
- newResearchNav.innerHTML = '<i class="fas fa-search"></i> New Research';
-
- // Reset the listener
- if (newResearchNav.hasAttribute('data-original-page')) {
- newResearchNav.setAttribute('data-page', newResearchNav.getAttribute('data-original-page'));
- newResearchNav.removeAttribute('data-original-page');
- }
-
- // If the terminate button is visible, hide it
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- terminateBtn.style.display = 'none';
- terminateBtn.disabled = false;
- terminateBtn.innerHTML = '<i class="fas fa-stop-circle"></i> Terminate Research';
- }
- }
-
- // Make sure the navigation highlights the correct item
- navItems.forEach(item => {
- if (item === newResearchNav) {
- if (isResearchInProgress) {
- if (document.getElementById('research-progress').classList.contains('active')) {
- item.classList.add('active');
- }
- } else if (document.getElementById('new-research').classList.contains('active')) {
- item.classList.add('active');
- }
- }
- });
- }
-
- // Connect to socket for updates
- window.connectToResearchSocket(currentResearchId);
- }
-
- // Function to update the research progress page from nav click
- function updateProgressPage() {
- if (!isResearchInProgress || !currentResearchId) {
- return;
- }
-
- // Update the progress page
- fetch(getApiUrl(`/api/research/${currentResearchId}`))
- .then(response => response.json())
- .then(data => {
- // Update the query display
- document.getElementById('current-query').textContent = data.query;
-
- // Update the progress bar
- updateProgressUI(data.progress || 0, data.status);
-
- // Connect to socket for live updates
- window.connectToResearchSocket(currentResearchId);
-
- // Check if we need to show the terminate button
- if (data.status === 'in_progress') {
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- terminateBtn.style.display = 'inline-flex';
- terminateBtn.disabled = false;
- }
- }
- })
- .catch(error => {
- console.error('Error fetching research status:', error);
- });
- }
-
- // Function to update a specific history item without reloading the whole list
- function updateHistoryItemStatus(researchId, status, statusText) {
- const historyList = document.getElementById('history-list');
-
- // Look for the item in the active research banner
- const activeBanner = historyList.querySelector(`.active-research-banner[data-research-id="${researchId}"]`);
- if (activeBanner) {
- const statusEl = activeBanner.querySelector('.history-item-status');
- if (statusEl) {
- statusEl.textContent = statusText || capitalizeFirstLetter(status);
- statusEl.className = 'history-item-status';
- statusEl.classList.add(`status-${status}`);
- }
-
- // Update buttons
- const terminateBtn = activeBanner.querySelector('.terminate-btn');
- if (terminateBtn) {
- terminateBtn.style.display = 'none';
- }
-
- const viewProgressBtn = activeBanner.querySelector('.view-progress-btn');
- if (viewProgressBtn) {
- if (status === 'suspended') {
- viewProgressBtn.innerHTML = '<i class="fas fa-pause-circle"></i> Suspended';
- } else if (status === 'failed') {
- viewProgressBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Failed';
- }
- viewProgressBtn.disabled = true;
- }
-
- return;
- }
-
- // Look for the item in the regular list
- const historyItem = historyList.querySelector(`.history-item[data-research-id="${researchId}"]`);
- if (historyItem) {
- const statusEl = historyItem.querySelector('.history-item-status');
- if (statusEl) {
- statusEl.textContent = statusText || capitalizeFirstLetter(status);
- statusEl.className = 'history-item-status';
- statusEl.classList.add(`status-${status}`);
- }
-
- // Update view button
- const viewBtn = historyItem.querySelector('.view-btn');
- if (viewBtn) {
- if (status === 'suspended') {
- viewBtn.innerHTML = '<i class="fas fa-pause-circle"></i> Suspended';
- viewBtn.disabled = true;
- } else if (status === 'failed') {
- viewBtn.innerHTML = '<i class="fas fa-exclamation-triangle"></i> Failed';
- viewBtn.disabled = true;
- }
- }
- }
- }
-
- // PDF Generation Functions
- function generatePdf() {
- const resultsContent = document.getElementById('results-content');
- const query = document.getElementById('result-query').textContent;
- const date = document.getElementById('result-date').textContent;
- const mode = document.getElementById('result-mode').textContent;
-
- // Show loading indicator
- const loadingIndicator = document.createElement('div');
- loadingIndicator.className = 'loading-spinner centered';
- loadingIndicator.innerHTML = '<div class="spinner"></div><p style="margin-top: 10px;">Generating PDF...</p>';
- resultsContent.parentNode.insertBefore(loadingIndicator, resultsContent);
- resultsContent.style.display = 'none';
-
- // Create a clone of the content for PDF generation
- const contentClone = resultsContent.cloneNode(true);
- contentClone.style.display = 'block';
- contentClone.style.position = 'absolute';
- contentClone.style.left = '-9999px';
- contentClone.style.width = '800px';
-
- // Apply PDF-specific styling for better readability
- contentClone.style.background = '#ffffff';
- contentClone.style.color = '#333333';
- contentClone.style.padding = '20px';
-
- // Improve visibility by adjusting styles specifically for PDF
- const applyPdfStyles = (element) => {
- // Set all text to dark color for better readability on white background
- element.querySelectorAll('*').forEach(el => {
- // Skip elements that already have inline color styles
- if (!el.style.color) {
- el.style.color = '#333333';
- }
-
- // Fix background colors
- if (el.style.backgroundColor &&
- (el.style.backgroundColor.includes('var(--bg') ||
- el.style.backgroundColor.includes('#121212') ||
- el.style.backgroundColor.includes('#1e1e2d') ||
- el.style.backgroundColor.includes('#2a2a3a'))) {
- el.style.backgroundColor = '#f8f8f8';
- }
-
- // Handle code blocks specifically
- if (el.tagName === 'PRE' || el.tagName === 'CODE') {
- el.style.backgroundColor = '#f5f5f5';
- el.style.border = '1px solid #e0e0e0';
- el.style.color = '#333333';
- }
-
- // Make links visible
- if (el.tagName === 'A') {
- el.style.color = '#0066cc';
- el.style.textDecoration = 'underline';
- }
- });
-
- // Fix specific syntax highlighting elements for PDF
- element.querySelectorAll('.hljs').forEach(hljs => {
- hljs.style.backgroundColor = '#f8f8f8';
- hljs.style.color = '#333333';
-
- // Fix common syntax highlighting colors for PDF
- hljs.querySelectorAll('.hljs-keyword').forEach(el => el.style.color = '#0000cc');
- hljs.querySelectorAll('.hljs-string').forEach(el => el.style.color = '#008800');
- hljs.querySelectorAll('.hljs-number').forEach(el => el.style.color = '#aa0000');
- hljs.querySelectorAll('.hljs-comment').forEach(el => el.style.color = '#888888');
- hljs.querySelectorAll('.hljs-function').forEach(el => el.style.color = '#880000');
- });
- };
-
- document.body.appendChild(contentClone);
-
- // Apply PDF-specific styles
- applyPdfStyles(contentClone);
-
- // Add title and metadata to the PDF content
- const headerDiv = document.createElement('div');
- headerDiv.innerHTML = `
- <h1 style="color: #6e4ff6; font-size: 24px; margin-bottom: 10px;">${query}</h1>
- <div style="margin-bottom: 20px; font-size: 14px; color: #666;">
- <p><strong>Generated:</strong> ${date}</p>
- <p><strong>Mode:</strong> ${mode}</p>
- <p><strong>Source:</strong> Deep Research Lab</p>
- </div>
- <hr style="margin-bottom: 20px; border: 1px solid #eee;">
- `;
- contentClone.insertBefore(headerDiv, contentClone.firstChild);
-
- setTimeout(() => {
- try {
- // Use window.jspdf which is from the UMD bundle
- const { jsPDF } = window.jspdf;
- const pdf = new jsPDF('p', 'pt', 'a4');
- const pdfWidth = pdf.internal.pageSize.getWidth();
- const pdfHeight = pdf.internal.pageSize.getHeight();
- const margin = 40;
- const contentWidth = pdfWidth - 2 * margin;
-
- // Create a more efficient PDF generation approach that keeps text selectable
- const generateTextBasedPDF = async () => {
- try {
- // Get all text elements and handle them differently than images and special content
- // Use html2canvas only for complex elements that can't be easily converted to text
- const elements = Array.from(contentClone.children);
- let currentY = margin;
- let pageNum = 1;
-
- // Function to add a page with header
- const addPageWithHeader = (pageNum) => {
- if (pageNum > 1) {
- pdf.addPage();
- }
- pdf.setFontSize(8);
- pdf.setTextColor(100, 100, 100);
- pdf.text(`Deep Research - ${query} - Page ${pageNum}`, margin, pdfHeight - 20);
- };
-
- addPageWithHeader(pageNum);
-
- // Process each element - for better quality combine text-based approach with canvas
- for (const element of elements) {
- // Simple text content can be handled directly by jsPDF
- if (element.tagName === 'P' && !element.querySelector('img, canvas, svg, code, pre')) {
- // Extract and add text content directly
- pdf.setFontSize(11);
- pdf.setTextColor(0, 0, 0);
-
- const text = element.textContent.trim();
- const textLines = pdf.splitTextToSize(text, contentWidth);
-
- // Check if we need a new page
- if (currentY + (textLines.length * 14) > pdfHeight - margin) {
- pageNum++;
- addPageWithHeader(pageNum);
- currentY = margin;
- }
-
- pdf.text(textLines, margin, currentY + 12);
- currentY += (textLines.length * 14) + 10;
- }
- // Handle headings differently to maintain hierarchy
- else if (['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(element.tagName)) {
- // Extract and add heading text directly
- const fontSize = {
- 'H1': 24,
- 'H2': 20,
- 'H3': 16,
- 'H4': 14,
- 'H5': 12,
- 'H6': 11
- }[element.tagName];
-
- pdf.setFontSize(fontSize);
- pdf.setTextColor(0, 0, 0);
-
- const text = element.textContent.trim();
- const textLines = pdf.splitTextToSize(text, contentWidth);
-
- // Check if we need a new page
- if (currentY + (textLines.length * (fontSize + 4)) > pdfHeight - margin) {
- pageNum++;
- addPageWithHeader(pageNum);
- currentY = margin;
- }
-
- pdf.text(textLines, margin, currentY + fontSize);
- currentY += (textLines.length * (fontSize + 4)) + 10;
- }
- // For complex elements like code, tables, images etc. use html2canvas
- else {
- const canvas = await html2canvas(element, {
- scale: 2, // Higher scale for better quality
- useCORS: true,
- logging: false,
- backgroundColor: '#FFFFFF'
- });
-
- const imgData = canvas.toDataURL('image/png');
- const imgHeight = (canvas.height * contentWidth) / canvas.width;
-
- // Check if we need a new page
- if (currentY + imgHeight > pdfHeight - margin) {
- pageNum++;
- addPageWithHeader(pageNum);
- currentY = margin;
- }
-
- // Add image to PDF
- pdf.addImage(imgData, 'PNG', margin, currentY, contentWidth, imgHeight);
- currentY += imgHeight + 10;
- }
- }
-
- // Download the PDF
- const filename = `${query.replace(/[^a-z0-9]/gi, '_').substring(0, 30).toLowerCase()}_research.pdf`;
- pdf.save(filename);
-
- // Clean up
- document.body.removeChild(contentClone);
- resultsContent.style.display = 'block';
- loadingIndicator.remove();
- } catch (error) {
- console.error('Error generating PDF:', error);
- alert('An error occurred while generating the PDF. Please try again.');
- document.body.removeChild(contentClone);
- resultsContent.style.display = 'block';
- loadingIndicator.remove();
- }
- };
-
- generateTextBasedPDF();
- } catch (error) {
- console.error('Error initializing PDF generation:', error);
- alert('An error occurred while preparing the PDF. Please try again.');
- document.body.removeChild(contentClone);
- resultsContent.style.display = 'block';
- loadingIndicator.remove();
- }
- }, 100);
- }
-
- // Function to generate PDF from a specific research ID
- async function generatePdfFromResearch(researchId) {
- try {
- // Load research details
- const detailsResponse = await fetch(getApiUrl(`/api/research/${researchId}`));
- const details = await detailsResponse.json();
-
- // Load the report content
- const reportResponse = await fetch(getApiUrl(`/api/report/${researchId}`));
- const reportData = await reportResponse.json();
-
- if (reportData.status === 'success') {
- // Create a temporary container to render the content
- const tempContainer = document.createElement('div');
- tempContainer.className = 'results-content pdf-optimized';
- tempContainer.style.display = 'none';
- document.body.appendChild(tempContainer);
-
- // Render markdown with optimized styles for PDF
- const renderedContent = marked.parse(reportData.content);
- tempContainer.innerHTML = renderedContent;
-
- // Apply syntax highlighting
- tempContainer.querySelectorAll('pre code').forEach((block) => {
- hljs.highlightElement(block);
- });
-
- // Format date
- let dateText = formatDate(new Date(details.completed_at || details.created_at));
- if (details.duration_seconds) {
- let durationText = '';
- const duration = parseInt(details.duration_seconds);
-
- if (duration < 60) {
- durationText = `${duration}s`;
- } else if (duration < 3600) {
- durationText = `${Math.floor(duration / 60)}m ${duration % 60}s`;
- } else {
- durationText = `${Math.floor(duration / 3600)}h ${Math.floor((duration % 3600) / 60)}m`;
- }
-
- dateText += ` (Duration: ${durationText})`;
- }
-
- // Set up data for PDF generation
- document.getElementById('result-query').textContent = details.query;
- document.getElementById('result-date').textContent = dateText;
- document.getElementById('result-mode').textContent = details.mode === 'quick' ? 'Quick Summary' : 'Detailed Report';
-
- // Replace the current content with our temporary content
- const resultsContent = document.getElementById('results-content');
- const originalContent = resultsContent.innerHTML;
- resultsContent.innerHTML = tempContainer.innerHTML;
-
- // Generate the PDF
- generatePdf();
-
- // Restore original content if we're not on the results page
- setTimeout(() => {
- if (!document.getElementById('research-results').classList.contains('active')) {
- resultsContent.innerHTML = originalContent;
- }
- document.body.removeChild(tempContainer);
- }, 500);
-
- } else {
- alert('Error loading report. Could not generate PDF.');
- }
- } catch (error) {
- console.error('Error generating PDF:', error);
- alert('An error occurred while generating the PDF. Please try again.');
- }
- }
-
- // Initialize the terminate button event listener
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- terminateBtn.addEventListener('click', () => {
- if (confirm('Are you sure you want to terminate this research? This action cannot be undone.')) {
- if (currentResearchId) {
- terminateResearch(currentResearchId);
- }
- }
- });
- }
-
- // Initialize PDF download button
- const downloadPdfBtn = document.getElementById('download-pdf-btn');
- if (downloadPdfBtn) {
- downloadPdfBtn.addEventListener('click', generatePdf);
- }
-});
\ No newline at end of file
diff --git a/templates/index.html b/templates/index.html
deleted file mode 100644
index 9e320353e9..0000000000
--- a/templates/index.html
+++ /dev/null
@@ -1,296 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Deep Research System</title>
- <link rel="stylesheet" href="{{ url_for('research.serve_static', path='css/styles.css') }}">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
- <!-- Change to CDN version that works in browsers -->
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github-dark.min.css">
- <link rel="icon" type="image/png" href="{{ url_for('static', filename='favicon.ico') }}">
-</head>
-<body>
- <div class="app-container">
- <!-- Sidebar -->
- <aside class="sidebar">
- <div class="sidebar-header">
- <h2 id="logo-link" style="cursor: pointer;"><i class="fas fa-atom"></i> Deep Research</h2>
- </div>
- <nav class="sidebar-nav">
- <ul>
- <li class="active" data-page="new-research"><i class="fas fa-search"></i> New Research</li>
- <li data-page="history"><i class="fas fa-history"></i> History</li>
- </ul>
- </nav>
- <div class="sidebar-footer">
- <p>v0.0.1 | <i class="fas fa-brain"></i></p>
- </div>
- </aside>
-
- <!-- Main Content -->
- <main class="main-content">
- <!-- New Research Page -->
- <div class="page active" id="new-research">
- <div class="page-header">
- <h1>Start New Research</h1>
- </div>
- <div class="card research-card">
- <div class="card-content">
- <form id="research-form">
- <div class="form-group">
- <label for="query">Research Query</label>
- <textarea id="query" name="query" rows="3" placeholder="Enter your research topic or question..."></textarea>
- </div>
- <div class="form-group">
- <label>Research Mode</label>
- <div class="mode-selection">
- <div class="mode-option active" data-mode="quick">
- <div class="mode-icon"><i class="fas fa-bolt"></i></div>
- <div class="mode-info">
- <h3>Quick Summary</h3>
- <p>Generated in a few minutes</p>
- </div>
- </div>
- <div class="mode-option" data-mode="detailed">
- <div class="mode-icon"><i class="fas fa-microscope"></i></div>
- <div class="mode-info">
- <h3>Detailed Report</h3>
- <p>In-depth analysis (takes longer)</p>
- </div>
- </div>
- </div>
- </div>
- <div class="form-actions">
- <button type="submit" class="btn btn-primary" id="start-research-btn"><i class="fas fa-rocket"></i> Start Research</button>
- </div>
- </form>
- </div>
- </div>
- </div>
-
- <!-- History Page -->
- <div class="page" id="history">
- <div class="page-header">
- <h1>Research History</h1>
- </div>
- <div class="card">
- <div class="card-content">
- <div class="history-list" id="history-list">
- <!-- Will be populated dynamically -->
- <div class="loading-spinner centered">
- <div class="spinner"></div>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Research Progress Page -->
- <div class="page" id="research-progress">
- <div class="page-header">
- <h1>Research in Progress</h1>
- </div>
- <div class="card">
- <div class="card-content">
- <div class="progress-info">
- <div class="current-query-container">
- <div class="current-query-label">Current Query:</div>
- <div id="current-query" class="current-query"></div>
- </div>
- <div class="progress-container">
- <div class="progress-bar">
- <div id="progress-fill" class="progress-fill"></div>
- </div>
- <div id="progress-percentage" class="progress-percentage">0%</div>
- </div>
- <div id="progress-status" class="progress-status">Initializing research process...</div>
- <div class="progress-actions">
- <button id="terminate-research-btn" class="btn btn-outline terminate-btn" style="display: none;">
- <i class="fas fa-stop-circle"></i> Terminate Research
- </button>
- </div>
- </div>
- </div>
- </div>
- </div>
-
- <!-- Research Details Page -->
- <div class="page" id="research-details">
- <div class="page-header">
- <div class="results-header">
- <h1>Research Details</h1>
- <div class="results-actions">
- <button class="btn btn-outline" id="back-to-history-from-details"><i class="fas fa-arrow-left"></i> Back to History</button>
- </div>
- </div>
- </div>
- <div class="card">
- <div class="card-content">
- <div class="research-metadata">
- <div class="metadata-item">
- <span class="metadata-label">Query:</span>
- <span id="detail-query" class="metadata-value"></span>
- </div>
- <div class="metadata-item">
- <span class="metadata-label">Status:</span>
- <span id="detail-status" class="metadata-value"></span>
- </div>
- <div class="metadata-item">
- <span class="metadata-label">Mode:</span>
- <span id="detail-mode" class="metadata-value"></span>
- </div>
- <div class="metadata-item">
- <span class="metadata-label">Progress:</span>
- <div class="detail-progress-container">
- <div class="detail-progress-bar">
- <div class="detail-progress-fill" id="detail-progress-fill"></div>
- </div>
- <span id="detail-progress-percentage">0%</span>
- </div>
- </div>
- </div>
-
- <div class="research-log-container">
- <h3>Research Progress Log</h3>
- <div class="research-log" id="research-log">
- <!-- Will be populated dynamically -->
- <div class="loading-spinner centered">
- <div class="spinner"></div>
- </div>
- </div>
- </div>
-
- <div class="detail-actions" id="detail-actions">
- <!-- Conditionally shown based on research status -->
- </div>
- </div>
- </div>
- </div>
-
- <!-- Research Results Page -->
- <div class="page" id="research-results">
- <div class="page-header">
- <div class="results-header">
- <h1>Research Results</h1>
- <div class="results-actions">
- <button class="btn btn-outline" id="download-pdf-btn"><i class="fas fa-file-pdf"></i> Download PDF</button>
- <button class="btn btn-outline" id="back-to-history"><i class="fas fa-arrow-left"></i> Back to History</button>
- </div>
- </div>
- </div>
- <div class="card results-card">
- <div class="card-content">
- <div class="results-metadata">
- <div class="metadata-item">
- <span class="metadata-label">Query:</span>
- <span id="result-query" class="metadata-value"></span>
- </div>
- <div class="metadata-item">
- <span class="metadata-label">Generated:</span>
- <span id="result-date" class="metadata-value"></span>
- </div>
- <div class="metadata-item">
- <span class="metadata-label">Mode:</span>
- <span id="result-mode" class="metadata-value"></span>
- </div>
- </div>
- <div class="results-content" id="results-content">
- <!-- Will be populated dynamically -->
- <div class="loading-spinner centered">
- <div class="spinner"></div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </main>
- </div>
-
- <!-- Templates -->
- <template id="history-item-template">
- <div class="history-item">
- <div class="history-item-header">
- <div class="history-item-title"></div>
- <div class="history-item-status"></div>
- </div>
- <div class="history-item-meta">
- <div class="history-item-date"></div>
- <div class="history-item-mode"></div>
- </div>
- <div class="history-item-actions">
- <button class="btn btn-sm btn-outline view-btn"><i class="fas fa-eye"></i> View</button>
- <button class="btn btn-sm btn-outline pdf-btn" style="display: none;"><i class="fas fa-file-pdf"></i> PDF</button>
- <!-- Delete button will be added dynamically -->
- </div>
- </div>
- </template>
-
- <!-- Mobile Tab Bar -->
- <nav class="mobile-tab-bar">
- <ul>
- <li class="active" data-page="new-research">
- <i class="fas fa-search"></i>
- <span>Research</span>
- </li>
- <li data-page="history">
- <i class="fas fa-history"></i>
- <span>History</span>
- </li>
- </ul>
- </nav>
-
- <template id="log-entry-template">
- <div class="log-entry">
- <div class="log-entry-time"></div>
- <div class="log-entry-content">
- <div class="log-entry-message"></div>
- <div class="log-entry-progress"></div>
- </div>
- </div>
- </template>
-
- <!-- Updated Scripts with proper CDN versions -->
- <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.4.1/socket.io.min.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.umd.min.js"></script>
- <!-- Update highlight.js to browser compatible version -->
- <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
- <!-- PDF generation libraries -->
- <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js" integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
- <script src="{{ url_for('research.serve_static', path='js/app.js') }}"></script>
- <script>
- document.addEventListener('DOMContentLoaded', function() {
- // Initialize the terminate button event listener
- const terminateBtn = document.getElementById('terminate-research-btn');
- if (terminateBtn) {
- terminateBtn.addEventListener('click', function() {
- // Get the current research ID from the page
- const currentResearchId = window.currentResearchId;
- if (currentResearchId) {
- window.terminateResearch(currentResearchId);
- } else {
- console.error('No active research ID found');
- alert('No active research found to terminate');
- }
- });
- }
- });
-
- // Configure marked to not use eval
- if (typeof marked !== 'undefined') {
- marked.setOptions({
- headerIds: false,
- mangle: false,
- smartypants: false
- });
- }
-
- // Configure html2canvas to avoid using eval if possible
- if (typeof html2canvas !== 'undefined') {
- // Disable features that might use eval
- window.html2canvas_noSandbox = true;
- }
- </script>
-</body>
-</html>
\ No newline at end of file
diff --git a/utilties/enums.py b/utilties/enums.py
deleted file mode 100644
index e082679096..0000000000
--- a/utilties/enums.py
+++ /dev/null
@@ -1,9 +0,0 @@
-# config/enums.py
-from enum import Enum, auto
-
-class KnowledgeAccumulationApproach(Enum):
- QUESTION = auto()
- ITERATION = auto()
- NO_KNOWLEDGE = auto()
- MAX_NR_OF_CHARACTERS = auto()
-
diff --git a/utilties/search_utilities.py b/utilties/search_utilities.py
deleted file mode 100644
index 126c9cff43..0000000000
--- a/utilties/search_utilities.py
+++ /dev/null
@@ -1,115 +0,0 @@
-import re
-
-
-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 = []
- 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, "index": index})
- except Exception:
- continue
- 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_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 += 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
-
-def print_search_results(search_results):
- formatted_text=""
- links = extract_links_from_search_results(search_results)
- if links:
- formatted_text=format_links(links=links)
- print(formatted_text)
-
diff --git a/web_search_engines/__init__.py b/web_search_engines/__init__.py
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/web_search_engines/engines/full_search.py b/web_search_engines/engines/full_search.py
deleted file mode 100644
index 38ed1fef3e..0000000000
--- a/web_search_engines/engines/full_search.py
+++ /dev/null
@@ -1,128 +0,0 @@
-import justext
-from langchain_community.document_loaders import AsyncChromiumLoader
-from langchain_community.document_transformers import BeautifulSoupTransformer
-from langchain_core.language_models import BaseLLM
-from typing import List, Dict
-import json, os
-from utilties.search_utilities import remove_think_tags
-from datetime import datetime
-import config
-
-class FullSearchResults:
- def __init__(
- self,
- llm: BaseLLM, # Add LLM parameter
- web_search: list,
- output_format: str = "list",
- language: str = "English",
- max_results: int = 10,
- region: str = "wt-wt",
- time: str = "y",
- safesearch: str = "Moderate"
-
- ):
- self.llm = llm
- self.output_format = output_format
- self.language = language
- self.max_results = max_results
- self.region = region
- self.time = time
- self.safesearch = safesearch
- self.web_search =web_search
- os.environ["USER_AGENT"] = "Local Deep Research/1.0"
-
-
- self.bs_transformer = BeautifulSoupTransformer()
- self.tags_to_extract = ["p", "div", "span"]
-
- def check_urls(self, results: List[Dict], query: str) -> List[Dict]:
- if not results:
- return results
-
- now = datetime.now()
- current_time = now.strftime("%Y-%m-%d")
- prompt = f"""ONLY Return a JSON array. The response contains no letters. Evaluate these URLs for:
- 1. Timeliness (today: {current_time})
- 2. Factual accuracy (cross-reference major claims)
- 3. Source reliability (prefer official company websites, established news outlets)
- 4. Direct relevance to query: {query}
-
- URLs to evaluate:
- {results}
-
- Return a JSON array of indices (0-based) for sources that meet ALL criteria.
- 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 []
-
- def remove_boilerplate(self, html: str) -> str:
- 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):
- nr_full_text = 0
- # Step 1: Get search results from DuckDuckGo
- search_results = self.web_search.invoke(query)
- #print(type(search_results))
- if not isinstance(search_results, list):
- raise ValueError("Expected the search results in list format.")
-
- # Step 2: Filter URLs using LLM
- if config.QUALITY_CHECK_DDG_URLS:
- filtered_results = self.check_urls(search_results, query)
- else:
- filtered_results = search_results
-
- # Extract URLs from filtered results
- urls = [result.get("link") for result in filtered_results if result.get("link")]
- print(urls)
- if not urls:
- print("\n === NO VALID LINKS ===\n")
- return []
-
- # Step 3: Download the full HTML pages for filtered URLs
- loader = AsyncChromiumLoader(urls)
- 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 filtered result
- for result in filtered_results:
- link = result.get("link")
- result["full_content"] = url_to_content.get(link, None)
-
- 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)
\ No newline at end of file
diff --git a/web_search_engines/engines/meta_search_engine.py b/web_search_engines/engines/meta_search_engine.py
deleted file mode 100644
index 3152697897..0000000000
--- a/web_search_engines/engines/meta_search_engine.py
+++ /dev/null
@@ -1,274 +0,0 @@
-import logging
-import os
-from typing import Dict, List, Any, Optional
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-from web_search_engines.search_engines_config import SEARCH_ENGINES
-from web_search_engines.search_engine_factory import create_search_engine
-from web_search_engines.engines.search_engine_wikipedia import WikipediaSearchEngine
-import config
-
-# Setup logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-
-class MetaSearchEngine(BaseSearchEngine):
- """
- LLM-powered meta search engine that intelligently selects and uses
- the appropriate search engines based on query analysis
- """
-
- def __init__(self,
- llm,
- max_results: int = 10,
- use_api_key_services: bool = True,
- max_engines_to_try: int = 3,
- max_filtered_results: Optional[int] = None,
- **kwargs):
- """
- Initialize the meta search engine.
-
- Args:
- llm: Language model instance for query classification and relevance filtering
- max_results: Maximum number of search results to return
- use_api_key_services: Whether to include services that require API keys
- max_engines_to_try: Maximum number of engines to try before giving up
- max_filtered_results: Maximum number of results to keep after filtering
- **kwargs: Additional parameters (ignored but accepted for compatibility)
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.use_api_key_services = use_api_key_services
- self.max_engines_to_try = max_engines_to_try
-
- # Cache for engine instances
- self.engine_cache = {}
-
- # Get available engines (excluding 'meta' and 'auto')
- self.available_engines = self._get_available_engines()
- logger.info(f"Meta Search Engine initialized with {len(self.available_engines)} available engines: {', '.join(self.available_engines)}")
-
- # Create a fallback engine in case everything else fails
- self.fallback_engine = WikipediaSearchEngine(
- max_results=max_results,
- llm=llm,
- max_filtered_results=max_filtered_results
- )
-
- def _get_available_engines(self) -> List[str]:
- """Get list of available engines, excluding 'meta' and 'auto'"""
- # Filter out 'meta' and 'auto' and check API key availability
- available = []
- for name, config in SEARCH_ENGINES.items():
- if name in ["meta", "auto"]:
- continue
-
- if config.get("requires_api_key", False) and not self.use_api_key_services:
- continue
-
- if config.get("requires_api_key", False):
- api_key_env = config.get("api_key_env")
- api_key = os.getenv(api_key_env) if api_key_env else None
- if not api_key:
- continue
-
- available.append(name)
-
- # Make sure we have at least one engine available
- if not available and "wikipedia" in SEARCH_ENGINES:
- available.append("wikipedia")
-
- return available
-
- def analyze_query(self, query: str) -> List[str]:
- """
- Use the LLM to analyze the query and return a ranked list of
- recommended search engines to try
- """
- if not self.available_engines:
- logger.warning("No search engines available")
- return []
-
- # Create engine descriptions for the prompt
- engine_descriptions = "\n".join([
- f"- {name.upper()}: Good for {', '.join(SEARCH_ENGINES[name]['strengths'][:3])}. "
- f"Weaknesses: {', '.join(SEARCH_ENGINES[name]['weaknesses'][:2])}. "
- f"Reliability: {SEARCH_ENGINES[name]['reliability']*100:.0f}%"
- for name in self.available_engines
- ])
-
- prompt = f"""Analyze this search query and rank the available search engines in order of most to least appropriate for answering it.
-
-Query: "{query}"
-
-Available search engines:
-{engine_descriptions}
-
-Consider:
-1. The nature of the query (factual, academic, product-related, news, etc.)
-2. The strengths and weaknesses of each engine
-3. The reliability of each engine
-
-Return ONLY a comma-separated list of search engine names in your recommended order. Example: "wikipedia,arxiv,duckduckgo"
-Do not include any engines that are not listed above. Only return the comma-separated list, nothing else."""
-
- # Get response from LLM
- try:
- response = self.llm.invoke(prompt)
- content = response.content.strip()
-
- # Parse the response into a list of engine names
- engine_names = [name.strip().lower() for name in content.split(',')]
-
- # Filter out any invalid engine names
- valid_engines = [name for name in engine_names if name in self.available_engines]
-
- # If no valid engines were returned, use default order based on reliability
- if not valid_engines:
- valid_engines = sorted(
- self.available_engines,
- key=lambda x: SEARCH_ENGINES[x]["reliability"],
- reverse=True
- )
-
- return valid_engines
- except Exception as e:
- logger.error(f"Error analyzing query with LLM: {str(e)}")
- # Fall back to reliability-based ordering
- return sorted(
- self.available_engines,
- key=lambda x: SEARCH_ENGINES[x]["reliability"],
- reverse=True
- )
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information by selecting the best search engine for this query.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- # Get ranked list of engines for this query
- ranked_engines = self.analyze_query(query)
-
- if not ranked_engines:
- logger.warning("No suitable search engines found for query, using fallback engine")
- return self.fallback_engine._get_previews(query)
-
- # Limit the number of engines to try
- engines_to_try = ranked_engines[:self.max_engines_to_try]
-
- logger.info(f"Search plan created. Will try these engines in order: {', '.join(engines_to_try)}")
-
- all_errors = []
- # Try each engine in order
- for engine_name in engines_to_try:
- logger.info(f"Trying search engine: {engine_name}")
-
- # Get or create the engine instance
- engine = self._get_engine_instance(engine_name)
-
- if not engine:
- logger.warning(f"Failed to initialize {engine_name}, skipping")
- all_errors.append(f"Failed to initialize {engine_name}")
- continue
-
- try:
- # Get previews from this engine
- previews = engine._get_previews(query)
-
- # If search was successful, return results
- if previews and len(previews) > 0:
- logger.info(f"Successfully got {len(previews)} preview results from {engine_name}")
- # Store selected engine for later use
- self._selected_engine = engine
- self._selected_engine_name = engine_name
- return previews
-
- logger.info(f"{engine_name} returned no previews")
- all_errors.append(f"{engine_name} returned no previews")
-
- except Exception as e:
- error_msg = f"Error getting previews from {engine_name}: {str(e)}"
- logger.error(error_msg)
- all_errors.append(error_msg)
-
- # If we reach here, all engines failed, use fallback
- logger.warning(f"All engines failed or returned no preview results: {', '.join(all_errors)}")
- logger.info("Using fallback Wikipedia engine for previews")
- self._selected_engine = self.fallback_engine
- self._selected_engine_name = "wikipedia"
- return self.fallback_engine._get_previews(query)
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content using the engine that provided the previews.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should get full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info("Getting full content for relevant items")
-
- # Use the selected engine to get full content
- if hasattr(self, '_selected_engine'):
- try:
- logger.info(f"Using {self._selected_engine_name} to get full content")
- return self._selected_engine._get_full_content(relevant_items)
- except Exception as e:
- logger.error(f"Error getting full content from {self._selected_engine_name}: {str(e)}")
- # Fall back to returning relevant items without full content
- return relevant_items
- else:
- logger.warning("No engine was selected during preview phase, returning relevant items as-is")
- return relevant_items
-
- def _get_engine_instance(self, engine_name: str) -> Optional[BaseSearchEngine]:
- """Get or create an instance of the specified search engine"""
- # Return cached instance if available
- if engine_name in self.engine_cache:
- return self.engine_cache[engine_name]
-
- # Create a new instance
- engine = None
- try:
- # Only pass parameters that all engines accept
- common_params = {
- "llm": self.llm,
- "max_results": self.max_results
- }
-
- # Add max_filtered_results if specified
- if self.max_filtered_results is not None:
- common_params["max_filtered_results"] = self.max_filtered_results
-
- engine = create_search_engine(
- engine_name,
- **common_params
- )
- except Exception as e:
- logger.error(f"Error creating engine instance for {engine_name}: {str(e)}")
- return None
-
- if engine:
- # Cache the instance
- self.engine_cache[engine_name] = engine
-
- return engine
-
- def invoke(self, query: str) -> List[Dict[str, Any]]:
- """Compatibility method for LangChain tools"""
- return self.run(query)
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_arxiv.py b/web_search_engines/engines/search_engine_arxiv.py
deleted file mode 100644
index 2f40057634..0000000000
--- a/web_search_engines/engines/search_engine_arxiv.py
+++ /dev/null
@@ -1,362 +0,0 @@
-from typing import Dict, List, Any, Optional
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-import arxiv
-
-class ArXivSearchEngine(BaseSearchEngine):
- """arXiv search engine implementation with two-phase approach"""
-
- def __init__(self,
- max_results: int = 10,
- sort_by: str = "relevance",
- sort_order: str = "descending",
- include_full_text: bool = False,
- download_dir: Optional[str] = None,
- max_full_text: int = 1,
- llm: Optional[BaseLLM] = None,
- max_filtered_results: Optional[int] = None): # Added this parameter
- """
- Initialize the arXiv search engine.
-
- Args:
- max_results: Maximum number of search results
- sort_by: Sorting criteria ('relevance', 'lastUpdatedDate', or 'submittedDate')
- sort_order: Sort order ('ascending' or 'descending')
- include_full_text: Whether to include full paper content in results (downloads PDF)
- download_dir: Directory to download PDFs to (if include_full_text is True)
- max_full_text: Maximum number of PDFs to download and process (default: 1)
- llm: Language model for relevance filtering
- max_filtered_results: Maximum number of results to keep after filtering
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.sort_by = sort_by
- self.sort_order = sort_order
- self.include_full_text = include_full_text
- self.download_dir = download_dir
- self.max_full_text = max_full_text
-
- # Map sort parameters to arxiv package parameters
- self.sort_criteria = {
- 'relevance': arxiv.SortCriterion.Relevance,
- 'lastUpdatedDate': arxiv.SortCriterion.LastUpdatedDate,
- 'submittedDate': arxiv.SortCriterion.SubmittedDate
- }
-
- self.sort_directions = {
- 'ascending': arxiv.SortOrder.Ascending,
- 'descending': arxiv.SortOrder.Descending
- }
-
- def _get_search_results(self, query: str) -> List[Any]:
- """
- Helper method to get search results from arXiv API.
-
- Args:
- query: The search query
-
- Returns:
- List of arXiv paper objects
- """
- # Configure the search client
- sort_criteria = self.sort_criteria.get(self.sort_by, arxiv.SortCriterion.Relevance)
- sort_order = self.sort_directions.get(self.sort_order, arxiv.SortOrder.Descending)
-
- # Create the search client
- client = arxiv.Client()
-
- # Create the search query
- search = arxiv.Search(
- query=query,
- max_results=self.max_results,
- sort_by=sort_criteria,
- sort_order=sort_order
- )
-
- # Get the search results
- papers = list(client.results(search))
-
- return papers
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information for arXiv papers.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- print("Getting paper previews from arXiv")
-
- try:
- # Get search results from arXiv
- papers = self._get_search_results(query)
-
- # Store the paper objects for later use
- self._papers = {paper.entry_id: paper for paper in papers}
-
- # Format results as previews with basic information
- previews = []
- for paper in papers:
- preview = {
- "id": paper.entry_id, # Use entry_id as ID
- "title": paper.title,
- "link": paper.entry_id, # arXiv URL
- "snippet": paper.summary[:250] + "..." if len(paper.summary) > 250 else paper.summary,
- "authors": [author.name for author in paper.authors[:3]], # First 3 authors
- "published": paper.published.strftime("%Y-%m-%d") if paper.published else None
- }
-
- previews.append(preview)
-
- return previews
-
- except Exception as e:
- print(f"Error getting arXiv previews: {e}")
- return []
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant arXiv papers.
- Downloads PDFs and extracts text when include_full_text is True.
- Limits the number of PDFs processed to max_full_text.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should get full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- print("Getting full content for relevant arXiv papers")
-
- results = []
- pdf_count = 0 # Track number of PDFs processed
-
- for item in relevant_items:
- # Start with the preview data
- result = item.copy()
-
- # Get the paper ID
- paper_id = item.get("id")
-
- # Try to get the full paper from our cache
- paper = None
- if hasattr(self, '_papers') and paper_id in self._papers:
- paper = self._papers[paper_id]
-
- if paper:
- # Add complete paper information
- result.update({
- "pdf_url": paper.pdf_url,
- "authors": [author.name for author in paper.authors], # All authors
- "published": paper.published.strftime("%Y-%m-%d") if paper.published else None,
- "updated": paper.updated.strftime("%Y-%m-%d") if paper.updated else None,
- "categories": paper.categories,
- "summary": paper.summary, # Full summary
- "comment": paper.comment,
- "journal_ref": paper.journal_ref,
- "doi": paper.doi
- })
-
- # Default to using summary as content
- result["content"] = paper.summary
- result["full_content"] = paper.summary
-
- # Download PDF and extract text if requested and within limit
- if self.include_full_text and self.download_dir and pdf_count < self.max_full_text:
- try:
- # Download the paper
- pdf_count += 1 # Increment counter before attempting download
- paper_path = paper.download_pdf(dirpath=self.download_dir)
- result["pdf_path"] = str(paper_path)
-
- # Extract text from PDF
- try:
- # Try PyPDF2 first
- try:
- import PyPDF2
- with open(paper_path, 'rb') as pdf_file:
- pdf_reader = PyPDF2.PdfReader(pdf_file)
- pdf_text = ""
- for page in pdf_reader.pages:
- pdf_text += page.extract_text() + "\n\n"
-
- if pdf_text.strip(): # Only use if we got meaningful text
- result["content"] = pdf_text
- result["full_content"] = pdf_text
- print(f"Successfully extracted text from PDF using PyPDF2")
- except (ImportError, Exception) as e1:
- # Fall back to pdfplumber
- try:
- import pdfplumber
- with pdfplumber.open(paper_path) as pdf:
- pdf_text = ""
- for page in pdf.pages:
- pdf_text += page.extract_text() + "\n\n"
-
- if pdf_text.strip(): # Only use if we got meaningful text
- result["content"] = pdf_text
- result["full_content"] = pdf_text
- print(f"Successfully extracted text from PDF using pdfplumber")
- except (ImportError, Exception) as e2:
- print(f"PDF text extraction failed: {str(e1)}, then {str(e2)}")
- print(f"Using paper summary as content instead")
- except Exception as e:
- print(f"Error extracting text from PDF: {e}")
- print(f"Using paper summary as content instead")
- except Exception as e:
- print(f"Error downloading paper {paper.title}: {e}")
- result["pdf_path"] = None
- pdf_count -= 1 # Decrement counter if download fails
- elif self.include_full_text and self.download_dir and pdf_count >= self.max_full_text:
- # Reached PDF limit
- print(f"Maximum number of PDFs ({self.max_full_text}) reached. Skipping remaining PDFs.")
- result["content"] = paper.summary
- result["full_content"] = paper.summary
-
- results.append(result)
-
- return results
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Execute a search using arXiv with the two-phase approach.
-
- Args:
- query: The search query
-
- Returns:
- List of search results
- """
- print("---Execute a search using arXiv---")
-
- # Use the implementation from the parent class which handles all phases
- results = super().run(query)
-
- # Clean up
- if hasattr(self, '_papers'):
- del self._papers
-
- return results
-
- def get_paper_details(self, arxiv_id: str) -> Dict[str, Any]:
- """
- Get detailed information about a specific arXiv paper.
-
- Args:
- arxiv_id: arXiv ID of the paper (e.g., '2101.12345')
-
- Returns:
- Dictionary with paper information
- """
- try:
- # Create the search client
- client = arxiv.Client()
-
- # Search for the specific paper
- search = arxiv.Search(id_list=[arxiv_id], max_results=1)
-
- # Get the paper
- papers = list(client.results(search))
- if not papers:
- return {}
-
- paper = papers[0]
-
- # Format result based on config
- result = {
- "title": paper.title,
- "link": paper.entry_id,
- "snippet": paper.summary[:250] + "..." if len(paper.summary) > 250 else paper.summary,
- "authors": [author.name for author in paper.authors[:3]] # First 3 authors
- }
-
- # Add full content if not in snippet-only mode
- if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:
- result.update({
- "pdf_url": paper.pdf_url,
- "authors": [author.name for author in paper.authors], # All authors
- "published": paper.published.strftime("%Y-%m-%d") if paper.published else None,
- "updated": paper.updated.strftime("%Y-%m-%d") if paper.updated else None,
- "categories": paper.categories,
- "summary": paper.summary, # Full summary
- "comment": paper.comment,
- "journal_ref": paper.journal_ref,
- "doi": paper.doi,
- "content": paper.summary, # Use summary as content
- "full_content": paper.summary # For consistency
- })
-
- # Download PDF if requested
- if self.include_full_text and self.download_dir:
- try:
- # Download the paper
- paper_path = paper.download_pdf(dirpath=self.download_dir)
- result["pdf_path"] = str(paper_path)
- except Exception as e:
- print(f"Error downloading paper: {e}")
-
- return result
-
- except Exception as e:
- print(f"Error getting paper details: {e}")
- return {}
-
- def search_by_author(self, author_name: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for papers by a specific author.
-
- Args:
- author_name: Name of the author
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of papers by the author
- """
- original_max_results = self.max_results
-
- try:
- if max_results:
- self.max_results = max_results
-
- query = f"au:\"{author_name}\""
- return self.run(query)
-
- finally:
- # Restore original value
- self.max_results = original_max_results
-
- def search_by_category(self, category: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for papers in a specific arXiv category.
-
- Args:
- category: arXiv category (e.g., 'cs.AI', 'physics.optics')
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of papers in the category
- """
- original_max_results = self.max_results
-
- try:
- if max_results:
- self.max_results = max_results
-
- query = f"cat:{category}"
- return self.run(query)
-
- finally:
- # Restore original value
- self.max_results = original_max_results
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_brave.py b/web_search_engines/engines/search_engine_brave.py
deleted file mode 100644
index 122c87425d..0000000000
--- a/web_search_engines/engines/search_engine_brave.py
+++ /dev/null
@@ -1,245 +0,0 @@
-from langchain_community.tools import BraveSearch
-from typing import Dict, List, Any, Optional
-import os
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-
-class BraveSearchEngine(BaseSearchEngine):
- """Brave search engine implementation with two-phase approach"""
-
- def __init__(self,
- max_results: int = 10,
- region: str = "US",
- time_period: str = "y",
- safe_search: bool = True,
- search_language: str = "English",
- api_key: Optional[str] = None,
- language_code_mapping: Optional[Dict[str, str]] = None,
- llm: Optional[BaseLLM] = None,
- include_full_content: bool = False,
- max_filtered_results: Optional[int] = None,
- **kwargs):
- """
- Initialize the Brave search engine.
-
- Args:
- max_results: Maximum number of search results
- region: Region code for search results
- time_period: Time period for search results
- safe_search: Whether to enable safe search
- search_language: Language for search results
- api_key: Brave Search API key (can also be set in BRAVE_API_KEY env)
- language_code_mapping: Mapping from language names to codes
- llm: Language model for relevance filtering
- include_full_content: Whether to include full webpage content in results
- max_filtered_results: Maximum number of results to keep after filtering
- **kwargs: Additional parameters (ignored but accepted for compatibility)
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.include_full_content = include_full_content
-
- # Set up language code mapping
- if language_code_mapping is None:
- language_code_mapping = {
- "english": "en",
- "spanish": "es",
- "chinese": "zh",
- "hindi": "hi",
- "french": "fr",
- "arabic": "ar",
- "bengali": "bn",
- "portuguese": "pt",
- "russian": "ru",
- }
-
- # Get API key
- brave_api_key = api_key or os.getenv("BRAVE_API_KEY")
- if not brave_api_key:
- raise ValueError("BRAVE_API_KEY not found. Please provide api_key or set the BRAVE_API_KEY environment variable.")
-
- # Get language code
- language_code = language_code_mapping.get(search_language.lower(), "en")
-
- # Convert time period format to Brave's format
- brave_time_period = f"p{time_period}"
-
- # Convert safe search to Brave's format
- brave_safe_search = "moderate" if safe_search else "off"
-
- # Initialize Brave Search
- self.engine = BraveSearch.from_api_key(
- api_key=brave_api_key,
- search_kwargs={
- "count": min(20, max_results),
- "country": region.upper(),
- "search_lang": language_code,
- "safesearch": brave_safe_search,
- "freshness": brave_time_period,
- }
- )
-
- # Set user agent for Brave Search
- os.environ["USER_AGENT"] = "Local Deep Research/1.0"
-
- # If full content is requested, initialize FullSearchResults
- if include_full_content:
- # Import FullSearchResults only if needed
- try:
- from web_search_engines.engines.full_search import FullSearchResults
- self.full_search = FullSearchResults(
- llm=llm,
- web_search=self.engine,
- language=search_language,
- max_results=max_results,
- region=region,
- time=time_period,
- safesearch=brave_safe_search
- )
- except ImportError:
- print("Warning: FullSearchResults not available. Full content retrieval disabled.")
- self.include_full_content = False
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information from Brave Search.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- print("Getting search results from Brave Search")
-
- try:
- # Get search results from Brave Search
- raw_results = self.engine.run(query[:400])
-
- # Parse results if they're in string format
- if isinstance(raw_results, str):
- try:
- import json
- raw_results = json.loads(raw_results)
- except json.JSONDecodeError:
- print("Error: Unable to parse BraveSearch response as JSON.")
- return []
-
- # Format results as previews
- previews = []
- for i, result in enumerate(raw_results):
- preview = {
- "id": i, # Use index as ID
- "title": result.get("title", ""),
- "link": result.get("link", ""),
- "snippet": result.get("snippet", ""),
- "displayed_link": result.get("link", ""),
- "position": i
- }
-
- # Store full Brave result for later
- preview["_full_result"] = result
-
- previews.append(preview)
-
- # Store the previews for potential full content retrieval
- self._search_results = previews
-
- return previews
-
- except Exception as e:
- print(f"Error getting Brave Search results: {e}")
- return []
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant search results.
- If include_full_content is True and FullSearchResults is available,
- retrieves full webpage content for the results.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content if requested
- """
- # Check if we should get full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Snippet-only mode, skipping full content retrieval")
-
- # Return the relevant items with their full Brave information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"]
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item
-
- results.append(result)
-
- return results
-
- # If full content retrieval is enabled
- if self.include_full_content and hasattr(self, 'full_search'):
- print("Retrieving full webpage content")
-
- try:
- # Extract only the links from relevant items
- links = [item.get("link") for item in relevant_items if item.get("link")]
-
- # Use FullSearchResults to get full content
- results_with_content = self.full_search._get_full_content(relevant_items)
-
- return results_with_content
-
- except Exception as e:
- print(f"Error retrieving full content: {e}")
- # Fall back to returning the items without full content
-
- # Return items with their full Brave information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item.copy()
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
-
- return results
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Execute a search using Brave Search with the two-phase approach.
-
- Args:
- query: The search query
-
- Returns:
- List of search results
- """
- print("---Execute a search using Brave Search---")
-
- # Use the implementation from the parent class which handles all phases
- results = super().run(query)
-
- # Clean up
- if hasattr(self, '_search_results'):
- del self._search_results
-
- return results
diff --git a/web_search_engines/engines/search_engine_ddg.py b/web_search_engines/engines/search_engine_ddg.py
deleted file mode 100644
index 99a5e34685..0000000000
--- a/web_search_engines/engines/search_engine_ddg.py
+++ /dev/null
@@ -1,123 +0,0 @@
-from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
-from typing import Dict, List, Any, Optional
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-from web_search_engines.engines.full_search import FullSearchResults # Import the FullSearchResults class
-
-class DuckDuckGoSearchEngine(BaseSearchEngine):
- """DuckDuckGo search engine implementation with two-phase retrieval"""
-
- def __init__(self,
- max_results: int = 10,
- region: str = "us",
- safe_search: bool = True,
- llm: Optional[BaseLLM] = None,
- language: str = "English",
- include_full_content: bool = False):
- """
- Initialize the DuckDuckGo search engine.
-
- Args:
- max_results: Maximum number of search results
- region: Region code for search results
- safe_search: Whether to enable safe search
- llm: Language model for relevance filtering
- language: Language for content processing
- include_full_content: Whether to include full webpage content in results
- """
- super().__init__(llm=llm)
- self.max_results = max_results
- self.region = region
- self.safe_search = safe_search
- self.language = language
- self.include_full_content = include_full_content
-
- # Initialize the DuckDuckGo wrapper
- self.engine = DuckDuckGoSearchAPIWrapper(
- region=region,
- max_results=max_results,
- safesearch="moderate" if safe_search else "off"
- )
-
- # Initialize FullSearchResults if full content is requested
- if include_full_content and llm:
- self.full_search = FullSearchResults(
- llm=llm,
- web_search=self.engine,
- language=language,
- max_results=max_results,
- region=region,
- time="y",
- safesearch="Moderate" if safe_search else "Off"
- )
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Execute a search using DuckDuckGo with the two-phase approach.
- Respects config parameters:
- - SEARCH_SNIPPETS_ONLY: If True, only returns snippets without full content
- - SKIP_RELEVANCE_FILTER: If True, returns all results without filtering
-
- Args:
- query: The search query
-
- Returns:
- List of search results
- """
- print("---Execute a search using DuckDuckGo---")
-
- # Implementation of the two-phase approach (from parent class)
- return super().run(query)
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information (titles and snippets) for initial search results.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries with 'id', 'title', and 'snippet' keys
- """
- try:
- # Get search results from DuckDuckGo
- results = self.engine.results(query, max_results=self.max_results)
-
- if not isinstance(results, list):
- return []
-
- # Process results to get previews
- previews = []
- for i, result in enumerate(results):
- preview = {
- "id": result.get("link"), # Use URL as ID for DDG
- "title": result.get("title", ""),
- "snippet": result.get("snippet", ""),
- "link": result.get("link", "")
- }
-
- previews.append(preview)
-
- return previews
-
- except Exception as e:
- print(f"Error getting DuckDuckGo previews: {e}")
- return []
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant items by using FullSearchResults.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # If we have FullSearchResults, use it to get full content
- if hasattr(self, 'full_search'):
- return self.full_search._get_full_content(relevant_items)
-
- # Otherwise, just return the relevant items without full content
- return relevant_items
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_github.py b/web_search_engines/engines/search_engine_github.py
deleted file mode 100644
index 0e7ca986cf..0000000000
--- a/web_search_engines/engines/search_engine_github.py
+++ /dev/null
@@ -1,663 +0,0 @@
-import requests
-import logging
-import base64
-import os
-import time
-from typing import Dict, List, Any, Optional, Union
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-# Setup logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-class GitHubSearchEngine(BaseSearchEngine):
- """
- GitHub search engine implementation.
- Provides search across GitHub repositories, code, issues, and users.
- """
-
- def __init__(self,
- max_results: int = 15,
- api_key: Optional[str] = None,
- search_type: str = "repositories",
- include_readme: bool = True,
- include_issues: bool = False,
- llm: Optional[BaseLLM] = None,
- max_filtered_results: Optional[int] = None):
- """
- Initialize the GitHub search engine.
-
- Args:
- max_results: Maximum number of search results
- api_key: GitHub API token (can also be set in GITHUB_API_KEY env)
- search_type: Type of GitHub search ("repositories", "code", "issues", "users")
- include_readme: Whether to include README content for repositories
- include_issues: Whether to include recent issues for repositories
- llm: Language model for relevance filtering
- max_filtered_results: Maximum number of results to keep after filtering
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.api_key = api_key or os.getenv("GITHUB_API_KEY")
- self.search_type = search_type
- self.include_readme = include_readme
- self.include_issues = include_issues
-
- # API endpoints
- self.api_base = "https://api.github.com"
- self.search_endpoint = f"{self.api_base}/search/{search_type}"
-
- # Set up API headers
- self.headers = {
- "Accept": "application/vnd.github.v3+json",
- "User-Agent": "Local-Deep-Research-Agent"
- }
-
- # Add authentication if API key provided
- if self.api_key:
- self.headers["Authorization"] = f"token {self.api_key}"
- logger.info("Using authenticated GitHub API requests")
- else:
- logger.warning("No GitHub API key provided. Rate limits will be restricted.")
-
- def _handle_rate_limits(self, response):
- """Handle GitHub API rate limits by logging warnings and sleeping if necessary"""
- remaining = int(response.headers.get("X-RateLimit-Remaining", 60))
- reset_time = int(response.headers.get("X-RateLimit-Reset", 0))
-
- if remaining < 5:
- current_time = time.time()
- wait_time = max(reset_time - current_time, 0)
- logger.warning(f"GitHub API rate limit almost reached. {remaining} requests remaining.")
-
- if wait_time > 0 and remaining == 0:
- logger.warning(f"GitHub API rate limit exceeded. Waiting {wait_time:.0f} seconds.")
- time.sleep(min(wait_time, 60)) # Wait at most 60 seconds
-
- def _search_github(self, query: str) -> List[Dict[str, Any]]:
- """
- Perform a GitHub search based on the configured search type.
-
- Args:
- query: The search query
-
- Returns:
- List of GitHub search result items
- """
- results = []
-
- try:
- # Optimize GitHub query format
- github_query = query
-
- # For long queries, focus on keywords and add filters for better results
- if len(query) > 80:
- # Extract key terms if it's a recommendation request
- if "recommend" in query.lower() or "looking for" in query.lower():
- github_query = "stars:>100 " + " ".join([
- word for word in query.split()
- if len(word) > 3 and word.lower() not in
- ["recommend", "recommended", "github", "repositories", "looking", "developers"]
- ])
-
- logger.info(f"Optimized GitHub query: {github_query}")
-
- # Construct search parameters
- params = {
- "q": github_query,
- "per_page": min(self.max_results, 100), # GitHub API max is 100 per page
- "page": 1
- }
-
- # Add sort parameters based on search type
- if self.search_type == "repositories":
- params["sort"] = "stars"
- params["order"] = "desc"
- elif self.search_type == "code":
- params["sort"] = "indexed"
- params["order"] = "desc"
- elif self.search_type == "issues":
- params["sort"] = "updated"
- params["order"] = "desc"
- elif self.search_type == "users":
- params["sort"] = "followers"
- params["order"] = "desc"
-
- # Execute the API request
- response = requests.get(
- self.search_endpoint,
- headers=self.headers,
- params=params
- )
-
- # Check for rate limiting
- self._handle_rate_limits(response)
-
- # Handle response with detailed logging
- if response.status_code == 200:
- data = response.json()
- total_count = data.get("total_count", 0)
- results = data.get("items", [])
- logger.info(f"GitHub search returned {len(results)} results (total available: {total_count})")
-
- # Log the rate limit information
- rate_limit_remaining = response.headers.get("X-RateLimit-Remaining", "unknown")
- rate_limit_reset = response.headers.get("X-RateLimit-Reset", "unknown")
- logger.info(f"GitHub API rate limit: {rate_limit_remaining} requests remaining")
-
- # If no results, try to provide more guidance
- if not results:
- logger.warning(f"No results found. Consider these search tips:")
- logger.warning(f"1. Use shorter, more specific queries")
- logger.warning(f"2. For repositories, try adding 'stars:>100' or 'language:python'")
- logger.warning(f"3. For contribution opportunities, search for 'good-first-issue' or 'help-wanted'")
- else:
- logger.error(f"GitHub API error: {response.status_code} - {response.text}")
-
- except Exception as e:
- logger.error(f"Error searching GitHub: {e}")
-
- return results
-
- def _get_readme_content(self, repo_full_name: str) -> str:
- """
- Get README content for a repository.
-
- Args:
- repo_full_name: Full name of the repository (owner/repo)
-
- Returns:
- Decoded README content or empty string if not found
- """
- try:
- # Get README
- response = requests.get(
- f"{self.api_base}/repos/{repo_full_name}/readme",
- headers=self.headers
- )
-
- # Check for rate limiting
- self._handle_rate_limits(response)
-
- if response.status_code == 200:
- data = response.json()
- content = data.get("content", "")
- encoding = data.get("encoding", "")
-
- if encoding == "base64" and content:
- return base64.b64decode(content).decode('utf-8', errors='replace')
- return content
- else:
- logger.warning(f"Could not get README for {repo_full_name}: {response.status_code}")
- return ""
-
- except Exception as e:
- logger.error(f"Error getting README for {repo_full_name}: {e}")
- return ""
-
- def _get_recent_issues(self, repo_full_name: str, limit: int = 5) -> List[Dict[str, Any]]:
- """
- Get recent issues for a repository.
-
- Args:
- repo_full_name: Full name of the repository (owner/repo)
- limit: Maximum number of issues to return
-
- Returns:
- List of recent issues
- """
- issues = []
-
- try:
- # Get recent issues
- response = requests.get(
- f"{self.api_base}/repos/{repo_full_name}/issues",
- headers=self.headers,
- params={
- "state": "all",
- "per_page": limit,
- "sort": "updated",
- "direction": "desc"
- }
- )
-
- # Check for rate limiting
- self._handle_rate_limits(response)
-
- if response.status_code == 200:
- issues = response.json()
- logger.info(f"Got {len(issues)} recent issues for {repo_full_name}")
- else:
- logger.warning(f"Could not get issues for {repo_full_name}: {response.status_code}")
-
- except Exception as e:
- logger.error(f"Error getting issues for {repo_full_name}: {e}")
-
- return issues
-
- def _get_file_content(self, file_url: str) -> str:
- """
- Get content of a file from GitHub.
-
- Args:
- file_url: API URL for the file
-
- Returns:
- Decoded file content or empty string if not found
- """
- try:
- # Get file content
- response = requests.get(
- file_url,
- headers=self.headers
- )
-
- # Check for rate limiting
- self._handle_rate_limits(response)
-
- if response.status_code == 200:
- data = response.json()
- content = data.get("content", "")
- encoding = data.get("encoding", "")
-
- if encoding == "base64" and content:
- return base64.b64decode(content).decode('utf-8', errors='replace')
- return content
- else:
- logger.warning(f"Could not get file content: {response.status_code}")
- return ""
-
- except Exception as e:
- logger.error(f"Error getting file content: {e}")
- return ""
-
- def _format_repository_preview(self, repo: Dict[str, Any]) -> Dict[str, Any]:
- """Format repository search result as preview"""
- return {
- "id": str(repo.get("id", "")),
- "title": repo.get("full_name", ""),
- "link": repo.get("html_url", ""),
- "snippet": repo.get("description", "No description provided"),
- "stars": repo.get("stargazers_count", 0),
- "forks": repo.get("forks_count", 0),
- "language": repo.get("language", ""),
- "updated_at": repo.get("updated_at", ""),
- "created_at": repo.get("created_at", ""),
- "topics": repo.get("topics", []),
- "owner": repo.get("owner", {}).get("login", ""),
- "is_fork": repo.get("fork", False),
- "search_type": "repository",
- "repo_full_name": repo.get("full_name", "")
- }
-
- def _format_code_preview(self, code: Dict[str, Any]) -> Dict[str, Any]:
- """Format code search result as preview"""
- repo = code.get("repository", {})
- return {
- "id": f"code_{code.get('sha', '')}",
- "title": f"{code.get('name', '')} in {repo.get('full_name', '')}",
- "link": code.get("html_url", ""),
- "snippet": f"Match in {code.get('path', '')}",
- "path": code.get("path", ""),
- "repo_name": repo.get("full_name", ""),
- "repo_url": repo.get("html_url", ""),
- "search_type": "code",
- "file_url": code.get("url", "")
- }
-
- def _format_issue_preview(self, issue: Dict[str, Any]) -> Dict[str, Any]:
- """Format issue search result as preview"""
- repo = issue.get("repository", {}) if "repository" in issue else {"full_name": ""}
- return {
- "id": f"issue_{issue.get('number', '')}",
- "title": issue.get("title", ""),
- "link": issue.get("html_url", ""),
- "snippet": issue.get("body", "")[:200] + "..." if len(issue.get("body", "")) > 200 else issue.get("body", ""),
- "state": issue.get("state", ""),
- "created_at": issue.get("created_at", ""),
- "updated_at": issue.get("updated_at", ""),
- "user": issue.get("user", {}).get("login", ""),
- "comments": issue.get("comments", 0),
- "search_type": "issue",
- "repo_name": repo.get("full_name", "")
- }
-
- def _format_user_preview(self, user: Dict[str, Any]) -> Dict[str, Any]:
- """Format user search result as preview"""
- return {
- "id": f"user_{user.get('id', '')}",
- "title": user.get("login", ""),
- "link": user.get("html_url", ""),
- "snippet": user.get("bio", "No bio provided"),
- "name": user.get("name", ""),
- "followers": user.get("followers", 0),
- "public_repos": user.get("public_repos", 0),
- "location": user.get("location", ""),
- "search_type": "user",
- "user_login": user.get("login", "")
- }
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information for GitHub search results.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- logger.info(f"Getting GitHub previews for query: {query}")
-
- # For contribution-focused queries, automatically adjust search type and add filters
- if any(term in query.lower() for term in ["contribute", "contributing", "contribution", "beginner", "newcomer"]):
- # Use repositories search with help-wanted or good-first-issue labels
- original_search_type = self.search_type
- self.search_type = "repositories"
- self.search_endpoint = f"{self.api_base}/search/repositories"
-
- # Create a specialized query for finding beginner-friendly projects
- specialized_query = "good-first-issues:>5 is:public archived:false"
-
- # Extract language preferences if present
- languages = []
- for lang in ["python", "javascript", "java", "rust", "go", "typescript", "c#", "c++", "ruby"]:
- if lang in query.lower():
- languages.append(lang)
-
- if languages:
- specialized_query += f" language:{' language:'.join(languages)}"
-
- # Extract keywords
- keywords = [word for word in query.split() if len(word) > 3 and word.lower() not in
- ["recommend", "recommended", "github", "repositories", "looking",
- "developers", "contribute", "contributing", "beginner", "newcomer"]]
-
- if keywords:
- specialized_query += " " + " ".join(keywords[:5]) # Add up to 5 keywords
-
- logger.info(f"Using specialized contribution query: {specialized_query}")
-
- # Perform GitHub search with specialized query
- results = self._search_github(specialized_query)
-
- # Restore original search type
- self.search_type = original_search_type
- self.search_endpoint = f"{self.api_base}/search/{self.search_type}"
- else:
- # Perform standard GitHub search
- results = self._search_github(query)
-
- if not results:
- logger.warning(f"No GitHub results found for query: {query}")
- return []
-
- # Format results as previews
- previews = []
- for result in results:
- # Format based on search type
- if self.search_type == "repositories":
- preview = self._format_repository_preview(result)
- elif self.search_type == "code":
- preview = self._format_code_preview(result)
- elif self.search_type == "issues":
- preview = self._format_issue_preview(result)
- elif self.search_type == "users":
- preview = self._format_user_preview(result)
- else:
- logger.warning(f"Unknown search type: {self.search_type}")
- continue
-
- previews.append(preview)
-
- logger.info(f"Formatted {len(previews)} GitHub preview results")
- return previews
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant GitHub search results.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should add full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info(f"Getting full content for {len(relevant_items)} GitHub results")
-
- results = []
- for item in relevant_items:
- result = item.copy()
- search_type = item.get("search_type", "")
-
- # Add content based on search type
- if search_type == "repository" and self.include_readme:
- repo_full_name = item.get("repo_full_name", "")
- if repo_full_name:
- # Get README content
- readme_content = self._get_readme_content(repo_full_name)
- result["full_content"] = readme_content
- result["content_type"] = "readme"
-
- # Get recent issues if requested
- if self.include_issues:
- issues = self._get_recent_issues(repo_full_name)
- result["recent_issues"] = issues
-
- elif search_type == "code":
- file_url = item.get("file_url", "")
- if file_url:
- # Get file content
- file_content = self._get_file_content(file_url)
- result["full_content"] = file_content
- result["content_type"] = "file"
-
- elif search_type == "issue":
- # For issues, the snippet usually contains a summary already
- # We'll just keep it as is
- result["full_content"] = item.get("snippet", "")
- result["content_type"] = "issue"
-
- elif search_type == "user":
- # For users, construct a profile summary
- user_login = item.get("user_login", "")
- profile_summary = f"GitHub user: {item.get('title', '')}\n"
-
- if item.get("name"):
- profile_summary += f"Name: {item.get('name')}\n"
-
- if item.get("location"):
- profile_summary += f"Location: {item.get('location')}\n"
-
- profile_summary += f"Followers: {item.get('followers', 0)}\n"
- profile_summary += f"Public repositories: {item.get('public_repos', 0)}\n"
-
- if item.get("snippet") and item.get("snippet") != "No bio provided":
- profile_summary += f"\nBio: {item.get('snippet')}\n"
-
- result["full_content"] = profile_summary
- result["content_type"] = "user_profile"
-
- results.append(result)
-
- return results
-
- def search_repository(self, repo_owner: str, repo_name: str) -> Dict[str, Any]:
- """
- Get detailed information about a specific repository.
-
- Args:
- repo_owner: Owner of the repository
- repo_name: Name of the repository
-
- Returns:
- Dictionary with repository information
- """
- repo_full_name = f"{repo_owner}/{repo_name}"
- logger.info(f"Getting details for repository: {repo_full_name}")
-
- try:
- # Get repository details
- response = requests.get(
- f"{self.api_base}/repos/{repo_full_name}",
- headers=self.headers
- )
-
- # Check for rate limiting
- self._handle_rate_limits(response)
-
- if response.status_code == 200:
- repo = response.json()
-
- # Format as repository preview
- result = self._format_repository_preview(repo)
-
- # Add README content if requested
- if self.include_readme:
- readme_content = self._get_readme_content(repo_full_name)
- result["full_content"] = readme_content
- result["content_type"] = "readme"
-
- # Add recent issues if requested
- if self.include_issues:
- issues = self._get_recent_issues(repo_full_name)
- result["recent_issues"] = issues
-
- return result
- else:
- logger.error(f"Error getting repository details: {response.status_code} - {response.text}")
- return {}
-
- except Exception as e:
- logger.error(f"Error getting repository details: {e}")
- return {}
-
- def search_code(self, query: str, language: Optional[str] = None, user: Optional[str] = None) -> List[Dict[str, Any]]:
- """
- Search for code with more specific parameters.
-
- Args:
- query: Code search query
- language: Filter by programming language
- user: Filter by GitHub username/organization
-
- Returns:
- List of code search results
- """
- # Build advanced query
- advanced_query = query
-
- if language:
- advanced_query += f" language:{language}"
-
- if user:
- advanced_query += f" user:{user}"
-
- # Save current search type
- original_search_type = self.search_type
-
- try:
- # Set search type to code
- self.search_type = "code"
- self.search_endpoint = f"{self.api_base}/search/code"
-
- # Perform search
- results = self._search_github(advanced_query)
-
- # Format results
- previews = [self._format_code_preview(result) for result in results]
-
- # Get full content if requested
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and not config.SEARCH_SNIPPETS_ONLY:
- return self._get_full_content(previews)
-
- return previews
-
- finally:
- # Restore original search type
- self.search_type = original_search_type
- self.search_endpoint = f"{self.api_base}/search/{self.search_type}"
-
- def search_issues(self, query: str, state: str = "open", sort: str = "updated") -> List[Dict[str, Any]]:
- """
- Search for issues with more specific parameters.
-
- Args:
- query: Issue search query
- state: Filter by issue state ("open", "closed", "all")
- sort: Sort order ("updated", "created", "comments")
-
- Returns:
- List of issue search results
- """
- # Build advanced query
- advanced_query = query + f" state:{state}"
-
- # Save current search type
- original_search_type = self.search_type
-
- try:
- # Set search type to issues
- self.search_type = "issues"
- self.search_endpoint = f"{self.api_base}/search/issues"
-
- # Set sort parameter
- params = {
- "q": advanced_query,
- "per_page": min(self.max_results, 100),
- "page": 1,
- "sort": sort,
- "order": "desc"
- }
-
- # Perform search
- response = requests.get(
- self.search_endpoint,
- headers=self.headers,
- params=params
- )
-
- # Check for rate limiting
- self._handle_rate_limits(response)
-
- if response.status_code == 200:
- data = response.json()
- results = data.get("items", [])
-
- # Format results
- previews = [self._format_issue_preview(result) for result in results]
-
- # For issues, we don't need to get full content
- return previews
- else:
- logger.error(f"GitHub API error: {response.status_code} - {response.text}")
- return []
-
- finally:
- # Restore original search type
- self.search_type = original_search_type
- self.search_endpoint = f"{self.api_base}/search/{self.search_type}"
-
- def set_search_type(self, search_type: str):
- """
- Set the search type for subsequent searches.
-
- Args:
- search_type: Type of GitHub search ("repositories", "code", "issues", "users")
- """
- if search_type in ["repositories", "code", "issues", "users"]:
- self.search_type = search_type
- self.search_endpoint = f"{self.api_base}/search/{search_type}"
- logger.info(f"Set GitHub search type to: {search_type}")
- else:
- logger.error(f"Invalid GitHub search type: {search_type}")
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_google_pse.py b/web_search_engines/engines/search_engine_google_pse.py
deleted file mode 100644
index b21b0554ed..0000000000
--- a/web_search_engines/engines/search_engine_google_pse.py
+++ /dev/null
@@ -1,283 +0,0 @@
-from typing import Dict, List, Any, Optional
-import os
-import requests
-import time
-import random
-import logging
-from requests.exceptions import RequestException
-from urllib.parse import quote_plus
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-
-# Set up logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-class GooglePSESearchEngine(BaseSearchEngine):
- """Google Programmable Search Engine implementation"""
-
- def __init__(self,
- max_results: int = 10,
- region: str = "us",
- safe_search: bool = True,
- search_language: str = "English",
- api_key: Optional[str] = None,
- search_engine_id: Optional[str] = None,
- llm: Optional[BaseLLM] = None,
- include_full_content: bool = False,
- max_filtered_results: Optional[int] = None,
- max_retries: int = 3,
- retry_delay: float = 2.0,
- **kwargs):
- """
- Initialize the Google Programmable Search Engine.
-
- Args:
- max_results: Maximum number of search results
- region: Region code for search results
- safe_search: Whether to enable safe search
- search_language: Language for search results
- api_key: Google API key (can also be set in GOOGLE_PSE_API_KEY env)
- search_engine_id: Google CSE ID (can also be set in GOOGLE_PSE_ENGINE_ID env)
- llm: Language model for relevance filtering
- include_full_content: Whether to include full webpage content in results
- max_filtered_results: Maximum number of results to keep after filtering
- max_retries: Maximum number of retry attempts for API requests
- retry_delay: Base delay in seconds between retry attempts
- **kwargs: Additional parameters (ignored but accepted for compatibility)
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.include_full_content = include_full_content
-
- # Retry configuration
- self.max_retries = max_retries
- self.retry_delay = retry_delay
-
- # Rate limiting - keep track of last request time
- self.last_request_time = 0
- self.min_request_interval = 0.5 # Minimum time between requests in seconds
-
- # Language code mapping
- language_code_mapping = {
- "english": "en",
- "spanish": "es",
- "french": "fr",
- "german": "de",
- "italian": "it",
- "japanese": "ja",
- "korean": "ko",
- "portuguese": "pt",
- "russian": "ru",
- "chinese": "zh-CN"
- }
-
- # Get language code
- search_language = search_language.lower()
- self.language = language_code_mapping.get(search_language, "en")
-
- # Safe search setting
- self.safe = "active" if safe_search else "off"
-
- # Region/Country setting
- self.region = region
-
- # API key and Search Engine ID
- self.api_key = api_key or os.getenv("GOOGLE_PSE_API_KEY")
- self.search_engine_id = search_engine_id or os.getenv("GOOGLE_PSE_ENGINE_ID")
-
- if not self.api_key:
- raise ValueError("Google API key is required. Set it in the GOOGLE_PSE_API_KEY environment variable.")
- if not self.search_engine_id:
- raise ValueError("Google Search Engine ID is required. Set it in the GOOGLE_PSE_ENGINE_ID environment variable.")
-
- # Validate connection and credentials
- self._validate_connection()
-
- def _validate_connection(self):
- """Test the connection to ensure API key and Search Engine ID are valid"""
- try:
- # Make a minimal test query
- response = self._make_request("test")
-
- # Check if we got a valid response
- if response.get("error"):
- error_msg = response["error"].get("message", "Unknown error")
- raise ValueError(f"Google PSE API error: {error_msg}")
-
- # If we get here, the connection is valid
- logger.info("Google PSE connection validated successfully")
- return True
-
- except Exception as e:
- # Log the error and re-raise
- logger.error(f"Error validating Google PSE connection: {str(e)}")
- raise
-
- def _respect_rate_limit(self):
- """Ensure we don't exceed rate limits by adding appropriate delay between requests"""
- current_time = time.time()
- elapsed = current_time - self.last_request_time
-
- # If we've made a request recently, wait until the minimum interval has passed
- if elapsed < self.min_request_interval:
- sleep_time = self.min_request_interval - elapsed
- logger.debug(f"Rate limiting: sleeping for {sleep_time:.2f}s")
- time.sleep(sleep_time)
-
- # Update the last request time
- self.last_request_time = time.time()
-
- def _make_request(self, query: str, start_index: int = 1) -> Dict:
- """
- Make a request to the Google PSE API with retry logic and rate limiting
-
- Args:
- query: Search query string
- start_index: Starting index for pagination
-
- Returns:
- JSON response from the API
-
- Raises:
- RequestException: If all retry attempts fail
- """
- # Base URL for the API
- url = "https://www.googleapis.com/customsearch/v1"
-
- # Parameters for the request
- params = {
- "key": self.api_key,
- "cx": self.search_engine_id,
- "q": query,
- "num": min(10, self.max_results), # Max 10 per request
- "start": start_index,
- "safe": self.safe,
- "lr": f"lang_{self.language}",
- "gl": self.region
- }
-
- # Implement retry logic with exponential backoff
- attempt = 0
- last_exception = None
-
- while attempt < self.max_retries:
- try:
- # Respect rate limits
- self._respect_rate_limit()
-
- # Add jitter to retries after the first attempt
- if attempt > 0:
- jitter = random.uniform(0.5, 1.5)
- sleep_time = self.retry_delay * (2 ** (attempt - 1)) * jitter
- logger.info(f"Retry attempt {attempt+1}/{self.max_retries} for query '{query}'. Waiting {sleep_time:.2f}s")
- time.sleep(sleep_time)
-
- # Make the request
- logger.debug(f"Making request to Google PSE API: {query} (start_index={start_index})")
- response = requests.get(url, params=params, timeout=10)
-
- # Check for HTTP errors
- response.raise_for_status()
-
- # Return the JSON response
- return response.json()
-
- except RequestException as e:
- logger.warning(f"Request error on attempt {attempt+1}/{self.max_retries}: {str(e)}")
- last_exception = e
- except Exception as e:
- logger.warning(f"Error on attempt {attempt+1}/{self.max_retries}: {str(e)}")
- last_exception = e
-
- attempt += 1
-
- # If we get here, all retries failed
- error_msg = f"Failed to get response from Google PSE API after {self.max_retries} attempts"
- logger.error(error_msg)
-
- if last_exception:
- raise RequestException(f"{error_msg}: {str(last_exception)}")
- else:
- raise RequestException(error_msg)
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """Get search result previews/snippets"""
- results = []
-
- # Google PSE API returns a maximum of 10 results per request
- # We may need to make multiple requests to get the desired number
- start_index = 1
- total_results = 0
-
- while total_results < self.max_results:
- try:
- response = self._make_request(query, start_index)
-
- # Break if no items
- if "items" not in response:
- break
-
- items = response.get("items", [])
-
- # Process each result
- for item in items:
- title = item.get("title", "")
- snippet = item.get("snippet", "")
- url = item.get("link", "")
-
- # Skip results without URL
- if not url:
- continue
-
- results.append({
- "title": title,
- "snippet": snippet,
- "url": url,
- "source": "Google Programmable Search"
- })
-
- total_results += 1
- if total_results >= self.max_results:
- break
-
- # Check if there are more results
- if not items or total_results >= self.max_results:
- break
-
- # Update start index for next request
- start_index += len(items)
-
- # Add a small delay between multiple requests to be respectful of the API
- if total_results < self.max_results:
- time.sleep(self.min_request_interval)
-
- except Exception as e:
- logger.error(f"Error getting search results: {str(e)}")
- break
-
- logger.info(f"Retrieved {len(results)} search results for query: '{query}'")
- return results
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """Get full content for search results"""
- # Use the BaseSearchEngine implementation
- return super()._get_full_content(relevant_items)
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """Run the search engine to get results for a query"""
- # Get search result previews/snippets
- search_results = self._get_previews(query)
-
- # Filter for relevance if we have an LLM and max_filtered_results
- if self.llm and self.max_filtered_results:
- search_results = self._filter_for_relevance(query, search_results)
-
- # Get full content if needed
- if self.include_full_content:
- search_results = self._get_full_content(search_results)
-
- return search_results
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_guardian.py b/web_search_engines/engines/search_engine_guardian.py
deleted file mode 100644
index b0196d9078..0000000000
--- a/web_search_engines/engines/search_engine_guardian.py
+++ /dev/null
@@ -1,337 +0,0 @@
-import requests
-from typing import Dict, List, Any, Optional
-import os
-from datetime import datetime, timedelta
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-
-class GuardianSearchEngine(BaseSearchEngine):
- """The Guardian API search engine implementation"""
-
- def __init__(self,
- max_results: int = 10,
- api_key: Optional[str] = None,
- from_date: Optional[str] = None,
- to_date: Optional[str] = None,
- section: Optional[str] = None,
- order_by: str = "relevance",
- llm: Optional[BaseLLM] = None):
- """
- Initialize The Guardian search engine.
-
- Args:
- max_results: Maximum number of search results
- api_key: The Guardian API key (can also be set in GUARDIAN_API_KEY env)
- from_date: Start date for search (YYYY-MM-DD format, default 1 month ago)
- to_date: End date for search (YYYY-MM-DD format, default today)
- section: Filter by section (e.g., "politics", "technology", "sport")
- order_by: Sort order ("relevance", "newest", "oldest")
- llm: Language model for relevance filtering
- """
- # Initialize the BaseSearchEngine with the LLM
- super().__init__(llm=llm)
-
- self.max_results = max_results
- self.api_key = api_key or os.getenv("GUARDIAN_API_KEY")
-
- if not self.api_key:
- raise ValueError("Guardian API key not found. Please provide api_key or set the GUARDIAN_API_KEY environment variable.")
-
- # Set date ranges if not provided
- if not from_date:
- # Default to one month ago
- one_month_ago = datetime.now() - timedelta(days=30)
- self.from_date = one_month_ago.strftime("%Y-%m-%d")
- else:
- self.from_date = from_date
-
- if not to_date:
- # Default to today
- self.to_date = datetime.now().strftime("%Y-%m-%d")
- else:
- self.to_date = to_date
-
- self.section = section
- self.order_by = order_by
-
- # API base URL
- self.api_url = "https://content.guardianapis.com/search"
-
- def _get_all_data(self, query: str) -> List[Dict[str, Any]]:
- """
- Get all article data from The Guardian API in a single call.
- Always requests all fields for simplicity.
-
- Args:
- query: The search query
-
- Returns:
- List of articles with all data
- """
- try:
- # Always request all fields for simplicity
- params = {
- "q": query,
- "api-key": self.api_key,
- "from-date": self.from_date,
- "to-date": self.to_date,
- "order-by": self.order_by,
- "page-size": min(self.max_results, 50), # API maximum is 50
- "show-fields": "headline,trailText,byline,body,publication",
- "show-tags": "keyword"
- }
-
- # Add section filter if specified
- if self.section:
- params["section"] = self.section
-
- # Execute the API request
- response = requests.get(self.api_url, params=params)
- response.raise_for_status()
-
- data = response.json()
-
- # Extract results from the response
- articles = data.get("response", {}).get("results", [])
-
- # Format results to include all data
- formatted_articles = []
- for i, article in enumerate(articles):
- if i >= self.max_results:
- break
-
- fields = article.get("fields", {})
-
- # Format the article with all fields
- result = {
- "id": article.get("id", ""),
- "title": fields.get("headline", article.get("webTitle", "")),
- "link": article.get("webUrl", ""),
- "snippet": fields.get("trailText", ""),
- "publication_date": article.get("webPublicationDate", ""),
- "section": article.get("sectionName", ""),
- "author": fields.get("byline", ""),
- "content": fields.get("body", ""),
- "full_content": fields.get("body", "")
- }
-
- # Extract tags/keywords
- tags = article.get("tags", [])
- result["keywords"] = [tag.get("webTitle", "") for tag in tags if tag.get("type") == "keyword"]
-
- formatted_articles.append(result)
-
- return formatted_articles
-
- except Exception as e:
- print(f"Error getting data from The Guardian API: {e}")
- return []
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information for Guardian articles.
- Actually gets all data but returns only preview fields.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- print("Getting articles from The Guardian API")
-
- # Get all article data
- articles = self._get_all_data(query)
-
- # Store full articles for later use (implementation detail)
- self._full_articles = {a["id"]: a for a in articles}
-
- # Return only preview fields for each article
- previews = []
- for article in articles:
- preview = {
- "id": article["id"],
- "title": article["title"],
- "link": article["link"],
- "snippet": article["snippet"],
- "publication_date": article["publication_date"],
- "section": article["section"],
- "author": article["author"],
- "keywords": article.get("keywords", [])
- }
- previews.append(preview)
-
- return previews
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant Guardian articles.
- Restores full content from the cached data.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- print("Adding full content to relevant Guardian articles")
-
- # Check if we should add full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- return relevant_items
-
- # Get full articles for relevant items
- results = []
- for item in relevant_items:
- article_id = item.get("id", "")
-
- # Get the full article from our cache
- if hasattr(self, '_full_articles') and article_id in self._full_articles:
- results.append(self._full_articles[article_id])
- else:
- # If not found (shouldn't happen), just use the preview
- results.append(item)
-
- return results
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Execute a search using The Guardian API with the two-phase approach.
-
- Args:
- query: The search query
-
- Returns:
- List of search results
- """
- print("---Execute a search using The Guardian---")
-
- # Use the implementation from the parent class which handles all phases
- results = super().run(query)
-
- # Clean up the cache after use
- if hasattr(self, '_full_articles'):
- del self._full_articles
-
- return results
-
- def get_article_by_id(self, article_id: str) -> Dict[str, Any]:
- """
- Get a specific article by its ID.
-
- Args:
- article_id: The Guardian article ID
-
- Returns:
- Dictionary with article information
- """
- try:
- # Guardian article API URL
- url = f"https://content.guardianapis.com/{article_id}"
-
- # Always request all fields
- response = requests.get(
- url,
- params={
- "api-key": self.api_key,
- "show-fields": "headline,trailText,body,byline,publication",
- "show-tags": "keyword"
- }
- )
- response.raise_for_status()
-
- data = response.json()
- article = data.get("response", {}).get("content", {})
-
- if not article:
- return {}
-
- fields = article.get("fields", {})
-
- # Format the article with all fields
- result = {
- "id": article_id,
- "title": fields.get("headline", article.get("webTitle", "")),
- "link": article.get("webUrl", ""),
- "snippet": fields.get("trailText", ""),
- "publication_date": article.get("webPublicationDate", ""),
- "section": article.get("sectionName", ""),
- "author": fields.get("byline", "")
- }
-
- # Only include full content if not in snippet-only mode
- if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:
- result["content"] = fields.get("body", "")
- result["full_content"] = fields.get("body", "")
-
- # Extract tags/keywords
- tags = article.get("tags", [])
- result["keywords"] = [tag.get("webTitle", "") for tag in tags if tag.get("type") == "keyword"]
-
- return result
-
- except Exception as e:
- print(f"Error getting article details: {e}")
- return {}
-
- def search_by_section(self, section: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for articles in a specific section.
-
- Args:
- section: The Guardian section name (e.g., "politics", "technology")
- max_results: Maximum number of search results (defaults to self.max_results)
-
- Returns:
- List of articles in the section
- """
- original_section = self.section
- original_max_results = self.max_results
-
- try:
- # Set section and max_results for this search
- self.section = section
- if max_results:
- self.max_results = max_results
-
- # Use empty query to get all articles in the section
- return self.run("")
-
- finally:
- # Restore original values
- self.section = original_section
- self.max_results = original_max_results
-
- def get_recent_articles(self, days: int = 7, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Get recent articles from The Guardian.
-
- Args:
- days: Number of days to look back
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of recent articles
- """
- original_from_date = self.from_date
- original_order_by = self.order_by
- original_max_results = self.max_results
-
- try:
- # Set parameters for this search
- self.from_date = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
- self.order_by = "newest"
- if max_results:
- self.max_results = max_results
-
- # Use empty query to get all recent articles
- return self.run("")
-
- finally:
- # Restore original values
- self.from_date = original_from_date
- self.order_by = original_order_by
- self.max_results = original_max_results
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_local.py b/web_search_engines/engines/search_engine_local.py
deleted file mode 100644
index 7fde606edd..0000000000
--- a/web_search_engines/engines/search_engine_local.py
+++ /dev/null
@@ -1,901 +0,0 @@
-from typing import Dict, List, Any, Optional, Tuple, Union
-import os
-import json
-import hashlib
-import time
-from datetime import datetime
-from pathlib import Path
-import tiktoken
-import logging
-import re
-import pickle
-
-from langchain_core.language_models import BaseLLM
-from langchain_community.document_loaders import (
- PyPDFLoader,
- TextLoader,
- UnstructuredMarkdownLoader,
- UnstructuredWordDocumentLoader,
- CSVLoader,
- UnstructuredExcelLoader,
- DirectoryLoader
-)
-from langchain_community.document_loaders.base import BaseLoader
-from langchain_text_splitters import RecursiveCharacterTextSplitter
-from langchain_community.vectorstores import FAISS
-from langchain_community.embeddings import (
- HuggingFaceEmbeddings,
- OllamaEmbeddings,
- SentenceTransformerEmbeddings
-)
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-# Setup logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-class LocalEmbeddingManager:
- """Handles embedding generation and storage for local document search"""
-
- def __init__(
- self,
- embedding_model: str = "all-MiniLM-L6-v2",
- embedding_device: str = "cpu",
- embedding_model_type: str = "sentence_transformers", # or 'ollama'
- ollama_base_url: Optional[str] = None,
- chunk_size: int = 1000,
- chunk_overlap: int = 200,
- cache_dir: str = ".cache/local_search",
- ):
- """
- Initialize the embedding manager for local document search.
-
- Args:
- embedding_model: Name of the embedding model to use
- embedding_device: Device to run embeddings on ('cpu' or 'cuda')
- embedding_model_type: Type of embedding model ('sentence_transformers' or 'ollama')
- ollama_base_url: Base URL for Ollama API if using ollama embeddings
- chunk_size: Size of text chunks for splitting documents
- chunk_overlap: Overlap between chunks
- cache_dir: Directory to store embedding cache and index
- """
-
- self.embedding_model = embedding_model
- self.embedding_device = embedding_device
- self.embedding_model_type = embedding_model_type
- self.ollama_base_url = ollama_base_url
- self.chunk_size = chunk_size
- self.chunk_overlap = chunk_overlap
- self.cache_dir = Path(cache_dir)
-
- # Create cache directory if it doesn't exist
- self.cache_dir.mkdir(parents=True, exist_ok=True)
-
- # Initialize the embedding model
- self._embeddings = None
-
- # Initialize the text splitter
- self.text_splitter = RecursiveCharacterTextSplitter(
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap
- )
-
- # Track indexed folders and their metadata
- self.indexed_folders = self._load_indexed_folders()
-
- # Vector store cache
- self.vector_stores = {}
- @property
- def embeddings(self):
- """
- Lazily initialize embeddings when first accessed.
- This allows the LocalEmbeddingManager to be created without
- immediately loading models, which is helpful when no local search is performed.
- """
- if self._embeddings is None:
- logger.info("Initializing embeddings on first use")
- self._embeddings = self._initialize_embeddings()
- return self._embeddings
-
- def _initialize_embeddings(self):
- """Initialize the embedding model based on configuration"""
- try:
- if self.embedding_model_type == "ollama":
- # Use Ollama for embeddings
- if not self.ollama_base_url:
- self.ollama_base_url = "http://localhost:11434"
-
- logger.info(f"Initializing Ollama embeddings with model {self.embedding_model}")
- return OllamaEmbeddings(
- model=self.embedding_model,
- base_url=self.ollama_base_url
- )
- else:
- # Default: Use SentenceTransformers/HuggingFace
- logger.info(f"Initializing SentenceTransformerEmbeddings with model {self.embedding_model}")
- return SentenceTransformerEmbeddings(
- model_name=self.embedding_model,
- model_kwargs={"device": self.embedding_device}
- )
- except Exception as e:
- logger.error(f"Error initializing embeddings: {e}")
- logger.warning("Falling back to HuggingFaceEmbeddings with all-MiniLM-L6-v2")
- return HuggingFaceEmbeddings(
- model_name="sentence-transformers/all-MiniLM-L6-v2"
- )
- def _load_or_create_vector_store(self):
- """Load the vector store from disk or create it if needed"""
- vector_store_path = self._get_vector_store_path()
-
- # Check if vector store exists and is up to date
- if vector_store_path.exists() and not self._check_folders_modified():
- logger.info(f"Loading existing vector store from {vector_store_path}")
- try:
- vector_store = FAISS.load_local(
- str(vector_store_path),
- self.embeddings,
- allow_dangerous_deserialization=True
- )
-
- # Add this code to show document count
- doc_count = len(vector_store.index_to_docstore_id)
- logger.info(f"Loaded index with {doc_count} document chunks")
-
- return vector_store
- except Exception as e:
- logger.error(f"Error loading vector store: {e}")
- logger.info("Will create a new vector store")
-
- # Create a new vector store
- return self._create_vector_store()
- def _load_indexed_folders(self) -> Dict[str, Dict[str, Any]]:
- """Load metadata about indexed folders from disk"""
- index_metadata_path = self.cache_dir / "index_metadata.json"
-
- if index_metadata_path.exists():
- try:
- with open(index_metadata_path, "r") as f:
- return json.load(f)
- except Exception as e:
- logger.error(f"Error loading index metadata: {e}")
-
- return {}
-
- def _save_indexed_folders(self):
- """Save metadata about indexed folders to disk"""
- index_metadata_path = self.cache_dir / "index_metadata.json"
-
- try:
- with open(index_metadata_path, "w") as f:
- json.dump(self.indexed_folders, f, indent=2)
- except Exception as e:
- logger.error(f"Error saving index metadata: {e}")
-
- def _get_folder_hash(self, folder_path: str) -> str:
- """Generate a hash for a folder based on its path"""
- return hashlib.md5(folder_path.encode()).hexdigest()
-
- def _get_index_path(self, folder_path: str) -> Path:
- """Get the path where the index for a specific folder should be stored"""
- folder_hash = self._get_folder_hash(folder_path)
- return self.cache_dir / f"index_{folder_hash}"
-
- def _check_folder_modified(self, folder_path: str) -> bool:
- """Check if a folder has been modified since it was last indexed"""
- folder_path = Path(folder_path)
-
- if not folder_path.exists() or not folder_path.is_dir():
- return False
-
- folder_hash = self._get_folder_hash(str(folder_path))
-
- # If folder has never been indexed, it's considered modified
- if folder_hash not in self.indexed_folders:
- return True
-
- last_indexed = self.indexed_folders[folder_hash].get("last_indexed", 0)
-
- # Check if any file in the folder has been modified since last indexing
- for root, _, files in os.walk(folder_path):
- for file in files:
- file_path = Path(root) / file
- if file_path.stat().st_mtime > last_indexed:
- return True
-
- return False
-
- def get_file_loader(self, file_path: str) -> Optional[BaseLoader]:
- """Get an appropriate document loader for a file based on its extension"""
- file_path = Path(file_path)
- extension = file_path.suffix.lower()
-
- try:
- if extension == ".pdf":
- return PyPDFLoader(str(file_path))
- elif extension == ".txt":
- return TextLoader(str(file_path))
- elif extension in [".md", ".markdown"]:
- return UnstructuredMarkdownLoader(str(file_path))
- elif extension in [".doc", ".docx"]:
- return UnstructuredWordDocumentLoader(str(file_path))
- elif extension == ".csv":
- return CSVLoader(str(file_path))
- elif extension in [".xls", ".xlsx"]:
- return UnstructuredExcelLoader(str(file_path))
- else:
- # Try the text loader as a fallback for unknown extensions
- logger.warning(f"Unknown file extension for {file_path}, trying TextLoader")
- return TextLoader(str(file_path), encoding="utf-8")
- except Exception as e:
- logger.error(f"Error creating loader for {file_path}: {e}")
- return None
-
- def index_folder(self, folder_path: str, force_reindex: bool = False) -> bool:
- """
- Index all documents in a folder for vector search.
-
- Args:
- folder_path: Path to the folder to index
- force_reindex: Whether to force reindexing even if unchanged
-
- Returns:
- bool: True if indexing was successful, False otherwise
- """
- folder_path = Path(folder_path)
-
- # Validate folder
- if not folder_path.exists():
- logger.error(f"Folder not found: {folder_path}")
- return False
-
- if not folder_path.is_dir():
- logger.error(f"Path is not a directory: {folder_path}")
- return False
-
- folder_str = str(folder_path)
- folder_hash = self._get_folder_hash(folder_str)
- index_path = self._get_index_path(folder_str)
-
- # Check if folder needs to be reindexed
- if not force_reindex and not self._check_folder_modified(folder_str):
- logger.info(f"Folder {folder_path} has not been modified since last indexing")
-
- # Load the vector store from disk if not already loaded
- if folder_hash not in self.vector_stores:
- try:
- self.vector_stores[folder_hash] = FAISS.load_local(
- str(index_path),
- self.embeddings,
- allow_dangerous_deserialization=True
- )
- logger.info(f"Loaded index for {folder_path} from disk")
- except Exception as e:
- logger.error(f"Error loading index for {folder_path}: {e}")
- # If loading fails, force reindexing
- force_reindex = True
- else:
- logger.info(f"Using cached index for {folder_path}")
-
- # If no reindexing is needed and vector store loaded successfully
- if not force_reindex and folder_hash in self.vector_stores:
- return True
-
- logger.info(f"Indexing folder: {folder_path}")
- start_time = time.time()
-
- # Find documents to index
- all_docs = []
- file_count = 0
- error_count = 0
-
- for root, _, files in os.walk(folder_path):
- for file in files:
- file_path = Path(root) / file
-
- # Skip hidden files and directories
- if file.startswith(".") or any(part.startswith(".") for part in file_path.parts):
- continue
-
- # Get a loader for this file
- loader = self.get_file_loader(str(file_path))
-
- if loader:
- try:
- # Load the document
- docs = loader.load()
-
- # Add source path metadata
- for doc in docs:
- doc.metadata["source"] = str(file_path)
- doc.metadata["filename"] = file
-
- all_docs.extend(docs)
- file_count += 1
- except Exception as e:
- logger.error(f"Error loading {file_path}: {e}")
- error_count += 1
-
- if not all_docs:
- logger.warning(f"No documents found in {folder_path} or all documents failed to load")
- return False
-
- # Split documents into chunks
- logger.info(f"Splitting {len(all_docs)} documents into chunks")
- splits = self.text_splitter.split_documents(all_docs)
- logger.info(f"Created {len(splits)} chunks from {file_count} files")
-
- # Create vector store
- logger.info(f"Creating vector store with {len(splits)} chunks")
- vector_store = FAISS.from_documents(splits, self.embeddings)
-
- # Save the vector store to disk
- logger.info(f"Saving index to {index_path}")
- vector_store.save_local(str(index_path))
-
- # Update cache
- self.vector_stores[folder_hash] = vector_store
-
- # Update metadata
- self.indexed_folders[folder_hash] = {
- "path": folder_str,
- "last_indexed": time.time(),
- "file_count": file_count,
- "chunk_count": len(splits),
- "error_count": error_count,
- "embedding_model": self.embedding_model,
- "chunk_size": self.chunk_size,
- "chunk_overlap": self.chunk_overlap
- }
-
- # Save updated metadata
- self._save_indexed_folders()
-
- elapsed_time = time.time() - start_time
- logger.info(f"Indexed {file_count} files in {elapsed_time:.2f} seconds")
-
- return True
-
- def search(
- self,
- query: str,
- folder_paths: List[str],
- limit: int = 10,
- score_threshold: float = 0.0,
- ) -> List[Dict[str, Any]]:
- """
- Search for documents relevant to a query across specified folders.
-
- Args:
- query: The search query
- folder_paths: List of folder paths to search in
- limit: Maximum number of results to return
- score_threshold: Minimum similarity score threshold
-
- Returns:
- List of results with document content and metadata
- """
- # Add detailed debugging for each folder
- for folder_path in folder_paths:
- folder_hash = self._get_folder_hash(folder_path)
- index_path = self._get_index_path(folder_path)
-
- logger.info(f"Diagnostic for {folder_path}:")
- logger.info(f" - Folder hash: {folder_hash}")
- logger.info(f" - Index path: {index_path}")
- logger.info(f" - Index exists on disk: {index_path.exists()}")
- logger.info(f" - Is in indexed_folders: {folder_hash in self.indexed_folders}")
-
- if folder_hash in self.indexed_folders:
- meta = self.indexed_folders[folder_hash]
- logger.info(f" - Metadata: file_count={meta.get('file_count', 0)}, chunk_count={meta.get('chunk_count', 0)}")
-
- # Validate folders exist
- valid_folder_paths = []
- for path in folder_paths:
- if os.path.exists(path) and os.path.isdir(path):
- valid_folder_paths.append(path)
- else:
- logger.warning(f"Skipping non-existent folder in search: {path}")
-
- # If no valid folders, return empty results
- if not valid_folder_paths:
- logger.warning(f"No valid folders to search among: {folder_paths}")
- return []
-
- all_results = []
-
- for folder_path in valid_folder_paths:
- folder_hash = self._get_folder_hash(folder_path)
-
- # Skip folders that haven't been indexed
- if folder_hash not in self.indexed_folders:
- logger.warning(f"Folder {folder_path} has not been indexed")
- continue
-
- # Make sure the vector store is loaded
- if folder_hash not in self.vector_stores:
- index_path = self._get_index_path(folder_path)
- try:
- self.vector_stores[folder_hash] = FAISS.load_local(
- str(index_path),
- self.embeddings,
- allow_dangerous_deserialization=True
- )
- except Exception as e:
- logger.error(f"Error loading index for {folder_path}: {e}")
- continue
-
- # Search in this folder
- vector_store = self.vector_stores[folder_hash]
-
- try:
- docs_with_scores = vector_store.similarity_search_with_score(query, k=limit)
-
- for doc, score in docs_with_scores:
- # Convert score from distance to similarity (lower distance = higher similarity)
- # FAISS cosine distance is in [0, 2], where 0 is identical and 2 is opposite
- # Convert to a similarity score in [0, 1]
- similarity = 1.0 - (score / 2.0)
-
- # Skip results below the threshold
- if similarity < score_threshold:
- continue
-
- result = {
- "content": doc.page_content,
- "metadata": doc.metadata,
- "similarity": similarity,
- "folder": folder_path
- }
-
- all_results.append(result)
- except Exception as e:
- logger.error(f"Error searching in {folder_path}: {e}")
-
- # Sort by similarity (highest first)
- all_results.sort(key=lambda x: x["similarity"], reverse=True)
-
- # Limit to the requested number
- return all_results[:limit]
-
- def clear_cache(self):
- """Clear all cached vector stores from memory (not disk)"""
- self.vector_stores.clear()
-
- def get_indexed_folders_info(self) -> List[Dict[str, Any]]:
- """Get information about all indexed folders"""
- info = []
-
- for folder_hash, metadata in self.indexed_folders.items():
- folder_info = metadata.copy()
-
- # Add formatted last indexed time
- if "last_indexed" in folder_info:
- folder_info["last_indexed_formatted"] = datetime.fromtimestamp(
- folder_info["last_indexed"]
- ).strftime("%Y-%m-%d %H:%M:%S")
-
- # Check if index file exists
- index_path = self._get_index_path(folder_info["path"])
- folder_info["index_exists"] = index_path.exists()
-
- info.append(folder_info)
-
- return info
-
-
-class LocalSearchEngine(BaseSearchEngine):
- """Local document search engine with two-phase retrieval"""
-
- def __init__(
- self,
- folder_paths: List[str],
- llm: Optional[BaseLLM] = None,
- max_results: int = 10,
- max_filtered_results: Optional[int] = None,
- embedding_model: str = "all-MiniLM-L6-v2",
- embedding_device: str = "cpu",
- embedding_model_type: str = "sentence_transformers",
- ollama_base_url: Optional[str] = None,
- force_reindex: bool = False,
- chunk_size: int = 1000,
- chunk_overlap: int = 200,
- cache_dir: str = ".cache/local_search",
- collections: Optional[Dict[str, Dict[str, Any]]] = None,
- ):
- """
- Initialize the local search engine.
-
- Args:
- folder_paths: List of folder paths to search in
- llm: Language model for relevance filtering
- max_results: Maximum number of results to return
- max_filtered_results: Maximum results after filtering
- embedding_model: Name of the embedding model to use
- embedding_device: Device to run embeddings on ('cpu' or 'cuda')
- embedding_model_type: Type of embedding model
- ollama_base_url: Base URL for Ollama API
- force_reindex: Whether to force reindexing
- chunk_size: Size of text chunks for splitting documents
- chunk_overlap: Overlap between chunks
- cache_dir: Directory to store embedding cache and index
- collections: Dictionary of named collections with paths and descriptions
- """
- # Initialize the base search engine
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- # Validate folder paths
- self.folder_paths = folder_paths
- self.valid_folder_paths = []
- for path in folder_paths:
- if os.path.exists(path) and os.path.isdir(path):
- self.valid_folder_paths.append(path)
- else:
- logger.warning(f"Folder not found or is not a directory: {path}")
-
- # If no valid folders, log a clear message
- if not self.valid_folder_paths and folder_paths:
- logger.warning(f"No valid folders found among: {folder_paths}")
- logger.warning("This search engine will return no results until valid folders are configured")
-
- self.max_results = max_results
- self.collections = collections or {"default": {"paths": folder_paths, "description": "Default collection"}}
-
- # Initialize the embedding manager with only valid folders
- self.embedding_manager = LocalEmbeddingManager(
- embedding_model=embedding_model,
- embedding_device=embedding_device,
- embedding_model_type=embedding_model_type,
- ollama_base_url=ollama_base_url,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- cache_dir=cache_dir
- )
-
- # Index all folders
- self._index_folders(force_reindex)
-
- def _index_folders(self, force_reindex: bool = False):
- """Index all valid configured folders"""
- indexed = []
- failed = []
- skipped = []
-
- # Keep track of invalid folders
- for folder in self.folder_paths:
- if folder not in self.valid_folder_paths:
- skipped.append(folder)
- continue
-
- success = self.embedding_manager.index_folder(folder, force_reindex)
- if success:
- indexed.append(folder)
- else:
- failed.append(folder)
-
- if indexed:
- logger.info(f"Successfully indexed {len(indexed)} folders: {', '.join(indexed)}")
-
- if failed:
- logger.warning(f"Failed to index {len(failed)} folders: {', '.join(failed)}")
-
- if skipped:
- logger.warning(f"Skipped {len(skipped)} invalid folders: {', '.join(skipped)}")
-
- def _get_previews(self, query: str, collection_names: Optional[List[str]] = None) -> List[Dict[str, Any]]:
- """
- Get preview information for documents matching the query.
-
- Args:
- query: The search query
- collection_names: Specific collections to search within (if None, search all)
-
- Returns:
- List of preview dictionaries
- """
- # Determine which collections to search
- if collection_names:
- # Search only in specified collections
- collections_to_search = {name: self.collections[name] for name in collection_names
- if name in self.collections}
- if not collections_to_search:
- logger.warning(f"No valid collections found among: {collection_names}")
- return []
- else:
- # Search in all collections
- collections_to_search = self.collections
-
- # Extract all folder paths from the collections to search
- search_paths = []
- for collection_config in collections_to_search.values():
- if "paths" in collection_config:
- search_paths.extend(collection_config["paths"])
-
- logger.info(f"Searching local documents in collections: {list(collections_to_search.keys())}")
-
- # Filter out invalid paths
- valid_search_paths = [path for path in search_paths if path in self.valid_folder_paths]
-
- if not valid_search_paths:
- logger.warning(f"No valid folders to search in collections: {list(collections_to_search.keys())}")
- return []
-
- # Search across the valid selected folders
- raw_results = self.embedding_manager.search(
- query=query,
- folder_paths=valid_search_paths,
- limit=self.max_results,
- score_threshold=0.1 # Skip very low relevance results
- )
-
- if not raw_results:
- logger.info(f"No local documents found for query: {query}")
- return []
-
- # Convert to preview format
- previews = []
- for i, result in enumerate(raw_results):
- # Create a unique ID
- result_id = f"local-{i}-{hashlib.md5(result['content'][:50].encode()).hexdigest()}"
-
- # Extract filename and path
- source_path = result['metadata'].get('source', 'Unknown')
- filename = result['metadata'].get('filename', os.path.basename(source_path))
-
- # Create preview snippet (first ~200 chars of content)
- snippet = result['content'][:200] + "..." if len(result['content']) > 200 else result['content']
-
- # Determine which collection this document belongs to
- collection_name = "Unknown"
- folder_path = result['folder']
- for name, collection in self.collections.items():
- if any(folder_path.startswith(path) for path in collection.get("paths", [])):
- collection_name = name
- break
-
- # Format the preview
- preview = {
- "id": result_id,
- "title": filename,
- "snippet": snippet,
- "link": source_path,
- "similarity": result['similarity'],
- "folder": folder_path,
- "collection": collection_name,
- "collection_description": self.collections.get(collection_name, {}).get("description", ""),
- "_full_content": result['content'], # Store full content for later
- "_metadata": result['metadata'] # Store metadata for later
- }
-
- previews.append(preview)
-
- logger.info(f"Found {len(previews)} local document matches")
- return previews
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant documents.
- For local search, the full content is already available.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should add full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- logger.info("Snippet-only mode, skipping full content addition")
- return relevant_items
-
- # For local search, we already have the full content
- results = []
- for item in relevant_items:
- # Create a copy with full content
- result = item.copy()
-
- # Add full content if we have it
- if "_full_content" in item:
- result["content"] = item["_full_content"]
- result["full_content"] = item["_full_content"]
-
- # Remove temporary fields
- if "_full_content" in result:
- del result["_full_content"]
-
- # Add metadata if we have it
- if "_metadata" in item:
- result["document_metadata"] = item["_metadata"]
-
- # Remove temporary fields
- if "_metadata" in result:
- del result["_metadata"]
-
- results.append(result)
-
- return results
-
- def run(self, query: str, collection_names: Optional[List[str]] = None) -> List[Dict[str, Any]]:
- """
- Execute a search using the two-phase approach.
-
- Args:
- query: The search query
- collection_names: Specific collections to search within (if None, search all)
-
- Returns:
- List of search result dictionaries with full content
- """
- logger.info(f"---Execute a search using Local Documents---")
-
- # Check if we have any special collection parameters in the query
- collection_prefix = "collection:"
- remaining_query = query
- specified_collections = []
-
- # Parse query for collection specifications like "collection:research_papers query terms"
- query_parts = query.split()
- for part in query_parts:
- if part.lower().startswith(collection_prefix):
- collection_name = part[len(collection_prefix):].strip()
- if collection_name in self.collections:
- specified_collections.append(collection_name)
- # Remove this part from the query
- remaining_query = remaining_query.replace(part, "", 1).strip()
-
- # If collections were specified in the query, they override the parameter
- if specified_collections:
- collection_names = specified_collections
- query = remaining_query
-
- # Phase 1: Get previews (with collection filtering)
- previews = self._get_previews(query, collection_names)
-
- if not previews:
- return []
-
- # Phase 2: Filter for relevance
- relevant_items = self._filter_for_relevance(previews, query)
-
- if not relevant_items:
- return []
-
- # Phase 3: Get full content for relevant items
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Returning snippet-only results as per config")
- results = relevant_items
- else:
- results = self._get_full_content(relevant_items)
-
- # Clean up temporary data
- self.embedding_manager.clear_cache()
-
- return results
-
- def get_collections_info(self) -> List[Dict[str, Any]]:
- """
- Get information about all collections, including indexing status.
-
- Returns:
- List of collection information dictionaries
- """
- collections_info = []
-
- for name, collection in self.collections.items():
- paths = collection.get("paths", [])
- description = collection.get("description", "")
-
- # Get indexing information for each path
- paths_info = []
- for path in paths:
- # Check if folder exists
- exists = os.path.exists(path) and os.path.isdir(path)
-
- # Check if folder is indexed
- folder_hash = self.embedding_manager._get_folder_hash(path)
- indexed = folder_hash in self.embedding_manager.indexed_folders
-
- # Get index details if available
- index_info = {}
- if indexed:
- index_info = self.embedding_manager.indexed_folders[folder_hash].copy()
-
- paths_info.append({
- "path": path,
- "exists": exists,
- "indexed": indexed,
- "index_info": index_info
- })
-
- collections_info.append({
- "name": name,
- "description": description,
- "paths": paths,
- "paths_info": paths_info,
- "document_count": sum(info.get("index_info", {}).get("file_count", 0) for info in paths_info),
- "chunk_count": sum(info.get("index_info", {}).get("chunk_count", 0) for info in paths_info),
- "all_indexed": all(info["indexed"] for info in paths_info if info["exists"])
- })
-
- return collections_info
-
- def reindex_collection(self, collection_name: str) -> bool:
- """
- Reindex a specific collection.
-
- Args:
- collection_name: Name of the collection to reindex
-
- Returns:
- True if reindexing was successful, False otherwise
- """
- if collection_name not in self.collections:
- logger.error(f"Collection '{collection_name}' not found")
- return False
-
- paths = self.collections[collection_name].get("paths", [])
- success = True
-
- for path in paths:
- if not self.embedding_manager.index_folder(path, force_reindex=True):
- success = False
-
- return success
-
- @classmethod
- def from_config(cls, config_dict: Dict[str, Any], llm: Optional[BaseLLM] = None) -> "LocalSearchEngine":
- """
- Create a LocalSearchEngine instance from a configuration dictionary.
-
- Args:
- config_dict: Configuration dictionary
- llm: Language model for relevance filtering
-
- Returns:
- Initialized LocalSearchEngine instance
- """
- # Required parameters
- folder_paths = []
- collections = config_dict.get("collections", {})
-
- # Extract all folder paths from collections
- for collection_config in collections.values():
- if "paths" in collection_config:
- folder_paths.extend(collection_config["paths"])
-
- # Fall back to folder_paths if no collections defined
- if not folder_paths:
- folder_paths = config_dict.get("folder_paths", [])
- # Create a default collection if using folder_paths
- if folder_paths:
- collections = {"default": {"paths": folder_paths, "description": "Default collection"}}
-
- # Optional parameters with defaults
- max_results = config_dict.get("max_results", 10)
- max_filtered_results = config_dict.get("max_filtered_results")
- embedding_model = config_dict.get("embedding_model", "all-MiniLM-L6-v2")
- embedding_device = config_dict.get("embedding_device", "cpu")
- embedding_model_type = config_dict.get("embedding_model_type", "sentence_transformers")
- ollama_base_url = config_dict.get("ollama_base_url")
- force_reindex = config_dict.get("force_reindex", False)
- chunk_size = config_dict.get("chunk_size", 1000)
- chunk_overlap = config_dict.get("chunk_overlap", 200)
- cache_dir = config_dict.get("cache_dir", ".cache/local_search")
-
- return cls(
- folder_paths=folder_paths,
- collections=collections,
- llm=llm,
- max_results=max_results,
- max_filtered_results=max_filtered_results,
- embedding_model=embedding_model,
- embedding_device=embedding_device,
- embedding_model_type=embedding_model_type,
- ollama_base_url=ollama_base_url,
- force_reindex=force_reindex,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- cache_dir=cache_dir
- )
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_local_all.py b/web_search_engines/engines/search_engine_local_all.py
deleted file mode 100644
index e62dbe7718..0000000000
--- a/web_search_engines/engines/search_engine_local_all.py
+++ /dev/null
@@ -1,153 +0,0 @@
-"""
-Search engine that searches across all local collections
-"""
-
-import logging
-from typing import Dict, List, Any, Optional
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-from web_search_engines.search_engine_factory import create_search_engine
-import config
-
-# Setup logging
-logger = logging.getLogger(__name__)
-
-class LocalAllSearchEngine(BaseSearchEngine):
- """
- Search engine that searches across all local document collections.
- Acts as a meta search engine specifically for local collections.
- """
-
- def __init__(
- self,
- llm: Optional[BaseLLM] = None,
- max_results: int = 10,
- max_filtered_results: Optional[int] = None,
- **kwargs
- ):
- """
- Initialize the local all-collections search engine.
-
- Args:
- llm: Language model for relevance filtering
- max_results: Maximum number of search results
- max_filtered_results: Maximum results after filtering
- **kwargs: Additional parameters passed to LocalSearchEngine instances
- """
- # Initialize the base search engine
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
-
- # Find all local collection search engines
- self.local_engines = {}
- try:
- from local_collections import LOCAL_COLLECTIONS
-
- for collection_id, collection in LOCAL_COLLECTIONS.items():
- if not collection.get("enabled", True):
- continue
-
- # Create a search engine for this collection
- try:
- engine = create_search_engine(
- collection_id,
- llm=llm,
- max_filtered_results=max_filtered_results
- )
-
- if engine:
- self.local_engines[collection_id] = {
- "engine": engine,
- "name": collection.get("name", collection_id),
- "description": collection.get("description", "")
- }
- except Exception as e:
- logger.error(f"Error creating search engine for collection '{collection_id}': {e}")
- except ImportError:
- logger.warning("No local collections configuration found")
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information for documents from all local collections.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- logger.info(f"Searching across all local collections for query: {query}")
-
- all_previews = []
-
- # Get previews from each local search engine
- for collection_id, engine_info in self.local_engines.items():
- engine = engine_info["engine"]
- try:
- # Get previews from this engine
- previews = engine._get_previews(query)
-
- # Add collection info to each preview
- for preview in previews:
- preview["collection_id"] = collection_id
- preview["collection_name"] = engine_info["name"]
- preview["collection_description"] = engine_info["description"]
-
- all_previews.extend(previews)
- except Exception as e:
- logger.error(f"Error searching collection '{collection_id}': {e}")
-
- if not all_previews:
- logger.info(f"No local documents found for query: {query}")
- return []
-
- # Sort by similarity score if available
- all_previews.sort(
- key=lambda x: float(x.get("similarity", 0)),
- reverse=True
- )
-
- # Limit to max_results
- return all_previews[:self.max_results]
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant documents.
- Delegates to the appropriate collection's search engine.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Group items by collection
- items_by_collection = {}
- for item in relevant_items:
- collection_id = item.get("collection_id")
- if collection_id and collection_id in self.local_engines:
- if collection_id not in items_by_collection:
- items_by_collection[collection_id] = []
- items_by_collection[collection_id].append(item)
-
- # Process each collection's items with its own engine
- all_results = []
- for collection_id, items in items_by_collection.items():
- engine = self.local_engines[collection_id]["engine"]
- try:
- results = engine._get_full_content(items)
- all_results.extend(results)
- except Exception as e:
- logger.error(f"Error getting full content from collection '{collection_id}': {e}")
- # Fall back to returning the items without full content
- all_results.extend(items)
-
- # Add any items that weren't processed
- processed_ids = set(item["id"] for item in all_results)
- for item in relevant_items:
- if item["id"] not in processed_ids:
- all_results.append(item)
-
- return all_results
diff --git a/web_search_engines/engines/search_engine_medrxiv.py b/web_search_engines/engines/search_engine_medrxiv.py
deleted file mode 100644
index 4aa64a70e0..0000000000
--- a/web_search_engines/engines/search_engine_medrxiv.py
+++ /dev/null
@@ -1,623 +0,0 @@
-from typing import Dict, List, Any, Optional
-from langchain_core.language_models import BaseLLM
-import requests
-import logging
-import re
-import time
-from datetime import datetime
-import xml.etree.ElementTree as ET
-from urllib.parse import quote
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-# Setup logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-class MedRxivSearchEngine(BaseSearchEngine):
- """medRxiv search engine implementation with two-phase approach"""
-
- def __init__(self,
- max_results: int = 10,
- sort_by: str = "relevance_score",
- sort_order: str = "desc",
- include_full_text: bool = False,
- download_dir: Optional[str] = None,
- max_full_text: int = 1,
- llm: Optional[BaseLLM] = None,
- max_filtered_results: Optional[int] = None,
- days_limit: Optional[int] = None,
- optimize_queries: bool = True):
- """
- Initialize the medRxiv search engine.
-
- Args:
- max_results: Maximum number of search results
- sort_by: Sorting criteria ('relevance_score', 'date', or 'date_posted')
- sort_order: Sort order ('desc' or 'asc')
- include_full_text: Whether to include full paper content in results (downloads PDF)
- download_dir: Directory to download PDFs to (if include_full_text is True)
- max_full_text: Maximum number of PDFs to download and process (default: 1)
- llm: Language model for relevance filtering
- max_filtered_results: Maximum number of results to keep after filtering
- days_limit: Limit results to papers from the last N days
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.sort_by = sort_by
- self.sort_order = sort_order
- self.include_full_text = include_full_text
- self.download_dir = download_dir
- self.max_full_text = max_full_text
- self.days_limit = days_limit
- self.optimize_queries = optimize_queries
-
- # medRxiv API endpoints
- self.search_base_url = "https://api.biorxiv.org/covid19/{}/{{}}".format(
- "desc" if sort_order.lower() == "desc" else "asc"
- )
- self.medrxiv_api_url = "https://api.biorxiv.org/details/medrxiv/{}/"
-
- # medRxiv base URL for papers
- self.medrxiv_base_url = "https://www.medrxiv.org/content/"
-
- def _optimize_query_for_medrxiv(self, query: str) -> str:
- """
- Optimize a natural language query for medRxiv search.
- Uses LLM to transform questions into effective keyword-based queries.
-
- Args:
- query: Natural language query
-
- Returns:
- Optimized query string for medRxiv
- """
- if not self.llm or not self.optimize_queries:
- # Return original query if no LLM available or optimization disabled
- return query
-
- try:
- # Prompt for query optimization
- prompt = f"""Transform this natural language question into an optimized search query for medRxiv (a medical preprint server).
-
-Original query: "{query}"
-
-CRITICAL RULES:
-1. ONLY RETURN THE EXACT SEARCH QUERY - NO EXPLANATIONS, NO COMMENTS
-2. Focus on clear medical terminology and keywords
-3. Keep it concise but comprehensive (typically 2-5 key terms)
-4. Include specific medical conditions, treatments, or methodologies
-5. Use Boolean operators (AND, OR) when appropriate
-6. Include common medical acronyms where relevant (e.g., COVID-19 instead of coronavirus disease)
-7. Put multi-word phrases in quotes (e.g., "long covid")
-8. Prioritize specific medical terms over general descriptions
-
-EXAMPLE CONVERSIONS:
-✓ "what are the neurological effects of long COVID?" → "long covid" AND neurological OR "nervous system"
-✓ "newest vaccine development for covid variants" → COVID-19 AND vaccine AND variant
-✗ BAD: "Here's a query to find information about..."
-✗ BAD: "The most effective search query would be..."
-
-Return ONLY the search query without any explanations.
-"""
-
- # Get response from LLM
- response = self.llm.invoke(prompt)
- optimized_query = response.content.strip()
-
- # Clean up the query - remove any explanations
- lines = optimized_query.split('\n')
- for line in lines:
- line = line.strip()
- if line and not line.lower().startswith(('here', 'i would', 'the best', 'this query')):
- optimized_query = line
- break
-
- # Remove any quotes that wrap the entire query
- if optimized_query.startswith('"') and optimized_query.endswith('"'):
- optimized_query = optimized_query[1:-1]
-
- logger.info(f"Original query: '{query}'")
- logger.info(f"Optimized for medRxiv: '{optimized_query}'")
-
- return optimized_query
-
- except Exception as e:
- logger.error(f"Error optimizing query: {e}")
- return query # Fall back to original query on error
-
- def _search_medrxiv(self, query: str) -> List[Dict[str, Any]]:
- """
- Search medRxiv using their API.
-
- Args:
- query: The search query
-
- Returns:
- List of paper dictionaries
- """
- results = []
- cursor = 0
- max_per_page = 50 # medRxiv API typically returns 50 results per page
- total_fetched = 0
-
- try:
- # URL encode the query
- encoded_query = quote(query)
-
- # Format the URL based on sorting and query
- url = self.search_base_url.format(encoded_query)
-
- # Add time restriction if specified
- if self.days_limit:
- # Calculate date range using days_limit
- from datetime import datetime, timedelta
- end_date = datetime.now()
- start_date = end_date - timedelta(days=self.days_limit)
-
- # Format dates for the API (YYYY-MM-DD)
- start_date_str = start_date.strftime("%Y-%m-%d")
- end_date_str = end_date.strftime("%Y-%m-%d")
-
- # Add date parameters to URL
- url += f"/{start_date_str}/{end_date_str}"
- logger.info(f"Using date range filter: {start_date_str} to {end_date_str}")
-
- while total_fetched < self.max_results:
- # Add cursor to URL
- page_url = f"{url}/{cursor}"
-
- # Make the request
- logger.debug(f"Requesting: {page_url}")
- response = requests.get(page_url)
- if response.status_code != 200:
- logger.error(f"Error searching medRxiv: {response.status_code}")
- break
-
- data = response.json()
-
- # Check if we have results
- collection = data.get("collection", [])
- if not collection:
- break
-
- # Extract results
- for paper in collection:
- if paper.get("server") == "medRxiv": # Ensure we're only getting medRxiv papers
- results.append(paper)
- total_fetched += 1
-
- if total_fetched >= self.max_results:
- break
-
- # Check if we should continue to next page
- if len(collection) < max_per_page or total_fetched >= self.max_results:
- break
-
- cursor += max_per_page
- time.sleep(0.5) # Be respectful with API requests
-
- logger.info(f"Found {len(results)} papers from medRxiv for query: {query}")
- return results
-
- except Exception as e:
- logger.error(f"Error searching medRxiv: {e}")
- return []
-
- def _get_paper_details(self, doi: str) -> Dict[str, Any]:
- """
- Get detailed information about a specific paper using its DOI.
-
- Args:
- doi: Digital Object Identifier for the paper
-
- Returns:
- Dictionary with paper details
- """
- try:
- # Format the DOI for the API
- formatted_doi = doi.replace("10.1101/", "")
-
- # Get paper details from the API
- url = self.medrxiv_api_url.format(formatted_doi)
- response = requests.get(url)
-
- if response.status_code != 200:
- logger.error(f"Error getting paper details: {response.status_code}")
- return {}
-
- data = response.json()
-
- # Extract the paper details
- collection = data.get("collection", [])
- if not collection:
- return {}
-
- return collection[0]
-
- except Exception as e:
- logger.error(f"Error getting paper details: {e}")
- return {}
-
- def _get_full_text_url(self, doi: str) -> Optional[str]:
- """
- Get the URL for the full text PDF of a paper.
-
- Args:
- doi: Digital Object Identifier for the paper
-
- Returns:
- URL to the PDF or None if not available
- """
- pdf_url = None
-
- try:
- # Format the DOI for the URL
- formatted_doi = doi.replace("10.1101/", "")
-
- # Construct the PDF URL
- # Note: This is a typical pattern for medRxiv PDFs, but may need adjustment
- pdf_url = f"https://www.medrxiv.org/content/10.1101/{formatted_doi}.full.pdf"
-
- # Verify the URL is valid (optional)
- response = requests.head(pdf_url)
- if response.status_code != 200:
- logger.warning(f"PDF not available at {pdf_url}")
- return None
-
- return pdf_url
-
- except Exception as e:
- logger.error(f"Error getting PDF URL: {e}")
- return None
-
- def _download_pdf(self, pdf_url: str, file_name: str) -> Optional[str]:
- """
- Download a PDF from a URL to the specified download directory.
-
- Args:
- pdf_url: URL to the PDF
- file_name: Name to save the file as
-
- Returns:
- Path to the downloaded file or None if download failed
- """
- if not self.download_dir:
- return None
-
- import os
-
- try:
- # Create download directory if it doesn't exist
- os.makedirs(self.download_dir, exist_ok=True)
-
- # Clean the filename
- safe_name = re.sub(r'[^\w\-_\.]', '_', file_name)
- file_path = os.path.join(self.download_dir, safe_name)
-
- # Download the file
- response = requests.get(pdf_url, stream=True)
- response.raise_for_status()
-
- with open(file_path, 'wb') as f:
- for chunk in response.iter_content(chunk_size=8192):
- f.write(chunk)
-
- logger.info(f"Downloaded PDF to {file_path}")
- return file_path
-
- except Exception as e:
- logger.error(f"Error downloading PDF: {e}")
- return None
-
- def _extract_text_from_pdf(self, pdf_path: str) -> str:
- """
- Extract text from a PDF file.
-
- Args:
- pdf_path: Path to the PDF file
-
- Returns:
- Extracted text or empty string if extraction failed
- """
- text = ""
-
- try:
- # First try PyPDF2
- try:
- import PyPDF2
- with open(pdf_path, 'rb') as pdf_file:
- pdf_reader = PyPDF2.PdfReader(pdf_file)
- for page in pdf_reader.pages:
- text += page.extract_text() + "\n\n"
- except (ImportError, Exception) as e1:
- # Fall back to pdfplumber
- try:
- import pdfplumber
- with pdfplumber.open(pdf_path) as pdf:
- for page in pdf.pages:
- text += page.extract_text() + "\n\n"
- except (ImportError, Exception) as e2:
- logger.error(f"PDF extraction failed with both methods: {e1}, then {e2}")
- return ""
-
- return text
-
- except Exception as e:
- logger.error(f"Error extracting text from PDF: {e}")
- return ""
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information for medRxiv papers.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- logger.info(f"Getting medRxiv previews for query: {query}")
-
- # Optimize the query for medRxiv if LLM is available
- if self.optimize_queries and self.llm:
- optimized_query = self._optimize_query_for_medrxiv(query)
-
- # Store original and optimized queries for potential fallback
- self._original_query = query
- self._optimized_query = optimized_query
-
- # Store for simplification if needed
- self._simplify_query_cache = optimized_query
-
- # Use the optimized query for adaptive search
- papers, strategy = self._adaptive_search(optimized_query)
- else:
- # Use the original query directly with adaptive search
- papers, strategy = self._adaptive_search(query)
-
- # If no results, return empty list
- if not papers:
- logger.warning(f"No medRxiv results found using strategy: {strategy}")
- return []
-
- # Store the paper objects for later use
- self._papers = {paper.get("doi"): paper for paper in papers}
- self._search_strategy = strategy
-
- # Format results as previews
- previews = []
- for paper in papers:
- # Extract the data
- doi = paper.get("doi", "")
- title = paper.get("title", "")
- abstract = paper.get("abstract", "")
- authors = paper.get("authors", "")
- date = paper.get("date", "")
-
- # Create a preview
- preview = {
- "id": doi, # Use DOI as ID
- "title": title,
- "link": f"https://www.medrxiv.org/content/{doi}v1",
- "snippet": abstract[:250] + "..." if len(abstract) > 250 else abstract,
- "authors": authors.split("; ") if authors else [],
- "published": date,
- "doi": doi,
- "source": "medRxiv",
- "_search_strategy": strategy # Store search strategy for analytics
- }
-
- previews.append(preview)
-
- logger.info(f"Found {len(previews)} medRxiv previews using strategy: {strategy}")
- return previews
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant medRxiv papers.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should get full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info(f"Getting full content for {len(relevant_items)} medRxiv papers")
-
- results = []
- pdf_count = 0 # Track number of PDFs processed
-
- for item in relevant_items:
- # Start with the preview data
- result = item.copy()
-
- # Get the paper DOI
- doi = item.get("id") or item.get("doi")
-
- if not doi:
- results.append(result)
- continue
-
- # Try to get the cached paper details
- paper = None
- if hasattr(self, '_papers') and doi in self._papers:
- paper = self._papers[doi]
- else:
- # Get the paper details from the API
- paper = self._get_paper_details(doi)
-
- if paper:
- # Update with more complete information
- result.update({
- "title": paper.get("title", result.get("title", "")),
- "authors": paper.get("authors", "").split("; ") if paper.get("authors") else result.get("authors", []),
- "published": paper.get("date", result.get("published", "")),
- "abstract": paper.get("abstract", ""),
- "doi": paper.get("doi", doi),
- "category": paper.get("category", ""),
- "journal": "medRxiv", # It's a preprint server
- "version": paper.get("version", "1"),
- "type": paper.get("type", "new_result"),
- })
-
- # Use abstract as content by default
- result["content"] = paper.get("abstract", "")
- result["full_content"] = paper.get("abstract", "")
-
- # Add search strategy if available
- if "_search_strategy" in item:
- result["search_strategy"] = item["_search_strategy"]
- # Remove temporary field
- if "_search_strategy" in result:
- del result["_search_strategy"]
-
- # Download PDF and extract text if requested and within limit
- if (self.include_full_text and self.download_dir and
- pdf_count < self.max_full_text):
- try:
- # Get the PDF URL
- pdf_url = self._get_full_text_url(doi)
-
- if pdf_url:
- # Download the PDF
- pdf_count += 1
- safe_name = f"medrxiv_{doi.replace('/', '_')}.pdf"
- pdf_path = self._download_pdf(pdf_url, safe_name)
-
- if pdf_path:
- result["pdf_path"] = pdf_path
-
- # Extract text from PDF
- pdf_text = self._extract_text_from_pdf(pdf_path)
-
- if pdf_text:
- result["content"] = pdf_text
- result["full_content"] = pdf_text
- result["content_type"] = "full_text"
- else:
- result["content_type"] = "abstract"
- except Exception as e:
- logger.error(f"Error processing PDF for {doi}: {e}")
- result["content_type"] = "abstract"
-
- results.append(result)
-
- return results
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Execute a search using medRxiv with the two-phase approach.
-
- Args:
- query: The search query
-
- Returns:
- List of search results
- """
- logger.info(f"---Execute a search using medRxiv---")
-
- # Use the implementation from the parent class which handles all phases
- # _get_previews will handle query optimization and adaptive search
- results = super().run(query)
-
- # Clean up temporary variables
- if hasattr(self, '_papers'):
- del self._papers
- if hasattr(self, '_original_query'):
- del self._original_query
- if hasattr(self, '_optimized_query'):
- del self._optimized_query
- if hasattr(self, '_simplify_query_cache'):
- del self._simplify_query_cache
- if hasattr(self, '_search_strategy'):
- del self._search_strategy
-
- return results
-
- def search_by_author(self, author_name: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for papers by a specific author.
-
- Args:
- author_name: Name of the author
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of papers by the author
- """
- original_max_results = self.max_results
-
- try:
- if max_results:
- self.max_results = max_results
-
- # medRxiv API doesn't have direct author search, so we include in query
- query = f"author:{author_name}"
- return self.run(query)
-
- finally:
- # Restore original value
- self.max_results = original_max_results
-
- def search_by_topic(self, topic: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for papers on a specific topic.
-
- Args:
- topic: Topic to search for
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of papers on the topic
- """
- original_max_results = self.max_results
-
- try:
- if max_results:
- self.max_results = max_results
-
- return self.run(topic)
-
- finally:
- # Restore original value
- self.max_results = original_max_results
-
- def search_recent(self, days: int = 30, topic: Optional[str] = None, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for recent papers, optionally filtered by topic.
-
- Args:
- days: Number of days to look back
- topic: Optional topic filter
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of recent papers
- """
- original_max_results = self.max_results
- original_days_limit = self.days_limit
-
- try:
- if max_results:
- self.max_results = max_results
-
- # Set days limit for this search
- self.days_limit = days
-
- # If topic is provided, use it as query, otherwise use a broad query
- query = topic if topic else "covid" # Default to COVID which will have many papers
- return self.run(query)
-
- finally:
- # Restore original values
- self.max_results = original_max_results
- self.days_limit = original_days_limit
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_pubmed.py b/web_search_engines/engines/search_engine_pubmed.py
deleted file mode 100644
index 7fd1ddd282..0000000000
--- a/web_search_engines/engines/search_engine_pubmed.py
+++ /dev/null
@@ -1,992 +0,0 @@
-import requests
-import logging
-import xml.etree.ElementTree as ET
-from typing import Dict, List, Any, Optional, Tuple
-from langchain_core.language_models import BaseLLM
-import time
-import re
-from datetime import datetime
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-# Setup logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-class PubMedSearchEngine(BaseSearchEngine):
- """
- PubMed search engine implementation with two-phase approach and adaptive search.
- Provides efficient access to biomedical literature while minimizing API usage.
- """
-
- def __init__(self,
- max_results: int = 10,
- api_key: Optional[str] = None,
- days_limit: Optional[int] = None,
- get_abstracts: bool = True,
- get_full_text: bool = False,
- full_text_limit: int = 3,
- llm: Optional[BaseLLM] = None,
- max_filtered_results: Optional[int] = None,
- optimize_queries: bool = True):
- """
- Initialize the PubMed search engine.
-
- Args:
- max_results: Maximum number of search results
- api_key: NCBI API key for higher rate limits (optional)
- days_limit: Limit results to N days (optional)
- get_abstracts: Whether to fetch abstracts for all results
- get_full_text: Whether to fetch full text content (when available in PMC)
- full_text_limit: Max number of full-text articles to retrieve
- llm: Language model for relevance filtering
- max_filtered_results: Maximum number of results to keep after filtering
- optimize_queries: Whether to optimize natural language queries for PubMed
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.api_key = api_key
- self.days_limit = days_limit
- self.get_abstracts = get_abstracts
- self.get_full_text = get_full_text
- self.full_text_limit = full_text_limit
- self.optimize_queries = optimize_queries
-
- # Base API URLs
- self.base_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils"
- self.search_url = f"{self.base_url}/esearch.fcgi"
- self.summary_url = f"{self.base_url}/esummary.fcgi"
- self.fetch_url = f"{self.base_url}/efetch.fcgi"
- self.link_url = f"{self.base_url}/elink.fcgi"
-
- # PMC base URL for full text
- self.pmc_url = "https://www.ncbi.nlm.nih.gov/pmc/articles/"
-
- def _get_result_count(self, query: str) -> int:
- """
- Get the total number of results for a query without retrieving the results themselves.
-
- Args:
- query: The search query
-
- Returns:
- Total number of matching results
- """
- try:
- # Prepare search parameters
- params = {
- "db": "pubmed",
- "term": query,
- "retmode": "json",
- "retmax": 0 # Don't need actual results, just the count
- }
-
- # Add API key if available
- if self.api_key:
- params["api_key"] = self.api_key
-
- # Execute search request
- response = requests.get(self.search_url, params=params)
- response.raise_for_status()
-
- # Parse response
- data = response.json()
- count = int(data["esearchresult"]["count"])
-
- logger.info(f"Query '{query}' has {count} total results in PubMed")
- return count
-
- except Exception as e:
- logger.error(f"Error getting result count: {e}")
- return 0
-
- def _extract_core_terms(self, query: str) -> str:
- """
- Extract core terms from a complex query for volume estimation.
-
- Args:
- query: PubMed query string
-
- Returns:
- Simplified query with core terms
- """
- # Remove field specifications and operators
- simplified = re.sub(r'\[\w+\]', '', query) # Remove [Field] tags
- simplified = re.sub(r'\b(AND|OR|NOT)\b', '', simplified) # Remove operators
-
- # Remove quotes and parentheses
- simplified = simplified.replace('"', '').replace('(', '').replace(')', '')
-
- # Split by whitespace and join terms with 4+ chars (likely meaningful)
- terms = [term for term in simplified.split() if len(term) >= 4]
-
- # Join with AND to create a basic search
- return " ".join(terms[:5]) # Limit to top 5 terms
-
- def _expand_time_window(self, time_filter: str) -> str:
- """
- Expand a time window to get more results.
-
- Args:
- time_filter: Current time filter
-
- Returns:
- Expanded time filter
- """
- # Parse current time window
- import re
- match = re.match(r'"last (\d+) (\w+)"[pdat]', time_filter)
- if not match:
- return '"last 10 years"[pdat]'
-
- amount, unit = int(match.group(1)), match.group(2)
-
- # Expand based on current unit
- if unit == "months" or unit == "month":
- if amount < 6:
- return '"last 6 months"[pdat]'
- elif amount < 12:
- return '"last 1 year"[pdat]'
- else:
- return '"last 2 years"[pdat]'
- elif unit == "years" or unit == "year":
- if amount < 2:
- return '"last 2 years"[pdat]'
- elif amount < 5:
- return '"last 5 years"[pdat]'
- else:
- return '"last 10 years"[pdat]'
-
- return '"last 10 years"[pdat]'
-
- def _optimize_query_for_pubmed(self, query: str) -> str:
- """
- Optimize a natural language query for PubMed search.
- Uses LLM to transform questions into effective keyword-based queries.
-
- Args:
- query: Natural language query
-
- Returns:
- Optimized query string for PubMed
- """
- if not self.llm or not self.optimize_queries:
- # Return original query if no LLM available or optimization disabled
- return query
-
- try:
- # Prompt for query optimization
- prompt = f"""Transform this natural language question into an optimized PubMed search query.
-
-Original query: "{query}"
-
-CRITICAL RULES:
-1. ONLY RETURN THE EXACT SEARCH QUERY - NO EXPLANATIONS, NO COMMENTS
-2. DO NOT wrap the entire query in quotes
-3. DO NOT include ANY date restrictions or year filters
-4. Use parentheses around OR statements: (term1[Field] OR term2[Field])
-5. Use only BASIC MeSH terms - stick to broad categories like "Vaccines"[Mesh]
-6. KEEP IT SIMPLE - use 2-3 main concepts maximum
-7. Focus on Title/Abstract searches for reliability: term[Title/Abstract]
-8. Use wildcards for variations: vaccin*[Title/Abstract]
-
-EXAMPLE QUERIES:
-✓ GOOD: (mRNA[Title/Abstract] OR "messenger RNA"[Title/Abstract]) AND vaccin*[Title/Abstract]
-✓ GOOD: (influenza[Title/Abstract] OR flu[Title/Abstract]) AND treatment[Title/Abstract]
-✗ BAD: (mRNA[Title/Abstract]) AND "specific disease"[Mesh] AND treatment[Title/Abstract] AND 2023[dp]
-✗ BAD: "Here's a query to find articles about vaccines..."
-
-Return ONLY the search query without any explanations.
-"""
-
- # Get response from LLM
- response = self.llm.invoke(prompt)
- raw_response = response.content.strip()
-
- # Clean up the query - extract only the actual query and remove any explanations
- # First check if there are multiple lines and take the first non-empty line
- lines = raw_response.split('\n')
- cleaned_lines = [line.strip() for line in lines if line.strip()]
-
- if cleaned_lines:
- optimized_query = cleaned_lines[0]
-
- # Remove any quotes that wrap the entire query
- if optimized_query.startswith('"') and optimized_query.endswith('"'):
- optimized_query = optimized_query[1:-1]
-
- # Remove any explanation phrases that might be at the beginning
- explanation_starters = ["here is", "here's", "this query", "the following"]
- for starter in explanation_starters:
- if optimized_query.lower().startswith(starter):
- # Find the actual query part - typically after a colon
- colon_pos = optimized_query.find(':')
- if colon_pos > 0:
- optimized_query = optimized_query[colon_pos + 1:].strip()
-
- # Check if the query still seems to contain explanations
- if len(optimized_query) > 200 or "this query will" in optimized_query.lower():
- # It's probably still an explanation - try to extract just the query part
- # Look for common patterns in the explanation like parentheses
- pattern = r'\([^)]+\)\s+AND\s+'
- import re
- matches = re.findall(pattern, optimized_query)
- if matches:
- # Extract just the query syntax parts
- query_parts = []
- for part in re.split(r'\.\s+', optimized_query):
- if '(' in part and ')' in part and ('AND' in part or 'OR' in part):
- query_parts.append(part)
- if query_parts:
- optimized_query = ' '.join(query_parts)
- else:
- # Fall back to original query if cleaning fails
- logger.warning("Failed to extract a clean query from LLM response")
- optimized_query = query
-
- # Final safety check - if query looks too much like an explanation, use original
- if len(optimized_query.split()) > 30:
- logger.warning("Query too verbose, falling back to simpler form")
- # Create a simple query from the original
- words = [w for w in query.split() if len(w) > 3 and w.lower() not in ('what', 'are', 'the', 'and', 'for', 'with', 'from', 'have', 'been', 'recent')]
- optimized_query = ' AND '.join(words[:3])
-
- # Safety check for invalid or overly complex MeSH terms
- # This helps prevent errors with non-existent or complex MeSH terms
- import re
- mesh_terms = re.findall(r'"[^"]+"[Mesh]', optimized_query)
- known_valid_mesh = ["Vaccines", "COVID-19", "Influenza", "Infectious Disease Medicine",
- "Communicable Diseases", "RNA, Messenger", "Vaccination",
- "Immunization"]
-
- # Replace potentially problematic MeSH terms with Title/Abstract searches
- for term in mesh_terms:
- term_name = term.split('"')[1] # Extract term name without quotes and [Mesh]
- if not any(valid in term_name for valid in known_valid_mesh):
- # Replace with Title/Abstract search
- replacement = f"{term_name.lower()}[Title/Abstract]"
- optimized_query = optimized_query.replace(term, replacement)
-
- # Simplify the query if still no results are found
- self._simplify_query_cache = optimized_query
-
- # Log original and optimized queries
- logger.info(f"Original query: '{query}'")
- logger.info(f"Optimized for PubMed: '{optimized_query}'")
-
- return optimized_query
-
- except Exception as e:
- logger.error(f"Error optimizing query: {e}")
- return query # Fall back to original query on error
-
- def _simplify_query(self, query: str) -> str:
- """
- Simplify a PubMed query that returned no results.
- Progressively removes elements to get a more basic query.
-
- Args:
- query: The original query that returned no results
-
- Returns:
- Simplified query
- """
- logger.info(f"Simplifying query: {query}")
-
- # Attempt different simplification strategies
-
- # 1. Remove any MeSH terms and replace with Title/Abstract
- import re
- simplified = re.sub(r'"[^"]+"[Mesh]', lambda m: m.group(0).split('"')[1].lower() + "[Title/Abstract]", query)
-
- # 2. If that doesn't work, focus on just mRNA and vaccines - the core concepts
- if simplified == query: # No changes were made
- simplified = "(mRNA[Title/Abstract] OR \"messenger RNA\"[Title/Abstract]) AND vaccin*[Title/Abstract]"
-
- logger.info(f"Simplified query: {simplified}")
- return simplified
-
- def _is_historical_focused(self, query: str) -> bool:
- """
- Determine if a query is specifically focused on historical/older information using LLM.
- Default assumption is that queries should prioritize recent information unless
- explicitly asking for historical content.
-
- Args:
- query: The search query
-
- Returns:
- Boolean indicating if the query is focused on historical information
- """
- if not self.llm:
- # Fall back to basic keyword check if no LLM available
- historical_terms = ["history", "historical", "early", "initial", "first", "original",
- "before", "prior to", "origins", "evolution", "development"]
- historical_years = [str(year) for year in range(1900, 2020)]
-
- query_lower = query.lower()
- has_historical_term = any(term in query_lower for term in historical_terms)
- has_past_year = any(year in query for year in historical_years)
-
- return has_historical_term or has_past_year
-
- try:
- # Use LLM to determine if the query is focused on historical information
- prompt = f"""Determine if this query is specifically asking for HISTORICAL or OLDER information.
-
-Query: "{query}"
-
-Answer ONLY "yes" if the query is clearly asking for historical, early, original, or past information from more than 5 years ago.
-Answer ONLY "no" if the query is asking about recent, current, or new information, or if it's a general query without a specific time focus.
-
-The default assumption should be that medical and scientific queries want RECENT information unless clearly specified otherwise.
-"""
-
- response = self.llm.invoke(prompt)
- answer = response.content.strip().lower()
-
- # Log the determination
- logger.info(f"Historical focus determination for query: '{query}'")
- logger.info(f"LLM determined historical focus: {answer}")
-
- return "yes" in answer
-
- except Exception as e:
- logger.error(f"Error determining historical focus: {e}")
- # Fall back to basic keyword check
- historical_terms = ["history", "historical", "early", "initial", "first", "original",
- "before", "prior to", "origins", "evolution", "development"]
- return any(term in query.lower() for term in historical_terms)
-
- def _adaptive_search(self, query: str) -> Tuple[List[str], str]:
- """
- Perform an adaptive search that adjusts based on topic volume and whether
- the query focuses on historical information.
-
- Args:
- query: The search query (already optimized)
-
- Returns:
- Tuple of (list of PMIDs, search strategy used)
- """
- # Estimate topic volume
- estimated_volume = self._get_result_count(query)
-
- # Determine if the query is focused on historical information
- is_historical_focused = self._is_historical_focused(query)
-
- if is_historical_focused:
- # User wants historical information - no date filtering
- time_filter = None
- strategy = "historical_focus"
- elif estimated_volume > 5000:
- # Very common topic - use tighter recency filter
- time_filter = '"last 1 year"[pdat]'
- strategy = "high_volume"
- elif estimated_volume > 1000:
- # Common topic
- time_filter = '"last 3 years"[pdat]'
- strategy = "common_topic"
- elif estimated_volume > 100:
- # Moderate volume
- time_filter = '"last 5 years"[pdat]'
- strategy = "moderate_volume"
- else:
- # Rare topic - still use recency but with wider range
- time_filter = '"last 10 years"[pdat]'
- strategy = "rare_topic"
-
- # Run search based on strategy
- if time_filter:
- # Try with adaptive time filter
- query_with_time = f"({query}) AND {time_filter}"
- logger.info(f"Using adaptive search strategy: {strategy} with filter: {time_filter}")
- results = self._search_pubmed(query_with_time)
-
- # If too few results, gradually expand time window
- if len(results) < 5 and not '"last 10 years"[pdat]' in time_filter:
- logger.info(f"Insufficient results ({len(results)}), expanding time window")
- expanded_time = self._expand_time_window(time_filter)
- query_with_expanded_time = f"({query}) AND {expanded_time}"
- expanded_results = self._search_pubmed(query_with_expanded_time)
-
- if len(expanded_results) > len(results):
- logger.info(f"Expanded time window yielded {len(expanded_results)} results")
- return expanded_results, f"{strategy}_expanded"
-
- # If still no results, try without time filter
- if not results:
- logger.info("No results with time filter, trying without time restrictions")
- results = self._search_pubmed(query)
- strategy = "no_time_filter"
- else:
- # Historical query - run without time filter
- logger.info(f"Using historical search strategy without date filtering")
- results = self._search_pubmed(query)
-
- return results, strategy
-
- def _search_pubmed(self, query: str) -> List[str]:
- """
- Search PubMed and return a list of article IDs.
-
- Args:
- query: The search query
-
- Returns:
- List of PubMed IDs matching the query
- """
- try:
- # Prepare search parameters
- params = {
- "db": "pubmed",
- "term": query,
- "retmode": "json",
- "retmax": self.max_results,
- "usehistory": "y"
- }
-
- # Add API key if available
- if self.api_key:
- params["api_key"] = self.api_key
-
- # Add date restriction if specified
- if self.days_limit:
- params["reldate"] = self.days_limit
- params["datetype"] = "pdat" # Publication date
-
- # Execute search request
- response = requests.get(self.search_url, params=params)
- response.raise_for_status()
-
- # Parse response
- data = response.json()
- id_list = data["esearchresult"]["idlist"]
-
- logger.info(f"PubMed search for '{query}' found {len(id_list)} results")
- return id_list
-
- except Exception as e:
- logger.error(f"Error searching PubMed: {e}")
- return []
-
- def _get_article_summaries(self, id_list: List[str]) -> List[Dict[str, Any]]:
- """
- Get summaries for a list of PubMed article IDs.
-
- Args:
- id_list: List of PubMed IDs
-
- Returns:
- List of article summary dictionaries
- """
- if not id_list:
- return []
-
- try:
- # Prepare parameters
- params = {
- "db": "pubmed",
- "id": ",".join(id_list),
- "retmode": "json",
- "rettype": "summary"
- }
-
- # Add API key if available
- if self.api_key:
- params["api_key"] = self.api_key
-
- # Execute request
- response = requests.get(self.summary_url, params=params)
- response.raise_for_status()
-
- # Parse response
- data = response.json()
- summaries = []
-
- for pmid in id_list:
- if pmid in data["result"]:
- article = data["result"][pmid]
-
- # Extract authors (if available)
- authors = []
- if "authors" in article:
- authors = [author["name"] for author in article["authors"]]
-
- # Create summary dictionary
- summary = {
- "id": pmid,
- "title": article.get("title", ""),
- "pubdate": article.get("pubdate", ""),
- "source": article.get("source", ""),
- "authors": authors,
- "journal": article.get("fulljournalname", ""),
- "doi": article.get("doi", ""),
- "link": f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/"
- }
-
- summaries.append(summary)
-
- return summaries
-
- except Exception as e:
- logger.error(f"Error getting article summaries: {e}")
- return []
-
- def _get_article_abstracts(self, id_list: List[str]) -> Dict[str, str]:
- """
- Get abstracts for a list of PubMed article IDs.
-
- Args:
- id_list: List of PubMed IDs
-
- Returns:
- Dictionary mapping PubMed IDs to their abstracts
- """
- if not id_list:
- return {}
-
- try:
- # Prepare parameters
- params = {
- "db": "pubmed",
- "id": ",".join(id_list),
- "retmode": "xml",
- "rettype": "abstract"
- }
-
- # Add API key if available
- if self.api_key:
- params["api_key"] = self.api_key
-
- # Execute request
- response = requests.get(self.fetch_url, params=params)
- response.raise_for_status()
-
- # Parse XML response
- root = ET.fromstring(response.text)
-
- # Extract abstracts
- abstracts = {}
-
- for article in root.findall(".//PubmedArticle"):
- pmid_elem = article.find(".//PMID")
- pmid = pmid_elem.text if pmid_elem is not None else None
-
- if pmid is None:
- continue
-
- # Find abstract text
- abstract_text = ""
- abstract_elem = article.find(".//AbstractText")
-
- if abstract_elem is not None:
- abstract_text = abstract_elem.text or ""
-
- # Some abstracts are split into multiple sections
- for section in article.findall(".//AbstractText"):
- # Get section label if it exists
- label = section.get("Label")
- section_text = section.text or ""
-
- if label and section_text:
- if abstract_text:
- abstract_text += f"\n\n{label}: {section_text}"
- else:
- abstract_text = f"{label}: {section_text}"
- elif section_text:
- if abstract_text:
- abstract_text += f"\n\n{section_text}"
- else:
- abstract_text = section_text
-
- # Store in dictionary
- if pmid and abstract_text:
- abstracts[pmid] = abstract_text
-
- return abstracts
-
- except Exception as e:
- logger.error(f"Error getting article abstracts: {e}")
- return {}
-
- def _find_pmc_ids(self, pmid_list: List[str]) -> Dict[str, str]:
- """
- Find PMC IDs for the given PubMed IDs (for full-text access).
-
- Args:
- pmid_list: List of PubMed IDs
-
- Returns:
- Dictionary mapping PubMed IDs to their PMC IDs (if available)
- """
- if not pmid_list or not self.get_full_text:
- return {}
-
- try:
- # Prepare parameters
- params = {
- "dbfrom": "pubmed",
- "db": "pmc",
- "linkname": "pubmed_pmc",
- "id": ",".join(pmid_list),
- "retmode": "json"
- }
-
- # Add API key if available
- if self.api_key:
- params["api_key"] = self.api_key
-
- # Execute request
- response = requests.get(self.link_url, params=params)
- response.raise_for_status()
-
- # Parse response
- data = response.json()
-
- # Map PubMed IDs to PMC IDs
- pmid_to_pmcid = {}
-
- for linkset in data.get("linksets", []):
- pmid = linkset.get("ids", [None])[0]
-
- if not pmid:
- continue
-
- for link in linkset.get("linksetdbs", []):
- if link.get("linkname") == "pubmed_pmc":
- pmcids = link.get("links", [])
- if pmcids:
- pmid_to_pmcid[str(pmid)] = f"PMC{pmcids[0]}"
-
- logger.info(f"Found {len(pmid_to_pmcid)} PMC IDs for full-text access")
- return pmid_to_pmcid
-
- except Exception as e:
- logger.error(f"Error finding PMC IDs: {e}")
- return {}
-
- def _get_pmc_full_text(self, pmcid: str) -> str:
- """
- Get full text for a PMC article.
-
- Args:
- pmcid: PMC ID of the article
-
- Returns:
- Full text content or empty string if not available
- """
- try:
- # Prepare parameters
- params = {
- "db": "pmc",
- "id": pmcid,
- "retmode": "xml",
- "rettype": "full"
- }
-
- # Add API key if available
- if self.api_key:
- params["api_key"] = self.api_key
-
- # Execute request
- response = requests.get(self.fetch_url, params=params)
- response.raise_for_status()
-
- # Parse XML response
- root = ET.fromstring(response.text)
-
- # Extract full text
- full_text = []
-
- # Extract article title
- title_elem = root.find(".//article-title")
- if title_elem is not None and title_elem.text:
- full_text.append(f"# {title_elem.text}")
-
- # Extract abstract
- abstract_paras = root.findall(".//abstract//p")
- if abstract_paras:
- full_text.append("\n## Abstract\n")
- for p in abstract_paras:
- text = ''.join(p.itertext())
- if text:
- full_text.append(text)
-
- # Extract body content
- body = root.find(".//body")
- if body is not None:
- for section in body.findall(".//sec"):
- # Get section title
- title = section.find(".//title")
- if title is not None and title.text:
- full_text.append(f"\n## {title.text}\n")
-
- # Get paragraphs
- for p in section.findall(".//p"):
- text = ''.join(p.itertext())
- if text:
- full_text.append(text)
-
- return "\n\n".join(full_text)
-
- except Exception as e:
- logger.error(f"Error getting PMC full text: {e}")
- return ""
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information for PubMed articles.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- logger.info(f"Getting PubMed previews for query: {query}")
-
- # Optimize the query for PubMed if LLM is available
- optimized_query = self._optimize_query_for_pubmed(query)
-
- # Perform adaptive search
- pmid_list, strategy = self._adaptive_search(optimized_query)
-
- # If no results, try a simplified query
- if not pmid_list:
- logger.warning(f"No PubMed results found using strategy: {strategy}")
- simplified_query = self._simplify_query(optimized_query)
- if simplified_query != optimized_query:
- logger.info(f"Trying with simplified query: {simplified_query}")
- pmid_list, strategy = self._adaptive_search(simplified_query)
- if pmid_list:
- logger.info(f"Simplified query found {len(pmid_list)} results")
-
- if not pmid_list:
- logger.warning(f"No PubMed results found after query simplification")
- return []
-
- # Get article summaries
- summaries = self._get_article_summaries(pmid_list)
-
- # Rate limit compliance (NCBI allows 10 requests per second with an API key, 3 without)
- time.sleep(0.1 if self.api_key else 0.33)
-
- # Format as previews
- previews = []
- for summary in summaries:
- # Authors formatting
- authors_text = ", ".join(summary.get("authors", []))
- if len(authors_text) > 100:
- # Truncate long author lists
- authors_text = authors_text[:97] + "..."
-
- # Create preview with basic information
- preview = {
- "id": summary["id"],
- "title": summary["title"],
- "link": summary["link"],
- "snippet": f"{authors_text}. {summary.get('journal', '')}. {summary.get('pubdate', '')}",
- "authors": summary.get("authors", []),
- "journal": summary.get("journal", ""),
- "pubdate": summary.get("pubdate", ""),
- "doi": summary.get("doi", ""),
- "source": "PubMed",
- "_pmid": summary["id"], # Store PMID for later use
- "_search_strategy": strategy # Store search strategy for analytics
- }
-
- previews.append(preview)
-
- logger.info(f"Found {len(previews)} PubMed previews using strategy: {strategy}")
- return previews
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant PubMed articles.
- Efficiently manages which content to retrieve (abstracts and/or full text).
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should add full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info(f"Getting content for {len(relevant_items)} PubMed articles")
-
- # Collect all PMIDs for relevant items
- pmids = []
- for item in relevant_items:
- if "_pmid" in item:
- pmids.append(item["_pmid"])
-
- # Get abstracts if requested and PMIDs exist
- abstracts = {}
- if self.get_abstracts and pmids:
- abstracts = self._get_article_abstracts(pmids)
-
- # Find PMC IDs for full-text retrieval (if enabled)
- pmid_to_pmcid = {}
- if self.get_full_text and pmids:
- pmid_to_pmcid = self._find_pmc_ids(pmids)
-
- # Add content to results
- results = []
- for item in relevant_items:
- result = item.copy()
- pmid = item.get("_pmid", "")
-
- # Add abstract if available
- if pmid in abstracts:
- result["abstract"] = abstracts[pmid]
-
- # Use abstract as content if no full text
- if pmid not in pmid_to_pmcid:
- result["full_content"] = abstracts[pmid]
- result["content"] = abstracts[pmid]
- result["content_type"] = "abstract"
-
- # Add full text for a limited number of top articles
- if (pmid in pmid_to_pmcid and
- self.get_full_text and
- len([r for r in results if r.get("content_type") == "full_text"]) < self.full_text_limit):
-
- # Get full text content
- pmcid = pmid_to_pmcid[pmid]
- full_text = self._get_pmc_full_text(pmcid)
-
- if full_text:
- result["full_content"] = full_text
- result["content"] = full_text
- result["content_type"] = "full_text"
- result["pmcid"] = pmcid
- elif pmid in abstracts:
- # Fall back to abstract if full text retrieval fails
- result["full_content"] = abstracts[pmid]
- result["content"] = abstracts[pmid]
- result["content_type"] = "abstract"
-
- # Remove temporary fields
- if "_pmid" in result:
- del result["_pmid"]
- if "_search_strategy" in result:
- del result["_search_strategy"]
-
- results.append(result)
-
- return results
-
- def search_by_author(self, author_name: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for articles by a specific author.
-
- Args:
- author_name: Name of the author
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of articles by the author
- """
- original_max_results = self.max_results
-
- try:
- if max_results:
- self.max_results = max_results
-
- query = f"{author_name}[Author]"
- return self.run(query)
-
- finally:
- # Restore original value
- self.max_results = original_max_results
-
- def search_by_journal(self, journal_name: str, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for articles in a specific journal.
-
- Args:
- journal_name: Name of the journal
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of articles from the journal
- """
- original_max_results = self.max_results
-
- try:
- if max_results:
- self.max_results = max_results
-
- query = f"{journal_name}[Journal]"
- return self.run(query)
-
- finally:
- # Restore original value
- self.max_results = original_max_results
-
- def search_recent(self, query: str, days: int = 30, max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Search for recent articles matching the query.
-
- Args:
- query: The search query
- days: Number of days to look back
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of recent articles matching the query
- """
- original_max_results = self.max_results
- original_days_limit = self.days_limit
-
- try:
- if max_results:
- self.max_results = max_results
-
- # Set days limit for this search
- self.days_limit = days
-
- return self.run(query)
-
- finally:
- # Restore original values
- self.max_results = original_max_results
- self.days_limit = original_days_limit
-
- def advanced_search(self, terms: Dict[str, str], max_results: Optional[int] = None) -> List[Dict[str, Any]]:
- """
- Perform an advanced search with field-specific terms.
-
- Args:
- terms: Dictionary mapping fields to search terms
- Valid fields: Author, Journal, Title, MeSH, Affiliation, etc.
- max_results: Maximum number of results (defaults to self.max_results)
-
- Returns:
- List of articles matching the advanced query
- """
- original_max_results = self.max_results
-
- try:
- if max_results:
- self.max_results = max_results
-
- # Build advanced query string
- query_parts = []
- for field, term in terms.items():
- query_parts.append(f"{term}[{field}]")
-
- query = " AND ".join(query_parts)
- return self.run(query)
-
- finally:
- # Restore original value
- self.max_results = original_max_results
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_serpapi.py b/web_search_engines/engines/search_engine_serpapi.py
deleted file mode 100644
index 049517c550..0000000000
--- a/web_search_engines/engines/search_engine_serpapi.py
+++ /dev/null
@@ -1,230 +0,0 @@
-from langchain_community.utilities import SerpAPIWrapper
-from typing import Dict, List, Any, Optional
-import os
-from langchain_core.language_models import BaseLLM
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-
-class SerpAPISearchEngine(BaseSearchEngine):
- """Google search engine implementation using SerpAPI with two-phase approach"""
-
- def __init__(self,
- max_results: int = 10,
- region: str = "us",
- time_period: str = "y",
- safe_search: bool = True,
- search_language: str = "English",
- api_key: Optional[str] = None,
- language_code_mapping: Optional[Dict[str, str]] = None,
- llm: Optional[BaseLLM] = None,
- include_full_content: bool = False,
- max_filtered_results: Optional[int] = None,
- **kwargs):
- """
- Initialize the SerpAPI search engine.
-
- Args:
- max_results: Maximum number of search results
- region: Region code for search results
- time_period: Time period for search results
- safe_search: Whether to enable safe search
- search_language: Language for search results
- api_key: SerpAPI API key (can also be set in SERP_API_KEY env)
- language_code_mapping: Mapping from language names to codes
- llm: Language model for relevance filtering
- include_full_content: Whether to include full webpage content in results
- max_filtered_results: Maximum number of results to keep after filtering
- **kwargs: Additional parameters (ignored but accepted for compatibility)
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.include_full_content = include_full_content
-
- # Set up language code mapping
- if language_code_mapping is None:
- language_code_mapping = {
- "english": "en",
- "spanish": "es",
- "chinese": "zh",
- "hindi": "hi",
- "french": "fr",
- "arabic": "ar",
- "bengali": "bn",
- "portuguese": "pt",
- "russian": "ru",
- }
-
- # Get API key
- serpapi_api_key = api_key or os.getenv("SERP_API_KEY")
- if not serpapi_api_key:
- raise ValueError("SERP_API_KEY not found. Please provide api_key or set the SERP_API_KEY environment variable.")
-
- # Get language code
- language_code = language_code_mapping.get(search_language.lower(), "en")
-
- # Initialize SerpAPI wrapper
- self.engine = SerpAPIWrapper(
- serpapi_api_key=serpapi_api_key,
- params={
- "engine": "google",
- "hl": language_code,
- "gl": region,
- "safe": "active" if safe_search else "off",
- "tbs": f"qdr:{time_period}",
- "num": max_results,
- }
- )
-
- # If full content is requested, initialize FullSearchResults
- if include_full_content:
- # Import FullSearchResults only if needed
- try:
- from web_search_engines.engines.full_search import FullSearchResults
- self.full_search = FullSearchResults(
- llm=llm,
- web_search=self.engine,
- language=search_language,
- max_results=max_results,
- region=region,
- time=time_period,
- safesearch="Moderate" if safe_search else "Off"
- )
- except ImportError:
- print("Warning: FullSearchResults not available. Full content retrieval disabled.")
- self.include_full_content = False
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information from SerpAPI.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- print("Getting search results from SerpAPI")
-
- try:
- # Get search results from SerpAPI
- organic_results = self.engine.results(query).get("organic_results", [])
-
- # Format results as previews
- previews = []
- for result in organic_results:
- preview = {
- "id": result.get("position", len(previews)), # Use position as ID
- "title": result.get("title", ""),
- "link": result.get("link", ""),
- "snippet": result.get("snippet", ""),
- "displayed_link": result.get("displayed_link", ""),
- "position": result.get("position")
- }
-
- # Store full SerpAPI result for later
- preview["_full_result"] = result
-
- previews.append(preview)
-
- # Store the previews for potential full content retrieval
- self._search_results = previews
-
- return previews
-
- except Exception as e:
- print(f"Error getting SerpAPI results: {e}")
- return []
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant search results.
- If include_full_content is True and FullSearchResults is available,
- retrieves full webpage content for the results.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content if requested
- """
- # Check if we should get full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Snippet-only mode, skipping full content retrieval")
-
- # Return the relevant items with their full SerpAPI information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"]
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item
-
- results.append(result)
-
- return results
-
- # If full content retrieval is enabled
- if self.include_full_content and hasattr(self, 'full_search'):
- print("Retrieving full webpage content")
-
- try:
- # Extract only the links from relevant items
- links = [item.get("link") for item in relevant_items if item.get("link")]
-
- # Use FullSearchResults to get full content
- # This is a simplified approach - in a real implementation,
- # you would need to fetch and process the URLs
- results_with_content = self.full_search._get_full_content(relevant_items)
-
- return results_with_content
-
- except Exception as e:
- print(f"Error retrieving full content: {e}")
- # Fall back to returning the items without full content
-
- # Return items with their full SerpAPI information
- results = []
- for item in relevant_items:
- # Use the full result if available, otherwise use the preview
- if "_full_result" in item:
- result = item["_full_result"].copy()
- # Remove temporary field
- if "_full_result" in result:
- del result["_full_result"]
- else:
- result = item.copy()
- if "_full_result" in result:
- del result["_full_result"]
-
- results.append(result)
-
- return results
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Execute a search using SerpAPI with the two-phase approach.
-
- Args:
- query: The search query
-
- Returns:
- List of search results
- """
- print("---Execute a search using SerpAPI (Google)---")
-
- # Use the implementation from the parent class which handles all phases
- results = super().run(query)
-
- # Clean up
- if hasattr(self, '_search_results'):
- del self._search_results
-
- return results
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_wayback.py b/web_search_engines/engines/search_engine_wayback.py
deleted file mode 100644
index 7fafb24030..0000000000
--- a/web_search_engines/engines/search_engine_wayback.py
+++ /dev/null
@@ -1,474 +0,0 @@
-import requests
-import logging
-from typing import Dict, List, Any, Optional, Tuple
-from langchain_core.language_models import BaseLLM
-import re
-import time
-from datetime import datetime
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-import justext
-
-# Setup logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-class WaybackSearchEngine(BaseSearchEngine):
- """
- Internet Archive Wayback Machine search engine implementation
- Provides access to historical versions of web pages
- """
-
- def __init__(self,
- max_results: int = 10,
- max_snapshots_per_url: int = 3,
- llm: Optional[BaseLLM] = None,
- language: str = "English",
- max_filtered_results: Optional[int] = None,
- closest_only: bool = False):
- """
- Initialize the Wayback Machine search engine.
-
- Args:
- max_results: Maximum number of search results
- max_snapshots_per_url: Maximum snapshots to retrieve per URL
- llm: Language model for relevance filtering
- language: Language for content processing
- max_filtered_results: Maximum number of results to keep after filtering
- closest_only: If True, only retrieves the closest snapshot for each URL
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.max_snapshots_per_url = max_snapshots_per_url
- self.language = language
- self.closest_only = closest_only
-
- # API endpoints
- self.available_api = "https://archive.org/wayback/available"
- self.cdx_api = "https://web.archive.org/cdx/search/cdx"
-
- def _extract_urls_from_query(self, query: str) -> List[str]:
- """
- Extract URLs from a query string or interpret as an URL if possible.
- For non-URL queries, use a DuckDuckGo search to find relevant URLs.
-
- Args:
- query: The search query or URL
-
- Returns:
- List of URLs to search in the Wayback Machine
- """
- # Check if the query is already a URL
- url_pattern = re.compile(r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+')
- urls = url_pattern.findall(query)
-
- if urls:
- logger.info(f"Found {len(urls)} URLs in query")
- return urls
-
- # Check if query is a domain without http prefix
- domain_pattern = re.compile(r'^(?:[-\w.]|(?:%[\da-fA-F]{2}))+\.\w+$')
- if domain_pattern.match(query):
- logger.info(f"Query appears to be a domain: {query}")
- return [f"http://{query}"]
-
- # For non-URL queries, use DuckDuckGo to find relevant URLs
- logger.info(f"Query is not a URL, using DuckDuckGo to find relevant URLs")
- try:
- # Import DuckDuckGo search engine
- from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
- ddg = DuckDuckGoSearchAPIWrapper(max_results=5)
- results = ddg.results(query)
-
- # Extract URLs from results
- ddg_urls = [result.get("link") for result in results if result.get("link")]
- if ddg_urls:
- logger.info(f"Found {len(ddg_urls)} URLs from DuckDuckGo search")
- return ddg_urls
- except Exception as e:
- logger.error(f"Error using DuckDuckGo for URL discovery: {e}")
-
- # Fallback: treat the query as a potential domain or path
- if "/" in query and "." in query:
- logger.info(f"Treating query as a partial URL: {query}")
- return [f"http://{query}"]
- elif "." in query:
- logger.info(f"Treating query as a domain: {query}")
- return [f"http://{query}"]
-
- # Return empty list if nothing worked
- logger.warning(f"Could not extract any URLs from query: {query}")
- return []
-
- def _format_timestamp(self, timestamp: str) -> str:
- """Format Wayback Machine timestamp into readable date"""
- if len(timestamp) < 14:
- return timestamp
-
- try:
- year = timestamp[0:4]
- month = timestamp[4:6]
- day = timestamp[6:8]
- hour = timestamp[8:10]
- minute = timestamp[10:12]
- second = timestamp[12:14]
- return f"{year}-{month}-{day} {hour}:{minute}:{second}"
- except:
- return timestamp
-
- def _get_wayback_snapshots(self, url: str) -> List[Dict[str, Any]]:
- """
- Get snapshots from the Wayback Machine for a specific URL.
-
- Args:
- url: URL to get snapshots for
-
- Returns:
- List of snapshot dictionaries
- """
- snapshots = []
-
- try:
- if self.closest_only:
- # Get only the closest snapshot
- response = requests.get(
- self.available_api,
- params={"url": url}
- )
- data = response.json()
-
- if "archived_snapshots" in data and "closest" in data["archived_snapshots"]:
- snapshot = data["archived_snapshots"]["closest"]
- snapshot_url = snapshot["url"]
- timestamp = snapshot["timestamp"]
-
- snapshots.append({
- "timestamp": timestamp,
- "formatted_date": self._format_timestamp(timestamp),
- "url": snapshot_url,
- "original_url": url,
- "available": snapshot.get("available", True),
- "status": snapshot.get("status", "200")
- })
- else:
- # Get multiple snapshots using CDX API
- response = requests.get(
- self.cdx_api,
- params={
- "url": url,
- "output": "json",
- "fl": "timestamp,original,statuscode,mimetype",
- "collapse": "timestamp:4", # Group by year
- "limit": self.max_snapshots_per_url
- }
- )
-
- # Check if response is valid JSON
- data = response.json()
-
- # First item is the header
- if len(data) > 1:
- headers = data[0]
- for item in data[1:]:
- snapshot = dict(zip(headers, item))
- timestamp = snapshot.get("timestamp", "")
-
- wayback_url = f"https://web.archive.org/web/{timestamp}/{url}"
-
- snapshots.append({
- "timestamp": timestamp,
- "formatted_date": self._format_timestamp(timestamp),
- "url": wayback_url,
- "original_url": url,
- "available": True,
- "status": snapshot.get("statuscode", "200")
- })
-
- # Limit to max snapshots per URL
- snapshots = snapshots[:self.max_snapshots_per_url]
-
- except Exception as e:
- logger.error(f"Error getting Wayback snapshots for {url}: {e}")
-
- return snapshots
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information for Wayback Machine snapshots.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- logger.info(f"Getting Wayback Machine previews for query: {query}")
-
- # Extract URLs from query
- urls = self._extract_urls_from_query(query)
-
- if not urls:
- logger.warning(f"No URLs found in query: {query}")
- return []
-
- # Get snapshots for each URL
- all_snapshots = []
- for url in urls:
- snapshots = self._get_wayback_snapshots(url)
- all_snapshots.extend(snapshots)
-
- # Respect rate limits
- if len(urls) > 1:
- time.sleep(0.5)
-
- # Format as previews
- previews = []
- for snapshot in all_snapshots:
- preview = {
- "id": f"{snapshot['timestamp']}_{snapshot['original_url']}",
- "title": f"Archive of {snapshot['original_url']} ({snapshot['formatted_date']})",
- "link": snapshot["url"],
- "snippet": f"Archived version from {snapshot['formatted_date']}",
- "original_url": snapshot["original_url"],
- "timestamp": snapshot["timestamp"],
- "formatted_date": snapshot["formatted_date"]
- }
- previews.append(preview)
-
- logger.info(f"Found {len(previews)} Wayback Machine snapshots")
- return previews
-
- def _remove_boilerplate(self, html: str) -> str:
- """
- Remove boilerplate content from HTML.
-
- Args:
- html: HTML content
-
- Returns:
- Cleaned text content
- """
- if not html or not html.strip():
- return ""
- try:
- 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
- except Exception as e:
- logger.error(f"Error removing boilerplate: {e}")
- return html
-
- def _get_wayback_content(self, url: str) -> Tuple[str, str]:
- """
- Retrieve content from a Wayback Machine URL.
-
- Args:
- url: Wayback Machine URL
-
- Returns:
- Tuple of (raw_html, cleaned_text)
- """
- try:
- headers = {
- "User-Agent": "Mozilla/5.0 (Local Deep Research Bot; research project)"
- }
- response = requests.get(url, headers=headers, timeout=10)
- raw_html = response.text
-
- # Clean the HTML
- cleaned_text = self._remove_boilerplate(raw_html)
-
- return raw_html, cleaned_text
- except Exception as e:
- logger.error(f"Error retrieving content from {url}: {e}")
- return "", f"Error retrieving content: {str(e)}"
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant Wayback Machine snapshots.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should add full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info(f"Getting full content for {len(relevant_items)} Wayback Machine snapshots")
-
- results = []
- for item in relevant_items:
- wayback_url = item.get("link")
- if not wayback_url:
- results.append(item)
- continue
-
- logger.info(f"Retrieving content from {wayback_url}")
-
- try:
- # Retrieve content
- raw_html, full_content = self._get_wayback_content(wayback_url)
-
- # Add full content to the result
- result = item.copy()
- result["raw_html"] = raw_html
- result["full_content"] = full_content
-
- results.append(result)
-
- # Brief pause for rate limiting
- time.sleep(0.5)
- except Exception as e:
- logger.error(f"Error processing {wayback_url}: {e}")
- results.append(item)
-
- return results
-
- def search_by_url(self, url: str, max_snapshots: int = None) -> List[Dict[str, Any]]:
- """
- Search for archived versions of a specific URL.
-
- Args:
- url: The URL to search for archives
- max_snapshots: Maximum number of snapshots to return
-
- Returns:
- List of snapshot dictionaries
- """
- max_snapshots = max_snapshots or self.max_snapshots_per_url
-
- snapshots = self._get_wayback_snapshots(url)
- previews = []
-
- for snapshot in snapshots[:max_snapshots]:
- preview = {
- "id": f"{snapshot['timestamp']}_{snapshot['original_url']}",
- "title": f"Archive of {snapshot['original_url']} ({snapshot['formatted_date']})",
- "link": snapshot["url"],
- "snippet": f"Archived version from {snapshot['formatted_date']}",
- "original_url": snapshot["original_url"],
- "timestamp": snapshot["timestamp"],
- "formatted_date": snapshot["formatted_date"]
- }
- previews.append(preview)
-
- # Get full content if not in snippets-only mode
- if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:
- return self._get_full_content(previews)
-
- return previews
-
- def search_by_date_range(self, url: str, start_date: str, end_date: str) -> List[Dict[str, Any]]:
- """
- Search for archived versions of a URL within a date range.
-
- Args:
- url: The URL to search for archives
- start_date: Start date in format YYYYMMDD
- end_date: End date in format YYYYMMDD
-
- Returns:
- List of snapshot dictionaries
- """
- try:
- # Use CDX API with date range
- response = requests.get(
- self.cdx_api,
- params={
- "url": url,
- "output": "json",
- "fl": "timestamp,original,statuscode,mimetype",
- "from": start_date,
- "to": end_date,
- "limit": self.max_snapshots_per_url
- }
- )
-
- # Process response
- data = response.json()
-
- # First item is the header
- if len(data) <= 1:
- return []
-
- headers = data[0]
- snapshots = []
-
- for item in data[1:]:
- snapshot = dict(zip(headers, item))
- timestamp = snapshot.get("timestamp", "")
-
- wayback_url = f"https://web.archive.org/web/{timestamp}/{url}"
-
- snapshots.append({
- "id": f"{timestamp}_{url}",
- "title": f"Archive of {url} ({self._format_timestamp(timestamp)})",
- "link": wayback_url,
- "snippet": f"Archived version from {self._format_timestamp(timestamp)}",
- "original_url": url,
- "timestamp": timestamp,
- "formatted_date": self._format_timestamp(timestamp)
- })
-
- # Get full content if not in snippets-only mode
- if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:
- return self._get_full_content(snapshots)
-
- return snapshots
-
- except Exception as e:
- logger.error(f"Error searching date range for {url}: {e}")
- return []
-
- def get_latest_snapshot(self, url: str) -> Optional[Dict[str, Any]]:
- """
- Get the most recent snapshot of a URL.
-
- Args:
- url: The URL to get the latest snapshot for
-
- Returns:
- Dictionary with snapshot information or None if not found
- """
- try:
- response = requests.get(
- self.available_api,
- params={"url": url}
- )
- data = response.json()
-
- if "archived_snapshots" in data and "closest" in data["archived_snapshots"]:
- snapshot = data["archived_snapshots"]["closest"]
- timestamp = snapshot["timestamp"]
- wayback_url = snapshot["url"]
-
- result = {
- "id": f"{timestamp}_{url}",
- "title": f"Latest archive of {url} ({self._format_timestamp(timestamp)})",
- "link": wayback_url,
- "snippet": f"Archived version from {self._format_timestamp(timestamp)}",
- "original_url": url,
- "timestamp": timestamp,
- "formatted_date": self._format_timestamp(timestamp)
- }
-
- # Get full content if not in snippets-only mode
- if not hasattr(config, 'SEARCH_SNIPPETS_ONLY') or not config.SEARCH_SNIPPETS_ONLY:
- raw_html, full_content = self._get_wayback_content(wayback_url)
- result["raw_html"] = raw_html
- result["full_content"] = full_content
-
- return result
-
- return None
-
- except Exception as e:
- logger.error(f"Error getting latest snapshot for {url}: {e}")
- return None
\ No newline at end of file
diff --git a/web_search_engines/engines/search_engine_wikipedia.py b/web_search_engines/engines/search_engine_wikipedia.py
deleted file mode 100644
index 780db3e715..0000000000
--- a/web_search_engines/engines/search_engine_wikipedia.py
+++ /dev/null
@@ -1,242 +0,0 @@
-import wikipedia
-from typing import Dict, List, Any, Optional
-from langchain_core.language_models import BaseLLM
-import logging
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-import config
-
-# Setup logging
-logger = logging.getLogger(__name__)
-
-
-class WikipediaSearchEngine(BaseSearchEngine):
- """Wikipedia search engine implementation with two-phase approach"""
-
- def __init__(self,
- max_results: int = 10,
- language: str = "en",
- include_content: bool = True,
- sentences: int = 5,
- llm: Optional[BaseLLM] = None,
- max_filtered_results: Optional[int] = None,
- **kwargs):
- """
- Initialize the Wikipedia search engine.
-
- Args:
- max_results: Maximum number of search results
- language: Language code for Wikipedia (e.g., 'en', 'fr', 'es')
- include_content: Whether to include full page content in results
- sentences: Number of sentences to include in summary
- llm: Language model for relevance filtering
- max_filtered_results: Maximum number of results to keep after filtering
- **kwargs: Additional parameters (ignored but accepted for compatibility)
- """
- # Initialize the BaseSearchEngine with the LLM and max_filtered_results
- super().__init__(llm=llm, max_filtered_results=max_filtered_results)
-
- self.max_results = max_results
- self.include_content = include_content
- self.sentences = sentences
-
- # Set the Wikipedia language
- wikipedia.set_lang(language)
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information (titles and summaries) for Wikipedia pages.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- logger.info(f"Getting Wikipedia page previews for query: {query}")
-
- try:
- # Get search results (just titles)
- search_results = wikipedia.search(query, results=self.max_results)
-
- logger.info(f"Found {len(search_results)} Wikipedia results: {search_results}")
-
- if not search_results:
- logger.info(f"No Wikipedia results found for query: {query}")
- return []
-
- # Create a cache for full pages (will be populated on-demand)
- self._page_cache = {}
-
- # Generate previews with summaries
- previews = []
- for title in search_results:
- try:
- # Get just the summary, with auto_suggest=False to be more precise
- summary = None
- try:
- summary = wikipedia.summary(title, sentences=self.sentences, auto_suggest=False)
- except wikipedia.exceptions.DisambiguationError as e:
- # If disambiguation error, try the first option
- if e.options and len(e.options) > 0:
- logger.info(f"Disambiguation for '{title}', trying first option: {e.options[0]}")
- try:
- summary = wikipedia.summary(e.options[0], sentences=self.sentences, auto_suggest=False)
- title = e.options[0] # Use the new title
- except Exception as inner_e:
- logger.error(f"Error with disambiguation option: {inner_e}")
- continue
- else:
- logger.warning(f"Disambiguation with no options for '{title}'")
- continue
-
- if summary:
- preview = {
- "id": title, # Use title as ID
- "title": title,
- "snippet": summary,
- "link": f"https://en.wikipedia.org/wiki/{title.replace(' ', '_')}"
- }
-
- previews.append(preview)
-
- except (wikipedia.exceptions.PageError,
- wikipedia.exceptions.WikipediaException) as e:
- # Skip pages with errors
- logger.warning(f"Error getting summary for '{title}': {e}")
- continue
- except Exception as e:
- logger.error(f"Unexpected error for '{title}': {e}")
- continue
-
- logger.info(f"Successfully created {len(previews)} previews from Wikipedia")
- return previews
-
- except Exception as e:
- logger.error(f"Error getting Wikipedia previews: {e}")
- return []
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant Wikipedia pages.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- # Check if we should add full content
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- logger.info("Snippet-only mode, skipping full content retrieval")
- return relevant_items
-
- logger.info(f"Getting full content for {len(relevant_items)} relevant Wikipedia pages")
-
- results = []
- for item in relevant_items:
- title = item.get("id") # Title stored as ID
-
- if not title:
- results.append(item)
- continue
-
- try:
- # Get the full page
- page = wikipedia.page(title, auto_suggest=False)
-
- # Create a full result with all information
- result = {
- "title": page.title,
- "link": page.url,
- "snippet": item.get("snippet", "") # Keep existing snippet
- }
-
- # Add additional information
- result["content"] = page.content
- result["full_content"] = page.content
- result["categories"] = page.categories
- result["references"] = page.references
- result["links"] = page.links
- result["images"] = page.images
- result["sections"] = page.sections
-
- results.append(result)
-
- except (wikipedia.exceptions.DisambiguationError,
- wikipedia.exceptions.PageError,
- wikipedia.exceptions.WikipediaException) as e:
- # If error, use the preview
- logger.warning(f"Error getting full content for '{title}': {e}")
- results.append(item)
- except Exception as e:
- logger.error(f"Unexpected error getting full content for '{title}': {e}")
- results.append(item)
-
- return results
-
- def get_summary(self, title: str, sentences: Optional[int] = None) -> str:
- """
- Get a summary of a specific Wikipedia page.
-
- Args:
- title: Title of the Wikipedia page
- sentences: Number of sentences to include (defaults to self.sentences)
-
- Returns:
- Summary of the page
- """
- sentences = sentences or self.sentences
- try:
- return wikipedia.summary(title, sentences=sentences, auto_suggest=False)
- except wikipedia.exceptions.DisambiguationError as e:
- if e.options and len(e.options) > 0:
- return wikipedia.summary(e.options[0], sentences=sentences, auto_suggest=False)
- raise
-
- def get_page(self, title: str) -> Dict[str, Any]:
- """
- Get detailed information about a specific Wikipedia page.
-
- Args:
- title: Title of the Wikipedia page
-
- Returns:
- Dictionary with page information
- """
- # Check if we should include full content
- include_content = not (hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY)
-
- try:
- page = wikipedia.page(title, auto_suggest=False)
-
- result = {
- "title": page.title,
- "link": page.url,
- "snippet": self.get_summary(title, self.sentences)
- }
-
- # Add additional information if requested
- if include_content:
- result["content"] = page.content
- result["full_content"] = page.content
- result["categories"] = page.categories
- result["references"] = page.references
- result["links"] = page.links
- result["images"] = page.images
- result["sections"] = page.sections
-
- return result
- except wikipedia.exceptions.DisambiguationError as e:
- if e.options and len(e.options) > 0:
- return self.get_page(e.options[0])
- raise
-
- def set_language(self, language: str) -> None:
- """
- Change the Wikipedia language.
-
- Args:
- language: Language code (e.g., 'en', 'fr', 'es')
- """
- wikipedia.set_lang(language)
\ No newline at end of file
diff --git a/web_search_engines/full_search.py b/web_search_engines/full_search.py
deleted file mode 100644
index 0e397604f4..0000000000
--- a/web_search_engines/full_search.py
+++ /dev/null
@@ -1,254 +0,0 @@
-import justext
-from langchain_community.document_loaders import AsyncChromiumLoader
-from langchain_community.document_transformers import BeautifulSoupTransformer
-from langchain_core.language_models import BaseLLM
-from typing import List, Dict, Any, Optional, Union
-import json
-import os
-from utilties.search_utilities import remove_think_tags
-from datetime import datetime
-import config
-
-class FullSearchResults:
- """
- Enhanced web content retrieval class that works with the BaseSearchEngine architecture.
- Can be used as a wrapper around web-based search engines like DuckDuckGo and SerpAPI.
- """
-
- def __init__(
- self,
- llm: BaseLLM,
- web_search,
- output_format: str = "list",
- language: str = "English",
- max_results: int = 10,
- region: str = "wt-wt",
- time: str = "y",
- safesearch: str = "Moderate"
- ):
- """
- Initialize the full search results processor.
-
- Args:
- llm: Language model instance for relevance filtering
- web_search: Web search engine instance that provides initial results
- output_format: Format of output ('list' or other formats)
- language: Language for content processing
- max_results: Maximum number of search results
- region: Search region
- time: Time period for search results
- safesearch: Safe search setting
- """
- self.llm = llm
- self.output_format = output_format
- self.language = language
- self.max_results = max_results
- self.region = region
- self.time = time
- self.safesearch = safesearch
- self.web_search = web_search
- os.environ["USER_AGENT"] = "Local Deep Research/1.0"
-
- self.bs_transformer = BeautifulSoupTransformer()
- self.tags_to_extract = ["p", "div", "span"]
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Legacy method that performs a full search in one step.
- Respects config parameters:
- - SEARCH_SNIPPETS_ONLY: If True, only returns snippets without full content
- - SKIP_RELEVANCE_FILTER: If True, returns all results without filtering
-
- Args:
- query: The search query
-
- Returns:
- List of search results with full content (unless SEARCH_SNIPPETS_ONLY is True)
- """
- # Phase 1: Get search results from the web search engine
- previews = self._get_previews(query)
- if not previews:
- return []
-
- # Phase 2: Filter URLs using LLM (unless SKIP_RELEVANCE_FILTER is True)
- if hasattr(config, 'SKIP_RELEVANCE_FILTER') and config.SKIP_RELEVANCE_FILTER:
- relevant_items = previews
- print("Skipping relevance filtering as per config")
- else:
- relevant_items = self._filter_relevant_items(previews, query)
- if not relevant_items:
- return []
-
- # Phase 3: Get full content for relevant items (unless SEARCH_SNIPPETS_ONLY is True)
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Returning snippet-only results as per config")
- return relevant_items
- else:
- results = self._get_full_content(relevant_items)
- return results
-
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information from the web search engine.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries
- """
- try:
- # Get search results from the web search engine
- search_results = self.web_search.invoke(query)
-
- if not isinstance(search_results, list):
- print("Error: Expected search results in list format")
- return []
-
- # Return the results as previews
- return search_results
-
- except Exception as e:
- print(f"Error getting previews: {e}")
- return []
-
- def _filter_relevant_items(self, previews: List[Dict[str, Any]], query: str) -> List[Dict[str, Any]]:
- """
- Filter previews for relevance using LLM.
-
- Args:
- previews: List of preview dictionaries
- query: The original search query
-
- Returns:
- List of relevant preview dictionaries
- """
- # Skip filtering if disabled in config or no previews
- if not config.QUALITY_CHECK_DDG_URLS or not previews:
- return previews
-
- # Format for LLM evaluation
- now = datetime.now()
- current_time = now.strftime("%Y-%m-%d")
- prompt = f"""ONLY Return a JSON array. The response contains no letters. Evaluate these URLs for:
- 1. Timeliness (today: {current_time})
- 2. Factual accuracy (cross-reference major claims)
- 3. Source reliability (prefer official company websites, established news outlets)
- 4. Direct relevance to query: {query}
-
- URLs to evaluate:
- {json.dumps(previews, indent=2)}
-
- Return a JSON array of indices (0-based) for sources that meet ALL criteria.
- 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)
-
- # Extract JSON array from response
- response_text = remove_think_tags(response.content)
- # Clean up response to handle potential formatting issues
- response_text = response_text.strip()
-
- # Find the first occurrence of '[' and the last occurrence of ']'
- start_idx = response_text.find('[')
- end_idx = response_text.rfind(']')
-
- if start_idx >= 0 and end_idx > start_idx:
- array_text = response_text[start_idx:end_idx+1]
- good_indices = json.loads(array_text)
-
- # Return only the results with good indices
- return [r for i, r in enumerate(previews) if i in good_indices]
- else:
- print("Could not find JSON array in response, returning all previews")
- return previews
-
- except Exception as e:
- print(f"URL filtering error: {e}")
- # Fall back to returning all previews on error
- return previews
-
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant items by retrieving and processing web pages.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- nr_full_text = 0
-
- # Extract URLs from relevant items
- urls = [item.get("link") for item in relevant_items if item.get("link")]
-
- if not urls:
- print("\n === NO VALID LINKS ===\n")
- return relevant_items
-
- try:
- # Download the full HTML pages for filtered URLs
- loader = AsyncChromiumLoader(urls)
- html_docs = loader.load()
-
- # Process the HTML using BeautifulSoupTransformer
- full_docs = self.bs_transformer.transform_documents(
- html_docs, tags_to_extract=self.tags_to_extract
- )
-
- # Remove boilerplate from each document
- url_to_content = {}
- for doc in full_docs:
- 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 result
- results = []
- for item in relevant_items:
- new_item = item.copy()
- link = item.get("link")
- new_item["full_content"] = url_to_content.get(link, None)
- results.append(new_item)
-
- print(f"FULL SEARCH WITH FILTERED URLS - Full text retrieved: {nr_full_text}")
- return results
-
- except Exception as e:
- print(f"Error retrieving full content: {e}")
- # Return original items if full content retrieval fails
- return relevant_items
-
- def _remove_boilerplate(self, html: str) -> str:
- """
- Remove boilerplate content from HTML.
-
- Args:
- html: HTML content
-
- Returns:
- Cleaned text content
- """
- if not html or not html.strip():
- return ""
- try:
- 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
- except Exception as e:
- print(f"Error removing boilerplate: {e}")
- return html
-
- def invoke(self, query: str) -> List[Dict[str, Any]]:
- """Compatibility method for LangChain tools"""
- return self.run(query)
-
- def __call__(self, query: str) -> List[Dict[str, Any]]:
- """Make the class callable like a function"""
- return self.invoke(query)
\ No newline at end of file
diff --git a/web_search_engines/search_engine_base.py b/web_search_engines/search_engine_base.py
deleted file mode 100644
index a6cb61867c..0000000000
--- a/web_search_engines/search_engine_base.py
+++ /dev/null
@@ -1,193 +0,0 @@
-from abc import ABC, abstractmethod
-from typing import Dict, List, Any, Optional
-from langchain_core.language_models import BaseLLM
-from datetime import datetime
-import json
-from utilties.search_utilities import remove_think_tags
-
-class BaseSearchEngine(ABC):
- """
- Abstract base class for search engines with two-phase retrieval capability.
- Handles common parameters and implements the two-phase search approach.
- """
-
- def __init__(self,
- llm: Optional[BaseLLM] = None,
- max_filtered_results: Optional[int] = None,
- **kwargs):
- """
- Initialize the search engine with common parameters.
-
- Args:
- llm: Optional language model for relevance filtering
- max_filtered_results: Maximum number of results to keep after filtering
- **kwargs: Additional engine-specific parameters
- """
- self.llm = llm # LLM for relevance filtering
- self.max_filtered_results = max_filtered_results # Limit filtered results
-
- def run(self, query: str) -> List[Dict[str, Any]]:
- """
- Run the search engine with a given query, retrieving and filtering results.
- This implements a two-phase retrieval approach:
- 1. Get preview information for many results
- 2. Filter the previews for relevance
- 3. Get full content for only the relevant results
-
- Args:
- query: The search query
-
- Returns:
- List of search results with full content (if available)
- """
- # Ensure we're measuring time correctly for citation tracking
- start_time = datetime.now()
-
- # Step 1: Get preview information for items
- previews = self._get_previews(query)
- if not previews:
- print(f"Search engine {self.__class__.__name__} returned no preview results for query: {query}")
- return []
-
- # Step 2: Filter previews for relevance with LLM
- filtered_items = self._filter_for_relevance(previews, query)
- if not filtered_items:
- print(f"All preview results were filtered out as irrelevant for query: {query}")
- # Fall back to preview items if everything was filtered
- # Access config inside the method to avoid circular import
- import config
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- return previews[:self.max_filtered_results or 5] # Return unfiltered but limited results
- else:
- filtered_items = previews[:self.max_filtered_results or 5]
-
- # Step 3: Get full content for filtered items
- # Import config inside the method to avoid circular import
- import config
- if hasattr(config, 'SEARCH_SNIPPETS_ONLY') and config.SEARCH_SNIPPETS_ONLY:
- print("Returning snippet-only results as per config")
- results = filtered_items
- else:
- results = self._get_full_content(filtered_items)
-
- return results
-
- def invoke(self, query: str) -> List[Dict[str, Any]]:
- """Compatibility method for LangChain tools"""
- return self.run(query)
-
- def _filter_for_relevance(self, previews: List[Dict[str, Any]], query: str) -> List[Dict[str, Any]]:
- """
- Filter search results for relevance to the query using an LLM.
-
- Checks config.SKIP_RELEVANCE_FILTER to determine whether to perform filtering.
-
- Args:
- previews: List of search result dictionaries with preview information
- query: The original search query
-
- Returns:
- Filtered list of the most relevant search results
- """
- # Import config inside the method to avoid circular import
- import config
-
- # Skip filtering if configured to do so or if no LLM is available
- if hasattr(config, 'SKIP_RELEVANCE_FILTER') and config.SKIP_RELEVANCE_FILTER:
- # Return all previews up to max_filtered_results if no filtering is performed
- limit = self.max_filtered_results or 5
- return previews[:limit]
-
- # Default implementation uses LLM if available
- if not self.llm or not previews:
- # If no LLM available, return all previews as relevant
- if self.max_filtered_results and len(previews) > self.max_filtered_results:
- return previews[:self.max_filtered_results]
- return previews
-
- now = datetime.now()
- current_time = now.strftime("%Y-%m-%d")
- prompt = f"""Analyze these search results and provide a ranked list of the most relevant ones.
-
-IMPORTANT: Evaluate and rank based on these criteria (in order of importance):
-1. Timeliness - current/recent information as of {current_time}
-2. Direct relevance to query: "{query}"
-3. Source reliability (prefer official sources, established websites)
-4. Factual accuracy (cross-reference major claims)
-
-Search results to evaluate:
-{json.dumps(previews, indent=2)}
-
-Return ONLY a JSON array of indices (0-based) ranked from most to least relevant.
-Include ONLY indices that meet ALL criteria, with the most relevant first.
-Example response: [4, 0, 2]
-
-Respond with ONLY the JSON array, no other text."""
-
- try:
- # Get LLM's evaluation
- response = self.llm.invoke(prompt)
-
- # Extract JSON array from response
- response_text = remove_think_tags(response.content)
- # Clean up response to handle potential formatting issues
- response_text = response_text.strip()
-
- # Find the first occurrence of '[' and the last occurrence of ']'
- start_idx = response_text.find('[')
- end_idx = response_text.rfind(']')
-
- if start_idx >= 0 and end_idx > start_idx:
- array_text = response_text[start_idx:end_idx+1]
- ranked_indices = json.loads(array_text)
-
- # Return the results in ranked order
- ranked_results = []
- for idx in ranked_indices:
- if idx < len(previews):
- ranked_results.append(previews[idx])
-
- # Limit to max_filtered_results if specified
- if self.max_filtered_results and len(ranked_results) > self.max_filtered_results:
- print(f"Limiting filtered results to top {self.max_filtered_results}")
- return ranked_results[:self.max_filtered_results]
-
- return ranked_results
- else:
- print("Could not find JSON array in response, returning all previews")
- if self.max_filtered_results and len(previews) > self.max_filtered_results:
- return previews[:self.max_filtered_results]
- return previews
-
- except Exception as e:
- print(f"Relevance filtering error: {e}")
- # Fall back to returning all previews (or top N) on error
- if self.max_filtered_results and len(previews) > self.max_filtered_results:
- return previews[:self.max_filtered_results]
- return previews
-
- @abstractmethod
- def _get_previews(self, query: str) -> List[Dict[str, Any]]:
- """
- Get preview information (titles, summaries) for initial search results.
-
- Args:
- query: The search query
-
- Returns:
- List of preview dictionaries with at least 'id', 'title', and 'snippet' keys
- """
- pass
-
- @abstractmethod
- def _get_full_content(self, relevant_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
- """
- Get full content for the relevant items.
-
- Args:
- relevant_items: List of relevant preview dictionaries
-
- Returns:
- List of result dictionaries with full content
- """
- pass
\ No newline at end of file
diff --git a/web_search_engines/search_engine_factory.py b/web_search_engines/search_engine_factory.py
deleted file mode 100644
index 07cf2a7a1f..0000000000
--- a/web_search_engines/search_engine_factory.py
+++ /dev/null
@@ -1,226 +0,0 @@
-import os
-import importlib
-import inspect
-import logging
-from typing import Dict, List, Any, Optional
-
-from web_search_engines.search_engine_base import BaseSearchEngine
-from web_search_engines.search_engines_config import SEARCH_ENGINES, DEFAULT_SEARCH_ENGINE
-
-# Setup logging
-logging.basicConfig(level=logging.INFO)
-logger = logging.getLogger(__name__)
-
-
-def create_search_engine(engine_name: str, llm=None, **kwargs) -> Optional[BaseSearchEngine]:
- """
- Create a search engine instance based on the engine name.
-
- Args:
- engine_name: Name of the search engine to create
- llm: Language model instance (required for some engines like meta)
- **kwargs: Additional parameters to override defaults
-
- Returns:
- Initialized search engine instance or None if creation failed
- """
- # If engine name not found, use default
- if engine_name not in SEARCH_ENGINES:
- logger.warning(f"Search engine '{engine_name}' not found, using default: {DEFAULT_SEARCH_ENGINE}")
- engine_name = DEFAULT_SEARCH_ENGINE
-
- # Get engine configuration
- engine_config = SEARCH_ENGINES[engine_name]
-
- # Check for API key requirements
- if engine_config.get("requires_api_key", False):
- api_key_env = engine_config.get("api_key_env")
- api_key = os.getenv(api_key_env) if api_key_env else None
-
- if not api_key:
- logger.warning(f"Required API key for {engine_name} not found in environment variable: {api_key_env}")
- return None
-
- # Check for LLM requirements
- if engine_config.get("requires_llm", False) and not llm:
- logger.error(f"Engine {engine_name} requires an LLM instance but none was provided")
- return None
-
- try:
- # Load the engine class
- module_path = engine_config["module_path"]
- class_name = engine_config["class_name"]
-
- module = importlib.import_module(module_path)
- engine_class = getattr(module, class_name)
-
- # Get the engine class's __init__ parameters to filter out unsupported ones
- engine_init_signature = inspect.signature(engine_class.__init__)
- engine_init_params = list(engine_init_signature.parameters.keys())
-
- # Combine default parameters with provided ones
- all_params = {**engine_config.get("default_params", {}), **kwargs}
-
- # Filter out parameters that aren't accepted by the engine class
- # Note: 'self' is always the first parameter of instance methods, so we skip it
- filtered_params = {k: v for k, v in all_params.items() if k in engine_init_params[1:]}
-
- # Add LLM if required
- if engine_config.get("requires_llm", False):
- filtered_params["llm"] = llm
-
- # Add API key if required and not already in filtered_params
- if engine_config.get("requires_api_key", False) and "api_key" not in filtered_params:
- api_key_env = engine_config.get("api_key_env")
- if api_key_env:
- api_key = os.getenv(api_key_env)
- if api_key:
- filtered_params["api_key"] = api_key
-
- logger.debug(f"Creating {engine_name} with filtered parameters: {filtered_params.keys()}")
-
- # Create the engine instance with filtered parameters
- engine = engine_class(**filtered_params)
-
- # Check if we need to wrap with full search capabilities
- if kwargs.get("use_full_search", False) and engine_config.get("supports_full_search", False):
- return _create_full_search_wrapper(engine_name, engine, llm, kwargs)
-
- return engine
-
- except Exception as e:
- logger.error(f"Failed to create search engine '{engine_name}': {str(e)}")
- return None
-
-
-def _create_full_search_wrapper(engine_name: str, base_engine: BaseSearchEngine, llm, params: Dict[str, Any]) -> Optional[BaseSearchEngine]:
- """Create a full search wrapper for the base engine if supported"""
- try:
- engine_config = SEARCH_ENGINES[engine_name]
-
- # Get full search class details
- module_path = engine_config.get("full_search_module")
- class_name = engine_config.get("full_search_class")
-
- if not module_path or not class_name:
- logger.warning(f"Full search configuration missing for {engine_name}")
- return base_engine
-
- # Import the full search class
- module = importlib.import_module(module_path)
- full_search_class = getattr(module, class_name)
-
- # Get the wrapper's __init__ parameters to filter out unsupported ones
- wrapper_init_signature = inspect.signature(full_search_class.__init__)
- wrapper_init_params = list(wrapper_init_signature.parameters.keys())[1:] # Skip 'self'
-
- # Extract relevant parameters for the full search wrapper
- wrapper_params = {k: v for k, v in params.items() if k in wrapper_init_params}
-
- # Special case for SerpAPI which needs the API key directly
- if engine_name == "serpapi" and "serpapi_api_key" in wrapper_init_params:
- serpapi_api_key = os.getenv("SERP_API_KEY")
- if serpapi_api_key:
- wrapper_params["serpapi_api_key"] = serpapi_api_key
-
- # Map some parameter names to what the wrapper expects
- if "language" in params and "search_language" not in params and "language" in wrapper_init_params:
- wrapper_params["language"] = params["language"]
-
- if "safesearch" not in wrapper_params and "safe_search" in params and "safesearch" in wrapper_init_params:
- wrapper_params["safesearch"] = "active" if params["safe_search"] else "off"
-
- # Special case for Brave which needs the API key directly
- if engine_name == "brave" and "api_key" in wrapper_init_params:
- brave_api_key = os.getenv("BRAVE_API_KEY")
- if brave_api_key:
- wrapper_params["api_key"] = brave_api_key
-
- # Map some parameter names to what the wrapper expects
- if "language" in params and "search_language" not in params and "language" in wrapper_init_params:
- wrapper_params["language"] = params["language"]
-
- if "safesearch" not in wrapper_params and "safe_search" in params and "safesearch" in wrapper_init_params:
- wrapper_params["safesearch"] = "moderate" if params["safe_search"] else "off"
-
- # Always include llm if it's a parameter
- if "llm" in wrapper_init_params:
- wrapper_params["llm"] = llm
-
- # If the wrapper needs the base engine and has a parameter for it
- if "web_search" in wrapper_init_params:
- wrapper_params["web_search"] = base_engine
-
- logger.debug(f"Creating full search wrapper for {engine_name} with filtered parameters: {wrapper_params.keys()}")
-
- # Create the full search wrapper with filtered parameters
- full_search = full_search_class(**wrapper_params)
-
- return full_search
-
- except Exception as e:
- logger.error(f"Failed to create full search wrapper for {engine_name}: {str(e)}")
- return base_engine
-
-
-
-def get_available_engines(include_api_key_services: bool = True):
- """Get a list of available engine names"""
- if include_api_key_services:
- return list(SEARCH_ENGINES.keys())
- else:
- return [name for name, config in SEARCH_ENGINES.items()
- if not config.get("requires_api_key", False)]
-
-
-def get_search(search_tool: str, llm_instance,
- max_results: int = 10,
- region: str = "us",
- time_period: str = "y",
- safe_search: bool = True,
- search_snippets_only: bool = False,
- search_language: str = "English",
- max_filtered_results: Optional[int] = None):
- """
- Get search tool instance based on the provided parameters.
-
- Args:
- search_tool: Name of the search engine to use
- llm_instance: Language model instance
- max_results: Maximum number of search results
- region: Search region/locale
- time_period: Time period for search results
- safe_search: Whether to enable safe search
- search_snippets_only: Whether to return just snippets (vs. full content)
- search_language: Language for search results
- max_filtered_results: Maximum number of results to keep after filtering
-
- Returns:
- Initialized search engine instance
- """
- # Common parameters
- params = {
- "max_results": max_results,
- "llm": llm_instance, # Only used by engines that need it
- }
-
- # Add max_filtered_results if provided
- if max_filtered_results is not None:
- params["max_filtered_results"] = max_filtered_results
-
- # Add engine-specific parameters
- if search_tool in ["duckduckgo", "serpapi", "google_pse", "brave"]:
- params.update({
- "region": region,
- "safe_search": safe_search,
- "use_full_search": not search_snippets_only
- })
-
- if search_tool in ["serpapi", "brave", "google_pse"]:
- params["search_language"] = search_language
-
- if search_tool == "serpapi":
- params["time_period"] = time_period
-
- # Create and return the search engine
- return create_search_engine(search_tool, **params)
diff --git a/web_search_engines/search_engines_config.py b/web_search_engines/search_engines_config.py
deleted file mode 100644
index ac6a176165..0000000000
--- a/web_search_engines/search_engines_config.py
+++ /dev/null
@@ -1,256 +0,0 @@
-"""
-Configuration file for search engines.
-Add or modify search engines here without changing code elsewhere.
-"""
-
-# Registry of all available search engines
-SEARCH_ENGINES = {
- # Wikipedia search engine
- "wikipedia": {
- "module_path": "web_search_engines.engines.search_engine_wikipedia",
- "class_name": "WikipediaSearchEngine",
- "requires_api_key": False,
- "reliability": 0.95,
- "strengths": ["factual information", "general knowledge", "definitions",
- "historical facts", "biographies", "overview information"],
- "weaknesses": ["recent events", "specialized academic topics", "product comparisons"],
- "default_params": {
- "include_content": True
- }
- },
-
- # arXiv search engine
- "arxiv": {
- "module_path": "web_search_engines.engines.search_engine_arxiv",
- "class_name": "ArXivSearchEngine",
- "requires_api_key": False,
- "reliability": 0.9,
- "strengths": ["scientific papers", "academic research", "physics", "computer science",
- "mathematics", "statistics", "machine learning", "preprints"],
- "weaknesses": ["non-academic topics", "consumer products", "news", "general information"],
- "default_params": {
- "sort_by": "relevance",
- "sort_order": "descending"
- }
- },
-
- # medRxiv search engine
- #"medrxiv": {
- # "module_path": "web_search_engines.engines.search_engine_medrxiv",
- # "class_name": "MedRxivSearchEngine",
- # "requires_api_key": False,
- # "reliability": 0.85,
- # "strengths": ["medical preprints", "health research", "covid-19 research",
- # "clinical studies", "medical sciences", "preliminary results"],
- # "weaknesses": ["not peer-reviewed", "preliminary findings", "limited to medical research"],
- # "default_params": {
- # "sort_by": "relevance_score",
- # "sort_order": "desc",
- # "include_full_text": False,
- # "optimize_queries": True # Use LLM to optimize natural language queries
- # },
- # "requires_llm": True # Needs LLM for query optimization
- #},
- # PubMed search engine
- "pubmed": {
- "module_path": "web_search_engines.engines.search_engine_pubmed",
- "class_name": "PubMedSearchEngine",
- "requires_api_key": False, # Works without API key but with rate limits
- "api_key_env": "NCBI_API_KEY", # Optional for higher rate limits
- "reliability": 0.95,
- "strengths": ["biomedical literature", "medical research", "clinical studies",
- "life sciences", "health information", "scientific papers"],
- "weaknesses": ["non-medical topics", "very recent papers may be missing",
- "limited to published research"],
- "default_params": {
- "max_results": 20,
- "get_abstracts": True,
- "get_full_text": False, # Default to abstracts only, not full text
- "full_text_limit": 3, # Limit full text retrieval to top 3 articles when enabled
- "days_limit": None, # No default time limit
- "optimize_queries": True # Use LLM to optimize natural language queries
- },
- "requires_llm": True # Needs LLM for query optimization
- },
- # GitHub search engine
- "github": {
- "module_path": "web_search_engines.engines.search_engine_github",
- "class_name": "GitHubSearchEngine",
- "requires_api_key": False, # Works without API key but rate limited
- #"api_key_env": "GITHUB_API_KEY",
- "reliability": 0.99,
- "strengths": ["code repositories", "software documentation", "open source projects",
- "programming issues", "developer information", "technical documentation"],
- "weaknesses": ["non-technical content", "content outside GitHub", "rate limits without API key"],
- "default_params": {
- "max_results": 15,
- "search_type": "repositories", # Options: "repositories", "code", "issues", "users"
- "include_readme": True,
- "include_issues": False
- },
- "supports_full_search": True
- },
- # DuckDuckGo search engine
- # "duckduckgo": {
- # "module_path": "web_search_engines.engines.search_engine_ddg",
- # "class_name": "DuckDuckGoSearchEngine",
- # "requires_api_key": False,
- # "reliability": 0.4,
- # "strengths": ["web search", "product information", "reviews", "recent information",
- # "news", "general queries", "broad coverage"],
- # "weaknesses": ["inconsistent due to rate limits", "not specialized for academic content"],
- # "default_params": {
- # "region": "us",
- # "safe_search": True
- # },
- # "supports_full_search": True,
- # "full_search_module": "web_search_engines.engines.full_search",
- # "full_search_class": "FullSearchResults"
- # },
-
- # SerpAPI search engine
- "serpapi": {
- "module_path": "web_search_engines.engines.search_engine_serpapi",
- "class_name": "SerpAPISearchEngine",
- "requires_api_key": True,
- "api_key_env": "SERP_API_KEY",
- "reliability": 0.6,
- "strengths": ["comprehensive web search", "product information", "reviews",
- "recent content", "news", "broad coverage"],
- "weaknesses": ["requires API key with usage limits", "not specialized for academic content"],
- "default_params": {
- "region": "us",
- "time_period": "y",
- "safe_search": True,
- "search_language": "English"
- },
- "supports_full_search": True,
- "full_search_module": "web_search_engines.engines.full_serp_search_results_old",
- "full_search_class": "FullSerpAPISearchResults"
- },
-
- # Google Programmable Search Engine
- "google_pse": {
- "module_path": "web_search_engines.engines.search_engine_google_pse",
- "class_name": "GooglePSESearchEngine",
- "requires_api_key": True,
- "api_key_env": "GOOGLE_PSE_API_KEY",
- "reliability": 0.9,
- "strengths": ["custom search scope", "high-quality results", "domain-specific search",
- "configurable search experience", "control over search index"],
- "weaknesses": ["requires API key with usage limits", "limited to 10,000 queries/day on free tier",
- "requires search engine configuration in Google Control Panel"],
- "default_params": {
- "region": "us",
- "safe_search": True,
- "search_language": "English"
- },
- "supports_full_search": True,
- "full_search_module": "web_search_engines.engines.full_search",
- "full_search_class": "FullSearchResults"
- },
-
- # Brave search engine
- "brave": {
- "module_path": "web_search_engines.engines.search_engine_brave",
- "class_name": "BraveSearchEngine",
- "requires_api_key": True,
- "api_key_env": "BRAVE_API_KEY",
- "reliability": 0.7,
- "strengths": ["privacy-focused web search", "product information", "reviews",
- "recent content", "news", "broad coverage"],
- "weaknesses": ["requires API key with usage limits", "smaller index than Google"],
- "default_params": {
- "region": "US",
- "time_period": "y",
- "safe_search": True,
- "search_language": "English"
- },
- "supports_full_search": True,
- "full_search_module": "web_search_engines.engines.full_search",
- "full_search_class": "FullSearchResults"
- },
-
- # The Guardian search engine - search seem to often provide irrelevant results.
- #"guardian": {
- # "module_path": "web_search_engines.engines.search_engine_guardian",
- # "class_name": "GuardianSearchEngine",
- # "requires_api_key": True,
- # "api_key_env": "GUARDIAN_API_KEY",
- # "reliability": 0.5,
- # "strengths": ["news articles", "current events", "opinion pieces", "journalism",
- # "UK and global news", "political analysis"],
- # "weaknesses": ["primarily focused on news", "limited historical content pre-1999"],
- # "default_params": {
- # "order_by": "relevance"
- # }
- #},
- # Wayback Machine search engine - not sure if it is usefull
- "wayback": {
- "module_path": "web_search_engines.engines.search_engine_wayback",
- "class_name": "WaybackSearchEngine",
- "requires_api_key": False,
- "reliability": 0.5,
- "strengths": ["historical web content", "archived websites", "content verification",
- "deleted or changed web pages", "website evolution tracking"],
- "weaknesses": ["limited to previously archived content", "may miss recent changes",
- "archiving quality varies"],
- "default_params": {
- "max_results": 15,
- "max_snapshots_per_url": 3,
- "closest_only": False,
- "language": "English"
- },
- "supports_full_search": True
- },
- # Meta search engine (intelligent engine selection)
- "auto": {
- "module_path": "web_search_engines.engines.meta_search_engine",
- "class_name": "MetaSearchEngine",
- "requires_api_key": False,
- "reliability": 0.85,
- "strengths": ["intelligent engine selection", "adaptable to query type", "fallback capabilities"],
- "weaknesses": ["slightly slower due to LLM analysis"],
- "default_params": {
- "use_api_key_services": True,
- "max_engines_to_try": 3
- },
- "requires_llm": True
- }
-}
-
-# Add 'auto' as an alias for 'meta'
-SEARCH_ENGINES["auto"] = SEARCH_ENGINES["auto"]
-
-# Default search engine to use if none specified
-DEFAULT_SEARCH_ENGINE = "wikipedia"
-
-
-# Import local collections
-try:
- from local_collections import register_local_collections
-
- # Register all enabled local collections as search engines
- register_local_collections(SEARCH_ENGINES)
-
- print(f"Registered local document collections as search engines")
-except ImportError:
- print("No local collections configuration found. Local document search is disabled.")
-
-# Optionally, also register a "local_all" search engine that searches all collections
-# This is useful when users want to search across all their local collections
-SEARCH_ENGINES["local_all"] = {
- "module_path": "web_search_engines.engines.search_engine_local_all",
- "class_name": "LocalAllSearchEngine",
- "requires_api_key": False,
- "reliability": 0.85,
- "strengths": ["searches all local collections", "personal documents", "offline access"],
- "weaknesses": ["may return too many results", "requires indexing"],
- "default_params": {},
- "requires_llm": True
-}
-
-# Ensure the meta search engine is still available at the end
-meta_config = SEARCH_ENGINES["auto"]
-del SEARCH_ENGINES["auto"]
-SEARCH_ENGINES["auto"] = meta_config